diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7ebdcc514f..44f0d8e9a0 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -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) diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts index 27998956b8..4f5dbe90f7 100644 --- a/amcharts/AmCharts.d.ts +++ b/amcharts/AmCharts.d.ts @@ -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. diff --git a/amplitude-js/v2/amplitude-js-tests.ts b/amplitude-js/v2/amplitude-js-tests.ts new file mode 100644 index 0000000000..3e69d7c867 --- /dev/null +++ b/amplitude-js/v2/amplitude-js-tests.ts @@ -0,0 +1,87 @@ +// Tests for Amplitude SDK TypeScript definitions + +/// + +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' }); + */ + } +} diff --git a/amplitude-js/v2/amplitude-js.d.ts b/amplitude-js/v2/amplitude-js.d.ts new file mode 100644 index 0000000000..613f5ad5d8 --- /dev/null +++ b/amplitude-js/v2/amplitude-js.d.ts @@ -0,0 +1,61 @@ +// Type definitions for Amplitude SDK 2.12.1 +// Project: https://github.com/amplitude/Amplitude-Javascript +// Definitions by: Arvydas Sidorenko +// 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; +} diff --git a/angular-es/angular-es.d.ts b/angular-es/angular-es.d.ts index 10979ae15c..0972b42da0 100644 --- a/angular-es/angular-es.d.ts +++ b/angular-es/angular-es.d.ts @@ -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) => ngESDecorator; + function Inject(...dependencies: Array): ngESDecorator; /** * Inject dependencies as properties to target @@ -122,7 +122,7 @@ declare module 'angular-es' { * * @returns {ngESDecorator} - decorated class */ - var InjectAsProperty: (...dependencies: Array) => ngESDecorator; + function InjectAsProperty(...dependencies: Array): 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, diff --git a/angular-gettext/angular-gettext.d.ts b/angular-gettext/angular-gettext.d.ts index 48734d4433..84721d8dc0 100644 --- a/angular-gettext/angular-gettext.d.ts +++ b/angular-gettext/angular-gettext.d.ts @@ -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; diff --git a/angular-jwt/angular-jwt-tests.ts b/angular-jwt/angular-jwt-tests.ts index 3a6b7d6bf1..818899e829 100644 --- a/angular-jwt/angular-jwt-tests.ts +++ b/angular-jwt/angular-jwt-tests.ts @@ -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(); \ No newline at end of file diff --git a/angular-jwt/angular-jwt.d.ts b/angular-jwt/angular-jwt.d.ts index eb02cf24df..d1f9eb085f 100644 --- a/angular-jwt/angular-jwt.d.ts +++ b/angular-jwt/angular-jwt.d.ts @@ -27,4 +27,11 @@ declare namespace angular.jwt { interface IJwtInterceptor { tokenGetter(...params : any[]): string; } + + interface IAuthManagerServiceProvider { + authenticate(): void; + unauthenticate(): void; + checkAuthOnRefresh(): void; + redirectWhenUnauthenticated(): void; + } } diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index 4464c599e3..c3ebcbaf99 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -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: '

Hello!

', hasBackdrop: true, disableParentScroll: true, diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 23da7bceb2..66852586da 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -22,7 +22,7 @@ declare namespace angular.material { clickOutsideToClose?: boolean; disableBackdrop?: boolean; escapeToClose?: boolean; - resolve?: {[index: string]: angular.IPromise}; + resolve?: {[index: string]: () => angular.IPromise}; 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}): T; + resolve(resolve?: {[index: string]: () => angular.IPromise}): 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} + resolve?: {[index: string]: () => angular.IPromise} controllerAs?: string; parent?: string|Element|JQuery; // default: root node onShowing?: Function; @@ -132,6 +132,7 @@ declare namespace angular.material { close(): angular.IPromise; 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} + resolve?: {[index: string]: () => angular.IPromise} 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} + resolve?: {[index: string]: () => angular.IPromise} attachTo?: string|JQuery|Element; propagateContainerEvents?: boolean; panelClass?: string; diff --git a/angular-ui-notification/angular-ui-notification-tests.ts b/angular-ui-notification/angular-ui-notification-tests.ts new file mode 100644 index 0000000000..3039a74c9e --- /dev/null +++ b/angular-ui-notification/angular-ui-notification-tests.ts @@ -0,0 +1,30 @@ +/// + +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
Some other content
This is a link
', title: 'Html content'}); + + Notification.error({message: 'Error Bottom Right', positionY: 'bottom', positionX: 'right'}); + + Notification.error({message: 'Error notification 1s', replaceMessage: true}); +} \ No newline at end of file diff --git a/angular-ui-notification/angular-ui-notification.d.ts b/angular-ui-notification/angular-ui-notification.d.ts new file mode 100644 index 0000000000..48215e6d42 --- /dev/null +++ b/angular-ui-notification/angular-ui-notification.d.ts @@ -0,0 +1,82 @@ +// Type definitions for angular-ui-notification +// Project: https://github.com/alexcrack/angular-ui-notification +// Definitions by: Kamil Rojewski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace angular.uiNotification { + // Taken from angular to avoid dependency + interface IPromise { + /** + * 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 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(successCallback: (promiseValue: T) => IPromise|TResult, errorCallback?: (reason: any) => any, notifyCallback?: (state: any) => any): IPromise; + + /** + * Shorthand for promise.then(null, errorCallback) + */ + catch(onRejected: (reason: any) => IPromise|TResult): IPromise; + + /** + * 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; + } + + 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; + info(message: Message): IPromise; + success(message: Message): IPromise; + warning(message: Message): IPromise; + error(message: Message): IPromise; + + clearAll(): void; + + (message: Message, type?: MessageType): IPromise; + } +} diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts index 168c6ba271..5f24c8ec38 100644 --- a/angular-ui-scroll/angular-ui-scroll.d.ts +++ b/angular-ui-scroll/angular-ui-scroll.d.ts @@ -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. * diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 441a7e1d3d..f7e803c1c8 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -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>; + actions?: IActionHash, options?: IResourceOptions): IResourceClass>; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): U; + actions?: IActionHash, options?: IResourceOptions): U; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass; + actions?: IActionHash, options?: IResourceOptions): IResourceClass; + } + + // 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): IModule; } + + namespace auto { + interface IInjectorService { + get(name: '$resource'): ng.resource.IResourceService; + } + } } interface Array diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 3c13fd6cf3..1831bc0493 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.5 // Project: http://angularjs.org -// Definitions by: Diego Vilar +// Definitions by: Diego Vilar , Georgii Dolzhykov // 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(value: any): value is T; isString(value: any): value is string; isUndefined(value: any): boolean; lowercase(str: string): string; @@ -1411,6 +1412,16 @@ declare namespace angular { * Absolute or relative URL of the resource that is being requested. */ url: string; + /** + * Event listeners to be bound to the XMLHttpRequest object. + * To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block. + */ + eventHandlers?: { [type: string]: EventListenerOrEventListenerObject }; + /** + * Event listeners to be bound to the XMLHttpRequest upload object. + * To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block. + */ + uploadEventHandlers?: { [type: string]: EventListenerOrEventListenerObject }; } interface IHttpHeadersGetter { @@ -1745,12 +1756,12 @@ declare namespace angular { */ $onInit?(): void; /** - * Called whenever one-way bindings are updated. The changesObj is a hash whose keys are the names of the bound - * properties that have changed, and the values are an {@link IChangesObject} object of the form + * Called whenever one-way bindings are updated. The onChangesObj is a hash whose keys are the names of the bound + * properties that have changed, and the values are an {@link IChangesObject} object of the form * { currentValue, previousValue, isFirstChange() }. Use this hook to trigger updates within a component such as * cloning the bound value to prevent accidental mutation of the outer value. */ - $onChanges?(changesObj: {[property:string]: IChangesObject}): void; + $onChanges?(onChangesObj: IOnChangesObject): void; /** * Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, * watches and event handlers. @@ -1766,6 +1777,10 @@ declare namespace angular { */ $postLink?(): void; } + + interface IOnChangesObject { + [property: string]: IChangesObject; + } interface IChangesObject { currentValue: any; diff --git a/atom/atom.d.ts b/atom/atom.d.ts index 389d6ef16e..ac899ba5ac 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -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; diff --git a/auth0-js/auth0-js-tests.ts b/auth0-js/auth0-js-tests.ts new file mode 100644 index 0000000000..c92251db91 --- /dev/null +++ b/auth0-js/auth0-js-tests.ts @@ -0,0 +1,23 @@ +/// + +var auth0 = new Auth0({ + domain: 'mine.auth0.com', + clientID: 'dsa7d77dsa7d7', + callbackURL: 'http://my-app.com/callback', + callbackOnLocationHash: true +}); + +auth0.login({ + connection: 'google-oauth2', + popup: true, + popupOptions: { + width: 450, + height: 800 + } +}, (err, profile, idToken, accessToken, state) => { + if (err) { + alert("something went wrong: " + err.message); + return; + } + alert('hello ' + profile.name); + }); diff --git a/auth0-js/auth0-js.d.ts b/auth0-js/auth0-js.d.ts new file mode 100644 index 0000000000..250c7a850e --- /dev/null +++ b/auth0-js/auth0-js.d.ts @@ -0,0 +1,133 @@ +// Type definitions for Auth0.js +// Project: https://github.com/auth0/auth0.js +// Definitions by: Robert McLaws +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** Extensions to the browser Window object. */ +interface Window { + /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ + token: string; +} + +/** This is the interface for the main Auth0 client. */ +interface Auth0Static { + + new(options: Auth0ClientOptions): Auth0Static; + changePassword(options: any, callback?: Function): void; + decodeJwt(jwt: string): any; + login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; + loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; + logout(query: string): void; + getConnections(callback?: Function): void; + refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; + getProfile(id_token: string, callback?: Function): Auth0UserProfile; + getSSOData(withActiveDirectories: any, callback?: Function): void; + parseHash(hash: string): Auth0DecodedHash; + signup(options: Auth0SignupOptions, callback: Function): void; + validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; +} + +/** Represents constructor options for the Auth0 client. */ +interface Auth0ClientOptions { + clientID: string; + callbackURL: string; + callbackOnLocationHash?: boolean; + domain: string; + forceJSONP?: boolean; +} + +/** Represents a normalized UserProfile. */ +interface Auth0UserProfile { + email: string; + email_verified: boolean; + family_name: string; + gender: string; + given_name: string; + locale: string; + name: string; + nickname: string; + picture: string; + user_id: string; + /** Represents one or more Identities that may be associated with the User. */ + identities: Auth0Identity[]; + user_metadata?: any; + app_metadata?: any; +} + +/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ +interface MicrosoftUserProfile extends Auth0UserProfile { + emails: string[]; +} + +/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ +interface Office365UserProfile extends Auth0UserProfile { + tenantid: string; + upn: string; +} + +/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ +interface AdfsUserProfile extends Auth0UserProfile { + issuer: string; +} + +/** Represents multiple identities assigned to a user. */ +interface Auth0Identity { + access_token: string; + connection: string; + isSocial: boolean; + provider: string; + user_id: string; +} + +interface Auth0DecodedHash { + access_token: string; + id_token: string; + profile: Auth0UserProfile; + state: any; +} + +interface Auth0PopupOptions { + width: number; + height: number; +} + +interface Auth0LoginOptions { + auto_login?: boolean; + connection?: string; + email?: string; + username?: string; + password?: string; + popup?: boolean; + popupOptions?: Auth0PopupOptions; +} + +interface Auth0SignupOptions extends Auth0LoginOptions { + auto_login: boolean; +} + +interface Auth0Error { + code: any; + details: any; + name: string; + message: string; + status: any; +} + +/** Represents the response from an API Token Delegation request. */ +interface Auth0DelegationToken { + /** The length of time in seconds the token is valid for. */ + expires_in: string; + /** The JWT for delegated access. */ + id_token: string; + /** The type of token being returned. Possible values: "Bearer" */ + token_type: string; +} + +declare var Auth0: Auth0Static; + +declare module "auth0-js" { + export = Auth0 +} diff --git a/auth0.lock/auth0.lock-tests.ts b/auth0.lock/auth0.lock-tests.ts index 07a7cf8323..d466cf5937 100644 --- a/auth0.lock/auth0.lock-tests.ts +++ b/auth0.lock/auth0.lock-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// const CLIENT_ID = "YOUR_AUTH0_APP_CLIENTID"; diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index 7a459afd97..43d842aecc 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -3,7 +3,7 @@ // Definitions by: Brian Caruso // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0LockAdditionalSignUpFieldOption { value: string; diff --git a/auth0.widget/auth0.widget-tests.ts b/auth0.widget/auth0.widget-tests.ts index 012e9b9769..f44601986e 100644 --- a/auth0.widget/auth0.widget-tests.ts +++ b/auth0.widget/auth0.widget-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var widget: Auth0WidgetStatic = new Auth0Widget({ diff --git a/auth0.widget/auth0.widget.d.ts b/auth0.widget/auth0.widget.d.ts index 20694526c3..e36a7f868a 100644 --- a/auth0.widget/auth0.widget.d.ts +++ b/auth0.widget/auth0.widget.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert McLaws // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Auth0WidgetStatic { diff --git a/auth0/auth0-tests.ts b/auth0/auth0-tests.ts index 9cd903b306..a1357246f3 100644 --- a/auth0/auth0-tests.ts +++ b/auth0/auth0-tests.ts @@ -1,23 +1,51 @@ -/// +/// -var auth0 = new Auth0({ - domain: 'mine.auth0.com', - clientID: 'dsa7d77dsa7d7', - callbackURL: 'http://my-app.com/callback', - callbackOnLocationHash: true +import * as auth0 from 'auth0'; + +const management = new auth0.ManagementClient({ + token: '{YOUR_API_V2_TOKEN}', + domain: '{YOUR_ACCOUNT}.auth0.com' }); -auth0.login({ - connection: 'google-oauth2', - popup: true, - popupOptions: { - width: 450, - height: 800 - } -}, (err, profile, idToken, accessToken, state) => { - if (err) { - alert("something went wrong: " + err.message); - return; - } - alert('hello ' + profile.name); - }); +const auth = new auth0.AuthenticationClient({ + domain: '{YOUR_ACCOUNT}.auth0.com', + clientId: '{OPTIONAL_CLIENT_ID}' +}); + +// Using a callback. +management.getUsers((err: Error, users: auth0.User[]) => { + if (err) { + // Handle error. + } + console.log(users); +}); + +// Using a Promise. +management + .getUsers() + .then((users) => { + console.log(users); + }) + .catch((err) => { + // Handle the error. + }); + +management + .createUser({ + connection: 'My-Connection', + email: 'hi@me.co', + }).then((user) => { + console.log(user); + }).catch((err) => { + // Handle the error. + }); + +auth + .requestChangePasswordEmail({ + connection: 'My-Connection', + email: 'hi@me.co', + }).then((response) => { + console.log(response); + }).catch((err) => { + // Handle the error. + }); diff --git a/auth0/auth0.d.ts b/auth0/auth0.d.ts index 5ca8487f85..e367d30411 100644 --- a/auth0/auth0.d.ts +++ b/auth0/auth0.d.ts @@ -1,132 +1,95 @@ -// Type definitions for Auth0.js -// Project: http://auth0.com -// Definitions by: Robert McLaws +// Type definitions for auth0 v2.3.1 +// Project: https://github.com/auth0/node-auth0 +// Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/** Extensions to the browser Window object. */ -interface Window { - /** Allows you to pass the id_token to other APIs, as specified in https://docs.auth0.com/apps-apis */ +/// + +declare module "auth0" { + + import * as Promise from 'bluebird'; + + export interface ManagementClientOptions { token: string; -} + domain?: string; + } -/** This is the interface for the main Auth0 client. */ -interface Auth0Static { - - new(options: Auth0ClientOptions): Auth0Static; - changePassword(options: any, callback?: Function): void; - decodeJwt(jwt: string): any; - login(options: any, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithPopup(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - loginWithResourceOwner(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: any) => any): void; - loginWithUsernamePassword(options: Auth0LoginOptions, callback: (error?: Auth0Error, profile?: Auth0UserProfile, id_token?: string, access_token?: string, state?: string) => any): void; - logout(query: string): void; - getConnections(callback?: Function): void; - refreshToken(refreshToken: string, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getDelegationToken(targetClientId: string, id_token: string, options: any, callback: (error?: Auth0Error, delegationResult?: Auth0DelegationToken) => any): void; - getProfile(id_token: string, callback?: Function): Auth0UserProfile; - getSSOData(withActiveDirectories: any, callback?: Function): void; - parseHash(hash: string): Auth0DecodedHash; - signup(options: Auth0SignupOptions, callback: Function): void; - validateUser(options: any, callback: (error?: Auth0Error, valid?: any) => any): void; -} - -/** Represents constructor options for the Auth0 client. */ -interface Auth0ClientOptions { - clientID: string; - callbackURL: string; - callbackOnLocationHash?: boolean; - domain: string; - forceJSONP?: boolean; -} - -/** Represents a normalized UserProfile. */ -interface Auth0UserProfile { - email: string; - family_name: string; - gender: string; - given_name: string; - locale: string; - name: string; - nickname: string; - picture: string; - user_id: string; - /** Represents one or more Identities that may be associated with the User. */ - identities: Auth0Identity[]; - user_metadata?: any; - app_metadata?: any; -} - -/** Represents an Auth0UserProfile that has a Microsoft Account as the primary identity. */ -interface MicrosoftUserProfile extends Auth0UserProfile { - emails: string[]; -} - -/** Represents an Auth0UserProfile that has an Office365 account as the primary identity. */ -interface Office365UserProfile extends Auth0UserProfile { - tenantid: string; - upn: string; -} - -/** Represents an Auth0UserProfile that has an Active Directory account as the primary identity. */ -interface AdfsUserProfile extends Auth0UserProfile { - issuer: string; -} - -/** Represents multiple identities assigned to a user. */ -interface Auth0Identity { - access_token: string; + export interface UserData { connection: string; - isSocial: boolean; - provider: string; - user_id: string; -} - -interface Auth0DecodedHash { - access_token: string; - id_token: string; - profile: Auth0UserProfile; - state: any; -} - -interface Auth0PopupOptions { - width: number; - height: number; -} - -interface Auth0LoginOptions { - auto_login?: boolean; - connection?: string; email?: string; username?: string; password?: string; - popup?: boolean; - popupOptions?: Auth0PopupOptions; -} + phone_number?: string; + user_metadata?: {}; + email_verified?: boolean; + app_metadata?: {}; + } -interface Auth0SignupOptions extends Auth0LoginOptions { - auto_login: boolean; -} + export interface GetUsersData { + per_page?: number; + page?: number; + include_totals?: boolean; + sort?: string; + connection?: string; + fields?: string; + include_fields?: boolean; + q?: string; + search_engine?: string; + } -interface Auth0Error { - code: any; - details: any; - name: string; - message: string; - status: any; -} + export interface User { + email?: string; + email_verified?: boolean; + username?: string; + phone_number?: string; + phone_verified?: boolean; + user_id?: string; + created_at?: string; + updated_at?: string; + identities?: Identity[]; + app_metadata?: {}; + user_metadata?: {}; + picture?: string; + name?: string; + nickname?: string; + multifactor?: string[]; + last_ip?: string; + last_login?: string; + logins_count?: number; + blocked?: boolean; + } -/** Represents the response from an API Token Delegation request. */ -interface Auth0DelegationToken { - /** The length of time in seconds the token is valid for. */ - expires_in: string; - /** The JWT for delegated access. */ - id_token: string; - /** The type of token being returned. Possible values: "Bearer" */ - token_type: string; -} + export interface Identity { + connection: string; + user_id: string; + provider: string; + isSocial: boolean; + } -declare var Auth0: Auth0Static; + export class ManagementClient { + constructor(options: ManagementClientOptions); + + getUsers(params?: GetUsersData): Promise; + getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void; + createUser(data: UserData): Promise; + createUser(data: UserData, cb: (err: Error, data: User) => void): void; + } + + export interface AuthenticationClientOptions { + clientId?: string; + domain: string; + } + + export interface RequestChangePasswordEmailData { + connection: string; + email: string; + } + + export class AuthenticationClient { + constructor(options: AuthenticationClientOptions); + + requestChangePasswordEmail(data: RequestChangePasswordEmailData): Promise; + requestChangePasswordEmail(data: RequestChangePasswordEmailData, cb: (err: Error, message: string) => void): void; + } -declare module "auth0" { - export = Auth0 } diff --git a/autobind-decorator/autobind-decorator-tests.ts b/autobind-decorator/autobind-decorator-tests.ts new file mode 100644 index 0000000000..e428604802 --- /dev/null +++ b/autobind-decorator/autobind-decorator-tests.ts @@ -0,0 +1,43 @@ +/// + +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' diff --git a/autobind-decorator/autobind-decorator.d.ts b/autobind-decorator/autobind-decorator.d.ts new file mode 100644 index 0000000000..51ba89c9bf --- /dev/null +++ b/autobind-decorator/autobind-decorator.d.ts @@ -0,0 +1,10 @@ +// Type definitions for autobind-decorator v1.3.3 +// Project: https://github.com/andreypopp/autobind-decorator +// Definitions by: Ivo Stratev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'autobind-decorator' { + function autobind(target: TFunction): TFunction | void; + function autobind(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; + export = autobind; +} diff --git a/autobind-decorator/autobind-decorator.ts.tscparams b/autobind-decorator/autobind-decorator.ts.tscparams new file mode 100644 index 0000000000..1ee3d05cb6 --- /dev/null +++ b/autobind-decorator/autobind-decorator.ts.tscparams @@ -0,0 +1 @@ +--experimentalDecorators diff --git a/aws-lambda/aws-lambda-tests.ts b/aws-lambda/aws-lambda-tests.ts index fd289dcb7f..f562b59d3d 100644 --- a/aws-lambda/aws-lambda-tests.ts +++ b/aws-lambda/aws-lambda-tests.ts @@ -4,46 +4,37 @@ import lambda = require('aws-lambda'); var str: string; var date: Date; -var sns: lambda.SNS; -var kinesis: lambda.Kinesis; -var recordsList: lambda.Record[]; var anyObj: any; var num: number; - -/* Records */ -var records: lambda.Records; - -recordsList = records.Records; - -/* Record */ -var record: lambda.Record; - -str = record.EventVersion; -str = record.EventSubscriptionArn; -str = record.EnventSource; -sns = record.Sns; -kinesis = record.kinesis; - -/* SNS */ -str = sns.Type; -str = sns.MessageId; -str = sns.TopicArn; -str = sns.Subject; -str = sns.Message; -date = sns.Timestamp; - -/* Kinesis */ -var kinesis: lambda.Kinesis; - -str = kinesis.data; +var identity: lambda.CognitoIdentity; +var error: Error; +var b: boolean; +var clientCtx: lambda.ClientContext; /* Context */ var context: lambda.Context; -context.log(str, anyObj); -context.fail(str); -context.succeed(str); -context.succeed(anyObj); -context.succeed(str, anyObj); +b = context.callbackWaitsForEmptyEventLoop; +str = context.functionName; +str = context.functionVersion; +str = context.invokedFunctionArn; +num = context.memoryLimitInMB; str = context.awsRequestId; -num = context.getRemainingTimeInMillis(); \ No newline at end of file +str = context.logGroupName; +str = context.logStreamName; +identity = context.identity; +clientCtx = context.clientContext; + +/* CognitoIdentity */ +var identity: lambda.CognitoIdentity; + +str = identity.cognitoIdentityId; +str = identity.cognitoIdentityPoolId; + +/* Callback */ +function callback(cb: lambda.Callback) { + cb(); + cb(null); + cb(error); + cb(null, anyObj); +} \ No newline at end of file diff --git a/aws-lambda/aws-lambda.d.ts b/aws-lambda/aws-lambda.d.ts index cdd8e2f506..c9a66a3783 100644 --- a/aws-lambda/aws-lambda.d.ts +++ b/aws-lambda/aws-lambda.d.ts @@ -1,43 +1,68 @@ // Type definitions for AWS Lambda // Project: http://docs.aws.amazon.com/lambda -// Definitions by: Michael Skarum +// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "aws-lambda" { + // Context + // http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html + interface Context { + // Properties + callbackWaitsForEmptyEventLoop: boolean; + functionName: string; + functionVersion: string; + invokedFunctionArn: string; + memoryLimitInMB: number; + awsRequestId: string; + logGroupName: string; + logStreamName: string; + identity?: CognitoIdentity; + clientContext?: ClientContext; + + // Functions + getRemainingTimeInMillis(): number; - export interface Records { - Records: Record[]; - } - interface Record { - EventVersion: string; - EventSubscriptionArn: string; - EnventSource: string; - Sns: SNS; - kinesis: Kinesis; - } - interface SNS { - Type: string; - MessageId: string; - TopicArn: string; - Subject: string; - Message: string; - Timestamp: Date; - } - - interface Kinesis { - data: string; - } - - export interface Context { + // Functions for compatibility with earlier Node.js Runtime v0.10.42 log(message: string, object: any): void; fail(message: string): void; succeed(message: string): void; succeed(object: any): void; - succeed(message: string, object: any): void; - awsRequestId: string; - getRemainingTimeInMillis(): number; + succeed(message: string, object: any): void; } - - - export type Callback = (error?: Error, message?: string) => void; + + interface CognitoIdentity { + cognitoIdentityId: string; + cognitoIdentityPoolId: string; + } + + interface ClientContext { + client: ClientContextClient; + Custom?: any; + env: ClientContextEnv; + } + + interface ClientContextClient { + installationId: string; + appTitle: string; + appVersionName: string; + appVersionCode: string; + appPackageName: string; + } + + interface ClientContextEnv { + platformVersion: string; + platform: string; + make: string; + model: string; + locale: string; + } + + /** + * Optional callback parameter. + * http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html + * + * @param error – an optional parameter that you can use to provide results of the failed Lambda function execution. + * @param result – an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible. + */ + export type Callback = (error?: Error, result?: any) => void; } \ No newline at end of file diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index cb35f34e97..09ec2f6267 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -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 { diff --git a/axe-core/axe-core-tests.ts b/axe-core/axe-core-tests.ts new file mode 100644 index 0000000000..7decb865c2 --- /dev/null +++ b/axe-core/axe-core-tests.ts @@ -0,0 +1,91 @@ +/// + +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() diff --git a/axe-core/axe-core.d.ts b/axe-core/axe-core.d.ts new file mode 100644 index 0000000000..98818e75cc --- /dev/null +++ b/axe-core/axe-core.d.ts @@ -0,0 +1,159 @@ +// Type definitions for axe-core 2.0.5 +// Project: https://github.com/dequelabs/axe-core +// Definitions by: Marcy Sutton +// 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; +} diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 093932c2fb..302f732889 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -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'); \ No newline at end of file +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 () {} }); diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index 0a42fa9ecf..a17e41e2d6 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -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; } + interface ContextData { + (table: TableDefinition): Data.Table; + execute(q: SqlQueryDefinition): Thenable; + } + + interface SqlQueryDefinition { + sql: string; + parameters?: SqlParameterDefinition[]; + } + + interface SqlParameterDefinition { + name: string; + value: any; + } + interface TableDefinition { authorize?: boolean; autoIncrement?: boolean; diff --git a/azure-mobile-services-client/AzureMobileServicesClient.d.ts b/azure-mobile-services-client/AzureMobileServicesClient.d.ts index afd6014598..6fa0f9c475 100644 --- a/azure-mobile-services-client/AzureMobileServicesClient.d.ts +++ b/azure-mobile-services-client/AzureMobileServicesClient.d.ts @@ -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; /** diff --git a/backlog-js/backlog-js-tests.ts b/backlog-js/backlog-js-tests.ts new file mode 100644 index 0000000000..979eb57ca4 --- /dev/null +++ b/backlog-js/backlog-js-tests.ts @@ -0,0 +1,88 @@ +/// + +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 => {}); diff --git a/backlog-js/backlog-js.d.ts b/backlog-js/backlog-js.d.ts new file mode 100644 index 0000000000..353e7e90cd --- /dev/null +++ b/backlog-js/backlog-js.d.ts @@ -0,0 +1,695 @@ +// Type definitions for backlog-js 0.9.0 +// Project: https://github.com/nulab/backlog-js +// Definitions by: Yuichi Watanabe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +declare module 'backlog-js' { + + class Request { + private configure; + constructor(configure: { + host: string; + apiKey?: string; + accessToken?: string; + timeout?: number; + }); + get(path: string, params?: any): Promise; + post(path: string, params?: any): Promise; + put(path: string, params: any): Promise; + patch(path: string, params: any): Promise; + delete(path: string, params?: any): Promise; + request(options: { + method: string; + path: string; + params?: Params | FormData; + }): Promise; + checkStatus(response: IResponse): Promise; + parseJSON(response: IResponse): Promise; + 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; + getSpaceActivities(params: Option.Space.GetActivitiesParams): Promise; + getSpaceNotification(): Promise; + putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise; + getSpaceDiskUsage(): Promise; + getSpaceIcon(): Promise; + postSpaceAttachment(form: FormData): Promise; + getUsers(): Promise; + getUser(userId: number): Promise; + postUser(params: Option.User.PostUserParams): Promise; + patchUser(userId: number, params: Option.User.PatchUserParams): Promise; + deleteUser(userId: number): Promise; + getMyself(): Promise; + getUserActivities(userId: number, params: Option.User.GetUserActivitiesParams): Promise; + getUserStars(userId: number, params: Option.User.GetUserStarsParams): Promise; + getUserStarsCount(userId: number, params: Option.User.GetUserStarsCountParams): Promise; + getRecentlyViewedIssues(params: Option.User.GetRecentlyViewedParams): Promise; + getRecentlyViewedProjects(params: Option.User.GetRecentlyViewedParams): Promise; + getRecentlyViewedWikis(params: Option.User.GetRecentlyViewedParams): Promise; + getUserIcon(userId: number): Promise; + getGroups(params: Option.Group.GetGroupsParams): Promise; + postGroups(params: Option.Group.PostGroupsParams): Promise; + getGroup(groupId: number): Promise; + patchGroup(groupId: number, params: Option.Group.PatchGroupParams): Promise; + deleteGroup(groupId: number): Promise; + getStatuses(): Promise; + getResolutions(): Promise; + getPriorities(): Promise; + postProject(params: Option.Project.PostProjectParams): Promise; + getProjects(params?: Option.Project.GetProjectsParams): Promise; + getProject(projectIdOrKey: string): Promise; + patchProject(projectIdOrKey: string, params: Option.Project.PatchProjectParams): Promise; + deleteProject(projectIdOrKey: string): Promise; + getProjectActivities(projectIdOrKey: string, params: Option.Space.GetActivitiesParams): Promise; + getProjectUsers(projectIdOrKey: string): Promise; + deleteProjectUsers(projectIdOrKey: string, params: Option.Project.DeleteProjectUsersParams): Promise; + postProjectAdministrators(projectIdOrKey: string, params: Option.Project.PostProjectAdministrators): Promise; + getProjectAdministrators(projectIdOrKey: string): Promise; + deleteProjectAdministrators(projectIdOrKey: string, params: Option.Project.DeleteProjectAdministrators): Promise; + getIssueTypes(projectIdOrKey: string): Promise; + postIssueType(projectIdOrKey: string, params: Option.Project.PostIssueTypeParams): Promise; + patchIssueType(projectIdOrKey: string, id: number, params: Option.Project.PatchIssueTypeParams): Promise; + deleteIssueType(projectIdOrKey: string, id: number, params: Option.Project.DeleteIssueTypeParams): Promise; + getCategories(projectIdOrKey: string): Promise; + postCategories(projectIdOrKey: string, params: Option.Project.PostCategoriesParams): Promise; + patchCategories(projectIdOrKey: string, id: number, params: Option.Project.PatchCategoriesParams): Promise; + deleteCategories(projectIdOrKey: string, id: number): Promise; + getVersions(projectIdOrKey: string): Promise; + postVersions(projectIdOrKey: string, params: Option.Project.PostVersionsParams): Promise; + patchVersions(projectIdOrKey: string, id: number, params: Option.Project.PatchVersionsParams): Promise; + deleteVersions(projectIdOrKey: string, id: number): Promise; + getCustomFields(projectIdOrKey: string): Promise; + postCustomField(projectIdOrKey: string, params: Option.Project.PostCustomFieldParams | Option.Project.PostCustomFieldWithNumericParams | Option.Project.PostCustomFieldWithDateParams | Option.Project.PostCustomFieldWithListParams): Promise; + patchCustomField(projectIdOrKey: string, id: number, params: Option.Project.PatchCustomFieldParams | Option.Project.PatchCustomFieldWithNumericParams | Option.Project.PatchCustomFieldWithDateParams | Option.Project.PatchCustomFieldWithListParams): Promise; + deleteCustomField(projectIdOrKey: string, id: number): Promise; + postCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; + patchCustomFieldItem(projectIdOrKey: string, id: number, itemId: number, params: Option.Project.PatchCustomFieldItemParams): Promise; + deleteCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; + getSharedFiles(projectIdOrKey: string, path: string, params: Option.Project.GetSharedFilesParams): Promise; + getProjectsDiskUsage(projectIdOrKey: string): Promise; + getWebhooks(projectIdOrKey: string): Promise; + postWebhook(projectIdOrKey: string, params: Option.Project.PostWebhookParams): Promise; + getWebhook(projectIdOrKey: string, webhookId: string): Promise; + patchWebhook(projectIdOrKey: string, webhookId: string, params: Option.Project.PatchWebhookParams): Promise; + deleteWebhook(projectIdOrKey: string, webhookId: string): Promise; + postIssue(params: Option.Issue.PostIssueParams): Promise; + patchIssue(issueIdOrKey: string, params: Option.Issue.PatchIssueParams): Promise; + getIssues(params?: Option.Issue.GetIssuesParams): Promise; + getIssue(issueIdOrKey: string): Promise; + getIssuesCount(params?: Option.Issue.GetIssuesParams): Promise; + deleteIssuesCount(issueIdOrKey: string): Promise; + getIssueComments(issueIdOrKey: string, params: Option.Issue.GetIssueCommentsParams): Promise; + postIssueComments(issueIdOrKey: string, params: Option.Issue.PostIssueCommentsParams): Promise; + getIssueCommentsCount(issueIdOrKey: string): Promise; + getIssueComment(issueIdOrKey: string, commentId: number): Promise; + patchIssueComment(issueIdOrKey: string, commentId: number, params: Option.Issue.PatchIssueCommentParams): Promise; + getIssueCommentNotifications(issueIdOrKey: string, commentId: number): Promise; + postIssueCommentNotifications(issueIdOrKey: string, commentId: number, prams: Option.Issue.IssueCommentNotifications): Promise; + getIssueAttachments(issueIdOrKey: string): Promise; + deleteIssueAttachment(issueIdOrKey: string, attachmentId: string): Promise; + getIssueSharedFiles(issueIdOrKey: string): Promise; + linkIssueSharedFiles(issueIdOrKey: string, params: Option.Issue.LinkIssueSharedFilesParams): Promise; + unlinkIssueSharedFile(issueIdOrKey: string, id: number): Promise; + getWikis(projectIdOrKey: number): Promise; + getWikisCount(projectIdOrKey: number): Promise; + getWikisTags(projectIdOrKey: number): Promise; + postWiki(params: Option.Wiki.PostWikiParams): Promise; + getWiki(wikiId: number): Promise; + patchWiki(wikiId: number, params: Option.Wiki.PatchWikiParams): Promise; + deleteWiki(wikiId: number, mailNotify: boolean): Promise; + getWikisAttachments(wikiId: number): Promise; + postWikisAttachments(wikiId: number, attachmentId: number[]): Promise; + deleteWikisAttachments(wikiId: number, attachmentId: number): Promise; + getWikisSharedFiles(wikiId: number): Promise; + linkWikisSharedFiles(wikiId: number, fileId: number[]): Promise; + unlinkWikisSharedFiles(wikiId: number, id: number): Promise; + getWikisHistory(wikiId: number, params: Option.Wiki.GetWikisHistoryParams): Promise; + getWikisStars(wikiId: number): Promise; + postStar(params: Option.Project.PostStarParams): Promise; + getNotifications(params: Option.Notification.GetNotificationsParams): Promise; + getNotificationsCount(params: Option.Notification.GetNotificationsCountParams): Promise; + resetNotificationsMarkAsRead(): Promise; + markAsReadNotification(id: number): Promise; + getGitRepositories(projectIdOrKey: string): Promise; + getGitRepository(projectIdOrKey: string, repoIdOrName: string): Promise; + getPullRequests(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; + getPullRequestsCount(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; + postPullRequest(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.PostPullRequestParams): Promise; + getPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + patchPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PatchPullRequestParams): Promise; + getPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.GetPullRequestCommentsParams): Promise; + postPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PostPullRequestCommentsParams): Promise; + getPullRequestCommentsCount(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + patchPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, commentId: number, params: Option.PullRequest.PatchPullRequestCommentsParams): Promise; + getPullRequestAttachments(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + deletePullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; + getProjectIcon(projectIdOrKey: string): Promise; + getSharedFile(projectIdOrKey: string, sharedFileId: number): Promise; + getIssueAttachment(issueIdOrKey: string, attachmentId: number): Promise; + getWikiAttachment(wikiId: number, attachmentId: number): Promise; + getPullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; + 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; + refreshAccessToken(options: { + host: string; + refreshToken: string; + }): Promise; + } + + 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; + } + } + 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'; + } + +} diff --git a/blessed/blessed-tests.ts b/blessed/blessed-tests.ts new file mode 100644 index 0000000000..4e7f7002e6 --- /dev/null +++ b/blessed/blessed-tests.ts @@ -0,0 +1,773 @@ +/// + +import * as blessed from 'blessed'; + +let screen: blessed.Widgets.Screen = null; + +// https://github.com/chjj/blessed/blob/master/test/widget-autopad.js + +screen = blessed.screen({ + dump: __dirname + '/logs/autopad.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var box1 = blessed.box({ + parent: screen, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line' +}); + +var box2 = blessed.box({ + parent: box1, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line' +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-bigtext.js + +screen = blessed.screen({ + dump: __dirname + '/logs/bigtext.log', + smartCSR: true, + warnings: true +}); + +var box = blessed.bigtext({ + parent: screen, + content: 'Hello', + shrink: true, + width: '80%', + // height: '80%', + height: 'shrink', + // width: 'shrink', + border: 'line', + fch: ' ', + ch: '\u2592', + style: { + fg: 'red', + bg: 'blue', + bold: false + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-csr.js + +screen = blessed.screen({ + dump: __dirname + '/logs/csr.log', + smartCSR: true, + warnings: true +}); + +var lorem = require('fs').readFileSync(__dirname + '/git.diff', 'utf8'); + +var cleanSides = screen.cleanSides; +function expectClean(value: any) { + screen.cleanSides = function(el: blessed.widget.Element) { + var ret = cleanSides.apply(this, arguments); + if (ret !== value) { + throw new Error('Failed. Expected ' + + value + ' from cleanSides. Got ' + + ret + '.'); + } + return ret; + }; +} +var btext = blessed.box({ + parent: screen, + left: 'center', + top: 'center', + width: '80%', + height: '80%', + style: { + bg: 'green' + }, + border: 'line', + content: 'CSR should still work.' +}); +let _oscroll = btext.scroll; +btext.scroll = function(offset, always) { + expectClean(true); + return _oscroll(offset, always); +}; + +var text = blessed.scrollabletext({ + parent: screen, + content: lorem, + border: 'line', + left: 'center', + top: 'center', + draggable: true, + width: '50%', + height: '50%', + mouse: true, + keys: true, + vi: true +}); + +_oscroll = text.scroll; +text.scroll = function(offset, always) { + var el = this; + var value = true; + if (el.left < 0) value = true; + if (el.top < 0) value = false; + if (el.left + el.width > screen.width) value = true; + if (el.top + el.height > screen.height) value = false; + expectClean(value); + return _oscroll(offset, always); +}; + +text.focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-dock-noborder.js + +screen = blessed.screen({ + dump: __dirname + '/logs/dock.log', + smartCSR: true, + dockBorders: true, + warnings: true +}); + +blessed.box({ + parent: screen, + left: -1, + top: -1, + width: '50%+1', + height: '50%+1', + border: 'line', + content: 'Foo' +}); + +blessed.box({ + parent: screen, + left: '50%-1', + top: -1, + width: '50%+3', + height: '50%+1', + content: 'Bar', + border: 'line' +}); + +blessed.box({ + parent: screen, + left: -1, + top: '50%-1', + width: '50%+1', + height: '50%+3', + border: 'line', + content: 'Foo' +}); + +blessed.listtable({ + parent: screen, + left: '50%-1', + top: '50%-1', + width: '50%+3', + height: '50%+3', + border: 'line', + align: 'center', + tags: true, + keys: true, + vi: true, + mouse: true, + style: { + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta', + selected: { + bg: 'blue' + } + } + }, + data: [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] + ] +}).focus(); + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://raw.githubusercontent.com/chjj/blessed/master/example/simple-form.js + +var form = blessed.form({ + parent: screen, + keys: true, + left: 0, + top: 0, + width: 30, + height: 4, + bg: 'green', + content: 'Submit or cancel?' +}); + +var submit = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 10, + top: 2, + shrink: true, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +var cancel = blessed.button({ + parent: form, + mouse: true, + keys: true, + padding: { + left: 1, + right: 1 + }, + left: 20, + top: 2, + shrink: true, + name: 'cancel', + content: 'cancel', + style: { + bg: 'blue', + focus: { + bg: 'red' + }, + hover: { + bg: 'red' + } + } +}); + +// https://github.com/chjj/blessed/blob/master/test/widget-layout.js + +screen = blessed.screen({ + dump: __dirname + '/logs/layout.log', + smartCSR: true, + autoPadding: true, + warnings: true +}); + +var layout = blessed.layout({ + parent: screen, + top: 'center', + left: 'center', + width: '50%', + height: '50%', + border: 'line', + layout: process.argv[2] === 'grid' ? 'grid' : 'inline', + style: { + bg: 'red', + border: { + fg: 'blue' + } + } +}); + +var box1 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '1' +}); + +var box2 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '2' +}); + +var box3 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '3' +}); + +var box4 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '4' +}); + +var box5 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '5' +}); + +var box6 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '6' +}); + +var box7 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '7' +}); + +var box8 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '8' +}); + +var box9 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '9' +}); + +var box10 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '10' +}); + +var box11 = blessed.box({ + parent: layout, + top: 0, + left: 0, + width: 10, + height: 5, + border: 'line', + content: '11' +}); + +var box12 = blessed.box({ + parent: layout, + top: 'center', + left: 'center', + width: 20, + height: 10, + border: 'line', + content: '12' +}); + +if (process.argv[2] !== 'grid') { + for (var i = 0; i < 10; i++) { + blessed.box({ + parent: layout, + // width: i % 2 === 0 ? 10 : 20, + // height: i % 2 === 0 ? 5 : 10, + width: Math.random() > 0.5 ? 10 : 20, + height: Math.random() > 0.5 ? 5 : 10, + border: 'line', + content: (i + 1 + 12) + '' + }); + } +} + +screen.key('q', function() { + return screen.destroy(); +}); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-form.js + +screen = blessed.screen({ + dump: __dirname + '/logs/form.log', + warnings: true +}); + +type FormData = { + radio1: boolean; + radio2: boolean; + text: string; + check: boolean; +}; + +var form2 = blessed.form({ + parent: screen, + mouse: true, + keys: true, + vi: true, + left: 0, + top: 0, + width: '100%', + //height: 12, + style: { + bg: 'green', + border: { + inverse: true + }, + scrollbar: { + inverse: true + } + }, + content: 'foobar', + scrollable: true, + scrollbar: { + ch: ' ' + } + //alwaysScroll: true +}); + +form2.on('submit', (data) => { + output.setContent(JSON.stringify(data, null, 2)); + screen.render(); +}); + +form2.key('d', function() { + form2.scroll(1, true); + screen.render(); +}); + +form2.key('u', function() { + form2.scroll(-1, true); + screen.render(); +}); + +var set = blessed.radioset({ + parent: form2, + left: 1, + top: 1, + shrink: true, + //padding: 1, + //content: 'f', + style: { + bg: 'magenta' + } +}); + +var radio1 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 0, + top: 0, + name: 'radio1', + content: 'radio1' +}); + +var radio2 = blessed.radiobutton({ + parent: set, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 15, + top: 0, + name: 'radio2', + content: 'radio2' +}); + +var text2 = blessed.textbox({ + parent: form2, + mouse: true, + keys: true, + style: { + bg: 'blue' + }, + height: 1, + width: 20, + left: 1, + top: 3, + name: 'text' +}); + +text2.on('focus', function() { + text2.readInput(); +}); + +var check = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 1, + name: 'check', + content: 'check' +}); + +var check2 = blessed.checkbox({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + style: { + bg: 'magenta' + }, + height: 1, + left: 28, + top: 14, + name: 'foooooooo2', + content: 'foooooooo2' +}); + +var submit = blessed.button({ + parent: form2, + mouse: true, + keys: true, + shrink: true, + padding: { + left: 1, + right: 1 + }, + left: 29, + top: 3, + name: 'submit', + content: 'submit', + style: { + bg: 'blue', + focus: { + bg: 'red' + } + } +}); + +submit.on('press', function() { + form2.submit(); +}); + +var box1 = blessed.box({ + parent: form2, + left: 1, + top: 10, + height: 10, + width: 10, + content: 'one', + style: { + bg: 'cyan' + } +}); + +var box2 = blessed.box({ + parent: box1, + left: 1, + top: 2, + height: 8, + width: 9, + content: 'two', + style: { + bg: 'magenta' + } +}); + +var box3 = blessed.box({ + parent: box2, + left: 1, + top: 2, + height: 6, + width: 8, + content: 'three', + style: { + bg: 'yellow' + } +}); + +var box4 = blessed.box({ + parent: box3, + left: 1, + top: 2, + height: 4, + width: 7, + content: 'four', + style: { + bg: 'blue' + } +}); + +var output = blessed.scrollabletext({ + parent: form2, + mouse: true, + keys: true, + left: 0, + top: 20, + height: 5, + right: 0, + style: { + bg: 'red' + }, + content: 'foobar' +}); + +var bottom = blessed.line({ + parent: form2, + type: 'line', + orientation: 'horizontal', + left: 0, + right: 0, + top: 50, + style: { + fg: 'blue' + } +}); + +screen.key('q', function() { + return screen.destroy(); +}); + +form2.focus(); + +form2.submit(); + +screen.render(); + +// https://github.com/chjj/blessed/blob/master/test/widget-table.js + +screen = blessed.screen({ + dump: __dirname + '/logs/table.log', + autoPadding: false, + fullUnicode: true, + warnings: true +}); + +var DU = '杜'; +var JUAN = '鹃'; + +var table = blessed.table({ + //parent: screen, + top: 'center', + left: 'center', + data: null, + border: 'line', + align: 'center', + tags: true, + //width: '80%', + width: 'shrink', + style: { + border: { + fg: 'red' + }, + header: { + fg: 'blue', + bold: true + }, + cell: { + fg: 'magenta' + } + } +}); + +var data1 = [ + [ 'Animals', 'Foods', 'Times' ], + [ 'Elephant', 'Apple', '1:00am' ], + [ 'Bird', 'Orange', '2:15pm' ], + [ 'T-Rex', 'Taco', '8:45am' ], + [ 'Mouse', 'Cheese', '9:05am' ] +]; + +data1[1][0] = '{red-fg}' + data1[1][0] + '{/red-fg}'; +data1[2][0] += ' (' + DU + JUAN + ')'; + +var data2 = [ + [ 'Animals', 'Foods', 'Times', 'Numbers' ], + [ 'Elephant', 'Apple', '1:00am', 'One' ], + [ 'Bird', 'Orange', '2:15pm', 'Two' ], + [ 'T-Rex', 'Taco', '8:45am', 'Three' ], + [ 'Mouse', 'Cheese', '9:05am', 'Four' ] +]; + +data2[1][0] = '{red-fg}' + data2[1][0] + '{/red-fg}'; +data2[2][0] += ' (' + DU + JUAN + ')'; + +screen.key('q', function() { + return screen.destroy(); +}); + +table.setData(data2); +screen.append(table); +screen.render(); + +setTimeout(function() { + table.setData(data1); + screen.render(); +}, 3000); diff --git a/blessed/blessed.d.ts b/blessed/blessed.d.ts index 6746afe5f5..cb9bd393ed 100644 --- a/blessed/blessed.d.ts +++ b/blessed/blessed.d.ts @@ -1,1256 +1,155 @@ -// Type definitions for blessed 0.1.5 +// Type definitions for blessed 0.1.81 // Project: https://github.com/chjj/blessed -// Definitions by: bryn austin bellomy +// Definitions by: bryn austin bellomy , Diullei Gomes // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// -declare module "blessed" -{ - import events = require('events'); - import buffer = require('buffer'); - import child_process = require('child_process'); +declare module "blessed" { + import {EventEmitter} from 'events'; + import * as stream from "stream" + import * as child_process from "child_process"; - module Blessed - { - export var colors: Colors; + export class BlessedProgram { + hideCursor: () => void; + move: any; + showCursor: any; + } - export interface GenericCallback { - (...args:any[]): void; + export module Widgets { + + export module Types { + + export type TTopLeft = string | number | "center"; + + export type TPosition = string | number; + + export type TMouseAction = "mousedown" | "mouseup" | "mousemove"; + + export type TStyle = { + type?: string; + bg?: string; + fg?: string; + ch?: string; + bold?: boolean; + underline?: boolean; + blink?: boolean; + inverse?: boolean; + invisible?: boolean; + transparent?: boolean; + border?: "line" | "bg" | TBorder; + hover?: boolean; + focus?: boolean; + label?: string; + track?: {bg?: string; fg?: string;}; + scrollbar?: {bg?: string; fg?: string;}; + } + + export type TBorder = { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export type TCursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } + + export type TAlign = "left" | "center" | "right"; + + export type ListbarCommand = { + key: string; + callback: () => void; + }; + + export type TImage = { + /** + * Pixel width. + */ + width: number; + /** + * Pixel height. + */ + height: number; + /** + * Image bitmap. + * */ + bmp: any; + /** + * Image cellmap (bitmap scaled down to cell size). + */ + cellmap: any; + }; + + export type Cursor = { + /** + * Have blessed draw a custom cursor and hide the terminal cursor (experimental). + */ + artificial: boolean; + /** + * Shape of the cursor. Can be: block, underline, or line. + */ + shape: boolean; + /** + * Whether the cursor blinks. + */ + blink: boolean; + /** + * Color of the color. Accepts any valid color value (null is default). + */ + color: string; + } } - export interface ColorPair { - /** background, must be number (-1 for default). */ - bg?: number; - /** foreground, must be number (-1 for default). */ - fg?: number; - } - - export interface Style extends ColorPair { - bold?: boolean; - underline?: boolean; - border: Border; - hover: ColorPair; - } - - export interface Border extends ColorPair { - /** type of border ('line' or 'bg'). */ - type?: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch?: string; - } - - export interface Padding { - top?:number; - right?:number; - bottom?:number; - left?:number; - } - - export interface Position { - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - top?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - right?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - bottom?:number|string; - /** offsets of the element relative to its parent. can be a number, percentage (0-100%), or keyword (center). right and bottom do not accept keywords. */ - left?:number|string; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?:number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?:number|string; - } - - export interface KeyCode { - name: string; - ctrl: boolean; - meta: boolean; - shift: boolean; - sequence: string; - full: string; - } - - export class Program - { - /** - Wrap the given text in terminal formatting codes corresponding to the given attribute - name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 - integer color number. - */ - text (text:string, attr:string): string; - } - - export interface Colors { - /** Either pass a hex string, an array of 3 numbers, or three separate numbers representing an RGB value. This returns the 0-255 color number for that color. */ - match (r:string|number[]|number, g?:number, b?:number): number; - - /** An array of the 255 colors as hex strings. */ - colors: string[]; - } - - export interface NodeOptions - { - screen?: Screen; - parent?: Node; - children?: Node[]; - } - - export class Node extends events.EventEmitter - { - constructor(options?:NodeOptions); - - type : string; - options : NodeOptions; - parent : Node; - screen : Screen; - children : Node[]; - data : any; - _ : any; - $ : any; - index : number; - - // on(event:string, callback:() => void); - // on(event:'adopt', callback:() => void); - // on(event:'remove', callback:() => void); - // on(event:'reparent', callback:() => void); - // on(event:'attach', callback:() => void); - // on(event:'detach', callback:() => void); - - prepend(node:Node): void; - append(node:Node): void; - remove(node:Node): void; - insert(node:Node, index:number): void; - insertBefore(node:Node, refNode:Node): void; - insertAfter(node:Node, refNode:Node): void; - detach(): void; - // emitDescendants(): void; - // get(key:string): any; - // get(key:string, default:any): any; - // set(key:string, value:any): void; - } - - export interface ScreenOptions extends NodeOptions - { - /** the blessed Program to be associated with. will be automatically instantiated if none is provided. */ - program?: any; - /** attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with uniform cells to their sides). this is known to cause flickering with elements that are not full-width, however, it is more optimal for terminal rendering. */ - smartCSR?: boolean; - /** do CSR on any element within 20 cols of the screen edge on either side. faster than smartCSR, but may cause flickering depending on what is on each side of the element. */ - fastCSR?: boolean; - /** attempt to perform back_color_erase optimizations for terminals that support it. it will also work with terminals that don't support it, but only on lines with the default background color. as it stands with the current implementation, it's uncertain how much terminal performance this adds at the cost of overhead within node. */ - useBCE?: boolean; - /** amount of time (in ms) to redraw the screen after the terminal is resized (default: 300). */ - resizeTimeout?: number; - /** the width of tabs within an element's content. */ - tabSize?: number; - /** automatically position child elements with border and padding in mind. */ - autoPadding?: boolean; - /** the name of the logfile to use. if specified but the file does not exist, it will be created. see log method. */ - log?: string; - /** dump all output and input to desired file. can be used together with log option if set as a boolean. */ - dump?: any; - /** debug mode. enables usage of the `debug` method. also creates a debug console which will display when pressing F12. it will display all log and debug messages. */ - debug?: boolean; - /** Array of keys in their full format (e.g. C-c) to ignore when keys are locked. Useful for creating a key that will always exit no matter whether the keys are locked. */ - ignoreLocked?: string[]; - - /** Do not clear the screen, only scroll down enough to make room for the elements on the screen. do not use the alternate screenbuffer. useful for writing a CLI tool or some kind of prompt (experimental - see test/widget-noalt.js) */ - noAlt?: boolean; - - /** Options for the cursor. */ - cursor?: CursorOptions; - } - - export interface CursorOptions { - /** have blessed draw a custom cursor and hide the terminal cursor (experimental). */ - artificial?: boolean; - /** shape of the artificial cursor. can be: block, underline, or line. */ - shape?: string; //'block'|'underline'|'line'; - /** whether the artificial cursor blinks. */ - blink?: boolean; - /** color of the artificial cursor. accepts any valid color value (null is default). */ - color?: string; - } - - export interface ScreenEventCallback { - (character:string, keyCode:KeyCode): void; - } - - export class Screen extends Node - { - constructor(options?:ScreenOptions); - - /** the blessed Program object. */ - program: any; - /** the blessed Tput object (only available if you passed tput: true to the Program constructor.) */ - tput: any; - /** top of the focus history stack. */ - focused: any; - /** width of the screen (same as program.cols). */ - width: number; - /** height of the screen (same as program.rows). */ - height: number; - /** same as screen.width. */ - cols: number; - /** same as screen.height. */ - rows: number; - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** whether the focused element grabs all keypresses. */ - grabKeys: boolean; - /** prevent keypresses from being received by any element. */ - lockKeys: boolean; - /** the currently hovered element. only set if mouse events are bound. */ - hover: Element; - /** set or get window title. */ - title: string; - - /** write string to the log file if one was created. */ - log(...msg:any[]): void; - /** same as the log method, but only gets called if the debug option was set. */ - debug(...msg:string[]): void; - /** allocate a new pending screen buffer and a new output screen buffer. */ - alloc(): void; - /** draw the screen based on the contents of the screen buffer. */ - draw(start:number, end:number): void; - /** render all child elements, writing all data to the screen buffer and drawing the screen. */ - render(): void; - /** clear any region on the screen. */ - clearRegion(x1:number, x2:number, y1:number, y2:number): void; - /** fill any region with a character of a certain attribute. */ - fillRegion(attr:number, ch:string, x1:number, x2:number, y1:number, y2:number): void; - /** focus element by offset of focusable elements. */ - focusOffset(offset:number): void; - /** focus previous element in the index. */ - focusPrevious(): void; - /** focus next element in the index. */ - focusNext(): void; - /** push element on the focus stack (equivalent to screen.focused = el). */ - focusPush(element:Element): void; - /** pop element off the focus stack. */ - focusPop(): void; - /** save the focused element. */ - saveFocus(): void; - /** restore the saved focused element. */ - restoreFocus(): void; - /** "rewind" focus to the last visible and attached element. */ - rewindFocus(): void; - /** bind a keypress listener for a specific key. */ - key(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** bind a keypress listener for a specific key once. */ - onceKey(keyEvents:string|string[], callback:ScreenEventCallback): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:ScreenEventCallback): void; - /** spawn a process in the foreground, return to blessed app after exit. */ - spawn(file:string, args:string[], options:NodeChildProcessExecOptions): child_process.ChildProcess; - /** spawn a process in the foreground, return to blessed app after exit. executes callback on error or exit. */ - exec(file:string, args:string[], options:NodeChildProcessExecOptions, callback:GenericCallback): child_process.ChildProcess; - /** read data from text editor. */ - readEditor(options:{}, callback:GenericCallback): void; - /** set effects based on two events and attributes. */ - setEffects(el:Element, fel:Element, over:string, out:string, effects:Style, temp?:string): void; - /** insert a line into the screen (using csr: this bypasses the output buffer). */ - insertLine(n:number, y:number, top:number, bottom:number): void; - /** delete a line from the screen (using csr: this bypasses the output buffer). */ - deleteLine(n:number, y:number, top:number, bottom:number): void; - /** insert a line at the bottom of the screen. */ - insertBottom(top:number, bottom:number): void; - /** insert a line at the top of the screen. */ - insertTop(top:number, bottom:number): void; - /** delete a line at the bottom of the screen. */ - deleteBottom(top:number, bottom:number): void; - /** delete a line at the top of the screen. */ - deleteTop(top:number, bottom:number): void; - - /** enable mouse events for the screen and optionally an element (automatically called when a form of on('mouse') is bound). */ - enableMouse(el?:Element): void; - /** enable keypress events for the screen and optionally an element (automatically called when a form of on('keypress') is bound). */ - enableKeys(el?:Element): void; - /** enable key and mouse events. calls bot enableMouse and enableKeys. */ - enableInput(el?:Element): void; - - /** attempt to copy text to clipboard using iTerm2's propriety sequence. returns true if successful. */ - copyToClipboard(text:string): boolean; - /** attempt to change cursor shape. will not work in all terminals (see artificial cursors for a solution to this). returns true if successful. */ - cursorShape(shape:string, blink:boolean): boolean; - /** attempt to change cursor color. returns true if successful. */ - cursorColor(color: string): boolean; - /** attempt to reset cursor. returns true if successful. */ - cursorReset(): boolean; - - } - - export interface ElementOptions extends NodeOptions - { - fg?: string; - bg?: string; - scrollbar?: ColorPair; - focus?: Style; - hover?: Style; - - /** border object, see below. */ - border?: Border; - /** positioning options. */ - position?: Position; - /** amount of padding on the inside of the element. can be a number or an object containing the properties: left, right, top, and bottom. */ - padding?: number|Padding; - /** element's text content. */ - content?: string; - /** element is clickable. */ - clickable?: boolean; - /** element is focusable and can receive key input. */ - input?: boolean; - /** element is focused. */ - focused?: boolean; - /** whether the element is hidden. */ - hidden?: boolean; - /** a simple text label for the element. */ - label?: string; - /** a floating text label for the element which appears on mouseover. */ - hoverText?: string; - /** text alignment: left, center, or right. */ - align?: string; - /** vertical text alignment: top, middle, or bottom. */ - valign?: string; - /** shrink/flex/grow to content and child elements. width/height during render. */ - shrink?: any; - /** width of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - width?: number|string; - /** height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). */ - height?: number|string; - /** whether the element is scrollable or not. */ - scrollable?: boolean; - /** background character (default is whitespace ). */ - ch?: string; - /** allow the element to be dragged with the mouse. */ - draggable?: boolean; - } - - export class Element extends Node - { - constructor(options?:ElementOptions); - - /** name of the element. useful for form submission. */ - name: string; - /** border object. */ - border: Border; - /** contains attributes (e.g. fg/bg/underline). see above. */ - style: Style; - /** raw width, height, and offsets. */ - position: Position; - /** type of border (line or bg). bg by default. */ - type: string; //'line'|'bg'; - /** character to use if bg type, default is space. */ - ch: string; - /** raw text content. */ - content: string; - /** whether the element is hidden or not. */ - hidden: boolean; - /** whether the element is visible or not. */ - visible: boolean; - /** whether the element is attached to a screen in its ancestry somewhere. */ - detached: boolean; - /** calculated width. */ - width: number; - /** calculated height. */ - height: number; - /** whether the element is draggable. set to true to allow dragging. */ - draggable: boolean; - - - - /** calculated relative left offset. */ - left: number; - /** calculated relative right offset. */ - right: number; - /** calculated relative top offset. */ - top: number; - /** calculated relative bottom offset. */ - bottom: number; - /** calculated absolute left offset. */ - aleft: number; - /** calculated absolute right offset. */ - aright: number; - /** calculated absolute top offset. */ - atop: number; - /** calculated absolute bottom offset. */ - abottom: number; - - - /** write content and children to the screen buffer. */ - render(): void; - /** hide element. */ - hide(): void; - /** show element. */ - show(): void; - /** toggle hidden/shown. */ - toggle(): void; - /** focus element. */ - focus(): void; - /** bind a keypress listener for a specific key. */ - key(name:string|string[], listener:(character?:any, keyCode?:any) => void): void; - /** bind a keypress listener for a specific key once. */ - onceKey(name:string, listener:() => void): void; - /** remove a keypress listener for a specific key. */ - unkey(name:string, listener:() => void): void; - /** same as el.on('screen', ...) except this will automatically cleanup listeners after the element is detached. */ - onScreenEvent(event:string, listener:(...args:any[]) => void): void; - /** set the z-index of the element (changes rendering order). */ - setIndex(z:number): void; - /** put the element in front of its siblings. */ - setFront(): void; - /** put the element in back of its siblings. */ - setBack(): void; - /** set the label text for the top-left corner. example options: {text:'foo',side:'left'} */ - setLabel(textOrOptions:string|{}): void; - /** remove the label completely. */ - removeLabel(): void; - /** set the hover text for the bottom-right corner. example options: {text:'foo'} */ - setHover(textOrOptions:string|{}): void; - /** remove the hover label completely. */ - removeHover(): void; - /** set the content. note: when text is input, it will be stripped of all non-SGR escape codes, tabs will be replaced with 8 spaces, and tags will be replaced with SGR codes (if enabled). */ - setContent(text:string): void; - /** return content, slightly different from el.content. assume the above formatting. */ - getContent(): void; - /** similar to setContent, but ignore tags and remove escape codes. */ - setText(text:string): void; - /** similar to getContent, but return content with tags and escape codes removed. */ - getText(): void; - /** insert a line into the box's content. */ - insertLine(index:number, lines:string|string[]): void; - /** delete a line from the box's content. */ - deleteLine(index:number, numLines:number): void; - /** get a line from the box's content. */ - getLine(index:number): void; - /** get a line from the box's content from the visible top. */ - getBaseLine(index:number): void; - /** set a line in the box's content. */ - setLine(index:number, line:string): void; - /** set a line in the box's content from the visible top. */ - setBaseLine(index:number, line:string): void; - /** clear a line from the box's content. */ - clearLine(index:number): void; - /** clear a line from the box's content from the visible top. */ - clearBaseLine(index:number): void; - /** insert a line at the top of the box. */ - insertTop(lines:string|string[]): void; - /** insert a line at the bottom of the box. */ - insertBottom(lines:string|string[]): void; - /** delete a line at the top of the box. */ - deleteTop(): void; - /** delete a line at the bottom of the box. */ - deleteBottom(): void; - /** unshift a line onto the top of the content. */ - unshiftLine(lines:string|string[]): void; - /** shift a line off the top of the content. */ - shiftLine(index:number): void; - /** push a line onto the bottom of the content. */ - pushLine(lines:string|string[]): void; - /** pop a line off the bottom of the content. */ - popLine(index:number): void; - /** an array containing the content lines. */ - getLines(): void; - /** an array containing the lines as they are displayed on the screen. */ - getScreenLines(): void; - /** get a string's real length, taking into account tags. */ - textLength(text:string): number; - - /** enable dragging of the element. */ - enableDrag(): void; - /** disable dragging of the element. */ - disableDrag(): void; - } - - - // - // Box - // - - export interface BoxOptions extends ElementOptions { - // intentionally empty - } - - export class Box extends Element { - constructor(options?:BoxOptions); - // intentionally empty - } - - - // - // ScrollableBox - // - - export interface ScrollableBoxOptions extends BoxOptions { - /** a limit to the childBase. default is `Infinity`. */ - baseLimit: number; - /** a option which causes the ignoring of `childOffset`. this in turn causes the childBase to change every time the element is scrolled. */ - alwaysScroll: boolean; - /** object enabling a scrollbar. */ - scrollbar: ScrollBar; - } - - /** A box with scrollable content. */ - export class ScrollableBox extends Box { - constructor(options?:ScrollableBoxOptions); - - /** the offset of the top of the scroll content. */ - childBase: number; - /** the offset of the chosen item/line. */ - childOffset: number; - /** scroll the content by a relative offset. */ - scroll(offset:number): void; - /** scroll the content to an absolute index. */ - scrollTo(index:number): void; - /** same as `scrollTo`. */ - setScroll(index:number): void; - /** set the current scroll index in percentage (0-100). */ - setScrollPerc(perc:number): void; - /** get the current scroll index in lines. */ - getScroll(): number; - /** get the actual height of the scrolling area. */ - getScrollHeight(): number; - /** get the current scroll index in percentage. */ - getScrollPerc(): number; - /** reset the scroll index to its initial state. */ - resetScroll(): void; - - } - - export interface ScrollBar { - /** style of the scrollbar. */ - style: Style; - /** style of the scrollbar track if present (takes regular style options). */ - track: Style; - } - - - // - // ScrollableText - // - - export interface ScrollableTextOptions extends ScrollableBoxOptions { - /** whether to enable automatic mouse support for this element. */ - mouse: boolean; - /** use predefined keys for navigating the text. */ - keys: boolean; - /** use vi keys with the `keys` option. */ - vi: boolean; - } - - /** __DEPRECATED__ - Use Box with the `scrollable` and `alwaysScroll` options instead. A scrollable text box which can display and scroll text, as well as handle pre-existing newlines and escape codes. */ - export class ScrollableText extends ScrollableBox { - constructor(options?:ScrollableTextOptions); - } - - - - // - // Text - // - - export interface TextOptions extends ElementOptions { - align?: string; //'left'|'center'|'right'; - } - - export class Text extends Element { - constructor(options?:TextOptions); - // intentionally empty - } - - - // - // Line - // - - export interface LineOptions extends BoxOptions { - orientation?: string; //'vertical'|'horizontal'; - style?: Style; - } - - export class Line extends Box { - constructor(options?:LineOptions); - // intentionally empty - } - - - // - // List - // - - export interface ListStyle extends Style { - selected?: Style; - item?: Style; - } - - export interface ListOptions extends BoxOptions - { - style?: ListStyle; - - /** whether to automatically enable mouse support for this list (allows clicking items). */ - mouse?: boolean; - /** use predefined keys for navigating the list. */ - keys?: any; - /** use vi keys with the keys option. */ - vi?: boolean; - /** an array of strings which become the list's items. */ - items?: string[]; - /** a function that is called when vi mode is enabled and the key / is pressed. This function accepts a callback function which should be called with the search string. The search string is then used to jump to an item that is found in items. */ - search?: (callback:(searchString:string) => void) => void; - /** whether the list is interactive and can have items selected (default: true). */ - interactive?: boolean; - } - - export class List extends Box - { - constructor(options?:ListOptions); - - /** The text of the currently selected item. */ - value:string; - /** The items in the list. */ - items:string[]; - /** The items in the list. */ - ritems:string[]; - /** The index of the current selection. */ - selected:number; - - /** add an item based on a string. */ - addItem(text:string): void; - /** returns the item index from the list. child can be an element, index, or string. */ - getItemIndex(child:Element|number|string): void; - /** returns the item element. child can be an element, index, or string. */ - getItem(child:Element|number|string): void; - /** removes an item from the list. child can be an element, index, or string. */ - removeItem(child:Element|number|string): void; - /** clears all items from the list. */ - clearItems(): void; - /** sets the list items to multiple strings. */ - setItems(items:string[]): void; - /** Sets the current selection by absolute index. */ - select(index:number): void; - /** Changes the current selection based on current offset. */ - move(offset:number): void; - /** select item above selected. */ - up(amount:number): void; - /** select item below selected. */ - down(amount:number): void; - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(cwd:string, callback:(err:any, file:string) => void): void; - - /** show/focus list and pick an item. the callback is executed with the result. */ - pick(callback:(err:any, file:string) => void): void; - } - - // - // Input - // - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - export class Input extends Box { - constructor(options?:InputOptions); - // intentionally empty - } - - export interface InputOptions extends BoxOptions { - // intentionally empty - } - - // - // Textarea - // - - export interface TextareaOptions extends InputOptions - { - /** use pre-defined keys (`i` or `enter` for insert, `e` for editor, `C-e` for editor while inserting). */ - keys?: boolean; - /** use pre-defined mouse events (right-click for editor). */ - mouse?: boolean; - /** call `readInput()` when the element is focused. automatically unfocus. */ - inputOnFocus?: boolean; - } - - /** A box which allows multiline text input. */ - export class Textarea extends Input - { - constructor(options?:TextareaOptions); - - /** the input text. __read-only__. */ - value: string; - - /** submit the textarea (emits `submit`). */ - submit(): void; - /** cancel the textarea (emits `cancel`). */ - cancel(): void; - /** grab key events and start reading text from the keyboard. takes a callback which receives the final value. */ - readInput(callback:GenericCallback): void; - /** open text editor in `$EDITOR`, read the output from the resulting file. takes a callback which receives the final value. */ - readEditor(callback:GenericCallback): void; - /** the same as `this.value`, for now. */ - getValue(): string; - /** clear input. */ - clearValue(): void; - /** set value. */ - setValue(text:string): void; - } - - - // - // Textbox - // - - export interface TextboxOptions extends TextareaOptions { - /** completely hide text. */ - secret?: boolean; - /** replace text with asterisks (`*`). */ - censor?: boolean; - } - - /** A box which allows text input. */ - export class Textbox extends Textarea { - constructor(options?:TextboxOptions); - - /** completely hide text. */ - secret: boolean; - /** replace text with asterisks (`*`). */ - censor: boolean; - } - - - // - // Button - // - - export interface ButtonOptions extends InputOptions { - } - - /** A button which can be focused and allows key and mouse input. */ - export class Button extends Input { - constructor(options?:ButtonOptions); - - // on(event:string, callback:() => void): void; - // on(event:'press', callback:() => void); - - /** press button. emits 'press'. */ - press(): void; - } - - - // - // ProgressBar - // - - export interface ProgressBarOptions extends InputOptions { - /** can be `horizontal` or `vertical`. */ - orientation: string; - /** the character to fill the bar with (default is space). */ - pch: string; - /** the amount filled (0 - 100). */ - filled: number; - /** same as `filled`. */ - value: number; - /** enable key support. */ - keys: boolean; - /** enable mouse support. */ - mouse: boolean; - - /** contains the extra key 'bar', which defines the style of the bar contents itself. */ - style: ProgressBarStyle; - } - - export interface ProgressBarStyle extends Style { - /** style of the bar contents itself. */ - bar: Style; - } - - - export class ProgressBar extends Input { - constructor(options?:ProgressBarOptions); - - /** progress the bar by a fill amount. */ - progress(amount:number): void; - /** set progress to specific amount. */ - setProgress(amount:number): void; - /** reset the bar. */ - reset(): void; - } - - // - // Checkbox - // - - export interface CheckboxOptions extends InputOptions { - /** whether the element is checked or not. */ - checked: boolean; - /** enable mouse support. */ - mouse: boolean; + export module Events { + + export interface IMouseEventArg { + x: number; + y: number; + action: Types.TMouseAction; + } + + export interface IKeyEventArg { + full: string; + name: string; + shift: boolean; + ctrl: boolean; + meta: boolean; + sequence: string; + } } - - /** A checkbox which can be used in a form element. */ - export class Checkbox extends Input - { - constructor(options?:CheckboxOptions); - - /** the text next to the checkbox (do not use setcontent, use `check.text = ''`). */ - text: string; - /** whether the element is checked or not. */ - checked: boolean; - /** same as `checked`. */ - value: boolean; - - /** check the element. */ - check(): void; - /** uncheck the element. */ - uncheck(): void; - /** toggle checked state. */ - toggle(): void; - } - - - // - // RadioSet - // - - export interface RadioSetOptions extends BoxOptions { - } - - - export class RadioSet extends Box { - constructor(options?:RadioSetOptions); - } - - - // - // RadioButton - // - - export interface RadioButtonOptions extends CheckboxOptions { - } - - - /** A radio button which can be used in a form element. */ - export class RadioButton extends Checkbox { - constructor(options?:RadioButtonOptions); - } - - - - // - // Prompt - // - - export interface PromptOptions extends BoxOptions { - } - - - /** A prompt box containing a text input, okay, and cancel buttons (automatically hidden). */ - export class Prompt extends Box - { - constructor(options?:PromptOptions); - - /** show the prompt and wait for the result of the textbox. set text and initial value */ - input(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - setInput(text:string, value:any, callback:(val:any) => void): void; - /** show the prompt and wait for the result of the textbox. set text and initial value */ - readInput(text:string, value:any, callback:(val:any) => void): void; - } - - - // - // Question - // - - export interface QuestionOptions extends BoxOptions { - } - - - /** A question box containing okay and cancel buttons (automatically hidden). */ - export class Question extends Box - { - constructor(options?:QuestionOptions); - - /** ask a `question`. `callback` will yield the result. */ - ask(question:string, callback:(result:any) => void): void; - } - - - // - // Message - // - - export interface MessageOptions extends BoxOptions { - } - - - /** A box containing a message to be displayed (automatically hidden). */ - export class Message extends Box - { - constructor(options?:MessageOptions); - - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - log(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display a message for a time (default is 3 seconds). set time to 0 for a perpetual message that is dismissed on keypress. */ - display(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - /** display an error in the same way. */ - error(text:string, timeOrCallback:number|MessageCallback, callback?:MessageCallback): void; - } - - export interface MessageCallback { - (): void; - } - - - // - // Loading - // - - export interface LoadingOptions extends BoxOptions { - } - - /** A box with a spinning line to denote loading (automatically hidden). */ - export class Loading extends Box - { - constructor(options?:LoadingOptions); - - /** display the loading box with a message. will lock keys until `stop` is called. */ - load(text:string): void; - /** hide loading box. unlock keys. */ - stop(): void; - } - - - // - // Listbar - // - - export interface ListbarOptions extends BoxOptions - { - /** Listbar's `style` object includes sub-styles for `selected` and `item`. */ - style?: ListbarStyle; - - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - items?: ListbarItemSet; - /** set buttons using an object with keys as titles of buttons, containing of objects containing keys of `keys` and `callback`. */ - commands?: ListbarItemSet; - /** automatically bind list buttons to keys 0-9. */ - autoCommandKeys?: boolean; - } - - export interface ListbarItemSet { - [name: string]: ListbarItem; - } - - export interface ListbarItem { - keys: string[]; - callback: GenericCallback; - } - - export interface ListbarStyle extends Style - { - /** style for a selected item. */ - selected: Style; - /** style for an unselected item. */ - item: Style; - } - - /** A horizontal list. Useful for a main menu bar. */ - export class Listbar extends Box - { - constructor(options?:ListbarOptions); - - /** append an item to the bar. */ - add(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - addItem(item:ListbarItem, callback:GenericCallback): void; - /** append an item to the bar. */ - appendItem(item:ListbarItem, callback:GenericCallback): void; - - /** select button and execute its callback. */ - selectTab(index: number): void; - - /** set commands (see `commands` option above). */ - setItems(commands: ListbarItemSet): void; - /** select an item on the bar. */ - select(offset: number): void; - /** remove item from the bar. */ - removeItem(child:ListbarItem): void; - /** move focus relatively across the bar. */ - move(offset: number): void; - /** move focus left relatively across the bar. */ - moveLeft(offset: number): void; - /** move focus right relatively across the bar. */ - moveRight(offset: number): void; - } - - - // - // Log - // - - export interface LogOptions extends ScrollableTextOptions { - /** amount of scrollback allowed. default: Infinity. */ - scrollback?: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput?: boolean; - } - - - /** A log permanently scrolled to the bottom. */ - export class Log extends ScrollableText - { - constructor(options?:LogOptions); - - /** amount of scrollback allowed. default: Infinity. */ - scrollback: number; - /** scroll to bottom on input even if the user has scrolled up. default: false. */ - scrollOnInput: boolean; - - /** add a log line. */ - log(text:string): void; - /** add a log line. */ - add(text:string): void; - } - - - // - // Table - // - - export interface TableOptions extends BoxOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - /** do not draw inner cells. */ - noCellBorders?: boolean; - /** fill cell borders with the adjacent background color. */ - fillCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface TableStyle extends Style { - /** header style. */ - header: Style; - /** cell style. */ - cell: Style; - } - - /** A stylized table of text elements. */ - export class Table extends Box - { - /** includes `header` and `cell` substyles. */ - style: TableStyle; - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - - // - // ListTable - // - - export interface ListTableOptions extends ListOptions - { - /** array of array of strings representing rows (same as `data`). */ - rows?: string[][]; - /** array of array of strings representing rows (same as `rows`). */ - data?: string[][]; - /** spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). */ - pad?: number; - - /** do not draw inner cells. */ - noCellBorders?: boolean; - - /** includes `header` and `cell` substyles. */ - style?: TableStyle; - } - - export interface ListTableStyle extends TableStyle { - } - - - /** A stylized table of text elements with a list. */ - export class ListTable extends List - { - constructor(options?:ListTableOptions); - - /** set rows in table. array of arrays of strings. */ - setData(rows: string[][]): void; - /** set rows in table. array of arrays of strings. */ - setRows(rows: string[][]): void; - } - - // - // Image - // - - export interface ImageOptions extends BoxOptions { - /** path to image. */ - file: string; - /** path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. */ - w3m: string; - } - - - /** Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. */ - export class Image extends Box - { - constructor(options?:ImageOptions); - - /** set the image in the box to a new path. */ - setImage (img:string, callback:GenericCallback): void; - /** clear the current image. */ - clearImage (callback:GenericCallback): void; - /** get the size of an image file in pixels. */ - imageSize (img:string, callback:GenericCallback): void; - /** get the size of the terminal in pixels. */ - termSize (callback:GenericCallback): void; - /** get the pixel to cell ratio for the terminal. */ - getPixelRatio (callback:GenericCallback): void; - } - - - // - // Form - // - - export interface FormOptions extends BoxOptions { - /** allow default keys (tab, vi keys, enter). */ - keys?:boolean; - /** allow vi keys. */ - vi?:boolean; - } - - export class Form extends Box - { - constructor(options?:FormOptions); - - /** last submitted data. */ - submission: any; - - // on(event:string, callback:() => void): void; - // on(event:'submit', callback:(data) => void): void; - // on(event:'cancel', callback:() => void): void; - // on(event:'reset', callback:() => void): void; - - next(): void; - previous(): void; - - resetSelected(): void; - /** focus first form element. */ - focusFirst(): void; - /** focus last form element. */ - focusLast(): void; - /** focus next form element. */ - focusNext(): void; - /** focus previous form element. */ - focusPrevious(): void; - /** submit the form. */ - submit(): void; - /** discard the form. */ - cancel(): void; - /** clear the form. */ - reset(): void; - } - - - // - // FileManager - // - - export interface FileManagerOptions extends ListOptions { - cwd?: string; - } - - export interface DirectoryEntry { - name: string; - text: string; - dir: boolean; - symlink: boolean; - } - - export class FileManager extends List - { - constructor(options?:FileManagerOptions); - - cwd: string; - - useFormatter (formatterFn:(entry:DirectoryEntry) => DirectoryEntry): void; - - /** refresh the file list (perform a readdir on cwd and update the list items). */ - refresh (cwd?:string, callback?:() => void): void; - - /** refresh the file list. */ - refresh (callback?:() => void): void; - - /** reset back to original cwd. */ - reset (cwd?:string, callback?:() => void): void; - } - - - // - // Terminal - // - - export interface TerminalOptions extends BoxOptions - { - /** handler for input data. */ - handler?: (userInput:Buffer) => void; - /** name of shell. $SHELL by default. */ - shell?:string; - /** args for shell. */ - args?:any; - /** can be line, underline, and block. */ - cursor?:string; //'line'|'underline'|'block'; - } - - export class Terminal extends Box - { - /** reference to the headless term.js terminal. */ - term: any; - /** reference to the pty.js pseudo terminal. */ - pty: any; - - /** write data to the terminal. */ - write(data:string): void; - - /** nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. */ - screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; - } - - - export interface NodeChildProcessExecOptions - { + export interface NodeChildProcessExecOptions { cwd?: string; stdio?: any; customFds?: any; @@ -1260,10 +159,2676 @@ declare module "blessed" maxBuffer?: number; killSignal?: string; } + + export interface IDestroyable { + destroy(): void; + } + + export interface IOptions { + } + + export interface IHasOptions { + options: T; + } + + export interface TputsOptions extends IOptions { + terminal?: string; + extended?: boolean; + debug?: boolean; + termcap?: string; + terminfoFile?: string; + terminfoPrefix?: string; + termcapFile?: string; + } + + export class Tput implements IHasOptions { + constructor(opts: TputsOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: TputsOptions; + + debug: boolean; + padding: boolean; + extended: boolean; + printf: boolean; + termcap: string; + terminfoPrefix: string; + terminfoFile: string; + termcapFile: string; + error: Error; + terminal: string; + + setup(): void; + term(is: any): boolean; + readTerminfo(term: string): string; + parseTerminfo(data: any, file: string): { + header: { + dataSize: number; + headerSize: number; + magicNumber: boolean; + namesSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + extended: { + dataSize: number; + headerSize: number; + boolCount: number; + numCount: number; + strCount: number; + strTableSize: number; + lastStrTableOffset: number; + } + } + name: string; + names: string[]; + desc: string; + bools: Object; + numbers: Object; + strings: Object; + }; + } + + export interface IDestroyable { + destroy(): void; + } + + export interface INodeOptions extends IOptions { + name?: string; + screen?: Screen; + parent?: Node; + children?: Node[]; + focusable?: boolean; + } + + export abstract class Node extends EventEmitter implements IHasOptions, IDestroyable { + constructor(options: INodeOptions); + + // ** properties ** // + + focusable: boolean; + + /** + * Original options object. + */ + options: INodeOptions; + + /** + * An object for any miscellanous user data. + */ + data: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + _: {[index: string]: any;}; + /** + * An object for any miscellanous user data. + */ + $: {[index: string]: any;}; + /** + * Type of the node (e.g. box). + */ + type: string; + /** + * Render index (document order index) of the last render call. + */ + index: number; + /** + * Parent screen. + */ + screen: Screen; + /** + * Parent node. + */ + parent: Node; + /** + * Array of node's children. + */ + children: Node[]; + + // ** methods ** // + + /** + * Prepend a node to this node's children. + */ + prepend(node: Node): void; + /** + * Append a node to this node's children. + */ + append(node: Node): void; + /** + * Remove child node from node. + */ + remove(node: Node): void; + /** + * Insert a node to this node's children at index i. + */ + insert(node: Node, index: number): void; + /** + * Insert a node to this node's children before the reference node. + */ + insertBefore(node: Node, refNode: Node): void; + /** + * Insert a node from node after the reference node. + */ + insertAfter(node: Node, refNode: Node): void; + /** + * Remove node from its parent. + */ + detach(): void; + /** + * Remove node from its parent. + */ + free(): void; + /** + * Remove node from its parent. + */ + forDescendants(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + forAncestors(iter: Function, s: any): void; + /** + * Remove node from its parent. + */ + collectDescendants(s: any): void; + /** + * Remove node from its parent. + */ + collectAncestors(s: any): void; + /** + * Remove node from its parent. + */ + emitDescendants(): void; + /** + * Remove node from its parent. + */ + emitAncestors(): void; + /** + * Remove node from its parent. + */ + hasDescendant(target: Node): void; + /** + * Remove node from its parent. + */ + hasAncestor(target: Node): boolean; + /** + * Remove node from its parent. + */ + destroy(): void; + /** + * Emit event for element, and recursively emit same event for all descendants. + */ + emitDescendants(type: string, ...args: any[]): void; + /** + * Get user property with a potential default value. + */ + get(name: string, def: T): T; + /** + * Set user property to value. + */ + set(name: string, value: T): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when node is added to a parent. + */ + on(event: "adopt", callback: (arg: Node) => void): this; + /** + * Received when node is removed from it's current parent. + */ + on(event: "remove", callback: (arg: Node) => void): this; + /** + * Received when node gains a new parent. + */ + on(event: "reparent", callback: (arg: Node) => void): this; + /** + * Received when node is attached to the screen directly or somewhere in its ancestry. + */ + on(event: "attach", callback: (arg: Node) => void): this; + /** + * Received when node is detached from the screen directly or somewhere in its ancestry. + */ + on(event: "detach", callback: (arg: Node) => void): this; + } + + export class NodeWithEvents extends Node { + // ** methods ** // + + /** + * Bind a keypress listener for a specific key. + */ + key(name: string | string[], listener: Function): void; + /** + * Bind a keypress listener for a specific key once. + */ + onceKey(name: string, listener: Function): void; + /** + * Remove a keypress listener for a specific key. + */ + unkey(name: string, listener: Function): void; + removeKey(name: string, listener: Function): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received on screen resize. + */ + on(event: "resize", callback: () => void): this; + /** + * Received on mouse events. + */ + on(event: "mouse", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseout", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseover", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousedown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mouseup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousewheel", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheeldown", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "wheelup", callback: (arg: Events.IMouseEventArg) => void): this; + on(event: "mousemove", callback: (arg: Events.IMouseEventArg) => void): this; + /** + * Received on key events. + */ + on(event: "keypress", callback: (ch: string, key: Events.IKeyEventArg) => void): this; + /** + * Global events received for all elements. + */ + on(event: "element click", callback: (arg: Screen) => void): this; + on(event: "element mouseover", callback: (arg: Screen) => void): this; + on(event: "element mouseout", callback: (arg: Screen) => void): this; + on(event: "element mouseup", callback: (arg: Screen) => void): this; + /** + * Received on key event for [name]. + */ + //on(event: "key", callback: (arg: BlessedScreen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "focus", callback: (arg: Screen) => void): this; + /** + * Received when the terminal window focuses/blurs. Requires a terminal supporting the + * focus protocol and focus needs to be passed to program.enableMouse(). + */ + on(event: "blur", callback: (arg: Screen) => void): this; + /** + * Received before render. + */ + on(event: "prerender", callback: () => void): this; + /** + * Received on render. + */ + on(event: "render", callback: () => void): this; + /** + * Received when blessed notices something untoward (output is not a tty, terminfo not found, etc). + */ + on(event: "warning", callback: (text: string) => void): this; + /** + * Received when the screen is destroyed (only useful when using multiple screens). + */ + on(event: "destroy", callback: () => void): this; + /** + * Received when the element is moved. + */ + on(event: "move", callback: () => void): this; + /** + * Element was clicked (slightly smarter than mouseup). + */ + on(event: "click", callback: (arg: Screen) => void): this; + /** + * Received when element is shown. + */ + on(event: "show", callback: () => void): this; + /** + * Received when element becomes hidden. + */ + on(event: "hide", callback: () => void): this; + + on(event: "set content", callback: () => void): this; + on(event: "parsed content", callback: () => void): this; + } + + export interface IScreenOptions extends INodeOptions { + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program?: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR?: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR?: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE?: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout?: number; + /** + * The width of tabs within an element's content. + */ + tabSize?: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding?: boolean; + + cursor?: Types.TCursor; + + /** + * Create a log file. See log method. + */ + log?: (...msg: any[]) => void; + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump?: string; + /** + * Debug mode. Enables usage of the debug method. Also creates a debug console which will display when + * pressing F12. It will display all log and debug messages. + */ + debug?: (...msg: string[]) => void; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked?: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders?: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast?: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode?: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus?: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings?: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode?: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input?: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output?: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput?: Tput; + /** + * Top of the focus history stack. + */ + focused?: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width?: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height?: Types.TPosition; + /** + * Same as screen.width. + */ + cols?: number; + /** + * Same as screen.height. + */ + rows?: number; + /** + * Relative top offset, always zero. + */ + top?: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left?: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right?: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom?: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop?: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft?: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright?: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom?: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys?: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys?: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover?: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal?: string; + /** + * Set or get window title. + */ + title?: string; + } + + export class Screen extends NodeWithEvents implements IHasOptions { + constructor(opts: IScreenOptions); + + // ** properties ** // + cleanSides: any; + + /** + * Original options object. + */ + options: IScreenOptions; + + /** + * The blessed Program to be associated with. Will be automatically instantiated if none is provided. + */ + program: BlessedProgram; + /** + * Attempt to perform CSR optimization on all possible elements (not just full-width ones, elements with + * uniform cells to their sides). This is known to cause flickering with elements that are not full-width, + * however, it is more optimal for terminal rendering. + */ + smartCSR: boolean; + /** + * Do CSR on any element within 20 cols of the screen edge on either side. Faster than smartCSR, + * but may cause flickering depending on what is on each side of the element. + */ + fastCSR: boolean; + /** + * Attempt to perform back_color_erase optimizations for terminals that support it. It will also work + * with terminals that don't support it, but only on lines with the default background color. As it + * stands with the current implementation, it's uncertain how much terminal performance this adds at + * the cost of overhead within node. + */ + useBCE: boolean; + /** + * Amount of time (in ms) to redraw the screen after the terminal is resized (Default: 300). + */ + resizeTimeout: number; + /** + * The width of tabs within an element's content. + */ + tabSize: number; + /** + * Automatically position child elements with border and padding in mind (NOTE: this is a recommended + * option. It may become default in the future). + */ + autoPadding: boolean; + + cursor: Types.TCursor; + + /** + * Dump all output and input to desired file. Can be used together with log option if set as a boolean. + */ + dump: string; + /** + * Array of keys in their full format (e.g. C-c) to ignore when keys are locked or grabbed. Useful + * for creating a key that will always exit no matter whether the keys are locked. + */ + ignoreLocked: boolean; + /** + * Automatically "dock" borders with other elements instead of overlapping, depending on position + * (experimental). For example: These border-overlapped elements: + */ + dockBorders: boolean; + /** + * Normally, dockable borders will not dock if the colors or attributes are different. This option + * will allow them to dock regardless. It may produce some odd looking multi-colored borders though. + */ + ignoreDockContrast: boolean; + /** + * Allow for rendering of East Asian double-width characters, utf-16 surrogate pairs, and unicode + * combining characters. This allows you to display text above the basic multilingual plane. This + * is behind an option because it may affect performance slightly negatively. Without this option + * enabled, all double-width, surrogate pair, and combining characters will be replaced by '??', + * '?', '' respectively. (NOTE: iTerm2 cannot display combining characters properly. Blessed simply + * removes them from an element's content if iTerm2 is detected). + */ + fullUnicode: boolean; + /** + * Send focus events after mouse is enabled. + */ + sendFocus: boolean; + /** + * Display warnings (such as the output not being a TTY, similar to ncurses). + */ + warnings: boolean; + /** + * Force blessed to use unicode even if it is not detected via terminfo, env variables, or windows code page. + * If value is true unicode is forced. If value is false non-unicode is forced (default: null). + */ + forceUnicode: boolean; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + input: stream.Writable; + /** + * Input and output streams. process.stdin/process.stdout by default, however, it could be a + * net.Socket if you want to make a program that runs over telnet or something of that nature. + * */ + output: stream.Readable; + /** + * The blessed Tput object (only available if you passed tput: true to the Program constructor.) + */ + tput: Tput; + /** + * Top of the focus history stack. + */ + focused: BlessedElement; + /** + * Width of the screen (same as program.cols). + */ + width: Types.TPosition; + /** + * Height of the screen (same as program.rows). + */ + height: Types.TPosition; + /** + * Same as screen.width. + */ + cols: number; + /** + * Same as screen.height. + */ + rows: number; + /** + * Relative top offset, always zero. + */ + top: Types.TTopLeft; + /** + * Relative left offset, always zero. + */ + left: Types.TTopLeft; + /** + * Relative right offset, always zero. + */ + right: Types.TPosition; + /** + * Relative bottom offset, always zero. + */ + bottom: Types.TPosition; + /** + * Absolute top offset, always zero. + */ + atop: Types.TTopLeft; + /** + * Absolute left offset, always zero. + */ + aleft: Types.TTopLeft; + /** + * Absolute right offset, always zero. + */ + aright: Types.TPosition; + /** + * Absolute bottom offset, always zero. + */ + abottom: Types.TPosition; + /** + * Whether the focused element grabs all keypresses. + */ + grabKeys: any; + /** + * Prevent keypresses from being received by any element. + */ + lockKeys: boolean; + /** + * The currently hovered element. Only set if mouse events are bound. + */ + hover: any; + /** + * Set or get terminal name. Set calls screen.setTerminal() internally. + */ + terminal: string; + /** + * Set or get window title. + */ + title: string; + + // ** methods ** // + + /** + * Write string to the log file if one was created. + */ + log(...msg: any[]): void; + /** + * Same as the log method, but only gets called if the debug option was set. + */ + debug(...msg: string[]): void; + /** + * Allocate a new pending screen buffer and a new output screen buffer. + */ + alloc(): void; + /** + * Reallocate the screen buffers and clear the screen. + */ + realloc(): void; + /** + * Draw the screen based on the contents of the screen buffer. + */ + draw(start: number, end: number): void; + /** + * Render all child elements, writing all data to the screen buffer and drawing the screen. + */ + render(): void; + /** + * Clear any region on the screen. + */ + clearRegion(x1: number, x2: number, y1: number, y2: number): void; + /** + * Fill any region with a character of a certain attribute. + */ + fillRegion(attr: string, ch: string, x1: number, x2: number, y1: number, y2: number): void; + /** + * Focus element by offset of focusable elements. + */ + focusOffset(offset: number): any; + /** + * Focus previous element in the index. + */ + focusPrevious(): void; + /** + * Focus next element in the index. + */ + focusNext(): void; + /** + * Push element on the focus stack (equivalent to screen.focused = el). + */ + focusPush(element: BlessedElement): void; + /** + * Pop element off the focus stack. + */ + focusPop(): BlessedElement; + /** + * Save the focused element. + */ + saveFocus(): BlessedElement; + /** + * Restore the saved focused element. + */ + restoreFocus(): BlessedElement; + /** + * "Rewind" focus to the last visible and attached element. + */ + rewindFocus(): BlessedElement; + /** + * Spawn a process in the foreground, return to blessed app after exit. + */ + spawn(file: string, args: string[], options: NodeChildProcessExecOptions): child_process.ChildProcess; + /** + * Spawn a process in the foreground, return to blessed app after exit. Executes callback on error or exit. + */ + exec(file: string, args: string[], options: NodeChildProcessExecOptions, callback: Function): child_process.ChildProcess; + /** + * Read data from text editor. + */ + readEditor(options: any, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + readEditor(callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + /** + * Set effects based on two events and attributes. + */ + setEffects(el: BlessedElement, fel: BlessedElement, over: any, out: any, effects: any, temp: any): void; + /** + * Insert a line into the screen (using csr: this bypasses the output buffer). + */ + insertLine(n: number, y: number, top: number, bottom: number): void; + /** + * Delete a line from the screen (using csr: this bypasses the output buffer). + */ + deleteLine(n: number, y: number, top: number, bottom: number): void; + /** + * Insert a line at the bottom of the screen. + */ + insertBottom(top: number, bottom: number): void; + /** + * Insert a line at the top of the screen. + */ + insertTop(top: number, bottom: number): void; + /** + * Delete a line at the bottom of the screen. + */ + deleteBottom(top: number, bottom: number): void; + /** + * Delete a line at the top of the screen. + */ + deleteTop(top: number, bottom: number): void; + /** + * Enable mouse events for the screen and optionally an element (automatically called when a form of + * on('mouse') is bound). + */ + enableMouse(el: BlessedElement): void; + enableMouse(): void; + /** + * Enable keypress events for the screen and optionally an element (automatically called when a form of + * on('keypress') is bound). + */ + enableKeys(el: BlessedElement): void; + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(el: BlessedElement): void; + enableInput(): void; + /** + * Attempt to copy text to clipboard using iTerm2's proprietary sequence. Returns true if successful. + */ + copyToClipboard(text: string): void; + /** + * Attempt to change cursor shape. Will not work in all terminals (see artificial cursors for a solution + * to this). Returns true if successful. + */ + cursorShape(shape: boolean, blink: boolean): any; + /** + * Attempt to change cursor color. Returns true if successful. + */ + cursorColor(color: string): void; + /** + * Attempt to reset cursor. Returns true if successful. + */ + cursorReset(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + /** + * Destroy the screen object and remove it from the global list. Also remove all global events relevant + * to the screen object. If all screen objects are destroyed, the node process is essentially reset + * to its initial state. + */ + destroy(): void; + /** + * Reset the terminal to term. Reloads terminfo. + */ + setTerminal(term: string): void; + } + + export interface Padding { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + + export class PositionCoords { + xi: number; + xl: number; + yi: number; + yl: number; + } + + export interface Position { + left: number | string; + right: number | string; + top: number | string; + bottom: number | string; + } + + export interface Border { + /** + * Type of border (line or bg). bg by default. + */ + type?: "line" | "bg"; + /** + * Character to use if bg type, default is space. + */ + ch?: string; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg?: number; + fg?: number; + /** + * Border attributes. + */ + bold?: string; + underline?: string; + } + + export interface ElementOptions extends INodeOptions { + tags?: boolean; + + fg?: string; + bg?: string; + bold?: string; + underline?: string; + + style?: any; + /** + * Border object, see below. + */ + border?: Border | "line" | "bg"; + /** + * Element's text content. + */ + content?: string; + /** + * Element is clickable. + */ + clickable?: boolean; + /** + * Element is focusable and can receive key input. + */ + input?: boolean; + keyable?: boolean; + /** + * Element is focused. + */ + focused?: BlessedElement; + /** + * Whether the element is hidden. + */ + hidden?: boolean; + /** + * A simple text label for the element. + */ + label?: string; + /** + * A floating text label for the element which appears on mouseover. + */ + hoverText?: string; + /** + * Text alignment: left, center, or right. + */ + align?: "left" | "center" | "right"; + /** + * Vertical text alignment: top, middle, or bottom. + */ + valign?: "top" | "middle" | "bottom"; + /** + * Shrink/flex/grow to content and child elements. Width/height during render. + */ + shrink?: boolean; + /** + * Amount of padding on the inside of the element. Can be a number or an object containing + * the properties: left, right, top, and bottom. + */ + padding?: number | Padding; + + top?: Types.TTopLeft; + left?: Types.TTopLeft; + right?: Types.TPosition; + bottom?: Types.TPosition; + + /** + * Width/height of the element, can be a number, percentage (0-100%), or keyword (half or shrink). + * Percentages can also have offsets (50%+1, 50%-1). + */ + width?: number | string; + /** + * Offsets of the element relative to its parent. Can be a number, percentage (0-100%), or + * keyword (center). right and bottom do not accept keywords. Percentages can also have + * offsets (50%+1, 50%-1). + */ + height?: number | string; + /** + * Can contain the above options. + */ + position?: Position; + /** + * Whether the element is scrollable or not. + */ + scrollable?: boolean; + /** + * Background character (default is whitespace ). + */ + ch?: string; + /** + * Allow the element to be dragged with the mouse. + */ + draggable?: boolean; + /** + * Draw a translucent offset shadow behind the element. + */ + shadow?: boolean; + } + + export interface Coords { + xl: number; + xi: number; + yl: number; + yi: number; + base: number; + _contentEnd: {x: number; y: number;}; + notop: Types.TTopLeft; + noleft: Types.TTopLeft; + noright: Types.TPosition; + nobot: Types.TPosition; + } + + export interface LabelOptions { + text: string; + side: Types.TAlign; + } + + // TODO: scrollable - Note: If the scrollable option is enabled, Element inherits all methods from ScrollableBox. + export abstract class BlessedElement extends NodeWithEvents implements IHasOptions { + constructor(opts: ElementOptions); + + // ** properties ** // + + /** + * Original options object. + */ + options: ElementOptions; + /** + * Name of the element. Useful for form submission. + */ + name: string; + /** + * Border object. + */ + border: Border; + + style: any; + position: Position; + content: string; + hidden: boolean; + visible: boolean; + detached: boolean; + /** + * Border foreground and background, must be numbers (-1 for default). + */ + bg: number; + fg: number; + /** + * Border attributes. + */ + bold: string; + underline: string; + /** + * Calculated width. + */ + width: number | string; + /** + * Calculated height. + */ + height: number | string; + /** + * Calculated relative top offset.*/ + top: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + left: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + right: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + bottom: Types.TPosition; + /** + * Calculated absolute top offset. + */ + atop: Types.TTopLeft; + /** + * Calculated absolute left offset. + */ + aleft: Types.TTopLeft; + /** + * Calculated absolute right offset. + */ + aright: Types.TPosition; + /** + * Calculated absolute bottom offset. + */ + abottom: Types.TPosition; + + /** + * Whether the element is draggable. Set to true to allow dragging. + */ + draggable: boolean; + + itop: Types.TTopLeft; + ileft: Types.TTopLeft; + iheight: Types.TPosition; + iwidth: Types.TPosition; + + /** + * Calculated relative top offset. + */ + rtop: Types.TTopLeft; + /** + * Calculated relative left offset. + */ + rleft: Types.TTopLeft; + /** + * Calculated relative right offset. + */ + rright: Types.TPosition; + /** + * Calculated relative bottom offset. + */ + rbottom: Types.TPosition; + + lpos: PositionCoords; + + // ** methods ** // + + /** + * Write content and children to the screen buffer. + */ + render(): Coords; + /** + * Hide element.*/ + hide(): void; + /** + * Show element. + */ + show(): void; + /** + * Toggle hidden/shown. + */ + toggle(): void; + /** + * Focus element. + */ + focus(): void; + /** + * Same asel.on('screen', ...) except this will automatically keep track of which listeners + * are bound to the screen object. For use with removeScreenEvent(), free(), and destroy(). + */ + onScreenEvent(type: string, handler: Function): void; + /** + * Same asel.removeListener('screen', ...) except this will automatically keep track of which + * listeners are bound to the screen object. For use with onScreenEvent(), free(), and destroy(). + */ + removeScreenEvent(type: string, handler: Function): void; + /** + * Free up the element. Automatically unbind all events that may have been bound to the screen + * object. This prevents memory leaks. For use with onScreenEvent(), removeScreenEvent(), + * and destroy(). + */ + free(): void; + /** + * Same as the detach() method, except this will automatically call free() and unbind any screen + * events to prevent memory leaks. for use with onScreenEvent(), removeScreenEvent(), and free(). + */ + destroy(): void; + /** + * Set the z-index of the element (changes rendering order). + */ + setIndex(z: number): void; + /** + * Put the element in front of its siblings.*/ + setFront(): void; + /** + * Put the element in back of its siblings. + */ + setBack(): void; + /** + * text/options - Set the label text for the top-left corner. Example options: {text:'foo',side:'left'} + */ + setLabel(arg: string | LabelOptions): void; + /** + * Remove the label completely. + */ + removeLabel(): any; + /** + * text/options - Set a hover text box to follow the cursor. Similar to the "title" DOM attribute + * in the browser. Example options: {text:'foo'} + */ + setHover(arg: string | LabelOptions): void; + /** + * Remove the hover label completely. + */ + removeHover(): void; + /** + * Enable mouse events for the element (automatically called when a form of on('mouse') is bound). + */ + enableMouse(): void; + /** + * Enable keypress events for the element (automatically called when a form of on('keypress') is bound). + */ + enableKeys(): void; + /** + * Enable key and mouse events. Calls bot enableMouse and enableKeys. + */ + enableInput(): void; + /** + * Enable dragging of the element. + */ + enableDrag(): void; + /** + * Disable dragging of the element. + */ + disableDrag(): void; + /** + * Take an SGR screenshot of the screen within the region. Returns a string containing only + * characters and SGR codes. Can be displayed by simply echoing it in a terminal. + */ + screenshot(xi: number, xl: number, yi: number, yl: number): string; + screenshot(): void; + + /* + Content Methods + + Methods for dealing with text content, line by line. Useful for writing a text editor, + irc client, etc. + + Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use deleteTop() + on a box with a wrapped line at the top, it may remove 3-4 "real" lines (rows) depending + on how long the original line was. + + The lines parameter can be a string or an array of strings. The line parameter must + be a string. + */ + + /** + * Set the content. Note: When text is input, it will be stripped of all non-SGR + * escape codes, tabs will be replaced with 8 spaces, and tags will be replaced + * with SGR codes (if enabled). + */ + setContent(text: string): void; + /** + * Return content, slightly different from el.content. Assume the above formatting. + */ + getContent(): string; + /** + * Similar to setContent, but ignore tags and remove escape codes. + */ + setText(text: string): void; + /** + * Similar to getContent, but return content with tags and escape codes removed. + */ + getText(): string; + /** + * Insert a line into the box's content. + */ + insertLine(i: number, lines: string | string[]): void; + /** + * Delete a line from the box's content. + */ + deleteLine(i: number): void; + /** + * Get a line from the box's content. + */ + getLine(i: number): string; + /** + * Get a line from the box's content from the visible top. + */ + getBaseLine(i: number): string; + /** + * Set a line in the box's content. + */ + setLine(i: number, line: string | string[]): void; + /** + * Set a line in the box's content from the visible top. + */ + setBaseLine(i: number, line: string | string[]): void; + /** + * Clear a line from the box's content. + */ + clearLine(i: number): void; + /** + * Clear a line from the box's content from the visible top. + */ + clearBaseLine(i: number): void; + /** + * Insert a line at the top of the box. + */ + insertTop(lines: string | string[]): void; + /** + * Insert a line at the bottom of the box. + */ + insertBottom(lines: string | string[]): void; + /** + * Delete a line at the top of the box. + */ + deleteTop(): void; + /** + * Delete a line at the bottom of the box. + */ + deleteBottom(): void; + /** + * Unshift a line onto the top of the content. + */ + unshiftLine(lines: string | string[]): void; + /** + * Shift a line off the top of the content. + */ + shiftLine(i: number): void; + /** + * Push a line onto the bottom of the content. + */ + pushLine(lines: string | string[]): void; + /** + * Pop a line off the bottom of the content. + */ + popLine(i: number): string; + /** + * An array containing the content lines. + */ + getLines(): string[]; + /** + * An array containing the lines as they are displayed on the screen. + */ + getScreenLines(): string[]; + /** + * Get a string's displayed width, taking into account double-width, surrogate pairs, + * combining characters, tags, and SGR escape codes. + */ + strWidth(text: string): string; + + // ** events ** // + } + + export interface ScrollableBoxOptions extends ElementOptions { + /** + * A limit to the childBase. Default is Infinity. + */ + baseLimit?: number; + /** + * A option which causes the ignoring of childOffset. This in turn causes the + * childBase to change every time the element is scrolled. + */ + alwaysScroll?: boolean; + /** + * Object enabling a scrollbar. + * Style of the scrollbar track if present (takes regular style options). + */ + scrollbar?: { style?: any; track?: any; ch?: string; } + } + + export interface ScrollableTextOptions extends ScrollableBoxOptions { + /** + * Whether to enable automatic mouse support for this element. + * Use pre-defined mouse events (right-click for editor). + */ + mouse?: boolean | (() => void); + /** + * Use pre-defined keys (i or enter for insert, e for editor, C-e for editor while inserting). + */ + keys?: string | string[] | boolean; + /** + * Use vi keys with the keys option. + */ + vi?: boolean; + } + + export interface BoxOptions extends ScrollableTextOptions { + bindings?: any; + } + + /** + * DEPRECATED - Use Box with the scrollable option instead. A box with scrollable content. + */ + export class ScrollableBoxElement extends BlessedElement { + /** + * The offset of the top of the scroll content. + */ + childBase: number; + /** + * The offset of the chosen item/line. + */ + childOffset: number; + + /** + * Scroll the content by a relative offset. + */ + scroll(offset: number, always?: boolean): void; + /** + * Scroll the content to an absolute index. + */ + scrollTo(index: number): void; + /** + * Same as scrollTo. + */ + setScroll(index: number): void; + /** + * Set the current scroll index in percentage (0-100). + */ + setScrollPerc(perc: number): void; + /** + * Get the current scroll index in lines. + */ + getScroll(): void; + /** + * Get the actual height of the scrolling area. + */ + getScrollHeight(): void; + /** + * Get the current scroll index in percentage. + */ + getScrollPerc(): void; + /** + * Reset the scroll index to its initial state. + */ + resetScroll(): void; + + on(event: string, listener: Function): this; + /** + * Received when the element is scrolled. + */ + on(event: "scroll", callback: () => void): this; + } + + /** + * DEPRECATED - Use Box with the scrollable and alwaysScroll options instead. + * A scrollable text box which can display and scroll text, as well as handle + * pre-existing newlines and escape codes. + */ + export class ScrollableTextElement extends ScrollableBoxElement { + } + + /** + * A box element which draws a simple box containing content or other elements. + */ + export class BoxElement extends ScrollableTextElement implements IHasOptions { + constructor(opts: BoxOptions); + + /** + * Original options object. + */ + options: BoxOptions; + } + + export interface TextOptions extends ElementOptions { + /** + * Fill the entire line with chosen bg until parent bg ends, even if there + * is not enough text to fill the entire width. + */ + fill?: boolean; + /** + * Text alignment: left, center, or right. + */ + align?: Types.TAlign; + } + + /** + * An element similar to Box, but geared towards rendering simple text elements. + */ + export class TextElement extends BlessedElement implements IHasOptions { + constructor(opts: TextOptions); + + /** + * Original options object. + */ + options: TextOptions; + } + + /** + * A simple line which can be line or bg styled. + */ + export interface LineOptions extends BoxOptions { + /** + * Can be vertical or horizontal. + */ + orientation?: "vertical" | "horizontal"; + /** + * Treated the same as a border object. (attributes can be contained in style). + */ + type?: string; + bg?: string; + fg?: string; + ch?: string; + } + + /** + * A simple line which can be line or bg styled. + */ + export class LineElement extends BoxElement implements IHasOptions { + constructor(opts: LineOptions); + + /** + * Original options object. + */ + options: LineOptions; + } + + export interface BigTextOptions extends BoxOptions { + /** + * bdf->json font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + font?: string; + /** + * bdf->json bold font file to use (see ttystudio for instructions on compiling BDFs to JSON). + */ + fontBold?: string; + /** + * foreground character. (default: ' ') + */ + fch?: string; + } + + /** + * A box which can render content drawn as 8x14 cell characters using the terminus font. + */ + export class BigTextElement extends BoxElement implements IHasOptions { + constructor(opts: BigTextOptions); + + /** + * Original options object. + */ + options: BigTextOptions; + } + + export interface ListElementStyle { + selected?: any; + item?: any; + } + + export interface ListOptions extends BoxOptions { + /** + * Style for a selected item. Style for an unselected item. + */ + style?: TStyle; + /** + * An array of strings which become the list's items. + */ + items?: string[]; + /** + * A function that is called when vi mode is enabled and the key / is pressed. This function accepts a + * callback function which should be called with the search string. The search string is then used to + * jump to an item that is found in items. + */ + search?: () => void; + /** + * Whether the list is interactive and can have items selected (Default: true). + */ + interactive?: boolean; + /** + * Whether to automatically override tags and invert fg of item when selected (Default: true). + */ + invertSelected?: boolean; + } + + export class ListElement extends BoxElement implements IHasOptions> { + constructor(opts: ListOptions); + + /** + * Original options object. + */ + options: ListOptions; + + /** + * Add an item based on a string. + */ + add(text: string): void; + /** + * Add an item based on a string. + */ + addItem(text: string): void; + /** + * Removes an item from the list. Child can be an element, index, or string. + */ + removeItem(child: BlessedElement): BlessedElement; + /** + * Push an item onto the list. + * */ + pushItem(child: BlessedElement): number; + /** + * Pop an item off the list. + * */ + popItem(): BlessedElement; + /** + * Unshift an item onto the list. + */ + unshiftItem(child: BlessedElement): number; + /** + * Shift an item off the list. + * */ + shiftItem(): BlessedElement; + /** + * Inserts an item to the list. Child can be an element, index, or string. + */ + insertItem(i: number, child: BlessedElement): void; + /** + * Returns the item element. Child can be an element, index, or string. + */ + getItem(child: BlessedElement): BlessedElement; + /** + * Set item to content. + */ + setItem(child: BlessedElement, content: BlessedElement | string): void; + /** + * Remove and insert items to the list. + * */ + spliceItem(i: number, n: number, ...items: BlessedElement[]): void; + /** + * Clears all items from the list. + * */ + clearItems(): void; + /** + * Sets the list items to multiple strings. + */ + setItems(items: BlessedElement[]): void; + /** + * Returns the item index from the list. Child can be an element, index, or string. + */ + getItemIndex(child: BlessedElement): number; + /** + * Select an index of an item. + * */ + select(index: number): void; + /** + * Select item based on current offset. + * */ + move(offset: number): void; + /** + * Select item above selected. + * */ + up(amount: number): void; + /** + * Select item below selected. + */ + down(amount: number): void; + /** + * Show/focus list and pick an item. The callback is executed with the result. + */ + pick(callback: () => void): void; + /** + * Find an item based on its text content. + */ + fuzzyFind(arg: string | RegExp | (() => void)): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "select", callback: (item: BoxElement, index: number) => void): this; + /** + * List was canceled (when esc is pressed with the keys option). + */ + on(event: "cancel", callback: () => void): this; + /** + * Either a select or a cancel event was received. + */ + on(event: "action", callback: () => void): this; + + on(event: "create item", callback: () => void): this; + on(event: "add item", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "insert item", callback: () => void): this; + on(event: "set items", callback: () => void): this; + on(event: "select item", callback: (item: BlessedElement, index: number) => void): this; + } + + export interface FileManagerOptions extends ListOptions { + /** + * Current working directory. + */ + cwd?: string; + } + + export class FileManagerElement extends ListElement implements IHasOptions { + constructor(opts: FileManagerOptions); + + /** + * Original options object. + */ + options: FileManagerOptions; + /** + * Current working directory. + */ + cwd: string; + + /** + * Refresh the file list (perform a readdir on cwd and update the list items). + */ + refresh(cwd:string, callback: () => void): void; + refresh(callback: () => void): void; + refresh(): void; + /** + * Pick a single file and return the path in the callback. + */ + pick(cwd:string, callback: () => void): void; + pick(callback: () => void): void; + /** + * Reset back to original cwd. + */ + reset(cwd:string, callback: () => void): void; + reset(callback: () => void): void; + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Received when an item is selected. + */ + on(event: "cd", callback: (file: string, cwd: string) => void): this; + /** + * Received when an item is selected. + */ + on(event: "file", callback: (file: string) => void): this; + + on(event: "error", callback: (err: any, file: string) => void): this; + on(event: "refresh", callback: () => void): this; + } + + export interface StyleListTable extends ListElementStyle { + /** + * Header style. + */ + header?: any; + /** + * Cell style. + */ + cell?: any; + } + + export interface ListTableOptions extends ListOptions { + /** + * Array of array of strings representing rows. + */ + rows?: string[]; + data?: string[][]; + /** + * Spaces to attempt to pad on the sides of each cell. 2 by default: one space on each side + * (only useful if the width is shrunken). + */ + pad?: number; + /** + * Do not draw inner cells. + */ + noCellBorders?: boolean; + + style?: StyleListTable; + } + + export class ListTableElement extends ListElement implements IHasOptions { + constructor(opts: ListTableOptions); + + /** + * Original options object. + */ + options: ListTableOptions; + + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setRows(rows: string[][]): void; + /** + * Set rows in table. Array of arrays of strings. + * @example: + * + * table.setData([ + [ 'Animals', 'Foods' ], + [ 'Elephant', 'Apple' ], + [ 'Bird', 'Orange' ] + ]); + */ + setData(rows: string[][]): void; + } + + export interface ListbarOptions extends BoxOptions { + style?: ListElementStyle; + /** + * Set buttons using an object with keys as titles of buttons, containing of objects + * containing keys of keys and callback. + */ + commands: Types.ListbarCommand[]; + items: Types.ListbarCommand[]; + /** + * Automatically bind list buttons to keys 0-9. + */ + autoCommandKeys: boolean; + } + + export class ListbarElement extends BoxElement implements IHasOptions { + constructor(opts: ListbarOptions); + + /** + * Original options object. + */ + options: ListbarOptions; + + /** + * Set commands (see commands option above). + */ + setItems(commands: Types.ListbarCommand[]): void; + /** + * Append an item to the bar. + */ + add(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + addItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Append an item to the bar. + */ + appendItem(item: Types.ListbarCommand, callback: () => void): void; + /** + * Select an item on the bar. + */ + select(offset: number): void; + /** + * Remove item from the bar. + */ + removeItem(child: BlessedElement): void; + /** + * Move relatively across the bar. + */ + move(offset: number): void; + /** + * Move left relatively across the bar. + */ + moveLeft(offset: number): void; + /** + * Move right relatively across the bar. + */ + moveRight(offset: number): void; + /** + * Select button and execute its callback. + */ + selectTab(index: number): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "set items", callback: () => void): this; + on(event: "remove item", callback: () => void): this; + on(event: "select tab", callback: () => void): this; + } + + export interface FormOptions extends BoxOptions { + /** + * Allow default keys (tab, vi keys, enter). + */ + keys?: any; + /** + * Allow vi keys. + */ + vi?: boolean; + } + + export class FormElement extends BoxElement implements IHasOptions { + constructor(opts: FormOptions); + + /** + * Original options object. + */ + options: FormOptions; + /** + * Last submitted data. + */ + submission: TFormData; + + /** + * Focus next form element. + */ + focusNext(): void; + /** + * Focus previous form element. + */ + focusPrevious(): void; + /** + * Submit the form. + */ + submit(): void; + /** + * Discard the form. + */ + cancel(): void; + /** + * Clear the form. + */ + reset(): void; + + // ** events ** // + + on(event: string, listener: Function): this; + /** + * Form is submitted. Receives a data object. + */ + on(event: "submit", callback: (out: TFormData) => void): this; + /** + * Form is discarded. + */ + on(event: "cancel", callback: () => void): this; + /** + * Form is cleared. + */ + on(event: "reset", callback: () => void): this; + } + + export interface InputOptions extends BoxOptions { } + + export abstract class InputElement extends BoxElement { + constructor(opts: InputOptions); + } + + /** + * A box which allows multiline text input. + */ + export interface TextareaOptions extends InputOptions { + /** + * Call readInput() when the element is focused. Automatically unfocus. + */ + inputOnFocus?: boolean; + } + + export class TextareaElement extends InputElement implements IHasOptions { + constructor(opts: TextareaOptions); + + /** + * Original options object. + */ + options: TextareaOptions; + + /** + * The input text. read-only. + */ + value: string; + + /** + * Submit the textarea (emits submit). + */ + submit(): void; + /** + * Cancel the textarea (emits cancel). + */ + cancel(): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + readInput(callback?: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + input(callback: (err: any, value?: string) => void): void; + /** + * Grab key events and start reading text from the keyboard. Takes a callback which receives + * the final value. + */ + setInput(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + readEditor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + editor(callback: (err: any, value?: string) => void): void; + /** + * Open text editor in $EDITOR, read the output from the resulting file. Takes a callback which + * receives the final value. + */ + setEditor(callback: (err: any, value?: string) => void): void; + /** + * The same as this.value, for now. + */ + getValue(): string; + /** + * Clear input. + */ + clearValue(): void; + /** + * Set value. + */ + setValue(text: string): void; + + // ** events ** // + + on(event: string, listener: Function): this; + + on(event: "error", callback: (err: any) => void): this; + + /** + * Value is submitted (enter). + */ + on(event: "submit", callback: (value: any) => void): this; + /** + * Value is discared (escape). + */ + on(event: "cancel", callback: (value: any) => void): this; + /** + * Either submit or cancel. + */ + on(event: "action", callback: (value: any) => void): this; + } + + export interface TextboxOptions extends TextareaOptions { + /** + * Completely hide text. + */ + secret?: boolean; + /** + * Replace text with asterisks (*). + */ + censor?: boolean; + } + + export class TextboxElement extends TextareaElement implements IHasOptions { + constructor(opts: TextboxOptions); + + /** + * Original options object. + */ + options: TextboxOptions; + + /** + * Completely hide text. + */ + secret: boolean; + /** + * Replace text with asterisks (*). + */ + censor: boolean; + } + + export interface ButtonOptions extends BoxOptions { } + + export class ButtonElement extends InputElement implements IHasOptions { + constructor(opts: ButtonOptions); + + /** + * Original options object. + */ + options: ButtonOptions; + + /** + * Press button. Emits press. + */ + press(): void; + + on(event: string, listener: Function): this; + + on(event: "press", callback: () => void): this; + } + + export interface CheckboxOptions extends BoxOptions { + /** + * whether the element is checked or not. + * */ + checked?: boolean; + /** + * enable mouse support. + * */ + mouse?: boolean; + } + + /** + * A checkbox which can be used in a form element. + * */ + export class CheckboxElement extends InputElement implements IHasOptions { + constructor(options?: CheckboxOptions); + + /** + * Original options object. + */ + options: CheckboxOptions; + + /** + * the text next to the checkbox (do not use setcontent, use `check.text = ''`). + * */ + text: string; + /** + * whether the element is checked or not. + * */ + checked: boolean; + /** + * same as `checked`. + * */ + value: boolean; + + /** + * check the element. + * */ + check(): void; + /** + * uncheck the element. + * */ + uncheck(): void; + /** + * toggle checked state. + * */ + toggle(): void; + } + + export interface RadioSetOptions extends BoxOptions { } + + /** + * An element wrapping RadioButtons. RadioButtons within this element will be mutually exclusive + * with each other. + * */ + export abstract class RadioSetElement extends BoxElement { + constructor(opts: RadioSetOptions); + } + + export interface RadioButtonOptions extends BoxOptions { } + + /** + * A radio button which can be used in a form element. + */ + export abstract class RadioButtonElement extends CheckboxElement { + constructor(opts: RadioButtonOptions); + } + + export interface PromptOptions extends BoxOptions { } + + /** + * A prompt box containing a text input, okay, and cancel buttons (automatically hidden). + */ + export class PromptElement extends BoxElement implements IHasOptions { + constructor(opts: PromptOptions); + + options: PromptOptions; + + /** + * Show the prompt and wait for the result of the textbox. Set text and initial value. + */ + input(text: string, value: string, callback: (err: any, value: string) => void): void; + setInput(text: string, value: string, callback: (err: any, value: string) => void): void; + readInput(text: string, value: string, callback: (err: any, value: string) => void): void; + } + + export interface QuestionOptions extends BoxOptions { } + + /** + * A question box containing okay and cancel buttons (automatically hidden). + */ + export class QuestionElement extends BoxElement implements IHasOptions { + constructor(opts: QuestionOptions); + + options: QuestionOptions; + + /** + * Ask a question. callback will yield the result. + */ + ask(question: string, callback: (err: any, value: string) => void): void; + } + + export interface MessageOptions extends BoxOptions { } + + /** + * A box containing a message to be displayed (automatically hidden). + */ + export class MessageElement extends BoxElement implements IHasOptions { + constructor(opts: MessageOptions); + + options: MessageOptions; + + /** + * Display a message for a time (default is 3 seconds). Set time to 0 for a perpetual message that is dismissed on keypress. + */ + log(text: string, time: number, callback: (err: any) => void): void; + log(text: string, callback: (err: any) => void): void; + display(text: string, time: number, callback: (err: any) => void): void; + display(text: string, callback: (err: any) => void): void; + + /** + * Display an error in the same way. + */ + error(text: string, time: number, callback: () => void): void; + error(text: string, callback: () => void): void; + } + + export interface LoadingOptions extends BoxOptions { } + + /** + * A box with a spinning line to denote loading (automatically hidden). + */ + export class LoadingElement extends BoxElement implements IHasOptions { + constructor(opts: LoadingOptions); + + options: LoadingOptions; + + /** + * Display the loading box with a message. Will lock keys until stop is called. + */ + load(text: string): void; + /** + * Hide loading box. Unlock keys. + */ + stop(): void; + } + + export interface ProgressBarOptions extends BoxOptions { + /** + * can be `horizontal` or `vertical`. + * */ + orientation: string; + /** + * the character to fill the bar with (default is space). + * */ + pch: string; + /** + * the amount filled (0 - 100). + * */ + filled: number; + /** + * same as `filled`. + * */ + value: number; + /** + * enable key support. + * */ + keys: boolean; + /** + * enable mouse support. + * */ + mouse: boolean; + } + + /** + * A progress bar allowing various styles. This can also be used as a form input. + */ + export class ProgressBarElement extends InputElement implements IHasOptions { + constructor(options?: ProgressBarOptions); + + options: ProgressBarOptions; + + /** + * progress the bar by a fill amount. + * */ + progress(amount:number): void; + /** + * set progress to specific amount. + * */ + setProgress(amount:number): void; + /** + * reset the bar. + * */ + reset(): void; + + on(event: string, listener: Function): this; + /** + * Bar was reset. + */ + on(event: "reset", callback: () => void): this; + /** + * Bar has completely filled. + */ + on(event: "complete", callback: () => void): this; + } + + export interface LogOptions extends ScrollableTextOptions { + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback?: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput?: boolean; + } + + /** + * A log permanently scrolled to the bottom. + * */ + export class Log extends ScrollableTextElement implements IHasOptions { + constructor(options?: LogOptions); + + options: LogOptions; + + /** + * amount of scrollback allowed. default: Infinity. + * */ + scrollback: number; + /** + * scroll to bottom on input even if the user has scrolled up. default: false. + * */ + scrollOnInput: boolean; + + /** + * add a log line. + * */ + log(text:string): void; + /** + * add a log line. + * */ + add(text:string): void; + } + + export interface TableOptions extends BoxOptions { + /** + * array of array of strings representing rows (same as `data`). + * */ + rows?: string[][]; + /** + * array of array of strings representing rows (same as `rows`). + * */ + data?: string[][]; + /** + * spaces to attempt to pad on the sides of each cell. `2` by default: one space on each side (only useful if the width is shrunken). + * */ + pad?: number; + /** + * do not draw inner cells. + * */ + noCellBorders?: boolean; + /** + * fill cell borders with the adjacent background color. + * */ + fillCellBorders?: boolean; + } + + /** + * A stylized table of text elements. + * */ + export class TableElement extends BoxElement implements IHasOptions { + constructor(opts: TableOptions); + + options: TableOptions; + + /** + * set rows in table. array of arrays of strings. + * */ + setData(rows: string[][]): void; + /** + * set rows in table. array of arrays of strings. + * */ + setRows(rows: string[][]): void; + } + + export interface TerminalOptions extends BoxOptions { + /** + * handler for input data. + * */ + handler?: (userInput:Buffer) => void; + /** + * name of shell. $SHELL by default. + * */ + shell?:string; + /** + * args for shell. + * */ + args?:any; + /** + * can be line, underline, and block. + * */ + cursor?: 'line'|'underline'|'block'; + + terminal?: string; + + /** + * Object for process env. + */ + env?: any; + } + + export class TerminalElement extends BoxElement implements IHasOptions { + constructor(opts: TerminalOptions); + + options: TerminalOptions; + + /** + * reference to the headless term.js terminal. + * */ + term: any; + /** + * reference to the pty.js pseudo terminal. + * */ + pty: any; + + /** + * write data to the terminal. + * */ + write(data:string): void; + + /** + * nearly identical to `element.screenshot`, however, the specified region includes the terminal's _entire_ scrollback, rather than just what is visible on the screen. + * */ + screenshot(xi?:number, xl?:number, yi?:number, yl?:number): string; + } + + export interface ImageOptions extends BoxOptions { + /** + * path to image. + * */ + file: string; + /** + * path to w3mimgdisplay. if a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + * */ + type: "ansi" | "overlay" | "w3m"; + } + + /** + * Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires w3m to be installed. X11 required: works in xterm, urxvt, and possibly other terminals. + * */ + export class ImageElement extends BoxElement implements IHasOptions { + constructor(options?: ImageOptions); + + options: ImageOptions; + } + + export interface ANSIImageOptions extends BoxOptions { + /** + * URL or path to PNG/GIF file. Can also be a buffer. + * */ + file: string; + /** + * Scale cellmap down (0-1.0) from its original pixel width/height (Default: 1.0). + * */ + scale: number; + + /** + * This differs from other element's width or height in that only one of them is needed: blessed will maintain the aspect ratio of the image as it scales down to the proper number of cells. NOTE: PNG/GIF's are always automatically shrunken to size (based on scale) if a width or height is not given. + * */ + width: number | string; + height: number | string; + + /** + * Add various "density" ASCII characters over the rendering to give the image more detail, similar to libcaca/libcucul (the library mplayer uses to display videos in the terminal). + */ + ascii: string; + + /** + * Whether to animate if the image is an APNG/animating GIF. If false, only display the first frame or IDAT (Default: true). + */ + animate: boolean; + + /** + * Set the speed of animation. Slower: 0.0-1.0. Faster: 1-1000. It cannot go faster than 1 frame per millisecond, so 1000 is the fastest. (Default: 1.0) + */ + speed: number; + + /** + * mem or cpu. If optimizing for memory, animation frames will be rendered to bitmaps as the animation plays, using less memory. Optimizing for cpu will precompile all bitmaps beforehand, which may be faster, but might also OOM the process on large images. (Default: mem). + */ + optimization: "mem" | "cpu"; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class ANSIImageElement extends BoxElement implements IHasOptions { + constructor(options?:ANSIImageOptions); + + options: ANSIImageOptions; + + /** + * Image object from the png reader. + */ + img: Types.TImage; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * Play animation if it has been paused or stopped. + */ + play(): void; + /** + * Pause animation. + */ + pause(): void; + /** + * Stop animation. + */ + stop(): void; + } + + export interface OverlayImageOptions extends BoxOptions { + /** + * Path to image. + */ + file: string; + /** + * Render the file as ANSI art instead of using w3m to overlay Internally uses the ANSIImage element. See the ANSIImage element for more information/options. (Default: true). + */ + ansi: boolean; + /** + * Path to w3mimgdisplay. If a proper w3mimgdisplay path is not given, blessed will search the entire disk for the binary. + */ + w3m: string; + /** + * Whether to search /usr, /bin, and /lib for w3mimgdisplay (Default: true). + */ + search: string; + } + + /** + * Convert any .png file (or .gif, see below) to an ANSI image and display it as an element. + * */ + export class OverlayImageElement extends BoxElement implements IHasOptions { + constructor(options?: OverlayImageOptions); + + options: OverlayImageOptions; + + /** + * set the image in the box to a new path. + * */ + setImage(img: string, callback: () => void): void; + /** + * clear the current image. + * */ + clearImage(callback: () => void): void; + /** + * get the size of an image file in pixels. + * */ + imageSize(img:string, callback: () => void): void; + /** + * get the size of the terminal in pixels. + * */ + termSize(callback: () => void): void; + /** + * get the pixel to cell ratio for the terminal. + * */ + getPixelRatio(callback: () => void): void; + } + + export interface VideoOptions extends BoxOptions { + /** + * Video to play. + */ + file: string; + /** + * Start time in seconds. + */ + start: number; + } + + export class VideoElement extends BoxElement implements IHasOptions { + constructor(options?: VideoOptions); + + options: VideoOptions; + + /** + * The terminal element running mplayer or mpv. + */ + tty: any; + } + + export interface LayoutOptions extends ElementOptions { + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer?: () => void; + + /** + * Using the default renderer, it provides two layouts: inline, and grid. inline is the default and will render + * akin to inline-block. grid will create an automatic grid based on element dimensions. The grid cells' + * width and height are always determined by the largest children in the layout. + */ + layout: "inline" | "inline-block" | "grid"; + } + + export class LayoutElement extends BlessedElement implements IHasOptions { + constructor(options?: LayoutOptions); + + options: LayoutOptions; + + /** + * A callback which is called right before the children are iterated over to be rendered. Should return an + * iterator callback which is called on each child element: iterator(el, i). + */ + renderer(coords: PositionCoords): void; + /** + * Check to see if a previous child element has been rendered and is visible on screen. This is only useful + * for checking child elements that have already been attempted to be rendered! see the example below. + */ + isRendered(el: BlessedElement): boolean; + /** + * Get the last rendered and visible child element based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. + */ + getLast(i: number): Element; + /** + * Get the last rendered and visible child element coords based on an index. This is useful for basing the position + * of the current child element on the position of the last child element. See the example below. + */ + getLastCoords(i: number): PositionCoords; + } + + export class Program { + /** + Wrap the given text in terminal formatting codes corresponding to the given attribute + name. The `attr` string can be of the form `red fg` or `52 bg` where `52` is a 0-255 + integer color number. + */ + text (text:string, attr:string): string; + } } - export = Blessed; + export module widget { + export class Element extends Widgets.BlessedElement { } + export class Node extends Widgets.Node { } + export class Screen extends Widgets.Screen { } + + export class Box extends Widgets.BoxElement { } + export class ScrollableBox extends Widgets.ScrollableBoxElement { } + export class ScrollableText extends Widgets.ScrollableTextElement { } + export class Text extends Widgets.BoxElement { } + export class Line extends Widgets.LineElement { } + export class BigText extends Widgets.BigTextElement { } + export class List extends Widgets.ListElement { } + export class FileManager extends Widgets.FileManagerElement { } + export class ListTable extends Widgets.ListTableElement { } + export class ListBar extends Widgets.ListbarElement { } + export class Form extends Widgets.FormElement { } + export class Textarea extends Widgets.TextareaElement { } + export class Button extends Widgets.ButtonElement { } + export class Checkbox extends Widgets.CheckboxElement { } + export class RadioSet extends Widgets.RadioSetElement { } + export class RadioButton extends Widgets.RadioButtonElement { } + + export class Prompt extends Widgets.PromptElement { } + export class question extends Widgets.QuestionElement { } + export class Message extends Widgets.MessageElement { } + export class Loading extends Widgets.LoadingElement { } + + export class ProgressBar extends Widgets.ProgressBarElement { } + export class Terminal extends Widgets.TerminalElement { } + } + + export function screen(options?: Widgets.IScreenOptions): Widgets.Screen; + + export function box(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function text(options?: Widgets.TextOptions): Widgets.TextElement; + export function line(options?: Widgets.LineOptions): Widgets.LineElement; + export function scrollablebox(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function scrollabletext(options?: Widgets.BoxOptions): Widgets.BoxElement; + export function bigtext(options?: Widgets.BigTextOptions): Widgets.BigTextElement; + export function list(options?: Widgets.ListOptions): Widgets.ListElement; + export function filemanager(options?: Widgets.FileManagerOptions): Widgets.FileManagerElement; + export function listtable(options?: Widgets.ListTableOptions): Widgets.ListTableElement; + export function listbar(options?: Widgets.ListbarOptions): Widgets.ListbarElement; + export function form(options?: Widgets.FormOptions): Widgets.FormElement; + export function input(options?: Widgets.InputOptions): Widgets.InputElement; + export function textarea(options?: Widgets.TextareaOptions): Widgets.TextareaElement; + export function textbox(options?: Widgets.TextboxOptions): Widgets.TextboxElement; + export function button(options?: Widgets.ButtonOptions): Widgets.ButtonElement; + export function checkbox(options?: Widgets.CheckboxOptions): Widgets.CheckboxElement; + export function radioset(options?: Widgets.RadioSetOptions): Widgets.RadioSetElement; + export function radiobutton(options?: Widgets.RadioButtonOptions): Widgets.RadioButtonElement; + + export function table(options?: Widgets.TableOptions): Widgets.TableElement; + + export function prompt(options?: Widgets.PromptOptions): Widgets.PromptElement; + export function question(options?: Widgets.QuestionOptions): Widgets.QuestionElement; + export function message(options?: Widgets.MessageOptions): Widgets.MessageElement; + export function loading(options?: Widgets.LoadingOptions): Widgets.LoadingElement; + + export function progressbar(options?: Widgets.ProgressBarOptions): Widgets.ProgressBarElement; + export function terminal(options?: Widgets.TerminalOptions): Widgets.TerminalElement; + + export function layout(options?: Widgets.LayoutOptions): Widgets.LayoutElement; + + export function escape(item: any): any; + export const colors: { + match: (hexColor: string) => string + } } - - - diff --git a/bluebird/bluebird-tests.ts b/bluebird/bluebird-tests.ts index 59cef89b1a..d7995438c1 100644 --- a/bluebird/bluebird-tests.ts +++ b/bluebird/bluebird-tests.ts @@ -82,6 +82,7 @@ var voidProm: Promise; var fooProm: Promise; var barProm: Promise; +var barOrVoidProm: Promise; var fooOrBarProm: Promise; var bazProm: Promise; @@ -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; diff --git a/bluebird/bluebird.d.ts b/bluebird/bluebird.d.ts index 042347f096..35b506542a 100644 --- a/bluebird/bluebird.d.ts +++ b/bluebird/bluebird.d.ts @@ -47,8 +47,10 @@ class Bluebird implements Bluebird.Thenable, Bluebird.Inspection { /** * 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(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => U | Bluebird.Thenable): Bluebird; - then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject?: (error: any) => void | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U1 | Bluebird.Thenable, onReject: (error: any) => U2 | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U | Bluebird.Thenable, onReject: (error: any) => U | Bluebird.Thenable): Bluebird; + then(onFulfill: (value: R) => U | Bluebird.Thenable): Bluebird; + then(): Bluebird; /** * 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. diff --git a/bootbox/bootbox.d.ts b/bootbox/bootbox.d.ts index ce422de880..c94b60625f 100644 --- a/bootbox/bootbox.d.ts +++ b/bootbox/bootbox.d.ts @@ -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; diff --git a/bowser/bowser-tests.ts b/bowser/bowser-tests.ts index 2f7cb8904c..79a846f3fb 100644 --- a/bowser/bowser-tests.ts +++ b/bowser/bowser-tests.ts @@ -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() === {android: true, x: true}; +bowser.check({msie: "11"}, window.navigator.userAgent); +bowser.isUnsupportedBrowser({msie: "10"}, window.navigator.userAgent); \ No newline at end of file diff --git a/bowser/bowser.d.ts b/bowser/bowser.d.ts index 2bf1b3d510..4d1840ff6a 100644 --- a/bowser/bowser.d.ts +++ b/bowser/bowser.d.ts @@ -3,52 +3,104 @@ // Definitions by: Paulo Cesar // 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; } } diff --git a/braintree-web/braintree-web-tests.ts b/braintree-web/braintree-web-tests.ts new file mode 100644 index 0000000000..40b34df418 --- /dev/null +++ b/braintree-web/braintree-web-tests.ts @@ -0,0 +1,432 @@ +/// + +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 +}); \ No newline at end of file diff --git a/braintree-web/braintree-web.d.ts b/braintree-web/braintree-web.d.ts new file mode 100644 index 0000000000..2cf2d89467 --- /dev/null +++ b/braintree-web/braintree-web.d.ts @@ -0,0 +1,1738 @@ +// Type definitions for Braintree-web v3.0.2 +// Project: https://github.com/braintree/braintree-web +// Definitions by: Guy Shahine +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * @module braintree-web/american-express + * @description This module is for use with Amex Express Checkout. To accept American Express cards, use Hosted Fields. + */ +declare namespace BraintreeWeb { + export interface AmericanExpress { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link AmericanExpress} instance. + * @returns {void} + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead. + * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields. + */ + export class AmericanExpress { + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead. + * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields. + */ + constructor(options: any); + + /** + * Gets the rewards balance associated with a Braintree nonce. + * @public + * @param {object} options Request options + * @param {string} options.nonce An existing Braintree nonce. + * @param {callback} callback The second argument, data, is the returned server data. + * @returns {void} + * @example + * var americanExpress = require('braintree-web/american-express'); + * + * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) { + * var options = {nonce: existingBraintreeNonce}; + * americanExpressInstance.getRewardsBalance(options, function (getErr, payload) { + * if (getErr || payload.error) { + * // Handle error + * return; + * } + * + * console.log('Rewards amount: ' + payload.rewardsAmount); + * }); + * }); + */ + public getRewardsBalance(options: { nonce: string }, callback: callback): void; + + /** + * Gets the Express Checkout nonce profile given a nonce from American Express. + * @public + * @param {object} options Request options + * @param {string} options.nonce An existing nonce from American Express (note that this is not a nonce from Braintree). + * @param {callback} callback The second argument, data, is the returned server data. + * @returns {void} + * @example + * var americanExpress = require('braintree-web/american-express'); + * + * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) { + * var options = {nonce: existingAmericanExpressNonce}; + * americanExpressInstance.getExpressCheckoutProfile(options, function (getErr, payload) { + * if (getErr) { + * // Handle error + * return; + * } + * + * console.log('Number of cards: ' + payload.amexExpressCheckoutCards.length); + * }); + * }); + */ + public getExpressCheckoutProfile(options: { nonce: string }, callback: callback): void; + } +} + + +// more info https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest + +// billingContact +// Billing contact information for the user. +// countryCode +//Required.The merchant’s two- letter ISO 3166 country code. +// currencyCode +// Required.The three- letter ISO 4217 currency code for the payment. +// lineItems +//A set of line items that explain recurring payments and additional charges. +// merchantCapabilities +// Required.The payment capabilities supported by the merchant.The value must be one or more of supports3DS, supportsEMV, supportsCredit, or supportsDebit. +// requiredBillingContactFields +// The billing information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. +// requiredShippingContactFields +// The shipping information that is required from the user.The value must be one or more of postalAddress, phone, email, or name. +// shippingContact +// Shipping contact information for the user. +// shippingMethods +//A set of available shipping methods.Totals for all shipping methods must be non- negative to pass validation. +// shippingType +// How the items are to be shipped.This property is optional.If specified, it must be one or more of shipping, delivery, storePickup, or servicePickup.The default value is shipping. +// supportedNetworks +// Required.The payment networks supported by the merchant.The value must be one or more of amex, discover, interac, masterCard, privateLabel, or visa. +// total +// Required.The total amount for the payment.The total must be greater than zero and have a label to pass validation. +interface ApplePayPaymentRequest { + total: { + label: string; + amount: string; + }; + countryCode: string; + currencyCode: string; + supportedNetworks: string[]; + merchantCapabilities: string[]; + + billingContact?: any; + shippingContact?: any; + shippingMethods?: any; + shippingType?: any; + requiredBillingContactFields?: any; + requiredShippingContactFields?: any; +} + +declare enum ApplePayStatusCodes { + // The requested action succeeded. + STATUS_SUCCESS = 1, + // The requested action failed. + STATUS_FAILURE, + // The billing address is not valid. + STATUS_INVALID_BILLING_POSTAL_ADDRESS, + // The shipping address is not valid. + STATUS_INVALID_SHIPPING_POSTAL_ADDRESS, + // The shipping contact information is not valid. + STATUS_INVALID_SHIPPING_CONTACT, + // The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction. + STATUS_PIN_REQUIRED, + // The PIN information is not valid.Cards on the China Union Pay network may require a PIN. + STATUS_PIN_INCORRECT, + // The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN. + STATUS_PIN_LOCKOUT, +} + +interface ApplePayPayload { + merchantIdentifier: string; + domainName: string; + displayName: string; +} + +declare class ApplePaySession { + constructor(version: number, request: ApplePayPaymentRequest); + + canMakePayments(): boolean; + + canMakePaymentsWithActiveCard(merchantIdentifier: string): boolean; + + completeMerchantValidation(merchantSession: any): void; + + abort(): void; + + begin(): void; + + completePayment(status: ApplePayStatusCodes): void; + + completePaymentMethodSelection(newTotal: any, newLineItems: any): void; + + completeShippingContactSelection(status: ApplePayStatusCodes, newShippingMethods: any, newTotal: any, newLineItems: any): void; + + completeShippingMethodSelection(status: ApplePayStatusCodes, newTotal: any, newLineItems: any): void; + + supportsVersion(version: number): boolean; + + oncancel: (event: any) => void; + + onpaymentauthorized: (event: any) => void; + + onpaymentmethodselected: (event: any) => void; + + onshippingcontactselected: (event: any) => void; + + onshippingmethodselected: (event: any) => void; + + onvalidatemerchant: (event: any) => void; +} + +/** + * @module braintree-web/apple-pay + * @description Accept Apple Pay on the Web. *This component is currently in beta and is subject to change.* + */ +declare namespace BraintreeWeb { + export interface ApplePay { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link ApplePay} instance. + * @returns {void} + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead. + * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments. + */ + export class ApplePay { + /** + * @class + * @param {object} options Options + * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead. + * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments. + */ + constructor(options: any); + + /** + * Merges a payment request with Braintree defaults + * The following properties are assigned to `paymentRequest` if not already defined + * - countryCode + * - currencyCode + * - merchantCapabilities + * - supportedNetworks + * @public + * @param {external:ApplePayPaymentRequest} paymentRequest The payment request details to apply on top of those from Braintree. + * @returns {external:ApplePayPaymentRequest} The decorated `paymentRequest`. + * @example + * var applePay = require('braintree-web/apple-pay'); + * + * applePay.create({client: clientInstance}, function (createErr, applePayInstance) { + * // ... + * var paymentRequest = applePay.createPaymentRequest({ + * total: { + * label: 'My Company', + * amount: '19.99' + * }); + * + * console.log(paymentRequest); + * // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] } + * + */ + public createPaymentRequest(paymentRequest: ApplePayPaymentRequest): ApplePayPaymentRequest + + /** + * Validates the merchant website, as required by ApplePaySession before payment can be authorized. + * @public + * @param {object} options Options + * @param {string} options.validationURL The validationURL fram an ApplePayValidateMerchantEvent. + * @param {string} [options.displayName] + * - The canonical name for your store. + * - The system may display this name to the user. + * - Use a 128-character or less, UTF-8 string. + * - Do not localize the name. + * @param {string} [options.merchantIdentifier] + * Your Apple merchant identifier. This is the Apple Merchant ID created on the Apple Developer Portal. + * Defaults to the merchant identifier specified in the Braintree Control Panel. + * You can use this field to override the merchant identifier for this transaction. + * @param {callback} callback The second argument, data, is the Apple Pay merchant session object. + * Pass the merchant session to your Apple Pay session's completeMerchantValidation method. + * @returns {void} + * @example + * var applePay = require('braintree-web/apple-pay'); + * + * applePay.create({client: clientInstance}, function (createErr, applePayInstance) { + * var session = new ApplePaySession(1, { + * // This should be the payment request object that + * // contains the information needed to display the payment sheet. + * }); + * + * session.onvalidatemerchant = function (event) { + * applePay.performValidation({ + * validationURL: event.validationURL + * }, function(err, validationData) { + * if (err) { + * console.error(err); + * session.abort(); + * return; + * } + * session.completeMerchantValidation(validationData); + * }); + * }; + * }); + */ + public performValidation(options: { validationURL: string, displayName?: string, merchantIdentifier?: string }, callback: callback): void; + + /** + * Tokenizes an Apple Pay payment. + * @public + * @param {object} options Options + * @param {object} options.token The `payment.token` property of an {@link external:ApplePayPaymentAuthorizedEvent} + * @param {callback} callback The second argument, data, is the tokenized payload. + * @returns {void} + * @example + * var applePay = require('braintree-web/apple-pay'); + * + * applePay.create({client: clientInstance}, function (createErr, applePayInstance) { + * var session = new ApplePaySession(1, { }); + * + * session.onpaymentauthorized = function (event) { + * applePay.tokenize({ + * token: event.payment.token + * }, function (err, tokenizedPayload) { + * if (err) { + * session.completePayment(ApplePaySession.STATUS_FAILURE); + * return; + * } + * session.completePayment(ApplePaySession.STATUS_SUCCESS); + * + * // Send the tokenizedPayload to your server. + * }); + * }; + * }); + */ + public tokenize(options: { token: any }, callback: callback): void; + + } +} + +/** @module braintree-web/client */ +declare namespace BraintreeWeb { + /** + * This object is returned by {@link Client#getConfiguration|getConfiguration}. This information is used extensively by other Braintree modules to properly configure themselves. + * @typedef {object} Client~configuration + * @property {object} client The braintree-web/client parameters. + * @property {string} client.authorization A tokenizationKey or clientToken. + * @property {object} gatewayConfiguration Gateway-supplied configuration. + * @property {object} analyticsMetadata Analytics-specific data. + * @property {string} analyticsMetadata.sessionId Uniquely identifies a browsing session. + * @property {string} analyticsMetadata.sdkVersion The braintree.js version. + * @property {string} analyticsMetadata.merchantAppId Identifies the merchant's web app. + */ + interface ClientAnalyticsMetadata { + sessionId: string; + sdkVersion: string; + merchantAppId: string; + } + + interface Configuration { + client: Client; + gatewayConfiguration: any; + analyticsMetadata: ClientAnalyticsMetadata; + } + + interface CreditCardInfo { + number: string; + cvv: string; + expirationDate: string; + billingAddress: { + postalCode?: string; + } + } + + export interface Client { + authorization: string; + + /** + * @function + * @description This function is the entry point for the braintree.client module. It is used for creating {@link Client} instances that service communication to Braintree servers. + * @param {object} options Object containing all {@link Client} options: + * @param {string} options.authorization A tokenizationKey or clientToken. + * @param {callback} callback The second argument, data, is the {@link Client} instance. + * @returns {void} + * @example + * var createClient = require('braintree-web/client').create; + * + * createClient({ + * authorization: CLIENT_AUTHORIZATION + * }, function (createErr, clientInstance) { + * ... + * }); + * @static + */ + create: (options: { authorization: string }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {Client~configuration} configuration Options + * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead. + * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}. + */ + export class Client { + /** + * @class + * @param {Client~configuration} configuration Options + * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead. + * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}. + */ + constructor(configuration: Configuration); + + + /** + * Returns a copy of the configuration values. + * @public + * @returns {Client~configuration} configuration + */ + public getConfiguration(): Configuration; + + /** + * Used by other modules to formulate all network requests to the Braintree gateway. It is also capable of being used directly from your own form to tokenize credit card information. However, be sure to satisfy PCI compliance if you use direct card tokenization. + * @public + * @param {object} options Request options: + * @param {string} options.method HTTP method. i.e. "get" or "post" + * @param {string} options.endpoint Enpoint path. i.e. "payment_methods" + * @param {object} options.data Data to send with the request + * @param {string} [options.timeout=60000] Timeout limit + * @param {callback} callback The second argument, data, is the returned server data. + * @example + * Direct Credit Card Tokenization + * var createClient = require('braintree-web/client').create; + * + * createClient({ + * authorization: CLIENT_AUTHORIZATION + * }, function (createErr, clientInstance) { + * var form = document.getElementById('my-form-id'); + * var data = { + * creditCard: { + * number: form['cc-number'].value, + * cvv: form['cc-cvv'].value, + * expirationDate: form['cc-date'].value, + * billingAddress: { + * postalCode: form['cc-postal'].value + * } + * } + * }; + * + * // Warning: For a merchant to be eligible for the easiest level of PCI compliance (SAQ A), + * // payment fields cannot be hosted on your checkout page. + * // For an alternative to the following, use Hosted Fields. + * clientInstance.request({ + * endpoint: 'payment_methods/credit_cards', + * method: 'post', + * data: data + * }, function (requestErr, response) { + * if (requestErr) { throw new Error(requestErr); } + * + * console.log('Got nonce:', response.creditCards[0].nonce); + * }); + * }); + * @returns {void} + */ + public request(options: { method: string, endpoint: string, data: any, timeout?: number }, callback: callback): void; + + } +} + +/** @module braintree-web/data-collector */ +declare namespace BraintreeWeb { + export interface DataCollector { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {boolean} [options.kount] If true, Kount fraud data collection is enabled. + * @param {boolean} [options.paypal] If true, PayPal fraud data collection is enabled. + * @param {callback} callback The second argument, `data`, is the {@link DataCollector} instance. + * @returns {void} + */ + create: (options: { client: Client, kount: boolean, paypal: boolean }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @global + * @name DataCollector + * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead. + * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions. + */ + export class DataCollector { + /** + * @class + * @global + * @name DataCollector + * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead. + * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions. + */ + constructor(); + + /** + * @memberof DataCollector + * @name deviceData + * @type string + * @description JSON string to pass with server transactions. + * @instance + */ + deviceData: string; + + /** + * @memberof DataCollector + * @name teardown + * @function + * @description Cleanly remove all event handlers and DOM nodes that were added. + * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @instance + * @returns {void} + */ + teardown(callback?: callback): void; + + } +} + +/** @module braintree-web/hosted-fields */ +declare namespace BraintreeWeb { + /** + * Fields used in {@link module:braintree-web/hosted-fields~fieldOptions fields options} + * @typedef {object} field + * @property {string} selector A CSS selector to find the container where the hosted field will be inserted. + * @property {string} [placeholder] Will be used as the `placeholder` attribute of the input. If `placeholder` is not natively supported by the browser, it will be polyfilled. + * @property {boolean} [formatInput=true] - Enable or disable automatic formatting on this field. Note: Input formatting does not work properly on Android and iOS, so input formatting is automatically disabled on those browsers. + */ + interface HostedFieldsField { + selector: string; + placeholder?: string; + formatInput?: boolean; + } + + /** + * An object that has {@link module:braintree-web/hosted-fields~field field objects} for each field. Used in {@link module:braintree-web/hosted-fields~create create}. + * @typedef {object} fieldOptions + * @property {field} [number] A field for card number. + * @property {field} [expirationDate] A field for expiration date in `MM/YYYY` format. This should not be used with the `expirationMonth` and `expirationYear` properties. + * @property {field} [expirationMonth] A field for expiration month in `MM` format. This should be used with the `expirationYear` property. + * @property {field} [expirationYear] A field for expiration year in `YYYY` format. This should be used with the `expirationMonth` property. + * @property {field} [cvv] A field for 3 or 4 digit CVV or CID. + * @property {field} [postalCode] A field for postal or region code. + */ + interface HostedFieldFieldOptions { + number: HostedFieldsField; + expirationDate?: HostedFieldsField; + expirationMonth?: HostedFieldsField; + expirationYear?: HostedFieldsField; + cvv: HostedFieldsField; + postalCode?: HostedFieldsField; + } + + /** + * @typedef {object} HostedFields~hostedFieldsCard + * @description Information about the card type, sent in {@link HostedFields~stateObject|stateObjects}. + * @property {string} type The code-friendly representation of the card type. It will be one of the following strings: + * - `american-express` + * - `diners-club` + * - `discover` + * - `jcb` + * - `maestro` + * - `master-card` + * - `unionpay` + * - `visa` + * @property {string} niceType The pretty-printed card type. It will be one of the following strings: + * - `American Express` + * - `Diners Club` + * - `Discover` + * - `JCB` + * - `Maestro` + * - `MasterCard` + * - `UnionPay` + * - `Visa` + * @property {object} code + * This object contains data relevant to the security code requirements of the card brand. + * For example, on a Visa card there will be a CVV of 3 digits, whereas an + * American Express card requires a 4-digit CID. + * @property {string} code.name "CVV" "CID" "CVC" + * @property {number} code.size The expected length of the security code. Typically, this is 3 or 4. + */ + + interface HostedFieldsCardCode { + name: string; + size: number; + } + + interface HostedFieldsHostedFieldsCard { + type: string; + niceType: string; + code: HostedFieldsCardCode; + } + + /** + * @typedef {object} HostedFields~hostedFieldsFieldData + * @description Data about Hosted Fields fields, sent in {@link HostedFields~stateObject|stateObjects}. + * @property {HTMLElement} container Reference to the container DOM element on your page associated with the current event. + * @property {boolean} isFocused Whether or not the input is currently focused. + * @property {boolean} isEmpty Whether or not the user has entered a value in the input. + * @property {boolean} isPotentiallyValid + * A determination based on the future validity of the input value. + * This is helpful when a user is entering a card number and types "41". + * While that value is not valid for submission, it is still possible for + * it to become a fully qualified entry. However, if the user enters "4x" + * it is clear that the card number can never become valid and isPotentiallyValid will + * return false. + * @property {boolean} isValid Whether or not the value of the associated input is fully qualified for submission. + */ + interface HostedFieldsHostedFieldsFieldData { + container: HTMLElement; + isFocused: boolean; + isEmpty: boolean; + isPotentiallyValid: boolean; + isValid: boolean; + } + + /** + * @typedef {object} HostedFields~stateObject + * @description The event payload sent from {@link HostedFields#on|on} or {@link HostedFields#getState|getState}. + * @property {HostedFields~hostedFieldsCard[]} cards + * This will return an array of potential {@link HostedFields~hostedFieldsCard|cards}. If the card type has been determined, the array will contain only one card. + * Internally, Hosted Fields uses credit-card-type, + * an open-source card detection library. + * @property {string} emittedBy + * The name of the field associated with an event. This will not be included if returned by {@link HostedFields#getState|getState}. It will be one of the following strings:
+ * - `"number"` + * - `"cvv"` + * - `"expirationDate"` + * - `"expirationMonth"` + * - `"expirationYear"` + * - `"postalCode"` + * @property {object} fields + * @property {?HostedFields~hostedFieldsFieldData} fields.number {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the number field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.cvv {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the CVV field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.expirationDate {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration date field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.expirationMonth {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration month field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.expirationYear {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration year field, if it is present. + * @property {?HostedFields~hostedFieldsFieldData} fields.postalCode {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the postal code field, if it is present. + */ + interface HostedFieldsFieldDataFields { + number: HostedFieldsHostedFieldsFieldData; + cvv: HostedFieldsHostedFieldsFieldData; + expirationDate: HostedFieldsHostedFieldsFieldData; + expirationMonth: HostedFieldsHostedFieldsFieldData; + expirationYear: HostedFieldsHostedFieldsFieldData; + postalCode: HostedFieldsHostedFieldsFieldData; + } + + interface HostedFieldsStateObject { + cards: HostedFieldsHostedFieldsCard[]; + emittedBy: string; + fields: HostedFieldsFieldDataFields; + } + + /** + * @typedef {object} HostedFields~tokenizePayload + * @property {string} nonce The payment method nonce. + * @property {object} details Additional account details. + * @property {string} details.cardType Type of card, ex: Visa, MasterCard. + * @property {string} details.lastTwo Last two digits of card number. + * @property {string} description A human-readable description. + * @property {string} type The payment method type, always `CreditCard`. + */ + interface HostedFieldsAccountDetails { + cardType: string; + lastTwo: string; + } + + interface HostedFieldsTokenizePayload { + nonce: string; + details: HostedFieldsAccountDetails; + type: string; + description: string; + } + + export interface HostedFields { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {fieldOptions} options.fields A {@link module:braintree-web/hosted-fields~fieldOptions set of options for each field}. + * @param {styleOptions} options.styles {@link module:braintree-web/hosted-fields~styleOptions Styles} applied to each field. + * @param {callback} callback The second argument, `data`, is the {@link HostedFields} instance. + * @returns {void} + * @example + * 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' + * } + * } + * }, callback); + */ + create: (options: { client: Client, fields: HostedFieldFieldOptions, styles: any }, callback: callback) => void; + + + /** + * An object that represents CSS that will be applied in each hosted field. This object looks similar to CSS. Typically, these styles involve fonts (such as `font-family` or `color`). + * + * These are the CSS properties that Hosted Fields supports. Any other CSS should be specified on your page and outside of any Braintree configuration. Trying to set unsupported properties will fail and put a warning in the console. + * + * `color` `font-family` `font-size-adjust` `font-size` `font-stretch` `font-style` `font-variant-alternates` `font-variant-caps` `font-variant-east-asian` `font-variant-ligatures` `font-variant-numeric` `font-variant` `font-weight` `font` `line-height` `opacity` `outline` `text-shadow` `transition` `-moz-osx-font-smoothing` `-moz-tap-highlight-color` `-moz-transition` `-webkit-font-smoothing` `-webkit-tap-highlight-color` `-webkit-transition` + * @typedef {object} styleOptions + */ + styleOptions: any; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class HostedFields + * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options. + * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead. + * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes. + */ + export class HostedFields { + /** + * @class HostedFields + * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options. + * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead. + * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes. + */ + constructor(options: any); + + /** + * @name HostedFields#on + * @function + * @param {string} event The name of the event to which you are subscribing. + * @param {function} handler A callback to handle the event. + * @description Subscribes a handler function to a named event. `event` should be {@link HostedFields#event:blur|blur}, {@link HostedFields#event:focus|focus}, {@link HostedFields#event:empty|empty}, {@link HostedFields#event:notEmpty|notEmpty}, {@link HostedFields#event:cardTypeChange|cardTypeChange}, or {@link HostedFields#event:validityChange|validityChange}. Events will emit a {@link HostedFields~stateObject|stateObject}. + * @example + * Listening to a Hosted Field event, in this case 'focus' + * hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) { + * hostedFieldsInstance.on('focus', function (event) { + * console.log(event.emittedBy, 'has been focused'); + * }); + * }); + * @returns {void} + */ + on(event: string, handler: (() => any)): void; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/hosted-fields.create|create} + * @public + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if teardown completes successfully. + * @example + * hostedFieldsInstance.teardown(function (teardownErr) { + * if (teardownErr) { + * console.error('Could not tear down Hosted Fields!'); + * } else { + * console.info('Hosted Fields has been torn down!'); + * } + * }); + * @returns {void} + */ + public teardown(callback?: callback): void; + + /** + * Tokenizes fields and returns a nonce payload. + * @public + * @param {object} [options] All tokenization options for the Hosted Fields component. + * @param {boolean} [options.vault=false] When true, will vault the tokenized card. Cards will only be vaulted when using a client created with a client token that includes a customer ID. + * @param {callback} callback The second argument, data, is a {@link HostedFields~tokenizePayload|tokenizePayload} + * @example Tokenize a card + * hostedFieldsInstance.tokenize(function (tokenizeErr, payload) { + * if (tokenizeErr) { + * 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); + * } + * } else { + * console.log('Got nonce:', payload.nonce); + * } + * }); + * @example Tokenize and vault a card + * hostedFieldsInstance.tokenize({ + * vault: true + * }, function (tokenizeErr, payload) { + * if (tokenizeErr) { + * console.error(tokenizeErr); + * } else { + * console.log('Got nonce:', payload.nonce); + * } + * }); + * @returns {void} + */ + public tokenize(options?: { vault: boolean }, callback?: callback): void; + + /** + * Add a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout. + * @public + * @param {string} field The field you wish to add a class to. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {string} classname The class to be added. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully. + * + * @example + * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) { + * if (addClassErr) { + * console.error(addClassErr); + * } + * }); + * @returns {void} + */ + public addClass(field: string, classname: string, callback?: callback): void; + + /** + * Removes a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout. + * @public + * @param {string} field The field you wish to remove a class from. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {string} classname The class to be removed. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is removed successfully. + * + * @example + * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) { + * if (addClassErr) { + * console.error(addClassErr); + * return; + * } + * + * // some time later... + * hostedFieldsInstance.removeClass('number', 'custom-class'); + * }); + * @returns {void} + */ + public removeClass(field: string, classname: string, callback?: callback): void; + + /** + * Sets the placeholder of a {@link module:braintree-web/hosted-fields~field field}. + * @public + * @param {string} field The field whose placeholder you wish to change. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {string} placeholder Will be used as the `placeholder` attribute of the input. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the placeholder updated successfully. + * + * @example + * hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr) { + * if (placeholderErr) { + * console.error(placeholderErr); + * } + * }); + * + * @example Update CVV field on card type change + * hostedFieldsInstance.on('cardTypeChange', function (event) { + * // Update the placeholder value if there is only one possible card type + * if (event.cards.length === 1) { + * hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr) { + * if (placeholderErr) { + * // Handle errors, such as invalid field name + * console.error(placeholderErr); + * } + * }); + * } + * }); + * @returns {void} + */ + public setPlaceholder(field: string, placeholder: string, callback?: callback): void; + + /** + * Clear the value of a {@link module:braintree-web/hosted-fields~field field}. + * @public + * @param {string} field The field whose placeholder you wish to clear. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}. + * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the field cleared successfully. + * @returns {void} + * @example + * hostedFieldsInstance.clear('number', function (clearErr) { + * if (clearErr) { + * console.error(clearErr); + * } + * }); + * + * @example Clear several fields + * hostedFieldsInstance.clear('number'); + * hostedFieldsInstance.clear('cvv'); + * hostedFieldsInstance.clear('expirationDate'); + */ + public clear(field: string, callback?: callback): void; + + /** + * Returns an {@link HostedFields~stateObject|object} that includes the state of all fields and possible card types. + * @public + * @returns {object} {@link HostedFields~stateObject|stateObject} + * @example Check if all fields are valid + * var state = hostedFields.getState(); + * + * var formValid = Object.keys(state.fields).every(function (key) { + * return state.fields[key].isValid; + * }); + */ + public getState(): any; + } +} + +/** @module braintree-web/paypal */ +declare namespace BraintreeWeb { + /** + * @typedef {object} PayPal~tokenizeReturn + * @property {Function} close A handle to close the PayPal checkout flow. + */ + interface PayPalTokenizeReturn { + close: (() => any); + } + + /** + * @typedef {object} PayPal~tokenizePayload + * @property {string} nonce The payment method nonce. + * @property {string} type The payment method type, always `PayPalAccount`. + * @property {object} details Additional PayPal account details. + * @property {string} details.email User's email address. + * @property {string} details.payerId User's payer ID, the unique identifier for each PayPal account. + * @property {string} details.firstName User's given name. + * @property {string} details.lastName User's surname. + * @property {?string} details.countryCode User's 2 character country code. + * @property {?string} details.phone User's phone number (e.g. 555-867-5309). + * @property {?object} details.shippingAddress User's shipping address details, only available if shipping address is enabled. + * @property {string} details.shippingAddress.recipientName Recipient of postage. + * @property {string} details.shippingAddress.line1 Street number and name. + * @property {string} details.shippingAddress.line2 Extended address. + * @property {string} details.shippingAddress.city City or locality. + * @property {string} details.shippingAddress.state State or region. + * @property {string} details.shippingAddress.postalCode Postal code. + * @property {string} details.shippingAddress.countryCode 2 character country code (e.g. US). + * @property {?object} details.billingAddress User's billing address details. + * You will also need to enable the PayPal Billing Address Request feature in your PayPal account. + * To enable this feature, [contact PayPal](https://developers.braintreepayments.com/support/guides/paypal/setup-guide#contacting-paypal-support). + * @property {string} details.billingAddress.line1 Street number and name. + * @property {string} details.billingAddress.line2 Extended address. + * @property {string} details.billingAddress.city City or locality. + * @property {string} details.billingAddress.state State or region. + * @property {string} details.billingAddress.postalCode Postal code. + * @property {string} details.billingAddress.countryCode 2 character country code (e.g. US). + */ + interface PayPalShippingAddress { + recipientName: string; + line1: string; + line2: string; + city: string; + state: string; + postalCode: string; + countryCode: string; + } + + interface PayPalBillingAddress { + line1: string; + line2: string; + city: string; + state: string; + postalCode: string; + countryCode: string; + } + + interface PayPalAccountDetails { + email: string; + payerId: string; + firstName: string; + lastName: string; + countryCode: string; + phone: string; + shippingAddress: PayPalShippingAddress; + billingAddress: PayPalBillingAddress; + } + + interface PayPalTokenizePayload { + nonce: string; + type: string; + details: PayPalAccountDetails; + } + + export interface PayPal { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link PayPal} instance. + * @example + * 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); + * } + * } + * } + * @returns {void} + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create} + * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component. + */ + export class PayPal { + /** + * @class + * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create} + * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component. + */ + constructor(options: any); + + /** + * Launches the PayPal login flow and returns a nonce payload. Only one PayPal login flow should be active at a time. One way to achieve this is to disable your PayPal button while the flow is open. + * @public + * @param {object} options All tokenization options for the PayPal component. + * @param {string} options.flow Set to 'checkout' for one-time payment flow, or 'vault' for Vault flow. If 'vault' is used with a client token generated with a customer id, the PayPal account will be added to that customer as a saved payment method. + * @param {string} [options.intent=authorize] + * Checkout flows only. + * * `authorize` - Submits the transaction for authorization but not settlement. + * * `sale` - Payment will be immediately submitted for settlement upon creating a transaction. + * @param {boolean} [options.offerCredit=false] Offers the customer PayPal Credit if they qualify. Checkout flows only. + * @param {string} [options.useraction] + * Changes the call-to-action in the PayPal flow. By default the final button will show the localized + * word for "Continue" and implies that the final amount billed is not yet known. + * + * Setting this option to `commit` changes the button text to "Pay Now" and page text will convey to + * the user that billing will take place immediately. + * @param {string|number} [options.amount] The amount of the transaction. Required when using the Checkout flow. + * @param {string} [options.currency] The currency code of the amount, such as 'USD'. Required when using the Checkout flow. + * @param {string} [options.displayName] The merchant name displayed inside of the PayPal lightbox; defaults to the company name on your Braintree account + * @param {string} [options.locale=en_US] Use this option to change the language, links, and terminology used in the PayPal flow to suit the country and language of your customer. + * @param {boolean} [options.enableShippingAddress=false] Returns a shipping address object in {@link PayPal#tokenize}. + * @param {object} [options.shippingAddressOverride] Allows you to pass a shipping address you have already collected into the PayPal payment flow. + * @param {string} options.shippingAddressOverride.line1 Street address. + * @param {string} [options.shippingAddressOverride.line2] Street address (extended). + * @param {string} options.shippingAddressOverride.city City. + * @param {string} options.shippingAddressOverride.state State. + * @param {string} options.shippingAddressOverride.postalCode Postal code. + * @param {string} options.shippingAddressOverride.countryCode Country. + * @param {string} [options.shippingAddressOverride.phone] Phone number. + * @param {string} [options.shippingAddressOverride.recipientName] Recipient's name. + * @param {boolean} [options.shippingAddressEditable=true] Set to false to disable user editing of the shipping address. + * @param {string} [options.billingAgreementDescription] Use this option to set the description of the preapproved payment agreement visible to customers in their PayPal profile during Vault flows. Max 255 characters. + * @param {callback} callback The second argument, data, is a {@link PayPal~tokenizePayload|tokenizePayload}. + * @example + * 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, payload) { + * 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 + * } + * }); + * }); + * @returns {PayPal~tokenizeReturn} A handle to close the PayPal checkout frame. + */ + public tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/paypal.create|create}. + * @public + * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @returns {void} + */ + public teardown(callback?: () => void): void; + + } +} + +/** @module braintree-web/three-d-secure */ +declare namespace BraintreeWeb { + /** + * @typedef {object} ThreeDSecure~verifyPayload + * @property {string} nonce The new payment method nonce produced by the 3D Secure lookup. The original nonce passed into {@link ThreeDSecure#verifyCard|verifyCard} was consumed. This new nonce should be used to transact on your server. + * @property {object} details Additional account details. + * @property {string} details.cardType Type of card, ex: Visa, MasterCard. + * @property {string} details.lastTwo Last two digits of card number. + * @property {string} description A human-readable description. + * @property {boolean} liabilityShiftPossible Indicates whether the card was eligible for 3D Secure. + * @property {boolean} liabilityShifted Indicates whether the liability for fraud has been shifted away from the merchant. + */ + interface ThreeDSecureAccountDetails { + cardType: string; + lastTwo: string; + } + + interface ThreeDSecureVerifyPayload { + nonce: string; + details: ThreeDSecureAccountDetails; + description: string; + liabilityShiftPossible: boolean; + liabilityShifted: boolean; + } + + export interface ThreeDSecure { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link ThreeDSecure} instance. + * @returns {void} + * @example + * braintree.threeDSecure.create({ + * client: client + * }, callback); + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options + * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead. + * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow. + */ + export class ThreeDSecure { + /** + * @class + * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options + * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead. + * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow. + */ + constructor(options: any); + + + /** + * @callback ThreeDSecure~addFrameCallback + * @param {?BraintreeError} [err] `null` or `undefined` if there was no error. + * @param {HTMLIFrameElement} iframe An iframe element containing the bank's authentication page that you must put on your page. + * @description The callback used for options.addFrame in {@link ThreeDSecure#verifyCard|verifyCard}. + * @returns {void} + */ + addFrameCallback: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void; + + /** + * @callback ThreeDSecure~removeFrameCallback + * @description The callback used for options.removeFrame in {@link ThreeDSecure#verifyCard|verifyCard}. + * @returns {void} + */ + removeFrameCallback: () => void; + + /** + * Launch the 3D Secure login flow, returning a nonce payload. + * @public + * @param {object} options Options for card verification. + * @param {string} options.nonce A nonce referencing the card to be verified. For example, this can be a nonce that was returned by Hosted Fields. + * @param {number} options.amount The amount of the transaction in the current merchant account's currency. For example, if you are running a transaction of $123.45 US dollars, `amount` would be 123.45. + * @param {errback} options.addFrame This {@link ThreeDSecure~addFrameCallback|addFrameCallback} will be called when the bank frame needs to be added to your page. + * @param {callback} options.removeFrame This {@link ThreeDSecure~removeFrameCallback|removeFrameCallback} will be called when the bank frame needs to be removed from your page. + * @param {errback} callback The second argument, data, is a {@link ThreeDSecure~verifyPayload|verifyPayload} + * @returns {void} + * @example + * Verifying an existing nonce with 3DS + * var my3DSContainer; + * + * threeDSecure.verifyCard({ + * nonce: existingNonce, + * amount: 123.45, + * addFrame: function (err, iframe) { + * // Set up your UI and add the iframe. + * my3DSContainer = document.createElement('div'); + * my3DSContainer.appendChild(iframe); + * document.body.appendChild(my3DSContainer); + * }, + * removeFrame: function () { + * // Remove UI that you added in addFrame. + * document.body.removeChild(my3DSContainer); + * } + * }, function (err, payload) { + * 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 + * } + * }); + */ + public verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void; + + /** + * Cancel the 3DS flow and return the verification payload if available. + * @public + * @param {errback} callback The second argument is a {@link ThreeDSecure~verifyPayload|verifyPayload}. If there is no verifyPayload (the initial lookup did not complete), an error will be returned. + * @returns {void} + * @example + * threeDSecure.cancelVerifyCard(function (err, verifyPayload) { + * 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 + * }); + */ + public cancelVerifyCard(callback: callback): void; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/three-d-secure.create|create} + * @public + * @param {errback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @returns {void} + */ + public teardown(callback?: callback): void; + } +} + +/** + * @module braintree-web/unionpay + * @description This module allows you to accept UnionPay payments. *It is currently in beta and is subject to change.* + */ +declare namespace BraintreeWeb { + /** + * @typedef {object} UnionPay~tokenizePayload + * @property {string} nonce The payment method nonce. + * @property {string} type Always CreditCard. + * @property {object} details Additional account details: + * @property {string} details.cardType Type of card, ex: Visa, MasterCard. + * @property {string} details.lastTwo Last two digits of card number. + * @property {string} description A human-readable description. + */ + interface UnionPayAccountDetails { + cardType: string; + lastTwo: string; + description: string; + } + + interface UnionPayTokenizePayload { + nonce: string; + type: string; + details: UnionPayAccountDetails; + } + + /** + * @typedef {object} UnionPay~enrollPayload + * @property {string} enrollmentId UnionPay enrollment ID. This value should be passed to `tokenize`. + * @property {boolean} smsCodeRequired UnionPay `smsCodeRequired` flag. + *

true - the user will receive an SMS code that needs to be supplied for tokenization. + *

false - the card can be immediately tokenized. + */ + interface UnionPayEnrollPayload { + enrollmentId: string; + smsCodeRequired: boolean; + } + + /** + * @typedef {object} UnionPay~fetchCapabilitiesPayload + * @property {boolean} isUnionPay Determines if this card is a UnionPay card. + * @property {boolean} isDebit Determines if this card is a debit card. This property is only present if `isUnionPay` is `true`. + * @property {object} unionPay UnionPay specific properties. This property is only present if `isUnionPay` is `true`. + * @property {boolean} unionPay.supportsTwoStepAuthAndCapture Determines if the card allows for an authorization, but settling the transaction later. + * @property {boolean} unionPay.isSupported Determines if Braintree can process this UnionPay card. When false, Braintree cannot process this card and the user should use a different card. + */ + + interface UnionPayProperties { + supportsTwoStepAuthAndCapture: boolean; + isSupported: boolean; + } + + interface UnionPayFetchCapabilitiesPayload { + isUnionPay: boolean; + isDebit: boolean; + unionPay: UnionPayProperties; + } + + export interface UnionPay { + /** + * @static + * @function create + * @param {object} options Creation options: + * @param {Client} options.client A {@link Client} instance. + * @param {callback} callback The second argument, `data`, is the {@link UnionPay} instance. + * @returns {void} + * @example + * braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) { + * if (createErr) { + * console.error(createErr); + * return; + * } + * // ... + * }); + */ + create: (options: { client: Client }, callback: callback) => void; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; + } + + /** + * @class + * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}. + * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead. + * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card. + */ + export class UnionPay { + /** + * @class + * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}. + * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead. + * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card. + */ + constructor(options: any); + + /** + * Fetches the capabilities of a card, including whether or not the SMS enrollment process is required. + * @public + * @param {object} options UnionPay {@link UnionPay#fetchCapabilities fetchCapabilities} options + * @param {object} [options.card] The card from which to fetch capabilities. Note that this will only have one property, `number`. Required if you are not using the `hostedFields` option. + * @param {string} options.card.number Card number. + * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option. + * @param {callback} callback The second argument, data, is a {@link UnionPay#fetchCapabilitiesPayload fetchCapabilitiesPayload}. + * @example With raw card data + * unionpayInstance.fetchCapabilities({ + * card: { + * number: '4111111111111111' + * } + * }, function (fetchErr, cardCapabilities) { + * 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 + * } + * }); + * @example With Hosted Fields + * // Fetch capabilities on `blur` inside of the Hosted Fields `create` callback + * hostedFieldsInstance.on('blur', function (event) { + * // Only attempt to fetch capabilities when a valid card number has been entered + * if (event.emittedBy === 'number' && event.fields.number.isValid) { + * unionpayInstance.fetchCapabilities({ + * hostedFields: hostedFieldsInstance + * }, function (fetchErr, cardCapabilities) { + * 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 + * // Hide the containers with your `cvv` and `expirationDate` fields + * } else { + * // CVV and expiration date are required + * } + * } else { + * // Not a UnionPay card + * // When form is complete, tokenize using your Hosted Fields instance + * } + * + * // Show your own mobile country code and phone number inputs for enrollment + * }); + * }); + * }); + * @returns {void} + */ + public fetchCapabilities(options: { card: any, hostedFields: HostedFields }, callback: callback): void; + + /** + * Enrolls a UnionPay card. Use {@link UnionPay#fetchCapabilities|fetchCapabilities} to determine if the SMS enrollment process is required. + * @public + * @param {object} options UnionPay enrollment options: + * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option. + * @param {string} options.card.number The card number. + * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored. + * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option. + * @param {object} options.mobile The mobile information collected from the customer. + * @param {string} options.mobile.countryCode The country code of the customer's mobile phone number. + * @param {string} options.mobile.number The customer's mobile phone number. + * @param {callback} callback The second argument, data, is a {@link UnionPay~enrollPayload|enrollPayload}. + * @example With raw card data + * unionpayInstance.enroll({ + * card: { + * number: '4111111111111111', + * expirationMonth: '12', + * expirationYear: '2038' + * }, + * mobile: { + * countryCode: '62', + * number: '111111111111' + * } + * }, function (enrollErr, response) { + * 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 + * }); + * @example With Hosted Fields + * unionpayInstance.enroll({ + * hostedFields: hostedFields, + * mobile: { + * countryCode: '62', + * number: '111111111111' + * } + * }, function (enrollErr, response) { + * 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 + * } + * }); + * @returns {void} + */ + public enroll(options: { card: any, hostedFields: HostedFields, mobile: any }, callback: callback): void; + + /** + * Tokenizes a UnionPay card and returns a nonce payload. + * @public + * @param {object} options UnionPay tokenization options: + * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option. + * @param {string} options.card.number The card number. + * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored. + * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored. + * @param {string} [options.card.cvv] The card's security number. + * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option. + * @param {string} options.enrollmentId The enrollment ID from {@link UnionPay#enroll}. + * @param {string} [options.smsCode] The SMS code received from the user if {@link UnionPay#enroll} payload have `smsCodeRequired`. if `smsCodeRequired` is false, smsCode should not be passed. + * @param {callback} callback The second argument, data, is a {@link UnionPay~tokenizePayload|tokenizePayload}. + * @example With raw card data + * 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, response) { + * if (tokenizeErr) { + * console.error(tokenizeErr); + * return; + * } + * + * // Send response.nonce to your server + * }); + * @example With Hosted Fields + * unionpayInstance.tokenize({ + * hostedFields: hostedFieldsInstance, + * 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, response) { + * if (tokenizeErr) { + * console.error(tokenizeErr); + * return; + * } + * + * // Send response.nonce to your server + * }); + * @returns {void} + */ + public tokenize(options: { card: any, hostedFields: HostedFields, enrollmentId: string, smsCode: string }, callback: callback): void; + + /** + * Cleanly tear down anything set up by {@link module:braintree-web/unionpay.create|create}. This only needs to be called when using UnionPay with Hosted Fields. + * @public + * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully. + * @example + * unionpayInstance.teardown(function (teardownErr) { + * if (teardownErr) { + * console.error('Could not tear down UnionPay.'); + * } else { + * console.log('UnionPay has been torn down.'); + * } + * }); + * @returns {void} + */ + public teardown(callback?: callback): void; + + } +} + +declare namespace BraintreeError { + /** + * Enum for {@link BraintreeError} types. + * @name BraintreeError.types + * @enum + * @readonly + * @memberof BraintreeError + * @property {string} CUSTOMER An error caused by the customer. + * @property {string} MERCHANT An error that is actionable by the merchant. + * @property {string} NETWORK An error due to a network problem. + * @property {string} INTERNAL An error caused by Braintree code. + * @property {string} UNKNOWN An error where the origin is unknown. + */ + export enum Types { + CUSTOMER, + MERCHANT, + NETWORK, + INTERNAL, + UNKNOWN + } +} + +/** + * @class + * @global + * @param {object} options Construction options + * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK. + * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}. + */ +declare class BraintreeError { + /** + * @class + * @global + * @param {object} options Construction options + * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK. + * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}. + */ + constructor(options: any); + + /** + * @type {string} + * @description A code that corresponds to specific errors. + */ + code: string; + + /** + * @type {string} + * @description A short description of the error. + */ + message: string; + + /** + * @type {BraintreeError.types} + * @description The type of error. + */ + type: BraintreeError.Types; + + /** + * @type {object=} + * @description Additional information about the error, such as an underlying network error response. + */ + details: any; +} + +declare namespace BraintreeWeb { + /** + * @global + * @callback callback + * @param {?BraintreeError} [err] `null` or `undefined` if there was no error. + * @param {?any} [data] The successful result of the asynchronous function call (if data exists). + * @description The Node.js-style callback pattern used throughout the SDK. + * @returns {void} + */ + type callback = (err?: BraintreeError, data?: any) => void; +} + +/** + * @module braintree-web + * @description This is the top-level module exported by the Braintree JavaScript SDK. In a browser environment, this will be the global braintree object. In a CommonJS environment (like Browserify or Webpack), it will be the default export of the braintree-web package. In AMD environments (like RequireJS), it can be `require`d like other modules. + * @example + * CommonJS + * var braintree = require('braintree-web'); + * + * braintree.client.create(...); + * @example + * In the browser + * + * + * @example + * AMD + * // main.js + * require.config({ + * paths: { + * braintreeClient: 'https://js.braintreegateway.com/web/3.0.2/js/client.min' + * } + * }); + * + * require(['braintreeClient'], function (braintreeClient) { + * braintreeClient.create(...); + * }); + */ +interface BraintreeStatic { + /** @type {module:braintree-web/client} */ + client: BraintreeWeb.Client; + + /** @type {module:braintree-web/paypal} */ + paypal: BraintreeWeb.PayPal; + + /** @type {module:braintree-web/hosted-fields} */ + hostedFields: BraintreeWeb.HostedFields; + + /** @type {module:braintree-web/three-d-secure} */ + threeDSecure: BraintreeWeb.ThreeDSecure; + + /** @type {module:braintree-web/data-collector} */ + dataCollector: BraintreeWeb.DataCollector; + + /** @type {module:braintree-web/american-express} */ + americanExpress: BraintreeWeb.AmericanExpress; + + /** @type {module:braintree-web/unionpay} */ + unionpay: BraintreeWeb.UnionPay; + + /** @type {module:braintree-web/apple-pay} */ + applePay: BraintreeWeb.ApplePay; + + /** + * @description The current version of the SDK, i.e. `3.0.2`. + * @type {string} + */ + VERSION: string; +} + +declare var braintree: BraintreeStatic; \ No newline at end of file diff --git a/bunnymq/bunnymq-tests.ts b/bunnymq/bunnymq-tests.ts new file mode 100644 index 0000000000..208eb7e992 --- /dev/null +++ b/bunnymq/bunnymq-tests.ts @@ -0,0 +1,36 @@ +/// + +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() +}); \ No newline at end of file diff --git a/bunnymq/bunnymq.d.ts b/bunnymq/bunnymq.d.ts new file mode 100644 index 0000000000..1167db21ed --- /dev/null +++ b/bunnymq/bunnymq.d.ts @@ -0,0 +1,120 @@ +// Type definitions for node-bunnymq 2.2.1 +// Project: https://github.com/dial-once/node-bunnymq +// Definitions by: Cyril Schumacher +// 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; + } + + /** + * 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; +} diff --git a/busboy/busboy-tests.ts b/busboy/busboy-tests.ts new file mode 100644 index 0000000000..058b5c92d3 --- /dev/null +++ b/busboy/busboy-tests.ts @@ -0,0 +1,39 @@ +/// +/// + +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('\ +
\ +
\ +
\ + \ +
\ + '); + } +} diff --git a/busboy/busboy.d.ts b/busboy/busboy.d.ts new file mode 100644 index 0000000000..3b64f3d112 --- /dev/null +++ b/busboy/busboy.d.ts @@ -0,0 +1,60 @@ +// Type definitions for busboy v0.2.13 +// Project: https://www.npmjs.com/package/busboy +// Definitions by: Jacob Baskin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +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; +} diff --git a/cache-manager/cache-manager.d.ts b/cache-manager/cache-manager.d.ts index 9570857f01..de6cf867a7 100644 --- a/cache-manager/cache-manager.d.ts +++ b/cache-manager/cache-manager.d.ts @@ -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; } diff --git a/canvas-gauges/canvas-gauges-tests.ts b/canvas-gauges/canvas-gauges-tests.ts new file mode 100644 index 0000000000..d0f04e1082 --- /dev/null +++ b/canvas-gauges/canvas-gauges-tests.ts @@ -0,0 +1,20 @@ +/// + +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); diff --git a/canvas-gauges/canvas-gauges.d.ts b/canvas-gauges/canvas-gauges.d.ts new file mode 100644 index 0000000000..53858e566e --- /dev/null +++ b/canvas-gauges/canvas-gauges.d.ts @@ -0,0 +1,263 @@ +// Type definitions for canvas-gauges +// Project: https://github.com/Mikhus/canvas-gauges +// Definitions by: 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; + } + + 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 { + 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; +} diff --git a/chai-things/chai-things-tests.ts b/chai-things/chai-things-tests.ts index de6a4c3ffe..c49ac3b468 100644 --- a/chai-things/chai-things-tests.ts +++ b/chai-things/chai-things-tests.ts @@ -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() { diff --git a/chai-things/chai-things.d.ts b/chai-things/chai-things.d.ts index 2636c9dcea..18c138ff38 100644 --- a/chai-things/chai-things.d.ts +++ b/chai-things/chai-things.d.ts @@ -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; diff --git a/chance/chance.d.ts b/chance/chance.d.ts index 290cde8048..6390b57864 100644 --- a/chance/chance.d.ts +++ b/chance/chance.d.ts @@ -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(arr: T[]): T; + pickone(arr: T[]): T; + /** + * @deprecated Use pickset + */ pick(arr: T[], count: number): T[]; + pickset(arr: T[], count: number): T[]; set: Setter; shuffle(arr: T[]): T[]; diff --git a/chart.js/chart.js.d.ts b/chart.js/chart.js.d.ts index e05d930d4e..57389ee4ea 100644 --- a/chart.js/chart.js.d.ts +++ b/chart.js/chart.js.d.ts @@ -73,7 +73,7 @@ interface ChartOptions { onClick?: (any?: any) => any; title?: ChartTitleOptions; legend?: ChartLegendOptions; - tooltip?: ChartTooltipOptions; + tooltips?: ChartTooltipOptions; hover?: ChartHoverOptions; animation?: ChartAnimationOptions; elements?: ChartElementsOptions; diff --git a/colors/colors-tests.ts b/colors/colors-tests.ts index 15fd5ab4e5..ff838da995 100644 --- a/colors/colors-tests.ts +++ b/colors/colors-tests.ts @@ -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')); diff --git a/colors/colors.d.ts b/colors/colors.d.ts index 7a78240287..50e960c416 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -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; diff --git a/cordova/cordova-tests.ts b/cordova/cordova-tests.ts index 7e97305a25..6d98471b12 100644 --- a/cordova/cordova-tests.ts +++ b/cordova/cordova-tests.ts @@ -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)=> { diff --git a/cordova/plugins/Contacts.d.ts b/cordova/plugins/Contacts.d.ts index d940fccd77..90b21ae2bb 100644 --- a/cordova/plugins/Contacts.d.ts +++ b/cordova/plugins/Contacts.d.ts @@ -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 -}; \ No newline at end of file + desiredFields?: ContactFieldType[]): ContactFindOptions +}; diff --git a/cordova/plugins/FileSystem.d.ts b/cordova/plugins/FileSystem.d.ts index 66a6014dea..f9471eda72 100644 --- a/cordova/plugins/FileSystem.d.ts +++ b/cordova/plugins/FileSystem.d.ts @@ -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 +} diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts index c633dc4ef6..1ad88ff41a 100644 --- a/core-js/core-js.d.ts +++ b/core-js/core-js.d.ts @@ -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; } diff --git a/couchbase/couchbase.d.ts b/couchbase/couchbase.d.ts index 351c9a806d..2508f0e1d5 100644 --- a/couchbase/couchbase.d.ts +++ b/couchbase/couchbase.d.ts @@ -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. diff --git a/countdown/countdown-tests.ts b/countdown/countdown-tests.ts index c803f1acc2..3ad8890aab 100644 --- a/countdown/countdown-tests.ts +++ b/countdown/countdown-tests.ts @@ -1,15 +1,15 @@ /// -import { countdown, Timespan, CountdownStatic, Format } from 'countdown'; +import * as countdown from 'countdown'; -let ts: Timespan; +let ts: countdown.Timespan; let interval: number; -ts = countdown(new Date()); -ts = countdown(150); +ts = countdown(new Date()); +ts = countdown(150); interval = countdown(new Date(), - function (ts: Timespan) { + function (ts: countdown.Timespan) { document.getElementById('pageTimer').innerHTML = ts.toHTML('strong'); }, countdown.HOURS | countdown.MINUTES | countdown.SECONDS, diff --git a/countdown/countdown.d.ts b/countdown/countdown.d.ts index 5b40541dd0..bcb0d07976 100644 --- a/countdown/countdown.d.ts +++ b/countdown/countdown.d.ts @@ -3,11 +3,11 @@ // Definitions by: Gabriel Juchault // 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; plural?: string | Array; 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; } diff --git a/cucumber/cucumber-tests.ts b/cucumber/cucumber-tests.ts index d6ada278c2..aa17cd331e 100644 --- a/cucumber/cucumber-tests.ts +++ b/cucumber/cucumber-tests.ts @@ -1,30 +1,32 @@ /// +/// function StepSample() { type Callback = cucumber.CallbackStepDefinition; + type Table = cucumber.TableDefinition; var step = this; var hook = 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) + }); } diff --git a/cucumber/cucumber.d.ts b/cucumber/cucumber.d.ts index 6c4273e4e0..a415a478e2 100644 --- a/cucumber/cucumber.d.ts +++ b/cucumber/cucumber.d.ts @@ -7,11 +7,20 @@ declare namespace cucumber { export interface CallbackStepDefinition{ pending : () => PromiseLike; - (errror?:any):void; + (errror?:any, pending?: string):void; } + export interface TableDefinition{ + raw: () => Array; + rows: () => Array; + rowsHash: () => {}; + hashes: () => {}; + } + + type StepDefinitionParam = string | CallbackStepDefinition | TableDefinition; + interface StepDefinitionCode { - (...stepArgs: Array): PromiseLike | any | void; + (...stepArgs: Array): PromiseLike | any | void; } interface StepDefinitionOptions{ diff --git a/d3/d3.d.ts b/d3/d3.d.ts index 3ad327ffc3..d539b7439d 100644 --- a/d3/d3.d.ts +++ b/d3/d3.d.ts @@ -297,7 +297,7 @@ declare namespace d3 { * @param value the function to compute data for each node */ datum(value: (datum: Datum, index: number, outerIndex: number) => NewDatum): Update; - + /** * 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; call(func: (selection: Enter, ...args: any[]) => any, ...args: any[]): Enter; - + empty(): boolean; size(): number; } @@ -1078,7 +1078,7 @@ declare namespace d3 { * Return the min and max simultaneously. */ export function extent(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; + tick(): Force; + alpha(): number; alpha(value: number): Force; diff --git a/date-fns/date-fns-tests.ts b/date-fns/date-fns-tests.ts new file mode 100644 index 0000000000..4c1dfc2476 --- /dev/null +++ b/date-fns/date-fns-tests.ts @@ -0,0 +1,16 @@ +/// + +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({}); + +} \ No newline at end of file diff --git a/date-fns/date-fns.d.ts b/date-fns/date-fns.d.ts new file mode 100644 index 0000000000..d0582c2571 --- /dev/null +++ b/date-fns/date-fns.d.ts @@ -0,0 +1,1195 @@ +// Type definitions for date-fns +// Project: https://date-fns.org/ +// Definitions by: Matt Lewis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type DateOrStringOrNumber = Date | string | number; + +declare module 'date-fns' { + + function addDays(date: DateOrStringOrNumber, amount: number): Date; + namespace addDays {} + + function addHours(date: DateOrStringOrNumber, amount: number): Date; + namespace addHours {} + + function addISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addISOYears {} + + function addMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addMilliseconds {} + + function addMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace addMinutes {} + + function addMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace addMonths {} + + function addQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace addQuarters {} + + function addSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addSeconds {} + + function addWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace addWeeks {} + + function addYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addYears {} + + function closestIndexTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): number; + namespace closestIndexTo {} + + function closestTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): Date; + namespace closestTo {} + + function compareAsc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareAsc {} + + function compareDesc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareDesc {} + + function differenceInCalendarDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarDays {} + + function differenceInCalendarISOWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOWeeks {} + + function differenceInCalendarISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOYears {} + + function differenceInCalendarMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarMonths {} + + function differenceInCalendarQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarQuarters {} + + function differenceInCalendarWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): number; + namespace differenceInCalendarWeeks {} + + function differenceInCalendarYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarYears {} + + function differenceInDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInDays {} + + function differenceInHours(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInHours {} + + function differenceInISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInISOYears {} + + function differenceInMilliseconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMilliseconds {} + + function differenceInMinutes(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMinutes {} + + function differenceInMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMonths {} + + function differenceInQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInQuarters {} + + function differenceInSeconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInSeconds {} + + function differenceInWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInWeeks {} + + function differenceInYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInYears {} + + function distanceInWords(dateFrom: DateOrStringOrNumber, dateTo: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWords {} + + function distanceInWordsToNow(date: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWordsToNow {} + + function eachDay(startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): Date[]; + namespace eachDay {} + + function endOfDay(date: DateOrStringOrNumber): Date; + namespace endOfDay {} + + function endOfHour(date: DateOrStringOrNumber): Date; + namespace endOfHour {} + + function endOfISOWeek(date: DateOrStringOrNumber): Date; + namespace endOfISOWeek {} + + function endOfISOYear(date: DateOrStringOrNumber): Date; + namespace endOfISOYear {} + + function endOfMinute(date: DateOrStringOrNumber): Date; + namespace endOfMinute {} + + function endOfMonth(date: DateOrStringOrNumber): Date; + namespace endOfMonth {} + + function endOfQuarter(date: DateOrStringOrNumber): Date; + namespace endOfQuarter {} + + function endOfSecond(date: DateOrStringOrNumber): Date; + namespace endOfSecond {} + + function endOfToday(): Date; + namespace endOfToday {} + + function endOfTomorrow(): Date; + namespace endOfTomorrow {} + + function endOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace endOfWeek {} + + function endOfYear(date: DateOrStringOrNumber): Date; + namespace endOfYear {} + + function endOfYesterday(): Date; + namespace endOfYesterday {} + + function format(date: DateOrStringOrNumber, format?: string): string; + namespace format {} + + function getDate(date: DateOrStringOrNumber): number; + namespace getDate {} + + function getDay(date: DateOrStringOrNumber): number; + namespace getDay {} + + function getDayOfYear(date: DateOrStringOrNumber): number; + namespace getDayOfYear {} + + function getDaysInMonth(date: DateOrStringOrNumber): number; + namespace getDaysInMonth {} + + function getDaysInYear(date: DateOrStringOrNumber): number; + namespace getDaysInYear {} + + function getHours(date: DateOrStringOrNumber): number; + namespace getHours {} + + function getISOWeek(date: DateOrStringOrNumber): number; + namespace getISOWeek {} + + function getISOWeeksInYear(date: DateOrStringOrNumber): number; + namespace getISOWeeksInYear {} + + function getISOYear(date: DateOrStringOrNumber): number; + namespace getISOYear {} + + function getMilliseconds(date: DateOrStringOrNumber): number; + namespace getMilliseconds {} + + function getMinutes(date: DateOrStringOrNumber): number; + namespace getMinutes {} + + function getMonth(date: DateOrStringOrNumber): number; + namespace getMonth {} + + function getQuarter(date: DateOrStringOrNumber): number; + namespace getQuarter {} + + function getSeconds(date: DateOrStringOrNumber): number; + namespace getSeconds {} + + function getYear(date: DateOrStringOrNumber): number; + namespace getYear {} + + function isAfter(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isAfter {} + + function isBefore(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isBefore {} + + function isDate(argument: any): boolean; + namespace isDate {} + + function isEqual(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isEqual {} + + function isFirstDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isFirstDayOfMonth {} + + function isFriday(date: DateOrStringOrNumber): boolean; + namespace isFriday {} + + function isFuture(date: DateOrStringOrNumber): boolean; + namespace isFuture {} + + function isLastDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isLastDayOfMonth {} + + function isLeapYear(date: DateOrStringOrNumber): boolean; + namespace isLeapYear {} + + function isMonday(date: DateOrStringOrNumber): boolean; + namespace isMonday {} + + function isPast(date: DateOrStringOrNumber): boolean; + namespace isPast {} + + function isSameDay(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameDay {} + + function isSameHour(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameHour {} + + function isSameISOWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOWeek {} + + function isSameISOYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOYear {} + + function isSameMinute(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMinute {} + + function isSameMonth(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMonth {} + + function isSameQuarter(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameQuarter {} + + function isSameSecond(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameSecond {} + + function isSameWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isSameWeek {} + + function isSameYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameYear {} + + function isSaturday(date: DateOrStringOrNumber): boolean; + namespace isSaturday {} + + function isSunday(date: DateOrStringOrNumber): boolean; + namespace isSunday {} + + function isThisHour(date: DateOrStringOrNumber): boolean; + namespace isThisHour {} + + function isThisISOWeek(date: DateOrStringOrNumber): boolean; + namespace isThisISOWeek {} + + function isThisISOYear(date: DateOrStringOrNumber): boolean; + namespace isThisISOYear {} + + function isThisMinute(date: DateOrStringOrNumber): boolean; + namespace isThisMinute {} + + function isThisMonth(date: DateOrStringOrNumber): boolean; + namespace isThisMonth {} + + function isThisQuarter(date: DateOrStringOrNumber): boolean; + namespace isThisQuarter {} + + function isThisSecond(date: DateOrStringOrNumber): boolean; + namespace isThisSecond {} + + function isThisWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isThisWeek {} + + function isThisYear(date: DateOrStringOrNumber): boolean; + namespace isThisYear {} + + function isThursday(date: DateOrStringOrNumber): boolean; + namespace isThursday {} + + function isToday(date: DateOrStringOrNumber): boolean; + namespace isToday {} + + function isTomorrow(date: DateOrStringOrNumber): boolean; + namespace isTomorrow {} + + function isTuesday(date: DateOrStringOrNumber): boolean; + namespace isTuesday {} + + function isValid(date: DateOrStringOrNumber): boolean; + namespace isValid {} + + function isWednesday(date: DateOrStringOrNumber): boolean; + namespace isWednesday {} + + function isWeekend(date: DateOrStringOrNumber): boolean; + namespace isWeekend {} + + function isWithinRange(date: DateOrStringOrNumber, startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): boolean; + namespace isWithinRange {} + + function isYesterday(date: DateOrStringOrNumber): boolean; + namespace isYesterday {} + + function lastDayOfISOWeek(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOWeek {} + + function lastDayOfISOYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOYear {} + + function lastDayOfMonth(date: DateOrStringOrNumber): Date; + namespace lastDayOfMonth {} + + function lastDayOfQuarter(date: DateOrStringOrNumber): Date; + namespace lastDayOfQuarter {} + + function lastDayOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace lastDayOfWeek {} + + function lastDayOfYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfYear {} + + function max(...dates: DateOrStringOrNumber[]): Date; + namespace max {} + + function min(...dates: DateOrStringOrNumber[]): Date; + namespace min {} + + function parse(dateString: string): Date; + namespace parse {} + + function setDate(date: DateOrStringOrNumber, dayOfMonth: number): Date; + namespace setDate {} + + function setDay(date: DateOrStringOrNumber, day: number, options?: {weekStartsOn: number}): Date; + namespace setDay {} + + function setDayOfYear(date: DateOrStringOrNumber, dayOfYear: number): Date; + namespace setDayOfYear {} + + function setHours(date: DateOrStringOrNumber, hours: number): Date; + namespace setHours {} + + function setISOWeek(date: DateOrStringOrNumber, isoWeek: number): Date; + namespace setISOWeek {} + + function setISOYear(date: DateOrStringOrNumber, isoYear: number): Date; + namespace setISOYear {} + + function setMilliseconds(date: DateOrStringOrNumber, milliseconds: number): Date; + namespace setMilliseconds {} + + function setMinutes(date: DateOrStringOrNumber, minutes: number): Date; + namespace setMinutes {} + + function setMonth(date: DateOrStringOrNumber, month: number): Date; + namespace setMonth {} + + function setQuarter(date: DateOrStringOrNumber, quarter: number): Date; + namespace setQuarter {} + + function setSeconds(date: DateOrStringOrNumber, seconds: number): Date; + namespace setSeconds {} + + function setYear(date: DateOrStringOrNumber, year: number): Date; + namespace setYear {} + + function startOfDay(date: DateOrStringOrNumber): Date; + namespace startOfDay {} + + function startOfHour(date: DateOrStringOrNumber): Date; + namespace startOfHour {} + + function startOfISOWeek(date: DateOrStringOrNumber): Date; + namespace startOfISOWeek {} + + function startOfISOYear(date: DateOrStringOrNumber): Date; + namespace startOfISOYear {} + + function startOfMinute(date: DateOrStringOrNumber): Date; + namespace startOfMinute {} + + function startOfMonth(date: DateOrStringOrNumber): Date; + namespace startOfMonth {} + + function startOfQuarter(date: DateOrStringOrNumber): Date; + namespace startOfQuarter {} + + function startOfSecond(date: DateOrStringOrNumber): Date; + namespace startOfSecond {} + + function startOfToday(): Date; + namespace startOfToday {} + + function startOfTomorrow(): Date; + namespace startOfTomorrow {} + + function startOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace startOfWeek {} + + function startOfYear(date: DateOrStringOrNumber): Date; + namespace startOfYear {} + + function startOfYesterday(): Date; + namespace startOfYesterday {} + + function subDays(date: DateOrStringOrNumber, amount: number): Date; + namespace subDays {} + + function subHours(date: DateOrStringOrNumber, amount: number): Date; + namespace subHours {} + + function subISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subISOYears {} + + function subMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subMilliseconds {} + + function subMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace subMinutes {} + + function subMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace subMonths {} + + function subQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace subQuarters {} + + function subSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subSeconds {} + + function subWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace subWeeks {} + + function subYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subYears {} + +} + +declare module 'date-fns/add_days' { + import {addDays} from 'date-fns'; + export = addDays; +} + +declare module 'date-fns/add_hours' { + import {addHours} from 'date-fns'; + export = addHours; +} + +declare module 'date-fns/add_iso_years' { + import {addISOYears} from 'date-fns'; + export = addISOYears; +} + +declare module 'date-fns/add_milliseconds' { + import {addMilliseconds} from 'date-fns'; + export = addMilliseconds; +} + +declare module 'date-fns/add_minutes' { + import {addMinutes} from 'date-fns'; + export = addMinutes; +} + +declare module 'date-fns/add_months' { + import {addMonths} from 'date-fns'; + export = addMonths; +} + +declare module 'date-fns/add_quarters' { + import {addQuarters} from 'date-fns'; + export = addQuarters; +} + +declare module 'date-fns/add_seconds' { + import {addSeconds} from 'date-fns'; + export = addSeconds; +} + +declare module 'date-fns/add_weeks' { + import {addWeeks} from 'date-fns'; + export = addWeeks; +} + +declare module 'date-fns/add_years' { + import {addYears} from 'date-fns'; + export = addYears; +} + +declare module 'date-fns/closest_index_to' { + import {closestIndexTo} from 'date-fns'; + export = closestIndexTo; +} + +declare module 'date-fns/closest_to' { + import {closestTo} from 'date-fns'; + export = closestTo; +} + +declare module 'date-fns/compare_asc' { + import {compareAsc} from 'date-fns'; + export = compareAsc; +} + +declare module 'date-fns/compare_desc' { + import {compareDesc} from 'date-fns'; + export = compareDesc; +} + +declare module 'date-fns/difference_in_calendar_days' { + import {differenceInCalendarDays} from 'date-fns'; + export = differenceInCalendarDays; +} + +declare module 'date-fns/difference_in_calendar_iso_weeks' { + import {differenceInCalendarISOWeeks} from 'date-fns'; + export = differenceInCalendarISOWeeks; +} + +declare module 'date-fns/difference_in_calendar_iso_years' { + import {differenceInCalendarISOYears} from 'date-fns'; + export = differenceInCalendarISOYears; +} + +declare module 'date-fns/difference_in_calendar_months' { + import {differenceInCalendarMonths} from 'date-fns'; + export = differenceInCalendarMonths; +} + +declare module 'date-fns/difference_in_calendar_quarters' { + import {differenceInCalendarQuarters} from 'date-fns'; + export = differenceInCalendarQuarters; +} + +declare module 'date-fns/difference_in_calendar_weeks' { + import {differenceInCalendarWeeks} from 'date-fns'; + export = differenceInCalendarWeeks; +} + +declare module 'date-fns/difference_in_calendar_years' { + import {differenceInCalendarYears} from 'date-fns'; + export = differenceInCalendarYears; +} + +declare module 'date-fns/difference_in_days' { + import {differenceInDays} from 'date-fns'; + export = differenceInDays; +} + +declare module 'date-fns/difference_in_hours' { + import {differenceInHours} from 'date-fns'; + export = differenceInHours; +} + +declare module 'date-fns/difference_in_iso_years' { + import {differenceInISOYears} from 'date-fns'; + export = differenceInISOYears; +} + +declare module 'date-fns/difference_in_milliseconds' { + import {differenceInMilliseconds} from 'date-fns'; + export = differenceInMilliseconds; +} + +declare module 'date-fns/difference_in_minutes' { + import {differenceInMinutes} from 'date-fns'; + export = differenceInMinutes; +} + +declare module 'date-fns/difference_in_months' { + import {differenceInMonths} from 'date-fns'; + export = differenceInMonths; +} + +declare module 'date-fns/difference_in_quarters' { + import {differenceInQuarters} from 'date-fns'; + export = differenceInQuarters; +} + +declare module 'date-fns/difference_in_seconds' { + import {differenceInSeconds} from 'date-fns'; + export = differenceInSeconds; +} + +declare module 'date-fns/difference_in_weeks' { + import {differenceInWeeks} from 'date-fns'; + export = differenceInWeeks; +} + +declare module 'date-fns/difference_in_years' { + import {differenceInYears} from 'date-fns'; + export = differenceInYears; +} + +declare module 'date-fns/distance_in_words' { + import {distanceInWords} from 'date-fns'; + export = distanceInWords; +} + +declare module 'date-fns/distance_in_words_to_now' { + import {distanceInWordsToNow} from 'date-fns'; + export = distanceInWordsToNow; +} + +declare module 'date-fns/each_day' { + import {eachDay} from 'date-fns'; + export = eachDay; +} + +declare module 'date-fns/end_of_day' { + import {endOfDay} from 'date-fns'; + export = endOfDay; +} + +declare module 'date-fns/end_of_hour' { + import {endOfHour} from 'date-fns'; + export = endOfHour; +} + +declare module 'date-fns/end_of_iso_week' { + import {endOfISOWeek} from 'date-fns'; + export = endOfISOWeek; +} + +declare module 'date-fns/end_of_iso_year' { + import {endOfISOYear} from 'date-fns'; + export = endOfISOYear; +} + +declare module 'date-fns/end_of_minute' { + import {endOfMinute} from 'date-fns'; + export = endOfMinute; +} + +declare module 'date-fns/end_of_month' { + import {endOfMonth} from 'date-fns'; + export = endOfMonth; +} + +declare module 'date-fns/end_of_quarter' { + import {endOfQuarter} from 'date-fns'; + export = endOfQuarter; +} + +declare module 'date-fns/end_of_second' { + import {endOfSecond} from 'date-fns'; + export = endOfSecond; +} + +declare module 'date-fns/end_of_today' { + import {endOfToday} from 'date-fns'; + export = endOfToday; +} + +declare module 'date-fns/end_of_tomorrow' { + import {endOfTomorrow} from 'date-fns'; + export = endOfTomorrow; +} + +declare module 'date-fns/end_of_week' { + import {endOfWeek} from 'date-fns'; + export = endOfWeek; +} + +declare module 'date-fns/end_of_year' { + import {endOfYear} from 'date-fns'; + export = endOfYear; +} + +declare module 'date-fns/end_of_yesterday' { + import {endOfYesterday} from 'date-fns'; + export = endOfYesterday; +} + +declare module 'date-fns/format' { + import {format} from 'date-fns'; + export = format; +} + +declare module 'date-fns/get_date' { + import {getDate} from 'date-fns'; + export = getDate; +} + +declare module 'date-fns/get_day' { + import {getDay} from 'date-fns'; + export = getDay; +} + +declare module 'date-fns/get_day_of_year' { + import {getDayOfYear} from 'date-fns'; + export = getDayOfYear; +} + +declare module 'date-fns/get_days_in_month' { + import {getDaysInMonth} from 'date-fns'; + export = getDaysInMonth; +} + +declare module 'date-fns/get_days_in_year' { + import {getDaysInYear} from 'date-fns'; + export = getDaysInYear; +} + +declare module 'date-fns/get_hours' { + import {getHours} from 'date-fns'; + export = getHours; +} + +declare module 'date-fns/get_iso_week' { + import {getISOWeek} from 'date-fns'; + export = getISOWeek; +} + +declare module 'date-fns/get_iso_weeks_in_year' { + import {getISOWeeksInYear} from 'date-fns'; + export = getISOWeeksInYear; +} + +declare module 'date-fns/get_iso_year' { + import {getISOYear} from 'date-fns'; + export = getISOYear; +} + +declare module 'date-fns/get_milliseconds' { + import {getMilliseconds} from 'date-fns'; + export = getMilliseconds; +} + +declare module 'date-fns/get_minutes' { + import {getMinutes} from 'date-fns'; + export = getMinutes; +} + +declare module 'date-fns/get_month' { + import {getMonth} from 'date-fns'; + export = getMonth; +} + +declare module 'date-fns/get_quarter' { + import {getQuarter} from 'date-fns'; + export = getQuarter; +} + +declare module 'date-fns/get_seconds' { + import {getSeconds} from 'date-fns'; + export = getSeconds; +} + +declare module 'date-fns/get_year' { + import {getYear} from 'date-fns'; + export = getYear; +} + +declare module 'date-fns/is_after' { + import {isAfter} from 'date-fns'; + export = isAfter; +} + +declare module 'date-fns/is_before' { + import {isBefore} from 'date-fns'; + export = isBefore; +} + +declare module 'date-fns/is_date' { + import {isDate} from 'date-fns'; + export = isDate; +} + +declare module 'date-fns/is_equal' { + import {isEqual} from 'date-fns'; + export = isEqual; +} + +declare module 'date-fns/is_first_day_of_month' { + import {isFirstDayOfMonth} from 'date-fns'; + export = isFirstDayOfMonth; +} + +declare module 'date-fns/is_friday' { + import {isFriday} from 'date-fns'; + export = isFriday; +} + +declare module 'date-fns/is_future' { + import {isFuture} from 'date-fns'; + export = isFuture; +} + +declare module 'date-fns/is_last_day_of_month' { + import {isLastDayOfMonth} from 'date-fns'; + export = isLastDayOfMonth; +} + +declare module 'date-fns/is_leap_year' { + import {isLeapYear} from 'date-fns'; + export = isLeapYear; +} + +declare module 'date-fns/is_monday' { + import {isMonday} from 'date-fns'; + export = isMonday; +} + +declare module 'date-fns/is_past' { + import {isPast} from 'date-fns'; + export = isPast; +} + +declare module 'date-fns/is_same_day' { + import {isSameDay} from 'date-fns'; + export = isSameDay; +} + +declare module 'date-fns/is_same_hour' { + import {isSameHour} from 'date-fns'; + export = isSameHour; +} + +declare module 'date-fns/is_same_iso_week' { + import {isSameISOWeek} from 'date-fns'; + export = isSameISOWeek; +} + +declare module 'date-fns/is_same_iso_year' { + import {isSameISOYear} from 'date-fns'; + export = isSameISOYear; +} + +declare module 'date-fns/is_same_minute' { + import {isSameMinute} from 'date-fns'; + export = isSameMinute; +} + +declare module 'date-fns/is_same_month' { + import {isSameMonth} from 'date-fns'; + export = isSameMonth; +} + +declare module 'date-fns/is_same_quarter' { + import {isSameQuarter} from 'date-fns'; + export = isSameQuarter; +} + +declare module 'date-fns/is_same_second' { + import {isSameSecond} from 'date-fns'; + export = isSameSecond; +} + +declare module 'date-fns/is_same_week' { + import {isSameWeek} from 'date-fns'; + export = isSameWeek; +} + +declare module 'date-fns/is_same_year' { + import {isSameYear} from 'date-fns'; + export = isSameYear; +} + +declare module 'date-fns/is_saturday' { + import {isSaturday} from 'date-fns'; + export = isSaturday; +} + +declare module 'date-fns/is_sunday' { + import {isSunday} from 'date-fns'; + export = isSunday; +} + +declare module 'date-fns/is_this_hour' { + import {isThisHour} from 'date-fns'; + export = isThisHour; +} + +declare module 'date-fns/is_this_iso_week' { + import {isThisISOWeek} from 'date-fns'; + export = isThisISOWeek; +} + +declare module 'date-fns/is_this_iso_year' { + import {isThisISOYear} from 'date-fns'; + export = isThisISOYear; +} + +declare module 'date-fns/is_this_minute' { + import {isThisMinute} from 'date-fns'; + export = isThisMinute; +} + +declare module 'date-fns/is_this_month' { + import {isThisMonth} from 'date-fns'; + export = isThisMonth; +} + +declare module 'date-fns/is_this_quarter' { + import {isThisQuarter} from 'date-fns'; + export = isThisQuarter; +} + +declare module 'date-fns/is_this_second' { + import {isThisSecond} from 'date-fns'; + export = isThisSecond; +} + +declare module 'date-fns/is_this_week' { + import {isThisWeek} from 'date-fns'; + export = isThisWeek; +} + +declare module 'date-fns/is_this_year' { + import {isThisYear} from 'date-fns'; + export = isThisYear; +} + +declare module 'date-fns/is_thursday' { + import {isThursday} from 'date-fns'; + export = isThursday; +} + +declare module 'date-fns/is_today' { + import {isToday} from 'date-fns'; + export = isToday; +} + +declare module 'date-fns/is_tomorrow' { + import {isTomorrow} from 'date-fns'; + export = isTomorrow; +} + +declare module 'date-fns/is_tuesday' { + import {isTuesday} from 'date-fns'; + export = isTuesday; +} + +declare module 'date-fns/is_valid' { + import {isValid} from 'date-fns'; + export = isValid; +} + +declare module 'date-fns/is_wednesday' { + import {isWednesday} from 'date-fns'; + export = isWednesday; +} + +declare module 'date-fns/is_weekend' { + import {isWeekend} from 'date-fns'; + export = isWeekend; +} + +declare module 'date-fns/is_within_range' { + import {isWithinRange} from 'date-fns'; + export = isWithinRange; +} + +declare module 'date-fns/is_yesterday' { + import {isYesterday} from 'date-fns'; + export = isYesterday; +} + +declare module 'date-fns/last_day_of_iso_week' { + import {lastDayOfISOWeek} from 'date-fns'; + export = lastDayOfISOWeek; +} + +declare module 'date-fns/last_day_of_iso_year' { + import {lastDayOfISOYear} from 'date-fns'; + export = lastDayOfISOYear; +} + +declare module 'date-fns/last_day_of_month' { + import {lastDayOfMonth} from 'date-fns'; + export = lastDayOfMonth; +} + +declare module 'date-fns/last_day_of_quarter' { + import {lastDayOfQuarter} from 'date-fns'; + export = lastDayOfQuarter; +} + +declare module 'date-fns/last_day_of_week' { + import {lastDayOfWeek} from 'date-fns'; + export = lastDayOfWeek; +} + +declare module 'date-fns/last_day_of_year' { + import {lastDayOfYear} from 'date-fns'; + export = lastDayOfYear; +} + +declare module 'date-fns/max' { + import {max} from 'date-fns'; + export = max; +} + +declare module 'date-fns/min' { + import {min} from 'date-fns'; + export = min; +} + +declare module 'date-fns/parse' { + import {parse} from 'date-fns'; + export = parse; +} + +declare module 'date-fns/set_date' { + import {setDate} from 'date-fns'; + export = setDate; +} + +declare module 'date-fns/set_day' { + import {setDay} from 'date-fns'; + export = setDay; +} + +declare module 'date-fns/set_day_of_year' { + import {setDayOfYear} from 'date-fns'; + export = setDayOfYear; +} + +declare module 'date-fns/set_hours' { + import {setHours} from 'date-fns'; + export = setHours; +} + +declare module 'date-fns/set_iso_week' { + import {setISOWeek} from 'date-fns'; + export = setISOWeek; +} + +declare module 'date-fns/set_iso_year' { + import {setISOYear} from 'date-fns'; + export = setISOYear; +} + +declare module 'date-fns/set_milliseconds' { + import {setMilliseconds} from 'date-fns'; + export = setMilliseconds; +} + +declare module 'date-fns/set_minutes' { + import {setMinutes} from 'date-fns'; + export = setMinutes; +} + +declare module 'date-fns/set_month' { + import {setMonth} from 'date-fns'; + export = setMonth; +} + +declare module 'date-fns/set_quarter' { + import {setQuarter} from 'date-fns'; + export = setQuarter; +} + +declare module 'date-fns/set_seconds' { + import {setSeconds} from 'date-fns'; + export = setSeconds; +} + +declare module 'date-fns/set_year' { + import {setYear} from 'date-fns'; + export = setYear; +} + +declare module 'date-fns/start_of_day' { + import {startOfDay} from 'date-fns'; + export = startOfDay; +} + +declare module 'date-fns/start_of_hour' { + import {startOfHour} from 'date-fns'; + export = startOfHour; +} + +declare module 'date-fns/start_of_iso_week' { + import {startOfISOWeek} from 'date-fns'; + export = startOfISOWeek; +} + +declare module 'date-fns/start_of_iso_year' { + import {startOfISOYear} from 'date-fns'; + export = startOfISOYear; +} + +declare module 'date-fns/start_of_minute' { + import {startOfMinute} from 'date-fns'; + export = startOfMinute; +} + +declare module 'date-fns/start_of_month' { + import {startOfMonth} from 'date-fns'; + export = startOfMonth; +} + +declare module 'date-fns/start_of_quarter' { + import {startOfQuarter} from 'date-fns'; + export = startOfQuarter; +} + +declare module 'date-fns/start_of_second' { + import {startOfSecond} from 'date-fns'; + export = startOfSecond; +} + +declare module 'date-fns/start_of_today' { + import {startOfToday} from 'date-fns'; + export = startOfToday; +} + +declare module 'date-fns/start_of_tomorrow' { + import {startOfTomorrow} from 'date-fns'; + export = startOfTomorrow; +} + +declare module 'date-fns/start_of_week' { + import {startOfWeek} from 'date-fns'; + export = startOfWeek; +} + +declare module 'date-fns/start_of_year' { + import {startOfYear} from 'date-fns'; + export = startOfYear; +} + +declare module 'date-fns/start_of_yesterday' { + import {startOfYesterday} from 'date-fns'; + export = startOfYesterday; +} + +declare module 'date-fns/sub_days' { + import {subDays} from 'date-fns'; + export = subDays; +} + +declare module 'date-fns/sub_hours' { + import {subHours} from 'date-fns'; + export = subHours; +} + +declare module 'date-fns/sub_iso_years' { + import {subISOYears} from 'date-fns'; + export = subISOYears; +} + +declare module 'date-fns/sub_milliseconds' { + import {subMilliseconds} from 'date-fns'; + export = subMilliseconds; +} + +declare module 'date-fns/sub_minutes' { + import {subMinutes} from 'date-fns'; + export = subMinutes; +} + +declare module 'date-fns/sub_months' { + import {subMonths} from 'date-fns'; + export = subMonths; +} + +declare module 'date-fns/sub_quarters' { + import {subQuarters} from 'date-fns'; + export = subQuarters; +} + +declare module 'date-fns/sub_seconds' { + import {subSeconds} from 'date-fns'; + export = subSeconds; +} + +declare module 'date-fns/sub_weeks' { + import {subWeeks} from 'date-fns'; + export = subWeeks; +} + +declare module 'date-fns/sub_years' { + import {subYears} from 'date-fns'; + export = subYears; +} + diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts index f3534a197e..a86614cfe8 100644 --- a/daterangepicker/daterangepicker.d.ts +++ b/daterangepicker/daterangepicker.d.ts @@ -11,7 +11,7 @@ interface JQuery { daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; } -declare module daterangepicker { +declare namespace daterangepicker { interface DatepickerEventObject extends JQueryEventObject { date: Date; @@ -164,3 +164,7 @@ declare module daterangepicker { monthNames?: string[]; } } + +declare module "daterangepicker" { + export = daterangepicker; +} diff --git a/db-migrate-base/db-migrate-base-tests.ts b/db-migrate-base/db-migrate-base-tests.ts new file mode 100644 index 0000000000..55d471b98f --- /dev/null +++ b/db-migrate-base/db-migrate-base-tests.ts @@ -0,0 +1,322 @@ +// Test file for db-migrate-base Definition file +/// + +import * as DbMigrateBase from "db-migrate-base"; + +// Throw together a dummy driver +let db = {}; + +let callback = (err: any, response: any) => { + // Do nothing. +}; + +/// createTable(tableName, columnSpec, callback) +db.createTable('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}, callback); + +db.createTable('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}, callback); + +/// dropTable(tableName, [options,] callback) +db.dropTable('pets', callback); + +db.dropTable('pets', { ifExists: true }, callback); + +/// renameTable(tableName, newTableName, callback) +db.renameTable('pets', 'pets_OLD', callback); + +/// addColumn(tableName, columnName, columnSpec, callback) +db.addColumn('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}, callback); + +db.addColumn('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}, callback); + +/// renameColumn(tableName, oldColumnName, newColumnName, callback) +db.renameColumn('pets', 'id', 'pet_id', callback); + +/// changeColumn(tableName, columnName, columnSpec, callback) +db.changeColumn('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}, callback); + +/// addIndex(tableName, indexName, columns, [unique,] callback) +db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback); +db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback); + +/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback) +db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}, callback); + +/// removeForeignKey(tableName, keyName, options, callback) +db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback); +db.removeForeignKey('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}, callback); + +/// insert(tableName, [columnNameArray,] valueArray, callback) +db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback); +db.insert('module_user', ['Test', 'Testerson'], callback); + +/// removeIndex([tableName,] indexName, callback) +db.removeIndex('pets', 'pets_eye_color_idx', callback); +db.removeIndex('pets_eye_color_idx', callback); + +/// runSql(sql, [params,] callback) +db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +], callback); +db.runSql('DROP TABLE `pets`', callback); + +/// all(sql, [params,] callback) +db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback); +db.all('SELECT * FROM `module_user`', callback); + +/// ========= +/// Async +/// ========= + +let onResolve = (result: any) => {}; + +/// createTableAsync(tableName, columnSpec) +db.createTableAsync('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}).then(onResolve); + +db.createTableAsync('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}).then(onResolve); + +/// dropTableAsync(tableName, [options]) +db.dropTableAsync('pets').then(onResolve); +db.dropTableAsync('pets', { ifExists: true }).then(onResolve); + +/// renameTableAsync(tableName, newTableName) +db.renameTableAsync('pets', 'pets_OLD').then(onResolve); + +/// addColumnAsync(tableName, columnName, columnSpec) +db.addColumnAsync('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}).then(onResolve); + +db.addColumnAsync('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}).then(onResolve); + +/// renameColumnAsync(tableName, oldColumnName, newColumnName) +db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve); + +/// changeColumnAsync(tableName, columnName, columnSpec) +db.changeColumnAsync('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}).then(onResolve); + +/// addIndexAsync(tableName, indexName, columns, [unique]) +db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve); +db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve); + +/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules) +db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}).then(onResolve); + +/// removeForeignKeyAsync(tableName, keyName, options) +db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve); +db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}).then(onResolve); + +/// insertAsync(tableName, [columnNameArray,] valueArray) +db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve); +db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve); + +/// removeIndexAsync([tableName,] indexName) +db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve); +db.removeIndexAsync('pets_eye_color_idx').then(onResolve); + +/// runSqlAsync(sql, [params]) +db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +]).then(onResolve); +db.runSqlAsync('DROP TABLE `pets`').then(onResolve); + +/// allAsync(sql, [params]) +db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); +db.allAsync('SELECT * FROM `module_user`').then(onResolve); \ No newline at end of file diff --git a/db-migrate-base/db-migrate-base.d.ts b/db-migrate-base/db-migrate-base.d.ts new file mode 100644 index 0000000000..d24388fdaf --- /dev/null +++ b/db-migrate-base/db-migrate-base.d.ts @@ -0,0 +1,152 @@ +// Type definitions for db-migrate-base +// Project: https://github.com/db-migrate/db-migrate-base +// Definitions by: nickiannone +// Definitions: https://github.com/nickiannone/DefinitelyTyped + +/// +/// + +declare module "db-migrate-base" { + + import * as Promise from "bluebird"; + + export interface CallbackFunction { (err: any, response: any): void; } + + export interface InternalModule { + log: any; + type: any; + } + + export interface InternalOptions { + mod: InternalModule; + } + + export interface ColumnSpec { + length?: number; + type: string; + unsigned?: boolean; + primaryKey?: boolean; + autoIncrement?: boolean; + notNull?: boolean; + unique?: boolean; + defaultValue?: any; + foreignKey?: ForeignKeySpec; + } + + export interface ForeignKeySpec { + name: string; + table: string; + rules?: ForeignKeyRules; + mapping: string | any; + } + + export interface ForeignKeyRules { + onDelete: string; + onUpdate: string; + } + + export interface RemoveForeignKeyOptions { + dropIndex?: boolean; + } + + export interface ColumnDef { + foreignKey?: any; // TODO Figure this out! + constraints: string; + } + + export interface CreateTableOptions { + columns?: Array; + ifNotExists?: boolean; + } + + export interface DropTableOptions { + ifExists?: boolean; + } + + export class Base { + constructor(intern: InternalOptions); + + close(callback?: CallbackFunction): void; + mapDataType(str: string): string; + truncate(tableName: string, callback: CallbackFunction): void; + checkDBMS(dbms: any, callback: CallbackFunction): void; + createDatabase(...options: any[]): void; + switchDatabase(...options: any[]): void; + dropDatabase(...options: any[]): void; + recurseCallbackArray(foreignKeys: Array, callback: CallbackFunction): void; + bindForeignKey(tableName: string, columnName: string, fkOptions: ForeignKeySpec): (callback: CallbackFunction) => void; + createColumnDef(name: string, spec: ColumnSpec, options?: any): ColumnDef; // TODO Figure out a type for `options`! + //createColumnConstraint(spec: ColumnSpec, options?: any, ...implementationDefinedOptions: any[]): string; + createMigrationsTable(callback: CallbackFunction): void; + createSeedsTable(callback: CallbackFunction): void; + createTable(tableName: string, options: any | CreateTableOptions, callback: CallbackFunction): void; + dropTable(tableName: string, optionsOrCb?: DropTableOptions | CallbackFunction, callback?: CallbackFunction): void; + renameTable(tableName: string, newTableName: string, callback: CallbackFunction): void; + addColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void; + removeColumn(tableName: string, columnName: string, callback: CallbackFunction): void; + renameColumn(tableName: string, oldColumnName: string, newColumnName: string, callback: CallbackFunction): void; + changeColumn(tableName: string, columnName: string, columnSpec: ColumnSpec, callback: CallbackFunction): void; + quoteDDLArr(arr: Array): Array; + quoteArr(arr: Array): Array; + addIndex(tableName: string, indexName: string, columns: string | Array, uniqueOrCb?: boolean | CallbackFunction, callback?: CallbackFunction): void; + insert(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): void; + update(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): void; + lookup(tableName: string, column: string, id?: any, callback?: CallbackFunction): void; + removeIndex(tableNameOrIndexName: string, indexNameOrCb?: string | CallbackFunction, callback?: CallbackFunction): void; + addForeignKey(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules, callback: CallbackFunction): void; + removeForeignKey(tableName: string, keyName: string, optionsOrCb?: RemoveForeignKeyOptions | CallbackFunction, callback?: CallbackFunction): void; + normalizeColumnSpec(spec: string | ColumnSpec): ColumnSpec; + addMigrationRecord(name: string, callback: CallbackFunction): void; + addSeedRecord(name: string, callback: CallbackFunction): void; + startMigration(callback: CallbackFunction): void; + endMigration(callback: CallbackFunction): void; + runSql(sql?: string, paramsOrCb?: Array | CallbackFunction, callback?: CallbackFunction): void; + allLoadedMigrations(callback: CallbackFunction): void; + allLoadedSeeds(callback: CallbackFunction): void; + deleteMigration(migrationName: string, callback: CallbackFunction): void; + remove(table: string, ids: any, callback: CallbackFunction): void; // TODO Make ids match the type of ids in buildWhereClause(ids); + buildWhereClause(ids: any): string; + deleteSeed(seedName: string, callback: CallbackFunction): void; + all(sql: string, paramsOrCb?: Array | CallbackFunction, callback?: CallbackFunction): void; + escape(str: string): string; + escapeString(str: string): string; + escapeDDL(str: string): string; + + // Promisified methods + closeAsync(): Promise; + truncateAsync(tableName: string): Promise; + checkDBMSAsync(dbms: any): Promise; + createDatabaseAsync(...options: any[]): Promise; + switchDatabaseAsync(...options: any[]): Promise; + dropDatabaseAsync(...options: any[]): Promise; + recurseCallbackArrayAsync(foreignKeys: Array): Promise; + createMigrationsTableAsync(): Promise; + createSeedsTableAsync(): Promise; + createTableAsync(tableName: string, options: any | CreateTableOptions): Promise; + dropTableAsync(tableName: string, options?: DropTableOptions): Promise; + renameTableAsync(tableName: string, newTableName: string): Promise; + addColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise; + removeColumnAsync(tableName: string, columnName: string): Promise; + renameColumnAsync(tableName: string, oldColumnName: string, newColumnName: string): Promise; + changeColumnAsync(tableName: string, columnName: string, columnSpec: ColumnSpec): Promise; + addIndexAsync(tableName: string, indexName: string, columns: string | Array, unique?: boolean): Promise; + insertAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise; + updateAsync(tableName: string, columnNameOrValueArray: any, valueArrayOrIds?: any, idsOrCb?: any | CallbackFunction, callback?: CallbackFunction): Promise; + lookupAsync(tableName: string, column: string, id?: any, callback?: CallbackFunction): Promise; + removeIndexAsync(tableNameOrIndexName: string, indexName?: string): Promise; + addForeignKeyAsync(tableName: string, referencedTableName: string, keyName: string, fieldMapping: any, rules: ForeignKeyRules): Promise; + removeForeignKeyAsync(tableName: string, keyName: string, options?: RemoveForeignKeyOptions): Promise; + addMigrationRecordAsync(name: string): Promise; + addSeedRecordAsync(name: string): Promise; + startMigrationAsync(): Promise; + endMigrationAsync(callback: CallbackFunction): Promise; + runSqlAsync(sql?: string, params?: Array): Promise; + allLoadedMigrationsAsync(): Promise; + allLoadedSeedsAsync(): Promise; + deleteMigrationAsync(migrationName: string): Promise; + removeAsync(table: string, ids: any): Promise; + deleteSeedAsync(seedName: string): Promise; + allAsync(sql: string, params?: Array): Promise; + } + +} \ No newline at end of file diff --git a/db-migrate-pg/db-migrate-pg-tests.ts b/db-migrate-pg/db-migrate-pg-tests.ts new file mode 100644 index 0000000000..3878c54607 --- /dev/null +++ b/db-migrate-pg/db-migrate-pg-tests.ts @@ -0,0 +1,411 @@ +// Test file for db-migrate-pg Definition file +/// + +import * as DbMigratePg from "db-migrate-pg"; + +// Throw together a dummy driver +let db = {}; + +let callback = (err: any, response: any) => { + // Do nothing. +}; + +/// createTable(tableName, columnSpec, callback) +db.createTable('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}, callback); + +db.createTable('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}, callback); + +db.createTable('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}, callback); + +/// dropTable(tableName, [options,] callback) +db.dropTable('pets', callback); + +db.dropTable('pets', { ifExists: true }, callback); + +/// renameTable(tableName, newTableName, callback) +db.renameTable('pets', 'pets_OLD', callback); + +/// addColumn(tableName, columnName, columnSpec, callback) +db.addColumn('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}, callback); + +db.addColumn('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}, callback); + +/// renameColumn(tableName, oldColumnName, newColumnName, callback) +db.renameColumn('pets', 'id', 'pet_id', callback); + +/// changeColumn(tableName, columnName, columnSpec, callback) +db.changeColumn('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}, callback); + +/// addIndex(tableName, indexName, columns, [unique,] callback) +db.addIndex('pets', 'pets_eye_color_idx', ['eye_color'], callback); +db.addIndex('pets', 'pets_registration_code_idx', ['registration_code'], true, callback); + +/// addForeignKey(tableName, referencedTableName, keyName, fieldMapping, rules, callback) +db.addForeignKey('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}, callback); + +/// removeForeignKey(tableName, keyName, options, callback) +db.removeForeignKey('module_user', 'module_uer_module_id_foreign', callback); +db.removeForeignKey('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}, callback); + +/// insert(tableName, [columnNameArray,] valueArray, callback) +db.insert('module_user', ['first_name', 'last_name'], ['Test', 'Testerson'], callback); +db.insert('module_user', ['Test', 'Testerson'], callback); + +/// removeIndex([tableName,] indexName, callback) +db.removeIndex('pets', 'pets_eye_color_idx', callback); +db.removeIndex('pets_eye_color_idx', callback); + +/// runSql(sql, [params,] callback) +db.runSql('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +], callback); +db.runSql('DROP TABLE `pets`', callback); + +/// all(sql, [params,] callback) +db.all('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test'], callback); +db.all('SELECT * FROM `module_user`', callback); + +/// ========= +/// Async +/// ========= + +let onResolve = (result: any) => {}; + +/// createTableAsync(tableName, columnSpec) +db.createTableAsync('pets', { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' +}).then(onResolve); + +db.createTableAsync('pets', { + columns: { + id: { type: 'int', primaryKey: true, autoIncrement: true }, + name: 'string' + }, + ifNotExists: true +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: 'id' + } + } +}).then(onResolve); + +db.createTableAsync('product_variant', +{ + id: { + type: 'int', + unsigned: true, + notNull: true, + primaryKey: true, + autoIncrement: true, + length: 10 + }, + product_id: { + type: 'int', + unsigned: true, + length: 10, + notNull: true, + foreignKey: { + name: 'product_variant_product_id_fk', + table: 'product', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + product_id: 'id' + } + } + } +}).then(onResolve); + +/// dropTableAsync(tableName, [options]) +db.dropTableAsync('pets').then(onResolve); +db.dropTableAsync('pets', { ifExists: true }).then(onResolve); + +/// renameTableAsync(tableName, newTableName) +db.renameTableAsync('pets', 'pets_OLD').then(onResolve); + +/// addColumnAsync(tableName, columnName, columnSpec) +db.addColumnAsync('pets', 'eyeColor', { + type: 'string', + length: 25, + notNull: true, +}).then(onResolve); + +db.addColumnAsync('pets', 'id', { + type: 'int', + primaryKey: true, + autoIncrement: true, + notNull: true, + unique: true +}).then(onResolve); + +/// renameColumnAsync(tableName, oldColumnName, newColumnName) +db.renameColumnAsync('pets', 'id', 'pet_id').then(onResolve); + +/// changeColumnAsync(tableName, columnName, columnSpec) +db.changeColumnAsync('pets', 'eye_color', { + type: 'int', + unsigned: true, + notNull: true, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + eye_color: 'id' + } + } +}).then(onResolve); + +/// addIndexAsync(tableName, indexName, columns, [unique]) +db.addIndexAsync('pets', 'pets_eye_color_idx', ['eye_color']).then(onResolve); +db.addIndexAsync('pets', 'pets_registration_code_idx', ['registration_code'], true).then(onResolve); + +/// addForeignKeyAsync(tableName, referencedTableName, keyName, fieldMapping, rules) +db.addForeignKeyAsync('module_user', 'modules', 'module_user_module_id_fk', +{ + 'module_id': 'id' +}, +{ + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' +}).then(onResolve); + +/// removeForeignKeyAsync(tableName, keyName, options) +db.removeForeignKeyAsync('module_user', 'module_uer_module_id_foreign').then(onResolve); +db.removeForeignKeyAsync('module_user', 'module_user_module_id_foreign', { + dropIndex: true, +}).then(onResolve); + +/// insertAsync(tableName, [columnNameArray,] valueArray) +db.insertAsync('module_user', ['first_name', 'last_name'], ['Test', 'Testerson']).then(onResolve); +db.insertAsync('module_user', ['Test', 'Testerson']).then(onResolve); + +/// removeIndexAsync([tableName,] indexName) +db.removeIndexAsync('pets', 'pets_eye_color_idx').then(onResolve); +db.removeIndexAsync('pets_eye_color_idx').then(onResolve); + +/// runSqlAsync(sql, [params]) +db.runSqlAsync('INSERT INTO `module_user` (`?`,`?`) VALUES (\'?\',\'?\')', [ + 'first_name', 'last_name', + 'Test', 'Testerson' +]).then(onResolve); +db.runSqlAsync('DROP TABLE `pets`').then(onResolve); + +/// allAsync(sql, [params]) +db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); +db.allAsync('SELECT * FROM `module_user`').then(onResolve); + +/// ==================== +/// PG-specific tests +/// ==================== + +/// createColumnConstraint(spec, options, tableName, columnName) (INTERNAL USE ONLY) +let constraint: DbMigratePg.ColumnConstraint; + +constraint = db.createColumnConstraint({ + type: 'int', + length: 10, + unsigned: true, + primaryKey: false, + autoIncrement: false, + notNull: true, + unique: false, + defaultValue: 0, + foreignKey: { + name: 'pets_eye_color_id_fk', + table: 'eye_color', + rules: { + onDelete: 'CASCADE', + onUpdate: 'RESTRICT' + }, + mapping: { + 'eye_color': 'id' + } + } +}, { + emitPrimaryKey: false +}, 'pets', 'eye_color'); + +// Print the SQL constraints +console.log(constraint.constraints); + +// Invoke the foreign key builder +constraint.foreignKey(callback); + +/// Public Callback Methods: + +/// createDatabase(dbName, [options,] callback) +db.createDatabase('petstore', callback); +db.createDatabase('petstore', {}, callback); + +/// dropDatabase(dbName, [options,] callback) +db.dropDatabase('petstore', callback); +db.dropDatabase('petstore', { ifExists: true }, callback); + +/// createSequence(sqName, [options,] callback) +db.createSequence('pets_id_sq', callback); +db.createSequence('pets_id_sq', { temp: true }, callback); + +/// switchDatabase(options, callback) +db.switchDatabase('petstore', callback); +db.switchDatabase({ database: 'petstore' }, callback); + +/// dropSequence(sqName, [options,] callback) +db.dropSequence('pets_id_sq', callback); +db.dropSequence('pets_id_sq', { + ifExists: true, + cascade: true, + restrict: true, +}, callback); + +/// Public Promisified Methods: + +/// createDatabaseAsync(dbName, [options]) +db.createDatabaseAsync('petstore').then(onResolve); +db.createDatabaseAsync('petstore', {}).then(onResolve); + +/// dropDatabaseAsync(dbName, [options]) +db.dropDatabaseAsync('petstore').then(onResolve); +db.dropDatabaseAsync('petstore', { ifExists: true }).then(onResolve); + +/// createSequenceAsync(sqName, [options]) +db.createSequenceAsync('pets_id_sq').then(onResolve); +db.createSequenceAsync('pets_id_sq', { temp: true }).then(onResolve); + +/// switchDatabaseAsync(options) +db.switchDatabaseAsync('petstore').then(onResolve); +db.switchDatabaseAsync({ database: 'petstore' }).then(onResolve); + +/// dropSequenceAsync(sqName, [options]) +db.dropSequenceAsync('pets_id_sq').then(onResolve); +db.dropSequenceAsync('pets_id_sq', { + ifExists: true, + cascade: true, + restrict: true, +}).then(onResolve); diff --git a/db-migrate-pg/db-migrate-pg.d.ts b/db-migrate-pg/db-migrate-pg.d.ts new file mode 100644 index 0000000000..533b8ff91d --- /dev/null +++ b/db-migrate-pg/db-migrate-pg.d.ts @@ -0,0 +1,60 @@ +// Type definitions for db-migrate-pg +// Project: https://github.com/db-migrate/pg +// Definitions by: nickiannone +// Definitions: https://github.com/nickiannone/DefinitelyTyped + +/// +/// + +declare module "db-migrate-pg" { + + import * as pg from "pg"; + import * as DbMigrateBase from "db-migrate-base"; + import * as Promise from "bluebird"; + + // Yes, this is a dummy interface for now; the current implementation of the pg driver doesn't need any options. + export interface CreateDatabaseOptions {} + + export interface DropDatabaseOptions { + ifExists?: boolean; + } + + export interface CreateSequenceOptions { + temp?: boolean; + } + + export interface SwitchDatabaseOptions { + database?: string; + } + + export interface DropSequenceOptions { + ifExists?: boolean; + cascade?: boolean; + restrict?: boolean; + } + + export interface ColumnConstraint { + foreignKey: (callback: DbMigrateBase.CallbackFunction) => void; + constraints: string; + } + + export interface ColumnConstraintOptions { + emitPrimaryKey?: boolean; + } + + export class PgDriver extends DbMigrateBase.Base { + constructor(connection: pg.Client, schema: string, intern: DbMigrateBase.InternalOptions); + createDatabase(dbName: string, optionsOrCb: CreateDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + dropDatabase(dbName: string, optionsOrCb: DropDatabaseOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + createSequence(sqName: string, optionsOrCb: CreateSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + switchDatabase(options: string | SwitchDatabaseOptions, callback: DbMigrateBase.CallbackFunction): void; + dropSequence(dbName: string, optionsOrCb: DropSequenceOptions | DbMigrateBase.CallbackFunction, callback?: DbMigrateBase.CallbackFunction): void; + createColumnConstraint(spec: DbMigrateBase.ColumnSpec, options: ColumnConstraintOptions, tableName: string, columnName: string): ColumnConstraint; + + createDatabaseAsync(dbName: string, options?: CreateDatabaseOptions): Promise; + dropDatabaseAsync(dbName: string, options?: DropDatabaseOptions): Promise; + createSequenceAsync(sqName: string, options?: CreateSequenceOptions): Promise; + switchDatabaseAsync(options: string | SwitchDatabaseOptions): Promise; + dropSequenceAsync(dbName: string, options?: DropSequenceOptions): Promise; + } +} \ No newline at end of file diff --git a/diff2html/diff2html-tests.ts b/diff2html/diff2html-tests.ts new file mode 100644 index 0000000000..35448baa90 --- /dev/null +++ b/diff2html/diff2html-tests.ts @@ -0,0 +1,26 @@ +/// + +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); diff --git a/diff2html/diff2html.d.ts b/diff2html/diff2html.d.ts new file mode 100644 index 0000000000..398cb1aba1 --- /dev/null +++ b/diff2html/diff2html.d.ts @@ -0,0 +1,66 @@ +// Type definitions for diff2html +// Project: https://github.com/rtfpessoa/diff2html +// Definitions by: 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; +} diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index bca5721240..eaab995a36 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -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(dest: T): T; + mixin( + dest: T, + source: U + ): T & U; + mixin( + dest: T, + source1: U, + source2: V + ): T & U & V; + mixin( + dest: T, + source1: U, + source2: V, + source3: W + ): T & U & V & W; + mixin(dest: Object, ...sources: Object[]): T; /** * similar to hitch() except that the scope object is left to be * whatever the execution context eventually becomes. diff --git a/dustjs-linkedin/dustjs-linkedin.d.ts b/dustjs-linkedin/dustjs-linkedin.d.ts index 70bd288a39..9bb05b1424 100644 --- a/dustjs-linkedin/dustjs-linkedin.d.ts +++ b/dustjs-linkedin/dustjs-linkedin.d.ts @@ -89,7 +89,7 @@ declare module "dustjs-linkedin" { * Registers an event listener. Streams accept a single listener for a given event. * @param evt the event. Possible values are data, end, error (maybe more, look in the source). */ - on(evt: string, callback: (data?: any) => any); + on(evt: string, callback: (data?: any) => any): this; pipe(stream: Stream): Stream; } @@ -126,8 +126,8 @@ declare module "dustjs-linkedin" { * @param name the template name. * @param context a plain object or an instance of dust.Context. */ - export function render(name: string, context: any, callback: (err: any, out: string) => any); - export function render(name: string, context: Context, callback: (err: any, out: string) => any); + export function render(name: string, context: any, callback: (err: any, out: string) => any): void; + export function render(name: string, context: Context, callback: (err: any, out: string) => any): void; /** * Compiles and renders source, invoking callback on completion. If no callback is supplied this function returns a Stream object. Use this function when precompilation is not required. diff --git a/dva/dva-tests.tsx b/dva/dva-tests.tsx new file mode 100644 index 0000000000..917ee69e60 --- /dev/null +++ b/dva/dva-tests.tsx @@ -0,0 +1,48 @@ +/// +/// + +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 ( +
+

{ count }

+ + +
+ ); +}); + +// 4. Router +app.router(({ history }) => + + + +); + +// 5. Start +const countApp = app.start(); diff --git a/dva/dva.d.ts b/dva/dva.d.ts new file mode 100644 index 0000000000..0cf7206e63 --- /dev/null +++ b/dva/dva.d.ts @@ -0,0 +1,61 @@ +// Type definitions for dva v1.0.0 +// Project: https://github.com/dvajs/dva +// Definitions by: nikogu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +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 { + render():JSX.Element + } + + + interface RouteProps { + path?: string, + component?: React.ReactNode + } + export class Route extends React.Component { + 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; +} diff --git a/elastic.js/elastic.js.d.ts b/elastic.js/elastic.js.d.ts index 850d1ccdfa..9bf5f6a9dc 100644 --- a/elastic.js/elastic.js.d.ts +++ b/elastic.js/elastic.js.d.ts @@ -19,7 +19,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -40,7 +40,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -58,7 +58,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -107,7 +107,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -139,7 +139,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -161,7 +161,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -226,7 +226,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets if the Query should be enhanced with a @@ -278,7 +278,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -298,7 +298,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost factor. @@ -314,7 +314,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -335,7 +335,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -362,7 +362,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -382,7 +382,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -425,7 +425,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -454,7 +454,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the analyzer name used to analyze the Query object. @@ -522,7 +522,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -536,7 +536,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets analyzer used to analyze the suggest text. @@ -593,7 +593,7 @@ declare module elasticjs { Retrieves the internal suggest object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets if transpositions should be counted as one or two changes, defaults @@ -635,7 +635,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -666,7 +666,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -693,7 +693,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -805,7 +805,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -839,7 +839,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -986,7 +986,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Allows you to specify a different value field to aggrerate over. @@ -1023,7 +1023,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -1086,7 +1086,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1110,7 +1110,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the decay value which defines how documents are scored at the distance @@ -1165,7 +1165,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1185,7 +1185,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the accuracy. How similar the suggested terms at least @@ -1285,7 +1285,7 @@ declare module elasticjs { Retrieves the internal generator object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1389,7 +1389,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -1419,7 +1419,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1438,7 +1438,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -1489,7 +1489,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -1521,7 +1521,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1531,7 +1531,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -1573,7 +1573,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1595,7 +1595,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -1616,7 +1616,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1636,7 +1636,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -1662,7 +1662,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1684,7 +1684,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -1734,7 +1734,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1766,7 +1766,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -1813,7 +1813,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1823,7 +1823,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -1864,7 +1864,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -1908,7 +1908,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -1946,7 +1946,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* The analyzer that will be used to analyze the text. Defaults to the @@ -2000,7 +2000,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -2035,7 +2035,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* The analyzer that will be used to analyze the text. Defaults to the @@ -2091,7 +2091,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -2116,7 +2116,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the Query. @@ -2179,7 +2179,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Set to false to use classic Levenshtein edit distance. @@ -2208,7 +2208,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the bottom-right coordinate of the bounding box @@ -2284,7 +2284,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -2344,7 +2344,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the distance unit. Valid values are: @@ -2383,7 +2383,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a new bounded range. @@ -2479,7 +2479,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the distance unit. Valid values are "mi" for miles or "km" @@ -2515,7 +2515,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -2601,7 +2601,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -2728,7 +2728,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -2771,7 +2771,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -2792,7 +2792,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the GeoPoint from an array point. The array must contain only @@ -2834,7 +2834,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -2853,7 +2853,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -2921,7 +2921,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -3007,7 +3007,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -3059,7 +3059,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -3079,7 +3079,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -3100,7 +3100,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -3119,7 +3119,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -3185,7 +3185,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -3232,7 +3232,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the child document type to search against @@ -3256,7 +3256,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -3317,7 +3317,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -3360,7 +3360,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -3390,7 +3390,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Set's the boundary characters. When highlighting a field that is @@ -3462,7 +3462,7 @@ declare module elasticjs { Sets arbitrary options that can be passed to the highlighter implementation in use. */ - options(opts: string, oField: Object): Highlight; + options(opts: string, oField: string): Highlight; /* Sets the order of highlight fragments. You can apply the option @@ -3508,7 +3508,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the highligher type. You can apply the option @@ -3539,7 +3539,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -3621,7 +3621,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -3655,7 +3655,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -3762,7 +3762,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Allows you to specify a different value field to aggrerate over. @@ -3793,7 +3793,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -3848,7 +3848,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -3859,7 +3859,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type as a single type or an array of types. If type is a @@ -3896,7 +3896,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the document id of the indexed shape. @@ -3919,7 +3919,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type which the shape is indexed under. @@ -3945,7 +3945,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -4006,7 +4006,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -4036,7 +4036,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4057,7 +4057,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -4115,7 +4115,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4133,7 +4133,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -4177,7 +4177,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -4216,7 +4216,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -4227,7 +4227,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4248,7 +4248,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the analyzer name used to analyze the Query object. @@ -4377,7 +4377,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type of the MatchQuery. Valid values are @@ -4411,7 +4411,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -4443,7 +4443,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4453,7 +4453,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -4485,7 +4485,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4507,7 +4507,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -4539,7 +4539,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4559,7 +4559,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -4585,7 +4585,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4603,7 +4603,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -4657,7 +4657,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* The analyzer that will be used to analyze the text. Defaults to the @@ -4748,7 +4748,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4767,7 +4767,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* The analyzer that will be used to analyze the text. Defaults to the @@ -4860,7 +4860,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -4883,7 +4883,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the analyzer name used to analyze the Query object. @@ -5022,7 +5022,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type of the MultiMatchQuery. Valid values are @@ -5061,7 +5061,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -5087,7 +5087,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5113,7 +5113,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the nested Query. @@ -5190,7 +5190,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -5227,7 +5227,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5246,7 +5246,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5300,7 +5300,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5388,7 +5388,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5437,7 +5437,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Compression controls memory usage and approximation error. The compression @@ -5496,7 +5496,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5518,7 +5518,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets analyzer used to analyze the suggest text. @@ -5625,7 +5625,7 @@ declare module elasticjs { Retrieves the internal suggest object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the token limit. @@ -5649,7 +5649,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5698,7 +5698,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the Query. @@ -5743,7 +5743,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* The prefix value. @@ -5780,7 +5780,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -5827,7 +5827,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5853,7 +5853,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -5888,7 +5888,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -5899,7 +5899,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -5922,7 +5922,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets whether or not wildcard characters (* and ?) are allowed as the @@ -6114,7 +6114,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets whether or not queries against multiple fields should be combined using Lucene's @@ -6140,7 +6140,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a filter whose matching documents will have the score function applied. @@ -6156,7 +6156,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -6181,7 +6181,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -6223,7 +6223,7 @@ declare module elasticjs { /* Adds a range to the list of exsiting range expressions. */ - range(from: string, to: string, key: string): RangeAggregation; + range(from: number, to?: number, key?: string): RangeAggregation; /* Allows you generate or modify the terms using a script. @@ -6239,7 +6239,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -6271,7 +6271,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a new bounded range. @@ -6356,7 +6356,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Allows you to specify an alternate value field to be used to compute statistical information. @@ -6385,7 +6385,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -6476,7 +6476,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the Query. @@ -6537,7 +6537,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -6557,7 +6557,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -6630,7 +6630,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value of the Query. @@ -6698,7 +6698,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* The regexp value. @@ -6721,7 +6721,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add an aggregation. This method can be called multiple times @@ -6769,7 +6769,7 @@ declare module elasticjs { by making multiple request. This parameters specifies the starting result/document number point. Combine with size() to achieve paging. */ - from(f: any[]): Request; + from(f: number): Request; /* Performs highlighting based on the Highlight @@ -6827,7 +6827,7 @@ declare module elasticjs { It is recommended to use Sort objects when possible. */ - sort(fieldName: string): Request; + sort(fieldName?: string | any[] | Sort, order?: string): Request; /* Allows to control how the _source field is returned with every hit. @@ -6859,7 +6859,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Enables score computation and tracking during sorting. Be default, @@ -6889,7 +6889,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the weight assigned to the original query of the rescoring. @@ -6921,7 +6921,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the window_size parameter of the rescoring. @@ -6936,7 +6936,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a filter whose matching documents will have the score function applied. @@ -6947,7 +6947,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -6969,7 +6969,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* If execeptions thrown from the script should be ignored or not. @@ -6997,7 +6997,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7015,7 +7015,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -7071,7 +7071,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Adds a filter whose matching documents will have the score function applied. @@ -7098,7 +7098,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7119,7 +7119,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the coordinates for the shape definition. Note, the coordinates @@ -7137,7 +7137,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the shape type. Can be set to one of: point, linestring, polygon, @@ -7163,7 +7163,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -7237,7 +7237,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7258,7 +7258,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the sort order to ascending (asc). Same as calling @@ -7393,7 +7393,7 @@ declare module elasticjs { Retrieves the internal script object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the script sort type. Valid values are: @@ -7433,7 +7433,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7454,7 +7454,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7474,7 +7474,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7490,7 +7490,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7509,7 +7509,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7543,7 +7543,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7562,7 +7562,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7583,7 +7583,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7602,7 +7602,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7620,7 +7620,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7640,7 +7640,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -7661,7 +7661,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7693,7 +7693,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enables caching of the facetFilter @@ -7762,7 +7762,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7786,7 +7786,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -7818,7 +7818,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7854,7 +7854,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the text to get suggestions for. If not set, the global @@ -7866,7 +7866,7 @@ declare module elasticjs { Retrieves the internal suggest object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7888,7 +7888,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -7920,7 +7920,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -7940,7 +7940,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -7994,7 +7994,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -8015,7 +8015,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8034,7 +8034,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Add a nested aggregation. This method can be called multiple times @@ -8134,7 +8134,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the type of the field value for use in scripts. Current values are: @@ -8169,7 +8169,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Allows you to return all terms, even if the frequency count is 0. This should not be @@ -8301,7 +8301,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8320,7 +8320,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -8416,7 +8416,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -8451,7 +8451,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8483,7 +8483,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Allows you to return all terms, even if the frequency count is 0. This should not be @@ -8579,7 +8579,7 @@ declare module elasticjs { Retrieves the internal facet object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the field for which statistical information will be generated. @@ -8612,7 +8612,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the accuracy. How similar the suggested terms at least @@ -8716,7 +8716,7 @@ declare module elasticjs { Retrieves the internal suggest object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8740,7 +8740,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -8787,7 +8787,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the child document type to search against @@ -8810,7 +8810,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Enable or disable caching of the filter @@ -8858,7 +8858,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the field to operate on. @@ -8890,7 +8890,7 @@ declare module elasticjs { Retrieves the internal agg object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; } @@ -8915,7 +8915,7 @@ declare module elasticjs { /* The type of ejs object. For internal use only. */ - _type(): String; + _type(): string; /* Sets the boost value for documents matching the Query. @@ -8960,7 +8960,7 @@ declare module elasticjs { Retrieves the internal query object. This is typically used by internal API functions so use with caution. */ - toJSON(): String; + toJSON(): any; /* Sets the wildcard query value. diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 9a85f2c908..6d308dc6ed 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -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) => { }); \ No newline at end of file diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index b06c11f6bc..d983817869 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,24 +1,28 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt +// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin // 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; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; + create(params: CreateDocumentParams): PromiseLike; + create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void; delete(params: DeleteDocumentParams): PromiseLike; delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void; - get(params: GetParams, callback: (error: any, response: any) => void): void; + get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): PromiseLike>; index(params: IndexDocumentParams): PromiseLike; index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams): PromiseLike>; - msearch(params: MSearchParams, callback: (error: any, response: any) => void): void; - msearch(params: MSearchParams): PromiseLike>; + mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; + mget(params: MGetParams): PromiseLike>; + msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; + msearch(params: MSearchParams): PromiseLike>; ping(params: PingParams): PromiseLike; ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; scroll(params: ScrollParams): PromiseLike; @@ -102,6 +106,21 @@ declare module Elasticsearch { index?: string; } + export interface CreateDocumentParams extends GenericParams { + consistency?: "one" | "quorum" | "all"; + parent?: string; + refressh?: boolean; + routing?: string; + timeout?: number | Date; + timestamp?: number | Date; + ttl?: number; + version?: number; + versionType?: "internal" | "external" | "external_gte" | "force"; + id: string; + index: string; + type: string; + } + export interface IndicesGetParams extends GenericParams { ignoreUnavailable?: boolean; index: string | string[] | boolean; @@ -177,7 +196,8 @@ declare module Elasticsearch { versionType?: string; } - export interface GetResponse extends GenericParams { + export interface GetResponse { + _index: string; _type: string; _id: string; _version: number; @@ -213,6 +233,7 @@ declare module Elasticsearch { scroll?: string; search_type?: string; fields?: string[]; + from?: number; size?: number; sort?: string | string[] | boolean; _source?: string | string[] | boolean; @@ -259,6 +280,10 @@ declare module Elasticsearch { search_type?: string; } + export interface MSearchResponse { + responses?: SearchResponse[]; + } + export interface MGetParams extends GenericParams { fields?: string | string[] | Boolean; preference?: string; @@ -270,6 +295,10 @@ declare module Elasticsearch { type?: string; } + export interface MGetResponse { + docs?: GetResponse[]; + } + export interface IndicesIndexExitsParams extends GenericParams { index: string | string[] | boolean; ignoreUnavailable?: boolean; @@ -316,6 +345,91 @@ declare module Elasticsearch { body: string | any; index: string | string[] | boolean; } + + export interface Cat { + health(params: CatHealthOptions, callback: (error: any, response: any) => void): void; + health(params: CatHealthOptions): PromiseLike + } + + 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; + health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthOptions): PromiseLike; + pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksOptions): PromiseLike; + putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsOptions): PromiseLike; + reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteOptions): PromiseLike; + state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void; + state(params: ClusterStateOptions): PromiseLike; + stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsOptions): PromiseLike; + } + + 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" { diff --git a/electron-notify/electron-notify-tests.ts b/electron-notify/electron-notify-tests.ts new file mode 100644 index 0000000000..95e2edf998 --- /dev/null +++ b/electron-notify/electron-notify-tests.ts @@ -0,0 +1,26 @@ +/// + +import * as eNotify from 'electron-notify'; + +eNotify.setConfig({ + appIcon: 'images/otherIcon.png', + displayTime: 6000, + defaultStyleText: { + color: '#FF0000', + fontWeight: 'bold' + } +}); + +eNotify.notify({ + title: 'Title', + text: 'Some text', + image: 'path/to/image.png', + url: 'http://google.de', + sound: 'notification.wav', + onClickFunc: (event) => { + console.log('onClick ' + event.id); + event.closeNotification('onClick'); + }, + onShowFunc: (event) => { console.log('onShow ' + event.id) }, + onCloseFunc: (event) => { console.log('onClose ' + event.id) } +}); \ No newline at end of file diff --git a/electron-notify/electron-notify.d.ts b/electron-notify/electron-notify.d.ts new file mode 100644 index 0000000000..b29efa0e50 --- /dev/null +++ b/electron-notify/electron-notify.d.ts @@ -0,0 +1,64 @@ +// Type definitions for electron-notify v0.1.0 +// Project: https://github.com/hankbao/electron-notify +// Definitions by: Daniel Pereira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** Nice and simple notifications for electron apps */ +declare module 'electron-notify' { + + export interface ICustomConfig { + width?: number, + height?: number, + padding?: number, + borderRadius?: number, + displayTime?: number, + animationSteps?: number, + animationStepMs?: number, + animateInParallel?: boolean, + appIcon?: string, + pathToModule?: string, + logging?: boolean, + defaultWindow?: Electron.BrowserWindowOptions, + defaultStyleContainer?: any, + defaultStyleAppIcon?: any, + defaultStyleImage?: any, + defaultStyleClose?: any, + defaultStyleText?: any + } + + export interface ICloseNotificationEvent { + event: 'close' | 'show' | 'click', + id: number + } + + export interface INotificationEvent extends ICloseNotificationEvent { + closeNotification: (reason: any) => void, + } + + export interface INotification { + title: string, + text?: string, + image?: string, + url?: string, + sound?: string, + onClickFunc?: (event: INotificationEvent) => void, + onShowFunc?: (event: INotificationEvent) => void, + onCloseFunc?: (event: ICloseNotificationEvent) => void + } + + /** Change some config options. Can be run multiple times, also between notify()-calls to change electron-notifys behaviour. */ + export function setConfig(customConfig: ICustomConfig): void; + + /** Displays new notification. */ + export function notify(notification: INotification): void; + + /** Clears the animation queue and closes all windows opened by electron-notify. Call this to clean up before quiting your app. */ + export function closeAll(): void; + + export function getTemplatePath(): string; + + export function setTemplatePath(path: string): void; + +} \ No newline at end of file diff --git a/esprima-walk/esprima-walk-tests.ts b/esprima-walk/esprima-walk-tests.ts new file mode 100644 index 0000000000..4588ebb615 --- /dev/null +++ b/esprima-walk/esprima-walk-tests.ts @@ -0,0 +1,25 @@ +/// +/// + +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 +}) + diff --git a/esprima-walk/esprima-walk.d.ts b/esprima-walk/esprima-walk.d.ts new file mode 100644 index 0000000000..d18cf96bb1 --- /dev/null +++ b/esprima-walk/esprima-walk.d.ts @@ -0,0 +1,40 @@ +// Type definitions for esprima-walk v0.1.0 +// Project: https://github.com/jrajav/esprima-walk +// Definitions by: tswaters +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +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 +} + diff --git a/esprima/esprima-tests.ts b/esprima/esprima-tests.ts index f1a0f7ad92..2bca0d5e54 100644 --- a/esprima/esprima-tests.ts +++ b/esprima/esprima-tests.ts @@ -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]; diff --git a/esprima/esprima.d.ts b/esprima/esprima.d.ts index 30fe9512bf..64a9333fa3 100644 --- a/esprima/esprima.d.ts +++ b/esprima/esprima.d.ts @@ -30,6 +30,7 @@ declare namespace esprima { attachComment?: boolean; tolerant?: boolean; source?: boolean; + sourceType?: 'script' | 'module'; } const Syntax: { diff --git a/eventemitter2/eventemitter2.d.ts b/eventemitter2/eventemitter2.d.ts index 39a349c6b6..de1be0d064 100644 --- a/eventemitter2/eventemitter2.d.ts +++ b/eventemitter2/eventemitter2.d.ts @@ -43,7 +43,7 @@ declare class EventEmitter2 { * @param event * @param listener */ - on(event: string, listener: Function): EventEmitter2; + on(event: string | string[], listener: Function): EventEmitter2; /** * Adds a listener that will be fired when any event is emitted. @@ -128,7 +128,7 @@ declare class EventEmitter2 { * @param event * @param args */ - emit(event: string, ...args: any[]): boolean; + emit(event: string | string[], ...args: any[]): boolean; /** * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. @@ -156,7 +156,7 @@ declare module "eventemitter2" { * @param event * @param listener */ - on(event: string, listener: Function): EventEmitter2; + on(event: string | string[], listener: Function): EventEmitter2; /** * Adds a listener that will be fired when any event is emitted. @@ -241,7 +241,7 @@ declare module "eventemitter2" { * @param event * @param args */ - emit(event: string, ...args: any[]): boolean; + emit(event: string | string[], ...args: any[]): boolean; /** * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index de91c521cc..e80ffa85a9 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -22,7 +22,7 @@ declare module "express-serve-static-core" { } interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; + (req: Request, res: Response, next?: NextFunction): any; } interface ErrorRequestHandler { @@ -117,11 +117,11 @@ declare module "express-serve-static-core" { interface CookieOptions { maxAge?: number; signed?: boolean; - expires?: Date; + expires?: Date | boolean; httpOnly?: boolean; path?: string; domain?: string; - secure?: boolean; + secure?: boolean | 'auto'; } interface Errback { (err: Error): void; } @@ -199,7 +199,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted charset of the specified character sets, - * based on the request’s Accept-Charset HTTP header field. + * based on the request's Accept-Charset HTTP header field. * If none of the specified charsets is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. @@ -212,7 +212,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted encoding of the specified encodings, - * based on the request’s Accept-Encoding HTTP header field. + * based on the request's Accept-Encoding HTTP header field. * If none of the specified encodings is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. @@ -225,7 +225,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted language of the specified languages, - * based on the request’s Accept-Language HTTP header field. + * based on the request's Accept-Language HTTP header field. * If none of the specified languages is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. @@ -1046,6 +1046,11 @@ declare module "express-serve-static-core" { * simply by removing them from this object. */ routes: any; + + /** + * Using to all registered routes in Express Application + */ + _router: any; } interface Express extends Application { diff --git a/express-session/express-session-tests.ts b/express-session/express-session-tests.ts index 1e1f909b14..0b8460214f 100644 --- a/express-session/express-session-tests.ts +++ b/express-session/express-session-tests.ts @@ -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', diff --git a/express-session/express-session.d.ts b/express-session/express-session.d.ts index 156e9404fc..90e1ed07cc 100644 --- a/express-session/express-session.d.ts +++ b/express-session/express-session.d.ts @@ -30,7 +30,7 @@ declare namespace Express { secure?: boolean; httpOnly: boolean; domain?: string; - expires: Date; + expires: Date | boolean; serialize: (name: string, value: string) => string; } } diff --git a/express-validator/express-validator-tests.ts b/express-validator/express-validator-tests.ts index 74bd277e46..ebd61d6cfc 100644 --- a/express-validator/express-validator-tests.ts +++ b/express-validator/express-validator-tests.ts @@ -15,19 +15,23 @@ app.post('/:urlparam', function(req: express.Request, res: express.Response) { // Similarly checkParams only checks in req.params (URL params) and // checkQuery only checks req.query (GET params). req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt(); - req.checkParams('urlparam', 'Invalid urlparam').isAlpha(); + req.checkParams('urlparam', 'Invalid urlparam').isAlpha().matches(/test?/i).matches('test?', 'i'); req.checkQuery('getparam', 'Invalid getparam').isInt(); - req.checkHeader('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); - req.checkFiles('testFiles', 'Invalid testFiles').isUrl(); - + req.checkHeaders('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); + req.checkFiles('testFiles', 'Invalid testFiles').isURL(); // OR assert can be used to check on all 3 types of params. // req.assert('postparam', 'Invalid postparam').notEmpty().isInt(); // req.assert('urlparam', 'Invalid urlparam').isAlpha(); // req.assert('getparam', 'Invalid getparam').isInt(); - req.sanitize('postparam').toBoolean(); req.filter('postparam').toBoolean(); + req.sanitize('postparam').blacklist('t').blacklist(['']).whitelist('hello').whitelist(['h', 'e', 'l']); + req.sanitizeBody('postvar').trim().stripLow().escape(); + req.sanitizeQuery('queryvar').toDate(); + req.sanitizeParams('urlparam').toFloat().toInt().toInt(10); + req.sanitizeHeaders('header').normalizeEmail(); + var errors = req.validationErrors(); var mappedErrors = req.validationErrors(true); diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 52792a391f..3599b9b79b 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -1,9 +1,10 @@ -// Type definitions for express-validator 2.9.0 +// Type definitions for express-validator 2.20.4 // Project: https://github.com/ctavan/express-validator -// Definitions by: Nathan Ridley , Jonathan Häberle +// Definitions by: Nathan Ridley , Jonathan Häberle , Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// // Add RequestValidation Interface on to Express's Request Interface. declare namespace Express { @@ -31,25 +32,33 @@ declare namespace ExpressValidator { param: string; } - interface ValidatorFunction { (item: string, message: string): Validator; } + interface ValidatorFunction { (item: string | {}, message?: string): Validator; } + interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; } interface SanitizerFunction { (item: string): Sanitizer; } interface Dictionary { [key: string]: T; } export interface RequestValidation { - assert: ValidatorFunction; - check: ValidatorFunction; + assert: ValidatorExtraFunction; + validate: ValidatorExtraFunction; + check: ValidatorExtraFunction; checkBody: ValidatorFunction; checkFiles: ValidatorFunction; - checkHeader: ValidatorFunction; + checkHeaders: ValidatorFunction; checkParams: ValidatorFunction; checkQuery: ValidatorFunction; - validate: ValidatorFunction; - + filter: SanitizerFunction; sanitize: SanitizerFunction; - + sanitizeBody: SanitizerFunction; + sanitizeQuery: SanitizerFunction; + sanitizeParams: SanitizerFunction; + sanitizeHeaders: SanitizerFunction; + onValidationError(errback: (msg: string) => void): void; - validationErrors(mapped?: boolean): Dictionary | any[]; + validationErrors(mapped?: boolean): Dictionary | MappedError[]; + validationErrors(mapped?: boolean): Dictionary | T[]; + asyncValidationErrors(mapped?: boolean): Promise>; + asyncValidationErrors(mapped?: boolean): Promise>; } export interface Validator { @@ -61,12 +70,13 @@ declare namespace ExpressValidator { * Alias for notRegex() */ not(): Validator; - isEmail(): Validator; + isEmail(options?:{}): Validator; /** * Accepts http, https, ftp */ - isUrl(): Validator; - + isURL(): Validator; + isFQDN(options?: MinMaxOptions): Validator; + /** * Combines isIPv4 and isIPv6 */ @@ -74,8 +84,21 @@ declare namespace ExpressValidator { isIPv4(): Validator; isIPv6(): Validator; isMACAddress(): Validator; - isAlpha(): Validator; - isAlphanumeric(): Validator; + isISBN(version?: number): Validator; + isISIN(): Validator; + isISO8601(): Validator; + isMobilePhone(locale: string): Validator; + isMongoId(): Validator; + isMultibyte(): Validator; + isAlpha(locale?: string): Validator; + isAlphanumeric(locale?: string): Validator; + isAscii(): Validator; + isBase64(): Validator; + isBoolean(): Validator; + isByteLength(options: MinMaxOptions): Validator; + isCurrency(options: {}): Validator; + isDataURI(): Validator; + isDivisibleBy(num: number): Validator; isNumeric(): Validator; isHexadecimal(): Validator; /** @@ -85,7 +108,7 @@ declare namespace ExpressValidator { /** * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't */ - isInt(): Validator; + isInt(options?: MinMaxOptions): Validator; isLowercase(): Validator; isUppercase(): Validator; isDecimal(): Validator; @@ -93,10 +116,12 @@ declare namespace ExpressValidator { * Alias for isDecimal */ isFloat(): Validator; + isFullWidth(): Validator; + isHalfWidth(): Validator; + isVariableWidth(): Validator; /** * Check if length is 0 */ - notNull(): Validator; isNull(): Validator; /** * Not just whitespace (input.trim().length !== 0) @@ -104,12 +129,13 @@ declare namespace ExpressValidator { notEmpty(): Validator; equals(equals:any): Validator; contains(str:string): Validator; - notContains(str:string): Validator; + /** - * Usage: regex(/[a-z]/i) or regex('[a-z]','i') + * Usage: matches(/[a-z]/i) or matches('[a-z]','i') */ - regex(pattern:string, modifiers:string): Validator; - notRegex(pattern:string, modifiers:string): Validator; + matches(pattern:string, modifiers?:string): Validator; + matches(pattern: RegExp): Validator; + /** * max is optional */ @@ -117,7 +143,7 @@ declare namespace ExpressValidator { /** * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier */ - isUUID(version:number): Validator; + isUUID(version?:number): Validator; /** * Alias for isUUID(3) */ @@ -137,17 +163,20 @@ declare namespace ExpressValidator { /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isAfter(date:Date): Validator; + isAfter(date?:Date): Validator; /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isBefore(date:Date): Validator; + isBefore(date?:Date): Validator; isIn(options:string): Validator; isIn(options:string[]): Validator; notIn(options:string): Validator; notIn(options:string[]): Validator; max(val:string): Validator; min(val:string): Validator; + isJSON(): Validator; + isLength(options: MinMaxOptions): Validator; + isWhitelisted(chars: string): Validator; /** * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats */ @@ -155,7 +184,10 @@ declare namespace ExpressValidator { /** * Check an input only when the input exists */ - optional(): Validator; + isSurrogatePar(): Validator; + + optional(options?: { checkFalsy?: boolean }): Validator; + withMessage(message: string): Validator; } interface Sanitizer { @@ -165,40 +197,49 @@ declare namespace ExpressValidator { trim(...chars:string[]): Sanitizer; ltrim(...chars:string[]): Sanitizer; rtrim(...chars:string[]): Sanitizer; - ifNull(replace:any): Sanitizer; + stripLow(keep_new_lines?: boolean): Sanitizer; toFloat(): Sanitizer; - toInt(): Sanitizer; + toInt(radix?: number): Sanitizer; /** - * True unless str = '0', 'false', or str.length == 0 - */ - toBoolean(): Sanitizer; - /** - * False unless str = '1' or 'true' - */ - toBooleanStrict(): Sanitizer; - /** - * Decode HTML entities + * True unless str = '0', 'false', or str.length == 0. In strict mode only '1' and 'true' return true. */ + toBoolean(strict?: boolean): Sanitizer; /** - * Convert the input string to a date, or null if the input is not a date. - */ - toDate(): Sanitizer; - - entityDecode(): Sanitizer; - entityEncode(): Sanitizer; + * Convert the input string to a date, or null if the input is not a date. + */ + toDate(): Sanitizer; + /** * Escape &, <, >, and " */ escape(): Sanitizer; + /** - * Remove common XSS attack vectors from user-supplied HTML + * Replaces HTML encoded entities with <, >, &, ', " and /. */ - xss(): Sanitizer; + unescape(): Sanitizer; + + blacklist(chars: string): Sanitizer; + blacklist(chars: string[]): Sanitizer; + whitelist(chars: string): Sanitizer; + whitelist(chars: string[]): Sanitizer; + + normalizeEmail(options?: { lowercase?: boolean; remove_dots?: boolean; remove_extensions?: boolean }): Sanitizer; + /** - * Remove common XSS attack vectors from images + * !!! XSS sanitization was removed from the library (see: https://github.com/chriso/validator.js#xss-sanitization) */ - xss(fromImages:boolean): Sanitizer; } - + + interface MappedError { + param: string; + msg: string; + value: string; + } + + interface MinMaxOptions { + min?: number; + max?: number; + } } diff --git a/express/express-tests.ts b/express/express-tests.ts index ed9265b66a..439ef95012 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,4 +1,5 @@ /// +/// import * as express from 'express'; var app = express(); @@ -91,3 +92,10 @@ app.listen(3000); const next: express.NextFunction = () => {}; const nextWithArgument: express.NextFunction = (err: any) => {}; + +/** + * The express.Application is compatible with http.createServer + */ + +import * as http from 'http'; +http.createServer(app); diff --git a/fabricjs/fabricjs.d.ts b/fabricjs/fabricjs.d.ts index 727cb57f23..08fcdb6ec3 100644 --- a/fabricjs/fabricjs.d.ts +++ b/fabricjs/fabricjs.d.ts @@ -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 */ diff --git a/fetch-mock/fetch-mock-tests.ts b/fetch-mock/fetch-mock-tests.ts index defefa25a1..b630668e18 100644 --- a/fetch-mock/fetch-mock-tests.ts +++ b/fetch-mock/fetch-mock-tests.ts @@ -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"}) diff --git a/fetch-mock/fetch-mock.d.ts b/fetch-mock/fetch-mock.d.ts index 490b4c7dfd..47c31e4c64 100644 --- a/fetch-mock/fetch-mock.d.ts +++ b/fetch-mock/fetch-mock.d.ts @@ -114,6 +114,26 @@ declare module "fetch-mock" { unmatched: Array; } + 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. diff --git a/file-type/file-type-tests.ts b/file-type/file-type-tests.ts new file mode 100644 index 0000000000..ebbee83783 --- /dev/null +++ b/file-type/file-type-tests.ts @@ -0,0 +1,7 @@ +/// + +"use strict"; + +import fileType = require("file-type") + +fileType(new Buffer([0xFF, 0xD8, 0xFF])) diff --git a/file-type/file-type.d.ts b/file-type/file-type.d.ts new file mode 100644 index 0000000000..58c449ca3c --- /dev/null +++ b/file-type/file-type.d.ts @@ -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 +// Definitions: https://github.com/DefinitelyType/DefinitelyTyped + +/// + +declare module "file-type" { + interface FileTypeResult { + ext: string + mime: string + } + + function FileType(buf: Buffer): FileTypeResult + + export = FileType +} diff --git a/fill-pdf/fill-pdf-tests.ts b/fill-pdf/fill-pdf-tests.ts new file mode 100644 index 0000000000..e5b34cd943 --- /dev/null +++ b/fill-pdf/fill-pdf-tests.ts @@ -0,0 +1,17 @@ +/// + +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 diff --git a/fill-pdf/fill-pdf.d.ts b/fill-pdf/fill-pdf.d.ts new file mode 100644 index 0000000000..d35057f934 --- /dev/null +++ b/fill-pdf/fill-pdf.d.ts @@ -0,0 +1,16 @@ +// Type definitions for fill-pdf v0.5.0 +// Project: https://github.com/dommmel/fill-pdf +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +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; +} diff --git a/fluent-ffmpeg/fluent-ffmpeg-tests.ts b/fluent-ffmpeg/fluent-ffmpeg-tests.ts new file mode 100644 index 0000000000..8b1031ff58 --- /dev/null +++ b/fluent-ffmpeg/fluent-ffmpeg-tests.ts @@ -0,0 +1,7 @@ +/// + +import ffmpeg = require("fluent-ffmpeg") + +let source: string, format: string, output: string + +ffmpeg({ source: source }).format(format).save(output) diff --git a/fluent-ffmpeg/fluent-ffmpeg.d.ts b/fluent-ffmpeg/fluent-ffmpeg.d.ts new file mode 100644 index 0000000000..92e1a33891 --- /dev/null +++ b/fluent-ffmpeg/fluent-ffmpeg.d.ts @@ -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 +// Definitions: https://github.com/DefinitelyType/DefinitelyTyped + +/// + +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 +} diff --git a/fs-extra/fs-extra.d.ts b/fs-extra/fs-extra.d.ts index 39656ce685..7061f08746 100644 --- a/fs-extra/fs-extra.d.ts +++ b/fs-extra/fs-extra.d.ts @@ -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 { diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts index 65df012185..81ce91d119 100644 --- a/fullCalendar/fullCalendar.d.ts +++ b/fullCalendar/fullCalendar.d.ts @@ -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; -} \ No newline at end of file +} diff --git a/geojson2osm/geojson2osm-tests.ts b/geojson2osm/geojson2osm-tests.ts new file mode 100644 index 0000000000..c7bfc05b85 --- /dev/null +++ b/geojson2osm/geojson2osm-tests.ts @@ -0,0 +1,47 @@ +/// +/// + +import { geojson2osm } from 'geojson2osm' + +const features: GeoJSON.FeatureCollection = { + 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) diff --git a/geojson2osm/geojson2osm.d.ts b/geojson2osm/geojson2osm.d.ts new file mode 100644 index 0000000000..58393411f1 --- /dev/null +++ b/geojson2osm/geojson2osm.d.ts @@ -0,0 +1,15 @@ +// Type definitions for geojson2osm 0.0.5 +// Project: https://github.com/Rub21/geojson2osm +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'geojson2osm' { + /** + * Converts GeoJSON features to OpenStreetMap XML. + * @param features Input features + * @returns OpenStreetMap XML + */ + export function geojson2osm(features: GeoJSON.Feature | GeoJSON.FeatureCollection): any +} diff --git a/github-electron/electron-prebuilt-tests.ts b/github-electron/electron-tests.ts similarity index 56% rename from github-electron/electron-prebuilt-tests.ts rename to github-electron/electron-tests.ts index 771fd06016..00b34d60b1 100644 --- a/github-electron/electron-prebuilt-tests.ts +++ b/github-electron/electron-tests.ts @@ -1,7 +1,7 @@ -/// +/// /// -import electron = require('electron-prebuilt'); +import electron = require('electron'); import child_process = require('child_process'); child_process.spawn(electron); diff --git a/github-electron/electron-prebuilt.d.ts b/github-electron/electron.d.ts similarity index 53% rename from github-electron/electron-prebuilt.d.ts rename to github-electron/electron.d.ts index d6b6dffc0e..5e331b3e47 100644 --- a/github-electron/electron-prebuilt.d.ts +++ b/github-electron/electron.d.ts @@ -1,9 +1,9 @@ -// Type definitions for electron-prebuilt 0.30.1 -// Project: https://github.com/mafintosh/electron-prebuilt +// Type definitions for electron 1.3.3 +// Project: https://github.com/electron-userland/electron-prebuilt // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module 'electron-prebuilt' { +declare module 'electron' { var electron: string; export = electron; } diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index bebf0b99c8..966465ed3a 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -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()) { diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 7b246966ab..3dc72d7075 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -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 , rhysd , Milan Burda // 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. */ @@ -4766,6 +4885,10 @@ declare namespace Electron { * @returns Whether the web page is destroyed. */ isDestroyed(): boolean; + /** + * @returns Whether the web page is focused. + */ + isFocused(): boolean; /** * @returns Whether guest page is still loading resources. */ @@ -4948,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. @@ -5043,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. * @@ -5058,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. */ @@ -5182,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[]; diff --git a/google-earth/google-earth-tests.ts b/google-earth/google-earth-tests.ts new file mode 100644 index 0000000000..6c9d4df1bf --- /dev/null +++ b/google-earth/google-earth-tests.ts @@ -0,0 +1,131 @@ +/// + +google.load("earth", "1", {"other_params":"sensor=true_or_false"}); + +google.earth.createInstance("map3d", initCB, failureCB); + +function failureCB(error: any) {} + +function initCB(ge: google.earth.GEPlugin) { + + ge.getWindow().setVisibility(true); + + + // Create the placemark. + var placemark = ge.createPlacemark(''); + placemark.setName("placemark"); + + // Set the placemark's location. + var point = ge.createPoint(''); + point.setLatitude(12.345); + point.setLongitude(54.321); + placemark.setGeometry(point); + + // Create a style map. + var styleMap = ge.createStyleMap(''); + + // Create normal style for style map. + var normalStyle = ge.createStyle(''); + var normalIcon = ge.createIcon(''); + normalIcon.setHref('http://maps.google.com/mapfiles/kml/paddle/red-circle.png'); + normalStyle.getIconStyle().setIcon(normalIcon); + + // Create highlight style for style map. + var highlightStyle = ge.createStyle(''); + var highlightIcon = ge.createIcon(''); + highlightIcon.setHref('http://google-maps-icons.googlecode.com/files/girlfriend.png'); + highlightStyle.getIconStyle().setIcon(highlightIcon); + highlightStyle.getIconStyle().setScale(5.0); + + styleMap.setNormalStyle(normalStyle); + styleMap.setHighlightStyle(highlightStyle); + + // Apply stylemap to a placemark. + placemark.setStyleSelector(styleMap); + + //Add the placemark to Earth. + ge.getFeatures().appendChild(placemark); + + + // balloons + var balloon = ge.createHtmlDivBalloon(''); + balloon.setFeature(placemark); + var div = document.createElement('DIV'); + div.innerHTML = 'Any HTML, CSS, or JavaScript goes here.'; + balloon.setContentDiv(div); + ge.setBalloon(balloon); + + // Create the ScreenOverlay + var screenOverlay = ge.createScreenOverlay(''); + + // Specify a path to the image and set as the icon + var icon = ge.createIcon(''); + icon.setHref('http://www.google.com/intl/en_ALL/images/logo.gif'); + screenOverlay.setIcon(icon); + + // Set the ScreenOverlay's position in the window + screenOverlay.getOverlayXY().setXUnits(ge.UNITS_PIXELS); + screenOverlay.getOverlayXY().setYUnits(ge.UNITS_PIXELS); + screenOverlay.getOverlayXY().setX(200); + screenOverlay.getOverlayXY().setY(200); + + // Set the overlay's size in pixels + screenOverlay.getSize().setXUnits(ge.UNITS_PIXELS); + screenOverlay.getSize().setYUnits(ge.UNITS_PIXELS); + screenOverlay.getSize().setX(250); + screenOverlay.getSize().setY(75); + + // Specify the point in the image around which to rotate + screenOverlay.getRotationXY().setXUnits(ge.UNITS_FRACTION); + screenOverlay.getRotationXY().setYUnits(ge.UNITS_FRACTION); + screenOverlay.getRotationXY().setX(0.5); + screenOverlay.getRotationXY().setY(0.5); + + // Rotate the overlay + screenOverlay.setRotation(25); + + // Add the ScreenOverlay to Earth + ge.getFeatures().appendChild(screenOverlay); + + + // network link + var link = ge.createLink(''); + var href = 'http://code.google.com/' + + 'apis/earth/documentation/samples/kml_example.kml' + link.setHref(href); + + var networkLink = ge.createNetworkLink(''); + networkLink.set(link, true, true); // Sets the link, refreshVisibility, and flyToView + + ge.getFeatures().appendChild(networkLink); + + // Get the current view. + var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND); + + // Set new latitude and longitude values. + lookAt.setLatitude(36.584207); + lookAt.setLongitude(-121.754322); + + // Update the view in Google Earth. + ge.getView().setAbstractView(lookAt); + + // time + ge.getTime().getControl().setVisibility(ge.VISIBILITY_SHOW); + ge.getTime().setHistoricalImageryEnabled(true); + var extents = ge.getTime().getControl().getExtents(); + var begin = extents.getBegin().get(); + var end = extents.getEnd().get(); + + // tour + ge.getTourPlayer().play(); + + + // controls + ge.getNavigationControl().getScreenXY().setXUnits(ge.UNITS_INSET_PIXELS); + ge.getNavigationControl().getScreenXY().setYUnits(ge.UNITS_PIXELS); + + + // sky + ge.getOptions().setMapType(ge.MAP_TYPE_SKY); + ge.getOptions().setMapType(ge.MAP_TYPE_EARTH); +} diff --git a/google-earth/google-earth.d.ts b/google-earth/google-earth.d.ts new file mode 100644 index 0000000000..d0adc8c04e --- /dev/null +++ b/google-earth/google-earth.d.ts @@ -0,0 +1,3978 @@ +// Type definitions for Google Earth Plugin +// Project: https://developers.google.com/earth/ +// Definitions by: Ilia Choly +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace google { + + export function load( + moduleName: string, + moduleVersion: string, + optionalSettings?: any + ): void; +} + +declare namespace google.earth { + + /** + * Specifies the current stage of the flow of events. + */ + export type GEEventPhaseEnum = any; + + /** + * Specifies how a feature should be displayed in a list view. + */ + export type KmlListItemTypeEnum = any; + + /** + * Specifies which color mode effect to apply to the base color. + */ + export type KmlColorModeEnum = any; + + /* + * Specifies how the altitude property is interpreted. + */ + export type KmlAltitudeModeEnum = any; + + /** + * Specifies how the link is refreshed. + */ + export type KmlRefreshModeEnum = any; + + /** + * Specifies how the link is refreshed when the viewport changes. + */ + export type KmlViewRefreshModeEnum = any; + + /** + * Specifies which units a value is specified in. + */ + type KmlUnitsEnum = any; + + /** + * Specifies if the map type is Earth or sky mode. + */ + type GEMapTypeEnum = any; + + /** + * Specifies if a control is always visible, always hidden, + * or visible only when the user intends to use the control. + */ + type GEVisibilityEnum = any; + + /** + * Specifies what to sample when performing a hit test. + */ + type GEHitTestModeEnum = any; + + /** + * Specifies the size of the navigation control. + */ + type GENavigationControlEnum = any; + + /** + * Specifies the state of viewer options, including sunlight, + * Street View, and historical imagery. + */ + type GEViewerOptionsValueEnum = any; + + /* + * Specifies the viewer option types. + */ + type GEViewerOptionsTypeEnum = any; + + /** + * Whether or not the Google Earth Browser Plug-in and API are supported on the current browser and operating system. + */ + export function isSupported(): boolean; + + /** + * Whether or not the Google Earth Browser Plug-in is currently installed on the user's machine. + * + * Note: if the plug-in is not installed, the user will be presented with a 'download' link upon calls to google.earth.createInstance(). + */ + export function isInstalled(): boolean; + + /** + * Attempts to create an instance of the plugin under the given web browser HTML DOM node. + * Upon success, calls the function passed in as the initCallback argument. + * Upon failure, calls the function passed in as the failureCallback argument and displays an error message to the user in place of the plug-in object. + * + * Note: + * + * The HTML DOM must be loaded before this function can be called. + * Common usage is to call this function upon the 's load event, or to use google.setOnLoadCallback. + */ + export function createInstance( + domNode: string|Element, + initCallback: (plugin: GEPlugin) => void, + failureCallback: (error: any) => void, + options?: any + ): void; + + /** + * Attaches a listener to a given object for a specific event; when the event occurs on the object, the given callback is invoked. + */ + export function addEventListener( + targetObject: any, + eventID: string, + listenerCallback: (event: KmlEvent) => void, + useCapture?: boolean + ): void; + + /** + * Removes an event listener previously added using google.earth.addEventListener() from the event chain. + * + * Note: + * + * You must pass in the exact same function object as was passed to addEventListener. + * If you are using an anonymous function callback, it will need to be refactored into its own variable. + */ + export function removeEventListener( + targetObject: any, + eventID: string, + listenerCallback: (event: KmlEvent) => void, + useCapture?: boolean + ): void; + + /** + * Retrieves and parses a KML or KMZ file at the given URL and returns an instance of a KmlFeature-derived class representing the parsed KML object model. + * + * Note: This function does not display the feature on the Earth. See below for more information. + */ + export function fetchKml( + pluginInstance: GEPlugin, + url: string, + completionCallback: (feature: KmlFeature) => void + ): void; + + /** + * Efficiently executes an arbitrary, user-defined function (the batch function), minimizing the amount of overhead incurred during cross-process communication between the web browser and Google Earth Plugin. + * This method is useful for batching together a large set of calls to the Earth API, for example, a large number of consecutive calls to KmlCoordArray.pushLatLngAlt. + */ + export function executeBatch(pluginInstance: GEPlugin, batchFunction: Function): void; + + /** + * Sets the language to be used for new instances of the plugin. + * Needs to be called before google.earth.createInstance(). + * Affects road and border labels, the error message displayed when the plugin fails to load, as well as the language of the Terms of Use page linked from the plugin. + */ + export function setLanguage(languageCode: string): void; + + /** + * This interface enables programmatic and user-driven interaction with photo overlays in the Google Earth Plugin. + * + * Note: This interface is still under development. + */ + export class GEPhotoOverlayViewer { + + /** + * Enters the given photo overlay object, exiting any other currently active photo overlay. + * If the argument is null, then any currently active photo overlay is exited and normal global navigation is enabled. + */ + setPhotoOverlay(photoOverlay: KmlPhotoOverlay): void; + } + + /** + * Used to manipulate the navigation controls in Google Earth. + */ + export class GENavigationControl { + + /** + * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. + * + * See also: + * + * * GEPlugin.VISIBILITY_SHOW + * * GEPlugin.VISIBILITY_HIDE + * * GEPlugin.VISIBILITY_AUTO + */ + getVisibility(): GEVisibilityEnum; + + /** + * Whether the control is always visible, always hidden, or visible only when the user intends to use the control. + * + * See also: + * + * * GEPlugin.VISIBILITY_SHOW + * * GEPlugin.VISIBILITY_HIDE + * * GEPlugin.VISIBILITY_AUTO + */ + setVisibility(visibility: GEVisibilityEnum): void; + + /** + * Specifies the size of the navigation control. + * + * See also: + * + * * GEPlugin.NAVIGATION_CONTROL_LARGE + * * GEPlugin.NAVIGATION_CONTROL_SMALL + */ + getControlType(): GENavigationControlEnum; + + /** + * Specifies the size of the navigation control. + * + * See also: + * + * * GEPlugin.NAVIGATION_CONTROL_LARGE + * * GEPlugin.NAVIGATION_CONTROL_SMALL + */ + setControlType(controlType: GENavigationControlEnum): void; + + /** + * The position of the navigation controls in Google Earth + */ + getScreenXY(): KmlVec2; + + /** + * Enables or disables user-initiated entry to Street View imagery. + * When true, the Pegman icon is present in the navigation controls, allowing a user to drag the Pegman onto a street to initiate Street View. + * Users can also zoom down to ground level to enter Street View when this is set to true. + */ + setStreetViewEnabled(streetViewEnabled: boolean): void; + + /** + * Whether Street View is enabled in the navigation controls. + */ + getStreetViewEnabled(): boolean; + } + + /** + * Defines a tour, which is a playlist of scripted camera and update events. + * + * Note: This interface is still under development. + */ + export class KmlTour extends KmlFeature {} + + /** + * This interface enables programmatic and user-driven interaction with KML tours in the Google Earth Plugin. + * + * Note: This interface is still under development. + */ + export class GETourPlayer { + + /** + * Enters the given tour object, exiting any other currently active tour. + * This method does not automatically begin playing the tour. + * If the argument is null, then any currently active tour is exited and normal globe navigation is enabled. + */ + setTour(tour: KmlTour): void; + + /** + * Plays the currently active tour. + */ + play(): void; + + /** + * Pauses the currently active tour. + */ + pause(): void; + + /** + * Resets the currently active tour, stopping playback and rewinding to the start of the tour. + */ + reset(): void; + + /** + * The current elapsed playing time of the active tour, in seconds. + */ + getCurrentTime(): number; + + /** + * The current elapsed playing time of the active tour, in seconds. + */ + setCurrentTime(currentTime: number): void; + + /** + * The total duration of the active tour, in seconds. If no tour is loaded, the behavior of this method is undefined. + */ + getDuration(): number; + } + + /** + * This interface contains result information obtained by calling GEView's hitTest method. + * + * See also: + * + * * GEView.hitTest + */ + export class GEHitTestResult { + + /** + * Latitude of sampled point. + */ + getLatitude(): number; + + /** + * Latitude of sampled point. + */ + setLatitude(latitude: number): void; + + /** + * Longitude of sampled point. + */ + getLongitude(): number; + + /** + * Longitude of sampled point. + */ + setLongitude(longitude: number): void; + + /** + * Altitude of sampled point. + */ + getAltitude(): number; + + /** + * Altitude of sampled point. + */ + setAltitude(altitude: number): void; + } + + /** + * Maps between two different icon styles. + * Typically this interface is used to provide separate normal and highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon. + */ + export class KmlStyleMap extends KmlStyleSelector { + + /** + * Sets both URLs for the placemark style. + */ + setUrl(normalStyleUrl: string, highlightStyleUrl: string): void; + + /** + * Sets both placemark styles. + */ + setStyle(normalStyle: KmlStyle, highlightStyle: KmlStyle): void; + + /** + * Defines a normal style for a placemark. + */ + getNormalStyleUrl(): string; + + /** + * Defines a normal style for a placemark. + */ + setNormalStyleUrl(normalStyleUrl: string): void; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + getHighlightStyleUrl(): string; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + setHighlightStyleUrl(highlightStyleUrl: string): void; + + /** + * Defines a normal style for a placemark. + */ + getNormalStyle(): KmlStyle; + + /** + * Defines a normal style for a placemark. + */ + setNormalStyle(normalStyle: KmlStyle): void; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + getHighlightStyle(): KmlStyle; + + /** + * Defines highlighted styles for a placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + setHighlightStyle(highlightStyle: KmlStyle): void; + } + + /** + * References a KML file or KMZ archive on a remote network. + * Use the Link property to specify the location of the KML file. + * Within that property, you can define the refresh options for updating the file, based on time and camera change. + * NetworkLinks can be used in combination with Regions to handle very large datasets efficiently. + */ + export class KmlNetworkLink extends KmlFeature { + + /** + * Sets the link, refreshVisibility, and flyToView for the network link. + */ + set(link: KmlLink, refreshVisibility: boolean, flyToView: boolean): void; + + /** + * Specifies the location of any of the following: + * + * * KML files fetched by network links + * * Image files used by icons in icon styles, ground overlays, and screen overlays + * * Model files used in the Model object + */ + getLink(): KmlLink; + + /** + * Specifies the location of any of the following: + * + * * KML files fetched by network links + * * Image files used by icons in icon styles, ground overlays, and screen overlays + * * Model files used in the Model object + */ + setLink(link: KmlLink): void; + + /** + * A value of 0 leaves the visibility of features within the control of the Google Earth user. + * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. + * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. + * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. + * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. + */ + getRefreshVisibility(): boolean; + + /** + * A value of 0 leaves the visibility of features within the control of the Google Earth user. + * Set the value to 1 to reset the visibility of features each time the NetworkLink is refreshed. + * For example, suppose a Placemark within the linked KML file has visibility set to 1 and the NetworkLink has refreshVisibility set to 1. + * When the file is first loaded into Google Earth, the user can clear the check box next to the item to turn off display in the 3D viewer. + * However, when the NetworkLink is refreshed, the Placemark will be made visible again, since its original visibility state was TRUE. + */ + setRefreshVisibility(refreshVisibility: boolean): void; + + /** + * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). + */ + getFlyToView(): boolean; + + /** + * A value of 1 causes Google Earth to fly to the view of the LookAt or Camera in the NetworkLinkControl (if it exists). + */ + setFlyToView(flyToView: boolean): void; + } + + /** + * Draws an image overlay fixed to the screen. + * Sample uses for ScreenOverlays are compasses, logos, and heads-up displays. + * ScreenOverlay sizing is determined by the size element. + * Positioning of the overlay is handled by mapping a point in the image specified by screenXY to a point on the screen specified by overlayXY. + * Then the image is rotated by rotation degrees about a point relative to the screen specified by rotationXY. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + export class KmlScreenOverlay extends KmlOverlay { + + /** + * Specifies a point on (or outside of) the overlay image that is mapped to the screen coordinate. + * It requires x and y values, and the units for those values. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + getScreenXY(): KmlVec2; + + /** + * Specifies a point relative to the screen origin that the overlay image is mapped to. + * The x and y values can be specified in three different ways: as pixels ("pixels"), as fractions of the screen ("fraction"), or as inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the screen. + * The x and y positions can be specified in different ways - for example, x can be in pixels and y can be a fraction. + * The origin of the coordinate system is in the lower left corner of the screen. + * + * Note: + * + * screenXY and overlayXY behave opposite to their corresponding behaviors in KML. + * This is due to a bug in the Earth API that will intentionally remain unfixed until a major version change. + */ + getOverlayXY(): KmlVec2; + + /** + * Point relative to the screen about which the screen overlay is rotated. + */ + getRotationXY(): KmlVec2; + + /** + * Specifies the size of the image for the screen overlay, as follows: + * + * * A value of -1 indicates to use the native dimension + * * A value of 0 indicates to maintain the aspect ratio + * * A value of n sets the value of the dimension + */ + getSize(): KmlVec2; + + /** + * Adjusts how the image is placed inside the field of view. + * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. + */ + getRotation(): number; + + /** + * Adjusts how the image is placed inside the field of view. + * This element is useful if your image has been rotated and deviates slightly from a desired horizontal view. + */ + setRotation(rotation: number): void; + } + + /** + * Defines a photo overlay, which is a geographically located photograph of the Earth. + * Photo overlays can be drawn onto 2D rectangles in three dimensional space, or in the case of panoramic photos, onto partial or full cylinders, or even spheres. + * + * Note: This interface is still under development. + */ + export class KmlPhotoOverlay extends KmlOverlay {} + + /** + * Draws an image overlay draped onto the terrain. + * The href child of Icon specifies the image to be used as the overlay. + * If this object is omitted or contains no href, a rectangle is drawn using the color defined by the overlay. + */ + export class KmlGroundOverlay extends KmlOverlay { + + /** + * Specifies the distance above the earth's surface. + */ + getAltitude(): number; + + /** + * Specifies the distance above the earth's surface. + */ + setAltitude(altitude: number): void; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + + /** + * The bounding box of the ground overlay. + */ + getLatLonBox(): KmlLatLonBox; + + /** + * The bounding box of the ground overlay. + */ + setLatLonBox(latLonBox: KmlLatLonBox): void; + } + + /** + * The KmlOverlay object is an abstract object and cannot be used directly in a KML file. + * Overlay is the base type for image overlays drawn on the planet surface or on the screen. + * Icon specifies the image to use and can be configured to reload images based on a timer or by camera changes. + * This object also includes specifications for stacking order of multiple overlays and for adding color and transparency values to the base image. + */ + export class KmlOverlay extends KmlFeature { + + /** + * Specifies the color values. + */ + getColor(): KmlColor; + + /** + * Defines the stacking order for the images in overlapping overlays. + * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. + */ + getDrawOrder(): number; + + /** + * Defines the stacking order for the images in overlapping overlays. + * Overlays with higher drawOrder values are drawn on top of overlays with lower drawOrder values. + */ + setDrawOrder(drawOrder: number): void; + + /** + * Defines the image associated with the Overlay. + */ + getIcon(): KmlIcon; + + /** + * Defines the image associated with the Overlay. + */ + setIcon(icon: KmlIcon): void; + } + + /** + * This class controls the display of sunlight, historical imagery, and Street View panoramas in the plugin. + * The KmlViewerOptions object is passed to KmlAbstractView.setViewerOptions() + */ + export class KmlViewerOptions extends KmlObject { + + /** + * Returns the current state of the specified viewer option type. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + * * GEPlugin.OPTION_STATE_DEFAULT + * * GEPlugin.OPTION_STATE_ENABLED + * * GEPlugin.OPTION_STATE_DISABLED + */ + setOption(type: GEViewerOptionsTypeEnum, state: GEViewerOptionsValueEnum): void; + + /** + * Set the state of viewer options, including sunlight, Street View, and historical imagery. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + * * GEPlugin.OPTION_STATE_DEFAULT + * * GEPlugin.OPTION_STATE_ENABLED + * * GEPlugin.OPTION_STATE_DISABLED + */ + getOption(type: GEViewerOptionsValueEnum): GEViewerOptionsValueEnum; + } + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + export class KmlOrientation extends KmlObject { + + /** + * Sets the heading, tilt, and roll of a model. + */ + set(heading: number, tilt: number, roll: number): void; + + /** + * Rotation about the z axis (normal to the Earth's surface). + * A value of 0 (the default) equals North. + * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. + */ + getHeading(): number; + + /** + * Rotation about the z axis (normal to the Earth's surface). + * A value of 0 (the default) equals North. + * A positive rotation is clockwise around the z axis and specified in degrees from 0 to 360. + */ + setHeading(heading: number): void; + + /** + * Rotation about the x axis. + * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. + */ + getTilt(): number; + + /** + * Rotation about the x axis. + * A positive rotation is clockwise around the x axis and specified in degrees from 0 to 360. + */ + setTilt(tilt: number): void; + + /** + * Rotation about the y axis. + * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. + */ + getRoll(): number; + + /** + * Rotation about the y axis. + * A positive rotation is clockwise around the y axis and specified in degrees from 0 to 360. + */ + setRoll(roll: number): void; + } + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + export class KmlLocation extends KmlObject { + + /** + * Sets the latitude, longitude, and altitude of the Model. + */ + setLatLngAlt(lat: number, lng: number, alt: number): void; + + /** + * Longitude of the Model's location. + * Angular distance in degrees, relative to the Prime Meridian. + * Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Longitude of the Model's location. + * Angular distance in degrees, relative to the Prime Meridian. + * Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Latitude of the camera location. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Latitude of the camera location. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Specifies the distance above the earth's surface. + */ + getAltitude(): number; + + /** + * Specifies the distance above the earth's surface. + */ + setAltitude(altitude: number): void; + } + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space. + */ + export class KmlScale extends KmlObject { + + /** + * Sets the x, y, and z coordinates for a model. + */ + set(x: number, y: number, z: number): void; + + /** + * Indicates the x coordinate. + */ + getX(): number; + + /** + * Indicates the x coordinate. + */ + setX(x: number): void; + + /** + * Indicates the y coordinate. + */ + getY(): number; + + /** + * Indicates the y coordinate. + */ + setY(y: number): void; + + /** + * Indicates the z coordinate. + */ + getZ(): number; + + /** + * Indicates the z coordinate. + */ + setZ(z: number): void; + } + + /** + * A single tuple consisting of floating point values for longitude, latitude, and altitude (in that order). + * Longitude and latitude values are in degrees. + * + * * longitude = -180 and <= 180 + * * latitude = -90 and = 90 + * * altitude values (optional) are in meters above sea level + */ + export class KmlCoord { + + /** + * Sets the latitude, longitude, altitude. + */ + setLatLngAlt(latitude: number, longitude: number, altitude: number): void; + + /** + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Distance from the earth's surface. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface. + */ + setAltitude(altitude: number): void; + } + + /** + * The KmlCoordArray object defines an array of coordinates. + */ + export class KmlCoordArray { + + /** + * Returns the coordinates at the given index. + */ + get(index: number): KmlCoord; + + /** + * Sets the coordinates at the given index.. + */ + set(index: number, coord: KmlCoord): void; + + /** + * Sets the latitude, longitude, and altitude. + */ + setLatLngAlt( + index: number, + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Appends one or more new elements to the end of an array and returns the new length of the array. + */ + pushLatLngAlt( + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Appends one or more new elements to the end of an array and returns the new length of the array. + */ + push(coordOrList: KmlCoord): void; + + /** + * Deletes the last element of an array, decrements the array length, and returns the value that is removed. + */ + pop(): KmlCoord; + + /** + * Adds an element or elements to the beginning of an array. + */ + unshift(coordOrList: KmlCoord): number; + + /** + * Adds an element or elements to the beginning of an array. + */ + unshiftLatLngAlt( + latitude: number, + longitude: number, + altitude: number + ): void; + + /** + * Removes and returns the first element of the array. + */ + shift(): KmlCoord; + + /** + * Reverses the order of the elements in the array. + */ + reverse(): void; + + /** + * Clears all of the elements in the array + */ + clear(): void; + + /** + * Specifies the length of the index array. + */ + getLength(): number; + } + + /** + * The object corresponding to the retangular region in which Google Earth is displayed. + */ + export class GEWindow extends GEEventEmitter { + + /** + * Gives the Google Earth object focus. + */ + focus(): void; + + /** + * Removes focus from the Google Earth object. + */ + blur(): void; + + /** + * Toggles the overall visibility of Google Earth inside the browser. + */ + getVisibility(): boolean; + + /** + * Toggles the overall visibility of Google Earth inside the browser. + */ + setVisibility(visibility: boolean): void; + } + + /** + * The GEGlobe class encapsulates the Google Earth globe to determine access and event behavior. + */ + export class GEGlobe extends KmlObject { + + /** + * Returns the altitude for a given location on the globe. + * If the altitude data for the location has not yet been loaded, the return value is 0. + */ + getGroundAltitude(lat: number, lon: number): number; + + /** + * The top-level features currently in the Earth instance. + */ + getFeatures(): GEFeatureContainer; + } + + /** + * Controls the behavior of the camera that views the scene in Google Earth. + */ + export class GEView { + + /** + * Returns the screen x,y coordinates of a given point on the globe. + * + * Tip: project() is the inverse of hitTest(). + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + project( + lat: number, + lng: number, + alt: number, + altitudeMode: KmlAltitudeModeEnum + ): KmlVec2; + + /** + * Sets the camera that views the scene in Google Earth. + */ + setAbstractView(view: KmlAbstractView): void; + + /** + * Creates and returns a new KmlLookAt object, initialized to the current camera position and orientation. + * Use 'altitudeMode' to specify the altitude mode of the looked-at point. + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + copyAsLookAt(altitudeMode: KmlAltitudeModeEnum): KmlLookAt; + + /** + * Creates and returns a new KmlCamera object, initialized to the current camera position and orientation. + * Use 'altitudeMode' to specify the altitude mode of the new camera. + * + * See also: + * + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + copyAsCamera(altitudeMode: KmlAltitudeModeEnum): KmlCamera; + + /** + * Returns a bounding box that completely contains the region of the globe that is currently visible. + * The returned box will be larger than what is strictly visible, if that is necessary to include everything that is visible. + */ + getViewportGlobeBounds(): KmlLatLonBox; + + /** + * Given a point on the screen in pixel coordinates, returns a GEHitTestResult with information about the geographic location corresponding to the point on the screen. + * Tip: hitTest() is the inverse of project(). + * + * See also: + * + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.HIT_TEST_GLOBE + * * GEPlugin.HIT_TEST_TERRAIN + * * GEPlugin.HIT_TEST_BUILDINGS + */ + hitTest( + x: number, + xUnits: KmlUnitsEnum, + y: number, + yUnits: KmlUnitsEnum, + mode: GEHitTestModeEnum + ): GEHitTestResult; + } + + /** + * Defines an image associated with an Icon style or overlay. + */ + export class KmlIcon extends KmlLink { + + /** + * Gets the offset from the left (), in pixels, of the icon. + */ + getX(): number; + + /** + * Specifies the icon's offset (), in pixels from the left side of its icon palette, if a palette has been specified in the element. + */ + setX(x: number): number; + + /** + * Gets the offset from the bottom (), in pixels, of the icon. + */ + getY(): number; + + /** + * Specifies the offset (), in pixels from the bottom of its icon palette, if a palette has been specified in the element. + */ + setY(y: number): void; + + /** + * Gets the width (), in pixels, of the icon. + */ + getW(): number; + + /** + * Specifies the width (), in pixels, of the icon to use. + */ + setW(w: number): void; + + /** + * Gets the height (), in pixels, of the icon. + */ + getH(): number; + + /** + * Specifies the height (), in pixels, of the icon to use. + */ + setH(h: number): void; + } + + /** + * Specifies the location of any KML files fetched by network links, image files used by icons in icon styles, ground overlays, and screen overlays, or model files used in the Model object. + */ + export class KmlLink extends KmlObject { + + /** + * A URL (either an HTTP address or a local file specification). + * When the parent of Link is a NetworkLink, href is a KML file. + * When the parent of Link is a Model, href is a COLLADA file. + * When the parent of Link is an Overlay, href is an image. + */ + getHref(): string; + + /** + * A URL (either an HTTP address or a local file specification). + * When the parent of Link is a NetworkLink, href is a KML file. + * When the parent of Link is a Model, href is a COLLADA file. + * When the parent of Link is an Overlay, href is an image. + */ + setHref(href: string): void; + + /** + * Specifies to use a time-based refresh mode. + * + * See also: + * + * * GEPlugin.REFRESH_ON_CHANGE + * * GEPlugin.REFRESH_ON_INTERVAL + * * GEPlugin.REFRESH_ON_EXPIRE + */ + getRefreshMode(): KmlRefreshModeEnum; + + /** + * Specifies to use a time-based refresh mode. + * + * See also: + * + * * GEPlugin.REFRESH_ON_CHANGE + * * GEPlugin.REFRESH_ON_INTERVAL + * * GEPlugin.REFRESH_ON_EXPIRE + */ + setRefreshMode(refreshMode: KmlRefreshModeEnum): void; + + /** + * Indicates to refresh the file every n seconds. + */ + getRefreshInterval(): number; + + /** + * Indicates to refresh the file every n seconds. + */ + setRefreshInterval(refreshInterval: number): void; + + /** + * Specifies how the link is refreshed when the viewport changes. + * + * See also: + * + * * GEPlugin.VIEW_REFRESH_NEVER + * * GEPlugin.VIEW_REFRESH_ON_STOP + * * GEPlugin.VIEW_REFRESH_ON_REGION + */ + getViewRefreshMode(): KmlViewRefreshModeEnum; + + /** + * Specifies how the link is refreshed when the viewport changes. + * + * See also: + * + * * GEPlugin.VIEW_REFRESH_NEVER + * * GEPlugin.VIEW_REFRESH_ON_STOP + * * GEPlugin.VIEW_REFRESH_ON_REGION + */ + setViewRefreshMode(viewRefreshMode: KmlViewRefreshModeEnum): void; + + /** + * Specifies how the link is refreshed when the camera changes. + */ + getViewRefreshTime(): number; + + /** + * Specifies how the link is refreshed when the camera changes. + */ + setViewRefreshTime(viewRefreshTime: number): void; + + /** + * Scales the BBOX parameters before sending them to the server. + * A value less than 1 specifies to use less than the full view (screen). + * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. + */ + getViewBoundScale(): number; + + /** + * Scales the BBOX parameters before sending them to the server. + * A value less than 1 specifies to use less than the full view (screen). + * A value greater than 1 specifies to fetch an area that extends beyond the edges of the current view. + */ + setViewBoundScale(viewBoundScale: number): void; + + /** + * Specifies the format of the query string that is appended to the Link's href before the file is fetched. + * (If the href specifies a local file, this element is ignored.) + */ + getViewFormat(): string; + + /** + * Specifies the format of the query string that is appended to the Link's href before the file is fetched. + * (If the href specifies a local file, this element is ignored.) + */ + setViewFormat(viewFormat: string): void; + } + + /** + * Controls time in the plugin. + */ + export class GETime { + + /** + * Set the plugin's clock rate. + * A value of 1 corresponds with real time; to pass one year in the plugin for every real second, set the rate to 31536000 (60 times 60 times 24 times 365). + */ + setRate(rate: number): void; + + /** + * Get the current plugin clock rate. + */ + getRate(): number; + + /** + * Returns the current computer clock time as a KmlTimeStamp object. + */ + getSystemTime(): KmlTimeStamp; + + /** + * Returns the GETimeControl object; this is the time slider. + */ + getControl(): GETimeControl; + + /** + * Whether or not historical imagery is enabled. + */ + getHistoricalImageryEnabled(): boolean; + + /** + * Turn historical imagery on or off. + * For more information, read the Time chapter of the Developer's Guide. + */ + setHistoricalImageryEnabled(historicalImageryEnabled: boolean): void; + + /** + * Get the current plugin time as a KmlTimeStamp or KmlTimeSpan. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Sets the current plugin time. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + } + + /** + * Used to manipulate the behavior of the Google Earth options such as, navigation, flyToSpeed, scroll wheel speed and so on. + */ + export class GEOptions { + + /** + * Sets the map type to Earth or sky mode. + */ + setMapType(type: GEMapTypeEnum): void; + + /** + * Speed of zoom when user rolls the mouse wheel. Default is 1. + * Set to a negative number to reverse the zoom direction. + */ + getScrollWheelZoomSpeed(): number; + + /** + * Speed of zoom when user rolls the mouse wheel. Default is 1. + * Set to a negative number to reverse the zoom direction. + */ + setScrollWheelZoomSpeed(scrollWheelZoomSpeed: number): void; + + /** + * Specifies the speed at which the camera moves (0 to 5.0). + * Set to SPEED_TELEPORT to immediately appear at selected destination. + * + * See also: + * + * * GEPlugin.SPEED_TELEPORT + */ + getFlyToSpeed(): number; + + /** + * Specifies the speed at which the camera moves (0 to 5.0). + * Set to SPEED_TELEPORT to immediately appear at selected destination. + * + * See also: + * + * * GEPlugin.SPEED_TELEPORT + */ + setFlyToSpeed(flyToSpeed: number): void; + + /** + * Show or hide the status bar. Disabled by default. + */ + getStatusBarVisibility(): boolean; + + /** + * Show or hide the status bar. Disabled by default. + */ + setStatusBarVisibility(statusBarVisibility: boolean): void; + + /** + * Show or hide the grid. Disabled by default. + */ + getGridVisibility(): boolean; + + /** + * Show or hide the grid. Disabled by default. + */ + setGridVisibility(gridVisibility: boolean): void; + + /** + * Show or hide the overview map. Disabled by default. + */ + getOverviewMapVisibility(): boolean; + + /** + * Show or hide the overview map. Disabled by default. + */ + setOverviewMapVisibility(overviewMapVisibility: boolean): void; + + /** + * Show or hide the scale legend. Disabled by default. + */ + getScaleLegendVisibility(): boolean; + + /** + * Show or hide the scale legend. Disabled by default. + */ + setScaleLegendVisibility(scaleLegendVisibility: boolean): void; + + /** + * Show or hide the blue atmosphere that appears around the perimeter of the Earth. + * On by default. + */ + getAtmosphereVisibility(): boolean; + + /** + * Show or hide the blue atmosphere that appears around the perimeter of the Earth. + * On by default. + */ + setAtmosphereVisibility(atmosphereVisibility: boolean): void; + + /** + * Enable or disable user panning and zooming of the map. Enabled by default. + * + * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). + */ + getMouseNavigationEnabled(): boolean; + + /** + * Enable or disable user panning and zooming of the map. Enabled by default. + * + * Note: This also enables and disables keyboard navigation (arrow keys, page-up/page-down, etc). + */ + setMouseNavigationEnabled(mouseNavigationEnabled: boolean): void; + + /** + * Returns true if the animation of features as they are added or removed from the globe has been enabled. + */ + getFadeInOutEnabled(): boolean; + + /** + * Enable or disable the animation of a feature when it is added or removed from the Google Earth plugin. + * The animation consists of a slight change of scale. Default is true. + */ + setFadeInOutEnabled(fadeInOutEnabled: boolean): void; + + /** + * Returns true if display units are set to imperial units (feet and miles). + * False denotes metric units (meters and kilometers). + */ + getUnitsFeetMiles(): boolean; + + /** + * Set display units to imperial (feet and miles) or metric (meters and kilometers). + * This setting affects only the values displayed in the status bar and the scale bar. + * The values passed and returned with an object's getters and setters are always metric. + */ + setUnitsFeetMiles(unitsFeetMiles: boolean): void; + + /** + * Enables or disables building selection. + * If enabled, clicking a building will pop a feature balloon containing information from the Google 3D Warehouse database. + */ + setBuildingSelectionEnabled(buildingSelectionEnabled: boolean): void; + + /** + * Whether or not building selection is enabled. + */ + getBuildingSelectionEnabled(): boolean; + + /** + * Returns true if building highlighting is enabled. + */ + getBuildingHighlightingEnabled(): boolean; + + /** + * Enables or disables building highlighting. + * When enabled, buildings will be highlighted when they are moused over. + */ + setBuildingHighlightingEnabled(buildingHighlightingEnabled: boolean): void; + + /** + * Returns the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. + */ + getTerrainExaggeration(): number; + + /** + * Set the terrain exaggeration value. Valid values are in the range of 1.0 through 3.0. + * Attempting to set outside of this range will result in the value being clamped. + */ + setTerrainExaggeration(terrainExaggeration: number): void; + + /** + * When enabled, the view will change to 'ground level view' when the camera reaches ground level. + * This view provides pan and lookAt controls, but no zoom slider. + * The tilt will be set to 90, or parallel with level ground. + */ + setAutoGroundLevelViewEnabled(autoGroundLevelViewEnabled: boolean): void; + + /** + * Whether automatic ground level view is enabled. + */ + getAutoGroundLevelViewEnabled(): boolean; + } + + /** + * Adds a node to the end of the list of children of a specified feature. + * Returns the appended object. + */ + export class GESchemaObjectContainer { + + /** + * Adds a node to the end of the list of children of a specified feature. + * Returns the appended object. + */ + appendChild(object: T): void; + + /** + * Removes a node from the list of children of a specified object. + */ + removeChild(oldChild: T): void; + + /** + * Inserts a child before the referenced child in the list of objects. + */ + insertBefore(newChild: T, refChild: T): void; + + /** + * Replaces existing child in the list of features. + * Returns the old child. + */ + replaceChild(newChild: T, oldChild: T): void; + + /** + * Returns true if the container is not empty. + */ + hasChildNodes(): boolean; + + /** + * First child in the list of objects. + */ + getFirstChild(): T; + + /** + * Last child in the list of objects. + */ + getLastChild(): T; + + /** + * List of features (for KmlContainer), or list of features, styles, and schemas (for KmlDocument). + * Returns true if there are any child nodes. + */ + getChildNodes(): KmlObjectList; + } + + /** + * A container class that holds one or more features and allows the creation of nested hierarchies. + */ + export class GEFeatureContainer extends GESchemaObjectContainer {} + + /** + * A container object that contains an array of geometries, typically the children of a multi-geometry. + */ + export class GEGeometryContainer extends GESchemaObjectContainer {} + + /** + * A container object that contains an array of closed line strings, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + * A Polygon can contain multiple LinearRing objects used as inner boundaries. + */ + export class GELinearRingContainer extends GESchemaObjectContainer {} + + /** + * A container that holds a collection of KmlStyle and KmlStyleMap objects. + * The KmlStyleMap object selects a style based on the current mode of the Placemark. + * An object derived from KmlStyleSelector is uniquely identified by its ID and its URL. + */ + export class GEStyleSelectorContainer extends GESchemaObjectContainer {} + + /** + * Defines the x and y coordinates of a 2D vector. + */ + export class KmlVec2 { + + /** + * Sets the coordinates of the vector. + */ + set( + x: number, + xUnits: KmlUnitsEnum, + y: number, + yUnits: KmlUnitsEnum + ): void; + + /** + * Indicates the x coordinate. + */ + getX(): number; + + /** + * Indicates the x coordinate. + */ + setX(x: number): void; + + /** + * Indicates the y coordinate. + */ + getY(): number; + + /** + * Indicates the y coordinate. + */ + setY(y: number): void; + + /** + * Units in which the x value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + */ + getXUnits(): KmlUnitsEnum; + + /** + * Units in which the x value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIXELS + * * GEPlugin.UNITS_INSET_PIXELS + */ + setXUnits(xUnits: KmlUnitsEnum): void; + + /** + * Units in which the y value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIyELS + * * GEPlugin.UNITS_INSET_PIyELS + */ + getYUnits(): KmlUnitsEnum; + + /** + * Units in which the y value is specified. + * + * See also: + * + * * GEPlugin.UNITS_FRACTION + * * GEPlugin.UNITS_PIyELS + * * GEPlugin.UNITS_INSET_PIyELS + */ + setYUnits(xUnits: KmlUnitsEnum): void; + } + + /** + * The GESun class controls the dawn to dusk views. + */ + export class GESun { + + /** + * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. + * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. + */ + getVisibility(): boolean; + + /** + * Specifies whether the feature is drawn in the 3D viewer when it is initially loaded. + * In order for a feature to be visible, the visibility property and all of its ancestors must also be set to 1. + */ + setVisibility(visibility: boolean): void; + } + + /** + * The KmlColor object values are expressed in hexadecimal notation. + * The range of values for any one color component is 0 to 255 (00 to ff). + * For alpha, 00 is fully transparent and ff is fully opaque. + * The order of expression is aabbggrr, where aa=alpha (00 to ff); bb=blue (00 to ff); gg=green (00 to ff); rr=red (00 to ff). + * For example, if you want to apply a blue color with 50 percent opacity to an overlay, + * you would specify the following when setting color value: 7fff0000, where alpha=0x7f, blue=0xff, green=0x00, and red=0x00. + */ + export class KmlColor { + + /** + * Set the color of an object. + */ + set(color: string): void; + + /** + * Returns the color of an object. + */ + get(): string; + + /** + * red numerical value + */ + getR(): number; + + /** + * red numerical value + */ + setR(r: number): void; + + /** + * green numerical value + */ + getG(): number; + + /** + * green numerical value + */ + setG(g: number): void; + + /** + * blue numerical value + */ + getB(): number; + + /** + * blue numerical value + */ + setB(b: number): void; + + /** + * opacity value + */ + getA(): number; + + /** + * opacity value + */ + setA(a: number): void; + } + + /** + * The event object used with all KMLObjects. + * For more information about events, see the Document Object Model Events specification at http: + */ + export class KmlEvent { + + /** + * Cancels the default action of the event. + * For example, calling this method in a placemark click handler prevents the placemark's default balloon from popping up. + */ + preventDefault(): void; + + /** + * Prevents event propagation. + * For example, if click event handlers are set up on both the GEGlobe and GEWindow objects, + * and stopPropagation is called in the GEGlobe click event handler, the GEWindow event handler will not be triggered when the globe is clicked. + */ + stopPropagation(): void; + + /** + * The object to which the KMLEvent was originally dispatched. + */ + getTarget(): GEEventEmitter; + + /** + * The target whose event listeners are currently being processed. + */ + getCurrentTarget: GEEventEmitter; + + /** + * The current stage of the flow of events. + */ + getEventPhase(): GEEventPhaseEnum; + + /** + * Indicates whether or not an event is a bubbling event. + */ + getBubbles(): boolean; + + /** + * Indicates whether the event can be cancelled. + * + * Note: Currently, cancelable has no effect. + */ + getCancelable(): boolean; + } + + /** + * Represents a mouse input event. + */ + export class KmlMouseEvent extends KmlEvent { + + /** + * The button on the mouse was pressed. + * Possible values include 0, 1, 2, where 0 is left, 1 is middle, and 2 is right mouse key. + */ + getButton(): number; + + /** + * The x coordinate at which the event occurred, measured in pixels from the left edge of the plug-in window. + */ + getClientX(): number; + + /** + * The y coordinate at which the event occurred, measured in pixels from the top edge of the plug-in window. + */ + getClientY(): number; + + /** + * The x coordinate at which the event occurred, measured in pixels from the left edge of the computer screen. + */ + getScreenX(): number; + + /** + * The y coordinate at which the event occurred, measured in pixels from the top edge of the computer screen. + */ + getScreenY(): number; + + /** + * The latitude at which the event occurred, in decimal degrees. + */ + getLatitude(): number; + + /** + * The longitude at which the event occurred, in decimal degrees. + */ + getLongitude(): number; + + /** + * The altitude at which the event occurred, in meters. + */ + getAltitude(): number; + + /** + * Indicates whether a mouse action occurred while on the Google Earth globe. + */ + getDidHitGlobe(): boolean; + + /** + * Indicates whether the ALT key was held down when an event occurred. + */ + getAltKey(): boolean; + + /** + * Indicates whether the CTRL key was held down when an event occurred. + */ + getCtrlKey(): boolean; + + /** + * Indicates whether the SHIFT key was held down when an event occurred. + */ + getShiftKey(): boolean; + + /** + * Used with the mouseover and mouseout events to specify a secondary target. + * For mouseover, it specifies the object that the mouse was over. + * For mouseout, it specifies the new object that the mouse is over. + */ + getRelatedTarget(): GEEventEmitter; + + /** + * Returns the timestamp of the event, in Unix time. + */ + getTimeStamp(): number; + } + + /** + * Defines when and how an event gets passed in and triggered from the Google Earth Plug-in. + */ + export class GEEventEmitter { + + /** + * Triggers an event when the user clicks a location in Google Earth with the mouse. + */ + click(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user double clicks a location in Google Earth with the mouse. + */ + dblclick(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse pointer over a location in Google Earth. + */ + mouseover(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user presses the mouse button over a location in Google Earth. + */ + mousedown(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user releases the mouse button over a location in Google Earth. + */ + mouseup(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse off of the object in Google Earth. + */ + mouseout(event: KmlMouseEvent): void; + + /** + * Triggers an event when the user moves the mouse inside Google Earth. + */ + mousemove(event: KmlMouseEvent): void; + } + + /** + * The base class for all the other objects in the Google Earth Plug-in. + * The methods and behavior of KMLObject are inherited by all other objects. + * This is an abstract base class and cannot be used directly. + * It provides the id attribute, which allows unique identification of an object. + */ + export class KmlObject extends GEEventEmitter { + + /** + * The interface name (i.e. 'KmlPlacemark') of the object. + */ + getType(): string; + + /** + * Test whether this object is the same as another object. + * Useful for Chrome and Safari, where the comparison a==b sometimes fails for plugin objects. + */ + equals(compareTo: KmlObject): boolean; + + /** + * The unique ID of the KML object. + */ + getId(): string; + + /** + * The unique URL of the KML object. + * This is the base address joined with the ID using the # character. + * + * For example: http://www.google.com/bar.kml#atlantis + */ + getUrl(): string; + + /** + * The parent node of the KML object. + */ + getParentNode(): KmlObject; + + /** + * The document that owns the KML object. + */ + getOwnerDocument(): KmlDocument; + + /** + * Permanently deletes an object, allowing its ID to be reused. + * Attempting to access the object once it is released will result in an error. + */ + release(): void; + } + + /** + * A collection of KmlObjects. + */ + export class KmlObjectList { + + /** + * Gets an item from the object list. For example, list.item(0) returns the first object in the list. + */ + item(index: number): T; + + /** + * Number of objects in collection. + */ + getLength(): number; + } + + /** + * The base class for KmlStyle and KmlStyleMap. + */ + export class KmlStyleSelector extends KmlObject {} + + /** + * Defines the icon, label, line, list, polygon, and balloon styles. + */ + export class KmlStyle extends KmlStyleSelector { + + /** + * Specifies how icons for point placemarks are drawn in Google Earth. + */ + getIconStyle(): KmlIconStyle; + + /** + * Specifies how the name of a feature is drawn in the 3D viewer. + * A custom color, color mode, and scale for the label (name) can be specified. + */ + getLabelStyle(): KmlLabelStyle; + + /** + * Specifies the drawing style (color, color mode, and line width) for line geometry. + * Line geometry includes the outlines of outlined polygons and the extruded tether of Placemark icons (if extrusion is enabled). + */ + getLineStyle(): KmlLineStyle; + + /** + * Specifies the style for list geometry. + */ + getListStyle(): KmlListStyle; + + /** + * Specifies the drawing style for polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). + */ + getPolyStyle(): KmlPolyStyle; + + /** + * Specifies the drawing style for balloons. + */ + getBalloonStyle(): KmlBalloonStyle; + } + + /** + * The KmlColorStyle object is an abstract object. + * It specifies the color and color mode of extended style types. + */ + export class KmlColorStyle extends KmlObject { + + /** + * Color and opacity (alpha) values. + */ + getColor(): KmlColor; + + /** + * Specifies which color mode effect to apply to the base color. + * + * See also: + * + * * GEPlugin.COLOR_NORMAL + * * GEPlugin.COLOR_INHERIT + * * GEPlugin.COLOR_RANDOM + */ + getColorMode(): KmlColorModeEnum; + + /** + * Specifies which color mode effect to apply to the base color. + * + * See also: + * + * * GEPlugin.COLOR_NORMAL + * * GEPlugin.COLOR_INHERIT + * * GEPlugin.COLOR_RANDOM + */ + setColorMode(colorMode: KmlColorModeEnum): void; + } + + /** + * Specifies how icons for point placemarks are drawn in Google Earth. + * The icon property specifies the icon image. + * The scale property specifies the x, y scaling of the icon. + * The color specified in the color property of KmlIconStyle is blended with the color of the Icon. + */ + export class KmlIconStyle extends KmlColorStyle { + + /** + * Resizes the icon. + */ + getScale(): number; + + /** + * Resizes the icon. + */ + setScale(scale: number): void; + + /** + * The direction that icons are set to point, clockwise, and in degrees. + */ + getHeading(): number; + + /** + * The direction that icons are set to point, clockwise, and in degrees. + */ + setHeading(heading: number): void; + + /** + * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. + */ + getIcon(): KmlIcon; + + /** + * A custom Icon. In KmlIconStyle, the only child element of KmlIcon is href and href is an HTTP address or a local file specification used to load an icon. + */ + setIcon(icon: KmlIcon): void; + + /** + * Specifies the position within the Icon that is anchored to the point specified in the placemark. + * The x and y values can be specified in three different ways: as pixels, as fractions of the icon, or as inset pixels, which is an offset in pixels from the upper right corner of the icon. + * The x and y positions can be specified in different ways. + * For example, x can be in pixels and y can be a fraction. + * The origin of the coordinate system is in the lower left corner of the icon. + */ + getHotSpot(): KmlVec2; + } + + /** + * Specifies how the name of a feature is drawn in the 3D viewer. + * A custom color, color mode, and scale for the label (name) can be specified. + */ + export class KmlLabelStyle extends KmlColorStyle { + + /** + * Resizes the label. + */ + getScale(): number; + + /** + * Resizes the label. + */ + setScale(scale: number): void; + } + + /** + * The KmlLineStyle object specifies the drawing style (color, color mode, and line width) for all line geometry. + * Line geometry includes the outlines of outlined polygons and the extruded "tether" of Placemark icons (if extrusion is enabled). + */ + export class KmlLineStyle extends KmlColorStyle { + + /** + * Width of the line, in pixels. + */ + getWidth(): number; + + /** + * Width of the line, in pixels. + */ + setWidth(width: number): void; + } + + /** + * Specifies the drawing style for all polygons, including polygon extrusions (which look like the walls of buildings) and line extrusions (which look like solid fences). + */ + export class KmlPolyStyle extends KmlColorStyle { + + /** + * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). + */ + getFill(): boolean; + + /** + * Specifies whether or not to fill the polygon. Possible values 1 (fill) and 0 (no fill). + */ + setFill(fill: boolean): void; + + /** + * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. + */ + getOutline(): boolean; + + /** + * Specifies whether to outline the polygon. Polygon outlines use the current KmlLineStyle. + */ + setOutline(outline: boolean): void; + } + + /** + * Specifies how a feature is displayed in the list view. + */ + export class KmlListStyle extends KmlObject { + + /** + * Background color for the Snippet. + */ + getBgColor(): KmlColor; + + /** + * Maximum number of lines of text for the Snippet. + */ + getMaxSnippetLines(): number; + + /** + * Maximum number of lines of text for the Snippet. + */ + setMaxSnippetLines(maxSnippetLines: number): void; + + /** + * Specifies how a feature should be displayed in a list view. + */ + getListItemType(): KmlListItemTypeEnum; + } + + /** + * Specifies how the description balloon for placemarks is drawn. + */ + export class KmlBalloonStyle extends KmlObject { + + /** + * Background color of the balloon (optional). + */ + getBgColor(): KmlColor; + + /** + * Foreground color for text. The default is black (ff000000). + */ + getTextColor(): KmlColor; + + /** + * The text contained in the balloon. + */ + getText(): string; + + /** + * The text contained in the balloon. + */ + setText(text: string): void; + } + + /** + * Specifies the top, bottom, right, and left sides of a bounding box on the Earth's surface. + */ + export class KmlLatLonBox extends KmlObject { + + /** + * Sets the north, south, east, and west edges of the bounding box, as well as the rotation of the overlay. + */ + setBox( + north: number, + south: number, + east: number, + west: number, + rotation: number + ): void; + + /** + * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. + */ + getNorth(): number; + + /** + * Specifies the latitude of the north edge of the bounding box, in decimal degrees from -90 to 90. + */ + setNorth(north: number): void; + + /** + * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. + */ + getSouth(): number; + + /** + * Specifies the latitude of the south edge of the bounding box, in decimal degrees from -90 to 90. + */ + setSouth(south: number): void; + + /** + * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + getEast(): number; + + /** + * Specifies the longitude of the east edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + setEast(east: number): void; + + /** + * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + getWest(): number; + + /** + * Specifies the longitude of the west edge of the bounding box, in decimal degrees from -180 to 180. + * (For overlays that overlap the meridian of 180 degrees longitude, values can extend beyond that range.) + */ + setWest(west: number): void; + + /** + * Specifies a rotation of the overlay about its center, in degrees. + * Values can be +/-180. The default is 0 (north). + * Rotations are specified in a counterclockwise direction. + */ + getRotation(): number; + + /** + * Specifies a rotation of the overlay about its center, in degrees. + * Values can be +/-180. The default is 0 (north). + * Rotations are specified in a counterclockwise direction. + */ + setRotation(rotation: number): void; + } + + /** + * Specifies a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + export class KmlLatLonAltBox extends KmlLatLonBox { + + /** + * Sets the north, south, east, west, rotation, minAltitude, maxAltitude, and altitudeMode of bounding box. + */ + setAltBox( + north: number, + south: number, + east: number, + west: number, + rotation: number, + minAltitude: number, + maxAltitude: number, + altitudeMode: KmlAltitudeModeEnum + ): void; + + /** + * Minimum altitude, specified in meters above sea level. + */ + getMinAltitude(): number; + + /** + * Minimum altitude, specified in meters above sea level. + */ + setMinAltitude(minAltitude: number): void; + + /** + * Maximim altitude, specified in meters above sea level. + */ + getMaxAltitude(): number; + + /** + * Maximim altitude, specified in meters above sea level. + */ + setMaxAltitude(maxAltitude: number): void; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how the altitude property is interpreted. + * + * See also: + * + * * GEPlugin.ALTITUDE_CLAMP_TO_GROUND + * * GEPlugin.ALTITUDE_RELATIVE_TO_GROUND + * * GEPlugin.ALTITUDE_ABSOLUTE + * * GEPlugin.ALTITUDE_CLAMP_TO_SEA_FLOOR + * * GEPlugin.ALTITUDE_RELATIVE_TO_SEA_FLOOR + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): number; + } + + /** + * The KmlLod or level of detail, describes the size of the projected region on the screen that is required in order for the region to be considered active. + * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + export class KmlLod extends KmlObject { + + /** + * Sets the minLodPixels, maxLodPixels, minFadeExtent, and maxFadeExtent for the projected region on the screen. + */ + set( + minLodPixels: number, + maxLodPixels: number, + minFadeExtent: number, + maxFadeExtent: number + ): void; + + /** + * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. + * Google Earth calculates the size of the region when projected onto screen space. + * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). + * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. + * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. + */ + getMinLodPixels(): number; + + /** + * Specifies measurement in screen pixels that represents the minimum limit of the visibility range for a given Region. + * Google Earth calculates the size of the region when projected onto screen space. + * Then it computes the square root of the region's area (if, for example, the Region is square and the viewpoint is directly above the Region, and the Region is not tilted, this measurement is equal to the width of the projected Region). + * If this measurement falls within the limits defined by minLodPixels and maxLodPixels (and if the LatLonAltBox is in view), the region is active. + * If this limit is not reached, the associated geometry is considered to be too far from the user's viewpoint to be drawn. + */ + setMinLodPixels(minLodPixels: number): void; + + /** + * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. + * A value of -1, the default, indicates "active to infinite size." + */ + getMaxLodPixels(): number; + + /** + * Measurement in screen pixels that represents the maximum limit of the visibility range for a given Region. + * A value of -1, the default, indicates "active to infinite size." + */ + setMaxLodPixels(maxLogPixels: number): void; + + /** + * Distance over which the geometry fades, from fully opaque to fully transparent. + * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. + */ + getMinFadeExtent(): number; + + /** + * Distance over which the geometry fades, from fully opaque to fully transparent. + * This ramp value, expressed in screen pixels, is applied at the minimum end of the LOD (visibility) limits. + */ + setMinFadeExtent(minFadeExtent: number): void; + + /** + * Distance over which the geometry fades, from fully transparent to fully opaque. + * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. + */ + getMaxFadeExtent(): number; + + /** + * Distance over which the geometry fades, from fully transparent to fully opaque. + * This ramp value, expressed in screen pixels, is applied at the maximum end of the LOD (visibility) limits. + */ + setMaxFadeExtent(maxFadeExtent: number): void; + } + + /** + * The KmlRegion object is used to set region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + * In addition, a Region contains an LOD (level of detail) extent that defines a validity range of the associated Region in terms of projected screen size. + * A Region is said to be "active" when the bounding box is within the user's view and the LOD requirements are met. + * Objects associated with a Region are drawn only when the Region is active. + * When the viewRefreshMode is onRegion, the Link or Icon is loaded only when the Region is active. + */ + export class KmlRegion extends KmlObject { + + /** + * Sets the latLonAltBox and lod for the region. + */ + set(latLonAltBox: KmlLatLonAltBox, lod: KmlLod): void; + + /** + * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + getLatLonAltBox(): KmlLatLonAltBox; + + /** + * A bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + setLatLonAltBox(latLonAltBox: KmlLatLonAltBox): void; + + /** + * LOD is an abbreviation for Level of Detail. + * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. + * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + getLod(): KmlLod; + + /** + * LOD is an abbreviation for Level of Detail. + * Lod describes the size of the projected region on the screen that is required in order for the region to be considered "active. + * " Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + setLod(lod: KmlLod): void; + } + + /** + * Represents a specific point in time. + * The plugin accepts time in this format only; it does not accept JavaScript date or time objects. + */ + export class KmlDateTime { + + /** + * Set the date. Accepts only XML Schema time (see XML Schema Part 2: Datatypes Second Edition). + * The value can be expressed as yyyy-mm-ddThh:mm:sszzzzzz, where T is the separator between the date and the time, + * and the time zone is either Z(for UTC) or zzzzzz, which represents +/-hh:mm in relation to UTC. + * Additionally, the value can be expressed as a date only. + */ + set(date: string): void; + + /** + * Returns the date and time in XML Schema time format. + */ + get(): string; + } + + /** + * An abstract object and cannot be used directly in a JavaScript file. + * This element is extended by the TimeSpan and TimeStamp objects. + */ + export class KmlTimePrimitive extends KmlObject {} + + /** + * Represents a single moment in time. + * This is a simple element and contains no children. + * Its value is a dateTime, specified in XML time. + * The precision of the TimeStamp is dictated by the dateTime value in the when property. + */ + export class KmlTimeStamp extends KmlTimePrimitive { + + /** + * Represents a single moment in time. + * This is a simple element and contains no children. + * Its value is a dateTime, specified in XML time. + * The precision of the TimeStamp is dictated by the dateTime value in the when property. + * + * * dateTime gives second resolution + * * date gives day resolution + * * gYearMonth gives month resolution + * * gYear gives year resolution + */ + getWhen(): KmlDateTime; + } + + /** + * Represents an extent in time bounded by begin and end dateTimes. + */ + export class KmlTimeSpan extends KmlTimePrimitive { + + /** + * Describes the beginning instant of a time period. + * If absent, the beginning of the period is unbounded. + */ + getBegin(): KmlDateTime; + + /** + * Describes the ending instant of a time period. + * If absent, the end of the period is unbounded. + */ + getEnd(): KmlDateTime; + } + + /** + * This is an abstract class and cannot be created directly. + * This class is extended by KmlCamera and KmlLookAt. + */ + export class KmlAbstractView extends KmlObject { + + /** + * Creates a new KmlLookAt object that matches as closely as possible this KmlAbstractView. + * KmlLookAt is unable to represent roll, so roll values in the current view will not be passed to the new KmlLookAt object. + * + * If this view is already a KmlLookAt, this function returns a new KmlLookAt representing the same view. + */ + copyAsLookAt(): KmlLookAt; + + /** + * Creates a new KmlCamera object that matches this KmlAbstractView. + * + * If this view is already a KmlCamera, this function returns a new KmlCamera representing the same view. + */ + copyAsCamera(): KmlCamera; + + /** + * Returns the KmlTimeStamp or KmlTimeSpan object associated with this view. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Associate a KmlTimeStamp or KmlTimeSpan object with this view. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + + /** + * Returns the viewer options on the current view. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + */ + getViewerOptions(): KmlViewerOptions; + + /** + * Sets the viewer options on the current view. + * + * See also: + * + * * GEPlugin.OPTION_STREET_VIEW + * * GEPlugin.OPTION_SUNLIGHT + * * GEPlugin.OPTION_HISTORICAL_IMAGERY + */ + setViewerOptions(viewerOptions: KmlViewerOptions): void; + } + + /** + * Defines a camera that is associated with anything derived from feature. + * The LookAt element positions the "camera" in relation to the object that is being viewed. + * This class either positions the relative to a feature, or you can manually change the view, using ge.getView().setAbstractView(). + */ + export class KmlLookAt extends KmlAbstractView { + + /** + * Sets the latitude, longitude, altitude, altitudeMode, heading, tilt, and range for the camera. + */ + set ( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + heading: number, + tilt: number, + range: number + ): void; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLatitude(): number; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLatitude(latitude: number): void; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + getLongitude(): number; + + /** + * Latitude of the point the camera is looking at. + * Degrees north or south of the Equator (0 degrees). + * Values range from -90 degrees (South Pole) to 90 degrees (North Pole). + */ + setLongitude(longitude: number): void; + + /** + * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. + */ + getRange(): number; + + /** + * The distance in meters from the point specified by longitude, latitude, and altitude for the LookAt position. + */ + setRange(range: number): void; + + /** + * Angle between the direction of the LookAt position and the normal to the surface of the earth. + * Values range from 0 to 90 degrees. Values for tilt cannot be negative. + * A tilt value of 0 degrees indicates viewing from directly above. + * A tilt value of 90 degrees indicates viewing along the horizon. + */ + getTilt(): number; + + /** + * Angle between the direction of the LookAt position and the normal to the surface of the earth. + * Values range from 0 to 90 degrees. Values for tilt cannot be negative. + * A tilt value of 0 degrees indicates viewing from directly above. + * A tilt value of 90 degrees indicates viewing along the horizon. + */ + setTilt(tilt: number): void; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + getHeading(): number; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + setHeading(heading: number): void; + + /** + * Distance from the earth's surface, in meters. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface, in meters. + */ + setAltitude(altitude: number): void; + + /** + * Specifies how altitude components in the coordinates element are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the coordinates element are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * Defines the camera that views the scene. + * This element defines the position of the camera relative to the Earth's surface as well as the viewing direction of the camera. + * The camera position is defined by longitude, latitude, altitude, and altitudeMode. + * The viewing direction of the camera is defined by heading, tilt, and roll. + * Camera can be a child element of any feature. + */ + export class KmlCamera extends KmlAbstractView { + + /** + * Sets the latitude, longitude, altitude, alitudeMode, heading, tilt, and roll values. + */ + set( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + heading: number, + tilt: number, + roll: number + ): void; + + /** + * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. + */ + getLatitude(): number; + + /** + * Latitude of the camera location. Degrees north or south of the Equator (0 degrees). Values range from -90 degrees to 90 degrees. + */ + setLatitude(latitude: number): void; + + /** + * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + getLongitude(): number; + + /** + * Longitude of the camera location. Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. + * Values east of the Meridian range from 0 to 180 degrees. + */ + setLongitude(longitude: number): void; + + /** + * Distance from the earth's surface. + */ + getAltitude(): number; + + /** + * Distance from the earth's surface. + */ + setAltitude(altitude: number): void; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + getHeading(): number; + + /** + * Direction (that is, North, South, East, West), in degrees. Default=0 (North). Values range from 0 to 360 degrees. + */ + setHeading(heading: number): void; + + /** + * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. + * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. + */ + getTilt(): number; + + /** + * Angle between the direction of the camera position and the normal to the surface of the earth. Values range from 0 to 360 degrees. + * A tilt value of 0 degrees indicates viewing from directly above, 90 degrees indicates viewing along the horizon, and 180 degrees indicates viewing straight up at the sky. + */ + setTilt(tilt: number): void; + + /** + * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. + */ + getRoll(): number; + + /** + * Rotation, in degrees, of the camera around the Z axis. Values range from -180 to +180 degrees. + */ + setRoll(roll: number): void; + + /** + * Specifies how altitude components in the coordinates are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the coordinates are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * The KmlGeometry object is an abstract object and cannot be used directly. + * It provides a placeholder object for all derived Geometry objects. + */ + export class KmlGeometry extends KmlObject {} + + /** + * Specifies an AltitudeMode for derived classes. + */ + export class KmlAltitudeGeometry extends KmlGeometry { + + /** + * Specifies how altitude components in the geometry coordinates are interpreted. + */ + getAltitudeMode(): KmlAltitudeModeEnum; + + /** + * Specifies how altitude components in the geometry coordinates are interpreted. + */ + setAltitudeMode(altitudeMode: KmlAltitudeModeEnum): void; + } + + /** + * A 3D object described in a referenced COLLADA file. + * COLLADA files have a .dae file extension. + * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. + * Google Earth supports the COLLADA common profile, with the following exceptions: + * + * * Google Earth supports only triangles and lines as primitive types. The maximum number of triangles allowed is 21845. + * * Google Earth does not support animation or skinning. + * * Google Earth does not support external geometry references. + */ + export class KmlModel extends KmlAltitudeGeometry { + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + getLocation(): KmlLocation; + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + setLocation(location: KmlLocation): void; + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + getOrientation(): KmlOrientation; + + /** + * Describes rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + setOrientation(orientation: KmlOrientation): void; + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space + */ + getScale(): KmlScale; + + /** + * Scales a model along the x, y, and z axes in the model's coordinate space + */ + setScale(scale: KmlScale): void; + + /** + * Returns the link of the collada model. + */ + getLink(): KmlLink; + + /** + * Sets the link of the collada model. + */ + setLink(link: KmlLink): void; + } + + /** + * A container for zero or more geometry primitives associated with the same feature. + */ + export class KmlMultiGeometry extends KmlGeometry { + + /** + * The collection of geometries that are children of this multi-geometry. + */ + getGeometries(): GEGeometryContainer; + } + + /** + * Specifies the behavior of the object's geometry. + */ + export class KmlExtrudableGeometry extends KmlAltitudeGeometry { + + /** + * Specifies whether to connect the geometry to the ground. + */ + getExtrude(): boolean; + + /** + * Specifies whether to connect the geometry to the ground. + */ + setExtrude(extrude: boolean): void; + + /** + * Specifies whether to allow the geometry to follow the terrain elevation. + */ + getTessellate(): boolean; + + /** + * Specifies whether to allow the geometry to follow the terrain elevation. + */ + setTessellate(tessellate: boolean): void; + } + + /** + * A Polygon is defined by an outer boundary and 0 or more inner boundaries. + * The boundaries, in turn, are defined by LinearRings. + * When a Polygon is extruded, its boundaries are connected to the ground to form additional polygons, which gives the appearance of a building or a box. + * Extruded Polygons use PolyStyle for their color, color mode, and fill. + */ + export class KmlPolygon extends KmlExtrudableGeometry { + + /** + * Contains a LinearRing element. + */ + getOuterBoundary(): KmlLinearRing; + + /** + * Contains a LinearRing element. + */ + setOuterBoundary(outerBoundary: KmlLinearRing): void; + + /** + * Contains a LinearRing element. + * You can specify multiple innerBoundary properties, which create multiple cut-outs inside the Polygon. + */ + getInnerBoundaries(): GELinearRingContainer; + } + + /** + * A geographic location defined by longitude, latitude, and (optional) altitude. + * When a Point is contained by a Placemark, the point itself determines the position of the Placemark's name and icon. + * When a Point is extruded, it is connected to the ground with a line. This tether uses the current LineStyle. + */ + export class KmlPoint extends KmlExtrudableGeometry { + + /** + * Sets altitudeMode, extrude, tessellate, latitude, longitude, and altitude values. + */ + set( + latitude: number, + longitude: number, + altitude: number, + altitudeMode: KmlAltitudeModeEnum, + extrude: boolean, + tessellate: boolean + ): void; + + /** + * Sets the latitude and longitude. + */ + setLatLng(latitude: number, longitude: number): void; + + /** + * Sets the latitude, longitude, and altitide. + */ + setLatLngAlt(latitude: number, longitude: number, altitude: number): void; + + /** + * The point's latitude, in degrees. + */ + getLatitude(): number; + + /** + * The point's latitude, in degrees. + */ + setLatitude(latitude: number): void; + + /** + * The point's longitude, in degrees. + */ + getLongitude(): number; + + /** + * The point's longitude, in degrees. + */ + setLongitude(longitude: number): void; + + /** + * The point's altitude, in meters. + */ + getAltitude(): number; + + /** + * The point's altitude, in meters. + */ + setAltitude(altitude: number): void; + } + + /** + * Defines a connected set of line segments. + * Use KmlLineStyle to specify the color, color mode, and width of the line. + * When a LineString is extruded, the line is extended to the ground, forming a polygon that looks somewhat like a wall or fence. + * For extruded LineStrings, the line itself uses the current LineStyle, and the extrusion uses the current PolyStyle. + */ + export class KmlLineString extends KmlExtrudableGeometry { + + /** + * Two or more coordinate tuples, each consisting of floating point values for longitude, latitude, and altitude. + * The altitude component is optional. + */ + getCoordinates(): KmlCoordArray; + + /** + * Added to the altitude values for all points on the line string. + * Adjusts the altitude of the feature as a whole, without the need to update each coordinate set. + */ + setAltitudeOffset(altitudeOffset: number): void; + + /** + * Returns the altitudeOffset, or 0 if not set. + */ + getAltitudeOffset(): number; + } + + /** + * Defines a closed line string, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + * A Polygon can contain multiple LinearRing elements used as inner boundaries. + * You do not need to connect the first and last points. + */ + export class KmlLinearRing extends KmlLineString {} + + + /** + * The KmlFeature object is an abstract object and is the base for all feature types (for example Placemarks, Overlays, and NetworkLinks). + */ + export class KmlFeature extends KmlObject { + + /** + * Retrieves the contents of the feature's element. + * The retrieved contents are scrubbed to remove JavaScript; CSS; and iframe, embed, and object tags. + * + * It should be safe to insert the resulting HTML into your page without concern for malicious content embedded in the feature data; + * however any feature depending on CSS or Javascript will not work. + */ + getBalloonHtml(): string; + + /** + * Retrieves the contents of the feature's element. The contents are not scrubbed. + * Use this method only if you trust the source of the feature data. + */ + getBalloonHtmlUnsafe(): string; + + /** + * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). + */ + getName(): string; + + /** + * User-defined text displayed in the plugin as the label for the object (for example, for a Placemark). + */ + setName(name: string): void; + + /** + * Specifies whether the feature is drawn in the plugin. + * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. + * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. + */ + getVisibility(): boolean; + + /** + * Specifies whether the feature is drawn in the plugin. + * In order for a feature to be visible, the visibility of all its ancestors must also be set to true. + * In the Google Earth List View, each feature has a checkbox that allows the user to control visibility of the feature. + */ + setVisibility(visibility: boolean): void; + + /** + * Default state of left panel. + */ + getOpen(): boolean; + + /** + * Default state of left panel. + */ + setOpen(open: boolean): void; + + /** + * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. + */ + getAddress(): string; + + /** + * Specifies a value representing an unstructured address written as a standard street, city, state address, and/or as a postal code. + */ + setAddress(address: string): void; + + /** + * Specifies a short description of the feature. + */ + getSnippet(): string; + + /** + * Specifies a short description of the feature. + */ + setSnippet(snippet: string): void; + + /** + * User-supplied text that appears in the description balloon. + */ + getDescription(): string; + + /** + * User-supplied text that appears in the description balloon. + */ + setDescription(description: string): void; + + /** + * Stores either the lookAt or camera view. + */ + getAbstractView(): KmlAbstractView; + + /** + * Stores either the lookAt or camera view. + */ + setAbstractView(abstractView: KmlAbstractView): void; + + /** + * URI of a Style or StyleMap defined in a Document. + * It refers to a Plug-in intitiated object. + */ + getStyleUrl(): string; + + /** + * URI of a Style or StyleMap defined in a Document. + * It refers to a Plug-in intitiated object. + */ + setStyleUrl(styleUrl: string): void; + + /** + * The style based on the current mode of the Placemark. + */ + getStyleSelector(): KmlStyleSelector; + + /** + * The style based on the current mode of the Placemark. + */ + setStyleSelector(styleSelector: KmlStyleSelector): void; + + /** + * Specifies region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + */ + getRegion(): KmlRegion; + + /** + * Specifies region objects and their properties. + * A region contains a bounding box (LatLonAltBox) that describes an area of interest defined by geographic coordinates and altitudes. + */ + setRegion(region: KmlRegion): void; + + /** + * Returns the KML for a feature. + */ + getKml(): string; + + /** + * Returns previous sibling node within the container. + */ + getPreviousSibling(): KmlFeature; + + /** + * Returns the next sibling node within the container. + */ + getNextSibling(): KmlFeature; + + /** + * Returns the KmlTimeStamp or KmlTimeSpan object associated with this feature. + */ + getTimePrimitive(): KmlTimePrimitive; + + /** + * Attach a KmlTimeStamp or KmlTimeSpan object to this feature. + */ + setTimePrimitive(timePrimitive: KmlTimePrimitive): void; + + /** + * Returns the computed style of a feature, merging any inline styles with styles imported from setHref() or a StyleUrl. + * + * Note: Modifying the returned KmlStyle object is undefined and not recommended. + */ + getComputedStyle(): KmlStyle; + + /** + * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. + * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). + * The opacity of a folder or document will influence the opacity of child features. + * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. + */ + getOpacity(): number; + + /** + * Experimental Feature — this is an experimental feature and can change (or even be removed) at any time. + * The opacity of a feature, ranging from 0 (completely transparent) to 1 (complete opaque). + * The opacity of a folder or document will influence the opacity of child features. + * Thus, if a folder has an opacity of 0.5 and a child ground overlay in the folder also has an opacity of 0.5, the overlay will be drawn with an opacity of 0.25. + */ + setOpacity(opacity: number): void; + } + + /** + * An abstract object and cannot be used directly. + * A KmlContainer object holds one or more features and allows the creation of nested hierarchies. + */ + export class KmlContainer extends KmlFeature { + + /** + * Get an element by ID. + * This is functionally equivalent to getElementByUrl with an unspecified base URL. + * + * For example: getElementByUrl('#foo'). + * + * Usage is when finding objects created with JavaScript, which have unspecified base URLs. + * The object must be a descendant of the container before it can be found. + */ + getElementById(id: string): KmlObject; + + /** + * Get an element by URL. A URL consists of the base address and ID, joined with the # character. + * + * For example: http://www.google.com/bar.kml#here_be_monsters + * + * This applies to objects that are fetched. + * In the case of plugin created objects, the URL is simply #foo. + * The object must be a descendant of the container before it can be found. + */ + getElementByUrl(url: string): KmlObject; + + /** + * Get an element by type. + */ + getElementsByType(type: string): KmlObjectList; + + /** + * A collection of features, such as name, description, and so on. + */ + getFeatures(): GEFeatureContainer; + } + + /** + * A Folder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). + * A feature is visible only if it and all of its ancestors are visible. + */ + export class KmlFolder extends KmlContainer {} + + /** + * A layer displayed in Google Earth. + */ + export class KmlLayer extends KmlFolder {} + + /** + * A container for the various layers displayed with the Google Earth Plug-in. + * It contains the same layers as Google Earth. + */ + export class KmlLayerRoot extends KmlFolder { + + /** + * Returns the layer based on the layer's ID. + */ + getLayerById(id: string): KmlLayer; + + /** + * Enables a layer based on its ID. + */ + enableLayerById(id: string, visibility: boolean): void; + + /** + * Returns the drawing order for this database. + */ + getDrawOrder(): number; + + /** + * Defines the drawing order for databases. + * Drawing order is lowest to highest. + * Google Earth Enterprise customers can add a side database and set the drawOrder to be either before or after that of the main database. + * Side databases default to a drawing order of 0. + */ + setDrawOrder(drawOrder: number): void; + } + + /** + * A KmlDocument has containers that holds features and styles. + * This container is required if you use shared styles. + * It is recommended that you use shared styles, which require the following. + * + * 1. Define all Styles in a Document. Assign a unique ID to each Style. + * 2. Within a given feature or StyleMap, reference the Style's ID using a styleUrl element. + * + * Note: Shared styles are not inherited by the features in the Document. + */ + export class KmlDocument extends KmlContainer { + + /** + * Returns a list of elements using a particular style URL. + */ + getElementsByStyleUrl(styleUrl: string): KmlObjectList; + + /** + * Returns an array containing the style selectors present in the KML document. + */ + getStyleSelectors(): GEStyleSelectorContainer; + } + + /** + * The KmlPlacemark is a feature with associated Geometry. + */ + export class KmlPlacemark extends KmlFeature { + + /** + * The geometry associated with the placemark. + */ + getGeometry(): KmlGeometry; + + /** + * The geometry associated with the placemark. + */ + setGeometry(geometry: KmlGeometry): void; + } + + /** + * The base class for the three types of balloon windows that can overlay the 3D window. + */ + export class GEAbstractBalloon { + + /** + * The ID of the balloon. + */ + getId(): string; + + /** + * The ID of the balloon. + */ + setId(id: string): void; + + /** + * Determines what the balloon is attached to. + */ + getFeature(): KmlFeature; + + /** + * Determines what the balloon is attached to. + */ + setFeature(feature: KmlFeature): void; + + /** + * Minimum width of the balloon. + */ + getMinWidth(): number; + + /** + * Minimum width of the balloon. + */ + setMinWidth(minWidth: number): void; + + /** + * Minimum height of the balloon. + */ + getMinHeight(): number; + + /** + * Minimum height of the balloon. + */ + setMinHeight(minHeight: number): void; + + /** + * Maximum width of the balloon. + */ + getMaxWidth(): number; + + /** + * Maximum width of the balloon. + */ + setMaxWidth(maxWidth: number): void; + + /** + * Maximum height of the balloon. + */ + getMaxHeight(): number; + + /** + * Maximum height of the balloon. + */ + setMaxHeight(maxHeight: number): void; + + /** + * When true, the balloon frame is displayed with a button that the user + * can click to close the balloon. When false, the balloon frame is just + * a plain frame. + * + * Default is true. + */ + getCloseButtonEnabled(): boolean; + + /** + * When true, the balloon frame is displayed with a button that the user + * can click to close the balloon. When false, the balloon frame is just + * a plain frame. + * + * Default is true. + */ + setCloseButtonEnabled(closeButtonEnabled: boolean): void; + } + + /** + * Base class for GEHtmlStringBalloon and GEHtmlDivBalloon. + */ + export class GEFeatureBalloon extends GEAbstractBalloon {} + + /** + * Creates a balloon that contains HTML. + */ + export class GEHtmlBalloon extends GEAbstractBalloon { + + /** + * The color of the text in the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, it is interpreted as #000000. + */ + getForegroundColor(): string; + + /** + * The color of the text in the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, it is interpreted as #000000. + */ + setForegroundColor(foregroundColor: string): void; + + /** + * The background color of the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, the default is interpreted as #FFFFFF. + */ + getBackgroundColor(): string; + + /** + * The background color of the balloon. + * This must be set using the HTML hex format #RRGGBB. + * If not set, the default is interpreted as #FFFFFF. + */ + setBackgroundColor(backgroundColor: string): void; + } + + /** + * The GEHtmlDivBalloon object creates a balloon based on the contentDiv property. + */ + export class GEHtmlDivBalloon extends GEHtmlBalloon { + + /** + * An HTMLDivElement to be used as the contents of the balloon. + * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. + * You can manipulate this balloon using ordinary HTML DOM techniques. + */ + getContentDiv(): HTMLDivElement; + + /** + * An HTMLDivElement to be used as the contents of the balloon. + * When the balloon is shown, the HTMLDivElement is attached to the balloon element in the web page. + * You can manipulate this balloon using ordinary HTML DOM techniques. + */ + setContentDiv(contentDiv: HTMLElement): void; + } + + /** + * The GEHtmlStringBalloon class represents a balloon based on the contentString. + */ + export class GEHtmlStringBalloon extends GEHtmlBalloon { + + /** + * You can include any HTML using the contentString property. + * When the balloon is visible, the content specified in contentString property, + * is inserted directly into the balloon element in the web page. + */ + getContentString(): string; + + /** + * You can include any HTML using the contentString property. + * When the balloon is visible, the content specified in contentString property, + * is inserted directly into the balloon element in the web page. + */ + setContentString(contentString: string): void; + } + + /** + * The base class for GETimeControl. + */ + export class GEControl {} + + /** + * Represents the time slider object. + */ + export class GETimeControl extends GEControl { + + /** + * Whether the time slider is visible or not. + */ + getVisibility(): GEVisibilityEnum; + + /** + * Specifies whether the control is visible or hidden. + */ + setVisibility(visibility: GEVisibilityEnum): void; + + /** + * Returns the clock rate that the plugin would use, if the play button on the time slider UI was pressed. + * This rate is calculated by the plugin based on the time range currently present in the slider. + */ + getCalculatedRate(): number; + + /** + * Returns a KmlTimeSpan object encompassing the earliest and latest times present in the time slider. + * For more information, refer to the Time chapter of the Developer's Guide. + */ + getExtents(): KmlTimeSpan; + + /** + * Returns an array containing the KmlTimeStamp objects associated with the historical imagery available in this view. + */ + getAvailableImageDates(): KmlObjectList; + + } + + /** + * The GEPlugin is the Google Earth Plugin's main object, and this is the object that is returned to the JavaScript application when you first create a plug-in instance. + * GEPlugin provides factory methods for ructing other objects (placemarks, and so on), and is also used to retrieve the root document objects. + */ + export class GEPlugin { + + /** + * A Specifies that altitudes are at ground level. For Ground overlays, this means that the image will be draped over the terrain. + */ + ALTITUDE_CLAMP_TO_GROUND: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above or below ground level (i.e. the elevation of the terrain at the location). + */ + ALTITUDE_RELATIVE_TO_GROUND: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above or below sea level, regardless of the actual elevation of the terrain beneath the object. + * For example, if you set the altitude of an object to 10 meters with an absolute altitude mode, the object will appear to be at ground level if the terrain beneath is also 10 meters above sea level. + * If the terrain is 3 meters above sea level, the object will appear elevated above the terrain by 7 meters. + * If, on the other hand, the terrain is 15 meters above sea level, the object may be completely invisible. + */ + ALTITUDE_ABSOLUTE: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are at sea floor level. + */ + ALTITUDE_CLAMP_TO_SEA_FLOOR: KmlAltitudeModeEnum; + + /** + * Specifies that altitudes are to be interpreted as meters above sea floor (i.e. the elevation of the sea floor at the location). + */ + ALTITUDE_RELATIVE_TO_SEA_FLOOR: KmlAltitudeModeEnum; + + /** + * Refresh when the file is loaded and whenever the Link parameters change. This refresh mode is the default. + */ + REFRESH_ON_CHANGE: KmlRefreshModeEnum; + + /** + * Refresh every n seconds (specified in refreshInterval). + */ + REFRESH_ON_INTERVAL: KmlRefreshModeEnum; + + /** + * Refresh when the expiration time is reached. + * If a fetched file has a NetworkLinkControl, the expires time takes precedence over expiration times specified in HTTP headers. + * If no expires time is specified, the HTTP max-age header is used (if present). + * If max-age is not present, the Expires HTTP header is used (if present). + */ + REFRESH_ON_EXPIRE: KmlRefreshModeEnum; + + /** + * Ignore changes in the view. Also ignore viewFormat parameters, if any. + * This view refresh mode is the default. + */ + VIEW_REFRESH_NEVER: KmlViewRefreshModeEnum; + + /** + * Refresh the file only when the user explicitly requests it. + */ + VIEW_REFRESH_ON_REQUEST: KmlViewRefreshModeEnum; + + /** + * Refresh n seconds after movement stops, where n is specified in viewRefreshTime. + */ + VIEW_REFRESH_ON_STOP: KmlViewRefreshModeEnum; + + /** + * Refresh only when the feature's Region becomes active. + */ + VIEW_REFRESH_ON_REGION: KmlViewRefreshModeEnum; + + /** + * Screen coordinates are to be interpreted as a fraction of an item, like an image or Google Earth window. + */ + UNITS_FRACTION: KmlUnitsEnum; + + /** + * Screen coordinates are to be interpreted as pixels from the left or bottom edge. + */ + UNITS_PIXELS: KmlUnitsEnum; + + /** + * Screen coordinates are to be interpreted as pixels from the top or right edge. + */ + UNITS_INSET_PIXELS: KmlUnitsEnum; + + /** + * Apply no color mode effect, i.e. use the base color as is. + */ + COLOR_NORMAL: KmlColorModeEnum; + + /** + * Apply a random linear scale to the base color. See the KML documentation for more details. + */ + COLOR_RANDOM: KmlColorModeEnum; + + /** + * Inherit the color mode from ancestor styles. + */ + COLOR_INHERIT: KmlColorModeEnum; + + /** + * The Earth map type, used with GEOptions' setMapType. + */ + MAP_TYPE_EARTH: GEMapTypeEnum; + + /** + * The Sky map type, used with GEOptions' setMapType. + */ + MAP_TYPE_SKY: GEMapTypeEnum; + + /** + * Hide the UI element. + */ + VISIBILITY_HIDE: GEVisibilityEnum; + + /** + * Show the UI element always. + */ + VISIBILITY_SHOW: GEVisibilityEnum; + + /** + * Automatically show or hide the UI element depending on user interaction. + */ + VISIBILITY_AUTO: GEVisibilityEnum; + + /** + * Specifies that fly-to should happen immediately, without a smooth transition. + */ + SPEED_TELEPORT: number; + + /** + * The Layer ID of the terrain layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_TERRAIN: string; + + /** + * The Layer ID of the roads layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_ROADS: string; + + /** + * The Layer ID of the photorealistic buildings layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_BUILDINGS: string; + + /** + * The Layer ID of the low resolution (gray) buildings layer. + * Use as an argument to getLayerById() or enableLayerById(). + * Note that as photorealistic buildings continue to be created and added to the LAYER_BUILDINGS layer, the low-resolution version of those buildings will be removed from this layer. + * This layer will therefore change over time. + */ + LAYER_BUILDINGS_LOW_RESOLUTION: string; + + /** + * The Layer ID of the borders layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_BORDERS: string; + + /** + * The Layer ID of the trees layer. Use as an argument to getLayerById() or enableLayerById(). + */ + LAYER_TREES: string; + + /** + * When using the GEView.hitTest method, this mode samples the globe (the earth's sphere at altitude 0, without terrain or buildings). + */ + HIT_TEST_GLOBE: GEHitTestModeEnum; + + /** + * When using the GEView.hitTest method, this mode samples the earth's terrain (the ground surface, including variations in altitude). + */ + HIT_TEST_TERRAIN: GEHitTestModeEnum; + + /** + * When using the GEView.hitTest method, this mode samples 3D buildings. + */ + HIT_TEST_BUILDINGS: GEHitTestModeEnum; + + /** + * Sets the render state to its default value. Currently, sunlight, Street View, and historical imagery all default to a disabled state. + */ + OPTION_STATE_DEFAULT: GEViewerOptionsValueEnum; + + /** + * Set the render state to on. Passed to the KmlViewerOptions.setOption method. + */ + OPTION_STATE_ENABLED: GEViewerOptionsValueEnum; + + /** + * Set the render state to off. Passed to the KmlViewerOptions.setOption method. + */ + OPTION_STATE_DISABLED: GEViewerOptionsValueEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether the Sun option should be visible. + * Sun can also be enabled/disabled with GEPlugin.getSun. + */ + OPTION_SUNLIGHT: GEViewerOptionsTypeEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether historical imagery should be enabled. + */ + OPTION_HISTORICAL_IMAGERY: GEViewerOptionsTypeEnum; + + /** + * Passed to the KmlViewerOptions.setOption method, along with a GEViewerOptionsValueEnum, to specify whether Street View should be enabled when the view reaches ground level. + * Note that this applies only to programmatic movement, such as fly-tos; to control whether the user can enter Street View using manual navigation controls, call ge.getPlugin().streetViewEnabled(true). + */ + OPTION_STREET_VIEW: GEViewerOptionsTypeEnum; + + /** + * The feature's visibility is tied to its list item's checkbox state. + */ + LIST_ITEM_CHECK: KmlListItemTypeEnum; + + /** + * When specified for a folder, document or network link, prevents all items from being made visible at once—that is, the user can turn all children off but cannot turn them all on at the same time. + * This setting is useful for containers or network links containing large amounts of data. + */ + LIST_ITEM_CHECK_OFF_ONLY: KmlListItemTypeEnum; + + /** + * Use a normal checkbox for visibility but do not display children in a list view. + * The item's checkbox should allows the user to toggle visibility of the child objects in the viewport. + */ + LIST_ITEM_CHECK_HIDE_CHILDREN: KmlListItemTypeEnum; + + /** + * When specified for a container (a folder or a document), only one of the container's items should be visible at a time. + */ + LIST_ITEM_RADIO_FOLDER: KmlListItemTypeEnum; + + /** + * The large navigation control type, used with GENavigationControl.setControlType(). + */ + NAVIGATION_CONTROL_LARGE: GENavigationControlEnum; + + /** + * The small navigation control type, used with GENavigationControl.setControlType(). + */ + NAVIGATION_CONTROL_SMALL: GENavigationControlEnum; + + /** + * Parse a string of KML and return a handle to the root of the KML object structure that was created. + */ + parseKml(kml: string): KmlObject; + + /** + * Get an element by ID. This is functionally equivalent to getElementByUrl with an unspecified base URL. + * + * For example: getElementByUrl('#foo'). + * + * Usage is when finding objects created with JavaScript, which have unspecified base URLs. + * The object must be a descendant of the DOM before it can be found. + */ + getElementById(id: string): KmlObject; + + /** + * Get an element by URL. A URL consists of the base address and the ID, joined with the # character. + * + * For example: http://www.google.com/bar.kml#here_be_monsters + * + * This applies to objects that are fetched. + * In the case of plugin created objects, the URL is simply #foo. + * The object must be a descendant of the DOM before it can be found. + */ + getElementByUrl(url: string): KmlObject; + + /** + * Get a list of elements by type. + */ + getElementsByType(): KmlObjectList; + + /** + * Creates a placemark on the globe. + * A Placemark is a feature with associated Geometry. + * A Placemark with a Point has an icon associated with it that marks a point on the Earth in the 3D viewer. + * (In the Google Earth 3D viewer, a Point Placemark is the only object you can click or roll over. + * Other Geometry objects do not have an icon in the 3D viewer. + * To allow the user to click in the 3D viewer, you would need to create a MultiGeometry object that contains both a Point and the other Geometry object.) + */ + createPlacemark(id: string): KmlPlacemark; + + /** + * Creates a point on the globe. Specifies the geographic location defined by longitude, latitude, and (optional) altitude. + */ + createPoint(id: string): KmlPoint; + + /** + * Creates a line string on Google Earth. + */ + createLineString(id: string): KmlLineString; + + /** + * Creates a folder. + * A KMLFolder is used to arrange other features hierarchically (Folders, Placemarks, NetworkLinks, or Overlays). + * A feature is visible only if it and all its ancestors are visible. + */ + createFolder(id: string): KmlFolder; + + /** + * Creates level of detail (LOD). + * LOD describes the size of the projected region on the screen that is required in order for the region to be considered active. + * Also specifies the size of the pixel ramp used for fading in (from transparent to opaque) and fading out (from opaque to transparent). + */ + createLod(id: string): KmlLod; + + /** + * Creates a LatLonBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createLatLonBox(id: string): KmlLatLonBox; + + /** + * Creates a LatLonAltBox, a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createLatLonAltBox(id: string): KmlLatLonAltBox; + + /** + * Creates a Document. A Document is a container for features and styles. + */ + createDocument(id: string): KmlDocument; + + /** + * Creates a Region in Google Earth. + * A Region contains a bounding box that describes an area of interest defined by geographic coordinates and altitudes. + */ + createRegion(id: string): KmlRegion; + + /** + * Specifies the exact coordinates of the Model's origin in latitude, longitude, and altitude. + * Latitude and longitude measurements are standard lat-lon projection with WGS84 datum. + * Altitude is distance above the earth's surface, in meters, and is interpreted according to altitudeMode. + */ + createLocation(id: string): KmlLocation; + + /** + * Sets the rotation of a 3D model's coordinate system to position the object in Google Earth. + */ + createOrientation(id: string): KmlOrientation; + + /** + * Sets the scale of a model along the x, y, and z axes in the model's coordinate space. + */ + createScale(id: string): KmlScale; + + /** + * Creates a model. + * A model is a 3D object described in a COLLADA file. + * COLLADA files have a .dae file extension. + * Models are created in their own coordinate space and then located, positioned, and scaled in Google Earth. + */ + createModel(id: string): KmlModel; + + /** + * A Style defines an addressable style group that can be referenced by StyleMaps and features. + */ + createStyle(id: string): KmlStyle; + + /** + * Creates a LinearRing. + * A LinearRing defines a closed line string, typically the outer boundary of a Polygon. + * Optionally, a LinearRing can also be used as the inner boundary of a Polygon to create holes in the Polygon. + */ + createLinearRing(id: string): KmlLinearRing; + + /** + * Creates a Polygon. A Polygon is defined by an outer boundary and 0 or more inner boundaries. + */ + createPolygon(id: string): KmlPolygon; + + /** + * Creates an Icon. An icon defines an image associated with an Icon style or overlay. + */ + createIcon(id: string): KmlIcon; + + /** + * Creates a Link. + * A Link specifies the location of KML files fetched by network links, image files used in any overlay, or model files used with the Model object. + */ + createLink(id: string): KmlLink; + + /** + * Creates a GroundOverlay. + * A GroundOverlay draws an image overlay draped onto the terrain. + */ + createGroundOverlay(id: string): KmlGroundOverlay; + + /** + * Creates a NetworkLink. + * A NetworkLink references a KML file or KMZ archive on a local or remote network. + */ + createNetworkLink(id: string): KmlNetworkLink; + + /** + * Creates a ScreenOverlay. + * A ScreenOverlay draws an image overlay fixed to the screen. + */ + createScreenOverlay(id: string): KmlScreenOverlay; + + /** + * Creates a container for one or more geometry primitives associated with the same feature. + */ + createMultiGeometry(id: string): KmlMultiGeometry; + + /** + * Creates a StyleMap. + * A StyleMap maps between two different icon styles. + * Typically, a StyleMap is used to provide separate normal and highlighted styles for a Placemark, so that the highlighted version appears when the user mouses over the icon in Google Earth. + */ + createStyleMap(id: string): KmlStyleMap; + + /** + * Creates a new LookAt. + * A LookAt element positions the camera view in relation to an object that is being viewed. + */ + createLookAt(id: string): KmlLookAt; + + /** + * Creates a new Camera. + * This element positions the camera relative to the Earth's surface and defines the view direction. + */ + createCamera(id: string): KmlCamera; + + /** + * Creates a new viewer options object. + */ + createViewerOptions(id: string): KmlViewerOptions; + + /** + * Create a KmlTimeStamp object. + * For more information, refer to the Time chapter of the Google Earth API developer's guide. + */ + createTimeStamp(id: string): KmlTimeStamp; + + /** + * Create a KmlTimeSpan object. + * For more information, refer to the Time chapter of the Google Earth API developer's guide. + */ + createTimeSpan(id: string): KmlTimeSpan; + + /** + * Creates a Feature balloon. + */ + createFeatureBalloon(id: string): GEFeatureBalloon; + + /** + * Creates an HTML string balloon. + */ + createHtmlStringBalloon(id: string): GEHtmlStringBalloon; + + /** + * Creates an Html Div Balloon. + */ + createHtmlDivBalloon(id: string): GEHtmlDivBalloon; + + /** + * Returns the currently active balloon, or null. + */ + getBalloon(): GEAbstractBalloon; + + /** + * Sets the given balloon as the active balloon, replacing any existing active balloon. + * If the given feature is visible, then the balloon is displayed. Otherwise, the balloon is hidden. + * + * If the argument is null, then any existing active balloon will be hidden. + */ + setBalloon(newActiveBalloon: GEAbstractBalloon): void; + + /** + * Used for debugging purposes; if this value is not equal to the value returned by getPluginVersion then there is a misconfiguration on the end user's system. + * This check is automatically done during plugin instantiation. + */ + getEarthVersion(): string; + + /** + * The version of the Google Earth Plug-in installed on the end user's machine. + */ + getPluginVersion(): string; + + /** + * The options used to manipulate the behavior of the Google Earth plugin. + */ + getOptions(): GEOptions; + + /** + * The time class used to manipulate the behavior of the Google Earth plugin time. + */ + getTime(): GETime; + + /** + * Controls the window options. + */ + getWindow(): GEWindow; + + /** + * Controls the globe behavior. + */ + getGlobe(): GEGlobe; + + /** + * Displays the dawn to dusk views. + */ + getSun(): GESun; + + /** + * Controls built-in layer behavior. + */ + getLayerRoot(): KmlLayerRoot; + + /** + * Controls the plugin viewport. + */ + getView(): GEView; + + /** + * Controls the navigation controls on the globe. + */ + getNavigationControl(): GENavigationControl; + + /** + * The top-level features currently in the Earth object. + */ + getFeatures(): GEFeatureContainer; + + /** + * Exposes functionality for interacting with KML tours. + */ + getTourPlayer(): GETourPlayer; + + /** + * Exposes functionality for interacting with photo overlays. + */ + getPhotoOverlayViewer(): GEPhotoOverlayViewer; + + /** + * Returns a number between 0 and 100 (inclusive) that indicates the progress of the streaming of imagery for the current view. + * + * A value of 100 means that the imagery is completely streamed in. + */ + getStreamingPercent(): number; + } + +} diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 0c551fd712..0aef3b74a6 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -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; diff --git a/graphlib/graphlib-tests.ts b/graphlib/graphlib-tests.ts new file mode 100644 index 0000000000..ff9268ab0f --- /dev/null +++ b/graphlib/graphlib-tests.ts @@ -0,0 +1,24 @@ +/// + +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); +} diff --git a/graphlib/graphlib.d.ts b/graphlib/graphlib.d.ts new file mode 100644 index 0000000000..1f017d5383 --- /dev/null +++ b/graphlib/graphlib.d.ts @@ -0,0 +1,291 @@ +// Type definitions for graphlib 2.1.1 +// Project: https://github.com/cpettitt/graphlib +// Definitions by: Dan Vanderkam +// 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[]; + } +} diff --git a/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts new file mode 100644 index 0000000000..fd7a053ce6 --- /dev/null +++ b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts @@ -0,0 +1,36 @@ +/// +/// + +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')); +}); \ No newline at end of file diff --git a/gulp-angular-templatecache/gulp-angular-templatecache.d.ts b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts new file mode 100644 index 0000000000..34e52acc36 --- /dev/null +++ b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts @@ -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 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +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; +} \ No newline at end of file diff --git a/gulp-rename/gulp-rename-tests.ts b/gulp-rename/gulp-rename-tests.ts index 6b204a36d9..b27f0f5ba9 100644 --- a/gulp-rename/gulp-rename-tests.ts +++ b/gulp-rename/gulp-rename-tests.ts @@ -3,6 +3,9 @@ import gulp = require("gulp"); import rename = require("gulp-rename"); +// Test that new import syntax works +import * as newRename from 'gulp-rename'; + // rename via string gulp.src("./src/main/text/hello.txt") .pipe(rename("main/text/ciao/goodbye.md")) @@ -26,4 +29,4 @@ gulp.src("./src/main/text/hello.txt", { base: process.cwd() }) suffix: "-hola", extname: ".md" })) - .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md \ No newline at end of file + .pipe(gulp.dest("./dist")); // ./dist/main/text/ciao/bonjour-aloha-hola.md diff --git a/gulp-rename/gulp-rename.d.ts b/gulp-rename/gulp-rename.d.ts index 11368e9698..4c68aecde7 100644 --- a/gulp-rename/gulp-rename.d.ts +++ b/gulp-rename/gulp-rename.d.ts @@ -20,5 +20,12 @@ declare module "gulp-rename" { function rename(name: string): NodeJS.ReadWriteStream; function rename(callback: (path: ParsedPath) => any): NodeJS.ReadWriteStream; function rename(opts: Options): NodeJS.ReadWriteStream; + + /** + * This is required as per: + * https://github.com/Microsoft/TypeScript/issues/5073 + */ + namespace rename {} + export = rename; -} \ No newline at end of file +} diff --git a/gulp-uglify/gulp-uglify-tests.ts b/gulp-uglify/gulp-uglify-tests.ts index 01cfb06f9e..6a1cf1281d 100644 --- a/gulp-uglify/gulp-uglify-tests.ts +++ b/gulp-uglify/gulp-uglify-tests.ts @@ -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 diff --git a/gulp-uglify/gulp-uglify.d.ts b/gulp-uglify/gulp-uglify.d.ts index 13eda63706..60cd8f11ea 100644 --- a/gulp-uglify/gulp-uglify.d.ts +++ b/gulp-uglify/gulp-uglify.d.ts @@ -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); } } diff --git a/gulp/gulp.d.ts b/gulp/gulp.d.ts index 74968ddcc5..f4314bd2f2 100644 --- a/gulp/gulp.d.ts +++ b/gulp/gulp.d.ts @@ -5,9 +5,11 @@ /// /// +/// 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 */ diff --git a/halfred/halfred-tests.ts b/halfred/halfred-tests.ts new file mode 100644 index 0000000000..3aecf39962 --- /dev/null +++ b/halfred/halfred-tests.ts @@ -0,0 +1,13 @@ +/// + +// run test with: $ tsc --noImplicitAny --target es6 --module commonjs halfred-tests.ts +import { parse } from 'halfred'; // require('halfred'); +let resource = parse({foo: "bar", "_links": { "self": { href: "fooo" }}}); +console.log(resource); + +let allLinks = resource.allLinks(); +for (let key in allLinks) { + let link = allLinks[key]; + + console.log(link[0].href); +} diff --git a/halfred/halfred.d.ts b/halfred/halfred.d.ts new file mode 100644 index 0000000000..9c1d571a9d --- /dev/null +++ b/halfred/halfred.d.ts @@ -0,0 +1,247 @@ +// Type definitions for Halfred v1.0.0 +// Project: https://github.com/basti1302/halfred +// Definitions by: David Herges +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "halfred" { + + /** + * halfred.parse(object) returns a Resource object. + * + * @see https://github.com/basti1302/halfred#usage + */ + export function parse(object: any): Resource; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function enableValidation(flag: boolean): void; + + /** @see https://github.com/basti1302/halfred#enabledisable-validation */ + export function disableValidation(): void; + + /** @see https://github.com/basti1302/halfred#resource-api */ + export interface Resource { + + /** + * Returns an object which has an array for each link that was present in the source object. + * See below why each link is represented as an array. + */ + allLinkArrays(): LinkCollection; + + /** Alias for allLinkArrays() */ + allLinks(): LinkCollection; + + /** + * Returns the array of links for the given key, or null if there are no links for this key. + */ + linkArray(key: string): Link[]; + + /** + * Returns the first element of the array of links for the given key or null if there are no + * links for this key. + */ + link(key: string): Link; + + /** + * Returns an object which has an array for each embedded resource that was present in the + * source object. + * See below why each embedded resource is represented as an array. Each element of any of + * this arrays is in turn a Resource object. + */ + allEmbeddedResourceArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedArrays(): ResourceCollection; + + /** Alias for allEmbeddedResourceArrays() */ + allEmbeddedResources(): ResourceCollection; + + /** + * Returns the array of embedded resources for the given key, or null if there are no embedded + * resources for this key. Each element of this arrays is in turn a Resource object. + */ + embeddedResourceArray(key: string): Resource[]; + + /** Alias for embeddedResourceArray() */ + embeddedArray(key: string): Resource[]; + + /** + * Returns the first element of the array of embedded resources for the given key or null if + * there are no embedded resources for this key. The returend object is a Resource object. + */ + embeddedResource(key: string): Resource; + + /** Alias for embeddedResource(key) */ + embedded(key: string): Resource; + + /** + * Returns the unmodified, original object that was parsed to this resource. This is rather + * uninteresting for the source object you give to the parse method (because you probably + * still have a reference to the source object) but it is a convenient way to get the part of + * the source object that corresponds to an embedded resource. + */ + original(): any; + + /** + * Returns true if the resource has any CURIEs (Compact URIs). + * + * @see http://www.w3.org/TR/2010/NOTE-curie-20101216/ + */ + hasCuries(): boolean; + + /** + * Returns the array of CURIEs. Each object in the array is a link object, which means it + * can be templated etc. See below for the link object API. + */ + curieArray(): Link[]; + + /** + * Returns the curie with the given name, if any. The returned object is a link object, which + * means it can be templated etc. See below for link object API. + */ + curie(name: string): Link; + + /** + * Returns the compact URI for the given full URL, if any + */ + reverseResolveCurie(fullUrl: string): string; + + /** + * Returns all validation issues. Validation issues are only gathered if validation has been + * turned on by calling ``halfred.enableValidation()`` before calling ``halfred.parse``. + */ + validationIssues(): any; + + /** + * Alias for validationIssues() + */ + validation(): any; + + /* + XX ... think we should NOT try to represent these things in TypeScript. + + In addition to the methods mentioned here, resource has all properties of the source object. + This is also true for embedded Resource objects. The non-HAL properties (that is, any + property except _links and _embedded) are copied over to the Resource object. This is always + a shallow copy, so modifying the a non-HAL property in the Resource object might also alter + the source object and vice versa. + + The Resource object also has the properties _links and _embedded but they might differ from + the _links/_embedded properties in the source object (Halfred applies some normalization to + them). These are not intended to be accessed by clients directly, instead, use the provided + methods to work with links and embedded resources. + */ + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface ResourceCollection { + [key: string]: Resource[]; + } + + /** @see https://github.com/basti1302/halfred#links-and-embedded-resources */ + interface LinkCollection { + [rel: string]: Link[] + } + + /** + * A Link Object represents a hyperlink from the containing resource to a URI. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5 + */ + interface Link { + + /** + * The "href" property is REQUIRED. + * + * Its value is either a URI [RFC3986] or a URI Template [RFC6570]. + * + * If the value is a URI Template then the Link Object SHOULD have a + * "templated" attribute whose value is true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.1 + */ + href: string; + + /** + * The "templated" property is OPTIONAL. + * + * Its value is boolean and SHOULD be true when the Link Object's "href" + * property is a URI Template. + * + * Its value SHOULD be considered false if it is undefined or any other + * value than true. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.2 + */ + templated?: boolean; + + /** + * The "type" property is OPTIONAL. + * + * Its value is a string used as a hint to indicate the media type + * expected when dereferencing the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.3 + */ + type?: string; + + /** + * The "deprecation" property is OPTIONAL. + * + * Its presence indicates that the link is to be deprecated (i.e. + * removed) at a future date. Its value is a URL that SHOULD provide + * further information about the deprecation. + * + * A client SHOULD provide some notification (for example, by logging a + * warning message) whenever it traverses over a link that has this + * property. The notification SHOULD include the deprecation property's + * value so that a client manitainer can easily find information about + * the deprecation. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.4 + */ + deprecation?: string; + + /** + * The "name" property is OPTIONAL. + * + * Its value MAY be used as a secondary key for selecting Link Objects + * which share the same relation type. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.5 + */ + name?: string; + + /** + * The "profile" property is OPTIONAL. + * + * Its value is a string which is a URI that hints about the profile (as + * defined by [I-D.wilde-profile-link]) of the target resource. + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.6 + */ + profile?: string; + + /** + * The "title" property is OPTIONAL. + * + * Its value is a string and is intended for labelling the link with a + * human-readable identifier (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.7 + */ + title?: string; + + /** + * The "hreflang" property is OPTIONAL. + * + * Its value is a string and is intended for indicating the language of + * the target resource (as defined by [RFC5988]). + * + * @see https://tools.ietf.org/html/draft-kelly-json-hal-08#section-5.8 + */ + hreflang?: string; + + } + +} diff --git a/hapi/hapi.d.ts b/hapi/hapi.d.ts index 68f6857110..ff5e1d9fe8 100644 --- a/hapi/hapi.d.ts +++ b/hapi/hapi.d.ts @@ -1605,6 +1605,9 @@ declare module "hapi" { addEventListener: any; info: IServerConnectionInfo; } + + type RequestExtPoints = "onRequest" | "onPreResponse" | "onPreAuth" | "onPostAuth" | "onPreHandler" | "onPostHandler" | "onPreResponse"; + type ServerExtPoints = "onPreStart" | "onPostStart" | "onPreStop" | "onPostStop"; /** Server http://hapijs.com/api#server rver object is the main application container. The server manages all incoming connections along with all the facilities provided by the framework. A server can contain more than one connection (e.g. listen to port 80 and 8080). @@ -2039,8 +2042,9 @@ declare module "hapi" { server.route({ method: 'GET', path: '/test', handler: handler }); server.start(); // All requests will get routed to '/test'*/ - ext(event: string, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; - ext(event: string, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: RequestExtPoints, method: (request: Request, reply: IReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: RequestExtPoints, method: (request: Request, reply: IStrictReply, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; + ext(event: ServerExtPoints, method: (server: Server, next: (err?: any) => void, bind?: any) => void, options?: { before: string | string[]; after: string | string[]; bind?: any }): void; /** server.handler(name, method) Registers a new handler type to be used in routes where: diff --git a/heremaps/heremaps-tests.ts b/heremaps/heremaps-tests.ts new file mode 100644 index 0000000000..3b2e1b5c30 --- /dev/null +++ b/heremaps/heremaps-tests.ts @@ -0,0 +1,82 @@ +// Test file for HERE Maps API for JavaScript Definition file +/// + +/** + * 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); +}; \ No newline at end of file diff --git a/heremaps/heremaps.d.ts b/heremaps/heremaps.d.ts new file mode 100644 index 0000000000..8d730f3ae5 --- /dev/null +++ b/heremaps/heremaps.d.ts @@ -0,0 +1,6354 @@ +// Type definitions for HERE Maps API for JavaScript v3.0.12.4 +// Project: https://developer.here.com/ +// Definitions by: Joshua Efiong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace H { + /***** Map *****/ + /** + * Map class defines map instance in the application. By creating this object you will initialize a visible map object which is attached to the provided dom element. Map class is an entry point to all operations related to layers, map objects and geo-screen transformations. By specifying options you can initialize map with predefined view. + */ + export class Map extends H.util.EventTarget { + /** + * Constructor + * @param element {Element} - html element into which the map will be rendered + * @param baseLayer {H.map.layer.Layer} - The layer to be used as the base (bottom most) layer. + * @param opt_options {H.Map.Options=} - additional map options + */ + constructor(element: Element, baseLayer: H.map.layer.Layer, opt_options?: H.Map.Options); + + /** + * This method returns the map root html element + * @returns {Element} + */ + getElement(): Element; + + /** + * This method sets the new center on a map. + * @param center {H.geo.IPoint} - requested center to be set + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setCenter(center: H.geo.IPoint, opt_animate?: boolean): H.Map; + + /** + * This method returns currently rendered center of the map. + * @returns {H.geo.Point} + */ + getCenter(): H.geo.Point; + + /** + * This method sets the zoom level on the map. Every zoom level represents different scale i.e map at zoom level 2 is twice as large as the map at zoom level 1. + * @param zoom {number} - requested zoom level + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setZoom(zoom: number, opt_animate?: boolean): H.Map; + + /** + * This method returns currently rendered zoom level. + * @returns {number} + */ + getZoom(): number; + + /** + * This method changes the map zoom while keeping target screen coordinates specified as x,y at the same place where they were before. + * @param zoom {number} - new zoom level + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + */ + zoomAt(zoom: number, x: number, y: number): void; + + /** + * This method sets the bounding rect to be displayed by the map. Maps display the bounding rect in a way that it fits entirely in the current viewport. + * @param boundingRect {H.geo.Rect} - view bound which should be shown on map + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setViewBounds(boundingRect: H.geo.Rect, opt_animate?: boolean): H.Map; + + /** + * This method returns bounding rect for the current map view. Returned bounding rect defines entire currently viewable area on the screen. + * @returns {H.geo.Rect} + */ + getViewBounds(): H.geo.Rect; + + /** + * Calculates the best CameraModel to show the provided bounding rectangle + * @param rect {H.geo.Rect} - The geographical bounding rectangle to use + * @returns {H.map.ViewModel.CameraData} - The result, represented by the properties zoom (number) and position (geo.Point) + */ + getCameraDataForBounds(rect: H.geo.Rect): H.map.ViewModel.CameraData; + + /** + * This method returns current map viewport. Viewport can be used to modify padding and margin which will reflect the position of the viewport center and the amount of extra data loaded (for margin) + * @returns {H.map.ViewPort} + */ + getViewPort(): H.map.ViewPort; + + /** + * This method returns current view model. View model can be used to modify the current view or camera. H.map.ViewModel + * @returns {H.map.ViewModel} + */ + getViewModel(): H.map.ViewModel; + + /** + * This method returns the map's current layer collection. + * @returns {H.map.DataModel} + */ + getLayers(): H.map.DataModel; + + /** + * This method returns the imprint object for this map. + * @returns {H.map.Imprint} + */ + getImprint(): H.map.Imprint; + + /** + * This method captures desired region of the map and objects on it. Result is returned as an HTML5 Canvas element. Origin of coordinate system for capturing is in the top left corner of the viewport. + * @param callback {function(HTMLCanvasElement=)} - Callback function to call once result of the capturing is ready + * @param opt_capturables {Array=} - Collection of "capturable" element(s) to draw into the resulting canvas + * @param opt_x1 {number=} - The X coordinate of the left edge of the capturing rectangle defaults to 0 + * @param opt_y1 {number=} - The Y coordinate of the top edge of the capturing rectangle defaults to 0 + * @param opt_x2 {number=} - The X coordinate of the right edge of the capturing rectangle defaults to viewport width + * @param opt_y2 {number=} - The Y coordinate of the bottom edge of the capturing rectangle defaults to viewport height + */ + capture(callback?: (canvas: HTMLCanvasElement) => void, opt_capturables?: Array, opt_x1?: number, opt_y1?: number, opt_x2?: number, opt_y2?: number): void; + + /** + * This method sets the rendering engine type for the map. Rendering engine is responsible for displaying i.e tiles and data on the map. + * @param type {H.Map.EngineType} + * @returns {H.Map} - the map itself + */ + setEngineType(type: H.Map.EngineType): H.Map; + + /** + * To persistently store the content of a map layer for a given area and range of zoom levels. It can be used to enable map rendering when no internet connection is established and also to reduce the download traffic for frequently visited map areas. + * @param opt_onprogress {function(H.util.Request)=} - A callback which is invoked every time when the progress state of the returned store request changes. + * @param opt_bounds {H.geo.Rect=} - The area to store, default is the current view bounds + * @param opt_min {number=} - The minimum zoom level to store, default is the current zoom level + * @param opt_max {number=} - The maximum zoom level to store, default is the current zoom level + * @param opt_layer {H.map.layer.BaseTileLayer=} - The layer to store, default is the current base layer + * @returns {H.util.Request} - A handle to the created storage request + */ + storeContent(opt_onprogress?: (req: H.util.Request) => void, opt_bounds?: H.geo.Rect, opt_min?: number, opt_max?: number, opt_layer?: H.map.layer.BaseTileLayer): H.util.Request; + + /** + * To clear the entire stored content + * @param opt_onprogress {function(H.util.Request)=} - A callback which is invoked every time when the progress state of the returned clear request changes + * @returns {H.util.Request} - A handle to the created flush request + */ + clearContent(opt_onprogress?: (req: H.util.Request) => void): H.util.Request; + + /** + * This method adds a layer to the map. + * @param layer {H.map.layer.Layer} - The map layer to be added + * @param opt_idx {number=} - index at which the new layer should be inserted + * @returns {H.Map} - current map instance + */ + addLayer(layer: H.map.layer.Layer, opt_idx?: number): H.Map; + + /** + * This method removes layer from the map. + * @param layer {H.map.layer.Layer} - The map layer to be removed + * @returns {H.Map} - current map instance + */ + removeLayer(layer: H.map.layer.Layer): H.Map; + + /** + * This method will set provided layer as base map. The layer will be inserted as the bottom most layer in the map. + * @param layer {H.map.layer.Layer} - The layer to use as base map + * @returns {H.Map} - the instance itself + */ + setBaseLayer(layer: H.map.layer.Layer): H.Map; + + /** + * To get the current base map layer. + * @returns {?H.map.layer.Layer} + */ + getBaseLayer(): H.map.layer.Layer; + + /** + * Returns the screen coordinates according to the given geographical coordinates. This method returns a screen pixel coordinates for the provided geo point. + * @param geoPoint {H.geo.IPoint} - point on the map + * @returns {?H.math.Point} + */ + geoToScreen(geoPoint: H.geo.IPoint): H.math.Point; + + /** + * Returns the geographical coordinates according to the given screen coordinates. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {?H.geo.Point} + */ + screenToGeo(x: number, y: number): H.geo.Point; + + /** + * Returns the camera data according to the given screen coordinates. Method converts screen pixel coordinates to correct camera data object + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {H.map.ViewModel.CameraData} + */ + screenToCameraData(x: number, y: number): H.map.ViewModel.CameraData; + + /** + * This method adds an map object to the map. Map object can be a marker or a spatial object like polygon or polyline. + * @param mapObject {!H.map.Object} - The map object to add + * @returns {!H.map.Object} - the added map object + */ + addObject(mapObject: H.map.Object): H.map.Object; + + /** + * This method removes previously added map object from the map. + * @param mapObject {!H.map.Object} - The map object to remove + * @returns {!H.map.Object} - the removed map object + */ + removeObject(mapObject: H.map.Object): H.map.Object; + + /** + * This method retrieves the list of all objects which have been added to the map. + * @returns {Array} - the list of all use objects which are currently on the map. + */ + getObjects(): Array; + + /** + * This method adds an array of objects or an object group to the map. + * @param mapObjects {Array} + * @returns {H.Map} - the map instance + */ + addObjects(mapObjects: Array): H.Map; + + /** + * This method removes an array of object or an object group from the map. + * @param mapObjects {(Array | H.map.Group)} + * @returns {H.Map} - the map instance + */ + removeObjects(mapObjects: (Array | H.map.Group)): H.Map; + + /** + * Returns the top most z-ordered map object found under the specific screen coordinates. Coordinates are viewport pixel coordinates starting from top left corner as (0, 0) point. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {?H.map.Object} - the encountered top most map object or null if no object found + */ + getObjectAt(x: number, y: number): H.map.Object; + + /** + * Returns a list of map objects in descending z-order found under the specific screen coordinates. Coordinates are viewport pixel coordinates starting from top left corner as (0, 0) point. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {Array} + */ + getObjectsAt(x: number, y: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Map { + /** + * It defines the number of lower and higher zoom levels, where cached content of the base map is rendered while content of the current zoom level is still loading. Example: if range was set to {lower: 3, higher: 2} and current level is 10 then rendering engine will try to display cached tiles from lower zoom levels 7, 8, 9 and higher levels 11 and 12. + * @property lower {number} - The number of lower zoom levels to take into account, default is 0 + * @property higher {number} - The number of higher zoom levels to take into account, default is 0 + */ + export interface BackgroundRange { + lower: number; + higher: number; + } + + /** + * Types of engines + */ + export enum EngineType { + P2D, + PANORAMA, + } + + /** + * This type defines options which can be used to initialize the map. + * @property center {H.geo.IPoint=} - The initial center of the map, default is {lat:0, lng: 0} + * @property zoom {number=} - The initial zoom level of the map, default is 0 respectively the minimal zoom level of the base map + * @property bounds {H.geo.Rect=} - The view bounds to be displayed on the map. If provided, it takes precedence over center and zoom. and zoom if provided) + * @property layers {Array=} - A list of layers to render on top of the base map + * @property engineType: {H.Map.EngineType=} - The initial engine type to use, default is P2D + * @property pixelRatio {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @property imprint {H.map.Imprint.Options=} - The imprint options or null to suppress the imprint + * @property renderBaseBackground {H.Map.BackgroundRange=} - Object describes how many cached zoom levels should be used as a base map background while base map tiles are loading. Example: {lower: 3, higher: 2} + * @property autoColor {boolean=} - Indicates whether the UI's colors should automatically adjusted to the base layer, default is true. Up to now only the copyright style will be adjusted. See H.map.layer.Layer.Options#dark + * @property margin {number=} - The size in pixel of the supplemental area to render for each side of the map + * @property padding {H.map.ViewPort.Padding=} - The padding in pixels for each side of the map + * @property fixedCenter {boolean=} - Indicates whether the center of the map should remain unchanged if the viewport's size or padding has been changed, default is true + */ + export interface Options { + center?: H.geo.IPoint; + zoom?: number; + bounds?: H.geo.Rect; + layers?: Array; + engineType?: EngineType; + pixelRatio?: number; + imprint?: H.map.Imprint.Options; + renderBaseBackground?: BackgroundRange; + autoColor?: boolean; + margin?: number; + padding?: H.map.ViewPort.Padding; + fixedCenter?: boolean; + } + } + + /***** clustering *****/ + export module clustering { + /** + * This class represents the input data structure for data points to be clustered. + * @property lat {H.geo.Latitude} - The latitude coordinate of the data point's position + * @property lng {H.geo.Longitude} - The longitude coordinate of the data point's position + * @property wt {number} - The weight of the data point + * @property data {*} - Data associated with this data point + */ + export class DataPoint implements H.geo.IPoint { + /** + * Constructor + * @param lat {H.geo.Latitude} - The latitude coordinate of the data point's position + * @param lng {H.geo.Longitude} - The longitude coordinate of the data point's position + * @param opt_weight {number=} - The weight of the data point as a positive number > 0. If not specified it , default is 1. + * @param opt_data {*=} - Optional data, which will be associated with this DataPoint + */ + constructor(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_weight?: number, opt_data?: any); + + lat: H.geo.Latitude; + lng: H.geo.Longitude; + alt: H.geo.Altitude; + ctx: H.geo.AltitudeContext; + wt: number; + data: any; + } + + /** + * This interface describes a cluster of data points, which fulfill the clustering specification (i.e. data points are within the epsilon and there are enough points to form a cluster). + */ + export interface ICluster { + /** + * Returns the maximum zoom level where this cluster doesn't fall apart into sub clusters and/or noise poinst + * @returns {number} + */ + getMaxZoom(): number; + + /** + * Returns the bounding rectangle of this cluster. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + + /** + * Invokes the specified callback for each "entry" of the cluster. That "entry" can be either a cluster which implements H.clustering.ICluster interface or a noise point which implements H.clustering.INoisePoint interface. + * @param callback {function(H.clustering.IResult)} - The callback gets the currently traversed entry as an argument, which is cluster or noise point. + */ + forEachEntry(callback: (result: H.clustering.IResult) => void): void; + + /** + * Invokes the specified callback for each data point which is part of this cluster, even indirectly. + * @param callback {function(H.clustering.INoisePoint)} - The callback gets the currently traversed noise point as argument. + */ + forEachDataPoint(callback: (noise: H.clustering.INoisePoint) => void): void; + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * This interface represents a data point which does not belong to a cluster. + */ + export interface INoisePoint { + /** + * This method returns data which coresponds to this noise point. + * @returns {*} + */ + getData(): any; + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * This interface represents the result item of a clustering operation. + */ + export interface IResult { + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * Interface which specifies the methods a theme must implement. + */ + export interface ITheme { + + /** + * Function returns a cluster presentation as a map object. + * @param cluster {H.clustering.ICluster} + * @returns {H.map.Object} + */ + getClusterPresentation(cluster: H.clustering.ICluster): H.map.Object; + + /** + * Function returns noise point presentation as a map object + * @param noisePoint {H.clustering.INoisePoint} + * @returns {H.map.Object} + */ + getNoisePresentation(noisePoint: H.clustering.INoisePoint): H.map.Object; + } + + /** + * The clustering provider serves clusters and noise point representation for the map depending on the provided data set. Levels for clustering as well as custom cluster representation can be set via Options. + * @property min {number} - Minimum zoom level at which provider can cluster data + * @property max {number} - Maximum zoom level at which provider can cluster data + */ + export class Provider extends H.util.EventTarget { + /** + * Constructor + * @param dataPoints {Array} + * @param opt_options {H.clustering.Provider.Options=} + */ + constructor(dataPoints: Array, opt_options?: H.clustering.Provider.Options); + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + /** + * This method sets new data to the provider + * @param dataPoints {Array} + */ + setDataPoints(dataPoints: Array): void; + + /** + * This method adds a data point to the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoint {H.clustering.DataPoint} + */ + addDataPoint(dataPoint: H.clustering.DataPoint): void; + + /** + * This method adds a list of data points to the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoints {Array} + */ + addDataPoints(dataPoints: Array): void; + + /** + * This method removes a data point from the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoint {H.clustering.DataPoint} + */ + removeDataPoint(dataPoint: H.clustering.DataPoint): void; + + /** + * This method returns current theme used for creating cluster visualization + * @returns {H.clustering.ITheme} + */ + getTheme(): H.clustering.ITheme; + + /** + * This method sets new theme on the provider. Calling this method will change visuals for displayed clusters and noise points. + * @param theme {H.clustering.ITheme} + */ + setTheme(theme: H.clustering.ITheme): void; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + + /** + * Returns all DomMarker cluster and noise point representations which intersect with the provided rectangular area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestDomMarkers(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesMarkers(): boolean; + + /** + * Returns all cluster and noise point markers which intersect with the provided rectangular area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestMarkers(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesSpatials(): boolean; + + /** + * Returns all polyline, polygon, circle and rect objects which represent cluster and noise points and intersect with the provided area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatials(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the spatial objects which intersect the given tile + * @param tile {H.map.provider.SpatialTile} - The tile for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatialsByTile(tile: H.map.provider.Tile, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the accumulate invalidations of this provider's objects that have occurred. + * @returns {H.map.provider.Invalidations} - an invalidations object + */ + getInvalidations(): H.map.provider.Invalidations; + + /** + * To signal to this provider that a map object has been changed. The method updates the Invalidations of this provider and the given map object and triggers dispatchUpdate() + * @param mapObject {!H.map.Object} - The map object to be invalidated + * @param changes {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(mapObject: H.map.Object, changes: H.math.BitMask): void; + + min: number; + max: number; + } + + export module Provider { + /** + * Options which are used within cluster calculations. + * @property eps {number=} - epsilon parameter for cluster calculation. For the FASTGRID strategy it must not exceed 256 and must take values that are power of 2. For the GRID and DYNAMICGRID strategies it can take values from 10 to 127. Default is 32. + * @property minWeight {number=} - the minimum points weight sum to form a cluster, default is 2 + * @property projection {H.geo.IProjection=} - projection to use for clustering, default is H.geo.mercator + * @property strategy {H.clustering.Provider.Strategy=} - clustering stretegy, defaults to H.clustering.Provider.Strategy.FASTGRID + */ + export interface ClusteringOptions { + eps?: number; + minWeight?: number; + projection?: H.geo.IProjection; + strategy?: H.clustering.Provider.Strategy; + } + + /** + * Options which are used to initialize the clustering Provider + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property clusteringOptions {H.clustering.Provider.ClusteringOptions=} - options for clustering algorithm + * @property theme {H.clustering.ITheme=} - cluster and noise point graphical representation + */ + export interface Options { + min?: number; + max?: number; + clusteringOptions?: H.clustering.Provider.ClusteringOptions; + theme?: H.clustering.ITheme; + } + + /** + * Enumeration represents possible clustering strategies. FASTGRID clustering is the efficient way to cluster large sets of data points. GRID clustering is slower but has greater precision due to the bigger range of epsilon values, this strategy suitable for clustering smaller data sets (up to 1000 data points) on desktop devices. DYNAMICGRID clustering uses the same algorithm of clustering as the GRID, but clusters on the viewport basis is meant to be used with data sets that are subject to the frequent update operations. + */ + export enum Strategy { + FASTGRID, + GRID, + DYNAMICGRID, + } + } + } + + /***** data *****/ + export module data { + /** + * An abstract reader class defines interface for data readers and has general functionality related to fetching data and reader events. + */ + export class AbstractReader extends H.util.EventTarget { + /** + * Constructor + * @param opt_url {string=} + */ + constructor(opt_url?: string); + + /** + * Method returns H.map.layer.ObjectLayer that contains parsed data, and can be added directly to the map. It returns new instance of the class with every invocation. If data hasn't been parsed it will return H.map.layer.ObjectLayer that contains partial information, and reader will add new parsed objects to the layer's provider later on. + * @returns {H.map.layer.ObjectLayer} + */ + getLayer(): H.map.layer.ObjectLayer; + + /** + * Method returns collection of currently parsed, and converted to H.map.Object data objects. Method returns only currently parsed objects if parsing is ongoing. + * @returns {Array} + */ + getParsedObjects(): Array; + + /** + * Returns URL of the current file, which is either in process of fetching/parsing or file that has been already parsed. + * @returns {(string | undefined)} - url + */ + getUrl(): string | void; + + /** + * Method sets reader's URL. Method resets current Reader's state to its initial values (clears data about last parsed objects, etc.), and throws InvalidState exception if Reader's state is not READY or ERROR. + * @param url {string} - The new URL + * @returns {H.data.AbstractReader} + */ + setUrl(url: string): H.data.AbstractReader; + + /** + * Returns the reader's processing state for possible states see H.data.AbstractReader.State + * @returns {H.data.AbstractReader.State} + */ + getState(): H.data.AbstractReader.State; + + /** + * Method launches parsing of the data file at the current url (see H.data.AbstractReader#setUrl or H.data.AbstractReader). Method uses XHR as a transport therefore same origin policy applies, or server should respond with proper CORS headers. + */ + parse(): void; + } + + export module AbstractReader { + /** + * The event class for state events that are dispatched by AbstractReader + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param target {(H.data.AbstractReader | H.map.Object)} - The target that's passed to event listeners + * @param type {string} - The type of the event + * @param state {H.data.AbstractReader.State} - The state of the target firing an event + * @param message {string} - The message associated with an event + */ + constructor(target: (H.data.AbstractReader | H.map.Object), type: string, state: H.data.AbstractReader.State, message: string); + } + + /** + * The state types of an Reader. Possible states are: + */ + export enum State { + ERROR, + LOADING, + VISIT, + READY, + } + } + } + + /***** geo *****/ + export module geo { + /** + * A Geographic coordinate that specifies the height of a point in meters. A value of undefined is treated as 0. + */ + export type Altitude = number; + + /** + * Contexts for altitudes to specify the contextual origin of an altitude's value + */ + export enum AltitudeContext { + /** Ground level */ + undefined, + /** Ground level */ + GL, + /** Obstruction level */ + OL, + /** Mean sea level */ + SL, + /** Sea bed level */ + SB, + /** WGS84 ellipsoid */ + WE, + /** WGS84 geoid */ + WG, + } + + /** + * An interface to represent a geographic point. Every point in geo space is represented by three coordinates latitude, longitude and optional altitude. + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property alt {H.geo.Altitude=} - The altitude coordinate. + * @property ctx {H.geo.AltitudeContext=} - The altitude context. + */ + export interface IPoint { + lat: H.geo.Latitude; + lng: Longitude; + alt?: H.geo.Altitude; + ctx?: H.geo.AltitudeContext; + } + + export interface IProjection { + latLngToPoint(lat: number, lng: number, opt_out?: H.math.Point): H.math.Point; + xyToGeo(x: number, y: number, opt_out?: H.geo.Point): H.geo.Point; + pointToGeo(point: H.math.IPoint, opt_out?: H.geo.Point): H.geo.Point; + geoToPoint(geoPoint: H.geo.IPoint, opt_out?: H.math.Point): H.math.Point; + } + + /** + * A geographic coordinate that specifies the north-south position of a point on the Earth's surface in the range from -90 to + 90 degrees, inclusive. + */ + export type Latitude = number; + + /** + * A Geographic coordinate that specifies the east-west position of a point on the Earth's surface in the range from -180 to 180 degrees, inclusive. + */ + export type Longitude = number; + + /** + * Class represents a geographical point, which is defined by the latitude, longitude and optional altitude. + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property alt {H.geo.Altitude} - The altitude coordinate. + * @property ctx {H.geo.AltitudeContext} - The altitude context. + */ + export class Point implements IPoint { + /** + * Constructor + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property opt_alt {H.geo.Altitude=} - The altitude coordinate. + * @property opt_ctx {H.geo.AltitudeContext=} - The altitude context. + */ + constructor(lat: H.geo.Latitude, lng: Longitude, opt_alt?: H.geo.Altitude, opt_ctx?: H.geo.AltitudeContext); + + /** + * To compare this point with a supplied other point for equality. Two points are considered equal if they have the same lat and lng as well as equivalent values for alt and ctx. + * @param other {H.geo.IPoint} + * @returns {boolean} - Whether the two points are equal. + */ + equals(other: IPoint): boolean; + + /** + * To calculate the distance between this point and the supplied other point. The method uses the Haversine formula. The altitude is not considered. + * @param other {H.geo.IPoint} + * @returns {number} - The distance between the given location and the location supplied by the caller in meters. + */ + distance(other: IPoint): number; + + /** + * This method calculates the geographic point of a destination point using the distance and bearing specified by the caller. The altitude is ignored, instead the WGS84 Mean Radius is taken. + * @param bearing {number} - The bearing to use in the calculation in degrees. + * @param distance {number} - The distance to the destination in meters. + * @param opt_overGreatCircle {boolean=} - If true the computation uses the 'Great Circle' otherwise 'Rhumb Line'. + * @returns {H.geo.Point} - The calculated point + */ + walk(bearing: number, distance: number, opt_overGreatCircle?: boolean): Point; + + /** + * This method validates the given IPoint. It checks, if lat, lng, alt and ctx have valid types. Additionally the value of the lat property is clamped into a range of -90 ... +90 and the value of the lng property is modulo into a range of -180 ... +180 plus validates the values of the alt and ctx properties + * @param point {H.geo.IPoint} - The point to validate + * @param opt_caller {Function=} - The caller to use for InvalidArgumentError. If omitted no error is thrown + * @param opt_argNr {number=} - The argument number to use for InvalidArgumentError. + * @returns {boolean} - if the given point could validate + */ + static validate(point: IPoint, opt_caller?: Function, opt_argNr?: number): boolean; + + /** + * This method creates a Point instance from a given IPoint object. + * @param iPoint {H.geo.IPoint} - The IPoint object to use + * @returns {H.geo.Point} - the created Point instance + */ + static fromIPoint(iPoint: IPoint): Point; + + lat: H.geo.Latitude; + lng: H.geo.Longitude; + alt: H.geo.Altitude; + ctx: H.geo.AltitudeContext; + } + + /** + * This class represents a rectangular geographic area. The area is defined by four geographical coordinates two (left, right) longitudes and two (top, bottom) latitudes. + */ + export class Rect { + /** + * Constructor + * @param top {H.geo.Latitude} - the northern-most latitude + * @param left {H.geo.Longitude} - the left-most longitude + * @param bottom {H.geo.Latitude} - the southern-most latitude + * @param right {H.geo.Longitude} - the right-most latitude + */ + constructor(top: H.geo.Latitude, left: H.geo.Longitude, bottom: H.geo.Latitude, right: H.geo.Longitude); + + /** + * To compare this rectangle with a supplied other rectangle for equality. + * @param other {H.geo.Rect} + * @returns {boolean} - Whether the two rectangles are equal. + */ + equals(other: H.geo.Rect): boolean; + + /** + * Toclone this rectangle. + * @returns {H.geo.Rect} + */ + clone(): H.geo.Rect; + + /** + * This method returns the top-left corner of the rectangular area. + * @returns {H.geo.Point} - the top-left corner of the area + */ + getTopLeft(): H.geo.Point; + + /** + * This method returns the bottom-right corner of the rectangular area. + * @returns {H.geo.Point} - the bottom-right corner of the area + */ + getBottomRight(): H.geo.Point; + + /** + * This method returns the north-most latitude of this rectangular area + * @returns {H.geo.Latitude} - the north-most latitude of the area + */ + getTop(): H.geo.Latitude; + + /** + * This method returns the south-most latitude of this rectangular area + * @returns {H.geo.Latitude} - the south-most latitude of the area + */ + getBottom(): H.geo.Latitude; + + /** + * This method returns the left-most longitude of this rectangular area + * @returns {H.geo.Longitude} - the left-most longitude of the area + */ + getLeft(): H.geo.Longitude; + + /** + * This method returns the right-most longitude of this rectangular area + * @returns {H.geo.Longitude} - the right-most longitude of the area + */ + getRight(): H.geo.Longitude; + + /** + * This method returns the center point of this rectangular area + * @returns {H.geo.Point} - the center point of the area + */ + getCenter(): H.geo.Point; + + /** + * Returns this width of this rectangular area in decimal degrees. + * @returns {number} - the width of this area + */ + getWidth(): number; + + /** + * Returns this height of this rectangular area in decimal degrees. + * @returns {number} - the height of this area + */ + getHeight(): number; + + /** + * Returns a boolean value indicating whether this rectangular area spans across the date border. + * @returns {boolean} - true if the area spans across the date border, otherwise false + */ + isCDB(): boolean; + + /** + * The method checks if the area enclosed by the given bounding box is 0. + * @returns {boolean} - true if the dimensions of the area a 0, otherwise false + */ + isEmpty(): boolean; + + /** + * This method checks if the latitude and longitude supplied by the caller lie within the area of this rectangular area. + * @param lat {H.geo.Latitude} - the latitude + * @param lng {H.geo.Longitude} - the longitude + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the latitude and longitude are contained in this area, otherwise false + */ + containsLatLng(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_skipValidation?: boolean): boolean; + + /** + * This method checks if the point supplied by the caller lies within the area of this rectangular area. + * @param geoPoint {H.geo.IPoint} - the point + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the point is contained in this area, otherwise false + */ + containsPoint(geoPoint: H.geo.IPoint, opt_skipValidation?: boolean): boolean; + + /** + * This method checks if the rectangular area supplied by the caller is completely contained within the area of this rectangular area. + * @param geoRect {H.geo.Rect} - the rectangular area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the rectangular area is contained in this area, otherwise false + */ + containsRect(geoRect: H.geo.Rect, opt_skipValidation?: boolean): boolean; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the latitude and longitude supplied by the caller. + * @param lat {H.geo.Latitude} - the latitude + * @param lng {H.geo.Longitude} - the longitude + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeLatLng(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the point supplied by the caller. + * @param geoPoint {H.geo.IPoint} - the point to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergePoint(geoPoint: H.geo.IPoint, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the rectangular area supplied by the caller. + * @param geoRect {H.geo.Rect} - the point to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeRect(geoRect: H.geo.Rect, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the rectangular area supplied by the caller. + * @param top {H.geo.Latitude} - The top latitude of the rectangle to merge + * @param left {H.geo.Longitude} - The left longitude of the rectangle to merge + * @param bottom {H.geo.Latitude} - The bottom latitude of the rectangle to merge + * @param right {H.geo.Longitude} - The right longitude of the rectangle to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeTopLeftBottomRight(top: H.geo.Latitude, left: H.geo.Longitude, bottom: H.geo.Latitude, right: H.geo.Longitude, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method checks if the intersection of two bounding boxes is non-empty. + * @param geoRect {H.geo.Rect} - a rectangular area to be tested for intersection with this rectangular area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - a boolean value indicating whether the two areas intersect + */ + intersects(geoRect: H.geo.Rect, opt_skipValidation?: boolean): boolean; + + /** + * This method merges two rects by their values. The result of the merge is a bounding rect which covers all provided rect bounds. + * @param topA {H.geo.Latitude} - the northern-most latitude + * @param leftA {H.geo.Longitude} - the left-most longitude of operand A + * @param bottomA {H.geo.Latitude} - the southern-most latitude of operand A + * @param rightA {H.geo.Longitude} - the right-most latitude of operand A + * @param topB {H.geo.Latitude} - the northern-most latitude of operand B + * @param leftB {H.geo.Longitude} - the left-most longitude of operand B + * @param bottomB {H.geo.Latitude} - the southern-most latitude of operand B + * @param rightB {H.geo.Longitude} - the right-most latitude of operand B + * @param opt_out {H.geo.Rect=} - an optional rect to store the results + * @returns {H.geo.Rect} - either the opt_out rect or a new rect + */ + static merge(topA: H.geo.Latitude, leftA: H.geo.Longitude, bottomA: H.geo.Latitude, rightA: H.geo.Longitude, topB: H.geo.Latitude, leftB: H.geo.Longitude, bottomB: H.geo.Latitude, rightB: H.geo.Longitude, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method creates a rectangular area from a top-left and bottom-right point pair. + * @param topLeft {H.geo.IPoint} - the top-left corner of the area + * @param bottomRight {H.geo.IPoint} - the bottom-right corner of the area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {H.geo.Rect} - returns the rectangular area defined by the top-left and bottom-right corners + */ + static fromPoints(topLeft: H.geo.IPoint, bottomRight: H.geo.IPoint, opt_skipValidation?: boolean): H.geo.Rect; + + /** + * This method creates the minimum rectangular area covering all of the points in the argument array. + * @param pointArray {Array} - the array of points to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {H.geo.Rect} - returns the minimum rectangular area covering the points or null if no point is covered + */ + static coverPoints(pointArray: Array, opt_skipValidation?: boolean): H.geo.Rect; + + /** + * This method creates the minimum rectangular area covering all of the coordinates in the argument array. + * @param latLngAltArray {Array} - the array of coordinates to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {(H.geo.Rect | undefined)} - returns the minimum rectangular area covering the coordinates + */ + static coverLatLngAlts(latLngAltArray: Array, opt_skipValidation?: boolean): H.geo.Rect | void; + + /** + * This method creates the minimum rectangular area covering all of the rectangular areas in the argument array. + * @param rectArray {Array} - the array of points to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {(H.geo.Rect | undefined)} - returns the minimum rectangular area covering the rectangular areas + */ + static coverRects(rectArray: Array, opt_skipValidation?: boolean): H.geo.Rect | void; + + /** + * This method clones the given bounding rect and resizes the clone if necessary until the location supplied by the caller is at its center. + * @param center {H.geo.IPoint} - a point which is to be the center of the resized rectangular area + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - the resized rectangular area + */ + resizeToCenter(center: H.geo.IPoint, opt_out?: H.geo.Rect): H.geo.Rect; + } + + /** + * A strip is a flat list of latitude, longitude, altitude tuples in a fixed order. + */ + export class Strip { + /** + * Constructor + * @param opt_latLngAlts {Array=} - An optional array of latitude, longitude and altitude triples to initialize the strip with. + * @param opt_ctx {H.geo.AltitudeContext=} - An optional altitude context for all altitudes contained in this strip. + */ + constructor(opt_latLngAlts?: Array, opt_ctx?: H.geo.AltitudeContext); + + /** + * This method pushes a lat, lng, alt to the end of this strip. + * @param lat {H.geo.Latitude} + * @param lng {H.geo.Longitude} + * @param alt {H.geo.Altitude} + */ + pushLatLngAlt(lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method splices the strip at the provided index, removing the specified number of items at that index and inserting the lat, lng, alt array. + * @param index {number} - The index at which to splice + * @param opt_nRemove {number=} - The number of lat, lng, alt values to remove + * @param opt_latLngAlts {Array=} - The lat, lng, alt values to add + * @returns {Array} - an array of removed elements + */ + spliceLatLngAlts(index: number, opt_nRemove?: number, opt_latLngAlts?: Array): Array; + + /** + * This method inserts one set of lat, lng, alt values into the strip at the specified index. + * @param index {number} - the index at which to add the element + * @param lat {H.geo.Latitude} - the latitude to insert + * @param lng {H.geo.Longitude} - the longitude to insert + * @param alt {H.geo.Altitude} - the altitude to insert + */ + insertLatLngAlt(index: number, lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method removes one set of lat, lng, alt values from the strip at the specified index. + * @param index {number} + */ + removeLatLngAlt(index: number): void; + + /** + * This method pushes the lat, lng, alt values of a H.geo.Point to the end of this strip. + * @param geoPoint {H.geo.IPoint} + */ + pushPoint(geoPoint: H.geo.IPoint): void; + + /** + * This method inserts the lat, lng, alt values of a H.geo.Point into the list at the specified index. + * @param pointIndex {number} + * @param geoPoint {H.geo.IPoint} + */ + insertPoint(pointIndex: number, geoPoint: H.geo.IPoint): void; + + /** + * This method removes one set of lat, lng, alt values from this strip at the virtual point index specified. + * @param pointIndex {number} - the virtual point index + */ + removePoint(pointIndex: number): void; + + /** + * This method extracts a H.geo.Point from this strip at the virtual point index. If the extracted point has an alt value, the strip's altitude context will be supplied to the point. + * @param pointIndex {number} - the virtual point index in the strip + * @param opt_out {H.geo.Point=} - an optional point object to store the lat, lng, alt values + * @returns {H.geo.Point} - returns either the 'opt_out' point object or a new point object. + */ + extractPoint(pointIndex: number, opt_out?: H.geo.Point): H.geo.Point; + + /** + * This method is a utility method that iterates over the lat, lng, alt array and calls the provided function for each 3 elements passing lat, lng and alt and the virtual point index as arguments. + * @param eachFn {function(H.geo.Latitude, H.geo.Longitude, H.geo.Altitude, number)} - the function to be called for each 3 elements + * @param opt_start {number=} - an optional start index to iterate from + * @param opt_end {number=} - an optional end index to iterate to + */ + eachLatLngAlt(eachFn: (lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude, n: number) => void, opt_start?: number, opt_end?: number): void; + + /** + * This method returns the number of times that legs in this strip cross the date border. + * @param opt_closed {boolean=} - indicates whether the strip is closed (i.e. whether the strip's last and first coordinates form the closing leg of a polygon) + * @returns {number} - the amount of times this strip crosses the date border. + */ + getDBCs(opt_closed?: boolean): number; + + /** + * This method return the number of points stored in this strip. + * @returns {number} - the number of points in this strip + */ + getPointCount(): number; + + /** + * This method returns the internal array keeping the lat, lng, alt values. Modifying this array directly can destroy the integrity of this strip. Use it only for read access. + * @returns {Array} - returns the raw lat, lng, alt values of this strip + */ + getLatLngAltArray(): Array; + + /** + * This method returns the bounding box of this strip. + * @returns {?H.geo.Rect} - this strip's bounding rectangle + */ + getBounds(): H.geo.Rect; + + /** + * This method checks whether two longitudes form a leg which crosses the date border. + * @param lng1 {H.geo.Longitude} - the start longitude of the leg + * @param lng2 {H.geo.Longitude} - the end longitude of the leg + * @returns {boolean} - true if the leg crosses the date border, otherwise false + */ + static isDBC(lng1: H.geo.Longitude, lng2: H.geo.Longitude): boolean; + + /** + * This method initializes a new strip with an array of lat, lng values. Arrays are expected to have an even length with the format [lat, lng, lat, lng, ...]. + * @param latLngs {Array} - the array of lat, lng value. + * @returns {H.geo.Strip} - the strip containing the lat, lng values + */ + static fromLatLngArray(latLngs: Array): H.geo.Strip; + } + } + + /***** lang *****/ + + /***** map *****/ + export module map { + /** + * This class represents marker, which offers a means of identifying a location on the map with an icon. + */ + export class AbstractMarker extends H.map.Object { + /** + * Constructor + * @param position {H.geo.IPoint} - The location of this marker + * @param opt_options {H.map.AbstractMarker.Options=} - The values to initialize this marker + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.AbstractMarker.Options); + + /** + * This method returns this marker's current position. + * @returns {H.geo.Point} - current marker geo position + */ + getPosition(): H.geo.Point; + + /** + * This method sets the marker's current position. + * @param position {H.geo.IPoint} + * @returns {H.map.AbstractMarker} - the marker itself + */ + setPosition(position: H.geo.IPoint): H.map.AbstractMarker; + + /** + * Returns this marker's current icon. + * @returns {!(H.map.Icon | H.map.DomIcon)} + */ + getIcon(): (H.map.Icon | H.map.DomIcon); + + /** + * Sets the marker's current icon. + * @param icon {!(H.map.Icon | H.map.DomIcon)} - The new marker icon + * @returns {H.map.AbstractMarker} - the marker itself + */ + setIcon(icon: (H.map.Icon | H.map.DomIcon)): H.map.AbstractMarker; + } + + export module AbstractMarker { + /** + * Options used to initialize a AbstractMarker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {(H.map.Icon | H.map.DomIcon)=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.Icon | H.map.DomIcon; + data?: any; + } + } + + /** + * This class represents style attributes for arrows to be rendered along a polyline. A ArrowStyle instance is always treated as immutable to avoid inconstiencies and must not modified. + */ + export class ArrowStyle { + /** + * Constructor + * @param opt_options {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} + */ + constructor(opt_options?: (H.map.ArrowStyle | H.map.ArrowStyle.Options)); + + /** + * This method checks value-equality with another arrow style. + * @param other {(H.map.ArrowStyle | H.map.ArrowStyle.Options)} - the arrow style to compare with + * @returns {boolean} - true if the arrow styles are value-equal, otherwise false + */ + equals(other: (H.map.ArrowStyle | H.map.ArrowStyle.Options)): boolean; + } + + export module ArrowStyle { + /** + * An object type to specify the style of arrows to render along a polyline + * @property fillColor {string=} - The CSS color value used to fill the arrow shapes. If omitted or the value evaluates to false it defaults to "rgba(255, 255, 255, 0.75)" + * @property width {number=} - The width of the arrow shape. The value is taken as a factor of the width of the line, where the arrow description is applied. If omitted or the value is <= 0 it defaults to 1.2 + * @property length {number=} - The length of the arrow shapes. The value is taken as a factor of the width of the line at the end of which the arrow is drawn. If omitted or the value is <= 0 it defaults to 1.6 + * @property frequency {number=} - The frequency of arrow shapes. The value is taken as factor of the length of the arrow. A value of 1 results in gapless arrows. If omitted or the value is false it defaults to 5 + */ + export interface Options { + fillColor?: string; + width?: number; + length?: number; + frequency?: number; + } + } + + /** + * A Polygon with a circular shape. + */ + export class Circle extends H.map.Polygon { + /** + * Constructor + * @param center {H.geo.IPoint} - The geographical coordinates of the circle's center + * @param radius {number} - The radius of the circle in meters + * @param opt_options {H.map.Circle.Options=} - An object that specifies circle options and their initial values (among these, precision has a significant impact on the shape of the circle - please see + */ + constructor(center: H.geo.IPoint, radius: number, opt_options?: H.map.Circle.Options); + + /** + * To set the geographical center point of this circle. If the specified center is an instance of H.geo.Point you must not modify this Point instance without calling setCenter immediately afterwards. + * @param center {H.geo.IPoint} + */ + setCenter(center: H.geo.IPoint): void; + + /** + * To get the center point of this circle You must not modify the returned Point instance without calling setCenter immediately afterwards. + * @returns {H.geo.Point} + */ + getCenter(): H.geo.Point; + + /** + * To set the length of the radius of the circle in meters. The value is clamped to the of {@code[0 ... 20015089.27787877]} (half WGS84 mean circumference) + * @param radius {number} + */ + setRadius(radius: number): void; + + /** + * To get the length of the radius of the circle in meters. + * @returns {number} + */ + getRadius(): number; + + /** + * To set the precision of this circle {@see H.map.Circle.Options#precision} + * @param precision {number} + */ + setPrecision(precision: number): void; + + /** + * To get the precision value of this circle + * @returns {number} + */ + getPrecision(): number; + } + + export module Circle { + /** + * @property style {H.map.SpatialStyle=} - the style to be used when tracing the polyline + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property precision {number=} - The precision of a circle as a number of segments to be used when rendering the circle. The value is clamped to the range between [4 ... 360], where 60 is the default. Note that the lower the value the more angular and the less circle-like the shape appears and, conversely, the higher the value the smoother and more rounded the result. Thus, starting at the extreme low end of the possible values, 4 produces a square, 6 a hexagon, while 30 results in a circle-like shape, although it appears increasingly angular as the zoom level increases (as you zoom in), and finally 360 produces a smooth circle. + * @property zIndex {number=} - The z-index value of the circle, default is 0 + * @property min {number=} - The minimum zoom level for which the circle is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the circle is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: H.map.SpatialStyle | H.map.SpatialStyle.Options; + visibility?: boolean; + precision?: number; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * The class represents data model of the map. It holds list of layers that are rendered by map's RenderEngine. The class listens to 'update' events from layers and dispatches them to the RenderEngine. + */ + export class DataModel extends H.util.OList { + /** + * Constructor + * @param opt_layers {Array=} - array of layers to be added to the data model + */ + constructor(opt_layers?: Array); + } + + /** + * A visual representation of the H.map.DomMarker. + */ + export class DomIcon { + /** + * Constructor + * @param element {!(Element | string)} - The element or markup to use for this icon + * @param opt_options {H.map.DomIcon.Options=} + */ + constructor(element: (Element | string), opt_options?: H.map.DomIcon.Options); + } + + export module DomIcon { + /** + * Options used to initialize a DomIcon + * @property onAttach {function(Element, H.map.DomIcon, H.map.DomMarker)=} - A callback which is invoked before a clone of the icon's element is appended and displayed on the map. This callback can be used to setup the clone. + * @property onDetach {function(Element, H.map.DomIcon, H.map.DomMarker)=} - A callback which is invoked after a clone of the icon's element is removed from the map. This callback can be used to clean up the clone. + */ + export interface Options { + onAttach?: (el: Element, icon: H.map.DomIcon, marker: H.map.DomMarker) => void; + onDetach?: (el: Element, icon: H.map.DomIcon, marker: H.map.DomMarker) => void; + } + } + + /** + * A marker with a visual representation in the form of a full styleable and scripteable DOM element. DomMarker are predestinated if small amounts of markers with dynamic styled and/or scripted icons should be displayed om the map (e.g. animated interactive SVG). + */ + export class DomMarker extends H.map.AbstractMarker { + /** + * Constructor + * @param position {H.geo.IPoint} + * @param opt_options {H.map.DomMarker.Options=} + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.DomMarker.Options); + } + + export module DomMarker { + /** + * Options used to initialize a DomMarker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {H.map.DomIcon=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.DomIcon; + data?: any; + } + } + + /** + * This class represents a spatial shape in geographic space. It is defined by a path containing the vertices of the shape (lat, lng, alt values). + */ + export class GeoShape extends H.map.Spatial { + /** + * Constructor + * @param isClosed {boolean} - Indicates whether this geographical shape is closed (a polygon) + * @param strip {H.geo.Strip} - The strip describing the shape of the spatial object + * @param options {H.map.Spatial.Options} - The options to apply + */ + constructor(isClosed: boolean, strip: H.geo.Strip, options: H.map.Spatial.Options); + + /** + * This method returns the strip which represents the shape of the spatial object. + * @returns {H.geo.Strip} - the strip + */ + getStrip(): H.geo.Strip; + + /** + * This method sets the geo-information for the spatial object + * @param strip {?H.geo.Strip} - The strip which represents the shape of the spatial object. + * @returns {H.map.GeoShape} - the Spatial instance itself + */ + setStrip(strip: H.geo.Strip): H.map.GeoShape; + + /** + * This method returns the bounding rectangle for this object. The rectangle is the smallest rectangle which encloses all points of the spatial object. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + } + + /** + * This class represents a map object which can contain other map objects. It's visibility, zIndex and object-order influences the contained map objects + */ + export class Group extends H.map.Object { + /** + * Constructor + * @param opt_options {H.map.Group.Options=} - an optional object containing initialization values + */ + constructor(opt_options?: H.map.Group.Options); + + /** + * + * @param callback {function(!H.map.Object, number, !H.map.Group)} + * @param opt_recursive {boolean=} - Indicates whether sub groups should be traversed recursively + * @param opt_context {*=} - The context to use as "this" within the callback + */ + forEach(callback: (object: H.map.Object, n: number, group: H.map.Group) => void, opt_recursive?: boolean, opt_context?: any): void; + + /** + * To get a list of all objects of this group. On groups with many chilren this method can cause a higher memory and CPU consumption. Alternatively you case use H.map.Group#forEach + * @param opt_recursive {boolean=} - Indicates whether objects in sub-groups are also collected . + * @returns {!Array} + */ + getObjects(opt_recursive?: boolean): Array; + + /** + * Method returns the bounding rectangle for the group. The rectangle is the smallest rectangle that covers all objects. If group doesn't contains objects method returns null. + * @returns {H.geo.Rect} - geo ractangle that covers all objects in the group + */ + getBounds(): H.geo.Rect; + + /** + * To add an object to this group. + * @param object {!H.map.Object} + * @returns {!H.map.Object} - a reference to the appended object + */ + addObject(object: H.map.Object): H.map.Object; + + /** + * Appends a list of objects to this group + * @param objects {Array} + */ + addObjects(objects: Array): void; + + /** + * Removes an object from this group. + * @param object {!H.map.Object} - The object to remove + * @returns {!H.map.Object} - a reference to the removed object + */ + removeObject(object: H.map.Object): H.map.Object; + + /** + * Removes objects from this group. + * @param objects {!Array} - The list of objects to remove + */ + removeObjects(objects: Array): void; + + /** + * Method removes all objects from the group. + */ + removeAll(): void; + } + + export module Group { + /** + * Options used to initialize a group + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + * @property objects {Array=} - A list of map objects to add initially to this group. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + objects?: Array; + } + } + + /** + * This class represents an area that objects, like a marker, occupies in the screen space, meaning that object can be probed and returned by H.Map@getObjectsAt method. + */ + export class HitArea { + /** + * Constructor + * @param shapeType {H.map.HitArea.ShapeType} - The shape type of the HitArea + * @param opt_values {Array=} - The type-dependent values to define the shape of the hit area. The format for the different types are: + */ + constructor(shapeType: H.map.HitArea.ShapeType, opt_values?: Array); + } + + export module HitArea { + /** + * Enumeration represents possible shape types that HitArea can have. + */ + export enum ShapeType { + NONE, + RECT, + CIRCLE, + POLYGON, + } + } + + /** + * Control interface defines method which are used for direct view or camera manipulation + */ + export interface IControl { + + /** + * This method starts control action for camera. This action allows to control camera animation and movement according to provided values in the H.map.IControl#control function + * @param opt_kinetics {H.util.kinetics.IKinetics=} - kinetics settings + * @param opt_atX {number=} - control starts at x screen coordinate + * @param opt_atY {number=} - control starts at y screen coordinate + */ + startControl(opt_kinetics?: H.util.kinetics.IKinetics, opt_atX?: number, opt_atY?: number): void; + + /** + * This method triggers single control action on engine. This will trigger an animation which will start modification of the view's or camera's properties according to values begin set. Modification will occur at every frame. The speed values are measure by 'levels per frame' were 1 level cooresponds to a distance to next zoom level. + * @param moveX {number} - moves the view/cam in right/left direction + * @param moveY {number} - moves the view/cam in bottom/top direction + * @param moveZ {number} - moves the view/cam in depth direction (changes zoom level) + * @param angleX {number} - rotates cam over x-axis + * @param angleY {number} - rotates cam over y-axis + * @param angleZ {number} - rotates cam over z-axis + * @param zoom {number} - changes current zoom level (for view works as moveZ) + * @param opt_timestamp {number=} + */ + control(moveX: number, moveY: number, moveZ: number, angleX: number, angleY: number, angleZ: number, zoom: number, opt_timestamp?: number): void; + + /** + * This method ends current control, which will stop ongoing animation triggered by the startControl method. This method can prevent kinetics as well as it can adjust the final view if the adjust function is being passed. + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics animation + * @param opt_adjustView {function(H.map.ViewModel.CameraData)=} - user defined function which can adjust the final view this function takes last requestedData from the view model and should return a modified H.map.ViewModel.CameraData which will be set as the final view + */ + endControl(opt_preventKinetics?: boolean, opt_adjustView?: (data: H.map.ViewModel.CameraData) => void): void; + } + + /** + * An interface to specify a copyright note + * @property label {string} - A short textual representation of the copyright note, e.g. "DigitalGlobe 2009" + * @property alt {string} - A detailed textual representation of the copyright note, e.g. "copyright 2009 DigitalGlobe, Inc." + */ + export interface ICopyright { + label: string; + alt: string; + } + + /** + * Interface describes interaction with the view port. Interaction will reflect view change depending on the interaction coordinates passed and the modifiers which specify the type of interaction. + */ + export interface IInteraction { + /** + * This method starts the interaction with the view port. Should be called every time when new interaction is started i.e mouse grab, or touch start. + * @param modifiers {number} - a bitmask which specifies what operations should performed during every interaction + * @param opt_kinetics {H.util.kinetics.IKinetics=} - specifies kinetic move at the end of interaction + */ + startInteraction(modifiers: H.math.BitMask, opt_kinetics?: H.util.kinetics.IKinetics): void; + + /** + * This method resolves direct screen (view port) interaction. This function will modify the current view according to values passed in. + * @param x {number} - viewport x coordinate + * @param y {number} - viewport y coordinate + * @param opt_bx {number=} - x coordinate for second pointer/touch if present + * @param opt_by {number=} - y coordinate for secong pointer/touch if present + * @param opt_timestamp {number=} - known timestamp which should be passed + */ + interaction(x: number, y: number, opt_bx?: number, opt_by?: number, opt_timestamp?: number): void; + + /** + * This method ends interaction and applies kinetic movement if defined by using startInteraction method + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics behaviour at the end of interaction + */ + endInteraction(opt_preventKinetics?: boolean): void; + } + + /** + * A visual representation of the H.map.Marker. + */ + export class Icon { + /** + * Constructor + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @param opt_options {H.map.Icon.Options=} + */ + constructor(bitmap: (string | HTMLImageElement | HTMLCanvasElement), opt_options?: H.map.Icon.Options); + + /** + * Returns the icon's bitmap loading state + * @returns {H.map.Icon.prototype.State} + */ + getState(): H.map.Icon.State; + + /** + * Returns the bitmap of this icon or null if the bitmap is not ready yet (see H.map.Icon#getState) + * @returns {?(HTMLImageElement | HTMLCanvasElement)} + */ + getBitmap(): (HTMLImageElement | HTMLCanvasElement); + + /** + * Returns the size of this icon or null if a size wasn't specified in the constructor's options and the state of this icon is not H.map.Icon.prototype.State.READY + * @returns {?H.math.Size} + */ + getSize(): H.math.Size; + + /** + * Returns the anchor point of this icon or null if an anchor wasn't specified in the constructor's options and the state of this icon is not H.map.Icon.prototype.State.READY. + * @returns {?H.math.Point} + */ + getAnchor(): H.math.Point; + + /** + * Returns the hit area of the icon. + * @returns {?H.map.HitArea} - icon's anchor point + */ + getHitArea(): H.map.HitArea; + + /** + * This method allows to listen for specific event triggered by the object. Keep in mind, that you must removeEventListener manually or dispose an object when you no longer need it. Otherwise memory leak is possible. + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + addEventListener(type: string, handler: Function, opt_capture?: boolean, opt_scope?: Object): void; + + /** + * This method will removed previously added listener from the event target + * @param type {string} - name of event + * @param handler {Function} - previously added event handler + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + removeEventListener(type: string, handler: Function, opt_capture?: boolean, opt_scope?: Object): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Icon { + /** + * The state types of an Icon + */ + export enum State { + ERROR, + LOADING, + READY, + } + + /** + * Options used to initialize a Icon + * @property size {H.math.ISize=} - The icon's size in pixel, default is the bitmap's natural size + * @property anchor {H.math.IPoint=} - The anchorage point in pixel, default is bottom-center + * @property hitArea {H.map.HitArea=} - The area to use for hit detection, default is the whole rectangular area + * @property asCanvas {H.map.HitArea=} - Indicates whether a non canvas bitmap is converted into a canvas, default is true. The conversion improves the rendering performance but it could also cause a higher memory consumption. + * @property crossOrigin {boolean} - Specifies whether to use anonynous Cross-Origin Resource Sharing (CORS) when fetching an image to prevent resulting canvas from tainting, default is false. The option is ignored by IE9-10. + */ + export interface Options { + size?: H.math.ISize; + anchor?: H.math.IPoint; + hitArea?: H.map.HitArea; + asCanvas?: H.map.HitArea; + crossOrigin: boolean; + } + } + + /** + * This class encapsulates the brand, copyright and terms of use elements on the map. + */ + export class Imprint { + /** + * Constructor + * @param map {H.Map} - The map where the imprint is attached to + * @param opt_options {H.map.Imprint.Options=} - The options to style the imprint + */ + constructor(map: H.Map, opt_options?: H.map.Imprint.Options); + + /** + * To set the imprint options. If no opt_options argument is defined then all values are reset to their defaults. + * @param opt_options {H.map.Imprint.Options=} - The options to style the imprint + */ + setOptions(opt_options?: H.map.Imprint.Options): void; + + /** + * This method retrieves the copyright string for the current view of the map. + * @returns {string} - The copyright string for the current map view + */ + getCopyrights(): string; + + /** + * To get the CSS style declaration of the imprint DOM element + * @returns {CSSStyleDeclaration} + */ + getStyle(): CSSStyleDeclaration; + + /** + * Method adds a callback which will be triggered when the object is disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRatio {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {function(HTMLCanvasElement=)} - Callback function to call once result of the capturing is ready + * @param opt_errback {function(string)=} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRatio: number, callback?: (canvas: HTMLCanvasElement) => void, opt_errback?: (s: string) => void): void; + } + + export module Imprint { + /** + * Options to style an imprint + * @property invert {boolean=} - Indicates whether the logo is inverted. If omitted the current value remains, default is false. + * @property font {string=} - The font of the text. If omitted the current value remains, default is "11px Arial,sans-serif". + * @property href {string=} - The URL of the "Terms of use" link. If omitted the current value remains, default is "http://here.com/terms". + */ + export interface Options { + invert?: boolean; + font?: string; + href?: string; + } + } + + /** + * A marker with a visual representation in the form of a bitmap icon. Marker are predestinated if large amounts of markers with static icons should be displayed om the map. + */ + export class Marker extends H.map.AbstractMarker { + /** + * Constructor + * @param position {H.geo.IPoint} - The location of this marker + * @param opt_options {H.map.Marker.Options=} - The values to initialize this marker + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.Marker.Options); + } + + export module Marker { + /** + * Options used to initialize a Marker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {H.map.Icon=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.Icon; + data?: any; + } + } + + /** + * This class represents the abstract base class for map objects such as polylines, polygons, markers, groups etc. + */ + export class Object extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.Object.Options=} - The values to initialize this object + */ + constructor(opt_options?: H.map.Object.Options); + + /** + * Returns the ID of this object. + * @returns {*} + */ + getId(): any; + + /** + * Sets the visibility of this object. + * @param opt_visibility {boolean=} - Indicates whether this map object should be visible. + * @returns {H.map.Object} - returns this object + */ + setVisibility(opt_visibility?: boolean): H.map.Object; + + /** + * Returns the visibility of this object. + * @param opt_effective {boolean=} - Indicates that the effective visibility is requested. In this case the visibility of all possible ancestor groups is also taken into account + * @returns {boolean} + */ + getVisibility(opt_effective?: boolean): boolean; + + /** + * Returns the z-index of this object. + * @returns {(number | undefined)} + */ + getZIndex(): number | void; + + /** + * To set the-index of this object. + * @param zIndex {(number | undefined)} + * @returns {H.map.Object} - returns this object + */ + setZIndex(zIndex?: number): H.map.Object; + + /** + * Compares two objects regarding their z-order, useful to sort a list of objects via Array's sort() method + * @param first {H.map.Object} - The first object to compare + * @param second {H.map.Object} - The second object to compare + * @returns {number} - If less then 0 the first object has a lower z-order. If equal 0 booth objects have the same z-order. If greater then 0 the first object has a higher z-order. + */ + static compareZOrder(first: H.map.Object, second: H.map.Object): number; + + /** + * Returns the parent group which contains this object or null if the object is not contained by any group. + * @returns {?H.map.Group} + */ + getParentGroup(): H.map.Group; + + /** + * The root object in which this object is attached or the object itself. + * @returns {!H.map.Object} + */ + getRootGroup(): H.map.Object; + + /** + * Checks whether the given object is an inclusive descendant of this object + * @param object {*} - The object that's being compared against. + * @returns {boolean} + */ + contains(object: any): boolean; + + /** + * The current provider of this object + * @returns {?H.map.provider.ObjectProvider} - the current provider + */ + getProvider(): H.map.provider.ObjectProvider; + + /** + * Returns the invalidations of this object + * @returns {H.map.provider.Invalidations} - an invalidation object + */ + getInvalidations(): H.map.provider.Invalidations; + + /** + * This method invalidates this map object. + * @param flags {H.math.BitMask} - The flags indicating the types of occurred changes + * @returns {boolean} - indicates whether a validtion was executed (only if the object has a provider) + */ + invalidate(flags: H.math.BitMask): boolean; + + /** + * This method returns previously stored arbitrary data from this object. + * @returns {*} - the previously stored data or undefined if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this map object + * @param data {*} - the data to be stored + * @returns {H.map.Object} - returns this map object instance + */ + setData(data: any): H.map.Object; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Object { + /** + * Options used to initialize a map object + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + } + + /** + * The major types of map objects + */ + export enum Type { + /** spatial object */ + ANY, + /** spatial object */ + OVERLAY, + /** spatial object */ + SPATIAL, + /** Marker object */ + MARKER, + /** DomMarker object */ + DOM_MARKER, + /** DomMarker object */ + GROUP, + } + } + + /** + * This class represents an overlay, which offers a bitmap that covers a geographical reactangular area on the map. + */ + export class Overlay extends H.map.Object { + /** + * Constructor + * @param bounds {H.geo.Rect} - The geographical reactangular area of this overlay + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @param opt_options {H.map.Overlay.Options=} - Optional values values to initialize this overlay + */ + constructor(bounds: H.geo.Rect, bitmap: (string | HTMLImageElement | HTMLCanvasElement), opt_options?: H.map.Overlay.Options); + + /** + * This method returns this overlay's current bounds. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + + /** + * This method sets the overlay's current bounds. + * @param bounds {H.geo.Rect} + * @returns {H.map.Overlay} - the overlay itself + */ + setBounds(bounds: H.geo.Rect): H.map.Overlay; + + /** + * Returns this overlay's current bitmap. + * @returns {?(HTMLImageElement | HTMLCanvasElement)} - the bitmap of this Overlay or null if it isn't ready yet + */ + getBitmap(): (HTMLImageElement | HTMLCanvasElement); + + /** + * Sets the overlay's current bitmap. + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @returns {H.map.Overlay} - the overlay itself + */ + setBitmap(bitmap: (string | HTMLImageElement | HTMLCanvasElement)): H.map.Overlay; + + /** + * Returns this overlay's current opacity. + * @returns {number} + */ + getOpacity(): number; + + /** + * Sets the overlay's current opacity. + * @param opacity {number} - The opacity in range from 0 (transparent) to 1 (opaque). + * @returns {H.map.Overlay} - the overlay itself + */ + setOpacity(opacity: number): H.map.Overlay; + } + + export module Overlay { + /** + * Options used to initialize an Overlay + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property opacity {number=} - The opacity of the object in range from 0 (transparent) to 1 (opaque), default is 1. + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + opacity?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * This class represents a polygon in geo-space. It is defined by a strip containing the vertices of a geo shape object (lat, lng, alt values) and a pen to use when rendering the polyline. Polygon represents a closed plane defined by the list of verticies, projected on the map display. List of vericies which define the polygon are is a list of geo coordinates encapsulated by the strip object H.geo.Strip + */ + export class Polygon extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Spatial.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Spatial.Options); + + /** + * To set the indicator whether this polygon covers the north pole. It's needed for Polygons whose strip is defined as lines arround the world on longitude axis (for example a circle whose center is one of the poles). In this case a additional information is needed to know if the southern or northern part of the world should be covered by the poygon. + * @param flag {boolean} - A value of true means it covers the north pole, false means south pole + * @returns {H.map.Polygon} - the Polygon instance itself + */ + setNorthPoleCovering(flag: boolean): H.map.Polygon; + + /** + * See H.map.Polygon#setNorthPoleCovering + * @returns {boolean} + */ + getNorthPoleCovering(): boolean; + } + + /** + * This class represents a polyline in geo-space. It is defined by a path containing the vertices of a polyline (lat, lng, alt values) and a pen to use when tracing the path on the map. + */ + export class Polyline extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Polyline.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Polyline.Options); + + /** + * This method clips this polyline against a rectangular area and returns the intersecting sub-lines. + * @param geoRect {H.geo.Rect} + * @returns {Array>} + */ + clip(geoRect: H.geo.Rect): Array>; + } + + export module Polyline { + /** + * Options which are used to initialize a polyline + * @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the polyline + * @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the polyline. + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options); + arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options); + visibility?: boolean; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * A Polygon with a rectangular shape. + */ + export class Rect extends H.map.Polygon { + /** + * Constructor + * @param bounds {H.geo.Rect} - The geographical bounding box for this rectangle + * @param opt_options {H.map.Spatial.Options=} + */ + constructor(bounds: H.geo.Rect, opt_options?: H.map.Spatial.Options); + + /** + * To set the bounds of this rectangle. + * @param bounds {H.geo.Rect} + */ + setBounds(bounds: H.geo.Rect): void; + } + + /** + * This class represents a spatial map object which provides its projected geometry. + */ + export class Spatial extends H.map.Object { + /** + * Constructor + * @param isClosed {boolean} - Indicates whether this spatial object represents a closed shape + * @param opt_options {H.map.Spatial.Options=} - The options to apply + */ + constructor(isClosed: boolean, opt_options?: H.map.Spatial.Options); + + /** + * To get the drawing style of this object. The returned style is treated as immutable and must not be modified afterwards to prevent inconsistancies! + * @returns {H.map.SpatialStyle} + */ + getStyle(): H.map.SpatialStyle; + + /** + * To set the drawing style of this object. If the passed opt_style argument is an instance of H.map.SpatialStyle it is treated as immutable and must not be modified afterwards to prevent inconsistancies! . + * @param opt_style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - The style to set. If it evaluates to a falsy the H.map.SpatialStyle.DEFAULT_STYLE is used. + * @returns {H.map.Spatial} - the Spatial instance itself + */ + setStyle(opt_style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): H.map.Spatial; + + /** + * To get the arrow style of this spatial object or undefined if no style is defined. A returned arrow style is treated as immutable and must not be modified afterwards to prevent inconsistancies! + * @returns {(H.map.ArrowStyle | undefined)} + */ + getArrows(): H.map.ArrowStyle | void; + + /** + * To set the arrow style of this object. + * @param opt_arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - the arrow style to be applied + * @returns {H.map.Spatial} - the Spatial instance itself + */ + setArrows(opt_arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options)): H.map.Spatial; + + /** + * Indicates whether this spatial object represents a closed shape + * @returns {boolean} + */ + isClosed(): boolean; + } + + export module Spatial { + /** + * Data to used as rendering hint for a label + * @property x {number} - The X coordinate of the first line's starting point + * @property y {number} - The Y coordinate of the first line's base line + * @property angle {number} - The clockwise rotation angle in radians + * @property font {string} - The CSS font-family + * @property size {number} - The CSS font-size + * @property color {string} - The CSS color + * @property text {string} - The text content, new line characters (\u000A) are interpreted as line breaks + */ + export interface Label { + x: number; + y: number; + angle: number; + font: string; + size: number; + color: string; + text: string; + } + + /** + * Options which are used to initialize spatial object object + * @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the spatial object + * @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the spatial. + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options); + arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options); + visibility?: boolean; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * The SpatialStyle class represents a style with which spatial objects like polylines and polygons are drawn. A SpatialStyle instance is always treated as immutable to avoid inconstiencies and must not modified. + * @property strokeColor {string} - The color of the stroke in CSS syntax, default is 'rgba(0, 85, 170, 0.6)'. + * @property fillColor {string} - The filling color in CSS syntax, default is 'rgba(0, 85, 170, 0.4)'. + * @property lineWidth {number} - The width of the line in pixels, default is 2. + * @property lineCap {H.map.SpatialStyle.LineCap} - The style of the end caps for a line, default is 'round'. + * @property lineJoin {H.map.SpatialStyle.LineJoin} - The type of corner created, when two lines meet, default is 'miter'. + * @property miterLimit {number} - The miter length is the distance between the inner corner and the outer corner where two lines meet. The default is 10. + * @property lineDash {Array} - The line dash pattern as an even numbered list of distances to alternately produce a line and a space. The default is [ ]. + * @property lineDashOffset {number} - The phase offset of the line dash pattern The default is 0. + * @property MAX_LINE_WIDTH {number} - This constant represents the maximum line width which can be used for rendering. + * @property DEFAULT_STYLE {H.map.SpatialStyle} - This static member defines the default style for spatial objects on the map. It's value is { strokeColor: '#05A', fillColor: 'rgba(0, 85, 170, 0.4)' lineWidth: 1, lineCap: 'round', lineJoin: 'miter', miterLimit: 10, lineDash: [ ], lineDashOffset: 0 } + */ + export class SpatialStyle { + /** + * Constructor + * @param opt_options {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - The optional style attributes + */ + constructor(opt_options?: (H.map.SpatialStyle | H.map.SpatialStyle.Options)); + + /** + * This method checks value-equality with another style. + * @param other {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - the style to compare with + * @returns {boolean} - true if the styles are value-equal, otherwise false + */ + equals(other: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): boolean; + + /** + * Returns a copy of spatial style object and replaces the passed style attributes into it. + * @param opt_attributes {H.map.SpatialStyle.Options=} - The style attributes to set on the copied style instance + * @returns {H.map.SpatialStyle} + */ + getCopy(opt_attributes?: H.map.SpatialStyle.Options): H.map.SpatialStyle; + + strokeColor: string; + fillColor: string; + lineWidth: number; + lineCap: H.map.SpatialStyle.LineCap; + lineJoin: H.map.SpatialStyle.LineJoin; + miterLimit: number; + lineDash: Array; + lineDashOffset: number; + static MAX_LINE_WIDTH: number; + static DEFAULT_STYLE: H.map.SpatialStyle; + } + + export module SpatialStyle { + /** + * The style of the end caps for a line, one of 'butt', 'round' or 'square'. + */ + export type LineCap = 'butt' | 'round' | 'square'; + + /** + * The type of corner created, when two lines meet, one of 'round', 'bevel' or 'miter'. + */ + export type LineJoin = 'round' | 'bevel' | 'miter'; + + /** + * Options used to initialize a style. If a property is not set, the default value from H.map.SpatialStyle is taken. + * @property strokeColor {string=} - The color of the stroke in CSS syntax. + * @property fillColor {string=} - The color of the stroke in CSS syntax. + * @property lineWidth {number=} - The width of the line in pixels, default is 2. The maximum supported line width is 100. + * @property lineCap {H.map.SpatialStyle.LineCap=} - The style of the end caps for a line. + * @property lineJoin {H.map.SpatialStyle.LineJoin=} - The type of corner created, when two lines meet. + * @property miterLimit {number=} - The miter limit in pixel, default is 10. The maximum supported miter limit is 100 + * @property lineDash {Array} - The line dash pattern as an even numbered list of distances to alternately produce a line and a space. If the browser doesn't support this feature this style property is ignored. + * @property lineDashOffset {number=} - The phase offset of the line dash pattern + */ + export interface Options { + strokeColor?: string; + fillColor?: string; + lineWidth?: number; + lineCap?: H.map.SpatialStyle.LineCap; + lineJoin?: H.map.SpatialStyle.LineJoin; + miterLimit?: number; + lineDash?: Array; + lineDashOffset?: number; + } + } + + /** + * This class represents a view of the map. It consists of a virtual camera and a look-at point both of which have a position in geo-space and orientation angles. The view model allows to change the values of these objects in order to move or rotate the map or zoom in and out. + */ + export class ViewModel extends H.util.EventTarget implements H.map.IControl { + /** + * This method returns the camera data, which is currently rendered. + * @returns {H.map.ViewModel.CameraData} - the current rendered camera data + */ + getCameraData(): H.map.ViewModel.CameraData; + + /** + * This method sets new camera data to be processed by the renderer. + * @param data {H.map.ViewModel.CameraData} - the values to be modified + * @returns {H.map.ViewModel} - this view model object + */ + setCameraData(data: H.map.ViewModel.CameraData): H.map.ViewModel; + + /** + * This method sets a new zoom level to be processed by the renderer + * @param zoom {number} - the new zoom level + * @param animate {boolean} + */ + setZoom(zoom: number, animate: boolean): void; + + /** + * This method returns the zoom level that is currently rendered. + * @returns {number} - current zoom level (scale) + */ + getZoom(): number; + + /** + * This method returns the currently requested data. + * @returns {H.map.ViewModel.CameraData} - last requested cam/view data + */ + getRequestedCameraData(): H.map.ViewModel.CameraData; + + /** + * A method to signal the begin of a control operation. + * @param opt_kinetics {H.util.kinetics.IKinetics=} - kinetics settings + * @param opt_atX {number=} - x screen coordinate at which control has started + * @param opt_atY {number=} - y screen coordinate at which control has started + */ + startControl(opt_kinetics?: H.util.kinetics.IKinetics, opt_atX?: number, opt_atY?: number): void; + + /** + * A method to set the values for a continuously modification of the ViewModel on different axes. If the current render engine doesn't support certain modifications then they are ignored. + * @param moveX {number} - The movement on x-axis as levels per millisecond where a level correlates to the distance between camera and look-at point. + * @param moveY {number} - The movement on y-axis as levels per millisecond where a level correlates to the distance between camera and look-at point + * @param moveZ {number} - The movement on z-axis as levels per millisecond. + * @param angleX {number} - The rotation of on screen's x axis as degrees per millisecond. + * @param angleY {number} - The rotation of on screen's y axis as degrees per millisecond. + * @param angleZ {number} - The rotation of on screen's z axis as degrees per millisecond. + * @param opt_zoom {number=} - The modification of the zoom level as levels per millisecond + */ + control(moveX: number, moveY: number, moveZ: number, angleX: number, angleY: number, angleZ: number, opt_zoom?: number): void; + + /** + * A method to signal the end of a control operation. + * @param opt_preventKinetics {boolean=} - A flag to indicate whether a kinetic effect is performed + * @param opt_adjustView {function(H.map.ViewModel.CameraData)=} - An callback to adjust the final ViewModel by modifying the passed camera data. + */ + endControl(opt_preventKinetics?: boolean, opt_adjustView?: (data: H.map.ViewModel.CameraData) => void): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module ViewModel { + /** + * Defines camera's properties. + * @property zoom {number=} - zoom level to be used by rendering engine + * @property position {H.geo.IPoint} - the position of the virtual camera in geo-space + * @property pitch {number=} - the rotation of the virtual camera along its local x-axis + * @property yaw {number=} - the rotation of the virtual camera along its local y-axis + * @property roll {number=} - the rotation of the virtual camera along its local z-axis + * @property fov {number=} - + */ + export interface CameraData { + zoom?: number; + position: H.geo.IPoint; + pitch?: number; + yaw?: number; + roll?: number; + fov?: number; + } + + /** + * Defines currently requested view data, which will be rendered by the map. + * @property camera {H.map.ViewModel.CameraData=} - The requested camera properties + * @property zoom {number=} - The requested zoom level + * @property animate {boolean=} - indicates if the requested transition should be animated + */ + export interface RequestedData { + camera?: H.map.ViewModel.CameraData; + zoom?: number; + animate?: boolean; + } + + /** + * Update event is fired whenever view model data is changed. It contains property which hold currently requested data + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class UpdateEvent extends H.util.Event { + /** + * Constructor + * @param requested {H.map.ViewModel.RequestedData} + */ + constructor(requested: H.map.ViewModel.RequestedData); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + } + + /** + * ViewPort object holds information about the HTML element where the map is rendered. It contains information regarding the element (view port) size and triggers events when the element size is changed. + * @property element {Element} - This property holds the HTML element, which defines the viewport. + * @property width {number} - This property holds this viewport's current width + * @property height {number} - This property holds this viewport's current height + * @property margin {number} - This property holds this viewport's current margin value + * @property padding {H.map.ViewPort.Padding} - This property holds this viewport's current padding + * @property center {H.math.Point} - This property holds this viewport's current center point + */ + export class ViewPort extends H.util.EventTarget implements H.map.IInteraction { + /** + * Constructor + * @param element {Element} - html element were map will be rendered + * @param opt_options {H.map.ViewPort.Options=} - optional configuration parameters + */ + constructor(element: Element, opt_options?: H.map.ViewPort.Options); + + /** + * This method sets the margin on the viewPort + * @param margin {number} - margin which is used to fetch map data + */ + setMargin(margin: number): void; + + /** + * This method sets the padding on the viewport. Padding will result in shifted map center which will be the visual center of the padded area. + * @param top {number} - padding from the top + * @param right {number} - padding from the right + * @param bottom {number} - padding from the bottom + * @param left {number} - padding from the left + */ + setPadding(top: number, right: number, bottom: number, left: number): void; + + /** + * This method updates size of the viewport according to container size. It must be called whenever the HTML element changed size in order to update the map's viewport values. + */ + resize(): void; + + /** + * This method starts the interaction with the view port. Should be called every time when new interaction is started i.e mouse grab, or touch start. + * @param modifiers {number} - a bitmask which specifies what operations should performed during every interaction + * @param opt_kinetics {H.util.kinetics.IKinetics=} - specifies kinetic move at the end of interaction + */ + startInteraction(modifiers: H.math.BitMask, opt_kinetics?: H.util.kinetics.IKinetics): void; + + /** + * This method resolves direct screen (view port) interaction. This function will modify the current view according to values passed in. + * @param x {number} - viewport x coordinate + * @param y {number} - viewport y coordinate + * @param opt_bx {number=} - x coordinate for second pointer/touch if present + * @param opt_by {number=} - y coordinate for secong pointer/touch if present + * @param opt_timestamp {number=} - known timestamp which should be passed + */ + interaction(x: number, y: number, opt_bx?: number, opt_by?: number, opt_timestamp?: number): void; + + /** + * This method ends interaction and applies kinetic movement if defined by using startInteraction method + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics behaviour at the end of interaction + */ + endInteraction(opt_preventKinetics?: boolean): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + element: Element; + width: number; + height: number; + margin: number; + padding: H.map.ViewPort.Padding; + center: H.math.Point; + } + + export module ViewPort { + /** + * Options which may be used to initialize new ViewPort instance + * @property margin {number=} - The size in pixel of the supplemental area to render for each side of the map + * @property padding {H.map.ViewPort.Padding=} - The padding in pixels for each side of the map + * @property fixedCenter {boolean=} - Indicates whether the center of the map should remain unchanged if the viewport's size or or padding has been changed, default is true + */ + export interface Options { + margin?: number; + padding?: H.map.ViewPort.Padding; + fixedCenter?: boolean; + } + + /** + * Represents viewport padding definition. + * @property top {number} - the padding on the top edge (in pixels) + * @property right {number} - the padding on the right edge (in pixels) + * @property bottom {number} - the padding on the bottom edge (in pixels) + * @property left {number} - the padding on the left edge (in pixels) + */ + export interface Padding { + top: number; + right: number; + bottom: number; + left: number; + } + } + + export module layer { + /** + * BaseTileLayer encapsulates funcitonailty that is common to all layers that deliver tiles, such as H.map.layer.TileLayer. The functionality includes geo bounding box to grid calculation, tile request management. + */ + export class BaseTileLayer extends H.map.layer.Layer { + /** + * Constructor + * @param provider {H.map.provider.TileProvider} - data source for the TileLayer + * @param opt_options {H.map.layer.ITileLayer.Options=} - additional options + */ + constructor(provider: H.map.provider.TileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method returns the provider which feeds this layer with data. + * @returns {H.map.provider.TileProvider} - this layer's provider + */ + getProvider(): H.map.provider.TileProvider; + + /** + * This method transforms a geo-rectangle to geometrical projected rectangle at the current projection zoom level or at provided zoom level + * @param geoRect {H.geo.Rect} - geo bounds to be projected + * @param opt_zoom {number=} - overrides current projection zoom level + * @returns {H.math.Rect} - projected 2d space rect cooresponding to provided geo bounds + */ + geoRectToRect(geoRect: H.geo.Rect, opt_zoom?: number): H.math.Rect; + + /** + * This method returns tile grid for a bounding rectangle + * @param rectBounds {H.math.Rect} - projected rect bounds which coorespond to geo bounding box + * @param zoom {number} - current zoom level + * @returns {H.math.Rect} - rectangle which represents the tile grid bounds + */ + getTileBounds(rectBounds: H.math.Rect, zoom: number): H.math.Rect; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + + /** + * This method requests tiles from the data source (provider). It can return a set of tiles which are currently loaded. All tiles which are not yet loaded will be included in response as soon as they will be available during subsequent calls. + * @param tileBounds {H.math.Rect} - bounds in tile grid + * @param isCDB {boolean} + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - returns an array if tile which are already loaded + */ + getProviderTiles(tileBounds: H.math.Rect, isCDB: boolean, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + } + + /** + * This interface describes a layer which provides marker objects to the renderer. + */ + export interface IMarkerLayer { + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + export module IMarkerLayer { + /** + * This type represents a response object returned by the H.map.layer.IMarkerLayer#requestMarkers function. + * @property total {number} - The total number of markers, inclusive markers with not ready icons + * @property markers {Array} - The marker objects for the bounding rectangle (only ready) + */ + export interface Response { + total: number; + markers: Array; + } + + /** + * This type represents a response object returned by the H.map.layer.IMarkerLayer#requestMarkers function. + * @property number {number} - of returned tiles + * @property requested {number} - number of requested tiles + * @property objects {Array} - the marker objects within requested tiled area + */ + export interface TiledResponse { + number: number; + requested: number; + objects: Array; + } + } + + /** + * This interface describes a layer which provides data partitioned in quad-tree tiles in an x, y, z fashion (where z describes the level within the tree and x and y describe the absolute column and row indeces whithin the level). + */ + export interface ITileLayer { + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + } + + export module ITileLayer { + /** + * Options which are used to initialize a TileLayer object. + * @property projection {H.geo.IProjection=} - an optional projection to be used for this layer, default is H.geo.mercator + * @property opacity {number=} - tile layer opacity, default is 1 + */ + export interface Options { + projection?: H.geo.IProjection; + opacity?: number; + } + + /** + * A response object for a tile request. Contains total number of elements requested and an array of currently available Tiles + * @property total {number} - the total number of requested tiles + * @property tiles {Array} - the tiles which this provider can currently return synchronously + */ + export interface Response { + total: number; + tiles: Array; + } + } + + /** + * The Layer class represents an object that is evaluated by the renderer in the order in which it is added to the layers collection. It provides the basic infrastructure for dispatching update events to the renderer in case new data is available. + */ + export class Layer extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.layer.Layer.Options=} - optional configuration object + */ + constructor(opt_options?: H.map.layer.Layer.Options); + + /** + * This method checks if a zoom level can be served by this layer. + * @param zoomLevel {number} - the zoom level to check + * @returns {boolean} - true if this layer can provide data for the zoom level, otherwise false + */ + isValid(zoomLevel: number): boolean; + + /** + * This method sets the minimum zoom level for which this layer will provide tiles. + * @param min {number} - The new minimum zoom level of this layer + * @returns {H.map.layer.Layer} - Returns this instance of the layer + */ + setMin(min: number): H.map.layer.Layer; + + /** + * This method sets the maximum zoom level for which this layer will provide tiles. + * @param max {number} - The new maximum zoom level of this layer + * @returns {H.map.layer.Layer} - Returns this instance of the layer + */ + setMax(max: number): H.map.layer.Layer; + + /** + * This method returns the copyright of the current data provider. + * @param bounds {H.geo.Rect} - the bounding area for which to retrieve the copyright information + * @param level {number} - the zoom level for which to retrieve the copyright information + * @returns {Array} - a list of copyright information objects for the provided area and zoom level + */ + getCopyrights(bounds: H.geo.Rect, level: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Layer { + /** + * Options which can be used when creating new layer object. + * @property min {number=} - The minimum zoom level for which the layer can provide data, default is 0 + * @property max {number=} - The maximum zoom level for which the layer can provide data, default is 22 + * @property dark {boolean=} - Indicates whether the content of this layer is mainly dark, default is false See also H.Map.Options#autoColor + * @property projection {H.geo.IProjection=} - The projection to be used for this layer, default is H.geo.mercator + * @property minWorldSize {number=} - The minimal world size at zoom level 0, default is 256 + */ + export interface Options { + min?: number; + max?: number; + dark?: boolean; + projection?: H.geo.IProjection; + minWorldSize?: number; + } + } + + /** + * ObjectTileLayer represents map objects which are requested on a tile basis + */ + export class MarkerTileLayer extends H.map.layer.BaseTileLayer implements H.map.layer.IMarkerLayer { + /** + * Constructor + * @param provider {H.map.provider.MarkerTileProvider} + * @param opt_options {H.map.layer.ITileLayer.Options=} + */ + constructor(provider: H.map.provider.MarkerTileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + /** + * This class represents a layer which renders map objects. Spatial objects like polygons and polylines a rendered to tiles before being passed to the enigne. Point objects like markers are provided as objects given an rectangular area. + */ + export class ObjectLayer extends H.map.layer.Layer implements H.map.layer.ITileLayer { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - the ObjectProvider which provides the map objects to this object layer. + * @param opt_options {H.map.layer.ObjectLayer.Options=} - The options for this layer + */ + constructor(provider: H.map.provider.ObjectProvider, opt_options?: H.map.layer.ObjectLayer.Options); + + /** + * This method returns current ObjectLayer's data provider + * @returns {H.map.provider.ObjectProvider} + */ + getProvider(): H.map.provider.ObjectProvider; + + /** + * To request overlay objects for the passsed bounding rectangle. It returns all overlay objects which are contained within this bounding rectangle. + * @param bounds {H.geo.Rect} - The bounding rectangle for which overlays are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ObjectLayer.OverlaysResponse} + */ + requestOverlays(bounds: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ObjectLayer.OverlaysResponse; + + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + export module ObjectLayer { + /** + * Configuration object which can be use to initialize the ObjectLayer. + * @property tileSize {number=} - the size of the tiles rendered by this layer for polylines and polygons (must be power of 2, default is 256) + * @property tileCacheSize {number=} - the number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property dataCacheSize {number=} - the number of tiles to cache which have render data only, default is 512 + * @property pixelRatio {number=} - The pixelRatio to use for over-sampling in cases of high-resolution displays + */ + export interface Options { + tileSize?: number; + tileCacheSize?: number; + dataCacheSize?: number; + pixelRatio?: number; + } + + /** + * A response object returned by the H.map.layer.ObjectLayer#requestOverlays function. + * @property total {number} - The total number of overlays within the requested bounds, inclusive overlays which are not ready loaded yet + * @property overlays {Array} - A list all overlays which are ready to render + */ + export interface OverlaysResponse { + total: number; + overlays: Array; + } + } + + /** + * Tile Layer, represents data shown on map on a tile basis. Can be used to show map tile images or other type of data which is partitioned into tiles. + * @event update {H.util.Event} + */ + export class TileLayer extends H.map.layer.BaseTileLayer implements H.map.layer.ITileLayer { + /** + * Constructor + * @param provider {H.map.provider.TileProvider} - data source for the TileLayer + * @param opt_options {H.map.layer.ITileLayer.Options=} - additional options + */ + constructor(provider: H.map.provider.TileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + update: H.util.Event; + } + } + + export module provider { + /** + * An ImageTileProvider uses network service to provide bitmap images as tiles. + * @property tileSize {number} - Size of a tile image supported by the provider + */ + export class ImageTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param options {H.map.provider.ImageTileProvider.Options} - configuration for tile provider + */ + constructor(options: H.map.provider.ImageTileProvider.Options); + + tileSize: number; + } + + export module ImageTileProvider { + /** + * Options to initialize an ImageTileProvider instance + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number) : ?Array)=} - A function to replace the default implementation of H.map.provider.Provider#getCopyrights + * @property tileSize {number=} - The size of a tile as edge length in pixels. It must be 2^n where n is in range [0 ... 30], default is 256 + * @property getURL {function(number, number, number)} - The function to create an URL for the specified tile. If it returns a falsy the tile is not requested. + * @property crossOrigin {(string | boolean=)} - The CORS settings to use for the crossOrigin attribute for the image, if omitted or if the value evaluates to false no CORS settings are used. + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?: ((rect: H.geo.Rect, n: number) => Array); + tileSize?: number; + getURL: (n1: number, n2: number, n3: number) => string; + crossOrigin?: (string | boolean); + } + } + + /** + * This class represents invalidation states of a renderable object. A renderer can optimize its rendering strategies based on the information in this object. + * @property MARK_INITIAL {H.map.provider.Invalidations.Mark} - This constant represents the initial invalidation mark an invalidations object has. + */ + export class Invalidations { + + /** + * To update invalidation marks accordingly to the given the invalidation types. + * @param mark {H.map.provider.Invalidations.Mark} - The invalidation mark to set + * @param types {H.math.BitMask} - The descrete invalidation types to update + */ + update(mark: H.map.provider.Invalidations.Mark, types: H.math.BitMask): void; + + /** + * This method returns the current invalidation mark of this invalidations object. + * @returns {H.map.provider.Invalidations.Mark} - the current invalidation mark + */ + getMark(): H.map.provider.Invalidations.Mark; + + /** + * Checks whether any change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isAny(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a visual change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isVisual(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a spatial change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isSpatial(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether an add-operation occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isAdd(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a remove operation occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isRemove(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a z-order change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isZOrder(since: H.map.provider.Invalidations.Mark): boolean; + + static MARK_INITIAL: H.map.provider.Invalidations.Mark; + } + + export module Invalidations { + /** + * This enumeration encapsulates bit flags for different invalidations of map objects. + */ + export enum Flag { + NONE, + VISUAL, + SPATIAL, + ADD, + REMOVE, + Z_ORDER, + } + + /** + * The invalidation mark represents a counter which is increased whenever an invalidation takes place. + */ + export interface Mark { } + } + + /** + * A MarkerTileProvider uses network service to provide markers on tile basis. + * @property requestTile {} - Request data on a tile basis + * @property cancelTile {} - Cancels tile from being requested using x, y, z coordinates (column, row, zoom) + * @property cancelTileByKey {} - Cancels tile from being requested using a tile-key + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class MarkerTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param options {H.map.provider.MarkerTileProvider.Options} - configuration for tile provider + */ + constructor(options: H.map.provider.MarkerTileProvider.Options); + + /** + * To signal to this provider that a map object has been changed. The method marks tile, that contains that object as invalid and triggers dispatchUpdate() + * @param marker {!H.map.AbstractMarker} - The map object to be invalidated + * @param flags {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(marker: H.map.AbstractMarker, flags: H.math.BitMask): void; + + /** + * Checks whether this provider is currently providing H.map.DomMarker map objects. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + } + + export module MarkerTileProvider { + /** + * Options which are used to initialize the MarkerTileProvider object. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property requestData {function(number, number, number, function(Array), Function) : H.util.ICancelable} - function that fetches marker data and creates array of H.map.AbstractMarker that is passed success callback, if function fails to fetch data onError callback must be called + * @property providesDomMarkers {boolean=} - indicates if markers provided are of type H.map.DomMarker or H.map.Marker, default is H.map.Marker + */ + export interface Options { + min?: number; + max?: number; + requestData: (n1: number, n2: number, n3: number, markerCallback: (markers: Array) => void, f: Function) => H.util.ICancelable; + providesDomMarkers?: boolean; + } + } + + /** + * An abstract class to manage and provide map objects (Marker, Polyline, Polygon) + */ + export class ObjectProvider extends H.map.provider.Provider { + /** + * Constructor + * @param opt_options {H.map.provider.Provider.Options=} + */ + constructor(opt_options?: H.map.provider.Provider.Options); + + /** + * Returns the accumulate invalidations of this provider's objects that have occurred. + * @param opt_type {H.map.Object.Type=} - The type of objects to consider for the invalidations. If undefined, all types are taken into account. + * @returns {H.map.provider.Invalidations} + */ + getInvalidations(opt_type?: H.map.Object.Type): H.map.provider.Invalidations; + + /** + * To signal to this provider that a map object has been changed. The method updates the Invalidations of this provider and the given map object and triggers dispatchUpdate() + * @param mapObject {!H.map.Object} - The map object to be invalidated + * @param changes {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(mapObject: H.map.Object, changes: H.math.BitMask): void; + + /** + * Checks whether this provider is currently providing overlay map objects. A concrete implementation of ObjectProvider must override it if it currently provides overlays. + * @returns {boolean} + */ + providesOverlays(): boolean; + + /** + * Returns all Overlay objects which intersect with the provided area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestOverlays(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing spatial map objects. A concrete implementation of ObjectProvider must override it if it currently provides Spatials. + * @returns {boolean} + */ + providesSpatials(): boolean; + + /** + * Returns all polyline, polygon, circle and rect objects which intersect with the provided area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatials(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the spatial objects which intersect the given tile + * @param tile {H.map.provider.SpatialTile} - The tile for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatialsByTile(tile: H.map.provider.Tile, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing Marker map objects. A concrete implementation of ObjectProvider must override it if it currently provides Markers. + * @returns {boolean} + */ + providesMarkers(): boolean; + + /** + * Returns all Marker map objects which intersect with the provided rectangular area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestMarkers(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing DomMarker map objects. A concrete implementation of ObjectProvider must override it if it currently provides Markers. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + + /** + * Returns all DomMarker map objects which intersect with the provided rectangular area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestDomMarkers(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + } + + /** + * A Provider defines an object which works as a database for the map. Providers can exists in different forms they can implement client side object storage or they can request data from the remote service. + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class Provider extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.provider.Provider.Options=} + */ + constructor(opt_options?: H.map.provider.Provider.Options); + + /** + * This method returns the copyrights of the provided content for a certain geographical area at a specified zoom level. + * @param bounds {H.geo.Rect} - The bounding area for which to retrieve the copyright information + * @param level {number} - The zoom level for which to retrieve the copyright information + * @returns {?Array} - a list of copyright information objects for the provided area and zoom level + */ + getCopyrights(bounds: H.geo.Rect, level: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + uri: string; + min: number; + max: number; + uid: string; + } + + export module Provider { + /** + * Options to initialize a Provider instance + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number) : ?Array)=} - A function to replace the default implementation of H.map.provider.Provider#getCopyrights + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?: (rect: H.geo.Rect, n: number) => Array; + } + } + + /** + * RemoteTileProvider is an abstract class which should be used by classes implementing data provision on a tile basis. Every child class needs to implement 'requestInternal' (to request remote tile) and 'getCache' (to provide configured cache object were tiled data is being cached) + */ + export class RemoteTileProvider extends H.map.provider.TileProvider { + /** + * Constructor + * @param options {H.map.provider.TileProvider.Options} - The options to instantiate this TileProvider + */ + constructor(options: H.map.provider.TileProvider.Options); + + /** + * This method returns cache which should be used to store tiles + * @returns {H.util.ICache} - cache + */ + getCache(): H.util.ICache; + + /** + * This method request tile from remote service + * @param x {number} - The row number of the tile + * @param y {number} - The column number of the tile + * @param z {number} - The zoom level for which the tile is requested + * @param onResponse {function((Array | HTMLImageElement | HTMLCanvasElement | ArrayBuffer | null), *=)} - function which is called after response arrives + * @param onError {function(string=)} - function which is called in case of communication error + * @param opt_priority {H.net.Request.Priority=} - optional request priority level + * @returns {H.util.ICancelable} + */ + requestInternal( + x: number, + y: number, + z: number, + + onResponse?: ( + object: Array | HTMLImageElement | HTMLCanvasElement | ArrayBuffer, + response: any + ) => void, + + onError?: (s: string) => void, + opt_priority?: H.net.Request.Priority + ): H.util.ICancelable; + + /** + * This method instructs the provider to reload data from it's source. + * @param hard {boolean} - a boolean flag indicating whether to invalidate in hard mode (true) or in soft mode (false); + */ + reload(hard: boolean): void; + } + + /** + * Generic Tile object which represents a part of the world fiting into the Tile area represented by the Tiel coordinates (x - row, y - column) and the zoom level (z). Number of tiles at particular zoom level (which means number of areas into world is being splitted) is defined as following: numberOfRows = numberOfColumns = 2^zoomlevel + * @property key {string} - Unique tile key generated by provider + * @property data {*} - Tile data (an image for example) + * @property valid {boolean} - This property holds a boolean flag indicating whether this tile is still valid (true) or whether it should be re-fetched (false) + * @property x {number} - Tile column + * @property y {number} - Tile row + * @property z {number} - Tile zoom level + */ + export class Tile { + /** + * Constructor + * @param x {number} - x tile coordinate (row) + * @param y {number} - y tile coordinate (column) + * @param z {number} - tile zoom level + * @param data {*} - generic data object which cooresponds to the given coordinates + */ + constructor(x: number, y: number, z: number, data?: any); key: string; + + data: any; + valid: boolean; + x: number; + y: number; + z: number; + } + + /** + * TileProvider is an abstract class to provide data on a tile basis + * @property requestTile {} - Request data on a tile basis + * @property cancelTile {} - Cancels tile from being requested using x, y, z coordinates (column, row, zoom) + * @property cancelTileByKey {} - Cancels tile from being requested using a tile-key + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class TileProvider extends H.map.provider.Provider { + /** + * Constructor + * @param options {H.map.provider.TileProvider.Options} - The options to instantiate this TileProvider + */ + constructor(options: H.map.provider.TileProvider.Options); + + /** + * This method creates a tile object with given parameters + * @param x {number} - x tile coordinate (row) + * @param y {number} - y tile coordinate (column) + * @param z {number} - tile coordinate (zoom) + * @param data {(HTMLImageElement | HTMLCanvasElement)} - data for the tile + * @param opt_options {Object=} - free form options object. These options are meant to be used in tile specific rendering cases + * @returns {H.map.provider.Tile} + */ + createTileInternal(x: number, y: number, z: number, data: (HTMLImageElement | HTMLCanvasElement), opt_options?: { [key: string]: any }): H.map.provider.Tile; + + /** + * This method creates a tile key consisting of the provider's uri, and the tile's x, y and z coordinates, seperated by underscores e.g.: "4711_7_42_23" + * @param x {number} - The x tile coordinate (row) + * @param y {number} - The y tile coordinate (column) + * @param z {number} - The z tile coordinate (zoom level) + * @returns {string} - string + */ + getTileKey(x: number, y: number, z: number): string; + + requestTile: any; + cancelTile: any; + cancelTileByKey: any; + uri: string; + min: number; + max: number; + uid: string; + } + + export module TileProvider { + /** + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number): Array)=} - A function to replace the default implememtation of H.map.provider.Provider#getCopyrights + * @property tileSize {number=} - The size of a tile as edge length in pixels. It must be 2^n where n is in range [0 ... 30], default is 256 + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?(rect: H.geo.Rect, number: number): Array; + tileSize?: number; + } + } + } + } + + /***** mapevents *****/ + export module mapevents { + /** + * Behavior class uses map events and adds behavior functionality to the map. This allows map panning and zooming via using mouse wheel + * @property DRAGGING {number} - Map responds to user dragging via mouse or touch + * @property WHEELZOOM {number} - Map zooms in or out in respond to mouse wheel events + * @property DBLTAPZOOM {number} - Map zooms in or out in response to double click or double tap. For double tap if more that one touches are on the screen map will zoom out. + */ + export class Behavior extends H.util.Disposable { + /** + * Constructor + * @param mapEvents {H.mapevents.MapEvents} - previously initialized map events instance + * @param options {H.mapevents.Behavior.Options} - additional options (i.e kinetics) + */ + constructor(mapEvents: H.mapevents.MapEvents, options?: H.mapevents.Behavior.Options); + + /** + * This method destroys all map interaction handling. Should be used when the behavior functionality is disposed. Behavior object will also be disposed (this function will be called) when attached H.mapevents.MapEvents object is dispose. + */ + dispose(): void; + + /** + * This method disables the behavior functionality for the map + * @param opt_behavior {number=} - The bitmask of behaviors to disable. If no arguments are passed, all behaviors will be disabled. + */ + disable(opt_behavior?: H.math.BitMask): void; + + /** + * This method re-enables the behavior functionality for the map. + * @param opt_behavior {number=} - The bitmask of behaviors to enable. If no arguments are passed, all behaviors will be enabled. + */ + enable(opt_behavior?: H.math.BitMask): void; + + /** + * This method checks if certain functionality is enabled + * @param behavior {number} - value like H.mapevents.Behavior.DRAGGING which the check is being performed + * @returns {boolean} + */ + isEnabled(behavior: number): boolean; + + static DRAGGING: number; + static WHEELZOOM: number; + static DBLTAPZOOM: number; + } + + export module Behavior { + /** + * Options which are used to initialize the Behavior class. + * @property kinetics {H.util.kinetics.IKinetics=} - The parameters for the kinetic movement. + * @property enable {number=} - The bitmask of behaviors to enable like H.mapevents.Behavior.DRAGGING. All are enabled by default. + */ + export interface Options { + kinetics?: H.util.kinetics.IKinetics; + enable?: H.math.BitMask; + } + } + + /** + * ContextMenuEvent should be fired, when a user right-clicks or longpresses on a map object. + * @property viewportX {Array} - Contains ContextItems, that will be used to create context menu entries. Should be filled by listeners of the "contextmenu" event + * @property viewportY {number} - Map viewport y position + * @property target {(H.map.Object | H.Map)} - Target for the event + * @property originalEvent {Event} - Original event + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class ContextMenuEvent extends H.util.Event { + /** + * Constructor + * @param viewportX {number} - The x coordinate on the viewport + * @param viewportY {number} - The y coordinate on the viewport + * @param target {(H.Map | H.map.Object)} - The event's target element + * @param originalEvent {Event} - target of the event + */ + constructor(viewportX: number, viewportY: number, target: (H.Map | H.map.Object), originalEvent: Event); + + viewportX: Array; + viewportY: number; + originalEvent: Event; + } + + /** + * Custom map event. Contains list of pointers on the map, list of changed pointers and original event. Inherits from H.util.Event. + * @property pointers {Array} - Pointers which are currently on the screen + * @property changedPointers {Array} - Pointers which has changed in course of event + * @property targetPointers {Array} - Pointers which are on same target as the current pointer + * @property currentPointer {H.mapevents.Pointer} - Current pointer + * @property originalEvent {Event} - Original event fired by the browser + * @property target {(H.map.Object | H.Map)} - Object which triggered event. Can be the map object (i.e marker or polyline) or the map itself + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param type {string} - type of event + * @param pointers {Array} - pointers which are currently on the screen + * @param changedPointers {Array} - pointers which changed during event + * @param targetPointers {Array} - pointers on the event target + * @param currentPointer {H.mapevents.Pointer} - pointer which triggered the event + * @param target {(H.Map | H.map.Object)} - target map object which triggered event + * @param originalEvent {Event} - original dom event + */ + constructor(type: string, pointers: Array, changedPointers: Array, targetPointers: Array, currentPointer: H.mapevents.Pointer, target: (H.Map | H.map.Object), originalEvent: Event); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + pointers: Array; + changedPointers: Array; + targetPointers: Array; + currentPointer: H.mapevents.Pointer; + originalEvent: Event; + target: (H.map.Object | H.Map); + currentTarget: (H.map.Object | H.Map); + type: string; + defaultPrevented: boolean; + } + + /** + * MapEvents enable the events functionality on the map and on the map objects. By using this extension it is possible to listen to events on map objects like markers, polylines, polygons, circles and on the map object itself. Events are triggered depending on user interaction. Please check the Events Summary section for the list of events fired by this class and by the map objects. + */ + export class MapEvents extends H.util.Disposable { + /** + * Constructor + * @param map {H.Map} - map instance which is used for firing events + */ + constructor(map: H.Map); + + /** + * This method destroys the MapEvents by removing all handlers from the map object. After calling this function mapEvents and map objects will not trigger any events. This object will be disposed automatically if the corresponding map object is disposed. + */ + dispose(): void; + + /** + * This method returns map into which events are attached + * @returns {H.Map} + */ + getAttachedMap(): H.Map; + } + + /** + * Class representing pointer on the map surface. A pointer in platform specific definition would mean either mouse, touch, pen or any pointing device which can trigger browser events. + * @property viewportX {number} - X coordinate on the map's viewport + * @property viewportY {number} - Y coordinate on the map's viewport + * @property target {(H.map.Object | H.Map)} - Map object directly under the pointer. Can be null if if pointer is out of the map viewport + * @property id {number} - Pointer unique identifier. + * @property type {string} - Pointer type can be: 'mouse', 'touch' or 'pen' + * @property dragTarget {(H.map.Object | H.Map)} - Object which is currently dragged by the pointer + * @property button {H.mapevents.Pointer.Button} - Indicates which pointer device button has changed. + */ + export class Pointer { + /** + * Constructor + * @param viewportX {number} - pointer position on x-axis + * @param viewportY {number} - pointer position on y-axis + * @param id {number} - unique pointer identifier among currently available pointers + * @param type {string} - type of pointer can be i.e 'mouse', 'touch'. 'pen' + * @param opt_button {H.mapevents.Pointer.Button=} - Indicates which pointer device button has changed. + * @param opt_buttons {number=} - Indicates which pointer device buttons are being pressed, expressed as a bitmask. Uses the same values, as "buttons" in Pointer Events spec. + */ + constructor(viewportX: number, viewportY: number, id: number, type: string, opt_button?: H.mapevents.Pointer.Button, opt_buttons?: H.math.BitMask); + static viewportX: number; + static viewportY: number; + static target: (H.map.Object | H.Map); + static id: number; + static type: string; + static dragTarget: (H.map.Object | H.Map); + static button: H.mapevents.Pointer.Button; + } + + export module Pointer { + /** + * Types of a button + */ + export enum Button { + /** No button */ + NONE, + /** Left mouse button or touch contact or pen contact */ + LEFT, + /** Middle mouse button */ + MIDDLE, + /** Right mouse button or Pen barrel button */ + RIGHT, + } + + /** + * Indicates which pointer device buttons are being pressed, expressed as a bitmask. Bit values are: + * + * - 0: No button pressed + * - 1: Left mouse button pressed, or Touch contact or Pen contact + * - 2: Right mouse button pressed, or Pen contact with barrel button pressed + * - 4: Middle mouse button pressed + */ + // TODO not sure this is the right interpretation of the docs + export type Buttons = H.math.BitMask; + } + + /** + * WheelEvent is fired when the mouse wheel is used over the map. It contains information about cursor position and the map object which resides directly under the cursor. + * @property delta {number} - Wheel move delta + * @property viewportX {number} - Map viewport x position + * @property viewportY {number} - Map viewport y position + * @property target {(H.map.Object | H.Map)} - Target for the event + * @property originalEvent {Event} - Original mouse wheel event + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class WheelEvent extends H.util.Event { + /** + * Constructor + * @param deltaY {number} - The wheel move delta on y-axis + * @param viewportX {number} - The x coordinate on the viewport + * @param viewportY {number} - The y coordinate on the viewport + * @param target {(H.Map | H.map.Object)} - The event's target element + * @param originalEvent {Event} - target of the event + */ + constructor(deltaY: number, viewportX: number, viewportY: number, target: (H.Map | H.map.Object), originalEvent: Event); + + delta: number; + viewportX: number; + viewportY: number; + originalEvent: Event; + } + } + + /***** math *****/ + export module math { + /** + * A signed 32 bit integer (JS restriction) where bit operator can be applied to. The range is [-2,147,483,648 ... 2,147,483,647] or [-2^31 ... 2^31 − 1] + */ + export type BitMask = number; + + /** + * An interface for a 2-dimensional point consisting a x and y coordinate. + * @property x {number} - The point's coordinate on X-axis. + * @property y {number} - The point's coordinate on Y-axis. + */ + export interface IPoint { + x: number; + y: number; + } + + /** + * An interface for a 2-dimensional size consisting a with and a height. + * @property w {number} - The size's width. + * @property h {number} - The size's height. + */ + export interface ISize { + w: number; + h: number; + } + + /** + * Class represents a 2-dimensional point, defined by x and y coordinates. + * @property x {number} - The point's coordinate on X-axis. + * @property y {number} - The point's coordinate on Y-axis. + */ + export class Point implements IPoint { + /** + * Constructor + * @param x {number} - The point's coordinate on X-axis. + * @param y {number} - The point's coordinate on Y-axis. + */ + constructor(x: number, y: number); + + /** + * Sets the x and y coordinate of this point + * @param x {number} - The point's coordinate on X-axis. + * @param y {number} - The point's coordinate on Y-axis. + */ + set(x: number, y: number): void; + + /** + * This method creates a copy of the current point. + * @param opt_out {H.math.Point=} - An optional point to store the copied values + * @returns {H.math.Point} - The clone of the point + */ + clone(opt_out?: Point): Point; + + /** + * This method adds given point coordinates to the current one. + * @param other {H.math.IPoint} - The point to add + * @returns {H.math.Point} - the point itself after adding + */ + add(other: IPoint): Point; + + /** + * This method subtracts given point coordinates from the current point. + * @param other {H.math.IPoint} - The point to subtract + * @returns {H.math.Point} - the point itself after subtracting + */ + sub(other: IPoint): Point; + + /** + * This method scales the current point coordinates by the given factor(s). + * @param factor {number} - multiplication factor + * @param opt_factorY {number=} - If omitted, the factor argument is used + * @returns {H.math.Point} - the point itself after scaling + */ + scale(factor: number, opt_factorY?: number): Point; + + /** + * This method rounds the x and y coordinates of the point. + * @returns {H.math.Point} - the point itself after rounding + */ + round(): Point; + + /** + * Rounds the x and y coordinates to the next smaller integer values. + * @returns {H.math.Point} - the point itself after flooring + */ + floor(): Point; + + /** + * Rounds the x and y coordinates to the next greater integer values. + * @returns {H.math.Point} - the point itself after ceiling + */ + ceil(): Point; + + /** + * This method compares current point coordinates with the supplied point coordinates. + * @param other {H.math.IPoint} - The point to compare to. + * @returns {boolean} - True if the points are equal + */ + equals(other: IPoint): boolean; + + /** + * Calculates the closest point on a given line + * @param start {H.math.IPoint} - The start point of the line + * @param end {H.math.IPoint} - The end point of the line + * @returns {H.math.IPoint} - the closest point + */ + getNearest(start: IPoint, end: IPoint): IPoint; + + /** + * This method calculates the distance to a point supplied by the caller. + * @param other {H.math.IPoint} + * @returns {number} + */ + distance(other: IPoint): number; + + /** + * This method creates a Point instance from a given IPoint object. + * @param iPoint {H.math.IPoint} - The IPoint object to use + * @returns {H.math.Point} - the created Point instance + */ + static fromIPoint(iPoint: IPoint): Point; + + x: number; + y: number; + } + + /** + * Class defines a rectangle in 2-dimensional geometric space. It is used to represent the area in projected space. + */ + export class Rect { + /** + * Constructor + * @param left {number} - The rectangle's left edge x value + * @param top {number} - The rectangle's top edge y value + * @param right {number} - The rectangle's right edge x value + * @param bottom {number} - The rectangle's bottom edge y value + */ + constructor(left: number, top: number, right: number, bottom: number); + + /** + * To set all values of the rectangle's edges + * @param left {number} - The rectangle's left edge x value + * @param top {number} - The rectangle's top edge y value + * @param right {number} - The rectangle's right edge x value + * @param bottom {number} - The rectangle's bottom edge y value + */ + set(left: number, top: number, right: number, bottom: number): void; + + /** + * To get the rectangle's top-left vertex + * @returns {H.math.Point} + */ + getTopLeft(): H.math.Point; + + /** + * To get the rectangle's bottom-right vertex + * @returns {H.math.Point} + */ + getBottomRight(): H.math.Point; + + /** + * Method checks if provided coordinates lie within rectangle. + * @param x {number} - x-coordinate to check + * @param y {number} - y-coordinate to check + * @returns {boolean} - returns true if coordinates lie within rectangle, if parameters are isNaN returns false + */ + containsXY(x: number, y: number): boolean; + + /** + * To create a rectangle from a top-left and bottom-right point pair. + * @param topLeft {H.math.IPoint} - the top-left vertex of the rectanle + * @param bottomRight {H.math.IPoint} - the bottom-right vertex of the rectanle + * @returns {H.math.Rect} - returns the rectangular area defined by the top-left and bottom-right vertices + */ + static fromPoints(topLeft: H.math.IPoint, bottomRight: H.math.IPoint): H.math.Rect; + + /** + * To clone a rectangle + * @returns {H.math.Rect} + */ + clone(): H.math.Rect; + } + + /** + * Class for representing sizes consisting of a width and height. + * @property w {number} - The size's width value + * @property h {number} - The size's height value + */ + export class Size { + /** + * Constructor + * @param width {number} - Width. + * @param height {number} - Height. + */ + constructor(width: number, height: number); + w: number; + h: number; + } + } + + /***** net *****/ + export module net { + export module Request { + export enum State { + DONE = 2, + OPENED = 1, + UNSENT = 0, + } + + // TODO no idea how this interface is set up, investigate + export interface Priority { } + } + } + + /***** places *****/ + + /***** service *****/ + export module service { + /** + * Abstract rest service class + */ + export class AbstractRestService implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.AbstractRestService.Options=} + */ + constructor(opt_options?: H.service.AbstractRestService.Options); + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module AbstractRestService { + export interface Options { + + } + } + + /** + * This class encapsulates Enterprise Routing REST API as a service stub. An instance of this class can be retrieved by calling the factory method on a platform instance. H.service.Platform#getEnterpriseRoutingService. + */ + export class EnterpriseRoutingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.EnterpriseRoutingService.Options=} + */ + constructor(opt_options?: H.service.EnterpriseRoutingService.Options); + + /** + * This method sends a "calculateroute" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param calculateRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateRoute(calculateRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "getroute" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param getRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + getRoute(getRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "getlinkinfo" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param getLinkInfoParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + getLinkInfo(getLinkInfoParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "calculateisoline" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param calculateIsolineParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateIsoline(calculateIsolineParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + } + + export module EnterpriseRoutingService { + /** + * @property subDomain {string=} - The sub-domain of the routing service relative to the platform's base URL (default is 'route') + * @property path {string=} - The path of the map tile service, default is "routing/7.2" + * @property baseUrl {H.service.Url=} - The base URL of the service, defaults to the the platform's base URL if instance was created using H.service.Platform#getEnterpriseRoutingService method. + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This class encapsulates the Geocoding REST API in a service stub with calls to its various resources implemented. + */ + export class GeocodingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.GeocodingService.Options=} + */ + constructor(opt_options?: H.service.GeocodingService.Options); + + /** + * This method sends a reverse geocoding request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param geoodingParams {H.service.ServiceParameters} - the service parameters to be sent with the geocoding request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + geocode(geoodingParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + + /** + * This method sends a reverse geocoding request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param reverseGeocodingParams {H.service.ServiceParameters} - the service parameters to be sent with the reverse geocoding request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + reverseGeocode(reverseGeocodingParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + + /** + * This method sends a landmark search request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param searchParams {H.service.ServiceParameters} - the service parameters to be sent with the reverse geocoding request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + search(searchParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + } + + export module GeocodingService { + /** + * @property subDomain {string=} - the sub-domain of the geo-coding service relative to the platform's base URL, default is 'geocoder' + * @property path {string=} - the path of the Geocoding service, default is '6.2' + */ + export interface Options { + subDomain?: string; + path?: string; + } + } + + /** + * An interface represents an object, that can be configured credentials, settings etc. by H.service.Platform + */ + export interface IConfigurable { + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + /** + * @property id {number} - the ID associated internally with this request + * @property cancel {function()} - this function cancels the request and invokes the errback function + */ + export interface JsonpRequestHandle { + id: number; + cancel: () => void; + } + + /** + * This class encapsulates a map tile end point of the HERE Map Tile API. + */ + export class MapTileService extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.MapTileService.Options=} + */ + constructor(opt_options?: H.service.MapTileService.Options); + + /** + * This method returns the map tile type provided by this service. + * @returns {string} - the map tile type + */ + getType(): string; + + /** + * This method returns the map tile service's newest version hash. + * @returns {string} - meta information for this map tile service + */ + getVersion(): string; + + /** + * This method returns the map tile service's meta information. The method will return an object once the map tile service's data has been fetched. + * @returns {(H.service.MapTileService.Info | undefined)} - meta information for this map tile service + */ + getInfo(): H.service.MapTileService.Info | void; + + /** + * This method creates a tile provider which uses the specified map tiles. This provider can be used as a data source for an ImageTileLayer. + * @param tileType {string} - the tile type + * @param scheme {string} - the tile scheme + * @param tileSize {number} - the tile size + * @param format {string} - the tile image format + * @param opt_additionalParameters {H.service.ServiceParameters=} - a hash of additional parameters to be + * @param opt_options {H.service.TileProviderOptions=} - additional set of options for the provider + * @returns {H.map.provider.ImageTileProvider} - the image tile provider + */ + createTileProvider(tileType: string, scheme: string, tileSize: number, format: string, opt_additionalParameters?: H.service.ServiceParameters, opt_options?: H.service.TileProviderOptions): H.map.provider.ImageTileProvider; + + /** + * This method creates a tile layer. This layer can be used as a layer on a map's data model. + * @param tileType {string} - the tile type + * @param scheme {string} - the tile scheme + * @param tileSize {number} - the tile size + * @param format {string} - the tile image format + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the map tile service + * @param opt_opacity {number=} - The opacity of this layer + * @param opt_dark {boolean=} - Indicates whether the content of this layer is mainly dark, default is false See also H.Map.Options#autoColor + * @param opt_options {H.service.TileProviderOptions=} - additional set of options for the provider + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(tileType: string, scheme: string, tileSize: number, format: string, opt_additionalParameters?: H.service.ServiceParameters, opt_opacity?: number, opt_dark?: boolean, opt_options?: H.service.TileProviderOptions): H.map.layer.TileLayer; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module MapTileService { + /** + * @property maps {Object} - + * @property schemes {Object} - + * @property tiletypes {Object} - + * @property formats {Object} - + * @property resolutions {Object} - + * @property languages {Object} - + */ + export interface Info { + maps: { [key: string]: any }; + schemes: { [key: string]: any }; + tiletypes: { [key: string]: any }; + formats: { [key: string]: any }; + resolutions: { [key: string]: any }; + languages: { [key: string]: any }; + } + + /** + * @property type {string=} - the type of the map tile service to communicate with, e.g. 'base' (default), 'aerial', etc. (refer to the Map Tile REST API documentation for available types) + * @property version {string=} - the map version hash to use for retrieving tiles, default is newest and will be automatically updated + * @property subDomain {string=} - the sub-domain of the map tile service relative to the platform's base URL, default is 'maps' + * @property path {string=} - the path of the map tile service, default is 'maptile/2.1' + */ + export interface Options { + type?: string; + version?: string; + subDomain?: string; + path?: string; + } + } + + /** + * A map type is an object holding tile layers corresponding to a map type (e.g. 'normal', 'satellite' or 'terrain'). A map type contains at least a map property which defines the basic map layer for a given map type. In addition it can hold other map layers with the given style, e.g. base, xbase, traffic etc. + * @property map {H.map.layer.TileLayer} - the basic map tiles with all features and labels + * @property mapnight {H.map.layer.TileLayer} - the basic map tiles with all features and labels (night mode) + * @property xbase {H.map.layer.TileLayer=} - map tiles without features and labels + * @property xbasenight {H.map.layer.TileLayer=} - map tiles without features and labels (night mode) + * @property base {H.map.layer.TileLayer=} - map tiles without labels + * @property basenight {H.map.layer.TileLayer=} - map tiles without labels (night mode) + * @property traffic {H.map.layer.TileLayer=} - map tiles with traffic flow highlighting + * @property trafficnight {H.map.layer.TileLayer=} - map tiles with traffic flow highlighting (night mode) + * @property transit {H.map.layer.TileLayer=} - map tiles with public transit lines highlighted + * @property panorama {H.map.layer.TileLayer=} - map tiles highlighting areas with HERE StreetLevel coverage + * @property panoramanight {H.map.layer.TileLayer=} - map tiles highlighting areas with HERE StreetLevel coverage (night mode) + * @property labels {H.map.layer.TileLayer=} - transparent map tiles with labels only + */ + export interface MapType { + map: H.map.layer.TileLayer; + mapnight: H.map.layer.TileLayer; + xbase?: H.map.layer.TileLayer; + xbasenight?: H.map.layer.TileLayer; + base?: H.map.layer.TileLayer; + basenight?: H.map.layer.TileLayer; + traffic?: H.map.layer.TileLayer; + trafficnight?: H.map.layer.TileLayer; + transit?: H.map.layer.TileLayer; + panorama?: H.map.layer.TileLayer; + panoramanight?: H.map.layer.TileLayer; + labels?: H.map.layer.TileLayer; + } + + /** + * Places service implements a low level places RestApi access. Please refer to Restful API documentation for providing parameters and handling response objects. + */ + export class PlacesService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.PlacesService.Options=} + */ + constructor(opt_options?: H.service.PlacesService.Options); + + /** + * This is generic method to query places RestAPI. + * @param entryPoint {string} - can be one of available entry points H.service.PlacesService.EntryPoint i.e value of H.service.PlacesService.EntryPoint.SEARCH + * @param entryPointParams {Object} - parameter map key value pairs will be transformed into the url key=value parametes. For entry point parameters description please refer to places restful api documentation documentation for available parameters for chose entry point + * @param onResult {Function} - callback which is called when result is returned + * @param onError {Function} - callback which is called when error occured (i.e request timeout) + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + request(entryPoint: string, entryPointParams: Object, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'search' entry point. Please refer to documentation for parameter specification and response handling. + * @param searchParams {H.service.ServiceParameters} - places api search entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + search(searchParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'suggestions' entry point. Please refer to documentation for parameter specification and response handling. + * @param suggestParams {H.service.ServiceParameters} - places api suggest entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + suggest(suggestParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'explore' entry point. Please refer to documentation for parameter specification and response handling. + * @param exploreParams {H.service.ServiceParameters} - places api explore entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + explore(exploreParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'around' entry point. Please refer to documentation for parameter specification and response handling. + * @param aroundParams {H.service.ServiceParameters} - places api around entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + around(aroundParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'here' entry point. Please refer to documentation for parameter specification and response handling. + * @param hereParams {H.service.ServiceParameters} - places api here entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + here(hereParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'categories' entry point. Please refer to documentation for parameter specification and response handling. + * @param categoriesParams {H.service.ServiceParameters} - places api here entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + categories(categoriesParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * This method should be used to follow hyperlinks available in results returned by dicovery queries. + * @param hyperlink {string} + * @param onResult {Function} + * @param onError {Function} + * @param opt_additionalParameters {Object=} - additional parameters to send with request + * @returns {H.service.JsonpRequestHandle} - jsonp resquest handle + */ + follow(hyperlink: string, onResult: Function, onError: Function, opt_additionalParameters?: Object): H.service.JsonpRequestHandle; + } + + export module PlacesService { + /** + * List of available entry points + */ + export enum EntryPoint { + SEARCH, + SUGGEST, + EXPLORE, + AROUND, + HERE, + CATEGORIES, + } + + /** + * @property subDomain {string=} - the sub-domain of the places service relative to the platform's base URL, default is 'places' + * @property path {string=} - the path of the places service, default is 'places/v1' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * The Platform class represents central class from which all other service stubs are created. It also contains the shared settings to be passed to the individual service stubs, for example the root URL of the platform, application credentials, etc. + */ + export class Platform { + /** + * Constructor + * @param options {H.service.Platform.Options} + */ + constructor(options: H.service.Platform.Options); + + /** + * Method attempts to configure object that implements H.service.IConfigurable + * @param configurable {H.service.IConfigurable} + * @returns {H.service.IConfigurable} + */ + configure(configurable: H.service.IConfigurable): H.service.IConfigurable; + + /** + * This method enables or disables HTTPS communication with the platform + * @param useHTTPS {boolean} - a boolean value indicating whether to communicate with the platform via HTTPS + */ + setUseHTTPS(useHTTPS: boolean): void; + + /** + * This method configures whether to use the "customer integration testing" instance of the platform. + * @param useCIT {boolean} - a boolean value indicating whether the CIT platform instance is to be used + */ + setUseCIT(useCIT: boolean): void; + + /** + * This method modifies the base URL to be used when creating service stubs. + * @param baseUrl {H.service.Url} - the new base URL to use + */ + setBaseUrl(baseUrl: H.service.Url): void; + + /** + * This method returns the currently used base URL. + * @returns {H.service.Url} + */ + getBaseUrl(): H.service.Url; + + /** + * This method returns an instance of H.service.TrafficIncidentsService to query the Traffic API Traffic Incident Data + * @returns {H.service.TrafficIncidentsService} - a new places service instance + */ + getTrafficIncidentsService(): H.service.TrafficIncidentsService; + + /** + * This method returns an instance of H.service.MapTileService to query the Map Tile API. + * @param opt_options {H.service.MapTileService.Options=} + * @returns {H.service.MapTileService} + */ + getMapTileService(opt_options?: H.service.MapTileService.Options): H.service.MapTileService; + + /** + * This method returns an instance of H.service.venues.Service to query the Venue Maps API + * @param opt_params {H.service.venues.Service.Options=} - additional service parameters + * @returns {H.service.venues.Service} + */ + getVenueService(opt_params?: H.service.venues.Service.Options): H.service.venues.Service; + + /** + * This method returns an instance of H.service.metaInfo.Service to query the Map Tile API Metainfo Tiles + * @param opt_params {H.service.metaInfo.Service.Options=} - additional service parameters + * @returns {H.service.metaInfo.Service} + */ + getMetaInfoService(opt_params?: H.service.metaInfo.Service.Options): H.service.metaInfo.Service; + + /** + * This method creates a pre-configured set of HERE tile layers for convenient use with the map. + * @param opt_tileSize {(H.service.Platform.DefaultLayersOptions | number)=} - When a number – optional tile size to be queried from the HERE Map Tile API, default is 256. If the parameter is an object, then it represents options and all remaining below parameters should be omitted. + * @param opt_ppi {number=} - optional 'ppi' parameter to use when querying tiles, default is not specified + * @param opt_lang {string=} - optional primary language parameter, default is not specified + * @param opt_secondaryLang {string=} - optional secondary language parameter, default is not specified + * @param opt_style {string=} - optional 'style' parameter to use when querying map tiles, default is not specified + * @param opt_pois {(string | boolean)=} - indicates if pois are displayed on the map. Pass true to indicate that all pois should be visible. Alternatively you can specify mask for the POI Categories as described at the Map Tile API documentation POI Categories chapter. + * @returns {Object} - a set of tile layers ready to use + */ + createDefaultLayers(opt_tileSize?: (H.service.Platform.DefaultLayersOptions | number), opt_ppi?: number, opt_lang?: string, opt_secondaryLang?: string, opt_style?: string, opt_pois?: (string | boolean)): H.service.Platform.MapTypes; + + /** + * This method returns an instance of H.service.RoutingService to query the Routing API. + * @param opt_options {H.service.RoutingService.Options=} + * @returns {H.service.RoutingService} + */ + getRoutingService(opt_options?: H.service.RoutingService.Options): H.service.RoutingService; + + /** + * This method returns an instance of H.service.GeocodingService to query the Geocoder API + * @param opt_options {H.service.GeocodingService.Options=} - an optional set of options for the new geocoding service to connect to + * @returns {H.service.GeocodingService} - a new geocoding service instance + */ + getGeocodingService(opt_options?: H.service.GeocodingService.Options): H.service.GeocodingService; + + /** + * This method returns an instance of H.service.PlacesService to query the Places API. + * @returns {H.service.PlacesService} - a new places service instance + */ + getPlacesService(): H.service.PlacesService; + + /** + * This method returns an instance of H.service.EnterpriseRoutingService to query the Enterprise Routing API. + * @param opt_options {H.service.EnterpriseRoutingService.Options=} + * @returns {H.service.EnterpriseRoutingService} + */ + getEnterpriseRoutingService(opt_options?: H.service.EnterpriseRoutingService.Options): H.service.EnterpriseRoutingService; + } + + export module Platform { + /** + * Options used to create default layers + * @property tileSize {number=} - tile size to be queried from the HERE Map Tile API, default is 256 + * @property ppi {number=} - 'ppi' parameter to use when querying tiles, default is not specified + * @property lg {string=} - optional primary language parameter, default is not specified + * @property lg2 {string=} - optional secondary language parameter, default is not specified + * @property style {string=} - optional 'style' parameter to use when querying map tiles, default is not specified + * @property pois {boolean=} - indicates if pois are displayed on the map + * @property crossOrigin {(string | boolean=)} - indicates if CORS headers should be used for default layers, if false is specified, CORS headers are not set, defaults to 'anonymous'. Be aware that storing of content is not possible if crossOrigin is not set to true (see H.Map#storeContent). + */ + export interface DefaultLayersOptions { + tileSize?: number; + ppi?: number; + lg?: string; + lg2?: string; + style?: string; + pois?: boolean; + crossOrigin?: (string | boolean); + } + + /** + * @property app_id {string} - The application ID to identify the client against the platform (mandatory to provide) + * @property app_code {string} - The application code to identify the client against the platform (mandatory to provide) + * @property baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com + * @property useCIT {boolean=} - Indicates whether the Customer Integration Testing should be used, default is false + * @property useHTTPS {boolean=} - Indicates whether secure communication should be used, default is false + */ + export interface Options { + app_id: string; + app_code: string; + baseUrl?: H.service.Url; + useCIT?: boolean; + useHTTPS?: boolean; + } + + /** + * pre-configured set of HERE tile layers for convenient use with the map. + */ + export interface MapTypes { + normal?: H.service.MapType; + satellite?: H.service.MapType; + terrain?: H.service.MapType; + [key: string]: H.service.MapType; + } + } + + /** + * This class encapsulates the Routing REST API as a service stub. An instance of this class can be retrieved by calling the factory method on a platform instance. H.service.Platform#getRoutingService. + */ + export class RoutingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.RoutingService.Options=} + */ + constructor(opt_options?: H.service.RoutingService.Options); + + /** + * This method sends a "calculateroute" request to Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param calculateRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateRoute(calculateRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + } + + export module RoutingService { + /** + * @property subDomain {string=} - the sub-domain of the routing service relative to the platform's base URL, default is 'route' + * @property path {string=} - the path of the map tile service, default is 'routing/7.2' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This type encapsulates URL parameters to be sent to a HERE platform service. + */ + export interface ServiceParameters { + [key: string]: string; + } + + /** + * This type encapsulates a response object provider by a HERE platform service. + */ + export interface ServiceResult { + [key: string]: string; + } + + /** + * Options which are used to initialize the tile provider. + * @property crossOrigin {boolean=} - The string to be set for the crossOrigin attribute for loaded images + */ + export interface TileProviderOptions { + crossOrigin?: boolean; + } + + /** + * TrafficIncindentsService provides functionality to the low level traffic incidents api Traffic API documentation where it is possible to retrieve traffic incident information on a tile basis + */ + export class TrafficIncidentsService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.TrafficIncidentsService.Options=} + */ + constructor(opt_options?: H.service.TrafficIncidentsService.Options); + + /** + * This method requests traffic incidents based on the service parameters provided. + * @param serviceParams {H.service.ServiceParameters} + * @param onResponse {function(H.service.ServiceResult)} + * @param onError {function()} + * @returns {H.service.JsonpRequestHandle} + */ + requestIncidents(serviceParams: H.service.ServiceParameters, onResponse: (result: H.service.ServiceResult) => void, onError: () => void): H.service.JsonpRequestHandle; + + /** + * This method requests traffic incident information by tile coordinates + * @param x {number} - tile column number + * @param y {number} - tile row number + * @param z {number} - zoom level + * @param onResponse {function(H.service.ServiceResult)} - callback to handle service resposne + * @param onError {function()} - callback to habdle communication error + * @param opt_serviceParams {H.service.ServiceParameters=} - optional service parameters to be added to the request + * @returns {H.service.JsonpRequestHandle} + */ + requestIncidentsByTile(x: number, y: number, z: number, onResponse: (result: H.service.ServiceResult) => void, onError: () => void, opt_serviceParams?: H.service.ServiceParameters): H.service.JsonpRequestHandle; + } + + export module TrafficIncidentsService { + /** + * @property subDomain {string=} - the sub-domain of the traffic incidents service relative to the platform's base URL, default is 'traffic' + * @property path {string=} - the path of the traffic incidents service, default is 'traffic/6.1' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This class represents a URL giving access to the individual parts that make up a URL,such as the scheme, host/domain, path, etc. Use the static parse method to populate a new URL object from a URL string. Be aware that URLs with user and password like "ftp://user:password@foo.bar/" are not supported! + */ + export class Url { + /** + * Constructor + * @param scheme {string} - the URL scheme (e.g. "http" or "https" or "mailto") + * @param host {string} - the host (or domain) part of the URL + * @param opt_path {string=} - the path following the host pointing to a resource + * @param opt_params {Object=} - the query string parameters of this URL + * @param opt_port {number=} - The port of the host on which the host listens. If a string is passed it must be convertible to an integer. + * @param opt_anchor {string=} - an optional anchor part of the URL (usually preceded by '#'); + */ + constructor(scheme: string, host: string, opt_path?: string, opt_params?: Object, opt_port?: number, opt_anchor?: string); + + /** + * This function parses a URL string and returns a H.service.Url object. The URL string must contain at least a scheme and a host. + * @param url {string} - The URL string to parse. + * @param opt_baseURL {string=} - The base URL to use to resolve relative URLs. If ommited the base URL of the document which loaded the API is taken. + * @returns {H.service.Url} - the parsed URL object + */ + static parse(url: string, opt_baseURL?: string): H.service.Url; + + /** + * Clones this URL object. Optionally, mutations can be passed to this function to modify properties of the cloned object. Note that URL parameters are not replaced but merged with the parameters of this instance. + * @returns {H.service.Url} - the clone of the URL object + */ + clone(): H.service.Url; + + /** + * This function sets the scheme of this URL object. + * @param scheme {string} - the new scheme + * @returns {H.service.Url} - this URL object + */ + setScheme(scheme: string): H.service.Url; + + /** + * This function returns the scheme of this Url object. + * @returns {string} - the scheme (for example 'http') + */ + getScheme(): string; + + /** + * This function sets the host of this URL object. + * @param host {string} - the new host + * @returns {H.service.Url} - this URL object + */ + setHost(host: string): H.service.Url; + + /** + * This function returns the host name of this Url object. + * @returns {string} - the host (for example 'api.here.com') + */ + getHost(): string; + + /** + * This function sets the path of this URL object. + * @param path {(string | undefined)} - the new path or a boolean to clear the path + * @returns {H.service.Url} - this URL object + */ + setPath(path: string | boolean): H.service.Url; + + /** + * This function returns the path part of this Url object. + * @returns {(string | undefined)} - the path (for example 'myresources/resource.html') + */ + getPath(): string | void; + + /** + * This function sets the specified parameters for this URL object. Keys in this object, which are associated with undefined values will be treated as query string parameters with no value. + * @param params {(Object | undefined)} - a hash of query string parameters specifying the parameters to be set.or a boolean to clear the parameters. + * @returns {H.service.Url} - this URL object + */ + setQuery(params?: Object | boolean): H.service.Url; + + /** + * This function returns a boolean value indicating whether there are any query string parameter associated with this URL. + * @returns {boolean} - true if there are parameters, false if none are present + */ + hasQuery(): boolean; + + /** + * This function returns the query object of this Url object. + * @returns {Object} - the query object + */ + getQuery(): Object; + + /** + * This function sets the anchor of this URL object. + * @param anchor {(string | boolean | undefined)} - the new anchor or undefined to clear the anchor + * @returns {H.service.Url} - this URL object + */ + setAnchor(anchor?: string | boolean): H.service.Url; + + /** + * This function returns the anchor of this Url object. + * @returns {(string | undefined)} - the anchor + */ + getAnchor(): string | void; + + /** + * This function merges the provided parameters into this URL's existing parameters. Key-value pairs which are defined in the argument and this URL's parameters will be overwritten. Key-value pairs which are defined in the argument and are not defined in this URL's parameters will be added. Prototype properties and function properties will not be merged. + * @param other {Object} - the parmeters to be merged into this URL's query string parameters + * @returns {H.service.Url} - this URL object + */ + mergeQuery(other: Object): H.service.Url; + + /** + * This function adds a sub-domain to the host of this URL object. + * @param subDomain {string} - the sub domain (non-empty string) to be added + * @returns {H.service.Url} - this URL object + */ + addSubDomain(subDomain: string): H.service.Url; + + /** + * This function adds a sub-path to this URL's path + * @param subPath {string} - the path to be added + * @returns {H.service.Url} - this URL object + */ + addSubPath(subPath: string): H.service.Url; + + /** + * This function formats this URL object to a full URL string. + * @returns {string} - the URL's string representation + */ + toString(): string; + } + + export module metaInfo { + /** + * This class encapsulates a Metainfo Tile end point of the HERE Map Tile API. + */ + export class Service extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.metaInfo.Service.Options=} - additional service parameters + */ + constructor(opt_options?: H.service.metaInfo.Service.Options); + + /** + * This method returns the meta info tile service's newest version hash. + * @returns {string} - meta information for this map tile service + */ + getVersion(): string; + + /** + * This method returns the meta info tile service's meta information. The method will return an object once the map tile service's data has been fetched. + * @returns {(H.service.metaInfo.Service.Info | undefined)} - meta information for this meta info tile service + */ + getInfo(): H.service.metaInfo.Service.Info | void; + + /** + * This method creates a tile provider which uses the meta info tile backend. This provider can be used as a data source for an TileLayer. + * @param tileSize {number} - The tile size + * @param pixelRatio {number} - The tile's pixel ratio, should be aligned with base map tile + * @param opt_categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the meta info service + * @param opt_tileType {string=} - the tile type (default is 'maptile') + * @param opt_scheme {string=} - the scheme for which the meta info tiles a requested (default is 'normal.day') + * @returns {H.map.provider.TileProvider} - the tile provider + */ + createTileProvider(tileSize: number, pixelRatio: number, opt_categoryFilter?: Array, opt_additionalParameters?: H.service.ServiceParameters, opt_tileType?: string, opt_scheme?: string): H.map.provider.TileProvider; + + /** + * This method creates a tile layer. This layer can be used as a layer on a map's data model. + * @param tileSize {number} - The tile size + * @param pixelRatio {number} - The tile's pixel ratio, should be aligned with base map tile + * @param opt_categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the meta info service + * @param opt_tileType {string=} - the tile type (default is 'maptile') + * @param opt_scheme {string=} - the scheme for which the meta info tiles a requested (default is 'normal.day') + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(tileSize: number, pixelRatio: number, opt_categoryFilter?: Array, opt_additionalParameters?: H.service.ServiceParameters, opt_tileType?: string, opt_scheme?: string): H.map.layer.TileLayer; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module Service { + /** + * @property maps {Object} - + * @property schemes {Object} - + * @property tiletypes {Object} - + * @property formats {Object} - + * @property resolutions {Object} - + * @property languages {Object} - + */ + export interface Info { + maps: { [key: string]: any }; + schemes: { [key: string]: any }; + tiletypes: { [key: string]: any }; + formats: { [key: string]: any }; + resolutions: { [key: string]: any }; + languages: { [key: string]: any }; + } + + /** + * @property type {string=} - the type of the map tile service to communicate with, e.g. 'base' (default), 'aerial', etc. (refer to the Map Tile REST API documentation for available types) + * @property version {string=} - the map version hash to use for retrieving tiles, default is newest and will be automatically updated + * @property subDomain {string=} - the sub-domain of the map tile service relative to the platform's base URL, default is 'maps' + */ + export interface Options { + type?: string; + version?: string; + subDomain?: string; + } + } + + /** + * This class utilizes Metainfo Tiles functionality provided by the Map Tile API to load meta information about map objects (buildings, labels, public transport etc.). + */ + export class TileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {(H.service.metaInfo.Service | H.service.MapTileService)} - the tile service which holds information from about the source of the tiles + * @param opt_params {H.service.ServiceParameters=} - an additional set of URL parameters + * @param opt_options {H.service.metaInfo.TileProvider.Options=} - additional parameters + */ + constructor(service: (H.service.metaInfo.Service | H.service.MapTileService), opt_params?: H.service.ServiceParameters, opt_options?: H.service.metaInfo.TileProvider.Options); + } + + export module TileProvider { + /** + * Configuration object which can be used to initialize the TileProvider. + * @property tileType {string=} - The tile type for which to request meta info + * @property scheme {string=} - The map scheme for which to request meta info + * @property tileCacheSize {number=} - The number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property tileSize {number=} - The size of the tiles rendered by this provider (must be power of 2, default is 256) + * @property pixelRatio {number=} - The pixel ratio to use for over-sampling in cases of high-resolution displays + * @property categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + */ + export interface Options { + tileType?: string; + scheme?: string; + tileCacheSize?: number; + tileSize?: number; + pixelRatio?: number; + categoryFilter?: Array; + } + } + } + + export module venues { + /** + * The class represents the building in the venue hiearachy (see H.service.venues.Venue) and holds floors that belong to the building. + */ + export class Building extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue building + * @param uid {string} - The unique identifier of this building + * @param minLevel {number} - The minimum floor level of this building + * @param maxLevel {number} - The maximum floor level of this building + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string, minLevel: number, maxLevel: number); + + /** + * Method returns the parent object - venue (see H.service.venues.Venue) to which the building belongs to. + * @returns {H.service.venues.Venue} + */ + getVenue(): H.service.venues.Venue; + + /** + * Method returns the minimum floor level of this building. + * @returns {number} + */ + getMinLevel(): number; + + /** + * Method returns the maximum floor level of this building + * @returns {number} + */ + getMaxLevel(): number; + + /** + * Method returns the floor (see H.service.venues.Floor) if one was already loaded. This method doesn't make attempt to fetch the floor data. + * @param level {number} - floor level within minimum and maximum level boundaries for the building + * @returns {(H.service.venues.Floor | undefined)} - The floor object or undefined if floor was not loaded + */ + getFloor(level: number): H.service.venues.Floor | void; + } + + /** + * The class represents the floor object in the venue hierarchy (see H.service.venues.Venue). The class holds information about floor geometry and spaces (see H.service.venues.Space) that belong to this floor. + */ + export class Floor extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue floor + * @param data {*} - The meta data of this floor + * @param level {number} - The level of this floor + */ + constructor(provider: H.map.provider.ObjectProvider, data: any, level: number); + + /** + * Method returns the level of the floor in the building. + * @returns {number} + */ + getLevel(): number; + + /** + * Method returns map geometry that represents floor boundaries. + * @returns {(H.service.venues.Space | undefined)} + */ + getFloorSpace(): H.service.venues.Space | void; + + /** + * Method returns the H.map.Group of all spaces that belong to the floor. + * @returns {H.map.Group} + */ + getSpaces(): H.map.Group; + + /** + * Method returns parent object - building (see H.service.venues.Building) of the floor. + * @returns {H.service.venues.Building} + */ + getBuilding(): H.service.venues.Building; + + /** + * Method returns raw data associated with the floor. For more details on data format see http://developer.here.com/rest-apis/documentation/venue-maps/topics/resource-type-venue-interaction-tile-floor.html + * @returns {*} - the raw floor data object + */ + getData(): any; + + /** + * Method returns the space object with the given ID, that belongs to the floor. + * @param id {string} - The ID of the space. + * @returns {(H.service.venues.Space | undefined)} - The requested space or undefined if space not found. + */ + getSpace(id: string): H.service.venues.Space | void; + } + + /** + * This class encapsulates methods to call Venue Maps API endpoints. + */ + export class Service extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.venues.Service.Options=} - additional service parameters + */ + constructor(opt_options?: H.service.venues.Service.Options); + + /** + * This method sends a discovery request to the Venue Maps API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object, or the onError callback if a communication error occured. + * @param serviceParams {H.service.ServiceParameters} - the service parameters to be sent with the discovery request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Venue Maps API provides a response to the request + * @param onError {function(string)} - this function will be called if a communication error occurs during request and error type is passed as an argument + */ + discover(serviceParams: H.service.ServiceParameters, onResult: (res: H.service.ServiceResult) => void, onError: (s: string) => void): void; + + /** + * This method creates a tile layer which can be added to the map in order to see the venues. It uses Interaction Tile endpoint of the Venue Maps API, more at http://developer.here.com/rest-apis/documentation/venue-maps/topics/quick-start-get-interaction-tile.html. + * @param opt_options {H.service.venues.TileProvider.Options=} - Tile provider options + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(opt_options?: H.service.venues.TileProvider.Options): H.map.layer.TileLayer; + + /** + * Method returns current state of the service. + * @returns {H.service.venues.Service.State} - State of the service + */ + getState(): H.service.venues.Service.State; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module Service { + /** + * @property subDomain {string=} - the sub-domain of the Venue Maps service relative to the platform's base URL, default is 'venue.maps' + * @property path {string=} - the path to append after host name when making requests to the Venue Maps API, default is empty + */ + export interface Options { + subDomain?: string; + path?: string; + } + + /** + * The state types of the H.service.venues.Service. Possible states are: + */ + export enum State { + ERROR, + INIT, + READY, + } + } + + /** + * Represents a spatial object for this space. Each space object contains data associated with that space and can be retrieved by using H.service.venues.Space#getData method. + */ + export class Space { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The provider of this object. + * @param uid {string} - The unique identifier of this space + * @param data {*} - The meta data of this space + * @param opt_isFloorSpace {boolean=} - Indicates whether this space represents a floor itself, defaults to false + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string, data?: any, opt_isFloorSpace?: boolean); + + /** + * The method indicates whether the spatial object represents the whole floor space or a space within a floor boundaries, that belongs to the floor. + * @returns {boolean} - True if this spatial object represents the floor space. + */ + isFloorSpace(): boolean; + + /** + * This method sets custom style to use for rendering the labels. Should be called before the first render of the space, otherwise has no any effect. Note that due to the design consistency currently it is not allowed to change the font family and the size of the labels. + * @param labelStyle {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - Custom label style + */ + initLabelStyle(labelStyle: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): void; + + /** + * Method returns parent object - floor (see H.service.venues.Floor) of the space. + * @returns {H.service.venues.Floor} + */ + getFloor(): H.service.venues.Floor; + + /** + * Method returns raw data associated with the space. For more details on data format see http://developer.here.com/rest-apis/documentation/venue-maps/topics/resource-type-venue-interaction-tile-space.html + * @returns {Object} - raw space data object + */ + getData(): Object; + } + + /** + * This class represents a Venue Maps tile provider which requests venues tiles from a platform venue tile service. + */ + export class TileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {H.service.venues.Service} + * @param opt_options {H.service.venues.TileProvider.Options=} + */ + constructor(service: H.service.venues.Service, opt_options?: H.service.venues.TileProvider.Options); + + /** + * Method specifies which floor level of the venues must be fetched by provider. Floor level is global to all venues and defaults to 0. + * @param level {number} + */ + setCurrentLevel(level: number): void; + + /** + * Method returns the floor level that provider uses for tile fetching. + * @returns {number} - current provider's floor level + */ + getCurrentLevel(): number; + } + + export module TileProvider { + /** + * Configuration object which can be used to initialize the TileProvider. + * @property tileCacheSize {number=} - The number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property pixelRatio {number=} - The pixel ratio to use for over-sampling in cases of high-resolution displays + * @property onSpaceCreated {function(H.service.venues.Space)=} - A callback function that is called on every created space (see H.service.venues.Space) object. The function can be used for space object styling. + */ + export interface Options { + tileCacheSize?: number; + pixelRatio?: number; + onSpaceCreated?: (space: H.service.venues.Space) => void; + } + } + + /** + * The class represents the venue, it is a root for the venue object heirarchy. The venue inherits from H.map.Group and holds building objects (see H.service.venues.Building). Building objects hold floor objects (see H.service.venues.Floor) and inherit from H.map.Group as well. Leaf objects are spaces (see H.service.venues.Space) that are spatial map objects and reside inside floor containers. + */ + export class Venue extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue + * @param uid {string} - The unique identifier of this venue + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string); + + /** + * Method returns the building object, that belongs to the venue, with the given ID . The method doesn't attempt to fetch building data. + * @param id {string} - the ID of the building + * @returns {(H.service.venues.Building | undefined)} - The requested building or undefined if building wasn't loaded + */ + getBuilding(id: string): H.service.venues.Building | void; + + /** + * Method returns map of all loaded buildings associated with the venue. + * @returns {Object<*, H.service.venues.Building>} + */ + getBuildings(): any; + } + } + } + + /***** ui *****/ + export module ui { + /** + * This class represents the base class for UI controls on the map. + */ + export class Control extends H.ui.base.Container { + /** + * This abstract method can be overridden by deriving classes to be invoked when the UI object's unit system changes. + * @param unitSystem {H.ui.UnitSystem} - the unit system the UI currently uses + */ + onUnitSystemChange(unitSystem: H.ui.UnitSystem): void; + + /** + * This abstract method can be overridden by deriving classes to be invoked when the underlying map engine changes. + * @param engineType {H.Map.EngineType} - the engine type the map currently uses + */ + onMapEngineTypeChange(engineType: H.Map.EngineType): void; + + /** + * This method returns the map to which this control is attached. + * @returns {?H.Map} - return the map + */ + getMap(): H.Map; + + /** + * This method returns the localization object which corresponds to the UI's current locale. + * @returns {H.ui.i18n.Localization} + */ + getLocalization(): H.ui.i18n.Localization; + + /** + * This method returns this control's layout alignment. + * @returns {H.ui.LayoutAlignment} - the control's current layout alignment + */ + getAlignment(): H.ui.LayoutAlignment; + + /** + * This method sets the control's layout alignments. + * @param alignment {H.ui.LayoutAlignment} - The new alignment of the control + * @returns {H.ui.Control} - returns this control instance + */ + setAlignment(alignment: H.ui.LayoutAlignment): H.ui.Control; + } + + /** + * This class represents a distance measurement control which helps calculating distances between geographical locations indicated by the user clicks. + */ + export class DistanceMeasurement extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.DistanceMeasurement.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.DistanceMeasurement.Options); + } + + export module DistanceMeasurement { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.RIGHT_BOTTOM + * @property startIcon {H.map.Icon=} - the icon to use for the first measurement point + * @property stopoverIcon {H.map.Icon=} - the icon to use for the intermediate measurement points + * @property endIcon {H.map.Icon=} - the icon to use for the last measurement point + * @property splitIcon {H.map.Icon=} - the icon to use for indicating position under pointer over the line where new point will be created once user clicks + * @property lineStyle {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - the style to use for connecting lines of the measurement points + * @property distanceFormatter {function(number)=} - Optional function used for formatting a distance. By default distance measurement tool will do the formatting according to the specified measurement unit (see H.ui.UI.Options#unitSystem) + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + startIcon?: H.map.Icon; + stopoverIcon?: H.map.Icon; + endIcon?: H.map.Icon; + splitIcon?: H.map.Icon; + lineStyle: H.map.SpatialStyle | H.map.SpatialStyle.Options; + distanceFormatter?(n: number): void; + } + } + + /** + * This class represents an information bubble bound to a geo-position on the map. + */ + export class InfoBubble extends base.Element { + /** + * Constructor + * @param position {H.geo.IPoint} - the geo-position to which this info bubble corresponds + * @param opt_options {H.ui.InfoBubble.Options=} - optional parameters to be passed to the info bubble + */ + constructor(position: H.geo.IPoint, opt_options?: InfoBubble.Options); + + /** + * This method sets the geo-position of this info bubble + * @param position {(H.geo.IPoint | H.geo.Point)} - the new geo-position of this bubble + */ + setPosition(position: H.geo.IPoint | H.geo.Point): void; + + /** + * This method returns this info bubble's current state. + * @returns {H.ui.InfoBubble.State} - this bubble's current state + */ + getState(): InfoBubble.State; + + /** + * This method sets the info bubble's state. + * @param state {H.ui.InfoBubble.State} - the new state + */ + setState(state: InfoBubble.State): void; + + /** + * This method closes the info bubble (setting its state to CLOSED) + */ + close(): void; + + /** + * This method opens the info bubble (setting its state to OPEN) + */ + open(): void; + + /** + * This method returns the bubble's content element. + * + * Note: Before adding an info bubble to a UI object the content element is null. + * @returns {?HTMLElement} - the content element of this info bubble + */ + getContentElement(): HTMLElement; + + /** + * This methods sets the content of the info bubble. This can either be a string (applied as innerHTML) to the content element of this info bubble or a HTML node which is appended to the content element. + * @param content {(string | Node)} - the content for this bubble + */ + setContent(content: string | Node): void; + } + + export module InfoBubble { + /** + * This enumeration holds the state an info bubble can have. + */ + export enum State { + /** This value represents the state where an info bubble is open and visible (value: 'open'). */ + OPEN, + /** This value represents the state where an info bubble is closed and invisible (value: 'closed') */ + CLOSED, + } + + export interface Options { + /** + * a callback to be invoked when the info bubble's state changes + * @param event {H.util.Event} + */ + onStateChange?(event: H.util.Event): void; + + /** + * content to be added to the info bubble + */ + content: string | Node; + } + } + + /** + * This enumeration holds the possible layout alignments for the UI elements. + */ + export enum LayoutAlignment { + TOP_LEFT, + TOP_CENTER, + TOP_RIGHT, + LEFT_TOP, + LEFT_MIDDLE, + LEFT_BOTTOM, + RIGHT_TOP, + RIGHT_MIDDLE, + RIGHT_BOTTOM, + BOTTOM_LEFT, + BOTTOM_CENTER, + BOTTOM_RIGHT, + } + + /** + * This class represents a menu control allowing to control which map type the map shows, etc. + */ + export class MapSettingsControl extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.MapSettingsControl.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.MapSettingsControl.Options); + + /** + * Sets the traffic incidents layer to be shown when activating the respective button on the map settings control. + * @param incidentsLayer {H.map.layer.Layer} - the incidents layer + */ + setIncidentsLayer(incidentsLayer: H.map.layer.Layer): void; + } + + export module MapSettingsControl { + /** + * The map type entry is an object containing a display name and a map type object to which it refers. + * @property name {string} - label which describes the map type + * @property mapType {H.service.MapType} - reference to map type + */ + export interface MapTypeEntry { + name: string; + mapType: H.service.MapType; + } + + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + * @property entries {Array=} - the map type entries to be shown in this map settings control + * @property incidents {H.map.layer.Layer} - the traffic incidents layer to be activated by the map settings control + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + entries?: Array; + incidents: H.map.layer.Layer; + } + } + + /** + * This class represents the UI controls for panorama + */ + export class Pano extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.Pano.Options=} - optional parameters to be passed to the map. + */ + constructor(opt_options?: H.ui.Pano.Options); + } + + export module Pano { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.RIGHT_BOTTOM + * @property mapTypes {H.service.MapTypes} - The map types to use + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + mapTypes: H.service.MapType; + } + } + + /** + * This class represents a UI element showing the current zoom scale. + */ + export class ScaleBar { + /** + * Constructor + * @param opt_options {H.ui.ScaleBar.Options=} - optional parameters to be passed to this scale bar. + */ + constructor(opt_options?: H.ui.ScaleBar.Options); + } + + export module ScaleBar { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + } + } + + /** + * This class encapsulates map UI functionality. + */ + export class UI implements H.util.ICapturable { + /** + * Constructor + * @param map {H.Map} + * @param opt_options {H.ui.UI.Options=} + */ + constructor(map: H.Map, opt_options?: UI.Options); + + /** + * This method returns this ui's root element. + * @returns {ELement} - the root element + */ + getElement(): Element; + + /** + * Returns the map instance to which this UI was added. + * @returns {H.Map} + */ + getMap(): H.Map; + + /** + * This method returns this UI object's current unit system. + * @returns {H.ui.UnitSystem} - the current unit system + */ + getUnitSystem(): UnitSystem; + + /** + * This method sets this UI object's unit system for displaying distances. + * @param unitSystem {H.ui.UnitSystem} - the unit system to use + */ + setUnitSystem(unitSystem: UnitSystem): void; + + /** + * Toggles this UI's unit system between {@link H.ui.UnitSystem.METRIC} and {@link H.ui.UnitSystem.IMPERIAL}. + */ + toggleUnitSystem(): void; + + /** + * This method adds an info bubble to the UI. + * @param bubble {H.ui.InfoBubble} - the info bubble to be added + */ + addBubble(bubble: InfoBubble): void; + + /** + * This method removes a previously added info bubble from the UI. + * @param bubble {H.ui.InfoBubble} - the info bubble to be removed + */ + removeBubble(bubble: InfoBubble): void; + + /** + * This method returns a list of info bubble objects which are currently attached to this UI. + * @returns {Array} - the list of info bubbles + */ + getBubbles(): Array; + + /** + * This method appends a control to the UI. + * @param name {string} - the name under which to register this control + * @param control {H.ui.Control} - the control to add to this UI + */ + addControl(name: string, control: Control): void; + + /** + * Removes a previously registered control from the UI object. + * @param name {string} - the name under which this control was previously registered + * @returns {H.ui.Control} - the removed control + */ + removeControl(name: string): Control; + + /** + * This method returns a UI control which was previously registered with the provided name. + * @param name {string} - the name under which the control was registered. + * @returns {H.ui.Control} - the control or undefined if the control does not exist. + */ + getControl(name: string): Control; + + /** + * This function creates the default UI including the zoom control, + * map settings control and scalebar and panorama discovery control. + * The default controls will be assigned the following values: + * + * Zoom control: + * id: 'zoom' + * alignment: 'right-middle' + * Map settings control: + * id: 'mapsettings' + * alignment: 'bottom-right' + * Scalebar: + * id: 'scalebar' + * alignment: 'bottom-right' + * Pano: + * id: 'panorama' + * alignment: 'top-right' + * + * @param map {H.Map} - The map instance to which to append the UI + * @param mapTypes {Object} - The map types to use + * @param opt_locale {(H.ui.i18n.Localization | string)=} - the language to use (or a full localization object). + * @returns {H.ui.UI} - the UI instance configured with the default controls + */ + static createDefault(map: H.Map, mapTypes: H.service.Platform.MapTypes, opt_locale?: H.ui.i18n.Localization | string): UI; + + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRation {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {ICapturable~captureCallback} - Callback function to call once result of the capturing is ready + * @param opt_errback {ICapturable~errorCallback} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRation: number, callback: (canvas?: HTMLCanvasElement) => void, opt_errback?: (error: string) => void): void; + + /** + * @callback ICapturable~captureCallback + * @param canvas {HTMLCanvasElement=} + */ + + /** + * @callback ICapturable~errorCallback + * @param error {string} + */ + } + + export module UI { + /** + * Optional parameters to be passed to the UI constructor. + * @property unitSystem {H.ui.UnitSystem=} - An optional unit system to be used by the UI, default is H.ui.UnitSystem.METRIC + * @property zoom {(H.ui.ZoomControl.Options | boolean)=} - + * @property zoomrectangle {(H.ui.ZoomRectangle.Options | boolean)=} - + * @property mapsettings {(H.ui.MapSettingsControl.Options | boolean)=} - + * @property scalebar {(H.ui.ScaleBar.Options | boolean)=} - + * @property panorama {(H.ui.Pano.Options | boolean)=} - + * @property distancemeasurement {(H.ui.DistanceMeasurement.Options | boolean)=} - + * @property locale {(H.ui.i18n.Localization | string)=} - defines language in which UI can be rendered. It can be predefined H.ui.i18n.Localization object with custom translation map, or a string one of following 'en-US', 'de-DE', 'es-ES', 'fi-FI', 'fr-FR', 'it-IT', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'tr-TR', 'zh-CN'. If not defined ui will use 'en-US' by default + */ + export interface Options { + unitSystem?: H.ui.UnitSystem; + zoom?: (H.ui.ZoomControl.Options | boolean); + zoomrectangle?: (H.ui.ZoomRectangle.Options | boolean); + mapsettings?: (H.ui.MapSettingsControl.Options | boolean); + scalebar?: (H.ui.ScaleBar.Options | boolean); + panorama?: (H.ui.Pano.Options | boolean); + distancemeasurement?: (H.ui.DistanceMeasurement.Options | boolean); + locale?: (H.ui.i18n.Localization | string); + } + } + + /** + * This enumeration holds the possible unit systems for the UI to display distances. + */ + export enum UnitSystem { + /** This value represents the imperial unit system using miles and feet (value: 'imperial'). */ + IMPERIAL, + /** This value represents the metric unit system using meters and kilometers, etc (value: 'metric'). */ + METRIC, + } + + /** + * This class represents the UI controls for zooming in an out of the map. + */ + export class ZoomControl extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.ZoomControl.Options=} - optional parameters to be passed to the map. + */ + constructor(opt_options?: H.ui.ZoomControl.Options); + + /** + * This method returns the zoom speed (in levels per millisecond) which is applied when the button is pressed constantly. + * @returns {number} - the current zoom speed + */ + getZoomSpeed(): number; + } + + export module ZoomControl { + /** + * @property zoomSpeed {number=} - the speed if zooming in and out in levels per millisecond, defaults to 0.05 + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, defaults to H.ui.LayoutAlignment.RIGHT_MIDDLE + * @property slider {boolean=} - flag whether to show the slider (true) or not, defaults to false + * @property sliderSnaps {boolean=} - flag whether slider should snap to the integer values or not, defaults to false. This option has effect only if slider is enabled. + */ + export interface Options { + zoomSpeed?: number; + alignment?: H.ui.LayoutAlignment; + slider?: boolean; + sliderSnaps?: boolean; + } + } + + /** + * This class represents a zoom rectangle control element that allows zooming to the selected area on the screen. + */ + export class ZoomRectangle extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.ZoomRectangle.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.ZoomRectangle.Options); + } + + export module ZoomRectangle { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + * @property adjustZoom {function(number, H.Map) : number=} - optional function that defines how zoom level should be changed, by default zoom level is picked to fit the bounding rectangle into the view port. + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + adjustZoom?(n: number, m: H.Map): number; + } + } + + type ES6Element = Element; + + /** + * This namespace contains basic UI elements from which the UI controls are built. + */ + export module base { + export class Container extends H.util.EventTarget { + /** + * Constructor + * @param opt_elementType {string=} - the type of HTML element this UI element renders as, default is 'div' + * @param opt_className {string=} - an optional class name to be used on this element + * @param opt_children {Array=} - optional child elements to be added to this container + */ + constructor(opt_elementType?: string, opt_className?: string, opt_children?: Array); + + /** + * Adds a child element to be rendered within the container element. + * @param child {H.ui.base.Element} - the child element to be added + * @returns {H.ui.base.Container} - this container instance + */ + addChild(child: Element): Container; + + /** + * Returns the child collection of this container. + * @returns {Array} - Returns the child collection of this container. + */ + getChildren(): Array; + + /** + * Removes a child element from this container's child collection. + * @param child {H.ui.base.Element} - the child element to be removed + */ + removeChild(child: Element): void; + + /** + * This method is the concrete implementation of the UI element. This method receives the pre-rendered HTML element which may be modified by deriving classes. + * @param element {Element} - this UI element's HTML representation + * @param doc {Document} - the HTML document into which the element is currently being rendered + */ + renderInternal(element: ES6Element, doc: Document): void; + + /** + * This method returns this UI element's disabled state as a boolean value. + * @returns {boolean} - true if the element is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method set's the disabled state of this UI element. + * @param disabled {boolean} - true to disable the element, false to enable it + * @param opt_force {boolean=} - an optional boolean flag indicating that the value should be set and propagated even if it is the same as the current state + * @returns {H.ui.base.Element} - this element instance + */ + setDisabled(disabled: boolean, opt_force?: boolean): ES6Element; + + /** + * This method returns a previously stored arbitrary data from this element. + * @returns {*} - the previously stored data object or null if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this UI element. + * @param data {*} - the data to be stored + */ + setData(data: any): void; + + /** + * This method returns the HTML element this UI element renders. + * + * Note: Before the UI element was rendered the method returns null. + * @returns {?HTMLElement} - the element + */ + getElement(): HTMLElement; + + /** + * Sets the visibility of this element. + * @param visibility {boolean} - visibility + */ + setVisibility(visibility: boolean): void; + + /** + * Returns the visibility of this element. + * @returns {boolean} - visibility + */ + getVisibility(): boolean; + + /** + * This method adds a CSS class to this UI element (if it is not already present). + * @param className {string} - the CSS class name to add + * @returns {H.ui.base.Element} - this UI element instance + */ + addClass(className: string): Element; + + /** + * This method removes a CSS class from this UI element (if it is present). + * @param className {string} - the CSS class name to remove + * @returns {H.ui.base.Element} - this UI element instance + */ + removeClass(className: string): Element; + } + + export class Element extends H.util.EventTarget { + /** + * Constructor + * @param opt_elementType {string=} - the type of HTML element this UI element renders as, default is 'div' + * @param opt_className {string=} - an optional class name to be used on this element + */ + constructor(opt_elementType?: string, opt_className?: string); + + /** + * This method is the concrete implementation of the UI element. This method receives the pre-rendered HTML element which may be modified by deriving classes. + * @param element {Element} - this UI element's HTML representation + * @param doc {Document} - the HTML document into which the element is currently being rendered + */ + renderInternal(element: ES6Element, doc: Document): void; + + /** + * This method returns this UI element's disabled state as a boolean value. + * @returns {boolean} - true if the element is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method set's the disabled state of this UI element. + * @param disabled {boolean} - true to disable the element, false to enable it + * @param opt_force {boolean=} - an optional boolean flag indicating that the value should be set and propagated even if it is the same as the current state + * @returns {H.ui.base.Element} - this element instance + */ + setDisabled(disabled: boolean, opt_force?: boolean): ES6Element; + + /** + * This method returns a previously stored arbitrary data from this element. + * @returns {*} - the previously stored data object or null if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this UI element. + * @param data {*} - the data to be stored + */ + setData(data: any): void; + + /** + * This method returns the HTML element this UI element renders. + * + * Note: Before the UI element was rendered the method returns null. + * @returns {?HTMLElement} - the element + */ + getElement(): HTMLElement; + + /** + * Sets the visibility of this element. + * @param visibility {boolean} - visibility + */ + setVisibility(visibility: boolean): void; + + /** + * Returns the visibility of this element. + * @returns {boolean} - visibility + */ + getVisibility(): boolean; + + /** + * This method adds a CSS class to this UI element (if it is not already present). + * @param className {string} - the CSS class name to add + * @returns {H.ui.base.Element} - this UI element instance + */ + addClass(className: string): Element; + + /** + * This method removes a CSS class from this UI element (if it is present). + * @param className {string} - the CSS class name to remove + * @returns {H.ui.base.Element} - this UI element instance + */ + removeClass(className: string): Element; + } + } + + /** + * Namespace contains functionality related to internationalization. + */ + export module i18n { + /** + * Default available locales. UI provides default translations for this set of locale codes. + */ + export const defaultLocales: Array; + + /** + * This class is used for internationalization of UI components. + */ + export class Localization { + constructor(locale: string, opt_translationMap?: any); + + /** + * This method returns current locale code i.e 'en-US' + * @returns {string} - locale code + */ + getLocale(): string; + + /** + * This method returns translation keys for current locale. Keys from this set can be used to get translations via translate method. + * @returns {Array} + */ + getKeys(): Array; + + /** + * This method returns a boolean value indicating whether this localization object has a translation for the specified translation key. + * @param key {string} - a translation key + * @returns {boolean} - true if the key exists, otherwise false + */ + hasKey(key: string): boolean; + + /** + * This method returns translation for provided key. It throws exception if translation is not available + * @param key {string} - a translation key + * @returns {string} - a localized string corresponding to provided key + */ + translate(key: string): string; + } + } + } + + /***** util *****/ + export module util { + /** + * The cache represents a in-memory LRU-cache with a fixed size. It stores any data that is added until the cache's content exceeds a maximum size. Once the size of all content elements exceeds the maximum size the cache will drop the least recently retrieved elements until the size of the cache is within the bounds of its maximum size. Data elements are always associated with an identifier that allow to retrieve them at a later stage and their content size. + */ + export class Cache implements H.util.ICache { + /** + * Constructor + * @param maxSize {number} - the maximum size of the cache + * @param opt_onDrop {function(string, ?, number)=} - A callback to be invoked when a data element is dropped from the cache + * @param opt_filter {(function(string, ?, number) : boolean)=} - A function to filter data elements that are not to be cached + */ + constructor(maxSize: number, opt_onDrop?: (s: string, i: any, n: number) => void, opt_filter?: (s: string, i: any, n: number) => boolean); + + /** + * This method sets this cache's maximum size to a new size. If the cache's contents exceed the new size, least recently used data elements will be dropped. + * @param maxSize {number} - the new maximum size of this cache. + * @returns {H.util.Cache} - this cache + */ + setMaxSize(maxSize: number): H.util.Cache; + + /** + * This method returns the maximum size of this cache. + * @returns {number} - the maximum size of the cache + */ + getMaxSize(): number; + + /** + * This method returns the current size of this cache. + * @returns {number} - the current size of the cache + */ + getCurrentSize(): number; + + /** + * This method adds an element to the cache. + * @param id {*} - The identifier of this data element, the value is converted to a string. + * @param data {*} - the actual data to be stored + * @param size {number} - the size of the data element + * @returns {boolean} - a boolean value indicating whether the data was added + */ + add(id: any, data: any, size: number): boolean; + + /** + * This method retrieves an element from the cache. + * @param id {string} - the ID of the data element to be retrieved. + * @param opt_noUpdate {boolean=} - and optional flag to indicate that the retrieved object should not be marked as 'most recently used'. + * @returns {*} - returns the data associated with the ID or undefined if the data element is not currently in the cache. + */ + get(id: string, opt_noUpdate?: boolean): any; + + /** + * This method explicitly drops an element from the cache. + * @param id {*} - the id of the item to drop + */ + drop(id: any): void; + + /** + * This method will execute the provided callback function on each of the cache's entries. If the optional match predicate is passed to this method the callback will only be executed on those entries for which the predicated returns true. + * @param callback {function(string, ?, number)} - the callback to be invoked for each entry + * @param opt_ctx {Object=} - an optional context object to be used as this within the callback + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional match predicate to customize on which entries the callback will be called + */ + forEach(callback: (s: string, i: any, n: number) => void, opt_ctx?: any, opt_matcher?: (s: string, i: any, n: number) => boolean): void; + + /** + * This method removes all data elements from the cache. If the optional match predicate is passed to this method only those data elements will be removed for which the predicate return true. + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional function that receives an entries id, data and size and may return true or false to either remove it or leave the entry in the cache respectively + */ + removeAll(opt_matcher?: (s: string, i: any, n: number) => boolean): void; + + /** + * This method registers a callback that should be called each time an entry is dropped from the cache. + * @param callback {(function(string, ?, number))} - the callback to be invoked for each entry + */ + registerOnDrop(callback: (s: string, i: any, n: number) => void): void; + } + + /** + * This event indicates a change. It contains the old and the new value. + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class ChangeEvent extends H.util.Event { + /** + * Constructor + * @param type {string} - The type of the event + * @param newValue {*} - The new value of the property + * @param oldValue {*} - The previous value of the property + */ + constructor(type: string, newValue: any, oldValue: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + + /** + * This class represents a contextual information/action. + * @property SEPARATOR {H.util.ContextItem} - Separator for the context items + */ + export class ContextItem extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.util.ContextItem.Options=} - The values to initialize this context item + */ + constructor(opt_options?: H.util.ContextItem.Options); + + /** + * This method returns label of the context item + * @returns {string} - the label of the context item + */ + getLabel(): string; + + /** + * This method changes context item label to the specified one + * @param label {string} - New label for the context item + * @returns {H.util.ContextItem} - this context item instance + */ + setLabel(label: string): H.util.ContextItem; + + /** + * This method returns disabled state of the context item. + * @returns {boolean} - true if the item is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method enables/disables the context item + * @param disabled {boolean} - true to disable and false to enabled it + * @returns {H.util.ContextItem} - this context item instance + */ + setDisabled(disabled: boolean): H.util.ContextItem; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + static SEPARATOR: H.util.ContextItem; + } + + export module ContextItem { + /** + * This type defines options which can be used to initialize the context item. + * @property label {string=} - the label of the context item + * @property disabled {boolean=} - flag indicatting whether context item is disabled or no, by default false + * @property callback {function(H.util.Event)=} - Optional callback function to call once context item is selected + */ + export interface Options { + label?: string; + disabled?: boolean; + callback?: (event: H.util.Event) => void; + } + } + + /** + * Object which can be safely disposed. + */ + export class Disposable { + /** + * Constructor + */ + constructor(); + + /** + * Method adds a callback which will be triggered when the object is disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + /** + * Base Event class which is used for all events dispatched by any EventTarget within the api. + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event { + /** + * Constructor + * @param type {string} - Event Type. + * @param opt_target {Object=} - Reference to the object that is the target of this event. It has to implement the {@link EventTargetInstance} interface. + */ + constructor(type: string, opt_target?: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + + /** + * EventTarget enabled listening and dispatching events on all instances and derived classes. + */ + export class EventTarget { + /** + * Constructor + */ + constructor(); + + /** + * This method allows to listen for specific event triggered by the object. Keep in mind, that you must removeEventListener manually or dispose an object when you no longer need it. Otherwise memory leak is possible. + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + addEventListener(type: string, handler: EventListenerOrEventListenerObject, opt_capture?: boolean, opt_scope?: any): void; + + /** + * This method will removed previously added listener from the event target + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + removeEventListener(type: string, handler: EventListenerOrEventListenerObject, opt_capture?: boolean, opt_scope?: any): void; + + /** + * This method will dispatch event on the event target object + * @param evt {H.util.Event | string} - event object or event name + */ + dispatchEvent(evt: H.util.Event | string): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: () => void, opt_scope?: any): void; + } + + /** + * An interface definition for the generic cache. Any data elements can be stored in the cache. They are always associated with an identifier to retrieve them at a later stage and their content size. + */ + export interface ICache { + /** + * This method adds an element to the cache. + * @param id {*} - The identifier of this data element, the value is converted to a string. + * @param data {*} - the actual data to be stored + * @param size {number} - the size of the data element + * @returns {boolean} - a boolean value indicating whether the data was added + */ + add(id: any, data: any, size: number): boolean; + + /** + * This method retrieves an element from the cache. + * @param id {string} - the ID of the data element to be retrieved. + * @param opt_noUpdate {boolean=} - and optional flag to indicate that the retrieved object should not be marked as 'most recently used'. + * @returns {*} - returns the data associated with the ID or undefined if the data element is not currently in the cache. + */ + get(id: string, opt_noUpdate?: boolean): any; + + /** + * This method explicitly drops an element from the cache. + * @param id {*} - the id of the item to drop + */ + drop(id: any): void; + + /** + * This method will execute the provided callback function on each of the cache's entries. If the optional match predicate is passed to this method the callback will only be executed on those entries for which the predicated returns true. + * @param callback {function(string, ?, number)} - the callback to be invoked for each entry + * @param opt_ctx {Object=} - an optional context object to be used as this within the callback + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional match predicate to customize on which entries the callback will be called + */ + forEach(callback: (s: string, t: any, n: number) => void, opt_ctx?: Object, opt_matcher?: ((s: string, t: any, n: number) => boolean)): void; + + /** + * This method removes all data elements from the cache. If the optional match predicate is passed to this method only those data elements will be removed for which the predicate return true. + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional function that receives an entries id, data and size and may return true or false to either remove it or leave the entry in the cache respectively + */ + removeAll(opt_matcher?: ((s: string, t: any, n: number) => boolean)): void; + + /** + * This method registers a callback that should be called each time an entry is dropped from the cache. + * @param callback {(function(string, ?, number))} - the callback to be invoked for each entry + */ + registerOnDrop(callback: ((s: string, t: any, n: number) => void)): void; + } + + /** + * An interface to cancelable requests and actions. + */ + export interface ICancelable { + /** + * This method is used to cancel current action + */ + cancel(): void; + } + + export interface ICapturable { + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRation {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {ICapturable~captureCallback} - Callback function to call once result of the capturing is ready + * @param opt_errback {ICapturable~errorCallback} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRation: number, callback: (canvas?: HTMLCanvasElement) => void, opt_errback?: (error: string) => void): void; + + /** + * @callback ICapturable~captureCallback + * @param canvas {HTMLCanvasElement=} + */ + + /** + * @callback ICapturable~errorCallback + * @param error {string} + */ + } + + /** + * This class represents an list of ordered entries which dispatches events when the list is modified. + * @event add {H.util.OList.Event} - Fired when an entry was added to the list. + * @event remove {H.util.OList.Event} - Fired when an entry was removed from the list. + * @event set {H.util.OList.Event} - Fired when an entry was set in the list. + * @event move {H.util.OList.Event} - Fired when an entry was moved within the list. + */ + export class OList extends H.util.EventTarget { + + /** + * This method inserts an entry to the list. Optionally it can place new entry at provided index. + * @param entry {?} - The entry to insert + * @param opt_idx {number=} - The index where the new entry should be inserted; if omitted or greater then the current size of the list, the entry is added at the end of the list; a negative index is treated as being relative from the end of the list + */ + add(entry: any, opt_idx?: number): void; + + /** + * This method removes an entry by a given index from the list. + * @param idx {number} - The index of the entry which should be removed; a negative index is treated as being relative from the end of the list + * @returns {?} - The removed entry + */ + removeAt(idx: number): any; + + /** + * This method removes the the first entry which is identical with the given entry. + * @param entry {?} - The entry to remove + * @returns {boolean} - signals if the entry could be found in the list and is removed + */ + remove(entry: any): boolean; + + /** + * This method replaces an entry at the given index with the given entry. + * @param idx {number} - The index of the entry which should be replaced; a negative index is treated as being relative from the end of the list + * @param entry {?} - The entry which replaces the existing one + * @returns {?} - The replaced entry + */ + set(idx: number, entry: any): any; + + /** + * This method retrieves the index of the first object in this list that is identical with the object supplied by the caller. + * @param entry {?} - The entry for which to return the index. + * @returns {number} - The index of the first matching entry in this list or -1 if the entry provided by the caller is not found in the list + */ + indexOf(entry: any): number; + + /** + * To get the entry at the specified index. + * @param idx {number} - The index of the entry to get a negative index is treated as being relative from the end of the list + * @returns {?} - The element at the given index + */ + get(idx: number): any; + + /** + * This method returns the length of the list. + * @returns {number} + */ + getLength(): number; + + /** + * This method returns all list's entries as an array. + * @returns {Array<*>} - The list as an array + */ + asArray(): Array; + + /** + * This method removes all entries from the list. + */ + flush(): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module OList { + /** + * The event class for events that are dispatched by OList + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param list {H.util.OList} - The OList instance which is emitting the event + * @param type {H.util.OList.prototype.EventType} - The type of the event + * @param idx {number} - The affected index within this list + * @param added {?*} - The value of the entry which was added or set + * @param removed {?*} - The value of the entry which was removed or replaced + * @param moved {?*} - The value of the entry which was moved + */ + constructor(list: H.util.OList, type: string, idx: number, added: any, removed: any, moved: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + } + + /** + * A generic class to represent a handle for any kind of asynchronous processed requests + */ + export class Request { + /** + * Constructor + * @param opt_onprogress {function(H.util.Request)=} - A callback to invoke every time when the request's progress state changes + * @param opt_total {number=} - The total number of processing steps to complete this request, default is 1 + */ + constructor(opt_onprogress?: (req: H.util.Request) => void, opt_total?: number); + + /** + * Returns the state of this request + * @returns {H.util.Request.State} + */ + getState(): H.util.Request.State; + + /** + * Returns the number of processing steps to complete this request + * @returns {number} + */ + getTotal(): number; + + /** + * Returns the number of steps which are already processed by this request + * @returns {number} + */ + getProcessed(): number; + + /** + * Returns the number of processingsteps which have been failed + * @returns {number} + */ + getFailed(): number; + } + + export module Request { + /** + * The supported states of an request + */ + export enum State { + PENDING, + PROCESSING, + COMPLETE, + CANCELLED, + ERROR, + } + } + + export module animation { + /** + * This mamespace contains easing functions used for Animation class. + */ + export class ease { + /** + * This function defines linear ease. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static LINEAR(val: number): number; + + /** + * This function defines quadratic ease in. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_IN_QUAD(val: number): number; + + /** + * This function defines quadratic ease out. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_OUT_QUAD(val: number): number; + + /** + * This function defines ease in and out with slope. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_IN_OUT_QUINT(val: number): number; + + /** + * This function defines ease out with circ function. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_OUT_CIRC(val: number): number; + } + } + + export module kinetics { + /** + * This interface defines kinetic move parameters used by map for kinetic drag. + * @property power {number} - Power multiplier. Multiplier is used to increase the speed of the kinetic move. By default map uses 1. + * @property duration {number} - Defines duration of the kinetic move. + */ + export interface IKinetics { + /** + * Easing function modifies animation progress. In example it can modify the animation in a way it starts rapidly and then slows down at the end. + * @param p {number} - current progress + * @returns {number} - modified progress + */ + ease(p: number): number; + + power: number; + duration: number; + } + } + } +} diff --git a/highcharts/highcharts-modules-exporting.d.ts b/highcharts/highcharts-modules-exporting.d.ts new file mode 100644 index 0000000000..4d3bdaa648 --- /dev/null +++ b/highcharts/highcharts-modules-exporting.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Highcharts 4.2.6 (exporting module) +// Project: http://www.highcharts.com/ +// Definitions by: Maciej Suchecki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var HighchartsExporting: (H: HighchartsStatic) => HighchartsStatic; + +declare module "highcharts/modules/exporting" { + export = HighchartsExporting; +} diff --git a/highcharts/highcharts-more.d.ts b/highcharts/highcharts-more.d.ts new file mode 100644 index 0000000000..1d42764b3c --- /dev/null +++ b/highcharts/highcharts-more.d.ts @@ -0,0 +1,12 @@ +// Type definitions for Highcharts 4.2.6 +// Project: http://www.highcharts.com/ +// Definitions by: Maciej Suchecki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var HighchartsMore: (H: HighchartsStatic) => HighchartsStatic; + +declare module "highcharts/highcharts-more" { + export = HighchartsMore; +} diff --git a/highcharts/highcharts.d.ts b/highcharts/highcharts.d.ts index de1e5343ca..bfe5a70235 100644 --- a/highcharts/highcharts.d.ts +++ b/highcharts/highcharts.d.ts @@ -240,7 +240,7 @@ interface HighchartsPlotBands { * Border color for the plot band. Also requires borderWidth to be set. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * Border width for the plot band. Also requires borderColor to be set. * @default 0 @@ -471,7 +471,7 @@ interface HighchartsAxisOptions { /** * Configure a crosshair that follows either the mouse pointer or the hovered point. */ - crosshair?: HighchartsCrosshairObject; + crosshair?: HighchartsCrosshairObject | boolean; /** * For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default * string representations used for each unit. For an overview of the replacement codes, see dateFormat. @@ -556,7 +556,7 @@ interface HighchartsAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0'. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 1 @@ -820,7 +820,7 @@ interface HighchartsAxisOptions { interface HighchartsColorAxisDataClass { from?: number; to?: number; - color?: string; + color?: string | HighchartsGradient; name?: string; } @@ -906,7 +906,7 @@ interface HighchartsColorAxisOptions { * The color of the line marking the axis itself. * @default '#C0D0E0' */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the line marking the axis itself. * @default 0 @@ -926,7 +926,7 @@ interface HighchartsColorAxisOptions { * The color of the marker. * @default 'gray' */ - color?: string; + color?: string | HighchartsGradient; }; /** * The maximum value of the axis in terms of map point values. If null, the max value is automatically calculated. @@ -1382,7 +1382,7 @@ interface HighchartsShadow { /** * @default 'black' */ - color?: string; + color?: string | HighchartsGradient; /** * @default 1 */ @@ -1491,7 +1491,7 @@ interface HighchartsChartOptions { * The color of the outer chart border. * @default '#4572A7' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the outer chart border. * @default 0 @@ -1721,7 +1721,7 @@ interface HighchartsChartOptions { interface HighchartsCSSObject { background?: string; border?: string; - color?: string; + color?: string | HighchartsGradient; cursor?: string; font?: string; fontFamily?: string; @@ -2429,7 +2429,7 @@ interface HighchartsLegendOptions { * The color of the drawn border around the legend. * @default '#909090' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border corner radius of the legend. * @default 0 @@ -2724,7 +2724,7 @@ interface HighchartsPaneBackground { /** * @default 'silver' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * @default 1 */ @@ -2803,7 +2803,7 @@ interface HighchartsDataLabels { * The border color for the data label. * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -2820,7 +2820,7 @@ interface HighchartsDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3066,7 +3066,7 @@ interface HighchartsMarkerState { * The color of the point marker's outline. When null, the series' or point's color is used. * @default '#FFFFFF', '#000000' for select state */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The width of the point marker's outline. * @default 0 @@ -3276,7 +3276,7 @@ interface HighchartsAreaZone { * Defines the color of the series. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * A name for the dash style to use for the graph. * @since 4.1.0 @@ -3321,7 +3321,7 @@ interface HighchartsRangeDataLabels { * @default undefined * @since 2.2.1 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border radius in pixels for the data label. * @default 0 @@ -3338,7 +3338,7 @@ interface HighchartsRangeDataLabels { * The text color for the data labels. * @default null */ - color?: string; + color?: string | HighchartsGradient; /** * Whether to hide data labels that are outside the plot area. By default, the data label is moved inside the plot * area according to the overflow option. @@ -3471,7 +3471,7 @@ interface HighchartsDial { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The length of the dial's base part, relative to the total radius or length of the dial. * @default '70%'. @@ -3490,7 +3490,7 @@ interface HighchartsDial { * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the gauge dial border in pixels. * @default 0 @@ -3524,14 +3524,14 @@ interface HighchartsPivot { * @default 'black' * @since 2.3.0 */ - backgroundColor?: string; + backgroundColor?: string | HighchartsGradient; /** * The border or stroke color of the pivot. In able to change this, the borderWidth must also be set to something * other than the default 0. * @default 'silver' * @since 2.3.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The border or stroke width of the pivot. * @default 0 @@ -3554,7 +3554,7 @@ interface HighchartsTreeMapLevel { * Can set borderColor on all points which lies on the same level. * @since 4.1.0 */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * et the dash style of the border of all the point which lies on the level. * @since 4.1.0 @@ -3569,7 +3569,7 @@ interface HighchartsTreeMapLevel { * Can set a color on all points which lies on the same level. * @since 4.1.0 */ - color?: string; + color?: string | HighchartsGradient; /** * Can set the options of dataLabels on each point which lies on the level. * @default undefined @@ -3594,7 +3594,7 @@ interface HighchartsTreeMapLevel { } /** - * General options for all series types + * General options for all series types. */ interface HighchartsSeriesChart { /** @@ -3615,7 +3615,7 @@ interface HighchartsSeriesChart { * specified. In bar type series it applies to the bars unless a color is specified per point. The default value is * pulled from the options.colors array. */ - color?: string; + color?: string | HighchartsGradient; /** * Polar charts only. Whether to connect the ends of a line series plot across the extremes. * @default true @@ -3860,7 +3860,7 @@ interface HighchartsAreaChart extends HighchartsSeriesChart { * A separate color for the graph line. By default the line takes the color of the series, but the lineColor setting * allows setting a separate color for the line without altering the fillColor. */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * A separate color for the negative part of the area. * @since 3.0 @@ -3902,7 +3902,7 @@ interface HighchartsBarChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4263,7 +4263,7 @@ interface HighchartsFunnelChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4385,7 +4385,7 @@ interface HighchartsHeatMapChart extends HighchartsSeriesChart { * The color of the border surrounding each column or bar. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The corner radius of the border surrounding each column or bar. * @default 0 @@ -4468,7 +4468,7 @@ interface HighchartsPieChart extends HighchartsSeriesChart { * borderless pies. * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4573,7 +4573,7 @@ interface HighchartsPyramidChart extends HighchartsSeriesChart { * The color of the border surrounding each slice * @default '#FFFFFF' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each slice * @default 1 @@ -4688,7 +4688,7 @@ interface HighchartsTreeMapChart extends HighchartsSeriesChart { * The color of the border surrounding each tree map item. * @default '#E0E0E0' */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The width of the border surrounding each column or bar. * @default 1 @@ -4783,7 +4783,7 @@ interface HighchartsWaterFallChart extends HighchartsBarChart { * @default '#333333' * @since 3.0 */ - lineColor?: string; + lineColor?: string | HighchartsGradient; /** * The color used specifically for positive point columns. When not specified, the general series color is used. */ @@ -4834,7 +4834,7 @@ interface HighchartsIndividualSeriesOptions { * specified. In bar type series it applies to the bars unless a color is specified per point. The default * value is pulled from the options.colors array. */ - color?: string; + color?: string | HighchartsGradient; /** * You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user * that the points and lines can be clicked. @@ -4949,7 +4949,7 @@ interface HighchartsDataPoint { * Individual color for the point. By default the color is pulled from the global colors array. * @default undefined */ - color?: string; + color?: string | HighchartsGradient; /** * Serves a purpose only if a colorAxis object is defined in the chart options. This value will decide which color * the point gets from the scale of the colorAxis. @@ -5173,7 +5173,7 @@ interface HighchartsTitleOptions { } interface HighchartsCrosshairObject { - color?: string; + color?: string | HighchartsGradient; width?: number; dashStyle?: string; //Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot zIndex?: number; @@ -5200,7 +5200,7 @@ interface HighchartsTooltipOptions extends HighchartsSeriesTooltipOptions { * The color of the tooltip border. When null, the border takes the color of the corresponding series or point. * @default null */ - borderColor?: string; + borderColor?: string | HighchartsGradient; /** * The radius of the rounded border corners. * @default 3 @@ -5602,7 +5602,7 @@ interface HighchartsAxisObject { * @param {boolean | HighchartsAnimation} animation When true, the resize will be animated with default animation options. The animation can also be a configuration object with properties duration and easing. * @since 1.2.0 */ - setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation): void; + setExtremes(min?: number, max?: number, redraw?: boolean, animation?: boolean | HighchartsAnimation, eventArguments?: any): void; /** * Update the title of the axis after render time. * @param {HighchartsAxisTitle} title The new title options on the same format as given in xAxis.title. diff --git a/html-pdf/html-pdf-tests.ts b/html-pdf/html-pdf-tests.ts new file mode 100644 index 0000000000..6a214ef231 --- /dev/null +++ b/html-pdf/html-pdf-tests.ts @@ -0,0 +1,13 @@ +/// +/// + +import * as fs from 'fs'; +import * as pdf from 'html-pdf'; + +var html = fs.readFileSync('./test/businesscard.html', 'utf8'); +var options: pdf.CreateOptions = { format: 'Letter' }; + +pdf.create(html, options).toFile('./businesscard.pdf', (err: Error, res: pdf.FileInfo) => { + if (err) return console.log(err); + console.log(res); // { filename: '/app/businesscard.pdf' } +}); diff --git a/html-pdf/html-pdf.d.ts b/html-pdf/html-pdf.d.ts new file mode 100644 index 0000000000..07c4be9f71 --- /dev/null +++ b/html-pdf/html-pdf.d.ts @@ -0,0 +1,80 @@ +// Type definitions for html-pdf v2.1.0 +// Project: https://github.com/marcbachmann/node-html-pdf +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'html-pdf' { + + import * as fs from 'fs'; + + export interface CreateOptions { + + // Export options + directory?: string; + + // Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html + height?: string; + width?: string; + format?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid'; + orientation?: 'portrait' | 'landscape'; + + // Page options + border?: string | { + top?: string; + right?: string; + bottom?: string; + left?: string; + }; + + header?: { + height?: string; + contents?: string; + }; + footer?: { + height?: string; + contents?: { + first?: string; + [page: number]: string; + default?: string; + last?: string; + }; + }; + + // Rendering options + base?: string; + + // Zooming option, can be used to scale images if `options.type` is not pdf + zoomFactor?: string; + + // File options + type?: 'png' | 'jpeg' | 'pdf'; + quality?: string; + + // Script options + phantomPath?: string; + phantomArgs?: string[]; + script?: string; + timeout?: number; + + // HTTP Headers that are used for requests + httpHeaders?: { + [header: string]: string; + }; + + } + + export interface FileInfo { + filename: string; + } + + export interface CreateResult { + toBuffer(callback: (err: Error, buffer: Buffer) => void): void; + toFile(callback: (err: Error, res: FileInfo) => void): void; + toFile(filename?: string, callback?: (err: Error, res: FileInfo) => void): void; + toStream(callback: (err: Error, stream: fs.ReadStream) => void): void; + } + + export function create(html: string, options?: CreateOptions): CreateResult; +} diff --git a/humps/humps-tests.ts b/humps/humps-tests.ts new file mode 100644 index 0000000000..66017b065c --- /dev/null +++ b/humps/humps-tests.ts @@ -0,0 +1,71 @@ +/// + +// Tests evaluated from: +// https://github.com/domchristie/humps/blob/master/README.md + +import * as humps from "humps"; + +let someObject = { attr_one: 'foo', attr_two: 'bar' }; +let someArray = [{ attr_one: 'foo' }, { attr_one: 'bar' }] + +let someOptions: humps.HumpsOptions = { + separator: '-' +}; +let someOptions2: humps.HumpsOptions = { + split: /^[A-Z0-9_]+$/ +}; +let someOptions3: humps.HumpsOptions = { + separator: '-', + process: function (key: string, convert: humps.HumpsProcessorParameter, options: humps.HumpsOptions) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); + } +}; + + +humps.camelize('hello_world') + +humps.decamelize('fooBar') +humps.decamelize('fooBarBaz', someOptions) + +humps.camelizeKeys(someObject); + +humps.camelizeKeys(someArray); + +humps.camelizeKeys(someObject, function (key, convert) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key); +}); + +humps.decamelizeKeys(someObject, function (key, convert, options) { + return /^[A-Z0-9_]+$/.test(key) ? key : convert(key, options); +}); + + +humps.camelize('hello_world-foo bar'); + +humps.pascalize('hello_world-foo bar'); + +humps.decamelize('helloWorldFooBar'); +humps.decamelize('helloWorldFooBar', someOptions); +humps.decamelize('helloWorld1', { split: /(?=[A-Z0-9])/ }) + +humps.depascalize('helloWorldFooBar'); + +humps.camelizeKeys(someObject); +humps.pascalizeKeys(someObject); +humps.decamelizeKeys(someObject); +humps.depascalizeKeys(someObject); + +humps.camelizeKeys(someObject, someOptions); +humps.pascalizeKeys(someObject, someOptions); +humps.decamelizeKeys(someObject, someOptions); +humps.depascalizeKeys(someObject, someOptions); + +humps.camelizeKeys(someObject, someOptions2); +humps.pascalizeKeys(someObject, someOptions2); +humps.decamelizeKeys(someObject, someOptions2); +humps.depascalizeKeys(someObject, someOptions2); + +humps.camelizeKeys(someObject, someOptions3); +humps.pascalizeKeys(someObject, someOptions3); +humps.decamelizeKeys(someObject, someOptions3); +humps.depascalizeKeys(someObject, someOptions3); diff --git a/humps/humps.d.ts b/humps/humps.d.ts new file mode 100644 index 0000000000..87f3bbd991 --- /dev/null +++ b/humps/humps.d.ts @@ -0,0 +1,39 @@ +// Type definitions for humps v1.1.0 +// Project: https://github.com/domchristie/humps +// Definitions by: Niklas Mollenhauer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace humps { + + function camelize(value: string): string; + function pascalize(value: string): string; + function decamelize(value: string, optionsOrProcessor?: OptionOrProcessor): string; + function depascalize(value: string, optionsOrProcessor?: OptionOrProcessor): string; + + function camelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function pascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function decamelizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + function depascalizeKeys(str: Object, optionsOrProcessor?: OptionOrProcessor): Object; + + function camelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function pascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function decamelizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + function depascalizeKeys(str: Object[], optionsOrProcessor?: OptionOrProcessor): Object[]; + + interface HumpsOptions { + separator?: string; + split?: RegExp; + process?: HumpsProcessor; + } + interface HumpsProcessor { + (key: string, convert: HumpsProcessorParameter, options?: HumpsOptions): string; + } + interface HumpsProcessorParameter { + (key: string, options?: HumpsOptions): string; + } + type OptionOrProcessor = HumpsOptions | HumpsProcessor; +} + +declare module "humps" { + export = humps; +} diff --git a/imap/imap.d.ts b/imap/imap.d.ts index 1531035152..07a7c8fe9a 100644 --- a/imap/imap.d.ts +++ b/imap/imap.d.ts @@ -236,7 +236,7 @@ declare namespace IMAP { serverSupports(capability: string): boolean; } - export class Connection implements NodeJS.EventEmitter, MessageFunctions { + export class Connection extends NodeJS.EventEmitter implements MessageFunctions { /** @constructor */ constructor(config: Config); diff --git a/incremental-dom/incremental-dom.d.ts b/incremental-dom/incremental-dom.d.ts index 56fd84542f..5a80e82d70 100644 --- a/incremental-dom/incremental-dom.d.ts +++ b/incremental-dom/incremental-dom.d.ts @@ -27,7 +27,7 @@ declare module "incremental-dom" { * @param {...*} var_args Attribute name/value pairs of the dynamic attributes * for the Element. */ - export var elementOpen: (tag: string, key?: string, statics?: any[], ...var_args: any[]) => void; + export var elementOpen: (tag: string, key?: string, statics?: any[], ...var_args: any[]) => HTMLElement; /** * Declares a virtual Element at the current location in the document. This * corresponds to an opening tag and a elementClose tag is required. This is @@ -54,11 +54,11 @@ declare module "incremental-dom" { /** * Closes an open tag started with elementOpenStart. */ - export var elementOpenEnd: () => void; + export var elementOpenEnd: () => HTMLElement; /** * Closes an open virtual Element. */ - export var elementClose: (tag: string) => void; + export var elementClose: (tag: string) => HTMLElement; /** * Declares a virtual Element at the current location in the document that has * no children. @@ -72,11 +72,11 @@ declare module "incremental-dom" { * @param {...*} var_args Attribute name/value pairs of the dynamic attributes * for the Element. */ - export var elementVoid: (tag: string, key?: string, statics?: any, ...var_args: any[]) => void; + export var elementVoid: (tag: string, key?: string, statics?: any, ...var_args: any[]) => HTMLElement; /** * Declares a virtual Text at this point in the document. * * @param {string} value The text of the Text. */ - export var text: (value: string) => void; + export var text: (value: string) => Text; } diff --git a/inversify-binding-decorators/inversify-binding-decorators-tests.ts b/inversify-binding-decorators/inversify-binding-decorators-tests.ts index 9b0dff520e..8ca0acc551 100644 --- a/inversify-binding-decorators/inversify-binding-decorators-tests.ts +++ b/inversify-binding-decorators/inversify-binding-decorators-tests.ts @@ -4,51 +4,52 @@ import { inject, Kernel } from "inversify"; import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators"; module decorator { + let kernel = new Kernel(); let provide = makeProvideDecorator(kernel); - interface INinja { + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon { throw(): string; } let TYPE = { - IKatana: "IKatana", - INinja: "INinja", - IShuriken: "IShuriken" + ThrowableWeapon: "ThrowableWeapon", + Warrior: "Warrior", + Weapon: "Weapon" }; - @provide(TYPE.IKatana) - class Katana implements IKatana { + @provide(TYPE.Weapon) + class Katana implements Weapon { public hit() { return "cut!"; } } - @provide(TYPE.IShuriken) - class Shuriken implements IShuriken { + @provide(TYPE.ThrowableWeapon) + class Shuriken implements ThrowableWeapon { public throw() { return "hit!"; } } - @provide(TYPE.INinja) - class Ninja implements INinja { + @provide(TYPE.Warrior) + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; public constructor( - @inject("IKatana") katana: IKatana, - @inject("IShuriken") shuriken: IShuriken + @inject(TYPE.Weapon) katana: Weapon, + @inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon ) { this._katana = katana; this._shuriken = shuriken; @@ -59,12 +60,13 @@ module decorator { } - let ninja = kernel.get(TYPE.INinja); + let ninja = kernel.get(TYPE.Warrior); console.log(ninja); } module fluent_decorator { + let kernel = new Kernel(); let provide = makeFluentProvideDecorator(kernel); @@ -76,27 +78,27 @@ module fluent_decorator { return provide(identifier).done(); }; - interface INinja { + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon { throw(): string; } let TYPE = { - IKatana: "IKatana", - INinja: "INinja", - IShuriken: "IShuriken" + ThrowableWeapon: "ThrowableWeapon", + Warrior: "Warrior", + Weapon: "Weapon" }; - @provideSingleton(TYPE.IKatana) - class Katana implements IKatana { + @provideSingleton(TYPE.Weapon) + class Katana implements Weapon { private _mark: any; public constructor() { this._mark = Math.random(); @@ -106,8 +108,8 @@ module fluent_decorator { } } - @provideTransient(TYPE.IShuriken) - class Shuriken implements IShuriken { + @provideTransient(TYPE.ThrowableWeapon) + class Shuriken implements ThrowableWeapon { private _mark: any; public constructor() { this._mark = Math.random(); @@ -117,15 +119,15 @@ module fluent_decorator { } } - @provideTransient(TYPE.INinja) - class Ninja implements INinja { + @provideTransient(TYPE.Warrior) + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; public constructor( - @inject("IKatana") katana: IKatana, - @inject("IShuriken") shuriken: IShuriken + @inject(TYPE.Weapon) katana: Weapon, + @inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon ) { this._katana = katana; this._shuriken = shuriken; @@ -136,7 +138,7 @@ module fluent_decorator { } - let ninja = kernel.get(TYPE.INinja); + let ninja = kernel.get(TYPE.Warrior); console.log(ninja); } diff --git a/inversify-binding-decorators/inversify-binding-decorators.d.ts b/inversify-binding-decorators/inversify-binding-decorators.d.ts index 623b6c32c7..d5f92132a3 100644 --- a/inversify-binding-decorators/inversify-binding-decorators.d.ts +++ b/inversify-binding-decorators/inversify-binding-decorators.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-beta.5 +// Type definitions for inversify-binding-decorators 1.0.0 // Project: https://github.com/inversify/inversify-binding-decorators // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,46 +7,50 @@ declare namespace inversifyBindingDecorators { - interface IProvideInSyntax extends IProvideDoneSyntax { - inSingletonScope(): IProvideWhenOnSyntax; - } + namespace interfaces { - interface IProvideDoneSyntax { - done(): (target: any) => any; - } + export interface ProvideInSyntax extends ProvideDoneSyntax { + inSingletonScope(): ProvideWhenOnSyntax; + } - interface IProvideOnSyntax extends IProvideDoneSyntax { - onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): IProvideWhenSyntax; - } + export interface ProvideDoneSyntax { + done(): (target: any) => any; + } - interface IProvideInWhenOnSyntax extends IProvideInSyntax, IProvideWhenSyntax, IProvideOnSyntax {} + export interface ProvideOnSyntax extends ProvideDoneSyntax { + onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): ProvideWhenSyntax; + } - interface IProvideWhenOnSyntax extends IProvideWhenSyntax, IProvideOnSyntax {} + export interface ProvideInWhenOnSyntax extends ProvideInSyntax, ProvideWhenSyntax, ProvideOnSyntax {} + + export interface ProvideWhenOnSyntax extends ProvideWhenSyntax, ProvideOnSyntax {} + + export interface ProvideWhenSyntax extends ProvideDoneSyntax { + when(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + whenTargetNamed(name: string): ProvideOnSyntax; + whenTargetTagged(tag: string, value: any): ProvideOnSyntax; + whenInjectedInto(parent: (Function|string)): ProvideOnSyntax; + whenParentNamed(name: string): ProvideOnSyntax; + whenParentTagged(tag: string, value: any): ProvideOnSyntax; + whenAnyAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; + whenNoAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; + whenAnyAncestorNamed(name: string): ProvideOnSyntax; + whenAnyAncestorTagged(tag: string, value: any): ProvideOnSyntax; + whenNoAncestorNamed(name: string): ProvideOnSyntax; + whenNoAncestorTagged(tag: string, value: any): ProvideOnSyntax; + whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + } - interface IProvideWhenSyntax extends IProvideDoneSyntax { - when(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; - whenTargetNamed(name: string): IProvideOnSyntax; - whenTargetTagged(tag: string, value: any): IProvideOnSyntax; - whenInjectedInto(parent: (Function|string)): IProvideOnSyntax; - whenParentNamed(name: string): IProvideOnSyntax; - whenParentTagged(tag: string, value: any): IProvideOnSyntax; - whenAnyAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; - whenNoAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; - whenAnyAncestorNamed(name: string): IProvideOnSyntax; - whenAnyAncestorTagged(tag: string, value: any): IProvideOnSyntax; - whenNoAncestorNamed(name: string): IProvideOnSyntax; - whenNoAncestorTagged(tag: string, value: any): IProvideOnSyntax; - whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; - whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; } export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void; export function makeProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => (target: any) => any; + (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (target: any) => any; export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => IProvideInWhenOnSyntax; + (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => interfaces.ProvideInWhenOnSyntax; } diff --git a/inversify-devtools/inversify-devtools-test.ts b/inversify-devtools/inversify-devtools-test.ts new file mode 100644 index 0000000000..3b99d7df93 --- /dev/null +++ b/inversify-devtools/inversify-devtools-test.ts @@ -0,0 +1,8 @@ +/// + +import render from "inversify-devtools"; +import { Kernel } from "inversify"; + +let connectKernel = render("root"); +let kernel = new Kernel(); +connectKernel(kernel); diff --git a/inversify-devtools/inversify-devtools.d.ts b/inversify-devtools/inversify-devtools.d.ts new file mode 100644 index 0000000000..841ae228c5 --- /dev/null +++ b/inversify-devtools/inversify-devtools.d.ts @@ -0,0 +1,15 @@ +// Type definitions for inversify-devtools 1.0.0 +// Project: https://github.com/inversify/inversify-devtools +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface ConnectKernel extends Function { + (kernel: inversify.interfaces.Kernel): void; +} + +declare module "inversify-devtools" { + let render: (container: string) => ConnectKernel; + export default render; +} diff --git a/inversify-express-utils/inversify-express-utils-tests.ts b/inversify-express-utils/inversify-express-utils-tests.ts index 1d421e397a..b082546448 100644 --- a/inversify-express-utils/inversify-express-utils-tests.ts +++ b/inversify-express-utils/inversify-express-utils-tests.ts @@ -1,21 +1,23 @@ /// -import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method } from "inversify-express-utils"; +import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method, TYPE } from "inversify-express-utils"; import * as express from "express"; import { Kernel } from "inversify"; +let kernel = new Kernel(); + module server { - let kernel = new Kernel(); + let server = new InversifyExpressServer(kernel); server - .setConfig((app) => { + .setConfig((app: express.Application) => { app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { console.log("hello world"); next(); }); }) - .setErrorConfig((app) => { + .setErrorConfig((app: express.Application) => { app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { console.error(err.stack); res.status(500).send("Something broke!"); @@ -55,6 +57,8 @@ module decorators { public testMethod() { return "METHOD:FOO"; } } + kernel.bind(TYPE.Controller).to(TestController); + function m1(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } function m2(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } function m3(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } diff --git a/inversify-express-utils/inversify-express-utils.d.ts b/inversify-express-utils/inversify-express-utils.d.ts index aa9a20d23c..f90b0cac88 100644 --- a/inversify-express-utils/inversify-express-utils.d.ts +++ b/inversify-express-utils/inversify-express-utils.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-alpha.4 +// Type definitions for inversify-express-utils 1.0.0 // Project: https://github.com/inversify/inversify-express-utils // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -11,40 +11,50 @@ declare module "inversify-express-utils" { import * as express from "express"; import * as inversify from "inversify"; - interface IInversifyExpressServerConstructor { - new(kernel: inversify.interfaces.Kernel): IInversifyExpressServer; + export namespace interfaces { + + export interface InversifyExpressServerConstructor { + new(kernel: inversify.interfaces.Kernel): InversifyExpressServer; + } + + export interface InversifyExpressServer { + setConfig(fn: ConfigFunction): InversifyExpressServer; + setErrorConfig(fn: ConfigFunction): InversifyExpressServer; + build(): express.Application; + } + + export interface ConfigFunction { + (app: express.Application): void; + } + + export interface HandlerDecoratorFactory { + (path: string, ...middleware: express.RequestHandler[]): HandlerDecorator; + } + + export interface HandlerDecorator { + (target: any, key: string, value: any): void; + } + } - interface IInversifyExpressServer { - setConfig(fn: IConfigFunction): IInversifyExpressServer; - setErrorConfig(fn: IConfigFunction): IInversifyExpressServer; - build(): express.Application; + export interface Controller {} + + interface ServiceIdentifiers { + Controller: Symbol; } - interface IConfigFunction { - (app: express.Application): void; - } - - interface IHandlerDecoratorFactory { - (path: string, ...middleware: express.RequestHandler[]): IHandlerDecorator; - } - - interface IHandlerDecorator { - (target: any, key: string, value: any): void; - } - - export interface IController {} - - export var InversifyExpressServer: IInversifyExpressServerConstructor; + export var InversifyExpressServer: interfaces.InversifyExpressServerConstructor; export var Controller: (path: string, ...middleware: express.RequestHandler[]) => (target: any) => void; - export var All: IHandlerDecoratorFactory; - export var Get: IHandlerDecoratorFactory; - export var Post: IHandlerDecoratorFactory; - export var Put: IHandlerDecoratorFactory; - export var Patch: IHandlerDecoratorFactory; - export var Head: IHandlerDecoratorFactory; - export var Delete: IHandlerDecoratorFactory; - export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => IHandlerDecorator; + export var All: interfaces.HandlerDecoratorFactory; + export var Get: interfaces.HandlerDecoratorFactory; + export var Post: interfaces.HandlerDecoratorFactory; + export var Put: interfaces.HandlerDecoratorFactory; + export var Patch: interfaces.HandlerDecoratorFactory; + export var Head: interfaces.HandlerDecoratorFactory; + export var Delete: interfaces.HandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => interfaces.HandlerDecorator; + export var TYPE: ServiceIdentifiers; + } diff --git a/inversify-inject-decorators/inversify-inject-decorators.d.ts b/inversify-inject-decorators/inversify-inject-decorators.d.ts index 032ed40cdd..34244c6d5e 100644 --- a/inversify-inject-decorators/inversify-inject-decorators.d.ts +++ b/inversify-inject-decorators/inversify-inject-decorators.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify-inject-decorators 1.0.0-beta.1 +// Type definitions for inversify-inject-decorators 1.0.0 // Project: https://github.com/inversify/inversify-inject-decorators // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,26 +7,25 @@ declare namespace inversifyInjectDecorators { - interface InjectDecorators { + export interface InjectDecorators { - lazyInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + lazyInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (proto: any, key: string) => void; - lazyInjectNamed: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), named: string) => + lazyInjectNamed: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, named: string) => (proto: any, key: string) => void; - lazyInjectTagged: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), key: string, value: any) => + lazyInjectTagged: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, key: string, value: any) => (proto: any, propertyName: string) => void; - lazyMultiInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + lazyMultiInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (proto: any, key: string) => void; } - export function getDecorators(kernel: inversify.interfaces.Kernel): InjectDecorators; - } declare module "inversify-inject-decorators" { - export default inversifyInjectDecorators.getDecorators; + let getDecorators: (kernel: inversify.interfaces.Kernel) => inversifyInjectDecorators.InjectDecorators; + export default getDecorators; } diff --git a/inversify-logger-middleware/inversify-logger-middleware-tests.ts b/inversify-logger-middleware/inversify-logger-middleware-tests.ts index c9c7d5c8a8..3b2119911a 100644 --- a/inversify-logger-middleware/inversify-logger-middleware-tests.ts +++ b/inversify-logger-middleware/inversify-logger-middleware-tests.ts @@ -4,23 +4,23 @@ declare var kernel: inversify.interfaces.Kernel; import { makeLoggerMiddleware, textSerializer } from "inversify-logger-middleware"; -interface ILoggerOutput { +interface LoggerOutput { entry: T; } -let makeStringRenderer = function (loggerOutput: ILoggerOutput) { - return function (entry: inversifyLoggerMiddleware.ILogEntry) { +let makeStringRenderer = function (loggerOutput: LoggerOutput) { + return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) { loggerOutput.entry = textSerializer(entry); }; }; -let makeObjRenderer = function (loggerOutput: ILoggerOutput) { - return function (entry: inversifyLoggerMiddleware.ILogEntry) { +let makeObjRenderer = function (loggerOutput: LoggerOutput) { + return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) { loggerOutput.entry = entry; }; }; -let options: inversifyLoggerMiddleware.ILoggerSettings = { +let options: inversifyLoggerMiddleware.interfaces.LoggerSettings = { request: { bindings: { activated: true, @@ -48,12 +48,12 @@ let options: inversifyLoggerMiddleware.ILoggerSettings = { let logger = makeLoggerMiddleware(); kernel.applyMiddleware(logger); -let loggerOutput1: ILoggerOutput = { entry: null }; +let loggerOutput1: LoggerOutput = { entry: null }; let stringRenderer1 = makeStringRenderer(loggerOutput1); let logger1 = makeLoggerMiddleware(options, stringRenderer1); kernel.applyMiddleware(logger1); -let loggerOutput2: ILoggerOutput = { entry: null }; +let loggerOutput2: LoggerOutput = { entry: null }; let objRenderer2 = makeObjRenderer(loggerOutput2); let logger2 = makeLoggerMiddleware(options, objRenderer2); kernel.applyMiddleware(logger2); diff --git a/inversify-logger-middleware/inversify-logger-middleware.d.ts b/inversify-logger-middleware/inversify-logger-middleware.d.ts index 3aa4ccca18..cd0037f432 100644 --- a/inversify-logger-middleware/inversify-logger-middleware.d.ts +++ b/inversify-logger-middleware/inversify-logger-middleware.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-beta.6 +// Type definitions for inversify-logger-middleware 1.0.0 // Project: https://github.com/inversify/inversify-logger-middleware // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,50 +7,61 @@ declare namespace inversifyLoggerMiddleware { - export interface ILoggerSettings { - request?: IRequestLoggerSettings; - time?: boolean; + export namespace interfaces { + + export interface LoggerSettings { + request?: RequestLoggerSettings; + time?: boolean; + } + + export interface RequestLoggerSettings { + serviceIdentifier?: boolean; + bindings?: BindingLoggerSettings; + target?: TargetLoggerSettings; + } + + export interface BindingLoggerSettings { + activated?: boolean; + serviceIdentifier?: boolean; + implementationType?: boolean; + factory?: boolean; + provider?: boolean; + constraint?: boolean; + onActivation?: boolean; + cache?: boolean; + dynamicValue?: boolean; + scope?: boolean; + type?: boolean; + } + + export interface TargetLoggerSettings { + serviceIdentifier?: boolean; + name?: boolean; + metadata?: boolean; + } + + export interface LogEntry { + error: boolean; + exception: any; + guid: string; + multiInject: boolean; + results: any[]; + rootRequest: inversify.interfaces.Request; + serviceIdentifier: any; + target: any; + time: string; + } + } - export interface IRequestLoggerSettings { - serviceIdentifier?: boolean; - bindings?: IBindingLoggerSettings; - target?: ITargetLoggerSettings; - } + export function makeLoggerMiddleware( + settings?: interfaces.LoggerSettings, + renderer?: (out: interfaces.LogEntry) => void + ): inversify.interfaces.Middleware; - export interface IBindingLoggerSettings { - activated?: boolean; - serviceIdentifier?: boolean; - implementationType?: boolean; - factory?: boolean; - provider?: boolean; - constraint?: boolean; - onActivation?: boolean; - cache?: boolean; - dynamicValue?: boolean; - scope?: boolean; - type?: boolean; - } - - export interface ITargetLoggerSettings { - serviceIdentifier?: boolean; - name?: boolean; - metadata?: boolean; - } - - export interface ILogEntry { - error: boolean; - exception: any; - multiInject: boolean; - results: any[]; - rootRequest: inversify.interfaces.Request; - serviceIdentifier: any; - target: any; - time: string; - } - - export function makeLoggerMiddleware(settings?: ILoggerSettings, renderer?: (out: ILogEntry) => void): inversify.interfaces.Middleware; - export function textSerializer(entry: ILogEntry): string; + export function textSerializer(entry: interfaces.LogEntry): string; + export function bindingTypeFormatter(type: number): string; + export function scopeFormatter(scope: number): string; } diff --git a/inversify-restify-utils/inversify-restify-utils-tests.ts b/inversify-restify-utils/inversify-restify-utils-tests.ts new file mode 100644 index 0000000000..5ff3ddc633 --- /dev/null +++ b/inversify-restify-utils/inversify-restify-utils-tests.ts @@ -0,0 +1,91 @@ +/// + +import { + InversifyRestifyServer, Controller, Get, Options, + Delete, Head, Put, Patch, Post, Method, TYPE +} from "inversify-restify-utils"; + +import * as restify from "restify"; +import { Kernel } from "inversify"; + +let kernel = new Kernel(); + +module server { + + let server = new InversifyRestifyServer(kernel); + + server + .setConfig((app: restify.Server) => { + app.use((req: restify.Request, res: restify.Response, next: restify.Next) => { + console.log("hello world"); + next(); + }); + }) + .build() + .listen(3000, "localhost"); +} + +module decorators { + + @Controller("/") + class TestController { + + @Get("/") + public testGet() { return "GET"; } + + @Options("/") + public testAll() { return "OPTIONS"; } + + @Delete("/") + public testDelete() { return "DELETE"; } + + @Head("/") + public testHead() { return "HEAD"; } + + @Put("/") + public testPut() { return "PUT"; } + + @Patch("/") + public testPatch() { return "PATCH"; } + + @Post("/") + public testPost() { return "POST"; } + + @Method("opts", "/") + public testMethod() { return "METHOD:OPTS"; } + } + + kernel.bind(TYPE.Controller).to(TestController); + + function m1(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + function m2(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + function m3(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + + @Controller("/", m1, m2, m3) + class TestMiddlewareController { + + @Get("/", m1, m2, m3) + public testGet() { return "GET"; } + + @Options("/", m1, m2, m3) + public testAll() { return "OPTIONS"; } + + @Delete("/", m1, m2, m3) + public testDelete() { return "DELETE"; } + + @Head("/", m1, m2, m3) + public testHead() { return "HEAD"; } + + @Put("/", m1, m2, m3) + public testPut() { return "PUT"; } + + @Patch("/", m1, m2, m3) + public testPatch() { return "PATCH"; } + + @Post("/", m1, m2, m3) + public testPost() { return "POST"; } + + @Method("opts", "/", m1, m2, m3) + public testMethod() { return "METHOD:OPTS"; } + } +} diff --git a/inversify-restify-utils/inversify-restify-utils.d.ts b/inversify-restify-utils/inversify-restify-utils.d.ts new file mode 100644 index 0000000000..4f2aab5510 --- /dev/null +++ b/inversify-restify-utils/inversify-restify-utils.d.ts @@ -0,0 +1,59 @@ +// Type definitions for inversify-restify-utils 1.0.0 +// Project: https://github.com/inversify/inversify-restify-utils +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "inversify-restify-utils" { + + import * as restify from "restify"; + import * as inversify from "inversify"; + + export namespace interfaces { + + export interface InversifyRestifyServerConstructor { + new(kernel: inversify.interfaces.Kernel): InversifyRestifyServer; + } + + export interface InversifyRestifyServer { + setConfig(fn: ConfigFunction): InversifyRestifyServer; + build(): restify.Server; + } + + export interface ConfigFunction { + (app: restify.Server): void; + } + + export interface HandlerDecoratorFactory { + (path: string, ...middleware: restify.RequestHandler[]): HandlerDecorator; + } + + export interface HandlerDecorator { + (target: any, key: string, value: any): void; + } + + } + + export interface Controller {} + + interface ServiceIdentifiers { + Controller: Symbol; + } + + export var InversifyRestifyServer: interfaces.InversifyRestifyServerConstructor; + + export var Controller: (path: string, ...middleware: restify.RequestHandler[]) => (target: any) => void; + + export var Options: interfaces.HandlerDecoratorFactory; + export var Get: interfaces.HandlerDecoratorFactory; + export var Post: interfaces.HandlerDecoratorFactory; + export var Put: interfaces.HandlerDecoratorFactory; + export var Patch: interfaces.HandlerDecoratorFactory; + export var Head: interfaces.HandlerDecoratorFactory; + export var Delete: interfaces.HandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: restify.RequestHandler[]) => interfaces.HandlerDecorator; + export var TYPE: ServiceIdentifiers; + +} diff --git a/inversify/inversify-global-tests.ts b/inversify/inversify-global-tests.ts index e2ead555d4..53b1a522bf 100644 --- a/inversify/inversify-global-tests.ts +++ b/inversify/inversify-global-tests.ts @@ -1,6 +1,8 @@ /// /// +import * as Proxy from "harmony-proxy"; + let injectable = inversify.injectable; let inject = inversify.inject; let tagged = inversify.tagged; @@ -13,10 +15,7 @@ let traverseAncerstors = inversify.traverseAncerstors; let taggedConstraint = inversify.taggedConstraint; let namedConstraint = inversify.namedConstraint; let typeConstraint = inversify.typeConstraint; -let makePropertyMultiInjectDecorator = inversify.makePropertyMultiInjectDecorator; -let makePropertyInjectTaggedDecorator = inversify.makePropertyInjectTaggedDecorator; -let makePropertyInjectNamedDecorator = inversify.makePropertyInjectNamedDecorator; -let makePropertyInjectDecorator = inversify.makePropertyInjectDecorator; +let unmanaged = inversify.unmanaged; module external_module_test { @@ -112,7 +111,7 @@ module external_module_test { // binding types kernel.bind("Weapon").to(Katana); kernel.bind("Weapon").toConstantValue(new Katana()); - kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); + kernel.bind("Weapon").toDynamicValue((context: inversify.interfaces.Context) => { return new Katana(); }); kernel.bind>("Weapon").toConstructor(Katana); @@ -145,6 +144,7 @@ module external_module_test { return new Proxy(katanaToBeInjected, handler); }); + @injectable() class Samurai implements Warrior { public katana: Weapon; @@ -161,8 +161,9 @@ module external_module_test { } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("Weapon").to(Katana).whenTargetTagged("canThrow", false); kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.getAllTagged("Weapon", "canThrow", false); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); @@ -200,6 +201,7 @@ module external_module_test { kernel.bind("Warrior").to(Samurai3); kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); + kernel.getAllNamed("Weapon", "weak"); @injectable() class Samurai4 implements Samurai { @@ -245,18 +247,18 @@ module external_module_test { // Constraint helpers kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); - kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("Ninja"); kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); @@ -341,103 +343,42 @@ module external_module_test { } -module property_injection { +module snapshot { let kernel = new Kernel(); - let TYPES = { Weapon: "Weapon" }; - - interface Weapon { - durability: number; - use(): void; - } - - @injectable() - class Sword implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - @injectable() - class WarHammer implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); - - class Warrior1 { - @propertyMultiInject(TYPES.Weapon) - public weapons: Weapon[]; - } - - let propertyInject = makePropertyInjectDecorator(kernel); - - interface Service { - count: number; - increment(): void; - } - - @injectable() - class SomeService implements Service { - public count: number; - public constructor() { - this.count = 0; - } - public increment() { - this.count = this.count + 1; - } - } - - class SomeWebComponent { - @propertyInject("Service") - private _service: Service; - public doSomething() { - let count = this._service.count; - this._service.increment(); - return count; - } - } - - let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); - - class Warrior2 { - - @propertyInjectNammed(TYPES.Weapon, "not-throwwable") - @named("not-throwwable") - public primaryWeapon: Weapon; - - @propertyInjectNammed(TYPES.Weapon, "throwwable") - @named("throwwable") - public secondaryWeapon: Weapon; - - } - - let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); - - class Warrior3 { - - @propertyInjectTagged(TYPES.Weapon, "throwwable", false) - @tagged("throwwable", false) - public primaryWeapon: Weapon; - - @propertyInjectTagged(TYPES.Weapon, "throwwable", true) - @tagged("throwwable", true) - public secondaryWeapon: Weapon; - - } - kernel.snapshot(); kernel.restore(); + @injectable() + class Test { } + + kernel.bind(Test).toSelf(); + kernel.bind(Test).toSelf().inSingletonScope(); +} + +module unmanaged_injection { + + let kernel = new Kernel(); + + const BaseId = "Base"; + + @injectable() + class Base { + public prop: string; + public constructor(@unmanaged() arg: string) { // injected by user + this.prop = arg; + } + } + + @injectable() + class Derived extends Base { + public constructor() { + super("unmanaged-injected-value"); // user injection + } + } + + kernel.bind(BaseId).to(Derived); + console.log(kernel.get(BaseId) instanceof Base); // true + } diff --git a/inversify/inversify-tests.ts b/inversify/inversify-tests.ts index 9b5de8fa0e..6b0d4a5f12 100644 --- a/inversify/inversify-tests.ts +++ b/inversify/inversify-tests.ts @@ -6,11 +6,7 @@ import { injectable, tagged, named, targetName, inject, multiInject, traverseAncerstors, taggedConstraint, namedConstraint, typeConstraint, - makePropertyMultiInjectDecorator, - makePropertyInjectTaggedDecorator, - makePropertyInjectNamedDecorator, - makePropertyInjectDecorator, - KernelModule, interfaces + KernelModule, interfaces, unmanaged } from "inversify"; import * as Proxy from "harmony-proxy"; @@ -109,7 +105,7 @@ module external_module_test { // binding types kernel.bind("Weapon").to(Katana); kernel.bind("Weapon").toConstantValue(new Katana()); - kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); + kernel.bind("Weapon").toDynamicValue((context: interfaces.Context) => { return new Katana(); }); kernel.bind>("Weapon").toConstructor(Katana); @@ -159,8 +155,9 @@ module external_module_test { } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("Weapon").to(Katana).whenTargetTagged("canThrow", false); kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.getAllTagged("Weapon", "canThrow", false); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); @@ -198,6 +195,7 @@ module external_module_test { kernel.bind("Warrior").to(Samurai3); kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); + kernel.getAllNamed("Weapon", "weak"); @injectable() class Samurai4 implements Samurai { @@ -243,18 +241,18 @@ module external_module_test { // Constraint helpers kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); - kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("Ninja"); kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); @@ -339,103 +337,42 @@ module external_module_test { } -module property_injection { +module snapshot { let kernel = new Kernel(); - let TYPES = { Weapon: "Weapon" }; - - interface Weapon { - durability: number; - use(): void; - } - - @injectable() - class Sword implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - @injectable() - class WarHammer implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); - - class Warrior1 { - @propertyMultiInject(TYPES.Weapon) - public weapons: Weapon[]; - } - - let propertyInject = makePropertyInjectDecorator(kernel); - - interface Service { - count: number; - increment(): void; - } - - @injectable() - class SomeService implements Service { - public count: number; - public constructor() { - this.count = 0; - } - public increment() { - this.count = this.count + 1; - } - } - - class SomeWebComponent { - @propertyInject("Service") - private _service: Service; - public doSomething() { - let count = this._service.count; - this._service.increment(); - return count; - } - } - - let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); - - class Warrior2 { - - @propertyInjectNammed(TYPES.Weapon, "not-throwwable") - @named("not-throwwable") - public primaryWeapon: Weapon; - - @propertyInjectNammed(TYPES.Weapon, "throwwable") - @named("throwwable") - public secondaryWeapon: Weapon; - - } - - let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); - - class Warrior3 { - - @propertyInjectTagged(TYPES.Weapon, "throwwable", false) - @tagged("throwwable", false) - public primaryWeapon: Weapon; - - @propertyInjectTagged(TYPES.Weapon, "throwwable", true) - @tagged("throwwable", true) - public secondaryWeapon: Weapon; - - } - kernel.snapshot(); kernel.restore(); + @injectable() + class Test { } + + kernel.bind(Test).toSelf(); + kernel.bind(Test).toSelf().inSingletonScope(); +} + +module unmanaged_injection { + + let kernel = new Kernel(); + + const BaseId = "Base"; + + @injectable() + class Base { + public prop: string; + public constructor(@unmanaged() arg: string) { // injected by user + this.prop = arg; + } + } + + @injectable() + class Derived extends Base { + public constructor() { + super("unmanaged-injected-value"); // user injection + } + } + + kernel.bind(BaseId).to(Derived); + console.log(kernel.get(BaseId) instanceof Base); // true + } diff --git a/inversify/inversify.d.ts b/inversify/inversify.d.ts index 0c77d9d82f..2f07d203e1 100644 --- a/inversify/inversify.d.ts +++ b/inversify/inversify.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 2.0.0-beta.9 +// Type definitions for inversify 2.0.0-rc.12 // Project: https://github.com/inversify/InversifyJS // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -45,7 +45,7 @@ declare namespace inversify { constraint: (request: Request) => boolean; onActivation: (context: Context, injectable: T) => T; cache: T; - dynamicValue: () => T; + dynamicValue: (context: Context) => T; scope: number; // BindingScope type: number; // BindingType } @@ -135,6 +135,7 @@ declare namespace inversify { export interface Target { guid: string; serviceIdentifier: ServiceIdentifier; + type: number; // TargetType name: QueryableString; metadata: Array; hasTag(key: string): boolean; @@ -152,6 +153,7 @@ declare namespace inversify { export interface Kernel { guid: string; + parent: Kernel; bind(serviceIdentifier: ServiceIdentifier): BindingToSyntax; unbind(serviceIdentifier: ServiceIdentifier): void; unbindAll(): void; @@ -160,6 +162,8 @@ declare namespace inversify { getNamed(serviceIdentifier: ServiceIdentifier, named: string): T; getTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T; getAll(serviceIdentifier: ServiceIdentifier): T[]; + getAllNamed(serviceIdentifier: ServiceIdentifier, named: string): T[]; + getAllTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T[]; load(...modules: KernelModule[]): void; unload(...modules: KernelModule[]): void; applyMiddleware(...middleware: Middleware[]): void; @@ -197,10 +201,12 @@ declare namespace inversify { export interface KeyValuePair { serviceIdentifier: ServiceIdentifier; value: Array; + guid: string; } export interface BindingInSyntax { inSingletonScope(): BindingWhenOnSyntax; + inTransientScope(): BindingWhenOnSyntax; } export interface BindingInWhenOnSyntax extends BindingInSyntax, BindingWhenOnSyntax {} @@ -211,8 +217,9 @@ declare namespace inversify { export interface BindingToSyntax { to(constructor: { new(...args: any[]): T; }): BindingInWhenOnSyntax; + toSelf(): BindingInWhenOnSyntax; toConstantValue(value: T): BindingWhenOnSyntax; - toDynamicValue(func: () => T): BindingWhenOnSyntax; + toDynamicValue(func: (context: Context) => T): BindingWhenOnSyntax; toConstructor(constructor: Newable): BindingWhenOnSyntax; toFactory(factory: FactoryCreator): BindingWhenOnSyntax; toFunction(func: T): BindingWhenOnSyntax; @@ -248,30 +255,19 @@ declare namespace inversify { export function tagged(metadataKey: string, metadataValue: any): (target: any, targetKey: string, index?: number) => any; export function named(name: string): (target: any, targetKey: string, index?: number) => any; export function targetName(name: string): (target: any, targetKey: string, index: number) => any; + export function unmanaged(): (target: any, targetKey: string, index: number) => any; export function inject(serviceIdentifier: interfaces.ServiceIdentifier): (target: any, targetKey: string, index?: number) => any; + export function guid(): string; export function multiInject( serviceIdentifier: interfaces.ServiceIdentifier ): (target: any, targetKey: string, index?: number) => any; - export function makePropertyInjectDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - - export function makePropertyInjectNamedDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable), named: string) => (proto: any, key: string) => void; - - export function makePropertyInjectTaggedDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable), key: string, value: any) => (proto: any, propertyName: string) => void; - - export function makePropertyMultiInjectDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - // constraint helpers export var traverseAncerstors: (request: interfaces.Request, constraint: (request: interfaces.Request) => boolean) => boolean; export var taggedConstraint: (tag: string) => (value: any) => (request: interfaces.Request) => boolean; export var namedConstraint: (value: any) => (request: interfaces.Request) => boolean; export var typeConstraint: (type: (Function|string)) => (request: interfaces.Request) => boolean; - } declare module "inversify" { diff --git a/ionic/ionic-tests.ts b/ionic/ionic-tests.ts index d8c98ae25f..140d102a8c 100644 --- a/ionic/ionic-tests.ts +++ b/ionic/ionic-tests.ts @@ -176,6 +176,7 @@ class IonicTestController { var currentStateName: string = this.$ionicHistory.currentStateName(); this.$ionicHistory.goBack(5); + this.$ionicHistory.removeBackView(); this.$ionicHistory.clearHistory(); this.$ionicHistory.clearCache().then(() => console.log("done clearing cache!")); this.$ionicHistory.nextViewOptions({ diff --git a/ionic/ionic.d.ts b/ionic/ionic.d.ts index fae9cdbf63..1df593037b 100644 --- a/ionic/ionic.d.ts +++ b/ionic/ionic.d.ts @@ -213,6 +213,7 @@ declare namespace ionic { currentStateName(): string; goBack(backCount?: number): void; + removeBackView(): void; clearHistory(): void; clearCache(): angular.IPromise; nextViewOptions(options: IonicHistoryNextViewOptions): void; diff --git a/ioredis/ioredis.d.ts b/ioredis/ioredis.d.ts index 983ed39f10..60eccd0272 100644 --- a/ioredis/ioredis.d.ts +++ b/ioredis/ioredis.d.ts @@ -197,6 +197,8 @@ declare module IORedis { hmget(...args: any[]): any; hincrby(args: any[], callback?: ResCallbackT): any; hincrby(...args: any[]): any; + hincrbyfloat(args: any[], callback?: ResCallbackT): any; + hincrbyfloat(...args: any[]): any; hdel(args: any[], callback?: ResCallbackT): any; hdel(...args: any[]): any; hlen(args: any[], callback?: ResCallbackT): any; @@ -478,6 +480,8 @@ declare module IORedis { hmget(...args: any[]): Pipeline; hincrby(args: any[], callback?: ResCallbackT): Pipeline; hincrby(...args: any[]): Pipeline; + hincrbyfloat(args: any[], callback?: ResCallbackT): Pipeline; + hincrbyfloat(...args: any[]): Pipeline; hdel(args: any[], callback?: ResCallbackT): Pipeline; hdel(...args: any[]): Pipeline; hlen(args: any[], callback?: ResCallbackT): Pipeline; diff --git a/is-plain-object/is-plain-object-tests.ts b/is-plain-object/is-plain-object-tests.ts new file mode 100644 index 0000000000..eb57b12434 --- /dev/null +++ b/is-plain-object/is-plain-object-tests.ts @@ -0,0 +1,25 @@ +/// + +import * as isPlainObject from 'is-plain-object'; + +isPlainObject(Object.create({})); +//=> true +isPlainObject(Object.create(Object.prototype)); +//=> true +isPlainObject({foo: 'bar'}); +//=> true +isPlainObject({}); + +isPlainObject(1); +//=> false +isPlainObject(['foo', 'bar']); +//=> false +isPlainObject([]); +//=> false +class Foo {} +isPlainObject(new Foo); +//=> false +isPlainObject(null); +//=> false +isPlainObject(Object.create(null)); +//=> false \ No newline at end of file diff --git a/is-plain-object/is-plain-object.d.ts b/is-plain-object/is-plain-object.d.ts new file mode 100644 index 0000000000..47d277f186 --- /dev/null +++ b/is-plain-object/is-plain-object.d.ts @@ -0,0 +1,10 @@ +// Type definitions for is-plain-object +// Project: https://github.com/jonschlinkert/is-plain-object +// Definitions by: Kevin Zeng +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "is-plain-object" { + namespace isPlainObject {} + function isPlainObject(obj: any): boolean; + export = isPlainObject; +} \ No newline at end of file diff --git a/isomorphic-fetch/isomorphic-fetch-tests.ts b/isomorphic-fetch/isomorphic-fetch-tests.ts index ddf11f84fe..fefabf2080 100644 --- a/isomorphic-fetch/isomorphic-fetch-tests.ts +++ b/isomorphic-fetch/isomorphic-fetch-tests.ts @@ -1,4 +1,5 @@ /// +/// import fetchImportedViaCommonJS = require('isomorphic-fetch'); import * as fetchImportedViaES6Module from 'isomorphic-fetch'; diff --git a/isomorphic-fetch/isomorphic-fetch.d.ts b/isomorphic-fetch/isomorphic-fetch.d.ts index 19754db0f1..41b63970b3 100644 --- a/isomorphic-fetch/isomorphic-fetch.d.ts +++ b/isomorphic-fetch/isomorphic-fetch.d.ts @@ -3,48 +3,53 @@ // Definitions by: Todd Lucas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare enum RequestContext { - "audio", "beacon", "cspreport", "download", "embed", "eventsource", - "favicon", "fetch", "font", "form", "frame", "hyperlink", "iframe", - "image", "imageset", "import", "internal", "location", "manifest", - "object", "ping", "plugin", "prefetch", "script", "serviceworker", - "sharedworker", "subresource", "style", "track", "video", "worker", - "xmlhttprequest", "xslt" -} -declare enum RequestMode { "same-origin", "no-cors", "cors" } -declare enum RequestCredentials { "omit", "same-origin", "include" } -declare enum RequestCache { - "default", "no-store", "reload", "no-cache", "force-cache", - "only-if-cached" -} -declare enum ResponseType { "basic", "cors", "default", "error", "opaque" } +type RequestType = "" | "audio" | "font" | "image" | "script" | "style" | + "track" | "video"; +type RequestDestination = "" | "document" | "embed" | "font" | "image" | + "manifest" | "media" | "object" | "report" | "script" | "serviceworker" | + "sharedworker" | "style" | "worker" | "xslt"; +type RequestMode = "navigate" | "same-origin" | "no-cors" | "cors"; +type RequestCredentials = "omit" | "same-origin" | "include"; +type RequestCache = + "default" | "no-store" | "reload" | "no-cache" | "force-cache" | + "only-if-cached"; +type RequestRedirect = "follow" | "error" | "manual"; -declare type HeaderInit = Headers | Array; -declare type BodyInit = ArrayBuffer | ArrayBufferView | Blob | FormData | string; -declare type RequestInfo = Request | string; +type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | + "opaqueredirect"; -interface RequestInit { - method?: string; - headers?: HeaderInit | { [index: string]: string }; - body?: BodyInit; - mode?: string | RequestMode; - credentials?: string | RequestCredentials; - cache?: string | RequestCache; -} +type ReferrerPolicy = "" | "no-referrer" | "no-referrer-when-downgrade" | + "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | + "strict-origin-when-cross-origin" | "unsafe-url"; interface IHeaders { - get(name: string): string; - getAll(name: string): Array; - has(name: string): boolean; -} - -declare class Headers implements IHeaders { append(name: string, value: string): void; - delete(name: string):void; + delete(name: string): void; get(name: string): string; getAll(name: string): Array; has(name: string): boolean; set(name: string, value: string): void; + + // TODO: iterable; + forEach(callback: (value: string, index: number, headers: IHeaders) => void, thisArg?: any): void; + // NOTE: The following are supported by whatwg-fetch but not node-fetch. + // entries(): IterableIterator<[string, string]>; + // keys(): IterableIterator; + // values(): IterableIterator; +} + +type HeadersInit = Headers | Array | { [index: string]: string }; + +declare class Headers implements IHeaders { + constructor(init?: HeadersInit); + append(name: string, value: string): void; + delete(name: string): void; + get(name: string): string; + getAll(name: string): Array; + has(name: string): boolean; + set(name: string, value: string): void; + + forEach(callback: (value: string, index: number, headers: IHeaders) => void, thisArg?: any): void; } interface IBody { @@ -70,49 +75,109 @@ declare class Body implements IBody { interface IRequest extends IBody { method: string; url: string; - headers: Headers; - context: string | RequestContext; - referrer: string; - mode: string | RequestMode; - credentials: string | RequestCredentials; - cache: string | RequestCache; + headers: IHeaders; + + type: RequestType; + destination: RequestDestination; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + redirect?: RequestRedirect; + integrity?: string; + + clone(): IRequest; } +type BodyInit = Blob | ArrayBufferView | ArrayBuffer | FormData /* | URLSearchParams */ | string; + +interface RequestInit { + method?: string; + headers?: HeadersInit; + body?: BodyInit; + referrer?: string; + referrerPolicy?: ReferrerPolicy; + mode?: RequestMode; + credentials?: RequestCredentials; + cache?: RequestCache; + redirect?: RequestRedirect; + integrity?: string; + window?: any; // can only be set to null +} + +type RequestInfo = IRequest | string; + declare class Request extends Body implements IRequest { - constructor(input: string | Request, init?: RequestInit); + constructor(input: RequestInfo, init?: RequestInit); + method: string; url: string; - headers: Headers; - context: string | RequestContext; + headers: IHeaders; + + type: RequestType + destination: RequestDestination; referrer: string; - mode: string | RequestMode; - credentials: string | RequestCredentials; - cache: string | RequestCache; + referrerPolicy: ReferrerPolicy; + mode: RequestMode; + credentials: RequestCredentials; + cache: RequestCache; + redirect: RequestRedirect; + integrity: string; + + clone(): IRequest; } interface IResponse extends IBody { + type: ResponseType; + url: string; + redirected: boolean; status: number; statusText: string; ok: boolean; headers: IHeaders; - type: string | ResponseType; - size: number; - timeout: number; - redirect(url: string, status: number): IResponse; - error(): IResponse; + // size: number; + // timeout: number; + body: any; + trailer: Promise; + clone(): IResponse; } -interface IFetchStatic { - Promise: any; - Headers: IHeaders - Request: IRequest; - Response: IResponse; - (url: string | IRequest, init?: RequestInit): Promise; +type ResponseBodyInit = BodyInit; + +interface ResponseInit { + status?: number; + statusText?: string; + headers?: HeadersInit; } -declare var fetch: IFetchStatic; +declare class Response extends Body implements IResponse { + constructor(body?: ResponseBodyInit, init?: ResponseInit); + + static redirect(url: string, status?: number): IResponse; + static error(): IResponse; + + type: ResponseType + + url: string; + redirected: boolean; + status: number; + statusText: string; + ok: boolean; + headers: IHeaders; + body: any; + trailer: Promise; + + clone(): IResponse; +} + +interface Window { + fetch(url: RequestInfo, init?: RequestInit): Promise; +} + +declare var fetch: typeof window.fetch; declare module "isomorphic-fetch" { export = fetch; diff --git a/jake/jake.d.ts b/jake/jake.d.ts index 3174a7b94c..5766b64093 100644 --- a/jake/jake.d.ts +++ b/jake/jake.d.ts @@ -207,7 +207,7 @@ declare namespace jake{ * * @event complete */ - export class Task implements NodeJS.EventEmitter { + export class Task extends NodeJS.EventEmitter { /** * @name name The name of the Task * @param prereqs Prerequisites to be run before this task diff --git a/jasmine-node/jasmine-node.d.ts b/jasmine-node/jasmine-node.d.ts index f547f844f6..f535d8c3e3 100644 --- a/jasmine-node/jasmine-node.d.ts +++ b/jasmine-node/jasmine-node.d.ts @@ -7,6 +7,12 @@ declare function it(expectation:string, assertion:(done:(err?:any) => void) => void, timeout?:number):void; +declare namespace jasmine { + interface Env { + defaultTimeoutInterval: number; + } +} + declare module "jasmine-node" { interface ExecuteSpecsOptions { specFolders: string[], diff --git a/jest/jest.d.ts b/jest/jest.d.ts index 10949a6691..b2484dfcc5 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -44,6 +44,7 @@ declare namespace jest { interface Matchers { not: Matchers; toThrow(expected?: any): boolean; + toThrowError(expected?: any): boolean; toBe(expected: any): boolean; toEqual(expected: any): boolean; toBeFalsy(): boolean; diff --git a/joi/joi-tests.ts b/joi/joi-tests.ts index 37848203df..c75309b45e 100644 --- a/joi/joi-tests.ts +++ b/joi/joi-tests.ts @@ -752,6 +752,10 @@ schema = Joi.alternatives(schema, anySchema, boolSchema); // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- +schema = Joi.lazy(() => schema) + +// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- + Joi.validate(value, obj); Joi.validate(value, schema); Joi.validate(value, schema, validOpts); diff --git a/joi/joi.d.ts b/joi/joi.d.ts index 3ba51d7383..b827903f9b 100644 --- a/joi/joi.d.ts +++ b/joi/joi.d.ts @@ -816,6 +816,13 @@ declare module 'joi' { export function alternatives(): AlternativesSchema; export function alternatives(types: Schema[]): AlternativesSchema; export function alternatives(type1: Schema, type2: Schema, ...types: Schema[]): AlternativesSchema; + + /** + * Generates a placeholder schema for a schema that you would provide with the fn. + * Supports the same methods of the any() type. + * This is mostly useful for recursive schemas + */ + export function lazy(cb: () => Schema): Schema; /** * Validates a value using the given schema and options. diff --git a/jquery-mockjax/jquery-mockjax-tests.ts b/jquery-mockjax/jquery-mockjax-tests.ts index 6fae52eb07..36ebd7e64c 100644 --- a/jquery-mockjax/jquery-mockjax-tests.ts +++ b/jquery-mockjax/jquery-mockjax-tests.ts @@ -9,7 +9,7 @@ class Tests { run(): void { const self = this; - var t = QUnit.test; + let t = QUnit.test; QUnit.begin(() => { @@ -36,7 +36,7 @@ class Tests { responseText: 'Hello Word' }); - var xhr = $.ajax({ + let xhr = $.ajax({ url: '/xmlhttprequest', complete: () => { } }); @@ -67,7 +67,7 @@ class Tests { }); t('Intercept asynchronized proxy calls', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/proxy', proxy: 'test_proxy.json' @@ -85,7 +85,7 @@ class Tests { }); t('Intercept and proxy (sub-ajax request)', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/proxy', @@ -104,7 +104,7 @@ class Tests { }); t('Proxy type specification', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/proxy', @@ -124,7 +124,7 @@ class Tests { }); t('Support 1.5 $.ajax(url, settings) signature.', (assert) => { - var done = assert.async(); + let done = assert.async(); $.mockjax({ url: '/resource', @@ -141,9 +141,9 @@ class Tests { }); t('Dynamic response callback', (assert) => { - var done = assert.async(); + let done = assert.async(); - var settings: MockJaxSettings = { + let settings: MockJaxSettings = { url: '/response-callback', response: (settings) => { settings.responseText = settings.data.response + ' 2'; @@ -165,8 +165,36 @@ class Tests { } }); }); + + t('Asyncronous response callback', (assert) => { + let done = assert.async(); + + let settings: MockJaxSettings = { + url: '/async-response-callback', + response: (settings, completed) => { + setTimeout(() => { + settings.responseText = settings.data.response + ' 3'; + completed(); + }, 10); + } + }; + + $.mockjax(settings); + + $.ajax({ + url: '/async-response-callback', + dataType: 'text', + data: { + response: 'Hello world' + }, + error: self._noErrorCallbackExpected, + complete: (xhr) => { + assert.equal(xhr.responseText, 'Hello world 3', 'Response Text matches'); + done(); + } + }); + }); } } -var tests = new Tests(); -tests.run(); +new Tests().run(); diff --git a/jquery-mockjax/jquery-mockjax.d.ts b/jquery-mockjax/jquery-mockjax.d.ts index 7505a30e6f..c054f33317 100644 --- a/jquery-mockjax/jquery-mockjax.d.ts +++ b/jquery-mockjax/jquery-mockjax.d.ts @@ -22,7 +22,7 @@ interface MockJaxSettings { isTimeout?: boolean; dataType?: string; contentType?: string; - response?: (settings: any) => void; + response?: (settings: any, done?: Function) => void; responseText?: string | Object; responseXml?: string; proxy?: string; diff --git a/jquery/jquery.d.ts b/jquery/jquery.d.ts index 0f72c709cf..b08598cc53 100644 --- a/jquery/jquery.d.ts +++ b/jquery/jquery.d.ts @@ -2780,8 +2780,9 @@ interface JQuery { /** * Retrieve all the elements contained in the jQuery set, as an array. + * @name toArray */ - toArray(): any[]; + toArray(): HTMLElement[]; /** * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. @@ -2837,8 +2838,9 @@ interface JQuery { get(index: number): HTMLElement; /** * Retrieve the elements matched by the jQuery object. + * @alias toArray */ - get(): any[]; + get(): HTMLElement[]; /** * Search for a given element from among the matched elements. diff --git a/js-beautify/js-beautify-tests.ts b/js-beautify/js-beautify-tests.ts index bcd431c2bd..6bef16e042 100644 --- a/js-beautify/js-beautify-tests.ts +++ b/js-beautify/js-beautify-tests.ts @@ -1,7 +1,16 @@ /// -var simple: string = js_beautify("console.log('Hello world!');"); +let bCss = js_beautify.css("body{display:none;}"); +bCss = js_beautify.css_beautify("body{display:none;}"); +let bHtml = js_beautify.html("
"); +bHtml = js_beautify.html_beautify("
"); + +let optHtml = {}; +let optCss = {}; +let optjs = {}; + +var simple: string = js_beautify("console.log('Hello world!');"); var full: string = js_beautify( "console.log('Hello world!');", { diff --git a/js-beautify/js-beautify.d.ts b/js-beautify/js-beautify.d.ts index 16cbbed679..ea67ddbad2 100644 --- a/js-beautify/js-beautify.d.ts +++ b/js-beautify/js-beautify.d.ts @@ -1,10 +1,6 @@ // Type definitions for js_beautify // Project: https://github.com/beautify-web/js-beautify/ -// Definitions by: Josh Goldberg -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Type definitions for js_beautify -// Project: https://github.com/beautify-web/js-beautify/ -// Definitions by: Josh Goldberg +// Definitions by: Josh Goldberg , Hans Windhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface JsBeautifyOptions { @@ -17,7 +13,7 @@ interface JsBeautifyOptions { max_preserve_newlines?: number; jslint_happy?: boolean; space_after_anon_function?: boolean; - brace_style?: string; + brace_style?: 'collapse-preserve-inline'|'collapse'|'expand'|'end-expand'|'none'; keep_array_indentation?: boolean; keep_function_indentation?: boolean; space_before_conditional?: boolean; @@ -25,11 +21,54 @@ interface JsBeautifyOptions { eval_code?: boolean; unescape_strings?: boolean; wrap_line_length?: number; - wrap_attributes?: string; + wrap_attributes?: 'auto'|'force' ; wrap_attributes_indent_size?: number; end_with_newline?: boolean; } -declare var js_beautify: { - (js_source_text: string, options?: JsBeautifyOptions): string; -}; +interface HTMLBeautifyOptions { + indent_size?: number; + indent_char?: string; + indent_with_tabs?: boolean; + eol?: string; + end_with_newline?: boolean; + preserve_newlines?: boolean; + max_preserve_newlines?: number; + indent_inner_html?: boolean; + brace_style?: 'collapse-preserve-inline'|'collapse'|'expand'|'end-expand'|'none'; + indent_scripts?: boolean; + wrap_line_length?: number; + wrap_attributes?: 'auto'|'force' ; + wrap_attributes_indent_size?: number; + unformatted?: string; + extra_liners?: string; +} + +interface CSSBeautifyOptions { + indent_size?: number; + indent_char?: string; + indent_with_tabs?: boolean; + eol?: string; + end_with_newline?: boolean; + selector_separator_newline?: boolean; + newline_between_rules?: boolean; +} + +interface jsb{ + (js_source_text: string, options?: JsBeautifyOptions) : string ; + js:(js_source_text: string, options?: JsBeautifyOptions) => string ; + beautify_js:(js_source_text: string, options?: JsBeautifyOptions) => string ; + + css:(js_source_text: string, options?: CSSBeautifyOptions) => string ; + css_beautify:(js_source_text: string, options?: CSSBeautifyOptions) => string ; + + html:(js_source_text: string, options?: HTMLBeautifyOptions) => string ; + html_beautify:(js_source_text: string, options?: HTMLBeautifyOptions) => string ; +} + +declare var js_beautify:jsb; +declare module "js-beautify" +{ + export = js_beautify; +} + diff --git a/js-data-http/js-data-http-tests.ts b/js-data-http/js-data-http-tests.ts index 390e20aa9e..9f0c4c3169 100644 --- a/js-data-http/js-data-http-tests.ts +++ b/js-data-http/js-data-http-tests.ts @@ -1,9 +1,15 @@ +/// /// +import * as axios from 'axios'; + var adapter = new DSHttpAdapter(); var store = new JSData.DS(); store.registerAdapter('http', adapter, { default: true }); +adapter.defaults.basePath = '/api'; +adapter.http = axios; + var ADocument:JSData.DSResourceDefinition = store.defineResource('document'); ADocument.inject({ id: 5, author: 'John' }); diff --git a/js-data-http/js-data-http.d.ts b/js-data-http/js-data-http.d.ts index cde3b4a2e1..04d07f5a38 100644 --- a/js-data-http/js-data-http.d.ts +++ b/js-data-http/js-data-http.d.ts @@ -15,6 +15,8 @@ declare namespace JSData { forceTrailingSlash?: boolean; log?: boolean | ((message?:any, ...optionalParams:any[])=> void); error?: boolean | ((message?:any, ...optionalParams:any[])=> void); + basePath?: string; + verbsUseBasePath?: string; } interface DSHttpAdapterPromiseResolveType { @@ -28,6 +30,9 @@ declare namespace JSData { new(options?:DSHttpAdapterOptions):DSHttpAdapter; + defaults: DSHttpAdapterOptions; + http: any; + // DSHttpAdapter uses axios so options are axios config objects. HTTP(options?:Object):JSDataPromise; DEL(url:string, data?:Object, options?:Object):JSDataPromise; diff --git a/js-data/js-data-tests.ts b/js-data/js-data-tests.ts index 7c66952162..9bbbfdfd64 100644 --- a/js-data/js-data-tests.ts +++ b/js-data/js-data-tests.ts @@ -600,3 +600,5 @@ customActionResource.emit("DS.change", customActionResource, customActionResourc customActionResourceInstance.on("DS.change", myEvtHandler); customActionResourceInstance.off("DS.change", myEvtHandler); customActionResourceInstance.emit("DS.change", customActionResource, customActionResourceInstance); + +JSData.DSUtils.Promise = Promise; \ No newline at end of file diff --git a/js-data/js-data.d.ts b/js-data/js-data.d.ts index da87e81ccc..58bef671b1 100644 --- a/js-data/js-data.d.ts +++ b/js-data/js-data.d.ts @@ -57,7 +57,7 @@ declare namespace JSData { scopes?:Object; strategy?: string; upsert?: boolean; - useClass?: boolean; + useClass?: boolean | any; useFilter?: boolean; watchChanges?:boolean; } @@ -342,6 +342,7 @@ declare namespace JSData { declare var JSData:{ DS: JSData.DS; DSErrors: JSData.DSErrors; + DSUtils: any; }; //Support node require diff --git a/jsdom/jsdom.d.ts b/jsdom/jsdom.d.ts index c6ebde2ce3..2efebc059f 100644 --- a/jsdom/jsdom.d.ts +++ b/jsdom/jsdom.d.ts @@ -68,6 +68,7 @@ declare module "jsdom" { export function createCookieJar(): CookieJar; export function nodeLocation(node: Node): any; export function reconfigureWindow(window: Window, newProps: WindowProperties): void; + export function changeURL(window: Window, url: string): void; export function jQueryify(window: Window, jqueryUrl: string, callback: (window: Window, jquery: JQuery) => any): void; diff --git a/json-editor/json-editor.d.ts b/json-editor/json-editor.d.ts index cbb0c9c29c..280c17e70f 100644 --- a/json-editor/json-editor.d.ts +++ b/json-editor/json-editor.d.ts @@ -39,7 +39,7 @@ type JSONEditorOptions = { /** * The icon library to use for the editor. */ - iconlib?: boolean; + iconlib?: "bootstrap2" | "bootstrap3" | "foundation2" | "foundation3" | "jqueryui" | "fontawesome3" | "fontawesome4"; /** * If true, objects can only contain properties defined with the properties keyword. */ @@ -75,7 +75,7 @@ type JSONEditorOptions = { /** * The CSS theme to use. */ - theme?: string; + theme?: "barebones" | "html" | "bootstrap2" | "bootstrap3" | "foundation3" | "foundation4" | "foundation5" | "foundation6" | "jqueryui"; /** * If true, only required properties will be included by default. */ diff --git a/jsoneditor/jsoneditor-tests.ts b/jsoneditor/jsoneditor-tests.ts new file mode 100644 index 0000000000..99bbb51b92 --- /dev/null +++ b/jsoneditor/jsoneditor-tests.ts @@ -0,0 +1,50 @@ +/// + +import JSONEditor, {JSONEditorMode, JSONEditorNode, JSONEditorOptions} from 'jsoneditor'; + +let options: JSONEditorOptions; +options = { + ace: ace, + //ajv: Ajv({allErrors: true, verbose: true}) + onChange() {}, + onEditable(node: JSONEditorNode) { + return true; + }, + onError(error: Error) {}, + onModeChange(newMode: JSONEditorMode, oldMode: JSONEditorMode) {}, + escapeUnicode: false, + sortObjectKeys: true, + history: true, + mode: 'tree', + modes: ['tree', 'view', 'form', 'code', 'text'], + name: 'foo', + schema: {}, + search: false, + indentation: 2, + theme: 'default' +}; +options = { + onEditable(node: JSONEditorNode) { + return {field: true, value: false}; + } +}; + +let jsonEditor: JSONEditor; +jsonEditor = new JSONEditor(document.body); +jsonEditor = new JSONEditor(document.body, {}); +jsonEditor = new JSONEditor(document.body, options, {foo: 'bar'}); + +jsonEditor.collapseAll(); +jsonEditor.destroy(); +jsonEditor.expandAll(); +jsonEditor.focus(); +jsonEditor.set({foo: 'bar'}); +jsonEditor.setMode('text'); +jsonEditor.setName('foo'); +jsonEditor.setName(); +jsonEditor.setSchema({}); +jsonEditor.setText('{foo: 1}'); + +const json: any = jsonEditor.get(); +const name: string = jsonEditor.getName(); +const jsonString: string = jsonEditor.getText(); diff --git a/jsoneditor/jsoneditor.d.ts b/jsoneditor/jsoneditor.d.ts new file mode 100644 index 0000000000..ea68a751a4 --- /dev/null +++ b/jsoneditor/jsoneditor.d.ts @@ -0,0 +1,52 @@ +// Type definitions for jsoneditor v5.5.7 +// Project: https://github.com/josdejong/jsoneditor +// Definitions by: Alejandro Sánchez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'jsoneditor' { + export interface JSONEditorNode { + field: string; + value: string; + path: Array; + } + + export type JSONEditorMode = 'tree' | 'view' | 'form' | 'code' | 'text'; + + export interface JSONEditorOptions { + ace?: AceAjax.Ace; + ajv?: any; // Any for now, since ajv typings aren't A-Ok + onChange?: () => void; + onEditable?: (node: JSONEditorNode) => boolean | {field: boolean, value: boolean}; + onError?: (error: Error) => void; + onModeChange?: (newMode: JSONEditorMode, oldMode: JSONEditorMode) => void; + escapeUnicode?: boolean; + sortObjectKeys?: boolean; + history?: boolean; + mode?: JSONEditorMode; + modes?: Array; + name?: string; + schema?: Object; + search?: boolean; + indentation?: number; + theme?: string; + } + + export default class JSONEditor { + constructor(container: HTMLElement, options?: JSONEditorOptions, json?: Object); + collapseAll(): void; + destroy(): void; + expandAll(): void; + focus(): void; + set(json: Object): void; + setMode(mode: JSONEditorMode): void; + setName(name?: string): void; + setSchema(schema: Object): void; + setText(jsonString: string): void; + get(): any; + getMode(): JSONEditorMode; + getName(): string; + getText(): string; + } +} diff --git a/jsts/jsts-tests.ts b/jsts/jsts-tests.ts index 3b37d0f185..e9c00fd52a 100644 --- a/jsts/jsts-tests.ts +++ b/jsts/jsts-tests.ts @@ -1,4 +1,7 @@ /// + +import * as jsts from 'jsts'; + var str: string; var n: number; var bool: boolean; @@ -142,4 +145,4 @@ obj = gjw.write(g); var wr: jsts.io.WKTReader = new jsts.io.WKTReader(); g = wr.read(str); -wr.reducePrecision(g); \ No newline at end of file +wr.reducePrecision(g); diff --git a/jsts/jsts.d.ts b/jsts/jsts.d.ts index 909dbbf7a1..f06b5c7f51 100644 --- a/jsts/jsts.d.ts +++ b/jsts/jsts.d.ts @@ -1664,3 +1664,7 @@ declare namespace jsts { } } } + +declare module "jsts" { + export = jsts; +} diff --git a/jwt-client/jwt-client-tests.ts b/jwt-client/jwt-client-tests.ts new file mode 100644 index 0000000000..c686800078 --- /dev/null +++ b/jwt-client/jwt-client-tests.ts @@ -0,0 +1,6 @@ +/// + +import * as JWT from "jwt-client"; +var token = 'eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0'; +var session = JWT.read(token); +console.log('session is', session); diff --git a/jwt-client/jwt-client.d.ts b/jwt-client/jwt-client.d.ts new file mode 100644 index 0000000000..4f6ca95d88 --- /dev/null +++ b/jwt-client/jwt-client.d.ts @@ -0,0 +1,42 @@ +// Type definitions for jwt-client v0.2.1 +// Project: https://github.com/pauldijou/jwt-client +// Definitions by: Timoteo Ponce +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "jwt-client"{ + + interface JWTHeader{ + typ: string; + alg: string; + } + + interface JWTObject{ + header: JWTHeader; + claim: any; + signature: string; + } + + /** + * Read a string value (normally an HTTP header) + * from JSON Web Token to an Object + */ + function read(header:string):JWTObject; + + /** + * Given a JWT object, stringify it back to + * its JWT representation. + */ + function write(value:JWTObject):string; + + function keep(value:JWTObject, key?:any, storate?: any):void; + + function remember():void; + + function forget():void; + + function get():string; + + function validate(value:JWTObject, issuer?:any, audience?: any):boolean; +} + diff --git a/karma-fixture/karma-fixture-tests.ts b/karma-fixture/karma-fixture-tests.ts new file mode 100644 index 0000000000..b3a1d8e51c --- /dev/null +++ b/karma-fixture/karma-fixture-tests.ts @@ -0,0 +1,10 @@ +/// + +fixture.setBase('fixtures/base/path'); +fixture.load('test1.html', 'test1.json', false); +fixture.load('test1.html', 'test2.html', 'test1.json'); +fixture.set('', true); +fixture.set('', ''); +fixture.cleanup(); +fixture.el.firstChild; +JSON.stringify(fixture.json[0]); diff --git a/karma-fixture/karma-fixture.d.ts b/karma-fixture/karma-fixture.d.ts new file mode 100644 index 0000000000..bc89b1b723 --- /dev/null +++ b/karma-fixture/karma-fixture.d.ts @@ -0,0 +1,27 @@ +// Type definitions for karma-fixture 0.2.6 +// Project: https://github.com/billtrik/karma-fixture +// Definitions by: Ezekiel Victor +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace fixture { + export var el: HTMLElement; + export var json: any[]; + + export function load(...files: string[]): any; + export function load(file1: string, append?: boolean): any; + export function load(file1: string, file2: string, append?: boolean): any; + export function load(file1: string, file2: string, file3: string, append?: boolean): any; + export function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any; + export function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any; + + export function set(...htmlStrs: string[]): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[]; + + export function cleanup(): void; + + export function setBase(fixtureBasePath: string): void; +} diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index d90c5f2356..e8f02f1776 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -89,40 +89,10 @@ declare namespace kendo { }; }; - var cultures: {[culture: string] : { - name?: string; - calendar?: { - AM: string[]; - PM: string[]; - days: { - names: string[]; - namesAbbr: string[]; - namesShort: string[]; - firstDay: number; - }; - months: { - names: string[]; - namesAbbr: string[]; - }; - patterns: { - D: string; - F: string; - G: string; - M: string; - T: string; - Y: string; - d: string; - g: string; - m: string; - s: string; - t: string; - u: string; - y: string; - }; - twoDigitYearMax: number; - }; - calendars?: { - standard: { + var cultures: { + [culture: string]: { + name?: string; + calendar?: { AM: string[]; PM: string[]; days: { @@ -152,25 +122,57 @@ declare namespace kendo { }; twoDigitYearMax: number; }; - }; - numberFormat?: { - currency: { + calendars?: { + standard: { + AM: string[]; + PM: string[]; + days: { + names: string[]; + namesAbbr: string[]; + namesShort: string[]; + firstDay: number; + }; + months: { + names: string[]; + namesAbbr: string[]; + }; + patterns: { + D: string; + F: string; + G: string; + M: string; + T: string; + Y: string; + d: string; + g: string; + m: string; + s: string; + t: string; + u: string; + y: string; + }; + twoDigitYearMax: number; + }; + }; + numberFormat?: { + currency: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; decimals: number; groupSize: number[]; pattern: string[]; - symbol: string; + percent: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; }; - decimals: number; - groupSize: number[]; - pattern: string[]; - percent: { - decimals: number; - groupSize: number[]; - pattern: string[]; - symbol: string; - }; - }; - }}; + } + }; function format(format: string, ...values: any[]): string; @@ -488,8 +490,8 @@ declare namespace kendo.data { change(e: Object): void; start(source: kendo.Observable): void; stop(source: kendo.Observable): void; - get (): any; - set (value: any): void; + get(): any; + set(value: any): void; destroy(): void; } @@ -500,7 +502,7 @@ declare namespace kendo.data { } class EventBinding extends Binding { - get (): void; + get(): void; } class TemplateBinding extends Binding { @@ -531,7 +533,7 @@ declare namespace kendo.data { interface BinderOptions { } - class ObservableObject extends Observable{ + class ObservableObject extends Observable { constructor(value?: any); uid: string; init(value?: any): void; @@ -571,6 +573,7 @@ declare namespace kendo.data { isAllDay?: boolean; id?: any; start?: Date; + taskId?: number; startTimezone?: string; recurrenceId?: any; recurrenceRule?: string; @@ -583,7 +586,7 @@ declare namespace kendo.data { static fields: DataSourceSchemaModelFields; constructor(data?: SchedulerEventData); - + taskId: number; description: string; end: Date; endTimezone: string; @@ -2653,7 +2656,7 @@ declare namespace kendo.ui { separator?: string; suggest?: boolean; headerTemplate?: string|Function; - template?: string|Function; + template?: string | Function; valuePrimitive?: boolean; virtual?: boolean|AutoCompleteVirtual; change?(e: AutoCompleteChangeEvent): void; @@ -4471,6 +4474,7 @@ declare namespace kendo.ui { width?: string|number; values?: any; menu?: boolean; + type?: any; } interface GridEditable { @@ -5890,6 +5894,7 @@ declare namespace kendo.ui { destroy(): void; enable(enable: boolean): void; value(): any; + values(): any; value(selectionStart: number, selectionEnd: number): void; resize(): void; @@ -8834,6 +8839,7 @@ declare namespace kendo.dataviz.ui { type?: string; visible?: boolean; weekStartDay?: number; + axisCrossingValues?: number[]; notes?: ChartCategoryAxisItemNotes; } @@ -10599,6 +10605,7 @@ declare namespace kendo.dataviz.ui { autoBind?: boolean; axisDefaults?: ChartAxisDefaults; categoryAxis?: ChartCategoryAxisItem[]; + valueAxis?: ChartValueAxisItem[]; chartArea?: ChartChartArea; dataSource?: any|any|kendo.data.DataSource; legend?: ChartLegend; @@ -10614,7 +10621,6 @@ declare namespace kendo.dataviz.ui { title?: ChartTitle; tooltip?: ChartTooltip; transitions?: boolean; - valueAxis?: ChartValueAxisItem[]; xAxis?: ChartXAxisItem[]; yAxis?: ChartYAxisItem[]; zoomable?: boolean|ChartZoomable; diff --git a/knex/knex.d.ts b/knex/knex.d.ts index 23dc58af82..ec6403ed2c 100644 --- a/knex/knex.d.ts +++ b/knex/knex.d.ts @@ -12,7 +12,7 @@ declare module "knex" { type Callback = Function; type Client = Function; - type Value = string|number|boolean|Date|Array|Array|Array|Array; + type Value = string|number|boolean|Date|Array|Array|Array|Array|Buffer; type ColumnName = string|Knex.Raw|Knex.QueryBuilder; type TableName = string|Knex.Raw|Knex.QueryBuilder; diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 6321cff0a5..f0e9fe023f 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -61,8 +61,10 @@ interface KnockoutSubscription { } interface KnockoutSubscribable extends KnockoutSubscribableFunctions { - subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription; subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable; getSubscriptionsCount(): number; } @@ -91,6 +93,11 @@ interface KnockoutObservableArrayStatic { } interface KnockoutObservableArray extends KnockoutObservable, KnockoutObservableArrayFunctions { + subscribe(callback: (newValue: KnockoutArrayChange[]) => void, target: any, event: "arrayChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription; + subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray; } @@ -325,7 +332,7 @@ interface KnockoutUtils { } interface KnockoutArrayChange { - status: string; + status: "added" | "deleted"; value: T; index: number; moved?: number; diff --git a/knockout/knockoutamd-tests.ts b/knockout/knockoutamd-tests.ts index c874c6208b..9ee6658335 100644 --- a/knockout/knockoutamd-tests.ts +++ b/knockout/knockoutamd-tests.ts @@ -1,6 +1,6 @@ /// -import ko = require("knockout"); +import ko = require("knockout"); var myArray = ko.observableArray([1, 2, 3]); diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 8da6c12950..122617b180 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -680,3 +680,38 @@ function test_tasks() { setTimeout(callback, 0); }; } + +function observableEventsTests() { + var observable = ko.observable(1); + observable.subscribe(value => { + var num: number = value; + }); + observable.subscribe(value => { + var num: number = value; + }, null, "change"); + observable.subscribe(value => { + var num: number = value; + }, null, "beforeChange"); +} + +function observableArrayEventsTests() { + var observableArray = ko.observableArray([1, 2, 3, 4]); + observableArray.subscribe(array => { + var arr: number[] = array; + }); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "change"); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "beforeChange"); + var count = 0; + observableArray.subscribe(changes => { + changes.forEach(change => { + if (change.status == "added") + count++; + else if (change.status == "deleted") + count--; + }); + }, null, "arrayChange"); +} \ No newline at end of file diff --git a/koa-compress/koa-compress.d.ts b/koa-compress/koa-compress.d.ts index c4cd2af582..49a0bb5f1b 100644 --- a/koa-compress/koa-compress.d.ts +++ b/koa-compress/koa-compress.d.ts @@ -37,5 +37,6 @@ declare module "koa-compress" { */ function compress(options?: CompressOptions): { (ctx: Koa.Context, next?: () => any): any }; + namespace compress {} export = compress; } diff --git a/koa-favicon/koa-favicon.d.ts b/koa-favicon/koa-favicon.d.ts index 618683fc76..e09c685173 100644 --- a/koa-favicon/koa-favicon.d.ts +++ b/koa-favicon/koa-favicon.d.ts @@ -31,5 +31,6 @@ declare module "koa-favicon" { }): { (ctx: Koa.Context, next?: () => any): any }; + namespace favicon {} export = favicon; } diff --git a/koa-json-error/koa-json-error-tests.ts b/koa-json-error/koa-json-error-tests.ts new file mode 100644 index 0000000000..37aae696b0 --- /dev/null +++ b/koa-json-error/koa-json-error-tests.ts @@ -0,0 +1,13 @@ +/// +/// +/// + +import * as Koa from "koa"; +import * as error from "koa-json-error"; +import { assign } from "lodash"; + +const app = new Koa(); + +app.use(error({ + preFormat: err => assign({}, err) +})); \ No newline at end of file diff --git a/koa-json-error/koa-json-error.d.ts b/koa-json-error/koa-json-error.d.ts new file mode 100644 index 0000000000..491ead463e --- /dev/null +++ b/koa-json-error/koa-json-error.d.ts @@ -0,0 +1,36 @@ +// Type definitions for koa-json-error v3.x +// Project: https://github.com/koajs/json-error +// Definitions by: Mudkip +// Definitions: https://github.com/mudkipme/DefinitelyTyped + +/// + +declare module "koa-json-error" { + + import * as Koa from "koa"; + + interface JSONErrorOptions { + /** + * Perform some task before calling `options.format`. Must be a function with the original err as its only argument. + */ + preFormat?: { (err: Error): any }; + + /** + * Runs inmediatly after `options.preFormat`. It receives two arguments: the original `err` and the output of `options.preFormat`. It should `return` a newly formatted error. + */ + format?: { (err: Error, obj: any): any }; + + /** + * Runs inmediatly after `options.format`. It receives two arguments: the original `err` and the output of `options.format`. It should `return` a newly formatted error. + */ + postFormat?: { (err: Error, obj: any): any }; + } + + /** + * Error handler for pure Koa 2.0.0+ JSON apps + */ + function jsonError(options?: JSONErrorOptions) : { (ctx: Koa.Context, next?: () => any): any }; + + namespace jsonError {} + export = jsonError; +} \ No newline at end of file diff --git a/koa-router/koa-router-tests.ts b/koa-router/koa-router-tests.ts index 36d3e6c1c8..d2bae290a4 100644 --- a/koa-router/koa-router-tests.ts +++ b/koa-router/koa-router-tests.ts @@ -23,11 +23,11 @@ router .put('/users/:id', function (ctx, next) { ctx.body = ctx.params.id; }) - .del('/users/:id', function (ctx, next) { + .del('/users/:id', function () { // ... }); -router.get('user', '/users/:id', function (ctx, next) { +router.get('user', '/users/:id', function (ctx) { ctx.body = "sdsd"; }); diff --git a/koa-router/koa-router.d.ts b/koa-router/koa-router.d.ts index 25ec962dad..81a961b93a 100644 --- a/koa-router/koa-router.d.ts +++ b/koa-router/koa-router.d.ts @@ -49,11 +49,11 @@ declare module "koa-router" { } export interface IMiddleware { - (ctx: Router.IRouterContext, next?: () => any): any; + (ctx: Router.IRouterContext, next: () => Promise): any; } export interface IParamMiddleware { - (param: string, ctx: Router.IRouterContext, next?: () => any): any; + (param: string, ctx: Router.IRouterContext, next: () => Promise): any; } export interface IRouterAllowedMethodsOptions { @@ -83,10 +83,8 @@ declare module "koa-router" { regexp: RegExp; path: string; - constructor(path: string, methods: string[], middleware: Router.IMiddleware, opts?: Layer.ILayerOptions); - constructor(path: string, methods: string[], middleware: Array, opts?: Layer.ILayerOptions); - constructor(path: RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Layer.ILayerOptions); - constructor(path: RegExp, methods: string[], middleware: Array, opts?: Layer.ILayerOptions); + constructor(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Layer.ILayerOptions); + constructor(path: string | RegExp, methods: string[], middleware: Array, opts?: Layer.ILayerOptions); /** * Returns whether request `path` matches route. @@ -96,7 +94,7 @@ declare module "koa-router" { /** * Returns map of URL parameters for given `path` and `paramNames`. */ - params(path: string, captures: string[], existingParams?: Object): Object; + params(path: string | RegExp, captures: string[], existingParams?: Object): Object; /** * Returns array of regexp url path captures. @@ -138,61 +136,61 @@ declare module "koa-router" { * "down" the middleware stack. */ use(...middleware: Array): Router; - use(path: string, ...middleware: Array): Router; + use(path: string | RegExp, ...middleware: Array): Router; /** * HTTP get method */ - get(name: string, path: string, ...middleware: Array): Router; - get(path: string, ...middleware: Array): Router; + get(name: string, path: string | RegExp, ...middleware: Array): Router; + get(path: string | RegExp, ...middleware: Array): Router; /** * HTTP post method */ - post(name: string, path: string, ...middleware: Array): Router; - post(path: string, ...middleware: Array): Router; + post(name: string, path: string | RegExp, ...middleware: Array): Router; + post(path: string | RegExp, ...middleware: Array): Router; /** * HTTP put method */ - put(name: string, path: string, ...middleware: Array): Router; - put(path: string, ...middleware: Array): Router; + put(name: string, path: string | RegExp, ...middleware: Array): Router; + put(path: string | RegExp, ...middleware: Array): Router; /** * HTTP delete method */ - delete(name: string, path: string, ...middleware: Array): Router; - delete(path: string, ...middleware: Array): Router; + delete(name: string, path: string | RegExp, ...middleware: Array): Router; + delete(path: string | RegExp, ...middleware: Array): Router; /** * Alias for `router.delete()` because delete is a reserved word */ - del(name: string, path: string, ...middleware: Array): Router; - del(path: string, ...middleware: Array): Router; + del(name: string, path: string | RegExp, ...middleware: Array): Router; + del(path: string | RegExp, ...middleware: Array): Router; /** * HTTP head method */ - head(name: string, path: string, ...middleware: Array): Router; - head(path: string, ...middleware: Array): Router; + head(name: string, path: string | RegExp, ...middleware: Array): Router; + head(path: string | RegExp, ...middleware: Array): Router; /** * HTTP options method */ - options(name: string, path: string, ...middleware: Array): Router; - options(path: string, ...middleware: Array): Router; + options(name: string, path: string | RegExp, ...middleware: Array): Router; + options(path: string | RegExp, ...middleware: Array): Router; /** * HTTP path method */ - patch(name: string, path: string, ...middleware: Array): Router; - patch(path: string, ...middleware: Array): Router; + patch(name: string, path: string | RegExp, ...middleware: Array): Router; + patch(path: string | RegExp, ...middleware: Array): Router; /** * Register route with all methods. */ - all(name: string, path: string, ...middleware: Array): Router; - all(path: string, ...middleware: Array): Router; + all(name: string, path: string | RegExp, ...middleware: Array): Router; + all(path: string | RegExp, ...middleware: Array): Router; /** * Set the path prefix for a Router instance that was already initialized. @@ -226,7 +224,7 @@ declare module "koa-router" { /** * Create and register a route. */ - register(path: string, methods: string[], middleware: Router.IMiddleware, opts?: Object): Layer; + register(path: string | RegExp, methods: string[], middleware: Router.IMiddleware, opts?: Object): Layer; /** * Lookup route with given `name`. @@ -254,7 +252,7 @@ declare module "koa-router" { /** * Generate URL from url pattern and given `params`. */ - static url(path: string, params: Object): string; + static url(path: string | RegExp, params: Object): string; } export = Router; diff --git a/libxslt/libxslt-tests.ts b/libxslt/libxslt-tests.ts new file mode 100644 index 0000000000..544269b11e --- /dev/null +++ b/libxslt/libxslt-tests.ts @@ -0,0 +1,102 @@ +/// +/// + +import * as libxslt from 'libxslt'; +import * as libxmljs from 'libxmljs'; + +const document: libxmljs.XMLDocument = libxslt.libxmljs.parseXmlString(''); + +let stylesheet: libxslt.Stylesheet; + +stylesheet = libxslt.parse(''); + +stylesheet = libxslt.parse(document); + +libxslt.parse('', (err, result) => { + if (err == null) { + stylesheet = result; + } +}); + +libxslt.parse(document, (err, result) => { + if (err == null) { + stylesheet = result; + } +}); + +libxslt.parseFile('/path/to/file', (err, result) => { + if (err == null) { + stylesheet = result; + } +}); + +let applyOptions: libxslt.ApplyOptions = {}; + +applyOptions = { + outputFormat: 'string', + noWrapParams: true +}; + +let transformedString: string; + +let transformedDocument: libxmljs.XMLDocument; + +transformedString = stylesheet.apply(''); + +transformedString = stylesheet.apply('', {}); + +let applyResult = stylesheet.apply('', {}, applyOptions); + +if (typeof applyResult === 'string') { + transformedString = applyResult; +} else { + transformedDocument = applyResult; +} + +stylesheet.apply('', {}, applyOptions, (err, result) => { + if (err != null) { + return; + } + + if (typeof result === 'string') { + transformedString = result; + } else { + transformedDocument = result; + } +}); + +transformedDocument = stylesheet.apply(document); + +transformedDocument = stylesheet.apply(document, {}); + +applyResult = stylesheet.apply(document, {}, applyOptions); + +if (typeof applyResult === 'string') { + transformedString = applyResult; +} else { + transformedDocument = applyResult; +} + +stylesheet.apply(document, {}, applyOptions, (err, result) => { + if (err != null) { + return; + } + + if (typeof result === 'string') { + transformedString = result; + } else { + transformedDocument = result; + } +}); + +stylesheet.applyToFile('/path/to/file', {}, applyOptions, (err, result) => { + if (err == null) { + transformedString = result; + } +}); + +stylesheet.applyToFile('/path/to/file', (err, result) => { + if (err == null) { + transformedString = result; + } +}); diff --git a/libxslt/libxslt.d.ts b/libxslt/libxslt.d.ts new file mode 100644 index 0000000000..0cfd4e1bcd --- /dev/null +++ b/libxslt/libxslt.d.ts @@ -0,0 +1,61 @@ +// Type definitions for node-libxslt +// Project: https://github.com/albanm/node-libxslt +// Definitions by: Alejandro Sánchez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'libxslt' { + import * as xmljs from 'libxmljs'; + + export const libxmljs: typeof xmljs; + + type OutputFormat = 'document' | 'string'; + + export interface ApplyOptions { + outputFormat?: OutputFormat; + noWrapParams?: boolean; + } + + type ApplyResult = string | xmljs.XMLDocument; + + type ApplyCallback = (err: Error, result: ApplyResult) => void; + + type ApplyStringCallback = (err: Error, result: string) => void; + + type ApplyDocumentCallback = (err: Error, result: xmljs.XMLDocument) => void; + + export interface Stylesheet { + apply(source: string, params?: Object): string; + + apply(source: string, params: Object, options: ApplyOptions): ApplyResult; + + apply(source: string, params: Object, options: ApplyOptions, callback: ApplyCallback): void; + + apply(source: string, callback: ApplyStringCallback): void; + + apply(source: xmljs.XMLDocument, params?: Object): xmljs.XMLDocument; + + apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions): ApplyResult; + + apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions, callback: ApplyCallback): void; + + apply(source: xmljs.XMLDocument, callback: ApplyDocumentCallback): void; + + applyToFile(sourcePath: string, params: Object, options: ApplyOptions, callback: ApplyStringCallback): void; + + applyToFile(sourcePath: string, callback: ApplyStringCallback): void; + } + + type ParseCallback = (err: Error, stylesheet: Stylesheet) => void; + + export function parse(source: string): Stylesheet; + + export function parse(source: string, callback: ParseCallback): void; + + export function parse(source: xmljs.XMLDocument): Stylesheet; + + export function parse(source: xmljs.XMLDocument, callback: ParseCallback): void; + + export function parseFile(sourcePath: string, callback: ParseCallback): void; +} diff --git a/localForage/localForage.d.ts b/localForage/localForage.d.ts index 803bde9e57..c727d93b3a 100644 --- a/localForage/localForage.d.ts +++ b/localForage/localForage.d.ts @@ -96,6 +96,6 @@ interface LocalForage { } declare module "localforage" { - export var localforage: LocalForage; - export default localforage; + var localforage: LocalForage; + export = localforage; } diff --git a/lodash/lodash-3.10-tests.ts b/lodash/lodash-3.10-tests.ts index 2616822f6e..3eeff29221 100644 --- a/lodash/lodash-3.10-tests.ts +++ b/lodash/lodash-3.10-tests.ts @@ -9658,6 +9658,25 @@ namespace TestSnakeCase { } } +// _.split +namespace TestSplit { + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('a-b-c').split(); + result = _('a-b-c').split('-'); + result = _('a-b-c').split('-', 2); + } + + { + let result: _.LoDashImplicitArrayWrapper; + + result = _('a-b-c').chain().split(); + result = _('a-b-c').chain().split('-'); + result = _('a-b-c').chain().split('-', 2); + } +} + // _.startCase namespace TestStartCase { { diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index aea06a8362..a63d92d0f0 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -14720,6 +14720,27 @@ declare module _ { snakeCase(): LoDashExplicitWrapper; } + //_.split + interface LoDashImplicitWrapper { + /** + * Splits string by separator. + * + * Note: This method is based on String#split. + * + * @param separator The separator pattern to split by. + * @param limit The length to truncate results to. + * @return Returns the new array with the terms splitted. + */ + split(separator?: RegExp|string, limit?: number): LoDashImplicitArrayWrapper; + } + + interface LoDashExplicitWrapper { + /** + * @see _.split + */ + split(separator?: RegExp|string, limit?: number): LoDashImplicitArrayWrapper; + } + //_.startCase interface LoDashStatic { /** diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 8ec22e98de..42fce74b8b 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -3674,33 +3674,51 @@ namespace TestFind { result = _.find(array); result = _.find(array, listIterator); + result = _.find(array, listIterator, 1); result = _.find(array, ''); + result = _.find(array, '', 1); result = _.find<{a: number}, TResult>(array, {a: 42}); + result = _.find<{a: number}, TResult>(array, {a: 42}, 1); result = _.find(list); result = _.find(list, listIterator); + result = _.find(list, listIterator, 1); result = _.find(list, ''); + result = _.find(list, '', 1); result = _.find<{a: number}, TResult>(list, {a: 42}); + result = _.find<{a: number}, TResult>(list, {a: 42}, 1); result = _.find(dictionary); result = _.find(dictionary, dictionaryIterator); + result = _.find(dictionary, dictionaryIterator, 1); result = _.find(dictionary, ''); + result = _.find(dictionary, '', 1); result = _.find<{a: number}, TResult>(dictionary, {a: 42}); + result = _.find<{a: number}, TResult>(dictionary, {a: 42}, 1); result = _(array).find(); result = _(array).find(listIterator); + result = _(array).find(listIterator, 1); result = _(array).find(''); + result = _(array).find('', 1); result = _(array).find<{a: number}>({a: 42}); + result = _(array).find<{a: number}>({a: 42}, 1); result = _(list).find(); result = _(list).find(listIterator); + result = _(list).find(listIterator, 1); result = _(list).find(''); + result = _(list).find('', 1); result = _(list).find<{a: number}, TResult>({a: 42}); + result = _(list).find<{a: number}, TResult>({a: 42}, 1); result = _(dictionary).find(); result = _(dictionary).find(dictionaryIterator); + result = _(dictionary).find(dictionaryIterator, 1); result = _(dictionary).find(''); + result = _(dictionary).find('', 1); result = _(dictionary).find<{a: number}, TResult>({a: 42}); + result = _(dictionary).find<{a: number}, TResult>({a: 42}, 1); } result = _.findLast([1, 2, 3, 4], function (num) { @@ -4661,32 +4679,38 @@ result = <{a: number}[][]>_({0: {a: 1}, 1: {a: 2}}).partition<{a: number}>('a', // result = _(dictionary).chain().map(['d', 0, 'b']); // } // } +namespace TestReduce { + interface ABC { + [index: string]: number; + a: number; + b: number; + c: number; + } -interface ABC { - [index: string]: number; - a: number; - b: number; - c: number; + result = _.reduce([1, 2, 3], function (sum: number, num: number) { + return sum + num; + }); + + // chained + result = _.chain([1, 2 ,3]).reduce(function (sum: number, num: number) { + return sum + num; + }).value(); + + result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { + r[key] = num * 3; + return r; + }, {}); + + result = _([1, 2, 3]).reduce(function (sum: number, num: number) { + return sum + num; + }); + result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce(function (r: ABC, num: number, key: string) { + r[key] = num * 3; + return r; + }, {}); + + result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); } - -result = _.reduce([1, 2, 3], function (sum: number, num: number) { - return sum + num; -}); -result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { - r[key] = num * 3; - return r; -}, {}); - -result = _([1, 2, 3]).reduce(function (sum: number, num: number) { - return sum + num; -}); -result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce(function (r: ABC, num: number, key: string) { - r[key] = num * 3; - return r; -}, {}); - -result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); - // _.reject namespace TestReject { let array: TResult[]; @@ -5733,11 +5757,11 @@ namespace TestFlow { let Fn2: (m: number, n: number) => number; let Fn3: (a: number) => string; let Fn4: (a: string) => number; - + { // type infer test let result: (m: number, n: number) => number; - + result = _.flow(Fn2, Fn1); result = _.flow(Fn2, Fn1, Fn1); result = _.flow(Fn2, Fn1, Fn1, Fn1); diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 52f274fd3c..eb24793955 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -172,6 +172,7 @@ Other changes - [x] Ensured _.range preserves the sign of start of -0 - [x] Ensured _.reduce & _.reduceRight use getIteratee in their array branch - [x] Fixed rounding issue with the precision param of _.floor +- [x] Added flush method to debounced & throttled functions ** LATER ** Misc: @@ -185,7 +186,6 @@ Misc: - [ ] _.extend as an alias of _.assignIn - [ ] _.extendWith as an alias of _.assignInWith - [ ] Added clear method to _.memoize.Cache -- [ ] Added flush method to debounced & throttled functions - [ ] Added support for ES6 maps, sets, & symbols to _.clone, _.isEqual, & _.toArray - [ ] Enabled _.flow & _.flowRight to accept an array of functions - [ ] Ensured “Collection” methods treat functions as objects @@ -6787,12 +6787,13 @@ declare module _ { * * @param collection The collection to search. * @param predicate The function invoked per iteration. - * @param thisArg The this binding of predicate. + * @param fromIndex The index to search from. * @return Returns the matched element, else undefined. */ find( collection: List, - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): T; /** @@ -6800,7 +6801,8 @@ declare module _ { */ find( collection: Dictionary, - predicate?: DictionaryIterator + predicate?: DictionaryIterator, + fromIndex?: number ): T; /** @@ -6808,7 +6810,8 @@ declare module _ { */ find( collection: List|Dictionary, - predicate?: string + predicate?: string, + fromIndex?: number ): T; /** @@ -6816,7 +6819,8 @@ declare module _ { */ find( collection: List|Dictionary, - predicate?: TObject + predicate?: TObject, + fromIndex?: number ): T; } @@ -6825,21 +6829,24 @@ declare module _ { * @see _.find */ find( - predicate?: ListIterator + predicate?: ListIterator, + fromIndex?: number ): T; /** * @see _.find */ find( - predicate?: string + predicate?: string, + fromIndex?: number ): T; /** * @see _.find */ find( - predicate?: TObject + predicate?: TObject, + fromIndex?: number ): T; } @@ -6848,21 +6855,24 @@ declare module _ { * @see _.find */ find( - predicate?: ListIterator|DictionaryIterator + predicate?: ListIterator|DictionaryIterator, + fromIndex?: number ): TResult; /** * @see _.find */ find( - predicate?: string + predicate?: string, + fromIndex?: number ): TResult; /** * @see _.find */ find( - predicate?: TObject + predicate?: TObject, + fromIndex?: number ): TResult; } @@ -8574,6 +8584,21 @@ declare module _ { callback: MemoIterator): LoDashExplicitObjectWrapper; } + interface LoDashExplicitArrayWrapper { + /**LoDashExplicitWrapper + * @see _.reduce + */ + reduce( + callback: MemoIterator, + accumulator: TResult): LoDashExplicitWrapper; + + /** + * @see _.reduce + */ + reduce( + callback: MemoIterator): LoDashExplicitWrapper; + } + //_.reduceRight interface LoDashStatic { /** @@ -10132,9 +10157,9 @@ declare module _ { /** * Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since * the last time the debounced function was invoked. The debounced function comes with a cancel method to - * cancel delayed invocations. Provide an options object to indicate that func should be invoked on the - * leading and/or trailing edge of the wait timeout. Subsequent calls to the debounced function return the - * result of the last func invocation. + * cancel delayed invocations and a flush method to immediately invoke them. Provide an options object to + * indicate that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent + * calls to the debounced function return the result of the last func invocation. * * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only * if the the debounced function is invoked more than once during the wait timeout. @@ -10755,9 +10780,9 @@ declare module _ { interface LoDashStatic { /** * Creates a throttled function that only invokes func at most once per every wait milliseconds. The throttled - * function comes with a cancel method to cancel delayed invocations. Provide an options object to indicate - * that func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to - * the throttled function return the result of the last func call. + * function comes with a cancel method to cancel delayed invocations and a flush method to immediately invoke + * them. Provide an options object to indicate that func should be invoked on the leading and/or trailing edge + * of the wait timeout. Subsequent calls to the throttled function return the result of the last func call. * * Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if * the the throttled function is invoked more than once during the wait timeout. @@ -19159,6 +19184,7 @@ declare module _ { interface Cancelable { cancel(): void; + flush(): void; } } diff --git a/mailparser/mailparser.d.ts b/mailparser/mailparser.d.ts index bc50dcc509..d265d30b16 100644 --- a/mailparser/mailparser.d.ts +++ b/mailparser/mailparser.d.ts @@ -60,7 +60,7 @@ declare module 'mailparser' { - class MailParser implements WritableStream { + class MailParser extends StreamModule.Writable { constructor(options?: Options); on(event: string, callback: (any: any) => void): this; diff --git a/maquette/maquette.d.ts b/maquette/maquette.d.ts index 7ad5081ed0..b1ee5bc9c7 100644 --- a/maquette/maquette.d.ts +++ b/maquette/maquette.d.ts @@ -325,6 +325,14 @@ declare namespace maquette { * @param {function} renderMaquetteFunction - Function with zero arguments that returns a {@link VNode} tree. */ append(parentNode: Element, renderMaquetteFunction: () => VNode): void; + /** + * Stops running the `renderMaquetteFunction` to update the DOM. The `renderMaquetteFunction` must have been + * registered using [[append]], [[merge]], [[insertBefore]] or [[replace]]. + * + * @returns The [[Projection]] which was created using this `renderMaquetteFunction`. + * The [[Projection]] contains a reference to the DOM Node that was rendered. + */ + detach(renderMaquetteFunction: () => VNode): Projection; /** * Scans the document for `