diff --git a/README.md b/README.md index 3028c233d0..9f3c4fe78f 100644 --- a/README.md +++ b/README.md @@ -89,6 +89,13 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in * Make changes. Remember to edit tests. * You may also want to add yourself to "Definitions by" section of the package header. - Do this by adding your name to the end of the line, as in `// Definitions by: Alice , Bob `. + - Or if there are more people, it can be multiline + ```typescript + // Definitions by: Alice + // Bob + // Steve + // John + ``` * `npm install -g typescript@2.0` and run `tsc`. When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors. diff --git a/notNeededPackages.json b/notNeededPackages.json index 2bc2de286f..ca42f4d9f5 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -354,6 +354,12 @@ "sourceRepoURL": "https://github.com/blakeembrey/path-case", "asOfVersion": "1.1.2" }, + { + "libraryName": "path-to-regexp", + "typingsPackageName": "path-to-regexp", + "sourceRepoURL": "https://github.com/pillarjs/path-to-regexp", + "asOfVersion": "1.7.0" + }, { "libraryName": "pg-promise", "typingsPackageName": "pg-promise", diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index 5afc9a9153..10648c0012 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -27,7 +27,7 @@ declare module 'angular' { escapeToClose?: boolean; resolve?: ResolveObject; controllerAs?: string; - parent?: ((scope: ng.IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node + parent?: ((scope: angular.IScope, element: JQuery) => Element | JQuery) | string | Element | JQuery; // default: root node disableParentScroll?: boolean; // default: true } @@ -107,9 +107,9 @@ declare module 'angular' { resolve?: ResolveObject; controllerAs?: string; parent?: string | Element | JQuery; // default: root node - onShowing?(scope: ng.IScope, element: JQuery): void; - onComplete?(scope: ng.IScope, element: JQuery): void; - onRemoving?(element: JQuery, removePromise: ng.IPromise): void; + onShowing?(scope: angular.IScope, element: JQuery): void; + onComplete?(scope: angular.IScope, element: JQuery): void; + onRemoving?(element: JQuery, removePromise: angular.IPromise): void; skipHide?: boolean; multiple?: boolean; fullscreen?: boolean; // default: false diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index 1d59854d9d..c895c4f7ee 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Angular JS 1.6 // Project: http://angularjs.org -// Definitions by: Diego Vilar , Georgii Dolzhykov +// Definitions by: Diego Vilar , Georgii Dolzhykov , Caleb St-Denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -1847,6 +1847,77 @@ declare namespace angular { $postLink?(): void; } + /** + * Interface for the $onInit lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IOnInit { + /** + * Called on each controller after all the controllers on an element have been constructed and had their bindings + * initialized (and before the pre & post linking functions for the directives on this element). This is a good + * place to put initialization code for your controller. + */ + $onInit(): void; + } + + /** + * Interface for the $doCheck lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IDoCheck { + /** + * Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes. + * Any actions that you wish to take in response to the changes that you detect must be invoked from this hook; + * implementing this has no effect on when `$onChanges` is called. For example, this hook could be useful if you wish + * to perform a deep equality check, or to check a `Dat`e object, changes to which would not be detected by Angular's + * change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; if detecting changes, + * you must store the previous value(s) for comparison to the current values. + */ + $doCheck(): void; + } + + /** + * Interface for the $onChanges lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IOnChanges { + /** + * 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(onChangesObj: IOnChangesObject): void; + } + + /** + * Interface for the $onDestroy lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IOnDestroy { + /** + * Called on a controller when its containing scope is destroyed. Use this hook for releasing external resources, + * watches and event handlers. + */ + $onDestroy(): void; + } + + /** + * Interface for the $postLink lifecycle hook + * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks + */ + interface IPostLink { + /** + * Called after this controller's element and its children have been linked. Similar to the post-link function this + * hook can be used to set up DOM event handlers and do direct DOM manipulation. Note that child elements that contain + * templateUrl directives will not have been compiled and linked since they are waiting for their template to load + * asynchronously and their own compilation and linking has been suspended until that occurs. This hook can be considered + * analogous to the ngAfterViewInit and ngAfterContentInit hooks in Angular 2. Since the compilation process is rather + * different in Angular 1 there is no direct mapping and care should be taken when upgrading. + */ + $postLink(): void; + } + interface IOnChangesObject { [property: string]: IChangesObject; } diff --git a/types/angular/tslint.json b/types/angular/tslint.json index 3ace427c86..50c4474b7c 100644 --- a/types/angular/tslint.json +++ b/types/angular/tslint.json @@ -17,4 +17,4 @@ "unified-signatures": false, "void-return": false } -} +} \ No newline at end of file diff --git a/types/archiver/archiver-tests.ts b/types/archiver/archiver-tests.ts index 57a569ab02..d4ea423a4f 100644 --- a/types/archiver/archiver-tests.ts +++ b/types/archiver/archiver-tests.ts @@ -1,26 +1,36 @@ -import Archiver = require('archiver'); -import FS = require('fs'); +import * as Archiver from 'archiver'; +import * as fs from 'fs'; const archiver = Archiver.create('zip'); -const writeStream = FS.createWriteStream('./archiver.d.ts'); -const readStream = FS.createReadStream('./archiver.d.ts'); +const writeStream = fs.createWriteStream('./archiver.d.ts'); +const readStream = fs.createReadStream('./archiver.d.ts'); archiver.abort(); + +archiver.pipe(writeStream); +archiver.append(readStream, { name: 'archiver.d.ts' }); + archiver.append(readStream, {name: 'archiver.d.ts'}) .append(readStream, {name: 'archiver.d.ts'}); archiver.bulk({ mappaing: {} }); archiver.directory('./path', './someOtherPath'); -archiver.directory('./path', { name: "testName"} ); - +archiver.directory('./path', { name: "testName" }); archiver.directory('./', "", {}); -archiver.directory('./', {name: 'test'}, {}); +archiver.directory('./', { name: 'test' }, {}); + +archiver.append(readStream, { + name: "sub/folder.xml" +}); + +archiver.glob("**", { + cwd: 'path/to/files', +}); +archiver.glob('./path', {}, {}); archiver.file('./path', { name: 'test' }); -archiver.glob('./path', {}, {}); -archiver.finalize(); archiver.setFormat('zip'); archiver.setModule(() => {}); @@ -28,4 +38,4 @@ archiver.setModule(() => {}); archiver.pointer(); archiver.use(() => {}); -archiver.pipe(writeStream); +archiver.finalize(); diff --git a/types/archiver/index.d.ts b/types/archiver/index.d.ts index 9c2b2ae509..2e4b1063ff 100644 --- a/types/archiver/index.d.ts +++ b/types/archiver/index.d.ts @@ -1,51 +1,67 @@ // Type definitions for archiver 1.3 // Project: https://github.com/archiverjs/node-archiver -// Definitions by: Esri +// Definitions by: Esri , Dolan Miu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* =================== USAGE =================== import Archiver = require('archiver); var archiver = Archiver.create('zip'); - archiver.pipe(FS.createWriteStream('xxx')); - archiver.append(FS.createReadStream('xxx')); + archiver.pipe(fs.createWriteStream('xxx')); + archiver.append(fs.createReadStream('xxx')); archiver.finalize(); =============================================== */ /// -import * as FS from 'fs'; -import * as STREAM from 'stream'; +import * as fs from 'fs'; +import * as stream from 'stream'; +import * as express from 'express'; +import * as glob from 'glob'; -declare function archiver(format: string, options?: {}): archiver.Archiver; +declare function archiver(format: archiver.Format, options?: archiver.ArchiverOptions): archiver.Archiver; declare namespace archiver { - function create(format: string, options?: {}): Archiver; + type Format = 'zip' | 'tar'; + + function create(format: string, options?: ArchiverOptions): Archiver; function registerFormat(format: string, module: Function): void; - interface nameInterface { + interface EntryData { name?: string; + prefix?: string; + stats?: string; } - interface Archiver extends STREAM.Transform { + interface Archiver extends stream.Transform { abort(): this; - append(source: STREAM.Readable | Buffer | string, name: nameInterface): this; + append(source: stream.Readable | Buffer | string, name?: EntryData): this; bulk(mappings: any): this; - directory(dirpath: string, destpath: nameInterface | string, data?: any | Function): this; + directory(dirpath: string, options: EntryData | string, data?: EntryData): this; - file(filepath: string, data: any): this; - glob(pattern: string, options: {}, data: any): this; + file(filename: string, data: EntryData): this; + glob(pattern: string, options?: glob.IOptions, data?: EntryData): this; finalize(): this; + pipe(stream: fs.WriteStream | express.Response): void; + setFormat(format: string): this; setModule(module: Function): this; pointer(): number; use(plugin: Function): this; } + + interface ArchiverOptions { + store?: boolean; + gzip?: boolean; + gzipOptions?: { + level: number, + }; + } } export = archiver; diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 8a37bdf21b..6741bcccd1 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AutobahnJS v0.9.7 // Project: http://autobahn.ws/js/ -// Definitions by: Elad Zelingher , Andy Hawkins +// Definitions by: Elad Zelingher , Andy Hawkins , Wladimir Totino // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -167,8 +167,14 @@ declare namespace autobahn { interface IPublishOptions { acknowledge?: boolean; exclude?: number[]; + exclude_authid?: string[]; + exclude_authrole?: string[]; eligible?: number[]; - disclose_me?: Boolean; + eligible_authid?: string[]; + eligible_authrole?: string[]; + retain?: boolean; + disclose_me?: boolean; + exclude_me?: boolean; } interface ISubscribeOptions { diff --git a/types/babylon/index.d.ts b/types/babylon/index.d.ts index 4400a8f1a0..eb35a5d799 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -5,10 +5,11 @@ /// -import * as t from 'babel-types'; -type Node = t.Node; +import { File, Expression } from 'babel-types'; -export function parse(code: string, opts?: BabylonOptions): Node; +export function parse(code: string, opts?: BabylonOptions): File; + +export function parseExpression(input: string, options?: BabylonOptions): Expression; export interface BabylonOptions { /** diff --git a/types/baconjs/baconjs-tests.ts b/types/baconjs/baconjs-tests.ts index e948668dc7..75560d4e42 100644 --- a/types/baconjs/baconjs-tests.ts +++ b/types/baconjs/baconjs-tests.ts @@ -190,6 +190,11 @@ function CommonMethodsInEventStreamsAndProperties() { console.log(sum); // returns [-1, 2, 8] in an order }); } + + { + var src = Bacon.fromArray([1, 2, 3]); + src.doLog('element value'); + } } function EventStream() { diff --git a/types/baconjs/index.d.ts b/types/baconjs/index.d.ts index 8659ea9115..0550d6ec48 100644 --- a/types/baconjs/index.d.ts +++ b/types/baconjs/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Bacon.js 0.7.0 // Project: https://baconjs.github.io/ -// Definitions by: Alexander Matsievsky +// Definitions by: Alexander Matsievsky , Joonas Javanainen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -69,7 +69,7 @@ declare namespace Bacon { /** * @function * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the optional `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream. - * @param {Promise|JQueryXHR} promise + * @param {PromiseLike|JQueryXHR} promise * @param {boolean} [abort] * @returns {EventStream} * @example @@ -78,7 +78,7 @@ declare namespace Bacon { * Bacon.fromPromise($.ajax("https://baconjs.github.io/"), true); * Bacon.fromPromise(Promise.resolve(1), false); */ - function fromPromise(promise:Promise|JQueryXHR, abort?:boolean):EventStream; + function fromPromise(promise:PromiseLike|JQueryXHR, abort?:boolean):EventStream; /** * @callback Bacon.fromPromise~eventTransformer @@ -88,7 +88,7 @@ declare namespace Bacon { /** * @function Bacon.fromPromise * @description Creates an [EventStream]{@link Bacon.EventStream} from a `promise` Promise object such as JQuery Ajax. This stream will contain a single value or an error, followed immediately by stream end. You can use the `abort` flag (i.e. ´Bacon.fromPromise(p, true)´ to have the `abort` method of the given promise be called when all subscribers have been removed from the created stream, and also pass a function `eventTransformer` that transforms the promise value into Events. The default is to transform the value into `[new Bacon.Next(value), new Bacon.End()]`. - * @param {Promise|JQueryXHR} promise + * @param {PromiseLike|JQueryXHR} promise * @param {boolean} abort * @param {Bacon.fromPromise~eventTransformer} eventTransformer * @returns {EventStream} @@ -100,7 +100,7 @@ declare namespace Bacon { * return [new Bacon.Next(n), new Bacon.Next(() => n), new Bacon.End()]; * }); */ - function fromPromise(promise:Promise|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial|Next|End|Error)[]):EventStream; + function fromPromise(promise:PromiseLike|JQueryXHR, abort:boolean, eventTransformer:(value:A) => (Initial|Next|End|Error)[]):EventStream; /** * @function @@ -1026,9 +1026,10 @@ declare namespace Bacon { /** * @method EventStream#doLog * @description Logs each value of the [EventStream]{@link Bacon.EventStream} to the console. [doLog]{@link Bacon.EventStream#doLog} behaves like [log]{@link Bacon.EventStream#log} but does not subscribe to the EventStream. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @param {string} [label] * @returns {EventStream} */ - doLog():EventStream; + doLog(label?:string):EventStream; /** * @method @@ -1613,9 +1614,10 @@ declare namespace Bacon { /** * @method Property#doLog * @description Logs each value of the [Property]{@link Bacon.Property} to the console. [doLog]{@link Bacon.Property#doLog} behaves like [log]{@link Bacon.Property#log} but does not subscribe to the Property. You can think of `doLog` as a logger function that – unlike `log` – is safe to use in production. `doLog` is safe, because it does not cause the same surprising side-effects as `log` does. + * @param {string} [label] * @returns {Property} */ - doLog():Property; + doLog(label?:string):Property; /** * @method diff --git a/types/bleno/bleno-tests.ts b/types/bleno/bleno-tests.ts new file mode 100644 index 0000000000..7dcb47ff35 --- /dev/null +++ b/types/bleno/bleno-tests.ts @@ -0,0 +1,56 @@ +import * as Bleno from 'bleno'; + +export class EchoCharacteristic extends Bleno.Characteristic { + _value: any; + _updateValueCallback: any; + + constructor() { + super({ + uuid: 'ec0e', + properties: ['read', 'write', 'notify'], + value: null + }); + this._value = new ArrayBuffer(0); + this._updateValueCallback = null; + } + + onReadRequest(offset: number, callback: any) { + callback(Bleno.Characteristic.RESULT_SUCCESS, this._value); + } + + onWriteRequest(data: any, offset: number, withoutResponse: boolean, callback: any) { + this._value = data; + + if (this._updateValueCallback) { + this._updateValueCallback(this._value); + } + + callback(Bleno.Characteristic.RESULT_SUCCESS); + } + + onSubscribe(maxValueSize: number, updateValueCallback: any) { + this._updateValueCallback = updateValueCallback; + } + + onUnsubscribefunction() { + this._updateValueCallback = null; + } +} + +Bleno.on('stateChange', (state: string) => { + if (state === 'poweredOn') { + Bleno.startAdvertising('echo', ['ec00'], () => {}); + } else { + Bleno.stopAdvertising(() => {}); + } +}); + +let characteristic = new EchoCharacteristic(); +Bleno.on('advertisingStart', (error: string) => { + if (!error) { + Bleno.setServices( + [new Bleno.PrimaryService({uuid: 'ec00', characteristics: [ characteristic ] })], + () => {} + ); + } +}); diff --git a/types/bleno/index.d.ts b/types/bleno/index.d.ts new file mode 100644 index 0000000000..a59e394a84 --- /dev/null +++ b/types/bleno/index.d.ts @@ -0,0 +1,128 @@ +// Type definitions for bleno 0.4 +// Project: https://github.com/sandeepmistry/bleno +// Definitions by: Manuel Francisco Naranjo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class Characteristic { + uuid: any; + properties: any; + secure: any; + value: any; + descriptors: any; + + constructor(options: any); + + onIndicate(): void; + + onNotify(): void; + + onReadRequest(offset: any, callback: any): void; + + onSubscribe(maxValueSize: any, updateValueCallback: any): void; + + onUnsubscribe(): void; + + onWriteRequest(data: any, offset: any, withoutResponse: any, callback: any): void; + + toString(): any; + + static RESULT_ATTR_NOT_LONG: number; + + static RESULT_INVALID_ATTRIBUTE_LENGTH: number; + + static RESULT_INVALID_OFFSET: number; + + static RESULT_SUCCESS: number; + + static RESULT_UNLIKELY_ERROR: number; +} + +export class Descriptor { + uuid: any; + value: any; + + constructor(options: any); + + toString(): any; +} + +export class PrimaryService { + uuid: any; + characteristics: any; + + constructor(options: any); + + toString(): any; +} + +export const address: string; + +export const domain: any; + +export const mtu: number; + +export const platform: string; + +export const rssi: number; + +export const state: string; + +export function addListener(type: any, listener: any): any; + +export function disconnect(): void; + +export function emit(type: any, ...args: any[]): any; + +export function eventNames(): any; + +export function getMaxListeners(): any; + +export function listenerCount(type: any): any; + +export function listeners(type: any): any; + +export function on(type: any, listener: any): any; + +export function onAccept(clientAddress: any): void; + +export function onAddressChange(address: any): void; + +export function onAdvertisingStart(error: any): void; + +export function onAdvertisingStop(): void; + +export function onDisconnect(clientAddress: any): void; + +export function onMtuChange(mtu: any): void; + +export function onPlatform(platform: any): void; + +export function onRssiUpdate(rssi: any): void; + +export function onServicesSet(error: any): void; + +export function onStateChange(state: any): void; + +export function once(type: any, listener: any): any; + +export function prependListener(type: any, listener: any): any; + +export function prependOnceListener(type: any, listener: any): any; + +export function removeAllListeners(type: any, ...args: any[]): any; + +export function removeListener(type: any, listener: any): any; + +export function setMaxListeners(n: any): any; + +export function setServices(services: any, callback: any): void; + +export function startAdvertising(name: any, serviceUuids: any, callback: any): void; + +export function startAdvertisingIBeacon(uuid: any, major: any, minor: any, measuredPower: any, callback: any): void; + +export function startAdvertisingWithEIRData(advertisementData: any, scanData: any, callback: any): void; + +export function stopAdvertising(callback: any): void; + +export function updateRssi(callback: any): void; diff --git a/types/promise/tsconfig.json b/types/bleno/tsconfig.json similarity index 82% rename from types/promise/tsconfig.json rename to types/bleno/tsconfig.json index 5fc066d3e9..44fa6c893f 100644 --- a/types/promise/tsconfig.json +++ b/types/bleno/tsconfig.json @@ -2,11 +2,11 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es5" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "promise-tests.ts" + "bleno-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/bleno/tslint.json b/types/bleno/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/types/bleno/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/types/bookshelf/bookshelf-tests.ts b/types/bookshelf/bookshelf-tests.ts index 61718a4274..f42a1bf784 100644 --- a/types/bookshelf/bookshelf-tests.ts +++ b/types/bookshelf/bookshelf-tests.ts @@ -481,6 +481,15 @@ new Book({'ISBN-13': '9780440180296'}) /* model.fetchAll(), see http://bookshelfjs.org/#Model-instance-fetchAll */ +{ + (new User).fetchAll({ + columns: ['id', 'name'], + withRelated: ['posts.tags'] + }).then((user: any) => { + console.log(user); + }) +} + /* model.format(), see http://bookshelfjs.org/#Model-instance-format */ /* model.get(), see http://bookshelfjs.org/#Model-instance-get */ @@ -637,6 +646,16 @@ customer.on('fetching', (model, columns) => { /* model.once(), see http://bookshelfjs.org/#Model-instance-once */ +/* model.orderBy(), see http://bookshelfjs.org/#Model-instance-orderBy */ +{ + (new User) + .orderBy('name', 'ASC') + .fetchAll() + .then((users: Bookshelf.Collection) => { + console.log(users) + }); +} + /* model.parse(), see http://bookshelfjs.org/#Model-instance-parse */ // Example of a "parse" to convert snake_case to camelCase, using `underscore.string` @@ -1096,6 +1115,16 @@ ships.on('fetched', (collection, response) => { /* collection.once(), see http://bookshelfjs.org/#Collection-instance-once */ +/* collection.orderBy(), see http://bookshelfjs.org/#Collection-instance-orderBy */ +{ + User.collection() + .orderBy('-name') + .fetch() + .then((users: Bookshelf.Collection) => { + console.log(users); + }) +} + /* collection.parse(), see http://bookshelfjs.org/#Collection-instance-parse */ /* collection.pluck(), see http://bookshelfjs.org/#Collection-instance-pluck */ @@ -1376,4 +1405,4 @@ new User({name: 'John'}).fetchAll({require: true}) new Country({id: 1}).capital().fetch().then(model => { // ... }); -} \ No newline at end of file +} diff --git a/types/bookshelf/index.d.ts b/types/bookshelf/index.d.ts index 398534806d..86176ed2e8 100644 --- a/types/bookshelf/index.d.ts +++ b/types/bookshelf/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for bookshelfjs v0.8.2 +// Type definitions for bookshelfjs v0.9.3 // Project: http://bookshelfjs.org/ -// Definitions by: Andrew Schurman +// Definitions by: Andrew Schurman , Vesa Poikajärvi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -23,6 +23,8 @@ interface Bookshelf extends Bookshelf.Events { declare function Bookshelf(knex: knex): Bookshelf; declare namespace Bookshelf { + type SortOrder = 'ASC'|'asc'|'DESC'|'desc'; + abstract class Events { on(event?: string, callback?: EventFunction, context?: any): void; off(event?: string): void; @@ -105,6 +107,7 @@ declare namespace Bookshelf { morphOne>(target: { new (...args: any[]): R }, name?: string, columnNames?: string[], morphValue?: string): R; morphTo(name: string, columnNames?: string[], ...target: typeof Model[]): T; morphTo(name: string, ...target: typeof Model[]): T; + orderBy(column: string, order?: SortOrder): T; // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[]) query(): Knex.QueryBuilder; @@ -242,6 +245,7 @@ declare namespace Bookshelf { detach(options?: SyncOptions): BlueBird; fetchOne(options?: CollectionFetchOneOptions): BlueBird; load(relations: string | string[], options?: SyncOptions): BlueBird>; + orderBy(column: string, order?: SortOrder): T; // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[]) query(): Knex.QueryBuilder; @@ -278,8 +282,7 @@ declare namespace Bookshelf { [index: string]: (query: Knex.QueryBuilder) => Knex.QueryBuilder; } - interface FetchAllOptions extends SyncOptions { - require?: boolean; + interface FetchAllOptions extends FetchOptions { } interface SaveOptions extends SyncOptions { diff --git a/types/bootstrap.v3.datetimepicker/index.d.ts b/types/bootstrap.v3.datetimepicker/index.d.ts index 4686aa9680..f37a42b67d 100644 --- a/types/bootstrap.v3.datetimepicker/index.d.ts +++ b/types/bootstrap.v3.datetimepicker/index.d.ts @@ -337,16 +337,16 @@ export interface DatetimepickerOptions { /** Shows the week of the year to the left of first day of the week. * @default: false */ - calendarWeeks?: boolean; + calendarWeeks?: boolean; /** Using a Bootstraps collapse to switch between date/time pickers. * @default: true */ - collapse?: boolean; + collapse?: boolean; /** Disables the section of days of the week, e.g. weekends. * Accepts: array of numbers from 0-6 * @default: false */ - daysOfWeekDisabled?: number[] | boolean; + daysOfWeekDisabled?: number[] | boolean; /** Changes the heading of the datepicker when in "days" view. * @default: "MMMM YYYY" */ @@ -358,14 +358,14 @@ export interface DatetimepickerOptions { /** Sets the picker default date/time. Overrides useCurrent * @default: false */ - defaultDate?: boolean | moment.Moment | Date | string; + defaultDate?: boolean | moment.Moment | Date | string; /** Disables selection of dates in the array, e.g. holidays * @default: false * IMPORTANT! The getter returns an Object NOT an Array, with keys being the dates, values being true. * eg disabledDates = ["2010-10-10"]; -> disabledDated will be { "2010-01-01": true } * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 */ - disabledDates?: boolean | Array | any; + disabledDates?: boolean | Array | any; /** Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days * @default: false * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. @@ -384,7 +384,7 @@ export interface DatetimepickerOptions { * eg enabledDates = ["2010-10-10"]; -> enabledDated will be { "2010-01-01": true } * https://github.com/Eonasdan/bootstrap-datetimepicker/issues/1499 */ - enabledDates?: boolean | Array | any; + enabledDates?: boolean | Array | any; /** Will allow or disallow hour selections (much like disabledTimeIntervals) but will affect all days * @default: false * IMPORTANT! The getter returns an Object NOT an Array, with keys being the hours, values being true. @@ -403,17 +403,17 @@ export interface DatetimepickerOptions { /** See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker. * @default: false */ - format?: boolean | string | moment.MomentBuiltinFormat; + format?: boolean | string | moment.MomentBuiltinFormat; /** Change the default icons for the pickers functions. */ - icons?: Icons; + icons?: Icons; /** Allow date picker show event to fire even when the associated input element has the readonly="readonly"property. * @default: false */ - ignoreReadonly?: boolean; + ignoreReadonly?: boolean; /** Will display the picker inline without the need of a input field. This will also hide borders and shadows. * @default: false */ - inline?: boolean; + inline?: boolean; /** Allows for custom events to fire on keyboard press. * eg: keybinds: { * up: (widget) => console.log(widget), @@ -433,17 +433,17 @@ export interface DatetimepickerOptions { /** See momentjs for valid locales. You must include moment-with-locales.js or a local js file. * @default: moment.locale() */ - locale?: string; + locale?: string; /** Prevents date/time selections after this date. * maxDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. * @default: false */ - maxDate?: boolean | moment.Moment | Date | string; + maxDate?: boolean | moment.Moment | Date | string; /** Prevents date/time selections before this date. * minDate will override defaultDate and useCurrent if either of these settings are the same day since both options are invalid according to the rules you've selected. * @default: false */ - minDate?: boolean | moment.Moment | Date | string; + minDate?: boolean | moment.Moment | Date | string; /** Allows custom input formatting For example: the user can enter "yesterday"" or "30 days ago". * {@link http://eonasdan.github.io/bootstrap-datetimepicker/Functions/#parseinputdate} */ @@ -452,7 +452,7 @@ export interface DatetimepickerOptions { * Clicking the "Clear" button will set the calendar to null. * @default: false */ - showClear?: boolean; + showClear?: boolean; /** Show the "Close" button in the icon toolbar. * Clicking the "Close" button will call hide() * @default: false @@ -462,11 +462,11 @@ export interface DatetimepickerOptions { * Clicking the "Today" button will set the calendar view and set the date to now. * @default: false */ - showTodayButton?: boolean; + showTodayButton?: boolean; /** Shows the picker side by side when using the time and date together. * @default: false */ - sideBySide?: boolean; + sideBySide?: boolean; /** Number of minutes the up/down arrow's will move the minutes value in the time picker * @default: 1 */ @@ -479,17 +479,17 @@ export interface DatetimepickerOptions { /** Changes the placement of the icon toolbar. * @default: "default" */ - toolbarPlacement?: "default" | "top" | "bottom"; + toolbarPlacement?: "default" | "top" | "bottom"; /** This will change the tooltips over each icon to a custom string */ tooltips?: Tooltips; /** On show, will set the picker to the current date/time * @default: true */ - useCurrent?: boolean; + useCurrent?: boolean; /** Defines if moment should use strict date parsing when considering a date to be valid * @default: false */ - useStrict?: boolean; + useStrict?: boolean; /** This will change the viewDate without changing or setting the selected date. * @default: false */ @@ -498,7 +498,7 @@ export interface DatetimepickerOptions { * Note: To limit the picker to selecting, for instance the year and month, use format: MM/YYYY * @default: "days" */ - viewMode?: "decades" | "years" | "months" | "days"; + viewMode?: "decades" | "years" | "months" | "days"; /** On picker show, places the widget at the identifier (string) or jQuery object if the element has css position: "relative" * @default: null */ @@ -520,7 +520,7 @@ export interface Icons { /** default: "glyphicon glyphicon-screenshot" */ previous?: string; /** default: "glyphicon glyphicon-chevron-right" */ - time?: string; + time?: string; /** default: "glyphicon glyphicon-chevron-down" */ today?: string; /** default: "glyphicon glyphicon-chevron-up" */ diff --git a/types/chai-arrays/chai-arrays-tests.ts b/types/chai-arrays/chai-arrays-tests.ts new file mode 100644 index 0000000000..7fabaacbca --- /dev/null +++ b/types/chai-arrays/chai-arrays-tests.ts @@ -0,0 +1,76 @@ +import { expect } from 'chai'; +import { assert } from 'chai'; + +import chai = require('chai'); +import ChaiArrays = require('chai-arrays'); + +chai.use(ChaiArrays); +chai.should(); + +const arr: any[] = [1, 2, 3]; +const str: string = 'abcdef'; + +const otherArr: number[] = [1, 2, 3]; +const anotherArr: number[] = [2, 4]; +const yetAnotherArr: number[] = [8, 5, 7]; + +arr.should.be.array(); +str.should.not.be.array(); + +expect(arr).to.be.array(); +expect(str).not.to.be.array(); + +assert.array(arr, 'is array'); + +arr.should.be.ofSize(3); +arr.should.not.be.ofSize(4); + +expect(arr).to.be.ofSize(3); +expect(str).not.to.be.ofSize(4); + +assert.ofSize(arr, 3, 'has 3 elements'); + +arr.should.be.equalTo(otherArr); +arr.should.not.be.equalTo(anotherArr); + +expect(arr).to.be.equalTo(otherArr); +expect(str).to.be.not.equalTo(anotherArr); + +assert.equalTo(arr, otherArr, 'is equal to'); + +arr.should.be.containing(1); +arr.should.not.be.containing(4); + +expect(arr).to.be.containing(1); +expect(str).to.be.not.containing(4); + +assert.containing(arr, 1, 'contains'); + +arr.should.be.containingAllOf(otherArr); +arr.should.not.be.containingAllOf(anotherArr); + +expect(arr).to.be.containingAllOf(otherArr); +expect(str).to.be.not.containingAllOf(anotherArr); + +assert.containingAllOf(arr, otherArr, 'contains all of'); + +arr.should.be.containingAnyOf(otherArr); +arr.should.be.containingAnyOf(anotherArr); +arr.should.not.be.containingAnyOf(yetAnotherArr); + +expect(arr).to.be.containingAnyOf(otherArr); +expect(str).to.be.containingAnyOf(anotherArr); +expect(str).to.be.not.containingAnyOf(yetAnotherArr); + +assert.containingAnyOf(arr, otherArr, 'contains any of'); +assert.containingAnyOf(arr, anotherArr, 'contains any of'); + +arr.should.be.sorted(); +anotherArr.should.be.sorted(); +yetAnotherArr.should.be.sorted(); + +expect(arr).to.be.sorted(); +expect(anotherArr).to.be.sorted(); +expect(yetAnotherArr).to.be.not.sorted(); + +assert.sorted(arr, 'sorted'); diff --git a/types/chai-arrays/index.d.ts b/types/chai-arrays/index.d.ts new file mode 100644 index 0000000000..d387d1614d --- /dev/null +++ b/types/chai-arrays/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for chai-arrays 1.0 +// Project: https://github.com/GaneshSPatil/chai-arrays +// Definitions by: Clément Prévot +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare global { + namespace Chai { + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + array(): Assertion; + ofSize(size: number): Assertion; + equalTo(arr: any[]): Assertion; + containing(value: any): Assertion; + containingAllOf(values: any[]): Assertion; + containingAnyOf(values: any[]): Assertion; + sorted(): Assertion; + } + + interface Assert { + array(val: any[], msg?: string): void; + ofSize(val: any[], size: number, msg?: string): void; + equalTo(val: any[], array: any[], msg?: string): void; + containing(val: any[], value: any, msg?: string): void; + containingAllOf(val: any[], values: any[], msg?: string): void; + containingAnyOf(val: any[], values: any[], msg?: string): void; + sorted(val: any[], msg?: string): void; + } + } + + interface Array { + should: Chai.Assertion; + } +} + +declare function chaiArrays(chai: any, utils: any): void; +export = chaiArrays; diff --git a/types/chai-arrays/tsconfig.json b/types/chai-arrays/tsconfig.json new file mode 100644 index 0000000000..a555dfb8e2 --- /dev/null +++ b/types/chai-arrays/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "chai-arrays-tests.ts" + ] +} diff --git a/types/leaflet-markercluster/tslint.json b/types/chai-arrays/tslint.json similarity index 100% rename from types/leaflet-markercluster/tslint.json rename to types/chai-arrays/tslint.json diff --git a/types/chocolatechipjs/index.d.ts b/types/chocolatechipjs/index.d.ts index 0e33e087c3..4c1d49f6d1 100644 --- a/types/chocolatechipjs/index.d.ts +++ b/types/chocolatechipjs/index.d.ts @@ -438,7 +438,7 @@ interface ChocolateChipStatic { /** * Serialize */ - serialize(form: HTMLFormElement | ChocolateChipElementArray): string; + serialize(form: HTMLFormElement | ChocolateChipElementArray): string; /** * Grabs values from a form and converts them into a JSON object. @@ -862,7 +862,7 @@ interface ChocolateChipElementArray extends Array { * @param property The property to remove. * @return HTMLElement[] */ - removeProp(property: string): ChocolateChipElementArray; + removeProp(property: string): ChocolateChipElementArray; /** * Adds the specified class(es) to each of the set of matched elements. diff --git a/types/color/color-tests.ts b/types/color/color-tests.ts index fb561d4ad1..7b1a48a945 100644 --- a/types/color/color-tests.ts +++ b/types/color/color-tests.ts @@ -59,3 +59,4 @@ var chain: Color.Color = color .opaquer(0) .rotate(0) .mix(colorOther, 0) + .hsl(); diff --git a/types/color/index.d.ts b/types/color/index.d.ts index 0b7b505c01..e7e460f62a 100644 --- a/types/color/index.d.ts +++ b/types/color/index.d.ts @@ -85,6 +85,7 @@ declare namespace Color { opaquer(value: number): Color; rotate(value: number): Color; mix(color: Color, value?: number): Color; + hsl(): Color; } } diff --git a/types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts b/types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts new file mode 100644 index 0000000000..4597e2c39a --- /dev/null +++ b/types/cordova-plugin-native-keyboard/cordova-plugin-native-keyboard-tests.ts @@ -0,0 +1,43 @@ +/** + * Display Messenger + */ +NativeKeyboard.showMessenger({ + onSubmit: (text) => {}, + onKeyboardDidHide: () => {}, + onKeyboardDidShow: () => {}, + onKeyboardWillShow: () => {}, + onTextChanged: (text) => {}, + onKeyboardWillHide: () => {}, +}); + +/** + * Display Messenger Keyboard + */ +NativeKeyboard.showMessengerKeyboard( + () => {}, + () => {}); + +/** + * Hide Messenger + */ +NativeKeyboard.hideMessenger( + { animated: true}, + () => {}, + () => {}); + +NativeKeyboard.hideMessenger(); + +/** + * Hide Messenger Keyboard + */ +NativeKeyboard.hideMessengerKeyboard( + () => {}, + () => {}); + +/** + * Update Messenger Keyboard + */ +NativeKeyboard.updateMessenger( + {text: 'FooBar'}, + () => {}, + () => {}); diff --git a/types/cordova-plugin-native-keyboard/index.d.ts b/types/cordova-plugin-native-keyboard/index.d.ts new file mode 100644 index 0000000000..0f64199bd1 --- /dev/null +++ b/types/cordova-plugin-native-keyboard/index.d.ts @@ -0,0 +1,303 @@ +// Type definitions for cordova-plugin-native-keyboard 1.3 +// Project: https://github.com/EddyVerbruggen/cordova-plugin-native-keyboard#readme +// Definitions by: Daniel Brolli +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +interface NativeKeyboard { + /** + * Show the messenger, the bare minimum which has to be passed to the function is + * the onSubmit callback + * @param options + */ + showMessenger( + options: NativeKeyboardShowOptions + ): void; + + /** + * It's likely your app only has 1 one page where you want to show the messenger, + * so you want to hide it when the user navigates away. You can choose to do this + * either animated (a quick slide down animation) or not. + * + * @param options + * @param onSuccess + * @param onError + */ + hideMessenger( + options?: NativeKeyboardHideOptions, + onSuccess?: () => void, + onError?: (err: any) => void + ): void; + + /** + * Show a previously hidden keyboard + * + * @param onSuccess + * @param onError + */ + showMessengerKeyboard( + onSuccess?: () => void, + onError?: (err: any) => void, + ): void; + + /** + * Hide the keyboard, but not the messenger bar + * + * @param onSuccess + * @param onError + */ + hideMessengerKeyboard( + onSuccess?: () => void, + onError?: (err: any) => void, + ): void; + + /** + * Manipulate the messenger while it's open. For instance if you want to + * update the text programmatically based on what the user typed (by responding to + * onTextChanged events). + * + * @param options + * @param onSuccess + * @param onError + */ + updateMessenger( + options: NativeKeyboardUpdateOptions, + onSuccess?: () => void, + onError?: (err: any) => void + ): void; +} + +interface NativeKeyboardUpdateOptions { + /** + * Replace the messenger's text by this. The current text remains if omitted. + */ + text?: string; + + /** + * Position the cursor anywhere in the text range. Defaults to the end of the text. + */ + caretIndex?: number; + + /** + * If false or omitted no changes to the keyboard state are made. + */ + showKeyboard?: boolean; +} + +interface NativeKeyboardHideOptions { + /** + * A boolean flag inidicating if the keyboard should be shown/hidden with an animation + */ + animated?: boolean; +} + +interface NativeKeyboardShowOptions { + /** + * Callback function, which is being called as soon as the user submits + * @param text + */ + onSubmit(text: string): void; + + /** + * Callback function which is being executed as soon as the keyboard will show + */ + onKeyboardWillShow?(): void; + + /** + * Callback function which is being executed as soon as the keyboard did show + */ + onKeyboardDidShow?(): void; + + /** + * Callback function which is being executed as soon as the keyboard will hide + */ + onKeyboardWillHide?(): void; + + /** + * Callback function which is being executed as soon as the keyboard did hide + */ + onKeyboardDidHide?(): void; + + /** + * Callback function which is being executed as soon as the entered text changes. Will + * return the new text + * + * @param text + */ + onTextChanged?(text: string): void; + + /** + * DOM element, which should be scrolled automatically + */ + autoscrollElement?: any; + + /** + * Boolean value indicating if the content should be scrolled to the end after the messenger is + * shown + */ + scrollToBottomAfterMessengerShows?: boolean; + + /** + * Boolean value indicating if the keyboard should be kept open after submitting the entered + * text + * + * Default: false + */ + keepOpenAfterSubmit?: boolean; + + /** + * Makes the messenger bar slide in from the bottom. + * + * Default: false + */ + animated?: boolean; + + /** + * Open the keyboard when showing the messenger. + * + * Default: false + */ + showKeyboard?: boolean; + + /** + * A text which will be in the messenger bar, when opening + */ + text?: string; + + /** + * The color of the typed text in HEX. + * + * Default: #444 + */ + textColor?: string; + + /** + * A placeholder which will be in the messenger bar, when opening and the input field is + * empty + */ + placeholder?: string; + + /** + * The color of the placeholder. + * + * Default: #ccc + */ + placeholderColor?: string; + + /** + * The background color of the messenger bar. + * + * Default: #F6F6F6 + */ + backgroundColor?: string; + + /** + * The background color of the textview. Looks nicest on Android + * if it's the same color as the backgroundColor property. + * + * Default: #F6F6F6 + */ + textViewBackgroundColor?: string; + + /** + * The border color of the textview. + * + * Default: #666666 + */ + textViewBorderColor?: string; + + /** + * Maximum amount of chars that can be entered + */ + maxChars?: number; + + /** + * Options are: "none", "split", "countdown", "countdownreversed". + * Note that if maxChars is set, "none" will still show a counter. + * + * Default: "none" + */ + counterStyle?: string; + + /** + * Options are: "default", "decimalpad", "phonepad", "numberpad", "namephonepad", + * "number", "email", "twitter", "url", "alphabet", "search", "ascii" + * + * Default: "default" + */ + type?: string; + + /** + * Options are: "light", "dark". + * + * Default: "default" + */ + appearance?: string; + + /** + * Disables things like the Emoji keyboard and the Predicive text entry bar + * + * Default: false + */ + secure?: boolean; + + /** + * The left button of the messenger bar + */ + leftButton?: LeftButtonOptions; + + /** + * The right button of the messenger bar + */ + rightButton?: ButtonOptions; +} + +interface ButtonOptions { + /** + * The type of the button. + * Either "text", "fontawesome" or "ionicon". + * + * Default: "text" + */ + type?: string; + + /** + * The value of the button. On "text" the string is used as label + * On fonatawesome or ionicon the icon name is used (e.g. fa-rocket) + * + * Default: "Send" + */ + value?: string; + + /** + * If type is "text" you can set this to either "normal", "bold" or "italic". + * + * Default: "normal" + */ + textStyle?: string; + + /** + * The color of the button in HEX + * + * Default: #000 + */ + color: string; + + /** + * A callback being executed as soon as the button is clicked + */ + onPress(): void; +} + +interface LeftButtonOptions extends ButtonOptions { + /** + * Set to true to disable the button once text has been entered. + * + * Default: false + */ + disabledWhenTextEntered?: boolean; +} + +/** NativeKeyboard instance */ +declare var NativeKeyboard: NativeKeyboard; +interface Window { + NativeKeyboard: NativeKeyboard; +} diff --git a/types/cordova-plugin-native-keyboard/tsconfig.json b/types/cordova-plugin-native-keyboard/tsconfig.json new file mode 100644 index 0000000000..4309b2406b --- /dev/null +++ b/types/cordova-plugin-native-keyboard/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cordova-plugin-native-keyboard-tests.ts" + ] +} diff --git a/types/cordova-plugin-native-keyboard/tslint.json b/types/cordova-plugin-native-keyboard/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cordova-plugin-native-keyboard/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cordova-plugin-qrscanner/cordova-plugin-qrscanner-tests.ts b/types/cordova-plugin-qrscanner/cordova-plugin-qrscanner-tests.ts index 009b0b7d2b..fe14bae63c 100644 --- a/types/cordova-plugin-qrscanner/cordova-plugin-qrscanner-tests.ts +++ b/types/cordova-plugin-qrscanner/cordova-plugin-qrscanner-tests.ts @@ -3,7 +3,7 @@ var QRScanner: QRScanner = window.QRScanner; QRScanner.prepare(); QRScanner.prepare((err, status) => { var error: QRScannerError = err; var obj: QRScannerStatus = status; }); -QRScanner.scan((err, results) => { var error: QRScannerError = err; var contents: String = results; }); +QRScanner.scan((err, results) => { var error: QRScannerError = err; var contents: string = results; }); QRScanner.cancelScan(); QRScanner.cancelScan((status) => {var obj: QRScannerStatus = status; }); QRScanner.show(); @@ -31,12 +31,12 @@ QRScanner.destroy((status) => {var obj: QRScannerStatus = status; }); QRScanner.prepare((err, status) => { var error: QRScannerError = err; - var num: Number = error.code; - var str: String = error.name; + var num: number = error.code; + var str: string = error.name; str = error._message; var obj: QRScannerStatus = status; - var bool: Boolean = status.authorized; + var bool: boolean = status.authorized; bool = status.denied; bool = status.restricted; bool = status.prepared; @@ -46,5 +46,5 @@ QRScanner.prepare((err, status) => { bool = status.lightEnabled; bool = status.canOpenSettings; bool = status.canEnableLight; - var num: Number = status.currentCamera; + var num: number = status.currentCamera; }); diff --git a/types/cordova-plugin-qrscanner/index.d.ts b/types/cordova-plugin-qrscanner/index.d.ts index ed5f72f26f..0f2a498a9c 100644 --- a/types/cordova-plugin-qrscanner/index.d.ts +++ b/types/cordova-plugin-qrscanner/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for cordova-plugin-qrscanner v1.0.0 +// Type definitions for cordova-plugin-qrscanner v1.0.1 // Project: https://github.com/bitpay/cordova-plugin-qrscanner // Definitions by: Jason Dreyzehner +// Josh Bronson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** @@ -32,7 +33,7 @@ interface QRScanner { * not need to be visible for scanning to function. * @param {function} callback Callback that gets an error or the results string. */ - scan: (callback: (error: QRScannerError, result: String) => any) => void; + scan: (callback: (error: QRScannerError, result: string) => any) => void; /** * Cancels the current scan. If `QRScanner.prepare()` has not been called, @@ -82,7 +83,7 @@ interface QRScanner { * @param {number} index A number representing the index of the camera to use. * @param {function} [callback] Callback that gets an error or the QRScannerStatus object. */ - useCamera: (index: Number, callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void; + useCamera: (index: number, callback?: (error: QRScannerError, status: QRScannerStatus) => any) => void; /** * Switch video capture to the device's front camera. If `QRScanner.prepare()` @@ -150,7 +151,7 @@ interface QRScannerStatus { * (`AVAuthorizationStatus.Authorized`). On platforms with permissions granted * at install (Android pre-6.0, Windows Phone) this property is always true. */ - authorized: Boolean, + authorized: boolean, /** * A boolean value which is true if the user permenantly denied camera access @@ -158,59 +159,59 @@ interface QRScannerStatus { * only be gained by requesting the user change their decision (consider * offering a link to the setting via `openSettings()`). */ - denied: Boolean, + denied: boolean, /** * A boolean value which is true if the user is unable to grant permissions due * to parental controls, organization security configuration profiles, or * similar reasons. */ - restricted: Boolean, + restricted: boolean, /** * A boolean value which is true if QRScanner is prepared to capture video and * render it to the view. */ - prepared: Boolean, + prepared: boolean, /** * A boolean value which is true if QRScanner is actively scanning for a QR code. */ - scanning: Boolean, + scanning: boolean, /** * A boolean value which is true if QRScanner is displaying a live preview * from the device's camera. Set to false when the preview is paused. */ - previewing: Boolean, + previewing: boolean, /** * A boolean value which is true when the native webview background is transparent. */ - webviewBackgroundIsTransparent: Boolean, + webviewBackgroundIsTransparent: boolean, /** * A boolean value which is true if the light is enabled. */ - lightEnabled: Boolean, + lightEnabled: boolean, /** * A boolean value which is true only if the users' operating system is able * to `QRScanner.openSettings()`. */ - canOpenSettings: Boolean, + canOpenSettings: boolean, /** * A boolean value which is true only if the users' device can enable a light * in the direction of the currentCamera. */ - canEnableLight: Boolean, + canEnableLight: boolean, /** * A number representing the index of the currentCamera. `0` is the back * camera, `1` is the front. */ - currentCamera: Number + currentCamera: number } /** @@ -218,8 +219,8 @@ interface QRScannerStatus { * * Many QRScanner functions accept a callback with an `error` parameter. When * QRScanner experiences errors, this parameter contains a QRScannerError object -* with properties `name` (_String_), `code` (_Number_), and `_message` -* (_String_). When handling errors, rely only on the `name` or `code` parameter, +* with properties `name` (_string_), `code` (_number_), and `_message` +* (_string_). When handling errors, rely only on the `name` or `code` parameter, *as the specific content of `_message` is not considered part of the plugin's * stable API. * @@ -242,17 +243,17 @@ interface QRScannerError { /** * The standard string identifying the type of this QRScannerError. */ - name: String, + name: string, /** * The standard number identifying the type of this QRScannerError. */ - code: Number, + code: number, /** * A simple message describing this QRScannerError. */ - _message: String + _message: string } declare var QRScanner: QRScanner; diff --git a/types/cucumber/cucumber-tests.ts b/types/cucumber/cucumber-tests.ts index 379922d1a7..53ca726230 100644 --- a/types/cucumber/cucumber-tests.ts +++ b/types/cucumber/cucumber-tests.ts @@ -7,7 +7,7 @@ function StepSample() { type HookScenarioResult = cucumber.HookScenarioResult; cucumber.defineSupportCode(function ({setWorldConstructor, defineParameterType, After, Around, Before, registerHandler, Given, When, Then}) { - setWorldConstructor(function ({attach, parameters}) { + setWorldConstructor(function ({attach, parameters}: any) { this.attach = attach; this.parameters = parameters; this.visit = function (url: string, callback: Callback) { @@ -19,7 +19,7 @@ function StepSample() { console.log(scenarioResult.status === "failed"); callback(); }); - + Before({ timeout: 1000 }, function (scenarioResult: HookScenarioResult, callback: Callback) { console.log(scenarioResult.status === "failed"); callback(); @@ -35,7 +35,7 @@ function StepSample() { console.log("After"); callback(); }); - + After({ timeout: 1000 }, (scenarioResult: HookScenarioResult, callback?: Callback) => { console.log("After"); callback(); @@ -48,7 +48,7 @@ function StepSample() { Given(/^a variable set to (\d+)$/, (x: string) => { console.log("the number is: " + x); }); - + Given(/^a variable set to (\d+)$/, (x: number) => { console.log(typeof x); }); diff --git a/types/cwise-compiler/cwise-compiler-tests.ts b/types/cwise-compiler/cwise-compiler-tests.ts new file mode 100644 index 0000000000..38e19de886 --- /dev/null +++ b/types/cwise-compiler/cwise-compiler-tests.ts @@ -0,0 +1,76 @@ +/// + +import * as parse from 'cwise-parser'; +import * as ndarray from 'ndarray'; +import * as compile from 'cwise-compiler'; +import * as tape from 'tape'; + +tape("block tests", (t) => { + const ops = require('ndarray-ops'); + const body2 = parse((a: number, b: number[]) => { + a = b[0] + b[1] + 1; + }); + const body23 = parse((a: number, b: number[][]) => { + a = b[0][0] * b[1][0] + b[0][1] * b[1][1] + b[0][2] * b[1][2]; + }); + + // Test with block index at the front of the indices + const c1 = compile({ + args: ["array", { blockIndices: 1 }], + pre: parse(() => { }), + body: body2, + post: parse(() => { }), + debug: false, + funcName: "cwise", + blockSize: 64 + }); + + const a1 = ndarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [3, 4]); + const b1 = ndarray([57, 17, 95, 78, 16, 96, 85, 93, 38, 42, 16, 66, 23, 77, 17, 36, 30, 52, 16, 18, 23, 69, 67, 27], [2, 3, 4]); + const ref1 = ndarray([81, 95, 113, 115, 47, 149, 102, 112, 62, 112, 84, 94], [3, 4]); + + c1(a1, b1); + + t.ok(ops.equals(a1, ref1), "front block"); + + // Test with block index at the back of the indices + const c2 = compile({ + args: ["array", { blockIndices: -1 }], + pre: parse(() => { }), + body: body2, + post: parse(() => { }), + debug: false, + funcName: "cwise", + blockSize: 64 + }); + + const a2 = ndarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [3, 4]); + const b2 = ndarray([57, 17, 95, 78, 16, 96, 85, 93, 38, 42, 16, 66, 23, 77, 17, 36, 30, 52, 16, 18, 23, 69, 67, 27], [3, 4, 2]); + const ref2 = ndarray([75, 174, 113, 179, 81, 83, 101, 54, 83, 35, 93, 95], [3, 4]); + + c2(a2, b2); + + t.ok(ops.equals(a2, ref2), "back block"); + + // Multiple block indices + const c3 = compile({ + args: ["array", { blockIndices: -2 }], + pre: parse(() => { }), + body: body23, + post: parse(() => { }), + debug: false, + funcName: "cwise", + blockSize: 64 + }); + const a3 = ndarray([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], [3, 4]); + const b3 = ndarray([48, 46, 89, 64, 72, 96, 38, 37, 79, 92, 89, 62, 84, 41, 13, 81, 53, 30, 68, 78, 34, 81, 90, 50, + 82, 97, 46, 18, 11, 79, 15, 68, 88, 58, 71, 84, 76, 35, 74, 82, 27, 47, 59, 25, 78, 61, 10, 43, + 96, 59, 21, 74, 41, 67, 11, 72, 38, 62, 95, 66, 57, 44, 93, 10, 51, 59, 50, 85, 71, 41, 79, 45], [3, 4, 2, 3]); + const ref = ndarray([14928, 11687, 9367, 14228, 6177, 13090, 10655, 7203, 10930, 10030, 8301, 11960], [3, 4]); + + c3(a3, b3); + + t.ok(ops.equals(a3, ref), "block with two indices"); + + t.end(); +}); diff --git a/types/cwise-compiler/index.d.ts b/types/cwise-compiler/index.d.ts new file mode 100644 index 0000000000..e661934a6a --- /dev/null +++ b/types/cwise-compiler/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for cwise-compiler 1.1 +// Project: https://github.com/scijs/cwise-compiler +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { CompiledRoutine } from 'cwise-parser'; +import * as ndarray from 'ndarray'; + +declare namespace cwise_compiler { + interface BlockIndice { + blockIndices: number; + } + interface OffsetArg { + offset: number[]; + array: number; + } + type ArgType = 'array' | 'offset' | 'shape' | 'scalar' | 'index' | BlockIndice | OffsetArg; + interface UserArgs { + args: ArgType[]; + pre: CompiledRoutine; + body: CompiledRoutine; + post: CompiledRoutine; + debug: boolean; + funcName: string; + blockSize: number; + printCode?: boolean; + } + interface Procedure { + argTypes: ArgType[]; + shimArgs: string[]; + arrayArgs: number[]; + arrayBlockIndices: number[]; + scalarArgs: number[]; + offsetArgs: OffsetArg[]; + offsetArgIndex: number[]; + indexArgs: number[]; + shapeArgs: number[]; + funcName: string; + pre: CompiledRoutine; + body: CompiledRoutine; + post: CompiledRoutine; + debug: boolean; + blockSize?: number; + } +} + +declare function cwise_compiler(user_args: cwise_compiler.UserArgs): (a: ndarray, b: ndarray, ...args: ndarray[]) => ndarray; + +export = cwise_compiler; diff --git a/types/cwise-compiler/tsconfig.json b/types/cwise-compiler/tsconfig.json new file mode 100644 index 0000000000..a78923fa03 --- /dev/null +++ b/types/cwise-compiler/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cwise-compiler-tests.ts" + ] +} diff --git a/types/cwise-compiler/tslint.json b/types/cwise-compiler/tslint.json new file mode 100644 index 0000000000..531fb4ef87 --- /dev/null +++ b/types/cwise-compiler/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/cwise-parser/cwise-parser-tests.ts b/types/cwise-parser/cwise-parser-tests.ts new file mode 100644 index 0000000000..c50b9be06a --- /dev/null +++ b/types/cwise-parser/cwise-parser-tests.ts @@ -0,0 +1,26 @@ +import * as parser from "cwise-parser"; +// import parser = require("cwise-parser"); +import * as tape from "tape"; + +tape("basic tests", (t) => { + const parsed = parser((a: number, b: number, c: number) => { + a += b; + c = Math.cos(b); + }); + + t.equals(parsed.args.length, 3); + + t.equals(parsed.args[0].lvalue, true); + t.equals(parsed.args[0].rvalue, true); + t.equals(parsed.args[0].count, 1); + + t.equals(parsed.args[1].lvalue, false); + t.equals(parsed.args[1].rvalue, true); + t.equals(parsed.args[1].count, 2); + + t.equals(parsed.args[2].lvalue, true); + t.equals(parsed.args[2].rvalue, false); + t.equals(parsed.args[2].count, 1); + + t.end(); +}); diff --git a/types/cwise-parser/index.d.ts b/types/cwise-parser/index.d.ts new file mode 100644 index 0000000000..d2a06fd7f1 --- /dev/null +++ b/types/cwise-parser/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for cwise-parser 1.0 +// Project: https://github.com/scijs/cwise-parser#readme +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace cwise_parser { + interface CompiledArgument { + name: string; + lvalue: boolean; + rvalue: boolean; + count: number; + } + interface CompiledRoutine { + body: string; + args: CompiledArgument[]; + thisVars: string[]; + localVars: string[]; + } +} + +declare function cwise_parser(func: (a: number, ...args: T[]) => any): cwise_parser.CompiledRoutine; +export = cwise_parser; diff --git a/types/cwise-parser/tsconfig.json b/types/cwise-parser/tsconfig.json new file mode 100644 index 0000000000..ce6c3c1355 --- /dev/null +++ b/types/cwise-parser/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cwise-parser-tests.ts" + ] +} diff --git a/types/cwise-parser/tslint.json b/types/cwise-parser/tslint.json new file mode 100644 index 0000000000..531fb4ef87 --- /dev/null +++ b/types/cwise-parser/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/cwise/cwise-tests.ts b/types/cwise/cwise-tests.ts new file mode 100644 index 0000000000..66843adfe2 --- /dev/null +++ b/types/cwise/cwise-tests.ts @@ -0,0 +1,366 @@ +import * as cwise from 'cwise'; +import * as ndarray from 'ndarray'; +import * as tape from 'tape'; + +// basic +tape("only allow same shape", (t) => { + const op1 = cwise({ + args: ["array"], + body: (a: number) => { a = 1; } + }); + const op2 = cwise({ + args: ["array", "array"], + body: (a: number, b: number) => { a = b; } + }); + const op3 = cwise({ + args: ["array", "array", "array"], + body: (a: number, b: number, c: number) => { a = b + c; } + }); + const op2block_pos = cwise({ + args: ["array", { blockIndices: 1 }], + body: (a: number, b: number[]) => { a = b[1]; } + }); + const op2block_neg = cwise({ + args: ["array", { blockIndices: -1 }], + body: (a: number, b: number[]) => { a = b[1]; } + }); + + t.doesNotThrow(() => { op1(ndarray([1, 2, 3], [3])); }); + t.doesNotThrow(() => { op2(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3])); }); + t.doesNotThrow(() => { op2(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + t.doesNotThrow(() => { op3(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3])); }); + t.doesNotThrow(() => { op2block_pos(ndarray([1, 2], [2]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + t.doesNotThrow(() => { op2block_neg(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + + t.throws(() => { op2(ndarray([1, 2, 3], [3]), ndarray([1, 2], [2])); }); + t.throws(() => { op2(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3], [3, 1])); }); + t.throws(() => { op2(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4], [2, 2])); }); + t.throws(() => { op3(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3]), ndarray([1, 2], [2])); }); + t.throws(() => { op3(ndarray([1, 2, 3], [3]), ndarray([1, 2], [2]), ndarray([1, 2, 3], [3])); }); + t.throws(() => { op3(ndarray([1, 2], [2]), ndarray([1, 2, 3], [3]), ndarray([1, 2, 3], [3])); }); + t.throws(() => { op2block_pos(ndarray([1, 2, 3], [3]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + t.throws(() => { op2block_neg(ndarray([1, 2], [2]), ndarray([1, 2, 3, 4, 5, 6], [3, 2])); }); + t.throws(() => { op2block_pos(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4], [2, 2])); }); + t.throws(() => { op2block_neg(ndarray([1, 2, 3, 4, 5, 6], [3, 2]), ndarray([1, 2, 3, 4], [2, 2])); }); + + t.end(); +}); + +// binarry +class DumbStorage { + data: Int32Array; + length: number; + constructor(n: number) { + this.data = new Int32Array(n); + this.length = n; + } + get(i: number) { + return this.data[i]; + } + set(i: number, v: number) { + return this.data[i] = v; + } +} + +tape("binary", (t) => { + const binary = cwise({ + args: ["array", "array", "scalar", "shape", "index"], + body(a: number, b: number, t: tape.Test, s: number[], idx: number) { + if (!(a === 0)) t.fail("idx:" + idx + ", shape:" + s + ",a:" + a); + a = b + 1001; + } + }); + + function testBinary1D(P: ndarray, Q: ndarray, testName: string) { + t.equals(P.shape[0], Q.shape[0], testName + "; shape"); + for (let i = 0; i < P.shape[0]; ++i) { + Q.set(i, i); + P.set(i, 0); + } + binary(P, Q, t); + for (let i = 0; i < P.shape[0]; ++i) { + if (!(P.get(i) === i + 1001)) { + t.fail(testName + "; encountered " + P.get(i) + " instead of " + (i + 1001) + " at " + i); + return; + } + } + t.pass(testName); + } + + const A1 = ndarray(new Int32Array(128)); + const B1 = ndarray(new Int32Array(128)); + + testBinary1D(ndarray(new Int32Array(0)), ndarray(new Int32Array(0)), "length==0"); + testBinary1D(ndarray(new Int32Array(1)), ndarray(new Int32Array(1)), "length==1"); + testBinary1D(A1, B1, "A, B"); + testBinary1D(A1.lo(32), B1.hi(128 - 32), "A.lo(32), B.hi(128-32)"); + testBinary1D(A1.step(-1), B1, "A.step(-1), B"); + testBinary1D(A1, B1.step(-1), "A, B.step(-1)"); + + const A2 = ndarray(new DumbStorage(128) as any); + const B2 = ndarray(new DumbStorage(128) as any); + testBinary1D(ndarray(new DumbStorage(0) as any), ndarray(new DumbStorage(0) as any), "DS; length==0"); + testBinary1D(ndarray(new DumbStorage(1) as any), ndarray(new DumbStorage(1) as any), "DS; length==0"); + testBinary1D(A2, B2, "DS; A, B"); + testBinary1D(A2.lo(32), B2.hi(128 - 32), "DS; A.lo(32), B.hi(128-32)"); + testBinary1D(A2.step(-1), B2, "DS; A.step(-1), B"); + testBinary1D(A2, B2.step(-1), "DS; A, B.step(-1)"); + + const X = ndarray(new Int32Array(64 * 64), [64, 64]); + const Y = ndarray(new Int32Array(64 * 64), [64, 64]); + + function testBinary2D(P: ndarray, Q: ndarray, testName: string) { + for (let i = 0; i < X.shape[0]; ++i) { + for (let j = 0; j < X.shape[1]; ++j) { + X.set(i, j, -10000); + Y.set(i, j, -256); + } + } + t.equals(P.shape[0], Q.shape[0], testName + "; shape[0]"); + t.equals(P.shape[1], Q.shape[1], testName + "; shape[1]"); + for (let i = 0; i < P.shape[0]; ++i) { + for (let j = 0; j < P.shape[1]; ++j) { + Q.set(i, j, i * 1000 + j); + P.set(i, j, 0); + } + } + binary(P, Q, t, P.shape); + for (let i = 0; i < P.shape[0]; ++i) { + for (let j = 0; j < P.shape[1]; ++j) { + if (!(P.get(i, j) === i * 1000 + j + 1001)) { + t.fail(testName + "; encountered " + P.get(i, j) + " instead of " + (i * 1000 + j + 1001) + " at (" + i + "," + j + ")"); + return; + } + } + } + t.pass(testName); + } + + testBinary2D(X, Y, "X, Y"); + testBinary2D(X.transpose(1, 0), Y.transpose(1, 0), "X.T, Y.T"); + testBinary2D(X.transpose(1, 0), Y, "X.T, Y"); + testBinary2D(X, Y.transpose(1, 0), "X, Y.T"); + testBinary2D(X.hi(32, 32), Y.hi(32, 32), "X.hi(32,32), Y.hi(32,32)"); + testBinary2D(X.hi(31, 31), Y.hi(31, 31), "X.hi(31,31), Y.hi(31,31)"); + testBinary2D(X.hi(0, 32), Y.hi(0, 32), "X.hi(0,32), Y.hi(0,32)"); + testBinary2D(X.transpose(1, 0).hi(0, 32), Y.hi(0, 32), "X.T.hi(0,32), Y.hi(0,32)"); + testBinary2D(X.transpose(1, 0).hi(33, 33), Y.hi(33, 33), "X.T.hi(33,33), Y.hi(33,33)"); + testBinary2D(X.transpose(1, 0).hi(31, 31), Y.hi(31, 31), "X.T.hi(31,31), Y.hi(31,31)"); + + t.end(); +}); + +// browserify +import * as browserify from "browserify"; +import * as vm from 'vm'; +import * as path from 'path'; + +const cases = ["unary", "binary", "offset", "fill"]; + +bundleCasesFrom(0); + +function bundleCasesFrom(i: number) { + if (i >= cases.length) return; + const b = browserify(); + b.ignore("tape"); + b.add(__dirname + "/" + cases[i] + ".js"); + b.transform(path.normalize(__dirname + "/../cwise.js")); + tape(cases[i], (t) => { // Without nested tests, the asynchronous nature of bundle causes issues with tape... + b.bundle((err, src) => { + if (err) { + throw new Error("failed to bundle!"); + } + vm.runInNewContext(src.toString(), { + test: t.test.bind(t), + Buffer, + Int8Array, + Int16Array, + Int32Array, + Float32Array, + Float64Array, + Uint8Array, + Uint16Array, + Uint32Array, + Uint8ClampedArray, + console: { log: console.log.bind(console) } + }); + t.end(); + }); + }); + bundleCasesFrom(i + 1); +} + +// fill +tape("fill", (t) => { + const fill = cwise({ + args: ["index", "array", "scalar"], + body(idx, out, f) { + out = f.apply(undefined, idx); + } + }); + + const xlen = 10; + const ylen = 5; + const array = ndarray(new Float32Array(xlen * ylen), [xlen, ylen]); + + fill(array, (row: number, col: number) => { + return 0; + }); + + for (let i = 0; i < xlen; i++) { + for (let j = 0; j < ylen; j++) { + t.equals(array.get(i, j), 0, 'fill (' + i + ',' + j + ')'); + } + } + + fill(array, (row: number, col: number) => { + return 10 * (row + col); + }); + + for (let i = 0; i < xlen; i++) { + for (let j = 0; j < ylen; j++) { + t.equals(array.get(i, j), 10 * (i + j), 'fill (' + i + ',' + j + ')'); + } + } + + t.end(); +}); + +// offset +tape("offset", (t) => { + const binary = cwise({ + args: ["array", "array", { offset: [1], array: 1 }, "scalar", "shape", "index"], + body(a, b, c, t, s, idx) { + if (!(a === 0)) t.fail("idx:" + idx + ", shape:" + s + ",a:" + a); + a = c + b + 1000; + } + }); + + function testBinary1D(P: ndarray, Q: ndarray, testName: string) { + t.equals(P.shape[0], Q.shape[0] - 1, testName + "; shape"); + for (let i = 0; i < P.shape[0]; ++i) { + Q.set(i, i); + P.set(i, 0); + } + Q.set(P.shape[0], P.shape[0]); + binary(P, Q.hi(Q.shape[0] - 1), t); + for (let i = 0; i < P.shape[0]; ++i) { + if (!(P.get(i) === 2 * i + 1001)) { + t.fail(testName + "; encountered " + P.get(i) + " instead of " + (2 * i + 1001) + " at " + i); + return; + } + } + t.pass(testName); + } + + const A1 = ndarray(new Int32Array(128)); + const B1 = ndarray(new Int32Array(129)); + + testBinary1D(ndarray(new Int32Array(0)), ndarray(new Int32Array(1)), "length==0"); + testBinary1D(ndarray(new Int32Array(1)), ndarray(new Int32Array(2)), "length==1"); + testBinary1D(A1, B1, "A, B"); + testBinary1D(A1.lo(32), B1.lo(32), "A.lo(32), B.lo(32)"); + testBinary1D(A1.step(-1), B1, "A.step(-1), B"); + testBinary1D(A1, B1.step(-1), "A, B.step(-1)"); + + const A2 = ndarray(new DumbStorage(128) as any); + const B2 = ndarray(new DumbStorage(129) as any); + testBinary1D(ndarray(new DumbStorage(0) as any), ndarray(new DumbStorage(1) as any), "DS; length==0"); + testBinary1D(ndarray(new DumbStorage(1) as any), ndarray(new DumbStorage(2) as any), "DS; length==1"); + testBinary1D(A2, B2, "DS; A, B"); + testBinary1D(A2.lo(32), B2.lo(32), "DS; A.lo(32), B.lo(32)"); + testBinary1D(A2.step(-1), B2, "DS; A.step(-1), B"); + testBinary1D(A2, B2.step(-1), "DS; A, B.step(-1)"); + + t.end(); +}); + +// unary + +tape("unary", (t) => { + const unary = cwise({ + args: ["array"], + body(a) { + ++a; + } + }); + + function testUnary1D(arr: ndarray, testName: string) { + for (let i = 0; i < arr.shape[0]; ++i) { + arr.set(i, i); + } + unary(arr); + for (let i = 0; i < arr.shape[0]; ++i) { + if (!(arr.get(i) === i + 1)) { + t.fail(testName + "; encountered " + arr.get(i) + " instead of " + (i + 1) + " at " + i); + return; + } + } + t.pass(testName); + } + const simple_zeros = ndarray(new Int32Array(4096)); + + testUnary1D(simple_zeros.hi(0), "simple_zeros.hi(0)"); + testUnary1D(simple_zeros.hi(1), "simple_zeros.hi(1)"); + testUnary1D(simple_zeros.hi(2), "simple_zeros.hi(2)"); + testUnary1D(simple_zeros, "simple_zeros"); + testUnary1D(simple_zeros.hi(31), "simple_zeros.hi(31)"); + testUnary1D(simple_zeros.hi(32), "simple_zeros.hi(32)"); + testUnary1D(simple_zeros.hi(33), "simple_zeros.hi(33)"); + testUnary1D(simple_zeros.step(-1), "simple_zeros.step(-1)"); + testUnary1D(simple_zeros.step(3), "simple_zeros.step(3)"); + testUnary1D(simple_zeros.step(4), "simple_zeros.step(4)"); + testUnary1D(simple_zeros.step(5).lo(10), "simple_zeros.step(5).lo(10)"); + + const custom_zeros = ndarray(new DumbStorage(4096) as any); + + testUnary1D(custom_zeros.hi(0), "custom_zeros.hi(0)"); + testUnary1D(custom_zeros.hi(1), "custom_zeros.hi(1)"); + testUnary1D(custom_zeros.hi(2), "custom_zeros.hi(2)"); + testUnary1D(custom_zeros, "custom_zeros"); + testUnary1D(custom_zeros.hi(31), "custom_zeros.hi(31)"); + testUnary1D(custom_zeros.hi(32), "custom_zeros.hi(32)"); + testUnary1D(custom_zeros.hi(33), "custom_zeros.hi(33)"); + testUnary1D(custom_zeros.step(-1), "custom_zeros.step(-1)"); + testUnary1D(custom_zeros.step(3), "custom_zeros.step(3)"); + testUnary1D(custom_zeros.step(4), "custom_zeros.step(4)"); + testUnary1D(custom_zeros.step(5).lo(10), "custom_zeros.step(5).lo(10)"); + + function testUnary2D(arr: ndarray, testName: string) { + for (let i = 0; i < arr.shape[0]; ++i) { + for (let j = 0; j < arr.shape[1]; ++j) { + arr.set(i, j, i + j * arr.shape[0]); + } + } + unary(arr); + for (let i = 0; i < arr.shape[0]; ++i) { + for (let j = 0; j < arr.shape[1]; ++j) { + if (!(arr.get(i, j) === 1 + i + j * arr.shape[0])) { + t.fail(testName + "; encountered " + arr.get(i, j) + " instead of " + (1 + i + j * arr.shape[0]) + " at (" + i + "," + j + ")"); + return; + } + } + } + t.pass(testName); + } + + const M1 = ndarray(new Int32Array(128 * 128), [128, 128]); + testUnary2D(M1, "M"); + testUnary2D(M1.hi(10, 10), "M.hi(10, 10)"); + testUnary2D(M1.lo(100, 1), "M.lo(100,1)"); + testUnary2D(M1.transpose(1, 0), "M.transpose(1,0)"); + testUnary2D(M1.step(-1, 1), "M.step(-1, 1)"); + testUnary2D(M1.step(-5, -2), "M.step(-5, -2)"); + testUnary2D(M1.step(16, 3), "M.step(16, 3)"); + + const M2 = ndarray(new DumbStorage(128 * 128) as any, [128, 128]); + testUnary2D(M2, "DS; M"); + testUnary2D(M2.hi(10, 10), "DS; M.hi(10, 10)"); + testUnary2D(M2.lo(100, 1), "DS; M.lo(100,1)"); + testUnary2D(M2.transpose(1, 0), "DS; M.transpose(1,0)"); + testUnary2D(M2.step(-1, 1), "DS; M.step(-1, 1)"); + testUnary2D(M2.step(-5, -2), "DS; M.step(-5, -2)"); + testUnary2D(M2.step(16, 3), "DS; M.step(16, 3)"); + + t.end(); +}); diff --git a/types/cwise/index.d.ts b/types/cwise/index.d.ts new file mode 100644 index 0000000000..d99d43ce59 --- /dev/null +++ b/types/cwise/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for cwise 1.0 +// Project: https://github.com/scijs/cwise#readme +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { ArgType } from "cwise-compiler"; +import * as ndarray from "ndarray"; + +declare function cwise(a: string | cwise.UserArgs): cwise.Return; + +declare namespace cwise { + type Arg = ndarray | ((row: number, col: number) => number) | number[] | any; + type Return = (a: ndarray, ...b: Arg[]) => void; + interface UserArgs { + args: ArgType[]; + pre?(a: number, ...args: any[]): void; + body(a: number, ...args: any[]): void; + post?(a: number, ...args: any[]): void; + funcName?: string; + blockSize?: number; + printCode?: boolean; + } +} +export = cwise; diff --git a/types/cwise/tsconfig.json b/types/cwise/tsconfig.json new file mode 100644 index 0000000000..f4aaf9b1a3 --- /dev/null +++ b/types/cwise/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cwise-tests.ts" + ] +} \ No newline at end of file diff --git a/types/cwise/tslint.json b/types/cwise/tslint.json new file mode 100644 index 0000000000..531fb4ef87 --- /dev/null +++ b/types/cwise/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/d3-contour/d3-contour-tests.ts b/types/d3-contour/d3-contour-tests.ts new file mode 100644 index 0000000000..751dfe99c9 --- /dev/null +++ b/types/d3-contour/d3-contour-tests.ts @@ -0,0 +1,189 @@ +/** + * Typescript definition tests for d3/d3-contour module + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +import * as d3Contour from 'd3-contour'; +import { + range, + thresholdSturges, + ThresholdArrayGenerator, + ThresholdCountGenerator +} from 'd3-array'; +import { geoPath } from 'd3-geo'; +import { randomNormal } from 'd3-random'; + +// ----------------------------------------------------------------------------- +// Preparatory Steps +// ----------------------------------------------------------------------------- + +// Some test setup is based on Contour Plot II Golstein-Price function at https://bl.ocks.org/mbostock/f48ff9c1af4d637c9a518727f5fdfef5 + +const n = 256; +const m = 256; +const values: number[] = new Array(n * m); +for (let j = 0.5, k = 0; j < m; ++j) { + for (let i = 0.5; i < n; ++i, ++k) { + values[k] = goldsteinPrice(i / n * 4 - 2, 1 - j / m * 3); + } +} + +function goldsteinPrice(x: number, y: number) { + return (1 + Math.pow(x + y + 1, 2) * (19 - 14 * x + 3 * x * x - 14 * y + 6 * x * x + 3 * y * y)) + * (30 + Math.pow(2 * x - 3 * y, 2) * (18 - 32 * x + 12 * x * x + 48 * y - 36 * x * y + 27 * y * y)); +} + +let size: [number, number]; +let boolFlag: boolean; +const thresholdArrayGen: ThresholdArrayGenerator = (values: number[], min: number, max: number) => { + let thresholds: number[]; + thresholds = [values[1], values[2], values[4]]; + return thresholds; +}; + +let thresholdGenerator: ThresholdArrayGenerator | ThresholdCountGenerator; +let pathStringMaybe: string | null; +let num: number; + +const pathSolo = geoPath(); + +// ----------------------------------------------------------------------------- +// Test Contour Generator +// ----------------------------------------------------------------------------- + +// Get contour generator ------------------------------------------------------- + +let contGen: d3Contour.Contours = d3Contour.contours(); + +// Configure contour generator ================================================= + +// size(...) ------------------------------------------------------------------- + +// set with chainability +contGen = contGen.size([n, m]); + +size = contGen.size(); + +// smooth(...) ----------------------------------------------------------------- + +// set with chainability +contGen = contGen.smooth(true); + +boolFlag = contGen.smooth(); + +// thresholds(...) ------------------------------------------------------------- + +// set with count +contGen = contGen.thresholds(10); + +// set with array +const thresholds1 = range(1, 21) + .map(p => Math.pow(2, p)); +contGen = contGen.thresholds(thresholds1); + +// set with threshold array generator + +contGen = contGen.thresholds(thresholdArrayGen); // mock + +// set with threshold count generator + +contGen = contGen.thresholds(thresholdSturges); + +// get +thresholdGenerator = contGen.thresholds(); + +// Use contour generator ======================================================= + +pathStringMaybe = pathSolo(contGen(values)[0]); + +// ----------------------------------------------------------------------------- +// Test Contour Generator for Density Estimates +// ----------------------------------------------------------------------------- + +interface CustomDatum { + x: number; + y: number; +} + +// Get contour generator ------------------------------------------------------- + +let contDensDefault: d3Contour.ContourDensity<[number, number]> = d3Contour.contourDensity(); +let contDensCustom: d3Contour.ContourDensity = d3Contour.contourDensity(); + +// Configure contour generator ================================================= + +// x(...) ---------------------------------------------------------------------- + +// set with chainability +contDensCustom = contDensCustom.x((datum) => { + const d: CustomDatum = datum; // check passed in argument type + return d.x; +}); + +// get +const xAcc: (d: CustomDatum) => number = contDensCustom.x(); + +// y(...) ---------------------------------------------------------------------- + +// set with chainability +contDensCustom = contDensCustom.y((datum) => { + const d: CustomDatum = datum; // check passed in argument type + return d.y; +}); + +// get +const yAcc: (d: CustomDatum) => number = contDensCustom.y(); + +// size(...) ------------------------------------------------------------------- + +// set with chainability +contDensCustom = contDensCustom.size([900, 600]); + +size = contDensCustom.size(); + +// cellSize(...) ----------------------------------------------------------------- + +// set with chainability +contDensCustom = contDensCustom.cellSize(3); + +num = contDensCustom.cellSize(); + +// thresholds(...) ------------------------------------------------------------- + +// set with count +contDensCustom = contDensCustom.thresholds(10); + +// set with array +contDensCustom = contDensCustom.thresholds([0.1, 0.25, 0.5, 0.75, 1]); + +// set with threshold array generator +contDensCustom = contDensCustom.thresholds(thresholdArrayGen); // mock + +// set with threshold count generator +contDensCustom = contDensCustom.thresholds(thresholdSturges); + +// get +thresholdGenerator = contDensCustom.thresholds(); + +// bandwidth(...) -------------------------------------------------------------- +// set with chainability +contDensCustom = contDensCustom.bandwidth(40); +// get +num = contDensCustom.bandwidth(); + +// Use contour generator ======================================================= + +const indNorm: CustomDatum[] = []; +const rX = randomNormal(); +const rY = randomNormal(1, 2); +for (let i = 0; i < 1000; i++) { + indNorm.push({ + x: rX(), + y: rY() + }); +} + +pathStringMaybe = pathSolo(contDensCustom(indNorm)[0]); diff --git a/types/d3-contour/index.d.ts b/types/d3-contour/index.d.ts new file mode 100644 index 0000000000..789ff32a5f --- /dev/null +++ b/types/d3-contour/index.d.ts @@ -0,0 +1,246 @@ +// Type definitions for d3-contour 1.1 +// Project: https://d3js.org/d3-contour/ +// Definitions by: Tom Wanzek , Hugues Stefanski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Last module patch version validated against: 1.1.0 + +import { MultiPolygon } from 'geojson'; +import { ThresholdArrayGenerator, ThresholdCountGenerator } from 'd3-array'; + +/** + * An extended GeoJSON MultiPolygon representing a contour. + */ +export interface ContourMultiPolygon extends MultiPolygon { + /** + * Threshold value of the contour. + */ + value: number; +} + +/** + * A contour generator which computes contour polygons by applying marching squares to a rectangular array of numeric values. + * + * For each threshold value, the contour generator constructs a GeoJSON MultiPolygon geometry object representing the area + * where the input values are greater than or equal to the threshold value. + * The geometry is in planar coordinates, where ⟨i + 0.5, j + 0.5⟩ corresponds to element i + jn in the input values array. + * + */ +export interface Contours { + /** + * Computes the contours for the given array of values, returning an array of GeoJSON MultiPolygon geometry objects. + * Each geometry object represents the area where the input values are greater than or equal to the corresponding threshold value; + * the threshold value for each geometry object is exposed as geometry.value. + * + * The returned geometry objects are typically passed to d3.geoPath to display, + * using null or d3.geoIdentity as the associated projection + * + * @param values Array of input values. The input values must be an array of length n×m where [n, m] is the contour generator’s size; + * furthermore, each values[i + jn] must represent the value at the position ⟨i, j⟩. + */ + (values: number[]): ContourMultiPolygon[]; + + /** + * Return the expected size of the input values grid, which defaults to [1,1]. + */ + size(): [number, number]; + /** + * Sets the expected size of the input values grid to the contour generator and returns the contour generator. + * + * @param size Size of the input values grid specified as an array [n, m] + * where n is the number of columns in the grid and m is the number of rows; n and m must be positive integers. + */ + size(size: [number, number]): this; + + /** + * Returns the current smoothing flag, which defaults to true. + */ + smooth(): boolean; + /** + * Sets whether or not the generated contour polygons are smoothed using linear interpolation and returns the contour generator. + * + * @param smooth Flag to enable linear interpolation. The default is "true". + */ + smooth(smooth: boolean): this; + + /** + * Returns the current threshold generator, which by default implements Sturges’ formula. + */ + thresholds(): ThresholdCountGenerator | ThresholdArrayGenerator; + /** + * Sets the threshold generator to use the specified count and returns this contour generator. + * The input values’ extent will be uniformly divided into approximately count bins. + * + * @param count Expected number of threshold bins. + */ + thresholds(count: number): this; + /** + * Sets the threshold generator to the specified array and returns this contour generator. + * + * Thresholds are defined as an array of values [x0, x1, …]. + * The first generated contour corresponds to the area where the input values are greater than or equal to x0; + * the second contour corresponds to the area where the input values are greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; + * the threshold value is exposed as geometry.value. + * + * @param thresholds Array of thresholds to use. + */ + thresholds(thresholds: number[]): this; + /** + * Sets the threshold generator to the specified function and returns this contour generator. + * + * Thresholds are defined as an array of values [x0, x1, …]. + * The first generated contour corresponds to the area where the input values are greater than or equal to x0; + * the second contour corresponds to the area where the input values are greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; + * the threshold value is exposed as geometry.value. + * + * @param thresholds A threshold generator function. The threshold generator function is passed the array of input values + * as its argument and returns either an array of calculated thresholds, or the count of thresholds to use. + */ + thresholds(thresholds: ThresholdCountGenerator | ThresholdArrayGenerator): this; +} + +/** + * Construct a new contour generator with the default settings. + */ +export function contours(): Contours; + +/** + * A contour generator for density estimates. + */ +export interface ContourDensity { + /** + * Estimates the density contours for the given array of data, returning an array of GeoJSON MultiPolygon geometry objects. + * Each geometry object represents the area where the estimated number of points per square pixel is greater than or equal to + * the corresponding threshold value; the threshold value for each geometry object is exposed as geometry.value. + * The returned geometry objects are typically passed to d3.geoPath to display, using null or d3.geoIdentity as the associated projection. + * See also d3.contours. + * + * The x- and y-coordinate for each data point are computed using density.x and density.y. + * The generated contours are only accurate within the estimator’s defined size. + * + * @param data Array of input data. + */ + (data: Datum[]): ContourMultiPolygon[]; + + /** + * Returns the current x-coordinate accessor. + * The default x-coordinate accessor is a functions which accepts as input a two-element array of numbers + * and returns the element at index 0. + */ + x(): (d: Datum) => number; + /** + * Sets the x-coordinate accessor and returns the density contour estimator. + * + * @param x An x-coordinate accessor function, which accepts as input an element of the input data array and returns the + * x-coordinate. + */ + x(x: (d: Datum) => number): this; + + /** + * Returns the current y-coordinate accessor. + * The default y-coordinate accessor is a functions which accepts as input a two-element array of numbers + * and returns the element at index 1. + */ + y(): (d: Datum) => number; + /** + * Sets the y-coordinate accessor and returns the density contour estimator. + * + * @param y An y-coordinate accessor function, which accepts as input an element of the input data array and returns the + * y-coordinate. + */ + y(y: (d: Datum) => number): this; + + /** + * Returns the current size, which defaults to [960, 500]. + */ + size(): [number, number]; + /** + * Sets the size of the density estimator to the specified bounds and returns the density contour estimator. + * + * @param size The size is specified as an array [width, height], where width is the maximum x-value and height is the maximum y-value. + */ + size(size: [number, number]): this; + + /** + * Returns the current cell size, which defaults to 4. + */ + cellSize(): number; + /** + * Sets the size of individual cells in the underlying bin grid to the specified positive integer and returns the density contour estimator. + * + * The cell size is rounded down to the nearest power of two. Smaller cells produce more detailed contour polygons, but are more expensive to compute. + * + * @param cellSize Cell size, a positive integer. + */ + cellSize(cellSize: number): this; + + /** + * Returns the current threshold generator, which by default generates about twenty nicely-rounded density thresholds. + */ + thresholds(): ThresholdCountGenerator | ThresholdArrayGenerator; + /** + * Sets the threshold generator to use the specified count and returns this density contour estimator. + * Approximately count uniformly-spaced nicely-rounded thresholds will be generated. + * + * @param count Expected number of thresholds. + */ + thresholds(count: number): this; + /** + * Sets the threshold generator to the specified array and returns this density contour estimator. + * + * Thresholds are defined as an array of values [x0, x1, …]. The first generated density contour corresponds to the area + * where the estimated density is greater than or equal to x0; the second contour corresponds to the area + * where the estimated density is greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; + * the threshold value is exposed as geometry.value. The first value x0 should typically be greater than zero. + * + * @param thresholds Array of thresholds to use. + */ + thresholds(thresholds: number[]): this; + /** + * Sets the threshold generator to the specified function and returns this density contour estimator. + * + * Thresholds are defined as an array of values [x0, x1, …]. The first generated density contour corresponds to the area + * where the estimated density is greater than or equal to x0; the second contour corresponds to the area + * where the estimated density is greater than or equal to x1, and so on. + * Thus, there is exactly one generated MultiPolygon geometry object for each specified threshold value; + * the threshold value is exposed as geometry.value. The first value x0 should typically be greater than zero. + * + * @param thresholds A threshold generator function. The threshold generator function is passed the array of input values + * as its argument and returns either an array of calculated thresholds, or the count of thresholds to use. + */ + thresholds(thresholds: ThresholdCountGenerator | ThresholdArrayGenerator): this; + + /** + * Returns the current bandwidth, which defaults to 20.4939…. + */ + bandwidth(): number; + /** + * Sets the bandwidth (the standard deviation) of the Gaussian kernel and returns the density contour estimator. + * + * @param bandwidth Bandwidth (the standard deviation) of the Gaussian kernel. + * The specified bandwidth is currently rounded to the nearest supported value by this implementation, and must be nonnegative. + */ + bandwidth(bandwidth: number): this; +} + +/** + * Construct a new contour generator for density estimates with the default settings. + * + * The default settings assume that, the elements of the data array used + * with the density contour generator are two-element arrays. The first element + * corresponds to the x-dimension, the second to the y-dimension. + */ +export function contourDensity(): ContourDensity<[number, number]>; +/** + * Construct a new contour generator for density estimates. + * + * The generic refers to the data type of an element in the data array + * used with the density contour generator. + * + * Important: ensure that the x- and y-accessor functions are configured to + * match the data type used for the generic Datum. + */ +export function contourDensity(): ContourDensity; diff --git a/types/d3-contour/tsconfig.json b/types/d3-contour/tsconfig.json new file mode 100644 index 0000000000..4f9d0a8284 --- /dev/null +++ b/types/d3-contour/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3-contour-tests.ts" + ] +} diff --git a/types/d3-contour/tslint.json b/types/d3-contour/tslint.json new file mode 100644 index 0000000000..08016de61a --- /dev/null +++ b/types/d3-contour/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} diff --git a/types/d3-ease/index.d.ts b/types/d3-ease/index.d.ts index 3de6fd2e87..1f2b5f4cdd 100644 --- a/types/d3-ease/index.d.ts +++ b/types/d3-ease/index.d.ts @@ -87,7 +87,7 @@ export interface PolynomialEasingFactory { * * @param e Exponent for polynomial easing. */ - exponent(e: number): PolynomialEasingFactory; + exponent(e: number): PolynomialEasingFactory; } /** @@ -240,7 +240,7 @@ export interface BackEasingFactory { * * @param s Overshoot parameter */ - overshoot(s: number): BackEasingFactory; + overshoot(s: number): BackEasingFactory; } /** @@ -282,14 +282,14 @@ export interface ElasticEasingFactory { * * @param a Amplitude for elastic easing. */ - amplitude(a: number): ElasticEasingFactory; - /** - * Returns a new elastic easing with the specified amplitude a. - * Defaults to 0.3,if not specified. - * - * @param p Period for elastic easing. - */ - period(p: number): ElasticEasingFactory; + amplitude(a: number): ElasticEasingFactory; + /** + * Returns a new elastic easing with the specified amplitude a. + * Defaults to 0.3,if not specified. + * + * @param p Period for elastic easing. + */ + period(p: number): ElasticEasingFactory; } /** diff --git a/types/d3-geo/index.d.ts b/types/d3-geo/index.d.ts index f6e4fa150d..bff408ce6b 100644 --- a/types/d3-geo/index.d.ts +++ b/types/d3-geo/index.d.ts @@ -3,10 +3,10 @@ // Definitions by: Hugues Stefanski , Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - // Last module patch version validated against: 1.6.1 +import * as GeoJSON from 'geojson'; + // ---------------------------------------------------------------------- // Shared Interfaces and Types // ---------------------------------------------------------------------- @@ -926,7 +926,8 @@ export interface GeoPath { * * Any additional arguments are passed along to the pointRadius accessor. * - * If the rendering context is null, the function returns an SVG Path string, otherwise the function renders to the current context. + * IMPORTANT: If the rendering context of the geoPath generator is null, + * then the geoPath is returned as an SVG path data string. * * Separate path elements are typically slower than a single path element. However, distinct path elements are useful for styling and interation (e.g., click or mouseover). * Canvas rendering (see path.context) is typically faster than SVG, but requires more effort to implement styling and interaction. @@ -935,7 +936,36 @@ export interface GeoPath { * * @param object An object to be rendered. */ - (this: This, object: DatumObject, ...args: any[]): string | undefined; + (this: This, object: DatumObject, ...args: any[]): string | null; + /** + * Renders the given object, which may be any GeoJSON feature or geometry object: + * + * + Point - a single position. + * + MultiPoint - an array of positions. + * + LineString - an array of positions forming a continuous line. + * + MultiLineString - an array of arrays of positions forming several lines. + * + Polygon - an array of arrays of positions forming a polygon (possibly with holes). + * + MultiPolygon - a multidimensional array of positions forming multiple polygons. + * + GeometryCollection - an array of geometry objects. + * + Feature - a feature containing one of the above geometry objects. + * + FeatureCollection - an array of feature objects. + * + * The type Sphere is also supported, which is useful for rendering the outline of the globe; a sphere has no coordinates. + * + * + * Any additional arguments are passed along to the pointRadius accessor. + * + * IMPORTANT: If the geoPath generator has been configured with a rendering context, + * then the geoPath is rendered to this context as a sequence of path method calls and this function returns void. + * + * Separate path elements are typically slower than a single path element. However, distinct path elements are useful for styling and interation (e.g., click or mouseover). + * Canvas rendering (see path.context) is typically faster than SVG, but requires more effort to implement styling and interaction. + * + * The first generic type of the GeoPath generator used, must correspond to the "this" context bound to the function upon invocation. + * + * @param object An object to be rendered. + */ + (this: This, object: DatumObject, ...args: any[]): void; /** * Returns the projected planar area (typically in square pixels) for the specified GeoJSON object. diff --git a/types/d3-sankey/d3-sankey-tests.ts b/types/d3-sankey/d3-sankey-tests.ts new file mode 100644 index 0000000000..246755a900 --- /dev/null +++ b/types/d3-sankey/d3-sankey-tests.ts @@ -0,0 +1,258 @@ +/** + * Typescript definition tests for d3/d3-sankey module + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +import * as d3Sankey from 'd3-sankey'; +import {select, Selection} from 'd3-selection'; + +// --------------------------------------------------------------------------- +// Preparatory Steps +// --------------------------------------------------------------------------- + +// Create interfaces for the user-provided node/link attributes, which are NOT mandated or calculated by +// the Sankey layout generator. The latter are reflected in the SankeyNode and SankeyLink interfaces provided +// by the definitions file +interface SNodeExtra { + nodeId: number; + name: string; +} + +interface SLinkExtra { + uom: string; +} + +// For convenience +type SNode = d3Sankey.SankeyNode; +type SLink = d3Sankey.SankeyLink; + +interface DAG { + nodes: SNode[]; + links: SLink[]; +} + +const graph: DAG = { + nodes: [{ + nodeId: 0, + name: "node0" + }, { + nodeId: 1, + name: "node1" + }, { + nodeId: 2, + name: "node2" + }, { + nodeId: 3, + name: "node3" + }, { + nodeId: 4, + name: "node4" + }], + links: [{ + source: 0, + target: 2, + value: 2, + uom: 'Widget(s)' + }, { + source: 1, + target: 2, + value: 2, + uom: 'Widget(s)' + }, { + source: 1, + target: 3, + value: 2, + uom: 'Widget(s)' + }, { + source: 0, + target: 4, + value: 2, + uom: 'Widget(s)' + }, { + source: 2, + target: 3, + value: 2, + uom: 'Widget(s)' + }, { + source: 2, + target: 4, + value: 2, + uom: 'Widget(s)' + }, { + source: 3, + target: 4, + value: 4, + uom: 'Widget(s)' + }] +}; + +let sNodes: SNode[]; +let sLinks: SLink[]; + +let num: number; +let numMaybe: number | undefined; +let str: string; +let size: [number, number]; + +const svgLinkPaths = select('svg').selectAll('.linkPath'); // assume mock DOM + +// --------------------------------------------------------------------------- +// Obtain SankeyLayout Generator +// --------------------------------------------------------------------------- + +let slgDefault: d3Sankey.SankeyLayout<{}, {}> = d3Sankey.sankey(); +let slgDAG: d3Sankey.SankeyLayout = d3Sankey.sankey(); + +// --------------------------------------------------------------------------- +// NodeWidth +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.nodeWidth(32); + +// Get ----------------------------------------------------------------------- + +num = slgDAG.nodeWidth(); + +// --------------------------------------------------------------------------- +// NodePadding +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.nodePadding(8); + +// Get ----------------------------------------------------------------------- + +num = slgDAG.nodePadding(); + +// --------------------------------------------------------------------------- +// Size +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.size([1200, 800]); + +// Get ----------------------------------------------------------------------- + +size = slgDAG.size(); + +// --------------------------------------------------------------------------- +// Nodes +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.nodes(graph.nodes); + +// Get ----------------------------------------------------------------------- + +sNodes = slgDAG.nodes(); + +// --------------------------------------------------------------------------- +// Links +// --------------------------------------------------------------------------- + +// Set ----------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.links(graph.links); + +// Get ----------------------------------------------------------------------- + +sLinks = slgDAG.links(); + +// --------------------------------------------------------------------------- +// Compute Layout +// --------------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.layout(22); + +// --------------------------------------------------------------------------- +// Relayout +// --------------------------------------------------------------------------- + +// test return type for chainability +slgDAG = slgDAG.relayout(); + +// --------------------------------------------------------------------------- +// Obtain and Use Link SVG Path Generator +// --------------------------------------------------------------------------- + +let pathGen: d3Sankey.SankeyLinkPathGenerator; + +pathGen = slgDAG.link(); + +// Adjust Link SVG Path Generator curvature ---------------------------------- + +// test return type +pathGen = pathGen.curvature(0.6); +num = pathGen.curvature(); + +// uses + +let svgPathString: string = pathGen(slgDAG.links()[0]); +svgLinkPaths.attr('d', pathGen); + +// --------------------------------------------------------------------------- +// Shape test Node/Link related interfaces and types +// --------------------------------------------------------------------------- + +// Sankey Node -------------------------------------------------------------- + +let sNode = sNodes[0]; + +// User-specified extra properties: + +num = sNode.nodeId; +str = sNode.name; + +// Sankey Layout calculated (if layout has been run, otherwise undefined): + +numMaybe = sNode.dx; +numMaybe = sNode.x; +numMaybe = sNode.dy; +numMaybe = sNode.y; +numMaybe = sNode.value; + +let linksArrMaybe: SLink[] | undefined; + +linksArrMaybe = sNode.sourceLinks; +linksArrMaybe = sNode.targetLinks; + +// Sankey Link -------------------------------------------------------------- + +let sLink = sLinks[0]; + +// User-specified extra properties: + +str = sLink.uom; + +// Sankey Layout mandated link properties: + +num = sLink.value; + +// Node depending on initialization strategy and whether +// layout(...) was invoked, the source and target nodes may be numbers +// objects without the Sankey layout coordinates, or objects with calculated +// information +let numOrSankeyNode: number | SNode; + +numOrSankeyNode = sLink.source; +numOrSankeyNode = sLink.target; + +// Sankey Layout calculated (if layout has been run, otherwise undefined): + +numMaybe = sLink.sy; +numMaybe = sLink.ty; +numMaybe = sLink.dy; diff --git a/types/d3-sankey/index.d.ts b/types/d3-sankey/index.d.ts new file mode 100644 index 0000000000..1446bc917f --- /dev/null +++ b/types/d3-sankey/index.d.ts @@ -0,0 +1,267 @@ +// Type definitions for D3JS d3-sankey module 0.4 +// Project: https://github.com/d3/d3-sankey/ +// Definitions by: Tom Wanzek , Alex Ford +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Last module patch version validated against: 0.4.2 + +/** + * A helper interface as an extension reference for user-provided properties of + * nodes and links in the graph, which are not required or calculated by + * the Sankey Layout Generator + */ +export interface SankeyExtraProperties { [key: string]: any; } + +/** + * Helper interface to define the properties of Sankey Nodes. Calculated properties may only be defined, + * once the layout(...) method of the Sankey layout generator has been invoked. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export interface SankeyNodeMinimal { + /** + * Array of links which have this node as their source. + * This property is calculated internally by the Sankey layout generator. + */ + sourceLinks?: Array>; + /** + * Array of links which have this node as their target. + * This property is calculated internally by the Sankey layout generator. + */ + targetLinks?: Array>; + /** + * Node value calculated by Sankey Layout Generator based on values of incoming and outgoing links + */ + value?: number; + /** + * Node horizontal position calculated by Sankey layout generator + */ + x?: number; + /** + * Node width calculated by Sankey layout generator + */ + dx?: number; + /** + * Node vertical position (depth) calculated by Sankey layout generator + */ + y?: number; + /** + * Node height (vertical extent based on node value) calculated by Sankey layout generator + */ + dy?: number; +} + +/** + * Sankey Node type including both user-defined node data elements as well as those + * calculated once the layout(...) method of the Sankey layout generators has been invoked. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export type SankeyNode = N & SankeyNodeMinimal; + +/** + * Helper interface to define the properties of Sankey Links. Calculated properties may only be defined, + * once the layout(...) method of the Sankey layout generator has been invoked. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export interface SankeyLinkMinimal { + /** + * Source node of the link. For convenience, when initializing a Sankey layout, source may be the index of the source node in the nodes array + * passed into the Sankey layout generator. Once the layout(...) method is invoked, the numeric index will be replaced with the corresponding + * source node object. + */ + source: number | SankeyNode; + /** + * Target node of the link. For convenience, when initializing a Sankey layout, target may be the index of the target node in the nodes array + * passed into the Sankey layout generator. Once the layout(...) method is invoked, the numeric index will be replaced with the corresponding + * target node object. + */ + target: number | SankeyNode; + /** + * Value of the link + */ + value: number; + /** + * Link breadth calculated by Sankey layout generator based on the link value + */ + dy?: number; + /** + * Vertical starting position of the link (at source node) calculated by Sankey layout generator + */ + sy?: number; + /** + * Vertical end position of the link (at target node) calculated by Sankey layout generator + */ + ty?: number; +} + +/** + * Sankey Link type including both user-defined link data elements, those required by the Sankey layout generator, + * as well as those calculated once the layout(...) method of the layout generator has been invoked. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export type SankeyLink = L & SankeyLinkMinimal; + +/** + * An svg path generator factory for the link paths in a calculated Sankey Layout. + */ +export interface SankeyLinkPathGenerator { + /** + * Return svg path string for a given link. + * + * IMPORTANT: Only invoke for link data with Sankey Layout information previously calculated. + * + * @param link A Sankey diagram link, for which the layout has already been calculated. + */ + (link: SankeyLink): string; + /** + * Returns the current curvature used to calculate svg paths for links. + * The default curvature is 0.5. + */ + curvature(): number; + /** + * Set the curvature used to calculate svg paths for links and return the updated link path generator. + * + * @param curvature Curvature to be used when calculating svg paths for links. The default curvature is 0.5. + */ + curvature(curvature: number): this; +} + +/** + * A Sankey layout generator. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export interface SankeyLayout { + /** + * Return the current node width, which defaults to 24. + */ + nodeWidth(): number; + /** + * Set the node width to the specified number and return this Sankey layout generator. + * + * @param width Width of node in pixels, which defaults to 24. + */ + nodeWidth(width: number): this; + + /** + * Return the current node padding, which defaults to 8. + * + * Node padding refers to the vertical space between nodes which occupy the same horizontal space. + */ + nodePadding(): number; + /** + * Set the node padding to the specified number and return this Sankey layout generator. + * + * Node padding refers to the vertical space between nodes which occupy the same horizontal space. + * + * @param padding Node padding in pixels, which defaults to 8. + */ + nodePadding(padding: number): this; + + /** + * Return the current array of nodes, which defaults to []. + */ + nodes(): Array>; + /** + * Set the sankey generator's nodes to the specified array of objects and returns this sankey layout generator. + * + * @param nodes Array of nodes. + */ + nodes(nodes: Array>): this; + + /** + * Return the current array of links, which defaults to []. + */ + links(): Array>; + /** + * Set the sankey generator's links to the specified array of objects and returns this sankey layout generator. + * + * @param links Array of links. + */ + links(links: Array>): this; + + /** + * Runs the sankey layout algorithm updating the nodes and links with their respective layout information and returns this sankey generator. + * + * @param iterations Number of passes to be used in the iterative relaxation algorithm for node placement. + */ + layout(iterations: number): this; + + /** + * Recalculate the depth of links and return this Sankey layout generator. + * This methods is primarily used when a node is moved vertically, e.g. using d3-drag. + */ + relayout(): this; + + /** + * Return the current layout size in pixels. The size is a two element array of [width, height] which defaults to [1, 1]. + */ + size(): [number, number]; + /** + * Set the size of the layout and return this Sankey layout generator. + * + * @param size A two element array of [width, height] in pixels which defaults to [1, 1]. + */ + size(size: [number, number]): this; + + /** + * Return a Sankey link path generator for the links based on the calculated Sankey diagram layout. + * The link path generator can be invoked as a function being passed as its argument a link object + * with calculated layout information. It returns the computed path string for the link. + * By default the link path generator uses a curvature of 0.5. + */ + link(): SankeyLinkPathGenerator; +} + +/** + * Get a Sankey layout generator. + * + * Invoking sankey() without generics, means the node type and link type assume no user-defined attributes, i.e. + * only the attributes internally used by the Sankey layout generator. + */ +export function sankey(): SankeyLayout<{}, {}>; +/** + * Get a Sankey layout generator. + * + * The first generic N refers to user-defined properties contained in the node data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyNodeMinimal interface. + * + * The second generic L refers to user-defined properties contained in the link data passed into + * Sankey layout generator. These properties are IN EXCESS to the properties explicitly identified in the + * SankeyLinkMinimal interface. + */ +export function sankey(): SankeyLayout; diff --git a/types/d3-sankey/tsconfig.json b/types/d3-sankey/tsconfig.json new file mode 100644 index 0000000000..bd11293dc2 --- /dev/null +++ b/types/d3-sankey/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3-sankey-tests.ts" + ] +} diff --git a/types/d3-sankey/tslint.json b/types/d3-sankey/tslint.json new file mode 100644 index 0000000000..08b1465cd6 --- /dev/null +++ b/types/d3-sankey/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} diff --git a/types/deepmerge/deepmerge-tests.ts b/types/deepmerge/deepmerge-tests.ts index 8c7988ba78..5467cb83f0 100644 --- a/types/deepmerge/deepmerge-tests.ts +++ b/types/deepmerge/deepmerge-tests.ts @@ -1,13 +1,19 @@ import * as deepmerge from "deepmerge"; -const x = { foo: { bar: 3 }, - array: [ { does: 'work', too: [ 1, 2, 3 ] } ] }; -const y = { foo: { baz: 4 }, +const x = { + foo: { bar: 3 }, + array: [{ does: 'work', too: [1, 2, 3] }] +}; +const y = { + foo: { baz: 4 }, quux: 5, - array: [ { does: 'work', too: [ 4, 5, 6 ] }, { really: 'yes' } ] }; + array: [{ does: 'work', too: [4, 5, 6] }, { really: 'yes' }] +}; -const expected = { foo: { bar: 3, baz: 4 }, - array: [ { does: 'work', too: [ 1, 2, 3, 4, 5, 6 ] }, { really: 'yes' } ], - quux: 5 }; +const expected = { + foo: { bar: 3, baz: 4 }, + array: [{ does: 'work', too: [1, 2, 3, 4, 5, 6] }, { really: 'yes' }], + quux: 5 +}; const result = deepmerge(x, y); diff --git a/types/dwt/dwt-tests.ts b/types/dwt/dwt-tests.ts new file mode 100644 index 0000000000..4b201cf33d --- /dev/null +++ b/types/dwt/dwt-tests.ts @@ -0,0 +1,101 @@ +function dwtOnReady() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); // Get the Dynamic Web TWAIN object that is embeded in the div with id 'dwtcontrolContainer' + if (DWObject) { + let count = DWObject.SourceCount; + if (count === 0) { + DWObject.CloseSourceManager(); + DWObject.ImageCaptureDriverType = 0; + DWObject.OpenSourceManager(); + count = DWObject.SourceCount; + } + } +} + +function acquireImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.SelectSourceByIndex(0); // Use method SelectSourceByIndex to avoid the 'Select Source' dialog + DWObject.OpenSource(); + DWObject.IfDisableSourceAfterAcquire = true; // Scanner source will be disabled/closed automatically after the scan. + DWObject.AcquireImage({}, () => {}, (errorCode: number, errorString: string) => {DWObject.CloseSource(); }); + } +} + +function registerEvent() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + // The event OnPostTransfer fires after each image is scanned and transferred + DWObject.RegisterEvent("OnPostTransfer", function () {}); + + // The event OnPostLoad fires after the images from a local directory have been loaded into the control + DWObject.RegisterEvent("OnPostLoad", function () {}); + + // The event OnMouseClick fires when the mouse clicks on an image on Dynamic Web TWAIN viewer + DWObject.RegisterEvent("OnMouseClick", function () {}); + + // The event OnTopImageInTheViewChanged fires when the top image currently displayed in the viewer changes + DWObject.RegisterEvent("OnTopImageInTheViewChanged", function (index: number) { + DWObject.CurrentImageIndexInBuffer = index; + }); + } +} + +function editImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + if (DWObject.HowManyImagesInBuffer > 0) + DWObject.RotateLeft(DWObject.CurrentImageIndexInBuffer); + + if (DWObject.HowManyImagesInBuffer > 0) + DWObject.RotateRight(DWObject.CurrentImageIndexInBuffer); + + if (DWObject.HowManyImagesInBuffer > 0) + DWObject.Mirror(DWObject.CurrentImageIndexInBuffer); + + if (DWObject.HowManyImagesInBuffer > 0) + DWObject.Flip(DWObject.CurrentImageIndexInBuffer); + } +} + +function showImageEditor() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.ShowImageEditor(); + } +} + +function saveImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.ConvertToGrayScale(DWObject.CurrentImageIndexInBuffer); + DWObject.SaveAsJPEG("DynamicWebTWAIN.jpg", DWObject.CurrentImageIndexInBuffer); + DWObject.SaveAllAsMultiPageTIFF("DynamicWebTWAIN.tiff", () => {}, (errorCode: number, errorString: string) => {}); + DWObject.SaveAllAsPDF("DynamicWebTWAIN.pdf", () => {}, (errorCode: number, errorString: string) => {}); + } +} + +function updateLargeViewer() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + let DWObjectLargeViewer = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainerLargeViewer'); + if (DWObject) { + DWObject.CopyToClipboard(DWObject.CurrentImageIndexInBuffer); // Copy the current image in the thumbnail to clipboard in DIB format. + DWObjectLargeViewer.LoadDibFromClipboard(); // Load the image from Clipboard into the large viewer. + } +} + +function uploadImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.HTTPPort = 80; + DWObject.IfSSL = false; + DWObject.HTTPUploadThroughPost("www.dynamsoft.com", DWObject.CurrentImageIndexInBuffer, "upload", "tmp.jpg", () => {}, (errorCode: number, errorString: string) => {}); + } +} + +function downloadImage() { + let DWObject = Dynamsoft.WebTwainEnv.GetWebTwain('dwtcontrolContainer'); + if (DWObject) { + DWObject.HTTPPort = 80; + DWObject.HTTPDownload("www.dynamsoft.com", "img.png", () => {}, (errorCode: number, errorString: string) => {}); + } +} diff --git a/types/dwt/index.d.ts b/types/dwt/index.d.ts new file mode 100644 index 0000000000..460158afe1 --- /dev/null +++ b/types/dwt/index.d.ts @@ -0,0 +1,3459 @@ +// Type definitions for dwt 12.3 +// Project: http://www.dynamsoft.com/Products/WebTWAIN_Overview.aspx +// Definitions by: Xiao Ling +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/*! +* Dynamsoft WebTwain JavaScript Intellisense +* Product: Dynamsoft Web Twain +* Web Site: http://www.dynamsoft.com +* +* Copyright 2017, Dynamsoft Corporation +* Author: Dynamsoft Support Team +* Version: 12.3 +*/ + +/** + * @namespace Dynamsoft + */ +declare namespace Dynamsoft { + namespace WebTwainEnv { + function GetWebTwain (cid: string): WebTwain; + function RegisterEvent(event: string, fn: () => void): void; + } +} + +/** ICAP_PIXELTYPE values (PT_ means Pixel Type) */ +declare enum EnumDWT_PixelType { + TWPT_BW = 0, + TWPT_GRAY = 1, + TWPT_RGB = 2, + TWPT_PALLETE = 3, + TWPT_CMY = 4, + TWPT_CMYK = 5, + TWPT_YUV = 6, + TWPT_YUVK = 7, + TWPT_CIEXYZ = 8, + TWPT_LAB = 9, + TWPT_SRGB = 10, + TWPT_SCRGB = 11, + TWPT_INFRARED = 16 +} + +declare enum EnumDWT_BorderStyle { + /** No border. */ + TWBS_NONE = 0, + /** Flat border. */ + TWBS_SINGLEFLAT = 1, + /** 3D border. */ + TWBS_SINGLE3D = 2 +} + +/** For query the operation that are supported by the data source on a capability . + * Application gets these through DG_CONTROL/DAT_CAPABILITY/MSG_QUERYSUPPORT + */ +declare enum EnumDWT_MessageType { + TWQC_GET = 1, + TWQC_SET = 2, + TWQC_GETDEFAULT = 4, + TWQC_GETCURRENT = 8, + TWQC_RESET = 16 +} + +/** Capabilities */ +declare enum EnumDWT_Cap { + /** Nothing. */ + CAP_NONE = 0, + /** The application is willing to accept this number of images. */ + CAP_XFERCOUNT = 1, + /** Allows the application and Source to identify which compression schemes they have in + * common for Buffered Memory and File transfers. + * Note for File transfers: + * Since only certain file formats support compression, this capability must be negotiated after + * setting the desired file format with ICAP_IMAGEFILEFORMAT. + */ + ICAP_COMPRESSION = 256, + /** The type of pixel data that a Source is capable of acquiring (for example, black and white, gray, RGB, etc.). */ + ICAP_PIXELTYPE = 257, + /** Unless a quantity is dimensionless or uses a specified unit of measure, ICAP_UNITS determines + * the unit of measure for all quantities. + */ + ICAP_UNITS = 258, + /** Allows the application and Source to identify which transfer mechanisms the source supports. */ + ICAP_XFERMECH = 259, + /** The name or other identifying information about the Author of the image. It may include a copyright string. */ + CAP_AUTHOR = 4096, + /** A general note about the acquired image. */ + CAP_CAPTION = 4097, + /** If TRUE, Source must acquire data from the document feeder acquire area and other feeder + * capabilities can be used. If FALSE, Source must acquire data from the non-feeder acquire area + * and no other feeder capabilities can be used. + */ + CAP_FEEDERENABLED = 4098, + /** Reflect whether there are documents loaded in the Source's feeder. */ + CAP_FEEDERLOADED = 4099, + /** The date and time the image was acquired. + * Stored in the form "YYYY/MM/DD HH:mm:SS.sss" where YYYY is the year, MM is the + * numerical month, DD is the numerical day, HH is the hour, mm is the minute, SS is the second, + * and sss is the millisecond. + */ + CAP_TIMEDATE = 4100, + /** Returns a list of all the capabilities for which the Source will answer inquiries. Does not indicate + * which capabilities the Source will allow to be set by the application. Some capabilities can only + * be set if certain setup work has been done so the Source cannot globally answer which + * capabilities are "set-able." + */ + CAP_SUPPORTEDCAPS = 4101, + /** Allows the application and Source to negotiate capabilities to be used in States 5 and 6. */ + CAP_EXTENDEDCAPS = 4102, + /** If TRUE, the Source will automatically feed the next page from the document feeder after the + * number of frames negotiated for capture from each page are acquired. CAP_FEEDERENABLED + * must be TRUE to use this capability. + */ + CAP_AUTOFEED = 4103, + /** If TRUE, the Source will eject the current page being acquired from and will leave the feeder + * acquire area empty. + * If CAP_AUTOFEED is TRUE, a fresh page will be advanced. + * CAP_FEEDERENABLED must equal TRUE to use this capability. + * This capability must have been negotiated as an extended capability to be used in States 5 and 6. + */ + CAP_CLEARPAGE = 4104, + /** If TRUE, the Source will eject the current page and advance the next page in the document feeder + * into the feeder acquire area. + * If CAP_AUTOFEED is TRUE, the same action just described will occur and CAP_AUTOFEED will + * remain active. + * CAP_FEEDERENABLED must equal TRUE to use this capability. + * This capability must have been negotiated as an extended capability to be used in States 5 and 6. + */ + CAP_FEEDPAGE = 4105, + /** If TRUE, the Source will return the current page to the input side of the document feeder and + * feed the last page from the output side of the feeder back into the acquisition area. + * If CAP_AUTOFEED is TRUE, automatic feeding will continue after all negotiated frames from this + * page are acquired. + * CAP_FEEDERENABLED must equal TRUE to use this capability. + * This capability must have been negotiated as an extended capability to be used in States 5 and 6. + */ + CAP_REWINDPAGE = 4106, + /** If TRUE, the Source will display a progress indicator during acquisition and transfer, regardless + * of whether the Source's user interface is active. If FALSE, the progress indicator will be + * suppressed if the Source's user interface is inactive. + * The Source will continue to display device-specific instructions and error messages even with + * the Source user interface and progress indicators turned off. + */ + CAP_INDICATORS = 4107, + /** Returns a list of all the capabilities for which the Source will answer inquiries. Does not indicate + * which capabilities the Source will allow to be set by the application. Some capabilities can only + * be set if certain setup work has been done so the Source cannot globally answer which + * capabilities are "set-able." + */ + CAP_SUPPORTEDCAPSEXT = 4108, + /** This capability determines whether the device has a paper sensor that can detect documents on the ADF or Flatbed. */ + CAP_PAPERDETECTABLE = 4109, + /** If TRUE, indicates that this Source supports acquisition with the UI disabled; i.e., + * TW_USERINTERFACE's ShowUI field can be set to FALSE. If FALSE, indicates that this Source + * can only support acquisition with the UI enabled. + */ + CAP_UICONTROLLABLE = 4110, + /** If TRUE, the physical hardware (e.g., scanner, digital camera, image database, etc.) that + * represents the image source is attached, powered on, and communicating. + */ + CAP_DEVICEONLINE = 4111, + /** This capability is intended to boost the performance of a Source. The fundamental assumption + * behind AutoScan is that the device is able to capture the number of images indicated by the + * value of CAP_XFERCOUNT without waiting for the Application to request the image transfers. + * This is only possible if the device has internal buffers capable of caching the images it captures. + * The default behavior is undefined, because some high volume devices are incapable of anything + * but CAP_AUTOSCAN being equal to TRUE. However, if a Source supports FALSE, it should use it + * as the mandatory default, since this best describes the behavior of pre-1.8 TWAIN Applications. + */ + CAP_AUTOSCAN = 4112, + /** Allows an application to request the delivery of thumbnail representations for the set of images + * that are to be delivered. + * Setting CAP_THUMBNAILSENABLED to TRUE turns on thumbnail mode. Images transferred + * thereafter will be sent at thumbnail size (exact thumbnail size is determined by the Data Source). + * Setting this capability to FALSE turns thumbnail mode off and returns full size images. + */ + CAP_THUMBNAILSENABLED = 4113, + /** This indicates whether the scanner supports duplex. If so, it further indicates whether one-path + * or two-path duplex is supported. + */ + CAP_DUPLEX = 4114, + /** The user can set the duplex option to be TRUE or FALSE. If TRUE, the scanner scans both sides + * of a paper; otherwise, the scanner will scan only one side of the image. + */ + CAP_DUPLEXENABLED = 4115, + /** Allows an application to query a source to see if it implements the new user interface settings dialog. */ + CAP_ENABLEDSUIONLY = 4116, + CAP_CUSTOMDSDATA = 4117, + /** Allows the application to specify the starting endorser / imprinter number. All other endorser/ + * imprinter properties should be handled through the data source's user interface. + * The user can set the starting number for the endorser. + */ + CAP_ENDORSER = 4118, + /** Turns specific audible alarms on and off. */ + CAP_ALARMS = 4120, + /** The volume of a device's audible alarm. Note that this control affects the volume of all alarms; + * no specific volume control for individual types of alarms is provided. + */ + CAP_ALARMVOLUME = 4121, + /** The number of images to automatically capture. This does not refer to the number of images to + * be sent to the Application, use CAP_XFERCOUNT for that. + */ + CAP_AUTOMATICCAPTURE = 4122, + /** For automatic capture, this value selects the number of milliseconds before the first picture is to + * be taken, or the first image is to be scanned. + */ + CAP_TIMEBEFOREFIRSTCAPTURE = 4123, + /** For automatic capture, this value selects the milliseconds to wait between pictures taken, or images scanned. */ + CAP_TIMEBETWEENCAPTURES = 4124, + /** CapGet() reports the presence of data in the scanner's buffers. CapSet() with a value of TWCB_CLEAR immediately clears the buffers. */ + CAP_CLEARBUFFERS = 4125, + /** Describes the number of pages that the scanner can buffer when CAP_AUTOSCAN is enabled. */ + CAP_MAXBATCHBUFFERS = 4126, + /** The date and time of the device's clock. + * Managed in the form "YYYY/MM/DD HH:mm:SS:sss" where YYYY is the year, MM is the + * numerical month, DD is the numerical day, HH is the hour, mm is the minute, SS is the second, + * and sss is the millisecond. + */ + CAP_DEVICETIMEDATE = 4127, + /** CapGet() reports the kinds of power available to the device. CapGetCurrent() reports the current power supply in use. */ + CAP_POWERSUPPLY = 4128, + /** This capability queries the Source for UI support for preview mode. If TRUE, the Source supports preview UI. */ + CAP_CAMERAPREVIEWUI = 4129, + /** A string containing the serial number of the currently selected device in the Source. Multiple + * devices may all report the same serial number. + */ + CAP_SERIALNUMBER = 4132, + /** CapGet() returns the current list of available printer devices, along with the one currently being used for negotiation. + * CapSet() selects the current device for negotiation, and optionally constrains the list. + * Top/Bottom refers to duplex devices, and indicates if the printer is writing on the top or the bottom of the sheet of paper. + * Simplex devices use the top settings. Before/After indicates whether printing occurs before or after the sheet of paper has been scanned. + */ + CAP_PRINTER = 4134, + /** Turns the current CAP_PRINTER device on or off. */ + CAP_PRINTERENABLED = 4135, + /** The User can set the starting number for the current CAP_PRINTER device. */ + CAP_PRINTERINDEX = 4136, + /** Specifies the appropriate current CAP_PRINTER device mode. + * Note: + * • TWPM_SINGLESTRING specifies that the printed text will consist of a single string. + * • TWPM _MULTISTRING specifies that the printed text will consist of an enumerated list of + * strings to be printed in order. + * • TWPM _COMPOUNDSTRING specifies that the printed string will consist of a compound of a + * String followed by a value followed by a suffix string. + */ + CAP_PRINTERMODE = 4137, + /** Specifies the string(s) that are to be used in the string component when the current + * CAP_PRINTER device is enabled. + */ + CAP_PRINTERSTRING = 4138, + /** Specifies the string that shall be used as the current CAP_PRINTER device's suffix. */ + CAP_PRINTERSUFFIX = 4139, + /** Allows Application and Source to identify which languages they have in common for the exchange of string data, + * and to select the language of the internal UI. Since the TWLG_xxxx codes include language and country data, there is no separate + * capability for selecting the country. + */ + CAP_LANGUAGE = 4140, + /** Helps the Application determine any special actions it may need to take when negotiating + * frames with the Source. Allowed values are listed in . + * TWFA_NONE: The alignment is free-floating. Applications should assume + * that the origin for frames is on the left. + * TWFA_LEFT: The alignment is to the left. + * TWFA_CENTER: The alignment is centered. This means that the paper will + * be fed in the middle of the ICAP_PHYSICALWIDTH of the + * device. If this is set, then the Application should calculate + * any frames with a left offset of zero. + * TWFA_RIGHT: The alignment is to the right. + */ + CAP_FEEDERALIGNMENT = 4141, + /** TWFO_FIRSTPAGEFIRST if the feeder starts with the top of the first page. + * TWFO_LASTPAGEFIRST is the feeder starts with the top of the last page. + */ + CAP_FEEDERORDER = 4142, + /** Indicates whether the physical hardware (e.g. scanner, digital camera) is capable of acquiring + * multiple images of the same page without changes to the physical registration of that page. + */ + CAP_REACQUIREALLOWED = 4144, + /** The minutes of battery power remaining to the device. */ + CAP_BATTERYMINUTES = 4146, + /** When used with CapGet(), return the percentage of battery power level on camera. If -1 is returned, it indicates that the battery is not present. */ + CAP_BATTERYPERCENTAGE = 4147, + /** Added 1.91 */ + CAP_CAMERASIDE = 4148, + /** Added 1.91 */ + CAP_SEGMENTED = 4149, + /** Added 2.0 */ + CAP_CAMERAENABLED = 4150, + /** Added 2.0 */ + CAP_CAMERAORDER = 4151, + /** Added 2.0 */ + CAP_MICRENABLED = 4152, + /** Added 2.0 */ + CAP_FEEDERPREP = 4153, + /** Added 2.0 */ + CAP_FEEDERPOCKET = 4154, + /** Added 2.1 */ + CAP_AUTOMATICSENSEMEDIUM = 4155, + /** Added 2.1 */ + CAP_CUSTOMINTERFACEGUID = 4156, + /** TRUE enables and FALSE disables the Source's Auto-brightness function (if any). */ + ICAP_AUTOBRIGHT = 4352, + /** The brightness values available within the Source. */ + ICAP_BRIGHTNESS = 4353, + /** The contrast values available within the Source. */ + ICAP_CONTRAST = 4355, + /** Specifies the square-cell halftone (dithering) matrix the Source should use to halftone the image. */ + ICAP_CUSTHALFTONE = 4356, + /** Specifies the exposure time used to capture the image, in seconds. */ + ICAP_EXPOSURETIME = 4357, + /** Describes the color characteristic of the subtractive filter applied to the image data. Multiple + * filters may be applied to a single acquisition. + */ + ICAP_FILTER = 4358, + /** Specifies whether or not the image was acquired using a flash. */ + ICAP_FLASHUSED = 4359, + /** Gamma correction value for the image data. */ + ICAP_GAMMA = 4360, + /** A list of names of the halftone patterns available within the Source. */ + ICAP_HALFTONES = 4361, + /** Specifies which value in an image should be interpreted as the lightest "highlight." All values + * "lighter" than this value will be clipped to this value. Whether lighter values are smaller or + * larger can be determined by examining the Current value of ICAP_PIXELFLAVOR. + */ + ICAP_HIGHLIGHT = 4362, + /** Informs the application which file formats the Source can generate (CapGet()). Tells the Source which file formats the application can handle (CapSet()). + * TWFF_TIFF Used for document + * TWFF_PICT Native Macintosh + * TWFF_BMP Native Microsoft + * TWFF_XBM Used for document + * TWFF_JFIF Wrapper for JPEG + * TWFF_FPX FlashPix, used with digital + * TWFF_TIFFMULTI Multi-page TIFF files + * TWFF_PNG An image format standard intended for use on the web, replaces GIF + * TWFF_SPIFF A standard from JPEG, intended to replace JFIF, also supports JBIG + * TWFF_EXIF File format for use with digital cameras. + */ + ICAP_IMAGEFILEFORMAT = 4364, + /** TRUE means the lamp is currently, or should be set to ON. Sources may not support CapSet() operations. */ + ICAP_LAMPSTATE = 4365, + /** Describes the general color characteristic of the light source used to acquire the image. */ + ICAP_LIGHTSOURCE = 4366, + /** Defines which edge of the "paper" the image's "top" is aligned with. This information is used to adjust the frames to match the + * scanning orientation of the paper. For instance, if an ICAP_SUPPORTEDSIZE of TWSS_ISOA4 has been negotiated, + * and ICAP_ORIENTATION is set to TWOR_LANDSCAPE, then the Source must rotate the frame it downloads to the scanner to reflect the + * orientation of the paper. Please note that setting ICAP_ORIENTATION does not affect the values reported by ICAP_FRAMES; + * it just causes the Source to use them in a different way. The upper-left of the image is defined as the location where both the primary and + * secondary scans originate. (The X axis is the primary scan direction and the Y axis is the secondary scan direction.) + * For a flatbed scanner, the light bar moves in the secondary scan direction. For a handheld scanner, the scanner is drug in the + * secondary scan direction. For a digital camera, the secondary direction is the vertical axis when the viewed image is considered upright. + */ + ICAP_ORIENTATION = 4368, + /** The maximum physical width (X-axis) the Source can acquire (measured in units of ICAP_UNITS). */ + ICAP_PHYSICALWIDTH = 4369, + /** The maximum physical height (Y-axis) the Source can acquire (measured in units of ICAP_UNITS). */ + ICAP_PHYSICALHEIGHT = 4370, + /** Specifies which value in an image should be interpreted as the darkest "shadow." All values + * "darker" than this value will be clipped to this value. + */ + ICAP_SHADOW = 4371, + /** The list of frames the Source will acquire on each page. */ + ICAP_FRAMES = 4372, + /** The native optical resolution along the X-axis of the device being controlled by the Source. Most + * devices will respond with a single value (TW_ONEVALUE). + * This is NOT a list of all resolutions that can be generated by the device. Rather, this is the + * resolution of the device's optics. Measured in units of pixels per unit as defined by + * ICAP_UNITS (pixels per TWUN_PIXELS yields dimensionless data). + */ + ICAP_XNATIVERESOLUTION = 4374, + /** The native optical resolution along the Y-axis of the device being controlled by the Source. + * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS + * yields dimensionless data). + */ + ICAP_YNATIVERESOLUTION = 4375, + /** All the X-axis resolutions the Source can provide. + * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS + * yields dimensionless data). That is, when the units are TWUN_PIXELS, both + * ICAP_XRESOLUTION and ICAP_YRESOLUTION shall report 1 pixel/pixel. Some data sources + * like to report the actual number of pixels that the device reports, but that response is more + * appropriate in ICAP_PHYSICALHEIGHT and ICAP_PHYSICALWIDTH. + */ + ICAP_XRESOLUTION = 4376, + /** All the Y-axis resolutions the Source can provide. + * Measured in units of pixels per unit as defined by ICAP_UNITS (pixels per TWUN_PIXELS + * yields dimensionless data). That is, when the units are TWUN_PIXELS, both + * ICAP_XRESOLUTION and ICAP_YRESOLUTION shall report 1 pixel/pixel. Some data sources + * like to report the actual number of pixels that the device reports, but that response is more + * appropriate in ICAP_PHYSICALHEIGHT and ICAP_PHYSICALWIDTH. + */ + ICAP_YRESOLUTION = 4377, + /** The maximum number of frames the Source can provide or the application can accept per page. + * This is a bounding capability only. It does not establish current or future behavior. + */ + ICAP_MAXFRAMES = 4378, + /** This is used with buffered memory transfers. If TRUE, Source can provide application with tiled image data. */ + ICAP_TILES = 4379, + /** Specifies how the bytes in an image are filled by the Source. TWBO_MSBFIRST indicates that the leftmost bit in the byte (usually bit 7) is + * the byte's Most Significant Bit. + */ + ICAP_BITORDER = 4380, + /** Used for CCITT Group 3 2-dimensional compression. The 'K' factor indicates how often the + * new compression baseline should be re-established. A value of 2 or 4 is common in facsimile + * communication. A value of zero in this field will indicate an infinite K factor—the baseline is + * only calculated at the beginning of the transfer. + */ + ICAP_CCITTKFACTOR = 4381, + /** Describes whether the image was captured transmissively or reflectively. */ + ICAP_LIGHTPATH = 4382, + /** Sense of the pixel whose numeric value is zero (minimum data value). */ + ICAP_PIXELFLAVOR = 4383, + /** Allows the application and Source to identify which color data formats are available. There are + * two options, "planar" and "chunky." + */ + ICAP_PLANARCHUNKY = 4384, + /** How the Source can/should rotate the scanned image data prior to transfer. This doesn't use + * ICAP_UNITS. It is always measured in degrees. Any applied value is additive with any + * rotation specified in ICAP_ORIENTATION. + */ + ICAP_ROTATION = 4385, + /** For devices that support fixed frame sizes. + * Defined sizes match typical page sizes. This specifies the size(s) the Source can/should use to acquire image data. + */ + ICAP_SUPPORTEDSIZES = 4386, + /** Specifies the dividing line between black and white. This is the value the Source will use to + * threshold, if needed, when ICAP_PIXELTYPE:TWPT_BW. + * The value is normalized so there are no units of measure associated with this ICAP. + */ + ICAP_THRESHOLD = 4387, + /** All the X-axis scaling values available. A value of '1.0' is equivalent to 100% scaling. Do not use values less than or equal to zero. */ + ICAP_XSCALING = 4388, + /** All the Y-axis scaling values available. A value of '1.0' is equivalent to 100% scaling. Do not use values less than or equal to zero. + * There are no units inherent with this data as it is normalized to 1.0 being "unscaled." + */ + ICAP_YSCALING = 4389, + /** Used for CCITT data compression only. Indicates the bit order representation of the stored compressed codes. */ + ICAP_BITORDERCODES = 4390, + /** Used only for CCITT data compression. Specifies whether the compressed codes' pixel "sense" + * will be inverted from the Current value of ICAP_PIXELFLAVOR prior to transfer. + */ + ICAP_PIXELFLAVORCODES = 4391, + /** Allows the application and Source to agree upon a common set of color descriptors that are + * made available by the Source. This ICAP is only useful for JPEG-compressed buffered memory image transfers. + */ + ICAP_JPEGPIXELTYPE = 4392, + /** Used only with CCITT data compression. Specifies the minimum number of words of compressed codes (compressed data) to be transmitted per line. */ + ICAP_TIMEFILL = 4394, + /** Specifies the pixel bit depths for the Current value of ICAP_PIXELTYPE. For example, when + * using ICAP_PIXELTYPE:TWPT_GRAY, this capability specifies whether this is 8-bit gray or 4-bit gray. + * This depth applies to all the data channels (for instance, the R, G, and B channels will all have + * this same bit depth for RGB data). + */ + ICAP_BITDEPTH = 4395, + /** Specifies the Reduction Method the Source should use to reduce the bit depth of the data. Most + * commonly used with ICAP_PIXELTYPE:TWPT_BW to reduce gray data to black and white. + */ + ICAP_BITDEPTHREDUCTION = 4396, + /** If TRUE the Source will issue a MSG_XFERREADY before starting the scan. + * Note: The Source may need to scan the image before initiating the transfer. This is the case if + * the scanned image is rotated or merged with another scanned image. + */ + ICAP_UNDEFINEDIMAGESIZE = 4397, + /** Allows the application to query the data source to see if it supports extended image attribute capabilities, + * such as Barcode Recognition, Shaded Area Detection and Removal, Skew detection and Removal, and so on. + */ + ICAP_EXTIMAGEINFO = 4399, + /** Allows the source to define the minimum height (Y-axis) that the source can acquire. */ + ICAP_MINIMUMHEIGHT = 4400, + /** Allows the source to define theminimum width (X-axis) that the source can acquire. */ + ICAP_MINIMUMWIDTH = 4401, + /** Use this capability to have the Source discard blank images. The Application never sees these + * images during the scanning session. + * TWBP_DISABLE – this must be the default state for the Source. It indicates that all images will + * be delivered to the Application, none of them will be discarded. + * TWBP_AUTO – if this is used, then the Source will decide if an image is blank or not and discard + * as appropriate. + * If the specified value is a positive number in the range 0 to 231–1, then this capability will use it + * as the byte size cutoff point to identify which images are to be discarded. If the size of the image + * is less than or equal to this value, then it will be discarded. If the size of the image is greater + * than this value, then it will be kept so that it can be transferred to the Application. + */ + ICAP_AUTODISCARDBLANKPAGES = 4404, + /** Flip rotation is used to properly orient images that flip orientation every other image. + * TWFR_BOOK The images to be scanned are viewed in book form, flipping each page from left to right or right to left. + * TWFR_FANFOLD The images to be scanned are viewed in fanfold paper style, flipping each page up or down. + */ + ICAP_FLIPROTATION = 4406, + /** Turns bar code detection on and off. */ + ICAP_BARCODEDETECTIONENABLED = 4407, + /** Provides a list of bar code types that can be detected by the current Data Source. */ + ICAP_SUPPORTEDBARCODETYPES = 4408, + /** The maximum number of supported search priorities. */ + ICAP_BARCODEMAXSEARCHPRIORITIES = 4409, + /** A prioritized list of bar code types dictating the order in which bar codes will be sought. */ + ICAP_BARCODESEARCHPRIORITIES = 4410, + /** Restricts bar code searching to certain orientations, or prioritizes one orientation over the other. */ + ICAP_BARCODESEARCHMODE = 4411, + /** Restricts the number of times a search will be retried if none are found on each page. */ + ICAP_BARCODEMAXRETRIES = 4412, + /** Restricts the total time spent on searching for a bar code on each page. */ + ICAP_BARCODETIMEOUT = 4413, + /** When used with CapGet(), returns all camera supported lens zooming range. */ + ICAP_ZOOMFACTOR = 4414, + /** Turns patch code detection on and off. */ + ICAP_PATCHCODEDETECTIONENABLED = 4415, + /** A list of patch code types that may be detected by the current Data Source. */ + ICAP_SUPPORTEDPATCHCODETYPES = 4416, + /** The maximum number of supported search priorities. */ + ICAP_PATCHCODEMAXSEARCHPRIORITIES = 4417, + /** A prioritized list of patch code types dictating the order in which patch codes will be sought. */ + ICAP_PATCHCODESEARCHPRIORITIES = 4418, + /** Restricts patch code searching to certain orientations, or prioritizes one orientation over the other. */ + ICAP_PATCHCODESEARCHMODE = 4419, + /** Restricts the number of times a search will be retried if none are found on each page. */ + ICAP_PATCHCODEMAXRETRIES = 4420, + /** Restricts the total time spent on searching for a patch code on each page. */ + ICAP_PATCHCODETIMEOUT = 4421, + /** For devices that support flash. CapSet() selects the flash to be used (if any). CapGet() reports the current setting. + * This capability replaces ICAP_FLASHUSED, which is only able to negotiate the flash being on or off. + */ + ICAP_FLASHUSED2 = 4422, + /** For devices that support image enhancement filtering. This capability selects the algorithm used to improve the quality of the image. */ + ICAP_IMAGEFILTER = 4423, + /** For devices that support noise filtering. This capability selects the algorithm used to remove noise. */ + ICAP_NOISEFILTER = 4424, + /** Overscan is used to scan outside of the boundaries described by ICAP_FRAMES, and is used to help acquire image data that + * may be lost because of skewing. + * This is primarily of use for transport scanners which rely on edge detection to begin scanning. + * If overscan is supported, then the device is capable of scanning in the inter-document gap to get the skewed image information. + */ + ICAP_OVERSCAN = 4425, + /** Turns automatic border detection on and off. */ + ICAP_AUTOMATICBORDERDETECTION = 4432, + /** Turns automatic deskew correction on and off. */ + ICAP_AUTOMATICDESKEW = 4433, + /** When TRUE this capability depends on intelligent features within the Source to automatically + * rotate the image to the correct position. + */ + ICAP_AUTOMATICROTATE = 4434, + /** Added 1.9 */ + ICAP_JPEGQUALITY = 4435, + /** Added 1.91 */ + ICAP_FEEDERTYPE = 4436, + /** Added 1.91 */ + ICAP_ICCPROFILE = 4437, + /** Added 2.0 */ + ICAP_AUTOSIZE = 4438, + /** Added 2.1 */ + ICAP_AUTOMATICCROPUSESFRAME = 4439, + /** Added 2.1 */ + ICAP_AUTOMATICLENGTHDETECTION = 4440, + /** Added 2.1 */ + ICAP_AUTOMATICCOLORENABLED = 4441, + /** Added 2.1 */ + ICAP_AUTOMATICCOLORNONCOLORPIXELTYPE = 4442, + /** Added 2.1 */ + ICAP_COLORMANAGEMENTENABLED = 4443, + /** Added 2.1 */ + ICAP_IMAGEMERGE = 4444, + /** Added 2.1 */ + ICAP_IMAGEMERGEHEIGHTTHRESHOLD = 4445, + /** Added 2.1 */ + ICAP_SUPPORTEDEXTIMAGEINFO = 4446 +} + +/** Capabilities exist in many varieties but all have a Default Value, Current Value, and may have other values available that can be supported if selected. + * To help categorize the supported values into clear structures, TWAIN defines four types of containers for capabilities = + * TW_ONEVALUE, TW_ARRAY, TW_RANGE and TW_ENUMERATION. + */ +declare enum EnumDWT_CapType { + /** Nothing. */ + TWON_NONE = 0, + /** A rectangular array of values that describe a logical item. It is similar to the TW_ONEVALUE because the current and default values are the same and + * there are no other values to select from. For example, a list of the names, such as the supported capabilities list returned by the CAP_SUPPORTEDCAPS + * capability, would use this type of container. + */ + TWON_ARRAY = 3, + /** This is the most general type because it defines a list of values from which the Current Value can be chosen. + * The values do not progress uniformly through a range and there is not a consistent step size between the values. + * For example, if a Source's resolution options do not occur in even step sizes then an enumeration would be used (for example, 150, 400, and 600). + */ + TWON_ENUMERATION = 4, + /** A single value whose current and default values are coincident. The range of available values for this type of capability is simply this single value. + * For example, a capability that indicates the presence of a document feeder could be of this type. + */ + TWON_ONEVALUE = 5, + /** Many capabilities allow users to select their current value from a range of regularly spaced values. + * The capability can specify the minimum and maximum acceptable values and the incremental step size between the values. + * For example, resolution might be supported from 100 to 600 in steps of 50 (100, 150, 200, ..., 550, 600). + */ + TWON_RANGE = 6 +} + +/** ICAP_XFERMECH values. */ +declare enum EnumDWT_TransferMode { + /** Native transfers require the data to be transferred to a single large block of RAM. Therefore, + * they always face the risk of having an inadequate amount of RAM available to perform the transfer successfully. + */ + TWSX_NATIVE = 0, + /** Disk File Mode Transfers. */ + TWSX_FILE = 1, + /** Buffered Memory Mode Transfers. */ + TWSX_MEMORY = 2, + /** added 1.91 */ + TWSX_MEMFILE = 4 +} + +/** ICAP_IMAGEFILEFORMAT values. */ +declare enum EnumDWT_FileFormat { + /** Used for document imaging. Tagged Image File Format */ + TWFF_TIFF = 0, + /** Native Macintosh format. Macintosh PICT */ + TWFF_PICT = 1, + /** Native Microsoft format. Windows Bitmap */ + TWFF_BMP = 2, + /** Used for document imaging. X-Windows Bitmap */ + TWFF_XBM = 3, + /** Wrapper for JPEG images. JPEG File Interchange Format */ + TWFF_JFIF = 4, + /** FlashPix, used with digital cameras. Flash Pix */ + TWFF_FPX = 5, + /** Multi-page TIFF files. Multi-page tiff file */ + TWFF_TIFFMULTI = 6, + /** An image format standard intended for use on the web, replaces GIF. */ + TWFF_PNG = 7, + /** A standard from JPEG, intended to replace JFIF, also supports JBIG. */ + TWFF_SPIFF = 8, + /** File format for use with digital cameras. */ + TWFF_EXIF = 9, + /** A file format from Adobe. 1.91 NB: this is not PDF/A */ + TWFF_PDF = 10, + /** A file format from the Joint Photographic Experts Group. 1.91 */ + TWFF_JP2 = 11, + /** 1.91 */ + TWFF_JPN = 12, + /** 1.91 */ + TWFF_JPX = 13, + /** A file format from LizardTech. 1.91 */ + TWFF_DEJAVU = 14, + /** A file format from Adobe. 2.0 */ + TWFF_PDFA = 15, + /** 2.1 Adobe PDF/A, Version 2 */ + TWFF_PDFA2 = 16 +} + +/** TIFF file compression type. */ +declare enum EnumDWT_TIFFCompressionType { + /** Auto mode. */ + TIFF_AUTO = 0, + /** Dump mode. */ + TIFF_NONE = 1, + /** CCITT modified Huffman RLE. */ + TIFF_RLE = 2, + /** CCITT Group 3 fax encoding. */ + TIFF_FAX3 = 3, + /** CCITT T.4 (TIFF 6 name). */ + TIFF_T4 = 3, + /** CCITT Group 4 fax encoding */ + TIFF_FAX4 = 4, + /** CCITT T.6 (TIFF 6 name). */ + TIFF_T6 = 4, + /** Lempel Ziv and Welch */ + TIFF_LZW = 5, + TIFF_JPEG = 7, + TIFF_PACKBITS = 32773 +} + +/** The method to do interpolation. */ +declare enum EnumDWT_InterpolationMethod { + IM_NEARESTNEIGHBOUR = 1, + IM_BILINEAR = 2, + IM_BICUBIC = 3, + IM_BESTQUALITY = 5 +} + +/** Image type */ +declare enum EnumDWT_ImageType { + /** Native Microsoft format. */ + IT_BMP = 0, + /** JPEG format. */ + IT_JPG = 1, + /** Tagged Image File Format. */ + IT_TIF = 2, + /** An image format standard intended for use on the web, replaces GIF. */ + IT_PNG = 3, + /** A file format from Adobe. */ + IT_PDF = 4, + IT_ALL = 5 +} + +/** PDF file compression type. */ +declare enum EnumDWT_PDFCompressionType { + /** Auto mode. */ + PDF_AUTO = 0, + /** CCITT Group 3 fax encoding. */ + PDF_FAX3 = 1, + /** CCITT Group 4 fax encoding */ + PDF_FAX4 = 2, + /** Lempel Ziv and Welch */ + PDF_LZW = 3, + /** CCITT modified Huffman RLE. */ + PDF_RLE = 4, + PDF_JPEG = 5 +} + +declare enum EnumDWT_ShowMode { + /** Activates the window and displays it in its current size and position. */ + SW_ACTIVE = 0, + /** Maximizes the window */ + SW_MAX = 1, + /** Minimize the window */ + SW_MIN = 2, + /** Close the latest opened editor window */ + SW_CLOSE = 3, + /** Check whether a window exists */ + SW_IFLIVE = 4 +} + +/** The kind of data stored in the container. */ +declare enum EnumDWT_CapValueType { + TWTY_INT8 = 0, + /** Means Item is a TW_INT16 */ + TWTY_INT16 = 1, + /** Means Item is a TW_INT32 */ + TWTY_INT32 = 2, + /** Means Item is a TW_UINT8 */ + TWTY_UINT8 = 3, + /** Means Item is a TW_UINT16 */ + TWTY_UINT16 = 4, + /** Means Item is a TW_int */ + TWTY_int = 5, + /** Means Item is a TW_BOOL */ + TWTY_BOOL = 6, + /** Means Item is a TW_FIX32 */ + TWTY_FIX32 = 7, + /** Means Item is a TW_FRAME */ + TWTY_FRAME = 8, + /** Means Item is a TW_STR32 */ + TWTY_STR32 = 9, + /** Means Item is a TW_STR64 */ + TWTY_STR64 = 10, + /** Means Item is a TW_STR128 */ + TWTY_STR128 = 11, + /** Means Item is a TW_STR255 */ + TWTY_STR255 = 12 +} + +/** ICAP_UNITS values. */ +declare enum EnumDWT_UnitType { + TWUN_INCHES = 0, + TWUN_CENTIMETERS = 1, + TWUN_PICAS = 2, + TWUN_POINTS = 3, + TWUN_TWIPS = 4, + TWUN_PIXELS = 5, + TWUN_MILLIMETERS = 6 +} + +/** ICAP_DUPLEX values. */ +declare enum EnumDWT_DUPLEX { + TWDX_NONE = 0, + TWDX_1PASSDUPLEX = 1, + TWDX_2PASSDUPLEX = 2 +} + +/** CAP_LANGUAGE values. */ +declare enum EnumDWT_CapLanguage { + /** Danish */ + TWLG_DAN = 0, + /** Dutch */ + TWLG_DUT = 1, + /** International English */ + TWLG_ENG = 2, + /** French Canadian */ + TWLG_FCF = 3, + /** Finnish */ + TWLG_FIN = 4, + /** French */ + TWLG_FRN = 5, + /** German */ + TWLG_GER = 6, + /** Icelandic */ + TWLG_ICE = 7, + /** Italian */ + TWLG_ITN = 8, + /** Norwegian */ + TWLG_NOR = 9, + /** Portuguese */ + TWLG_POR = 10, + /** Spanish */ + TWLG_SPA = 11, + /** Swedish */ + TWLG_SWE = 12, + /** U.S. English */ + TWLG_USA = 13, + /** Added for 1.8 */ + TWLG_USERLOCALE = -1, + TWLG_AFRIKAANS = 14, + TWLG_ALBANIA = 15, + TWLG_ARABIC = 16, + TWLG_ARABIC_ALGERIA = 17, + TWLG_ARABIC_BAHRAIN = 18, + TWLG_ARABIC_EGYPT = 19, + TWLG_ARABIC_IRAQ = 20, + TWLG_ARABIC_JORDAN = 21, + TWLG_ARABIC_KUWAIT = 22, + TWLG_ARABIC_LEBANON = 23, + TWLG_ARABIC_LIBYA = 24, + TWLG_ARABIC_MOROCCO = 25, + TWLG_ARABIC_OMAN = 26, + TWLG_ARABIC_QATAR = 27, + TWLG_ARABIC_SAUDIARABIA = 28, + TWLG_ARABIC_SYRIA = 29, + TWLG_ARABIC_TUNISIA = 30, + /** United Arabic Emirates */ + TWLG_ARABIC_UAE = 31, + TWLG_ARABIC_YEMEN = 32, + TWLG_BASQUE = 33, + TWLG_BYELORUSSIAN = 34, + TWLG_BULGARIAN = 35, + TWLG_CATALAN = 36, + TWLG_CHINESE = 37, + TWLG_CHINESE_HONGKONG = 38, + /** People's Republic of China */ + TWLG_CHINESE_PRC = 39, + TWLG_CHINESE_SINGAPORE = 40, + TWLG_CHINESE_SIMPLIFIED = 41, + TWLG_CHINESE_TAIWAN = 42, + TWLG_CHINESE_TRADITIONAL = 43, + TWLG_CROATIA = 44, + TWLG_CZECH = 45, + TWLG_DANISH = 0, + TWLG_DUTCH = 1, + TWLG_DUTCH_BELGIAN = 46, + TWLG_ENGLISH = 2, + TWLG_ENGLISH_AUSTRALIAN = 47, + TWLG_ENGLISH_CANADIAN = 48, + TWLG_ENGLISH_IRELAND = 49, + TWLG_ENGLISH_NEWZEALAND = 50, + TWLG_ENGLISH_SOUTHAFRICA = 51, + TWLG_ENGLISH_UK = 52, + TWLG_ENGLISH_USA = 13, + TWLG_ESTONIAN = 53, + TWLG_FAEROESE = 54, + TWLG_FARSI = 55, + TWLG_FINNISH = 4, + TWLG_FRENCH = 5, + TWLG_FRENCH_BELGIAN = 56, + TWLG_FRENCH_CANADIAN = 3, + TWLG_FRENCH_LUXEMBOURG = 57, + TWLG_FRENCH_SWISS = 58, + TWLG_GERMAN = 6, + TWLG_GERMAN_AUSTRIAN = 59, + TWLG_GERMAN_LUXEMBOURG = 60, + TWLG_GERMAN_LIECHTENSTEIN = 61, + TWLG_GERMAN_SWISS = 62, + TWLG_GREEK = 63, + TWLG_HEBREW = 64, + TWLG_HUNGARIAN = 65, + TWLG_ICELANDIC = 7, + TWLG_INDONESIAN = 66, + TWLG_ITALIAN = 8, + TWLG_ITALIAN_SWISS = 67, + TWLG_JAPANESE = 68, + TWLG_KOREAN = 69, + TWLG_KOREAN_JOHAB = 70, + TWLG_LATVIAN = 71, + TWLG_LITHUANIAN = 72, + TWLG_NORWEGIAN = 9, + TWLG_NORWEGIAN_BOKMAL = 73, + TWLG_NORWEGIAN_NYNORSK = 74, + TWLG_POLISH = 75, + TWLG_PORTUGUESE = 10, + TWLG_PORTUGUESE_BRAZIL = 76, + TWLG_ROMANIAN = 77, + TWLG_RUSSIAN = 78, + TWLG_SERBIAN_LATIN = 79, + TWLG_SLOVAK = 80, + TWLG_SLOVENIAN = 81, + TWLG_SPANISH = 11, + TWLG_SPANISH_MEXICAN = 82, + TWLG_SPANISH_MODERN = 83, + TWLG_SWEDISH = 12, + TWLG_THAI = 84, + TWLG_TURKISH = 85, + TWLG_UKRANIAN = 86, + /** More stuff added for 1.8 */ + TWLG_ASSAMESE = 87, + TWLG_BENGALI = 88, + TWLG_BIHARI = 89, + TWLG_BODO = 90, + TWLG_DOGRI = 91, + TWLG_GUJARATI = 92, + TWLG_HARYANVI = 93, + TWLG_HINDI = 94, + TWLG_KANNADA = 95, + TWLG_KASHMIRI = 96, + TWLG_MALAYALAM = 97, + TWLG_MARATHI = 98, + TWLG_MARWARI = 99, + TWLG_MEGHALAYAN = 100, + TWLG_MIZO = 101, + TWLG_NAGA = 102, + TWLG_ORISSI = 103, + TWLG_PUNJABI = 104, + TWLG_PUSHTU = 105, + TWLG_SERBIAN_CYRILLIC = 106, + TWLG_SIKKIMI = 107, + TWLG_SWEDISH_FINLAND = 108, + TWLG_TAMIL = 109, + TWLG_TELUGU = 110, + TWLG_TRIPURI = 111, + TWLG_URDU = 112, + TWLG_VIETNAMESE = 113 +} + +/** TWAIN Supported sizes. */ +declare enum EnumDWT_CapSupportedSizes { + /** 0 */ + TWSS_NONE = 0, + /** 1 */ + TWSS_A4LETTER = 1, + /** 2 */ + TWSS_B5LETTER = 2, + /** 3 */ + TWSS_USLETTER = 3, + /** 4 */ + TWSS_USLEGAL = 4, + /** Added 1.5 + * 5 + */ + TWSS_A5 = 5, + /** 6 */ + TWSS_B4 = 6, + /** 7 */ + TWSS_B6 = 7, + /** Added 1.7 + * 9 + */ + TWSS_USLEDGER = 9, + /** 10 */ + TWSS_USEXECUTIVE = 10, + /** 11 */ + TWSS_A3 = 11, + /** 12 */ + TWSS_B3 = 12, + /** 13 */ + TWSS_A6 = 13, + /** 14 */ + TWSS_C4 = 14, + /** 15 */ + TWSS_C5 = 15, + /** 16 */ + TWSS_C6 = 16, + /** Added 1.8 + * 17 + */ + TWSS_4A0 = 17, + /** 18 */ + TWSS_2A0 = 18, + /** 19 */ + TWSS_A0 = 19, + /** 20 */ + TWSS_A1 = 20, + /** 21 */ + TWSS_A2 = 21, + /** 1 */ + TWSS_A4 = 1, + /** 22 */ + TWSS_A7 = 22, + /** 23 */ + TWSS_A8 = 23, + /** 24 */ + TWSS_A9 = 24, + /** 25 */ + TWSS_A10 = 25, + /** 26 */ + TWSS_ISOB0 = 26, + /** 27 */ + TWSS_ISOB1 = 27, + /** 28 */ + TWSS_ISOB2 = 28, + /** 12 */ + TWSS_ISOB3 = 12, + /** 6 */ + TWSS_ISOB4 = 6, + /** 29 */ + TWSS_ISOB5 = 29, + /** 7 */ + TWSS_ISOB6 = 7, + /** 30 */ + TWSS_ISOB7 = 30, + /** 31 */ + TWSS_ISOB8 = 31, + /** 32 */ + TWSS_ISOB9 = 32, + /** 33 */ + TWSS_ISOB10 = 33, + /** 34 */ + TWSS_JISB0 = 34, + /** 35 */ + TWSS_JISB1 = 35, + /** 36 */ + TWSS_JISB2 = 36, + /** 37 */ + TWSS_JISB3 = 37, + /** 38 */ + TWSS_JISB4 = 38, + /** 2 */ + TWSS_JISB5 = 2, + /** 39 */ + TWSS_JISB6 = 39, + /** 40 */ + TWSS_JISB7 = 40, + /** 41 */ + TWSS_JISB8 = 41, + /** 41 */ + TWSS_JISB9 = 42, + /** 43 */ + TWSS_JISB10 = 43, + /** 44 */ + TWSS_C0 = 44, + /** 45 */ + TWSS_C1 = 45, + /** 46 */ + TWSS_C2 = 46, + /** 47 */ + TWSS_C3 = 47, + /** 48 */ + TWSS_C7 = 48, + /** 49 */ + TWSS_C8 = 49, + /** 50 */ + TWSS_C9 = 50, + /** 51 */ + TWSS_C10 = 51, + /** 52 */ + TWSS_USSTATEMENT = 52, + /** 53 */ + TWSS_BUSINESSCARD = 53, + /** 54. Added 2.1 */ + TWSS_MAXSIZE = 54 +} + +/** CAP_FEEDERALIGNMENT values. */ +declare enum EnumDWT_CapFeederAlignment { + /** The alignment is free-floating. Applications should assume that the origin for frames is on the left. */ + TWFA_NONE = 0, + /** The alignment is to the left. */ + TWFA_LEFT = 1, + /** The alignment is centered. This means that the paper will be fed in the middle of the ICAP_PHYSICALWIDTH of the + * device. If this is set, then the Application should calculate any frames with a left offset of zero. + */ + TWFA_CENTER = 2, + /** The alignment is to the right. */ + TWFA_RIGHT = 3 +} +/** CAP_FEEDERORDER values. */ +declare enum EnumDWT_CapFeederOrder { + /** The feeder starts with the top of the first page. */ + TWFO_FIRSTPAGEFIRST = 0, + /** The feeder starts with the top of the last page. */ + TWFO_LASTPAGEFIRST = 1 +} + +/** CAP_PRINTER values. */ +declare enum EnumDWT_CapPrinter { + TWPR_IMPRINTERTOPBEFORE = 0, + TWPR_IMPRINTERTOPAFTER = 1, + TWPR_IMPRINTERBOTTOMBEFORE = 2, + TWPR_IMPRINTERBOTTOMAFTER = 3, + TWPR_ENDORSERTOPBEFORE = 4, + TWPR_ENDORSERTOPAFTER = 5, + TWPR_ENDORSERBOTTOMBEFORE = 6, + TWPR_ENDORSERBOTTOMAFTER = 7 +} + +/** CAP_PRINTERMODE values. */ +declare enum EnumDWT_CapPrinterMode { + /** Specifies that the printed text will consist of a single string. */ + TWPM_SINGLESTRING = 0, + /** Specifies that the printed text will consist of an enumerated list of strings to be printed in order. */ + TWPM_MULTISTRING = 1, + /** Specifies that the printed string will consist of a compound of a String followed by a value followed by a suffix string. */ + TWPM_COMPOUNDSTRING = 2 +} + +/** ICAP_BITDEPTHREDUCTION values. */ +declare enum EnumDWT_CapBitdepthReduction { + TWBR_THRESHOLD = 0, + TWBR_HALFTONE = 1, + TWBR_CUSTHALFTONE = 2, + TWBR_DIFFUSION = 3 +} + +/** ICAP_BITORDER values. */ +declare enum EnumDWT_CapBitOrder { + TWBO_LSBFIRST = 0, + /** Indicates that the leftmost bit in the byte (usually bit 7) is the byte's Most Significant Bit. */ + TWBO_MSBFIRST = 1 +} + +/** ICAP_FILTER values. */ +declare enum EnumDWT_CapFilterType { + TWFT_RED = 0, + TWFT_GREEN = 1, + TWFT_BLUE = 2, + TWFT_NONE = 3, + TWFT_WHITE = 4, + TWFT_CYAN = 5, + TWFT_MAGENTA = 6, + TWFT_YELLOW = 7, + TWFT_BLACK = 8 +} + +/** ICAP_FLASHUSED2 values. */ +declare enum EnumDWT_CapFlash { + TWFL_NONE = 0, + TWFL_OFF = 1, + TWFL_ON = 2, + TWFL_AUTO = 3, + TWFL_REDEYE = 4 +} + +/** ICAP_FLIPROTATION values. */ +declare enum EnumDWT_CapFlipRotation { + /** The images to be scanned are viewed in book form, flipping each page from left to right or right to left. */ + TWFR_BOOK = 0, + /** The images to be scanned are viewed in fanfold paper style, flipping each page up or down. */ + TWFR_FANFOLD = 1 +} + +/** ICAP_IMAGEFILTER values. */ +declare enum EnumDWT_CapImageFilter { + TWIF_NONE = 0, + TWIF_AUTO = 1, + /** Good for halftone images. */ + TWIF_LOWPASS = 2, + /** Good for improving text. */ + TWIF_BANDPASS = 3, + /** Good for improving fine lines. */ + TWIF_HIGHPASS = 4, + TWIF_TEXT = 3, + TWIF_FINELINE = 4 +} + +/** ICAP_LIGHTPATH values. */ +declare enum EnumDWT_CapLightPath { + TWLP_REFLECTIVE = 0, + TWLP_TRANSMISSIVE = 1 +} + +/** ICAP_LIGHTSOURCE values. */ +declare enum EnumDWT_CapLightSource { + TWLS_RED = 0, + TWLS_GREEN = 1, + TWLS_BLUE = 2, + TWLS_NONE = 3, + TWLS_WHITE = 4, + TWLS_UV = 5, + TWLS_IR = 6 +} + +/** TWEI_MAGTYPE values. (MD_ means Mag Type) Added 2.0 */ +declare enum EnumDWT_MagType { + /** Added 2.0 */ + TWMD_MICR = 0, + /** added 2.1 */ + TWMD_RAW = 1, + /** added 2.1 */ + TWMD_INVALID = 2 +} + +/** ICAP_NOISEFILTER values. */ +declare enum EnumDWT_CapNoiseFilter { + TWNF_NONE = 0, + TWNF_AUTO = 1, + TWNF_LONEPIXEL = 2, + TWNF_MAJORITYRULE = 3 +} + +/** ICAP_ORIENTATION values. */ +declare enum EnumDWT_CapORientation { + TWOR_ROT0 = 0, + TWOR_ROT90 = 1, + TWOR_ROT180 = 2, + TWOR_ROT270 = 3, + TWOR_PORTRAIT = 0, + TWOR_LANDSCAPE = 3, + /** 2.0 */ + TWOR_AUTO = 4, + /** 2.0 */ + TWOR_AUTOTEXT = 5, + /** 2.0 */ + TWOR_AUTOPICTURE = 6 +} + +/** ICAP_OVERSCAN values. */ +declare enum EnumDWT_CapOverscan { + TWOV_NONE = 0, + TWOV_AUTO = 1, + TWOV_TOPBOTTOM = 2, + TWOV_LEFTRIGHT = 3, + TWOV_ALL = 4 +} + +/** ICAP_PIXELFLAVOR values. */ +declare enum EnumDWT_CapPixelFlavor { + /** Zero pixel represents darkest shade. zero pixel represents darkest shade */ + TWPF_CHOCOLATE = 0, + /** Zero pixel represents lightest shade. zero pixel represents lightest shade */ + TWPF_VANILLA = 1 +} + +/** ICAP_PLANARCHUNKY values. */ +declare enum EnumDWT_CapPlanarChunky { + TWPC_CHUNKY = 0, + TWPC_PLANAR = 1 +} + +/** Data source status. */ +declare enum EnumDWT_DataSourceStatus { + /** Indicate the data source is closed. */ + TWDSS_CLOSED = 0, + /** Indicate the data source is opened. */ + TWDSS_OPENED = 1, + /** Indicate the data source is enabled. */ + TWDSS_ENABLED = 2, + /** Indicate the data source is acquiring image. */ + TWDSS_ACQUIRING = 3 +} + +/** Fit window type */ +declare enum EnumDWT_FitWindowType { + /** Fit the image to the width and height of the window */ + enumFitWindow = 0, + /** Fit the image to the height of the window */ + enumFitWindowHeight = 1, + /** Fit the image to the width of the window */ + enumFitWindowWidth = 2 +} + +declare enum EnumDWT_UploadDataFormat { + Binary = 0, + Base64 = 1 +} + +declare enum EnumDWT_MouseShape { + Default = 0, + Hand = 1, + Crosshair = 2, + Zoom = 3 +} + +/** + * @class + */ +// properties (get/set) / sync functions +interface WebTwain { + /** + * Returns or sets whether multi-page selection is supported. + * @type {bool} + */ + AllowMultiSelect: boolean; + + /** + * [Deprecated.] Returns or sets whether allowing the plugin to send authentication request. The default value of this property is TRUE. + * @type {bool} + */ + AllowPluginAuthentication: boolean; + + /** + * [Deprecated.] Returns or sets whether the async mode is activated. With this mode, Dynamic Web TWAIN is able to upload/download files via HTTP/FTP asynchronously. The default value is false. + * @type {bool} + */ + AsyncMode: boolean; + + /** + * Returns or sets the background color of the main control. It is a value specifying the 24-bit RGB value. + * @type {int} + */ + BackgroundColor: number; + + /** + * Returns or sets the fill color of the selected area of an image when it is cut, erased or rotated. It is a value specifying the 24-bit RGB value. + * @type {int} + */ + BackgroundFillColor: number; + + /** + * [Deprecated.] Returns the number of barcode detected in an image. + * @type {int} + */ + BarcodeCount: number; + + /** + * Returns or sets the pixel bit depths for the current value of PixelType property. This is a runtime property. + * @type {short} + */ + BitDepth: number; + + /** + * Returns the current deviation of the pixels in the image. + * @type {float} + */ + BlankImageCurrentStdDev: number; + + /** + * Returns or sets the standard deviation of the pixels in the image. + * @type {float} + */ + BlankImageMaxStdDev: number; + + /** + * Returns or sets the dividing line between black and white. The default value is 128. + * @type {int} + */ + BlankImageThreshold: number; + + /** + * [Deprecated.] Returns or sets the border style. + * @type {EnumDWT_BorderStyle} + */ + BorderStyle: EnumDWT_BorderStyle; + + /** + * Returns or sets the brightness values available within the Source. This is a runtime property. + * @type {float} + */ + Brightness: number; + + /** + * [Deprecated.] Sets or returns whether brokerprocess is enabled for scanning. + * @type {int} + */ + BrokerProcessType: number; + + /** + * Sets or returns how much physical memory is allowed for storing images currently loaded in Dynamic Web TWAIN. Once the limit is reached, images will be cached on the hard disk. + * @type {int} + */ + BufferMemoryLimit: number; + + /** + * Specifies the capabiltiy to be negotiated. This is a runtime property. + * @type {EnumDWT_Cap} + */ + Capability: EnumDWT_Cap; + + /** + * Sets or returns the index (0-based) of a list to indicate the Current Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. + * @type {int} + */ + CapCurrentIndex: number; + + /** + * Sets or returns the current value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {double} + */ + CapCurrentValue: number; + + /** + * Returns the index (0-based) of a list to indicate the Default Value when the value of the CapType property is TWON_ENUMERATION. If the data type of the capability is String, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime, read-only property. + * @type {int} + */ + CapDefaultIndex: number; + + /** + * Returns the default value in a range when the value of the CapType property is TWON_RANGE. This is a runtime, read-only property. + * @type {double} + */ + CapDefaultValue: number; + + /** + * Sets or returns the maximum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {double} + */ + CapMaxValue: number; + + /** + * Sets or returns the minimum value in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {double} + */ + CapMinValue: number; + + /** + * [Deprecated.] Sets or returns how many items are in the list when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. For String data type, the list is in CapItemsString property. For other data types, the list is in CapItems property. This is a runtime property. + * @type {int} + */ + CapNumItems: number; + + /** + * [Deprecated.] Replaced by GetCapItemsString method and SetCapItemsString method. + * @type {string} + */ + CapItemsString: string; + + /** + * Sets or returns the step size in a range when the value of the CapType property is TWON_RANGE. This is a runtime property. + * @type {double} + */ + CapStepSize: number; + + /** + * Sets or returns the type of capability container used to exchange capability information between application and source. This is a runtime property. + * @type {EnumDWT_CapType} + */ + CapType: EnumDWT_CapType; + + /** + * Returns or sets the value of the capability specified by Capability property when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. + * @type {double} + */ + CapValue: number; + + /** + * Sets or returns the string value for a capability when the value of the CapType property is TWON_ONEVALUE. This is a runtime property. + * @type {string} + */ + CapValueString: string; + + /** + * Sets or returns the value type for reading the value of a capability. This is a runtime property. + * @type {short} + */ + CapValueType: number; + + /** + * Returns or sets the contrast values available within the Source. This is a runtime property. + * @type {float} + */ + Contrast: number; + + /** + * Sets or returns the product name string for the application identity. + * @type {string} + */ + ProductName: string; + + /** + * Returns or sets current index of image in buffer. This is a runtime property. + * @type {short} + */ + CurrentImageIndexInBuffer: number; + + /** + * Returns the device name of current source. This is a runtime, read-only property. + * @type {string} + */ + CurrentSourceName: string; + + /** + * Returns the value indicating the data source status. This is a runtime, read-only property. + * @type {int} + */ + DataSourceStatus: number; + + /** + * Returns the device name of default source. This is a runtime, read-only property. + * @type {string} + */ + DefaultSourceName: string; + + /** + * Returns whether the source supports duplex. If so, it further returns the level of duplex the Source supports (one pass or two pass duplex). This is a runtime, read-only property. + * @type {int} + */ + Duplex: number; + + /** + * [Deprecated.] Returns or sets whether the user can zoom image using hot key. + * @type {bool} + */ + EnableInteractiveZoom: boolean; + + /** + * Returns the error code. This is a runtime, read-only property. + * @type {int} + */ + ErrorCode: number; + + /** + * Returns the error string. This is a runtime, read-only property. + * @type {string} + */ + ErrorString: string; + + /** + * Returns or sets whether to resize the image to fit the image to the width or height of the window. To use the property, the view mode should be set to -1 by -1. You can use SetViewMode method to set the view mode. + * @type {EnumDWT_FitWindowType} + */ + FitWindowType: EnumDWT_FitWindowType; + + /** + * Returns or sets the password used to log into the FTP server. + * @type {string} + */ + FTPPassword: string; + + /** + * Returns or sets the port number of the FTP server. + * @type {int} + */ + FTPPort: number; + + /** + * Returns or sets the user name used to log into the FTP server. + * @type {string} + */ + FTPUserName: string; + + /** + * Returns how many images are in buffer. This is a runtime, read-only property. + * @type {short} + */ + HowManyImagesInBuffer: number; + + /** + * Specifies the field name of uploaded image through POST. + * @type {string} + */ + HttpFieldNameOfUploadedImage: string; + + /** + * [Deprecated.] Sets or returns the password used to log into the HTTP server. + * @type {string} + */ + HTTPPassword: string; + + /** + * Returns or sets the port number of the HTTP server. + * @type {int} + */ + HTTPPort: number; + + /** + * Returns the response string from the HTTP server if an error occurs for HTTPUploadThroughPost() method. This is a runtime, read-only property. + * @type {string} + */ + HTTPPostResponseString: string; + + /** + * [Deprecated.] Returns or sets the user name used to log into the HTTP server. + * @type {string} + */ + HTTPUserName: string; + + /** + * Returns or sets whether the feature of disk caching is enabled. + * @type {bool} + */ + IfAllowLocalCache: boolean; + + /** + * Returns or sets whether insert or append new scanned images. + * @type {bool} + */ + IfAppendImage: boolean; + + /** + * Returns or sets whether the Source's Auto-brightness function is enabled. This is a runtime property. + * @type {bool} + */ + IfAutoBright: boolean; + + /** + * Returns or sets whether the data source (scanner) will discard blank images during scanning. The property works only if the device and its driver support discarding blank pages. You can find whether your device supports this capbility from its user manual. Or, you can use the built-in methods of Dynamic Web TWAIN to detect blank images: IsBlankImage, IsBlankImageEx. + * @type {bool} + */ + IfAutoDiscardBlankpages: boolean; + + /** + * Returns or sets whether the Source enable automatic document feeding process. This is a runtime property. + * @type {bool} + */ + IfAutoFeed: boolean; + + /** + * Turns automatic border detection on and off. The property works only if the device and its driver support detecting the border automatically. You can find whether your device supports this capbility from its user manual. + * @type {bool} + */ + IfAutomaticBorderDetection: boolean; + + /** + * Turns automatic skew correction on and off. + * @type {bool} + */ + IfAutomaticDeskew: boolean; + + /** + * Returns or sets whether the Source enables the automatic document scanning process. This is a runtime property. + * @type {bool} + */ + IfAutoScan: boolean; + + /** + * Returns or sets whether close the Data Source User Interface after acquire all images. Default value of this property is FALSE. + * @type {bool} + */ + IfDisableSourceAfterAcquire: boolean; + + /** + * Returns or sets whether the Source supports duplex. If TRUE, the scanner scans both sides of a paper; otherwise, the scanner will scan only one side of the image. This is a runtime property. + * @type {bool} + */ + IfDuplexEnabled: boolean; + + /** + * Returns or sets whether the Automatic Document Feeder (ADF) is enabled. This is a runtime property. + * @type {bool} + */ + IfFeederEnabled: boolean; + + /** + * Returns whether or not there are documents loaded in the Source's feeder when IfFeederEnabled and IfPaperDetectable are TRUE. This is a runtime, read-only property. + * @type {bool} + */ + IfFeederLoaded: boolean; + + /** + * Returns or sets whether to resize the image to fit the size of window when the view mode is set to -1 by -1. You can use SetViewMode method to set the view mode. + * @type {bool} + */ + IfFitWindow: boolean; + + /** + * [Deprecated.] Returns or sets whether the UI (User Interface) of Source runs in modal state. Default value of this property is TRUE. + * @type {bool} + */ + IfModalUI: boolean; + + /** + * Sets or returns whether Dynamic Web TWAIN uses Graphics Device Interface (GDI) when decoding images. + * @type {bool} + */ + IfOpenImageWithGDIPlus: boolean; + + /** + * Returns the value whether the Source has a paper sensor that can detect documents on the ADF or Flatbed. This is a runtime, read-only property. + * @type {bool} + */ + IfPaperDetectable: boolean; + + /** + * Returns or sets whether FTP passive mode is enabled. + * @type {bool} + */ + IfPASVMode: boolean; + + /** + * [Deprecated.] Returns or sets whether communicate with device in a separate thread. Default value of this property is FALSE. + * @type {bool} + */ + IfScanInNewThread: boolean; + + /** + * Sets or returns whether to show the cancel dialog when uploading images to server. + * @type {bool} + */ + IfShowCancelDialogWhenImageTransfer: boolean; + + /** + * Returns or sets whether to show the file dialog box when saving scanned images or loading images from local folder. + * @type {bool} + */ + IfShowFileDialog: boolean; + + /** + * Returns or sets whether the Source displays a progress indicator during acquisition and transfer, regardless of whether the Source's user interface is active. This is a runtime property. + * @type {bool} + */ + IfShowIndicator: boolean; + + /** + * [Deprecated.] Returns or sets whether the driver of the printer displays the User Interface. + * @type {bool} + */ + IfShowPrintUI: boolean; + + /** + * Returns or sets whether the progress bar will be displayed during the transaction. This is a runtime property. + * @type {bool} + */ + IfShowProgressBar: boolean; + + /** + * Returns or sets whether the Source displays the User Interface. + * @type {bool} + */ + IfShowUI: boolean; + + /** + * Returns or sets whether SSL is used when uploading or downloading images. + * @type {bool} + */ + IfSSL: boolean; + + /** + * Return or sets whether the Source allows to save many images in one TIFF file. The default value is FALSE. + * @type {bool} + */ + IfTiffMultiPage: boolean; + + /** + * Returns whether the Source supports acquisition with the UI (User Interface) disabled. If FALSE, indicates that this Source can only support acquisition with the UI enabled. This is a runtime, read-only property. + * @type {bool} + */ + IfUIControllable: boolean; + + /** + * Sets or returns whether Dynamic Web TWAIN uses the new TWAIN Data Source Manager (TWAINDSM.dll) when acquiring images from TWAIN devices. + * @type {bool} + */ + IfUseTwainDSM: boolean; + + /** + * Specifies whether or not to automatically scroll to the last image or stay on the current image when loading or acquiring images + * @type {bool} + */ + IfAutoScroll: boolean; + + /** + * [Deprecated.] The number of bits in each image pixel (or bit depth). This is a runtime, read-only property. + * @type {short} + */ + ImageBitsPerPixel: number; + + /** + * Returns or sets whether a TWAIN driver or Native Scan of Mac OS X is used for document scanning. This property works for Mac edition only. + * @type {int} + */ + ImageCaptureDriverType: number; + + /** + * [Deprecated.] Returns or sets whether the image enumerator is enabled in Image Editor. + * @type {bool} + */ + ImageEditorIfEnableEnumerator: boolean; + + /** + * [Deprecated.] Returns or sets whether the Image Editor is a modal window. + * @type {bool} + */ + ImageEditorIfModal: boolean; + + /** + * [Deprecated.] Returns or sets whether the Image Editor is read-only. + * @type {bool} + */ + ImageEditorIfReadonly: boolean; + + /** + * [Deprecated.] Returns or sets the title of Image Editor window. + * @type {string} + */ + ImageEditorWindowTitle: string; + + /** + * Returns the document number of the current image. This is a runtime, read-only property. + * @type {int} + */ + ImageLayoutDocumentNumber: number; + + /** + * Returns the value of the bottom-most edge of the current image frame (in Unit). This is a read-only runtime property. + * @type {float} + */ + ImageLayoutFrameBottom: number; + + /** + * Returns the value of the left-most edge of the current image frame (in Unit). This is a runtime, read-only property. + * @type {float} + */ + ImageLayoutFrameLeft: number; + + /** + * Returns the frame number of the current image. This is a runtime, read-only property. + * @type {int} + */ + ImageLayoutFrameNumber: number; + + /** + * Returns the value of the right-most edge of the current image frame (in Unit). This is a runtime, read-only property. + * @type {float} + */ + ImageLayoutFrameRight: number; + + /** + * Returns the value of the top-most edge of the current image frame (in Unit). This is a runtime, read-only property. + * @type {float} + */ + ImageLayoutFrameTop: number; + + /** + * Returns the page number of the current image. This is a runtime, read-only property. + * @type {Long} + */ + ImageLayoutPageNumber: number; + + /** + * [Deprecated.] Returns how tall/long, in pixels, the image is. This is a runtime, read-only property. + * @type {int} + */ + ImageLength: number; + + /** + * Returns or sets the margin between images when multiple images are displayed in Dynamic Web TWAIN. + * @type {short} + */ + ImageMargin: number; + + /** + * Returns the pixel type of the current image. This is a runtime, read-only property. Please note the property is only valid in OnPreTransfer and OnPostTransfer event. + * @type {EnumDWT_PixelType} + */ + ImagePixelType: EnumDWT_PixelType; + + /** + * [Deprecated.] Returns how width, in pixels, the image is. This is a runtime, read-only property. + * @type {int} + */ + ImageWidth: number; + + /** + * [Deprecated.] Returns the X resolution of the current image. X resolution is the number of pixels per Unit in the horizontal direction. This is a runtime, read-only property. + * @type {float} + */ + ImageXResolution: number; + + /** + * [Deprecated.] Returns the Y resolution of the current image. Y resolution is the number of pixels per Unit in the vertical direction. This is a runtime, read-only property. + * @type {float} + */ + ImageYResolution: number; + + /** + * Returns or sets the quality of JPEG files and PDF files using JPEG compression. + * @type {short} + */ + JPEGQuality: number; + + /** + * Returns or sets the log level for debugging. + * @type {short} + */ + LogLevel: number; + + /** + * Return the magnetic data if the scanner support magnetic data recognition. + * @type {string} + */ + MagData: string; + + /** + * Return the magnetic type if the scanner support magnetic data recognition. + * @type {short} + */ + MagType: number; + + /** + * Sets or returns the manufacture string for the application identity. + * @type {string} + */ + Manufacturer: string; + + /** + * Returns or sets the maximum number of images can be held in buffer. + * @type {short} + */ + MaxImagesInBuffer: number; + + /** + * [Deprecated.] Returns or sets how many threads can be used when you upload files through POST. + * @type {int} + */ + MaxInternetTransferThreads: number; + + /** + * Sets or returns the maximum allowed size when Dynamic Web TWAIN uploads a document. + * @type {int} + */ + MaxUploadImageSize: number; + + /** + * Returns or sets the shape of the mouse. + * @type {bool} + */ + MouseShape: boolean; + + /** + * Returns the X co-ordinate of the mouse. This is a runtime property. + * @type {int} + */ + MouseX: number; + + /** + * Returns the Y co-ordinate of the mouse. This is a runtime property. + * @type {int} + */ + MouseY: number; + + /** + * Returns or sets the page size(s) the Source can/should use to acquire image data. This is a runtime property. + * @type {short} + */ + PageSize: number; + + /** + * Returns or sets the name of the person who creates the PDF document. + * @type {string} + */ + PDFAuthor: string; + + /** + * Returns or sets the compression type of PDF files. This is a runtime property. + * @type {EnumDWT_PDFCompressionType} + */ + PDFCompressionType: EnumDWT_PDFCompressionType; + + /** + * Returns or sets the date when the PDF document is created. + * @type {string} + */ + PDFCreationDate: string; + + /** + * Returns or sets the name of the application that created the original document, if the PDF document is converted from another form. + * @type {string} + */ + PDFCreator: string; + + /** + * Returns or sets the keywords associated with the PDF document. + * @type {string} + */ + PDFKeywords: string; + + /** + * Returns or sets the date when the PDF document is last modified. + * @type {string} + */ + PDFModifiedDate: string; + + /** + * Returns or sets the name of the application that converted the PDF document from its native. + * @type {string} + */ + PDFProducer: string; + + /** + * Returns or sets the subject of the PDF document. + * @type {string} + */ + PDFSubject: string; + + /** + * Returns or sets the title of the PDF document. + * @type {string} + */ + PDFTitle: string; + + /** + * Returns or sets the value of the PDF version. + * @type {string} + */ + PDFVersion: string; + + /** + * Returns the number of transfers the Source is ready to supply, upon demand. This is a runtime, read-only property. + * @type {short} + */ + PendingXfers: number; + + /** + * Returns or sets the pixel flavor for acquired images. This is a runtime property. + * @type {short} + */ + PixelFlavor: number; + + /** + * Returns or sets the pixel type of current data source. This is a runtime property. Using this property after calling OpenSource() method and before calling AcquireImage(). + * @type {EnumDWT_PixelType} + */ + PixelType: EnumDWT_PixelType; + + /** + * Sets or returns the product family string for the application identity. + * @type {string} + */ + ProductFamily: string; + + /** + * Sets the product key. A product key is generated in Licensing Tool which is intalled with Dynamic Web TWAIN. Each product key corresponds with a license. + * @type {string} + */ + ProductKey: string; + + /** + * [Deprecated.] Returns or sets the name of the proxy server. + * @type {string} + */ + ProxyServer: string; + + /** + * Returns or sets the current resolution for acquired images. This is a runtime property. + * @type {float} + */ + Resolution: number; + + /** + * Returns or sets how many scanned images are selected. + * @type {short} + */ + SelectedImagesCount: number; + + /** + * Returns or sets the border color of the selected image. It is a value specifying the 24-bit RGB value. + * @type {int} + */ + SelectionImageBorderColor: number; + + /** + * Specifies a fixed aspect ratio to be used for selecting an area. + * @type {float} + */ + SelectionRectAspectRatio: number; + + /** + * Returns how many sources are installed in the system. This is a runtime, read-only property. + * @type {int} + */ + SourceCount: number; + + /** + * [Deprecated.] Replaced by GetSourceNameItems method. + * @type {string} + */ + SourceNameItems: string; + + /** + * [Deprecated.] + * @type {string} + */ + GetSourceNames: string; + + /** + * Returns or sets the compression type of TIFF files. This is a runtime property. + * @type {EnumDWT_TIFFCompressionType} + */ + TIFFCompressionType: EnumDWT_TIFFCompressionType; + + /** + * Sets or returns the transfer mode. + * @type {EnumDWT_TransferMode} + */ + TransferMode: EnumDWT_TransferMode; + + /** + * Returns or sets the unit of measure. This is a runtime property. + * @type {short} + */ + Unit: number; + + /** + * Sets or returns the version info string for the application identity. + * @type {string} + */ + VersionInfo: string; + + /** + * Returns and sets the number of images you are willing to transfer per session. This is a runtime property. + * @type {short} + */ + XferCount: number; + + /** + * Returns or sets zoom factor for the image, only valid When the view mode is set to -1 by -1. + * @type {float} + */ + Zoom: number; + + /** + * Binds a specified function to an event, so that the function gets called whenever the event fires. + * @method WebTwain#RegisterEvent + * @param {string} name the name of the event that the function is bound to. + * @param {object} evt specifies the function to call when event fires. + * @return {bool} + */ + RegisterEvent(name: string, evt: object): boolean; + + // --- SCAN start -- + + /** + * Cancels all pending transfers. + * @method WebTwain#CancelAllPendingTransfers + * @return {bool} + */ + CancelAllPendingTransfers(): boolean; + + /** + * Closes Data Source. + * @method WebTwain#CloseSource + * @return {bool} + */ + CloseSource(): boolean; + + /** + * Closes and unloads Data Source Manager. + * @method WebTwain#CloseSourceManager + * @return {bool} + */ + CloseSourceManager(): boolean; + + /** + * Disable the source. If the source's user interface is displayed when the source is enabled, it will be closed. + * @method WebTwain#DisableSource + * @return {bool} + */ + DisableSource(): boolean; + + /** + * Sets the Source to eject the current page and advance the next page in the document feeder into the feeder acquire area when IfFeederEnabled is TRUE. + * @method WebTwain#FeedPage + * @return {bool} + */ + FeedPage(): boolean; + + /** + * Retrieve the device type of the currently selected data source, it might be a scanner, a web camera, etc. + * @method WebTwain#GetDeviceType + * @return {int} + */ + GetDeviceType(): number; + + /** + * Get the source name according to the source index. + * @method WebTwain#GetSourceNameItems + * @param {short} index int index. Index is 0-based and can not be greater than SourceCount property. + * @return {string} + */ + GetSourceNameItems(index: number): string; + + /** + * Loads the specified Source into main memory and causes its initialization, + * placing Dynamic Web TWAIN into Capability Negotiation state. If no source is + * specified (no SelectSource() or SelectSourceByIndex() is called), opens the default source. + * @method WebTwain#OpenSource + * @return {bool} + */ + OpenSource(): boolean; + + /** + * Loads and opens Data Source Manager. + * @method WebTwain#OpenSourceManager + * @return {bool} + */ + OpenSourceManager(): boolean; + + /** + * Reverts the current image layout to the Data Source's default. + * @method WebTwain#ResetImageLayout + * @return {bool} + */ + ResetImageLayout(): boolean; + + /** + * Sets the Source to return the current page to the input side of the document feeder and + * feed the last page from the outside of the feeder back into the acquisition area if IfFeederEnabled is TRUE. + * @method WebTwain#RewindPage + * @return {bool} + */ + RewindPage(): boolean; + + /** + * Brings up the TWAIN Data Source Manager's Source Selection User Interface (UI) + * so that user can choose which Data Source to be the current Source. + * @method WebTwain#SelectSource + * @return {bool} + */ + SelectSource(): boolean; + + /** + * Selects the index-the source in SourceNameItems property as the current source. + * @method WebTwain#SelectSourceByIndex + * @param {short} index It is the index of SourceNameItems property. + * @return {bool} + */ + SelectSourceByIndex(index: number): boolean; + + /** + * Sets file name and file format information used in File Transfer Mode. + * @method WebTwain#SetFileXferInfo + * @param {string} fileName the name of the file to be used in transfer. + * @param {EnumDWT_FileFormat} fileFormat an enumerated value indicates the format of the image. + * @return {bool} + */ + SetFileXferInfo(fileName: string, fileFormat: EnumDWT_FileFormat): boolean; + + /** + * Sets the left, top, right, and bottom sides of the image layout rectangle for the current Data Source. + * @method WebTwain#SetImageLayout + * @param {float} left specifies the floating point number for the left side of the image layout rectangle. + * @param {float} top specifies the floating point number for the top side of the image layout rectangle. + * @param {float} right specifies the floating point number for the right side of the image layout rectangle. + * @param {float} bottom specifies the floating point number for the bottom side of the image layout rectangle. + * @return {bool} + */ + SetImageLayout(left: number, top: number, right: number, bottom: number): boolean; + + /** + * Clears all the web forms which are used for image uploading. + * @method WebTwain#ClearAllHTTPFormField + * @return {bool} + */ + ClearAllHTTPFormField(): boolean; + + /** + * Clears the content of all custom tiff tags. + * @method WebTwain#ClearTiffCustomTag + * @return {void} + */ + ClearTiffCustomTag(): void; + + /** + * Check whether a certain file exists on the local disk. + * @method WebTwain#FileExists + * @param {string} localFile specifies the absolute path of the local file. + * @return {bool} + */ + FileExists(localFile: string): boolean; + + /** + * Downloads an image from the FTP server. + * @method WebTwain#FTPDownload + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPDownload(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly download a file from the FTP server to local disk without loading it into Dynamic Web TWAIN. + * @method WebTwain#FTPDownloadDirectly + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. + * @param {string} localFile specify a full path to store the file. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPDownloadDirectly(FTPServer: string, FTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Downloads an image from the FTP server. + * @method WebTwain#FTPDownloadEx + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the file to be downloaded. It should be the relative path of the file on the FTP server. + * @param {EnumDWT_ImageType} lImageType simage format of the file to be downloaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPDownloadEx(FTPServer: string, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the FTP server. + * @method WebTwain#FTPUpload + * @param {string} FTPServer the name of the FTP server. + * @param {short} sImageIndex specifies the index of the image in the buffer. The index is 0-based. + * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUpload(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly upload a specific file to the FTP server without loading it into Dynamic Web TWAIN. + * @method WebTwain#FTPUploadDirectly + * @param {string} FTPServer the name of the FTP server. + * @param {string} localFile specify the the full path of a local file. + * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadDirectly(FTPServer: string, localFile: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the FTP server as a specified image format. + * @method WebTwain#FTPUploadEx + * @param {string} FTPServer the name of the FTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} FTPRemoteFile the name of the file to be created on the FTP server. It should be a relative path on the FTP server. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadEx(FTPServer: string, sImageIndex: number, FTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in buffer to the FTP server as Multi-Page TIFF. + * @method WebTwain#FTPUploadAllAsMultiPageTIFF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadAllAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in buffer to the FTP server as Multi-Page PDF. + * @method WebTwain#FTPUploadAllAsPDF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadAllAsPDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in buffer to the FTP server as Multi-Page PDF. + * @method WebTwain#FTPUploadAsMultiPagePDF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadAsMultiPagePDF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in buffer to the FTP server as Multi-Page TIFF. + * @method WebTwain#FTPUploadAsMultiPageTIFF + * @param {string} FTPServer the name of the FTP server. + * @param {string} FTPRemoteFile the name of the image to be uploaded. It should be a relative path on the FTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + FTPUploadAsMultiPageTIFF(FTPServer: string, FTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Downloads an image from the HTTP server. + * @method WebTwain#HTTPDownload + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile the name of the image to be downloaded. It should be the relative path of the file on the HTTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPDownload(HTTPServer: string, HTTPRemoteFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly downloads a file from the HTTP server to a local disk without loading it into Dynamic Web TWAIN. + * @method WebTwain#HTTPDownloadDirectly + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile The relative path of the file on the HTTP server. + * @param {string} localFile specify the location to store the downloaded file. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPDownloadDirectly(HTTPServer: string, HTTPRemoteFile: string, localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Downloads an image from the HTTP server. + * @method WebTwain#HTTPDownloadEx + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) + * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPDownloadEx(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Download an image from the server using a HTTP Post call. + * @method WebTwain#HTTPDownloadThroughPost + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} HTTPRemoteFile the relative path of the file on the HTTP server, or path to an action page (with necessary parameters) which gets and sends back the image stream to the client (please check the sample for more info) + * @param {EnumDWT_ImageType} lImageType the image format of the file to be downloaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the download succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the download fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPDownloadThroughPost(HTTPServer: string, HTTPRemoteFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the HTTP server through the HTTP POST method. + * @method WebTwain#HTTPUploadThroughPost + * @param {string} HTTPServer the name of the HTTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPost(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Directly upload a specific local file to the HTTP server through the HTTP POST method without loading it into Dynamic Web TWAIN. + * @method WebTwain#HTTPUploadThroughPostDirectly + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} localFile specifies the path of a local file . + * @param {string} ActionPage the specified page for posting files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the file to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPostDirectly(HTTPServer: string, localFile: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP POST method. + * @method WebTwain#HTTPUploadThroughPostEx + * @param {string} HTTPServer the name of the HTTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server.s + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPostEx(HTTPServer: string, sImageIndex: number, ActionPage: string, fileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadAllThroughPostAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadAllThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadThroughPostAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPostAsMultiPageTIFF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads all images in the buffer to the HTTP server through HTTP Post method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadAllThroughPostAsPDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadAllThroughPostAsPDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Uploads the selected images in the buffer to the HTTP server through the HTTP Post method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadThroughPostAsMultiPagePDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} ActionPage the specified page for posting image files. This is the relative path of the page, not the absolute path. For example: "upload.asp", not "http://www.webserver.com/upload.asp". + * @param {string} fileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnHttpUploadSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnHttpUploadFailure. + * @return {bool} + */ + HTTPUploadThroughPostAsMultiPagePDF(HTTPServer: string, ActionPage: string, fileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Directly uploads a specific local file to the HTTP server through the HTTP PUT method without loading it into Dynamic Web TWAIN. + * @method WebTwain#HTTPUploadThroughPutDirectly + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} localFile specifies the path of a local file. + * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPutDirectly(HTTPServer: string, localFile: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server through the HTTP PUT method. + * @method WebTwain#HTTPUploadThroughPut + * @param {string} HTTPServer the name of the HTTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} RemoteFileName the name of the image to be created on the HTTP server. It should a relative path on the web server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPut(HTTPServer: string, sImageIndex: number, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the image of a specified index in the buffer to the HTTP server as a specified image format through the HTTP PUT method. + * @method WebTwain#HTTPUploadThroughPutEx + * @param {string} HTTPServer the name of the HTTP server. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {string} RemoteFileName the name of the file to be created on the HTTP server. It should a relative path on the web server. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be created on the HTTP server. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPutEx(HTTPServer: string, sImageIndex: number, RemoteFileName: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadAllThroughPutAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadAllThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page TIFF. + * @method WebTwain#HTTPUploadThroughPutAsMultiPageTIFF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPutAsMultiPageTIFF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads all images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadAllThroughPutAsPDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadAllThroughPutAsPDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * [Deprecated.] Uploads the selected images in the buffer to the HTTP server through the HTTP Put method as a Multi-Page PDF. + * @method WebTwain#HTTPUploadThroughPutAsMultiPagePDF + * @param {string} HTTPServer the name of the HTTP server. + * @param {string} RemoteFileName the name of the image to be uploaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUploadThroughPutAsMultiPagePDF(HTTPServer: string, RemoteFileName: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Configures how segmented upload is done. + * @method WebTwain#SetUploadSegment + * @param {int} segmentUploadThreshold specifies the threshold (in MB) over which segmented upload will be invoked. + * @param {int} moduleSize specifies the size of each segment (in KB). + * @return {bool} + */ + SetUploadSegment (segmentUploadThreshold: number, moduleSize: number): boolean; + + /** + * Uploads the images specified by the indices to the HTTP server. + * @method WebTwain#HTTPUpload + * @param {string} url the url where the images are sent in a POST request. + * @param {Array} indices indices specifies which images are to be uploaded. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be uploaded. + * @param {EnumDWT_UploadDataFormat} dataFormat whether to upload the images as binary or a base64-based string. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + HTTPUpload (url: string, indices: number[], enumImageType: EnumDWT_ImageType, dataFormat: EnumDWT_UploadDataFormat, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads a DIB format image from Clipboard into the Dynamic Web TWAIN. + * @method WebTwain#LoadDibFromClipboard + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + LoadDibFromClipboard(optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads an image into the Dynamic Web TWAIN. + * @method WebTwain#LoadImage + * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + LoadImage(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads an image into the Dynamic Web TWAIN. + * @method WebTwain#LoadImageEx + * @param {string} localFile the name of the image to be loaded. It should be the absolute path of the image file on the local disk. + * @param {EnumDWT_ImageType} lImageType the image format of the file to be loaded. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the loading succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the loading fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + LoadImageEx(localFile: string, lImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Loads image from a base64 byte array with the specified file format. + * @method WebTwain#LoadImageFromBase64Binary + * @param {string} bry specifies the base64 string data. + * @param {EnumDWT_ImageType} lImageType specifies the file format. + * @return {bool} + */ + LoadImageFromBase64Binary(bry: string, lImageType: EnumDWT_ImageType): boolean; + + /** + * [Deprecated.] Loads image from a byte array with the specified file format. + * @method WebTwain#LoadImageFromBytes + * @param {int} lBufferSize Specifies the buffer size. + * @param {Array} buffer A byte array of the image data. + * @param {EnumDWT_ImageType} lImageType Specifies the file format. + * @return {bool} + */ + LoadImageFromBytes(lBufferSize: number, buffer: number[], lImageType: EnumDWT_ImageType): boolean; + + /** + * Saves all images in buffer as a MultiPage TIFF file. + * @method WebTwain#SaveAllAsMultiPageTIFF + * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + SaveAllAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves all images in buffer as a Multi-Page PDF file. + * @method WebTwain#SaveAllAsPDF + * @param {string} localFile the name of the Multi-Page PDF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + SaveAllAsPDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the image of a specified index in buffer as a BMP file. + * @method WebTwain#SaveAsBMP + * @param {string} localFile the name of the BMP file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsBMP(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the image of a specified index in buffer as a JPEG file. + * @method WebTwain#SaveAsJPEG + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsJPEG(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the image of a specified index in buffer as a PDF file. + * @method WebTwain#SaveAsPDF + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsPDF(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the image of a specified index in buffer as a PNG file. + * @method WebTwain#SaveAsPNG + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsPNG(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the image of a specified index in buffer as a TIFF file. + * @method WebTwain#SaveAsTIFF + * @param {string} localFile the name of the JPEG file to be saved. It should be an absolute path on the local disk. + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SaveAsTIFF(localFile: string, sImageIndex: number): boolean; + + /** + * Saves the selected images in buffer as a Multipage PDF file. + * @method WebTwain#SaveSelectedImagesAsMultiPagePDF + * @param {string} localFile the name of the MultiPage PDF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + SaveSelectedImagesAsMultiPagePDF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the selected images in buffer as a Multipage TIFF file. + * @method WebTwain#SaveSelectedImagesAsMultiPageTIFF + * @param {string} localFile the name of the MultiPage TIFF file to be saved. It should be an absolute path on the local disk. + * @param {function} optionalAsyncSuccessFunc optional. The function to call when the saving succeeds. Please refer to the function prototype OnSuccess. + * @param {function} optionalAsyncFailureFunc optional. The function to call when the saving fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + SaveSelectedImagesAsMultiPageTIFF(localFile: string, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Saves the selected images in buffer to base64 string. + * @method WebTwain#SaveSelectedImagesToBase64Binary + * @return {string} + */ + SaveSelectedImagesToBase64Binary(): string; + + /** + * [Deprecated.] Saves the selected images in buffer to a byte array in the specified file format. + * @method WebTwain#SaveSelectedImagesToBytes + * @param {int} bufferSize specified the buffer size. + * @param {Array} buffer A byte array of the image data. + * @return {int} + */ + SaveSelectedImagesToBytes(bufferSize: number, buffer: number[]): number; + + /** + * [Deprecated.] Sets current cookie into the Http Header to be used when uploading scanned images through POST. + * @method WebTwain#SetCookie + * @param {string} cookie the cookie on current page. + * @return {void} + */ + SetCookie(cookie: string): void; + + /** + * Sets a text parameter as a filed in a web form. This form is maintained by the component itself (meaning it's not on the page). All fields in this form will be passed to the server when uploading images. + * @method WebTwain#SetHTTPFormField + * @param {string} FieldName specifies the name of a text field in web form. + * @param {string} FieldValue specifies the value of a text field in web form. + * @return {bool} + */ + SetHTTPFormField(FieldName: string, FieldValue: string): boolean; + + /** + * Sets a custom tiff tag. Currently you can set up to 32 tags. The string to be set in a tag can be encoded with base64. + * @method WebTwain#SetTiffCustomTag + * @param {int} tag specifies the tag identifier. The value should be between 600 and 700. + * @param {string} content the string to be set for this tag. The string will be written to the .tiff file when you save/upload it. If the string is base64 encoded, we'll decode it before writing it. + * @param {bool} base64Str if you'd like to encode the string with base64, set this to true. Otherwise, the string will be plin text. + * @return {bool} + */ + SetTiffCustomTag(tag: number, content: string, base64Str: boolean): boolean; + + /** + * Show save file dialog or show open file dialog. + * @method WebTwain#ShowFileDialog + * @param {bool} SaveDialog True -- show save file dialog, False -- show open file dialog. + * @param {string} Filter The filter name specifies the filter pattern (for example, "*.TXT"). To specify multiple filter patterns for a single display string, use a semicolon to separate the patterns (for example, "*.TXT;*.DOC;*.BAK"). A pattern string can be a combination of valid file name characters and the asterisk (*) wildcard character. Do not include spaces in the pattern string. To retrieve a shortcut's target without filtering, use the string "All Files\0*.*\0\0", but the program will replace "\0" with "|" automatically. + * @param {int} FilterIndex The index of the currently selected filter in the File Types control. The buffer pointed to by Filter contains pairs of strings that define the filters. The index is 0-based. + * @param {string} DefExtension Define the default extension. GetOpenFileName and GetSaveFileName append this extension to the file name only if the user fails to type an extension. If this member is NULL and the user fails to type an extension, no extension is appended. + * @param {string} InitialDir The initial directory. The algorithm for selecting the initial directory varies on different platforms. + * @param {bool} AllowMultiSelect True -- allows users to select more than one file, False -- only allows to select one file. + * @param {bool} OverwritePrompt True -- If a file already exists with the same name, the old file will be simply overwritten, False -- not allows to save and overwrite a same name file. + * @param {int} Flags If this parameter equals 0, the program will be initiated with the default flags, otherwise initiated with the cumstom value and paramters "AllowMultiSelect" and "OverwritePrompt" will be useless. + * @return {bool} + */ + ShowFileDialog(SaveDialog: boolean, Filter: string, FilterIndex: number, DefExtension: string, InitialDir: string, AllowMultiSelect: boolean, OverwritePrompt: boolean, Flags: number): boolean; + + /** + * Gets information of the capability specified by the Capability property. + * @method WebTwain#CapGet + * @return {bool} + */ + CapGet(): boolean; + + /** + * Returns the Source's current Value for the specified capability. + * @method WebTwain#CapGetCurrent + * @return {bool} + */ + CapGetCurrent(): boolean; + + /** + * Returns the Source's Default Value for the specified capability. This is the Source's preferred default value. + * @method WebTwain#CapGetDefault + * @return {bool} + */ + CapGetDefault(): boolean; + + /** + * Returns the value of the bottom-most edge of the specified frame. + * @method WebTwain#CapGetFrameBottom + * @param {short} index specifies the value of which frame to get. The index is 0-based. + * @return {float} + */ + CapGetFrameBottom(index: number): number; + + /** + * Returns the value (in Unit) of the left-most edge of the specified frame. + * @method WebTwain#CapGetFrameLeft + * @param {short} index specifies the value of which frame to get. The index is 0-based. + * @return {float} + */ + CapGetFrameLeft(index: number): number; + + /** + * Returns the value (in Unit) of the left-most edge of the specified frame. + * @method WebTwain#CapGetFrameRight + * @param {short} index specifies the value of which frame to get. The index is 0-based. + * @return {float} + */ + CapGetFrameRight(index: number): number; + + /** + * Returns the value (in Unit) of the top-most edge of the specified frame. + * @method WebTwain#CapGetFrameTop + * @param {short} index specifies the value of which frame to get. The index is 0-based. + * @return {float} + */ + CapGetFrameTop(index: number): number; + + /** + * Queries whether the Source supports a particular operation on the capability. + * @method WebTwain#CapIfSupported + * @param {EnumDWT_MessageType} messageType specifies the type of capability operation. + * @return {bool} + */ + CapIfSupported(messageType: EnumDWT_MessageType): boolean; + + /** + * Changes the Current Value of the capability specified by Capability property back to its power-on value. + * @method WebTwain#CapReset + * @return {bool} + */ + CapReset(): boolean; + + /** + * Sets the current capability using the container type specified by CapType property. The current capability is specified by Capability property. + * @method WebTwain#CapSet + * @return {bool} + */ + CapSet(): boolean; + + /** + * Sets the values of the specified frame. + * @method WebTwain#CapSetFrame + * @param {short} index specifies the values of which frame to set. The index is 0-based. + * @param {float} left the value (in Unit) of the left-most edge of the specified frame. + * @param {float} top the value (in Unit) of the top-most edge of the specified frame. + * @param {float} right the value (in Unit) of the right-most edge of the specified frame. + * @param {float} bottom the value (in Unit) of the bottom-most edge of the specified frame. + * @return {bool} + */ + CapSetFrame(index: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Get the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. + * @method WebTwain#GetCapItems + * @param {int} index Index is 0-based. It is the index of the cap item. + * @return {double} + */ + GetCapItems(index: number): number; + + /** + * Returns the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. + * @method WebTwain#GetCapItemsString + * @param {int} index Index is 0-based. It is the index of the cap item. + * @return {string} + */ + GetCapItemsString(index: number): string; + + /** + * Set the value of the specified cap item. + * @method WebTwain#SetCapItems + * @param {int} index Index is 0-based. It is the index of the cap item. + * @param {double} newVal The Double type of CapItems property is used to present Double, Single(float), Long, int and even boolean types. For string type, please use CapItemsstring property. + * @return {void} + */ + SetCapItems(index: number, newVal: number): void; + + /** + * Set the cap item value of the capability specified by Capability property, when the value of the CapType property is TWON_ARRAY or TWON_ENUMERATION. + * @method WebTwain#SetCapItemsString + * @param {int} index Index is 0-based. It is the index of the cap item. + * @param {string} newVal The new value to be set. + * @return {void} + */ + SetCapItemsString(index: number, newVal: string): void; + // --- SCAN end -- + + // --- View & Edit start -- + + /** + * Add text on an image. + * @method WebTwain#AddText + * @param {short} sImageIndex the index of the image that you want to add text to. + * @param {int} x the x coordinate for the text. + * @param {int} y the y coordinate for the text. + * @param {string} text the content of the text that you want to add. + * @param {int} txtColor the color for the text. + * @param {int} backgroundColor the background color. + * @param {float} backgroundRoundRadius ranging from 0 to 0.5. Please NOTE that MAC version does not support this parameter. + * @param {float} backgroundOpacity specifies the opacity of the background of the added text, it ranges from 0 to 1.0. Please NOTE that Mac version only supports value 0 and 1 + * @return {bool} + */ + AddText(sImageIndex: number, x: number, y: number, text: string, txtColor: number, backgroundColor: number, backgroundRoundRadius: number, backgroundOpacity: number): boolean; + + /** + * Create the font for adding text using the method AddText. + * @method WebTwain#CreateTextFont + * @param {int} height Specifies the desired height (in logical units) of the font.The absolute value of nHeight must not exceed 16,384 device units after it is converted.For all height comparisons, the font mapper looks for the largest font that does not exceed the requested size or the smallest font if all the fonts exceed the requested size. + * @param {int} width Specifies the average width (in logical units) of characters in the font. If Width is 0, the aspect ratio of the device will be matched against the digitization aspect ratio of the available fonts to find the closest match, which is determined by the absolute value of the difference. + * @param {int} escapement Specifies the angle (in 0.1-degree units) between the escapement vector and the x-axis of the display surface. The escapement vector is the line through the origins of the first and last characters on a line. The angle is measured counterclockwise from the x-axis. + * @param {int} orientation Specifies the angle (in 0.1-degree units) between the baseline of a character and the x-axis.The angle is measured counterclockwise from the x-axis for coordinate systems in which the y-direction is down and clockwise from the x-axis for coordinate systems in which the y-direction is up. + * @param {int} weight Specifies the font weight (in inked pixels per 1000). The described valuesare approximate; the actual appearance depends on the typeface. Some fonts haveonly FW_NORMAL, FW_REGULAR, and FW_BOLD weights. If FW_DONTCARE is specified, a default weight is used. + * @param {short} italic Specifies an italic font if set to TRUE. + * @param {short} underline Specifies an underlined font if set to TRUE. + * @param {short} strikeOut A strikeout font if set to TRUE. + * @param {short} charSet Specifies the font's character set. The OEM character set is system-dependent. Fonts with other character sets may exist in the system. An application that uses a font with an unknown character set must not attempt to translate or interpret strings that are to be rendered with that font. + * @param {short} outputPrecision Specifies the desired output precision. The output precision defines how closely the output must match the requested font's height, width, character orientation, escapement, and pitch. + * @param {short} clipPrecision Specifies the desired clipping precision. The clipping precision defines how to clip characters that are partially outside the clipping region. + * @param {short} quality Specifies the font's output quality, which defines how carefully the GDI must attempt to match the logical-font attributes to those of an actual physical font. + * @param {short} pitchAndFamily The pitch and family of the font. + * @param {string} faceName the typeface name, the length of this string must not exceed 32 characters, including the terminating null character. + * @return {bool} + */ + CreateTextFont(height: number, width: number, escapement: number, orientation: number, weight: number, italic: number, underline: number, strikeOut: number, charSet: number, outputPrecision: number, clipPrecision: number, quality: number, pitchAndFamily: number, faceName: string): boolean; + + /** + * Copies the image of a specified index in buffer to clipboard in DIB format. + * @method WebTwain#CopyToClipboard + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + CopyToClipboard(sImageIndex: number): boolean; + + /** + * Clears the specified area of a specified image, and fill the area with the fill color. + * @method WebTwain#Erase + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {bool} + */ + Erase(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Returns the pixel bit depth of the selected image. + * @method WebTwain#GetImageBitDepth + * @param {short} sImageIndex specifies the index of image. The index is 0-based. + * @return {short} + */ + GetImageBitDepth(sImageIndex: number): number; + + /** + * Returns the width (pixels) of the selected image. This is a read-only property. + * @method WebTwain#GetImageWidth + * @param {short} sImageIndex specifies the index of image. The index is 0-based. + * @return {int} + */ + GetImageWidth(sImageIndex: number): number; + + /** + * Returns the height (pixels) of the selected image. This is a read-only property. + * @method WebTwain#GetImageHeight + * @param {short} sImageIndex specifies the index of image. The index is 0-based. + * @return {int} + */ + GetImageHeight(sImageIndex: number): number; + + /** + * Returns the file size of the new image resized from the image of a specified index in buffer. + * @method WebTwain#GetImageSize + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} iWidth specifies the pixel width of the new image. + * @param {int} iHeight specifies the pixel height of the new image. + * @return {double} + */ + GetImageSize(sImageIndex: number, iWidth: number, iHeight: number): number; + + /** + * Pre-calculate the file size of the local image file that is saved from an image of a specified index in buffer. + * @method WebTwain#GetImageSizeWithSpecifiedType + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {short} sImageType specifies the type of an image file.. + * @return {int} + */ + GetImageSizeWithSpecifiedType(sImageIndex: number, sImageType: number): number; + + /** + * Return the horizontal resolution of the specified image. + * @method WebTwain#GetImageXResolution + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {int} + */ + GetImageXResolution(sImageIndex: number): number; + + /** + * Return the vertical resolution of the specified image. + * @method WebTwain#GetImageYResolution + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {int} + */ + GetImageYResolution(sImageIndex: number): number; + + /** + * Returns the index of the selected image. + * @method WebTwain#GetSelectedImageIndex + * @param {short} sSelectedIndex specifies the index of the selected image. + * @return {short} + */ + GetSelectedImageIndex(sSelectedIndex: number): number; + + /** + * You can use the method to select images programatically which is ususally done by mouse clicking. + * @method WebTwain#SetSelectedImageIndex + * @param {short} sSelectedIndex this is the index of an array that holds the indices of selected images. + * @param {short} newVal specifies the index of an image that you want to select. + * @return {void} + */ + SetSelectedImageIndex(selectedIndex: number, newVal: number): void; + + /** + * Pre-calculate the file size of the local image file that is saved from the selected images in buffer. + * @method WebTwain#GetSelectedImagesSize + * @param {int} iImageType specifies the type of an image file. + * @return {int} + */ + GetSelectedImagesSize(iImageType: number): number; + + /** + * Check the skew angle of an image by its index in buffer. + * @method WebTwain#GetSkewAngle + * @param {short} sImageIndex the index of the image in the buffer. + * @return {double} + */ + GetSkewAngle(sImageIndex: number): number; + + /** + * Check the skew angle of a rectangular part of an image by its index in buffer. + * @method WebTwain#GetSkewAngleEx + * @param {short} sImageIndex the index of the image in the buffer. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {double} + */ + GetSkewAngleEx(sImageIndex: number, left: number, top: number, right: number, bottom: number): number; + + /** + * [Deprecated.] Detects whether a certain area on an image is blank. + * @method WebTwain#IsBlankImageEx + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @param {bool} bFuzzyMatch specifies whether use fuzzy matching when detecting. + * @return {bool} + */ + IsBlankImageEx(sImageIndex: number, left: number, top: number, right: number, bottom: number, bFuzzyMatch: boolean): boolean; + + /** + * Mirrors the image of a specified index in buffer. + * @method WebTwain#Mirror + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + Mirror(sImageIndex: number): boolean; + + /** + * Decorates image of a specified index in buffer with rectangles of transparent color. + * @method WebTwain#OverlayRectangle + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @param {int} color Specifies the fill color of the rectangle. The byte-ordering of the RGB value is 0xBBGGRR. BB represents blue, GG represents green, RR represents red. + * @param {float} fOpacity Specifies the opacity of the rectangle. The value represents opacity. 1.0 is 100% opaque and 0.0 is totally transparent. + * @return {bool} + */ + OverlayRectangle(sImageIndex: number, left: number, top: number, right: number, bottom: number, color: number, fOpacity: number): boolean; + + /** + * Removes all images in buffer. + * @method WebTwain#RemoveAllImages + * @return {void} + */ + RemoveAllImages(): void; + + /** + * Removes selected images in buffer. + * @method WebTwain#RemoveAllSelectedImages + * @return {bool} + */ + RemoveAllSelectedImages(): boolean; + + /** + * Removes the image of a specified index in buffer. + * @method WebTwain#RemoveImage + * @param {short} sImageIndexToBeDeleted specifies the index of the image to be deleted in buffer. The index is 0-based. + * @return {bool} + */ + RemoveImage(sImageIndexToBeDeleted: number): boolean; + + // Image Operate + /** + * Rotates the image of a specified index in buffer by specified angle. + * @method WebTwain#Rotate + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {float} fAngle Specifies the rotation angle. + * @param {bool} bKeepSize Keep size or not. + * @return {bool} + */ + Rotate(sImageIndex: number, fAngle: number, bKeepSize: boolean): boolean; + + /** + * Rotates the image of a specified index in buffer by specified angle. + * @method WebTwain#RotateEx + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {float} fAngle Specifies the rotation angle. + * @param {bool} bKeepSize Keep size or not. + * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. + * @return {bool} + */ + RotateEx(sImageIndex: number, fAngle: number, bKeepSize: boolean, newVal: EnumDWT_InterpolationMethod): boolean; + + /** + * Rotates the image of a specified index in buffer by 90 degrees counter-clockwise. + * @method WebTwain#RotateLeft + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + RotateLeft(sImageIndex: number): boolean; + + /** + * Rotates the image of a specified index in buffer by 90 degrees clockwise. + * @method WebTwain#RotateRight + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + RotateRight(sImageIndex: number): boolean; + + /** + * Changes width and height of the image of a specified index in the buffer. Please note the file size of the image will be changed proportionately. + * @method WebTwain#ChangeImageSize + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} iNewWidth specifies the pixel width of the new image. + * @param {int} iNewHeight specifies the pixel height of the new image. + * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. + * @return {bool} + */ + ChangeImageSize(sImageIndex: number, iNewWidth: number, iNewHeight: number, newVal: EnumDWT_InterpolationMethod): boolean; + + /** + * Flips the image of a specified index in buffer. + * @method WebTwain#Flip + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + Flip(sImageIndex: number): boolean; + + /** + * Crops the image of a specified index in buffer. + * @method WebTwain#Crop + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {bool} + */ + Crop(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Crops the image of a specified index in buffer to clipboard in DIB format. + * @method WebTwain#CropToClipboard + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {bool} + */ + CropToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Cuts the image data in the specified area to the system clipboard in DIB format. + * @method WebTwain#CutFrameToClipboard + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left specifies the x-coordinate of the upper-left corner of the rectangle. + * @param {int} top specifies the y-coordinate of the upper-left corner of the rectangle. + * @param {int} right specifies the x-coordinate of the lower-right corner of the rectangle. + * @param {int} bottom specifies the y-coordinate of the lower-right corner of the rectangle. + * @return {bool} + */ + CutFrameToClipboard(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Cuts the image of a specified index in buffer to clipboard in DIB format. + * @method WebTwain#CutToClipboard + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + CutToClipboard(sImageIndex: number): boolean; + + /** + * Change the DPI (dots per inch) for the specified image. + * @method WebTwain#SetDPI + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} xResolution The horizontal resolution. + * @param {int} yResolution The vertical resolution. + * @param {bool} bResampleImage Whether to resample the image. (The image size will be changed if this is set to true). + * @param {EnumDWT_InterpolationMethod} newVal specifies the method to do interpolation. + * @return {bool} + */ + SetDPI(sImageIndex: number, xResolution: number, yResolution: number, bResampleImage: boolean, newVal: EnumDWT_InterpolationMethod): boolean; + + /** + * Sets the view mode that images are displayed in Dynamic Web TWAIN. You can use this method to display multiple images in Dynamic Web TWAIN. + * @method WebTwain#SetViewMode + * @param {short} sHorizontalImageCount specifies how many columns can be displayed in Dynamic Web TWAIN. + * @param {short} sVerticalImageCount specifies how many rows can be displayed in Dynamic Web TWAIN.. + * @return {void} + */ + SetViewMode(sHorizontalImageCount: number, sVerticalImageCount: number): void; + + /** + * Moves a specified image. + * @method WebTwain#MoveImage + * @param {short} sSourceImageIndex Specifies the source index of image in buffer. The index is 0-based. + * @param {short} sTargetImageIndex Specifies the target index of image in buffer. The index is 0-based. + * @return {bool} + */ + MoveImage(sSourceImageIndex: number, sTargetImageIndex: number): boolean; + + /** + * Switchs two images of specified indices in buffer. + * @method WebTwain#SwitchImage + * @param {short} sImageIndex1 specifies the index of image in buffer. The index is 0-based. + * @param {short} sImageIndex2 specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + SwitchImage(sImageIndex1: number, sImageIndex2: number): boolean; + + /** + * Shows the GUI of Image Printer. + * @method WebTwain#Print + * @return {bool} + */ + Print(): boolean; + // --- View & Edit end -- + + // --- Upload & Save end -- + + // --- Others --- + /** + * Shows the GUI of Image Editor. + * @method WebTwain#ShowImageEditor + * @return {bool} + */ + ShowImageEditor(): boolean; + + /** + * Unbinds an event from the specified function, so that the function stops receiving notifications when the event fires. + * @method WebTwain#UnregisterEvent + * @param {string} name the name of the event. + * @param {object} evt specified the function to be unbound. + * @return {bool} + */ + UnregisterEvent(name: string, evt: object): boolean; + // --- Others end --- + + /** + * Enables the source to accept image. + * @method WebTwain#EnableSource + * @return {bool} + */ + EnableSource(): boolean; + + /** + * Displays the source's built-in interface to acquire image. + * @method WebTwain#AcquireImage + * @param {object} optionalDeviceConfig a JS object used to set up the device for image acquisition. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + AcquireImage(optionalDeviceConfig?: object, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + // start from 10.0 + /** + * Change the width of an image in buffer. + * @method WebTwain#SetImageWidth + * @param {short} sImageIndex specifies which image you'd like to change. + * @param {int} iNewWidth specifies how wide you'd like to change the image. + * @return {bool} + */ + SetImageWidth(sImageIndex: number, iNewWidth: number): boolean; + + // Set custom DS data (DAT_CUSTOMDSDATA), the input string is encoded with base64 + /** + * Sets custom DS data to be used for scanning, the input string is encoded with base64. Custom DS data means a specific scanning profile. + * @method WebTwain#SetCustomDSDataEx + * @param {string} value the input string which is encoded with base64. + * @return {bool} + */ + SetCustomDSDataEx(value: string): boolean; + + // Set custom DS data, load data from the specified file + /** + * Sets custom DS data to be used for scanning, the data is stored in a file. Custom DS data means a specific scanning profile. + * @method WebTwain#SetCustomDSData + * @param {string} fileName the absolute path of the file where the custom data source data is stored. + * @return {bool} + */ + SetCustomDSData(fileName: string): boolean; + + // Get custom DS data, and returned string is encoded with base64 + /** + * Gets custom DS data, the returned string is base64 encoded. + * @method WebTwain#GetCustomDSDataEx + * @return {string} + */ + GetCustomDSDataEx(): string; + + // Get custom DS data, and save the data to the specified file + /** + * Gets custom DS data and save the data in a specified file. + * @method WebTwain#GetCustomDSData + * @param {string} fileName the path of the file used for storing custom DS data. + * @return {bool} + */ + GetCustomDSData(fileName: string): boolean; + + /** + * Changes the bitdepth of a specified image. + * @method WebTwain#ChangeBitDepth + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {short} sBitDepth specifies the target bit depth. + * @param {bool} bHighQuality specifies whether or not to keep high quality while changing the bit depth. When it's true, it takes more time. + * @return {bool} + */ + ChangeBitDepth(sImageIndex: number, sBitDepth: number, bHighQuality: boolean): boolean; + + /** + * Changes a specified image to gray scale. + * @method WebTwain#ConvertToGrayScale + * @param {short} sIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + ConvertToGrayScale(sIndex: number): boolean; + + /** + * [Deprecated.] Shows the GUI of Image Editor with custom settings. + * @method WebTwain#ShowImageEditorEx + * @param {int} x specifies the new position of the left top corner of the window. + * @param {int} y specifies the new position of the left top corner of the window. + * @param {int} cx specifies the width of the window. + * @param {int} cy specifies the height of the window. + * @param {int} nCmdShow specifices how the window should be shown. + * @return {bool} + */ + ShowImageEditorEx(x: number, y: number, cx: number, cy: number, nCmdShow: number): boolean; + + /** + * [Deprecated.] Detects whether an image is blank. + * @method WebTwain#IsBlankImage + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + IsBlankImage(sImageIndex: number): boolean; + + /** + * Detects whether a specific image is blank. + * @method WebTwain#IsBlankImageExpress + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @return {bool} + */ + IsBlankImageExpress(sImageIndex: number): boolean; + + /** + * [Deprecated.] Detects whether a specific image is blank. + * @method WebTwain#GetBarcodeInfo + * @param {int} barcodeInfoType Defined in TWAIN Specification. + * @param {int} barcodeIndex Specifies which barcode to check. The index is 0-based. + * @return {object} + */ + GetBarcodeInfo(barcodeInfoType: number, barcodeIndex: number): object; + + /** + * [Deprecated.] Gets the content from a specified barcode. + * @method WebTwain#GetBarcodeText + * @param {int} barcodeIndex Specifies which barcode to check. The index is 0-based. + * @return {bool} + */ + GetBarcodeText(barcodeIndex: number): boolean; + + /** + * Sets the default source to use. It's only valid when IfUseTWAINDSM is set to true. + * @method WebTwain#SetDefaultSource + * @param {short} sImageIndex specifies the index of the default source. The index is 0-based. + * @return {bool} + */ + SetDefaultSource(sImageIndex: number): boolean; + + /** + * Draws a rectangle on the viewer which represents the selected area. + * @method WebTwain#SetSelectedImageArea + * @param {short} sImageIndex specifies the index of image in buffer. The index is 0-based. + * @param {int} left The X axis of the left border. + * @param {int} top The Y axis of the top border. + * @param {int} right The X axis of the right border. + * @param {int} bottom The Y axis of the bottom border. + * @return {bool} + */ + SetSelectedImageArea(sImageIndex: number, left: number, top: number, right: number, bottom: number): boolean; + + /** + * Converts the images specified by the indices to base64. + * @method WebTwain#ConvertToBase64 + * @param {Array} indices indices specifies which images are to be converted to base64. + * @param {EnumDWT_ImageType} enumImageType the image format in which the images are to be converted to base64. + * @param {function} asyncSuccessFunc the function to call when the upload succeeds. Please refer to the function prototype OnSuccess. + * @param {function} asyncFailureFunc the function to call when the upload fails. Please refer to the function prototype OnFailure. + * @return {bool} + */ + ConvertToBase64(indices: number[], enumImageType: EnumDWT_ImageType, optionalAsyncSuccessFunc?: () => void, optionalAsyncFailureFunc?: (errorCode: number, errorString: string) => void): boolean; + + /** + * Returns the direct URL of an image specified by index, if iWidth or iHeight is set to -1, you get the original image, otherwise you get the image with specified iWidth or iHeight while keeping the same aspect ratio. + * @method WebTwain#GetImageURL + * @param {short} index the index of the image. + * @param {int} iWidth the width of the image. + * @param {int} iHeight the height of the image. + * @return {string} + */ + GetImageURL(index: number, iWidth: number, iHeight: number): string; + + /** + * Sets a header for the current HTTP Post request. + * @method WebTwain#SetHTTPHeader + * @param {string} key the key of the header. + * @param {string} value the value of the header. + * @return {bool} + */ + SetHTTPHeader(key: string, value: string): boolean; +} diff --git a/types/path-to-regexp/tsconfig.json b/types/dwt/tsconfig.json similarity index 92% rename from types/path-to-regexp/tsconfig.json rename to types/dwt/tsconfig.json index bee259111e..5ff27b3787 100644 --- a/types/path-to-regexp/tsconfig.json +++ b/types/dwt/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "path-to-regexp-tests.ts" + "dwt-tests.ts" ] } \ No newline at end of file diff --git a/types/dwt/tslint.json b/types/dwt/tslint.json new file mode 100644 index 0000000000..acce7c8a0b --- /dev/null +++ b/types/dwt/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "max-line-length": [false], + "no-trailing-whitespace": false, + "space-before-function-paren": false, + "only-arrow-functions": [false] + } +} diff --git a/types/element-resize-event/element-resize-event-tests.ts b/types/element-resize-event/element-resize-event-tests.ts index 96c859cdae..5ebf93dcab 100644 --- a/types/element-resize-event/element-resize-event-tests.ts +++ b/types/element-resize-event/element-resize-event-tests.ts @@ -2,6 +2,6 @@ import ere = require("element-resize-event"); var domNode: Element = null; -ere(domNode, (): void => { -}); +ere(domNode, (): void => {}); +ere.unbind(domNode, (): void => {}); diff --git a/types/element-resize-event/index.d.ts b/types/element-resize-event/index.d.ts index e500d2e7f9..4745bc3a11 100644 --- a/types/element-resize-event/index.d.ts +++ b/types/element-resize-event/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for element-resize-event 1.0.1 +// Type definitions for element-resize-event 2.0.9 // Project: https://github.com/KyleAMathews/element-resize-event -// Definitions by: Rogier Schouten +// Definitions by: Rogier Schouten , Pierre-Luc Gregoire // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare function elementResizeEvent(domNode: Element, callback: () => void): void; -export = elementResizeEvent; +export = element_resize_event; +declare function element_resize_event(omNode: Element, callback: () => void): void; +declare namespace element_resize_event { + function unbind(omNode: Element, callback: () => void): void; +} diff --git a/types/ember/ember-tests.ts b/types/ember/ember-tests.ts index 99f00aae6f..4119e1d7ec 100644 --- a/types/ember/ember-tests.ts +++ b/types/ember/ember-tests.ts @@ -105,6 +105,17 @@ App.userController = Em.Object.create({ }) }); +Ember.Helper.helper((params) => { + let cents = params[0]; + return `${cents * 0.01}`; +}); + +Ember.Helper.helper((params, hash) => { + let cents = params[0]; + let currency = hash.currency; + return `${currency}${cents * 0.01}`; +}); + Handlebars.registerHelper('highlight', (property: string, options: any) => new Handlebars.SafeString('' + "some value" + '')); diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index f7aedcb7c1..37818e787e 100644 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -548,9 +548,9 @@ declare namespace Ember { toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; - '@each': EachProxy; + '@each': EachProxy; Boolean: boolean; - '[]': any[]; + '[]': any[]; firstObject: any; hasEnumerableObservers: boolean; lastObject: any; @@ -630,8 +630,8 @@ declare namespace Ember { unshiftObject(object: any): any; unshiftObjects(objects: any[]): any[]; without(value: any): Enumerable; - '[]': any[]; - '@each': EachProxy; + '[]': any[]; + '@each': EachProxy; Boolean: boolean; firstObject: any; hasEnumerableObservers: boolean; @@ -1030,7 +1030,7 @@ declare namespace Ember { toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; - '[]': any[]; + '[]': any[]; firstObject: any; hasEnumerableObservers: boolean; lastObject: any; @@ -1137,7 +1137,7 @@ declare namespace Ember { service(name?: string): Service; }; class Helper extends Object { - static helper( h: (a: any) => any): Helper; + static helper( h: (params: any, hash?: any) => any): Helper; compute(params: any[], hash: any): any; recompute(params: any[], hash: any): any; } @@ -1291,7 +1291,7 @@ declare namespace Ember { toArray(): any[]; uniq(): Enumerable; without(value: any): Enumerable; - '[]': any[]; + '[]': any[]; firstObject: any; hasEnumerableObservers: boolean; lastObject: any; diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 7118fd4403..2dc9e98c87 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; -import {shallow, mount, render, ShallowWrapper, ReactWrapper} from "enzyme"; -import {Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent} from "react"; +import { shallow, mount, render, ShallowWrapper, ReactWrapper } from "enzyme"; +import { Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent } from "react"; // Help classes/interfaces interface MyComponentProps { @@ -27,9 +27,11 @@ const MyStatelessComponent = (props: StatelessProps) => ; // ShallowWrapper function ShallowWrapperTest() { let shallowWrapper: ShallowWrapper = - shallow(); + shallow(); let reactElement: ReactElement; + let reactElements: Array>; + let domElement: Element; let boolVal: boolean; let stringVal: string; let numOrStringVal: number | string; @@ -44,7 +46,7 @@ function ShallowWrapperTest() { } function test_shallow_options() { - shallow(, { + shallow(, { context: { test: "a", }, @@ -80,19 +82,19 @@ function ShallowWrapperTest() { } function test_contains() { - boolVal = shallowWrapper.contains(
); + boolVal = shallowWrapper.contains(
); } function test_containsMatchingElement() { - boolVal = shallowWrapper.contains(
); + boolVal = shallowWrapper.contains(
); } function test_containsAllMatchingElements() { - boolVal = shallowWrapper.containsAllMatchingElements([
]); + boolVal = shallowWrapper.containsAllMatchingElements([
]); } function test_containsAnyMatchingElement() { - boolVal = shallowWrapper.containsAnyMatchingElements([
]); + boolVal = shallowWrapper.containsAnyMatchingElements([
]); } function test_dive() { @@ -104,15 +106,15 @@ function ShallowWrapperTest() { bar: any; } - const diveWrapper: ShallowWrapper = shallowWrapper.dive({ context: { foobar: 'barfoo' }}); + const diveWrapper: ShallowWrapper = shallowWrapper.dive({ context: { foobar: 'barfoo' } }); } function test_equals() { - boolVal = shallowWrapper.equals(
); + boolVal = shallowWrapper.equals(
); } function test_matchesElement() { - boolVal = shallowWrapper.matchesElement(
); + boolVal = shallowWrapper.matchesElement(
); } function test_hasClass() { @@ -196,6 +198,18 @@ function ShallowWrapperTest() { reactElement = shallowWrapper.get(1); } + function test_getNode() { + reactElement = shallowWrapper.getNode(); + } + + function test_getNodes() { + reactElements = shallowWrapper.getNodes(); + } + + function test_getDOMNode() { + domElement = shallowWrapper.getDOMNode(); + } + function test_at() { shallowWrapper = shallowWrapper.at(1); } @@ -208,6 +222,15 @@ function ShallowWrapperTest() { shallowWrapper = shallowWrapper.last(); } + function test_slice() { + shallowWrapper = shallowWrapper.slice(1); + shallowWrapper = shallowWrapper.slice(1, 3); + } + + function test_tap() { + shallowWrapper.tap((intercepter) => { }); + } + function test_state() { const state: MyComponentState = shallowWrapper.state(); const prop: string = shallowWrapper.state('stateProperty'); @@ -333,9 +356,11 @@ function ShallowWrapperTest() { // ReactWrapper function ReactWrapperTest() { let reactWrapper: ReactWrapper = - mount(); + mount(); let reactElement: ReactElement; + let reactElements: Array>; + let domElement: Element; let boolVal: boolean; let stringVal: string; let elementWrapper: ReactWrapper, {}>; @@ -355,7 +380,7 @@ function ReactWrapperTest() { function test_mount() { reactWrapper = reactWrapper.mount(); - mount(, { + mount(, { attachTo: document.getElementById('test'), context: { a: "b" @@ -409,27 +434,27 @@ function ReactWrapperTest() { } function test_contains() { - boolVal = reactWrapper.contains(
); + boolVal = reactWrapper.contains(
); } function test_containsMatchingElement() { - boolVal = reactWrapper.contains(
); + boolVal = reactWrapper.contains(
); } function test_containsAllMatchingElements() { - boolVal = reactWrapper.containsAllMatchingElements([
]); + boolVal = reactWrapper.containsAllMatchingElements([
]); } function test_containsAnyMatchingElement() { - boolVal = reactWrapper.containsAnyMatchingElements([
]); + boolVal = reactWrapper.containsAnyMatchingElements([
]); } function test_equals() { - boolVal = reactWrapper.equals(
); + boolVal = reactWrapper.equals(
); } function test_matchesElement() { - boolVal = reactWrapper.matchesElement(
); + boolVal = reactWrapper.matchesElement(
); } function test_hasClass() { @@ -501,6 +526,18 @@ function ReactWrapperTest() { reactElement = reactWrapper.get(1); } + function test_getNode() { + reactElement = reactWrapper.getNode(); + } + + function test_getNodes() { + reactElements = reactWrapper.getNodes(); + } + + function test_getDOMNode() { + domElement = reactWrapper.getDOMNode(); + } + function test_at() { reactWrapper = reactWrapper.at(1); } @@ -513,6 +550,15 @@ function ReactWrapperTest() { reactWrapper = reactWrapper.last(); } + function test_slice() { + reactWrapper = reactWrapper.slice(1); + reactWrapper = reactWrapper.slice(1, 3); + } + + function test_tap() { + reactWrapper.tap((intercepter) => { }); + } + function test_state() { const state: MyComponentState = reactWrapper.state(); const prop: string = reactWrapper.state('stateProperty'); diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index abd40975be..721895e522 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Enzyme 2.7 +// Type definitions for Enzyme 2.8 // Project: https://github.com/airbnb/enzyme // Definitions by: Marian Palkus // Cap3 @@ -6,6 +6,7 @@ // Tom Crockett // jwbay // huhuanming +// MartynasZilinskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -22,7 +23,7 @@ export class ElementClass extends Component { * all specified in the implementation. TS chooses the EnzymePropSelector overload and loses the generics */ export interface ComponentClass { - new(props?: Props, context?: any): Component; + new (props?: Props, context?: any): Component; } export type StatelessComponent = (props: Props, context?: any) => JSX.Element; @@ -42,6 +43,8 @@ export interface EnzymePropSelector { } export type EnzymeSelector = string | StatelessComponent | ComponentClass | EnzymePropSelector; +export type Intercepter = (intercepter: T) => void; + export interface CommonWrapper { /** * Returns a new wrapper with only the nodes of the current wrapper that, when passed into the provided predicate function, return true. @@ -97,6 +100,7 @@ export interface CommonWrapper { /** * Returns whether or not the current node is empty. + * @deprecated Use .exists() instead. */ isEmpty(): boolean; @@ -134,6 +138,21 @@ export interface CommonWrapper { */ get(index: number): ReactElement; + /** + * Returns the wrapper's underlying node. + */ + getNode(): ReactElement; + + /** + * Returns the wrapper's underlying nodes. + */ + getNodes(): Array>; + + /** + * Returns the outer most DOMComponent of the current wrapper. + */ + getDOMNode(): Element; + /** * Returns a wrapper around the node at a given index of the current wrapper. * @param index @@ -150,6 +169,16 @@ export interface CommonWrapper { */ last(): this; + /** + * Returns a new wrapper with a subset of the nodes of the original wrapper, according to the rules of `Array#slice`. + */ + slice(begin?: number, end?: number): this; + + /** + * Taps into the wrapper method chain. Helpful for debugging. + */ + tap(intercepter: Intercepter): this; + /** * Returns the state hash for the root node of the wrapper. Optionally pass in a prop name and it will return just that value. * @param [key] @@ -335,7 +364,7 @@ export interface CommonWrapper { * * Note: can only be called on a wrapper of a single node. */ - type(): string | ComponentClass

| StatelessComponent

; + type(): string | ComponentClass

| StatelessComponent

; length: number; } diff --git a/types/exceljs/exceljs-tests.ts b/types/exceljs/exceljs-tests.ts new file mode 100644 index 0000000000..95147c7726 --- /dev/null +++ b/types/exceljs/exceljs-tests.ts @@ -0,0 +1,82 @@ +import * as Excel from 'exceljs'; + +// most examples taken and adapted from README.md + +const workbook = new Excel.Workbook(); + +workbook.creator = 'Me'; +workbook.lastModifiedBy = 'Her'; +workbook.created = new Date(1985, 8, 30); +workbook.modified = new Date(); +workbook.lastPrinted = new Date(2016, 9, 27); +workbook.properties.date1904 = true; + +workbook.views = [ + { + x: 0, y: 0, width: 10000, height: 20000, + firstSheet: 0, activeTab: 1, visibility: 'visible' + } +]; + +const worksheet: Excel.Worksheet = workbook.addWorksheet('My Sheet'); +const worksheet2 = workbook.getWorksheet('My Sheet'); +const worksheet3 = workbook.getWorksheet(1); +const sheet = workbook.addWorksheet('My Sheet', {views: [{showGridLines: false}]}); + +const row: Excel.Row = worksheet.addRow([3, 'Sam', new Date()]); +row.getCell(1).value = 5; + +worksheet.eachRow((row: Excel.Row, rowNumber: number): void => { + // nothing +}); + +row.eachCell((cell: Excel.Cell, colNumber: number): void => { + // nothing +}); + +worksheet.mergeCells('A4:B5'); + +worksheet.getCell('A1').numFmt = '0.00%'; +worksheet.getCell('A1').font = { + name: 'Comic Sans MS', + family: 4, + size: 16, + underline: true, + bold: true +}; + +worksheet.getCell('A1').alignment = { vertical: 'top', horizontal: 'left' }; +worksheet.getCell('B1').alignment = { vertical: 'middle', horizontal: 'center' }; +worksheet.getCell('C1').alignment = { vertical: 'bottom', horizontal: 'right' }; +worksheet.getCell('D1').alignment = { wrapText: true }; +worksheet.getCell('E1').alignment = { indent: 1 }; + +worksheet.getCell('A1').border = { + top: {style: 'thin'}, + left: {style: 'thin'}, + bottom: {style: 'thin'}, + right: {style: 'thin'} +}; + +worksheet.getCell('A3').border = { + top: {style: 'double', color: {argb: 'FF00FF00'}}, + left: {style: 'double', color: {argb: 'FF00FF00'}}, + bottom: {style: 'double', color: {argb: 'FF00FF00'}}, + right: {style: 'double', color: {argb: 'FF00FF00'}} +}; + +worksheet.getCell('A1').fill = { + type: 'pattern', + pattern: 'solid', + fgColor: {argb: 'FFFF0000'} +}; + +workbook.xlsx.readFile("/home/john/bla.xlsx") + .then((): void => { + // use workbook + }); + +workbook.xlsx.writeFile("/home/john/bla.xlsx") + .then((): void => { + // done + }); diff --git a/types/exceljs/index.d.ts b/types/exceljs/index.d.ts new file mode 100644 index 0000000000..259eaccae1 --- /dev/null +++ b/types/exceljs/index.d.ts @@ -0,0 +1,231 @@ +// Type definitions for exceljs 0.4 +// Project: https://github.com/guyonroche/exceljs +// Definitions by: Rogier Schouten +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const enum ValueType { + Null = 0, + Merge = 1, + Number = 2, + String = 3, + Date = 4, + Hyperlink = 5, + Formula = 6, + SharedString = 7, + RichText = 8, + Boolean = 9, + Error = 10 +} + +export const enum FormulaType { + None = 0, + Master = 1, + Shared = 2 +} + +export const enum RelationshipType { + None = 0, + OfficeDocument = 1, + Worksheet = 2, + CalcChain = 3, + SharedStrings = 4, + Styles = 5, + Theme = 6, + Hyperlink = 7 +} + +export const enum DocumentType { + Xlsx = 1 +} + +export const enum ReadingOrder { + RightToLeft = 1, + LeftToRight = 2, +} + +export interface ErrorValue { + error: "#N/A" | "#REF!" | "#NAME?" | "#DIV/0!" | "#NULL!" | "#VALUE!" | "#NUM!"; +} + +export interface WorksheetView { + state?: "normal" | "split" | "frozen"; + showRuler?: boolean; + showRowColHeaders?: boolean; + showGridLines?: boolean; + zoomScale?: number; + zoomScaleNormal?: number; + style?: "pageBreakPreview" | "pageLayout"; +} + +export interface WorkbookView { + x?: number; + y?: number; + width?: number; + height?: number; + firstSheet?: number; + activeTab?: number; + visibility?: string; +} + +export interface Fill { + type: "pattern" | "gradient"; + pattern?: "none" | "solid"; + fgColor?: Color; + bgColor?: Color; +} + +export interface Font { + name: string; + size?: number; + family?: number; + schema?: "minor" | "major" | "none"; + charset?: number; + color?: Color; + bold?: boolean; + italic?: boolean; + underline?: true | false | "none" | "single" | "double" | "singleAccounting" | "doubleAccounting"; + strike?: boolean; + outline?: boolean; +} + +export type BorderStyle = + "thin" | "dotted" | "dashDot" | "hair" | "dashDotDot" | "slantDashDot" | "mediumDashed" | "mediumDashDotDot" | + "mediumDashDot" | "medium" | "double" | "thick"; + +export interface Color { + /** + * Hex string for alpha-red-green-blue e.g. FF00FF00 + */ + argb: string; +} + +export interface Border { + style?: BorderStyle; + color?: Color; +} + +export interface Borders { + top?: Border; + left?: Border; + bottom?: Border; + right?: Border; +} + +export interface Alignment { + horizontal?: "left" | "center" | "right" | "fill" | "justify" | "centerContinuous" | "distributed"; + vertical?: "top" | "middle" | "bottom" | "distributed" | "justify"; + wrapText?: boolean; + indent?: number; + readingOrder?: "rtl" | "ltr"; + textrotation?: number | "vertical"; +} + +export interface Cell { + border?: Borders; + font?: Font; + alignment?: Alignment; + numFmt?: string; + value?: any; + fill?: Fill; +} + +export interface Row { + /** + * The row number + */ + number: number; + height: number; + hidden: boolean; + collapsed: boolean; + values: any[]; + outlineLevel?: number; + + readonly cellCount: number; + readonly actualCellCount: number; + + getCell(index: number): Cell; + + eachCell(callback: (cell: Cell, colNumber: number) => void): void; + eachCell(opts: { includeEmpty: boolean}, callback: (cell: Cell, colNumber: number) => void): void; +} + +export interface Column { + width: number; +} + +export interface Worksheet { + /** + * The total row size of the document. Equal to the row number of the last row that has values. + */ + rowCount: number; + /** + * A count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count. + */ + actualRowCount: number; + /** + * The total column size of the document. Equal to the maximum cell count from all of the rows + */ + columnCount: number; + /** + * A count of the number of columns that have values. + */ + actualColumnCount: number; + + /** + * Get or create a column + */ + getColumn(index: number): Column; + + /** + * Create a new row + */ + addRow(data: any[]): Row; + + /** + * Get or create row by 0-based index + */ + getRow(index: number): Row; + eachRow(callback: (row: Row, rowNumber: number) => void): void; + + /** + * Get or create cell + */ + getCell(ref: string): Cell; + + /** + * Merge cells, either: + * tlbr string + * tl string, br string + * t, l, b, r numbers + */ + mergeCells(a: number | string, b?: number | string, c?: number, d?: number): void; +} + +export interface Xlsx { + readFile(path: string): Promise; + writeFile(path: string): Promise; +} + +export interface WorksheetProps { + showGridLines: boolean; +} + +export class Workbook { + constructor(); + + creator: string; + lastModifiedBy: string; + created: Date; + modified: Date; + lastPrinted: Date; + properties: { + date1904: boolean; + }; + views: WorkbookView[]; + + addWorksheet(name: string, opts?: { properties?: WorksheetProps, views?: WorksheetView[] }): Worksheet; + + getWorksheet(indexOrName: number | string): Worksheet; + + xlsx: Xlsx; +} diff --git a/types/exceljs/tsconfig.json b/types/exceljs/tsconfig.json new file mode 100644 index 0000000000..f9cb219d06 --- /dev/null +++ b/types/exceljs/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "exceljs-tests.ts" + ] +} diff --git a/types/exceljs/tslint.json b/types/exceljs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/exceljs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fecha/fecha-tests.ts b/types/fecha/fecha-tests.ts new file mode 100644 index 0000000000..0d0ce48638 --- /dev/null +++ b/types/fecha/fecha-tests.ts @@ -0,0 +1,124 @@ +import fecha = require('fecha'); + +// test fecha.parse +fecha.parse("February 3rd, 2014", "MMMM Do, YYYY"); +fecha.parse("5/3/98", "shortDate"); + +// test override fecha.i18n +fecha.i18n = { + dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"], + dayNames: [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + monthNamesShort: [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ], + monthNames: [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + amPm: ["am", "pm"], + DoFn(D: number) { + return D + "th"; + } +}; + +// just change one default mask +fecha.masks.shortDate = "M/D/YY"; + +// test override fecha.masks with an object. Must implement all keys. +// if you want to implement partially, use +// fecha.masks = Object.assign(fecha.masks, {shortDate: 'M/D/YY'}) for example. +fecha.masks = { + default: "ddd MMM DD YYYY HH:mm:ss", + shortDate: "M/D/YY", + mediumDate: "MMM D, YYYY", + longDate: "MMMM D, YYYY", + fullDate: "dddd, MMMM D, YYYY", + shortTime: "HH:mm", + mediumTime: "HH:mm:ss", + longTime: "HH:mm:ss.SSS" +}; + +// test add custom named mask. +// fecha.masks.myMask = "HH:mm:ss YY/MM/DD"; does not work for now. +fecha.masks['myMask'] = "HH:mm:ss YY/MM/DD"; + +// test fecha.format without i18nSettings, with Date object. +fecha.format(new Date(2014, 5, 6, 14, 10, 45), "myMask"); + +// test fecha.format without i18nSettings with number. +fecha.format(Date.now(), "myMask"); + +// test override i18nSettings with fecha.format +fecha.format(new Date(2014, 5, 6, 14, 10, 45), "myMask", { + dayNamesShort: ["Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat"], + dayNames: [ + "Sunday", + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday" + ], + monthNamesShort: [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ], + monthNames: [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + amPm: ["am", "pm"], + DoFn(D: number) { + return D + "th"; + } +}); diff --git a/types/fecha/index.d.ts b/types/fecha/index.d.ts new file mode 100644 index 0000000000..f68d26a316 --- /dev/null +++ b/types/fecha/index.d.ts @@ -0,0 +1,52 @@ +// Type definitions for fecha 2.3 +// Project: https://github.com/taylorhakes/fecha +// Definitions by: Goh Yisheng +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Days = [string, string, string, string, string, string, string]; + +export type Months = [ + string, + string, + string, + string, + string, + string, + string, + string, + string, + string, + string, + string +]; + +export interface i18nSettings { + amPm: [string, string]; + dayNames: Days; + dayNamesShort: Days; + monthNames: Months; + monthNamesShort: Months; + DoFn(D: number): string; +} + +export interface Masks { + default: string; + fullDate: string; + longDate: string; + longTime: string; + mediumDate: string; + mediumTime: string; + shortDate: string; + shortTime: string; + [myMask: string]: string; +} + +export let masks: Masks; + +export let i18n: i18nSettings; + +export function format(dateObj: Date | number, mask: string, i18nSettings?: i18nSettings): string; + +export function parse(dateStr: string, format: string, i18nSettings?: i18nSettings): Date; + +export as namespace Fecha; diff --git a/types/fecha/tsconfig.json b/types/fecha/tsconfig.json new file mode 100644 index 0000000000..581630d1b6 --- /dev/null +++ b/types/fecha/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fecha-tests.ts" + ] +} diff --git a/types/fecha/tslint.json b/types/fecha/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fecha/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fs-extra-promise/index.d.ts b/types/fs-extra-promise/index.d.ts index a03512a577..b4c9a648ac 100644 --- a/types/fs-extra-promise/index.d.ts +++ b/types/fs-extra-promise/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/overlookmotel/fs-extra-promise // Definitions by: midknight41 , Jason Swearingen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// /// @@ -10,10 +11,15 @@ import * as stream from 'stream'; import { Stats } from 'fs'; import * as Promise from 'bluebird'; -import { CopyFilter, CopyOptions, ReadOptions, WriteOptions, MkdirOptions, MoveOptions } from 'fs-extra'; +import { CopyFilter, CopyOptions, ReadOptions, WriteOptions, MoveOptions } from 'fs-extra'; export * from 'fs-extra'; +export interface MkdirOptions { + fs?: any; + mode?: number; +} + //promisified versions export declare function copyAsync(src: string, dest: string): Promise; export declare function copyAsync(src: string, dest: string, filter: CopyFilter): Promise; diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index d39cae8d6f..005857e48c 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -1,106 +1,214 @@ import * as fs from 'fs-extra'; import * as Path from 'path'; +const len = 2; const src = ""; const dest = ""; const file = ""; const dir = ""; const path = ""; const data = ""; +const uid = 0; +const gid = 0; +const fd = 0; +const modeNum = 0; +const modeStr = ""; const object = {}; -const errorCallback = (err: Error) => {}; +const errorCallback = (err: Error) => { }; const readOptions: fs.ReadOptions = { - reviver : {} + reviver: {} }; const writeOptions: fs.WriteOptions = { - replacer: {} + replacer: {} }; +fs.moveSync(src, dest, {}); +fs.move(src, dest, {}).then(() => { + // stub +}); +fs.move(src, dest).then(() => { + // stub +}); +fs.move(src, dest, {}, () => { + // stub +}); +fs.move(src, dest, () => { + // stub +}); + +fs.copy(src, dest).then(() => { + // stub +}); +fs.copy(src, dest, { overwrite: true }).then(() => { + // stub +}); fs.copy(src, dest, errorCallback); -fs.copy(src, dest, (src: string) => { - return false; -}, errorCallback); +fs.copy(src, dest, (src: string) => false, errorCallback); fs.copy(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, - filter: (src: string) => { return false; } + filter: (src: string) => false }, errorCallback ); fs.copy(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, filter: /.*/ }, errorCallback ); fs.copySync(src, dest); -fs.copySync(src, dest, (src: string) => { - return false; -}); +fs.copySync(src, dest, (src: string) => false); fs.copySync(src, dest, /.*/); fs.copySync(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, - filter: (src: string) => { return false; } + filter: (src: string) => false } ); fs.copySync(src, dest, { - clobber: true, + overwrite: true, preserveTimestamps: true, filter: /.*/ } ); +fs.createFile(file).then(() => { + // stub +}); fs.createFile(file, errorCallback); fs.createFileSync(file); +fs.mkdirs(dir).then(() => { + // stub +}); +fs.mkdirp(dir).then(() => { + // stub +}); fs.mkdirs(dir, errorCallback); -fs.mkdirs(dir, {}, errorCallback); fs.mkdirsSync(dir); -fs.mkdirsSync(dir, {}); fs.mkdirp(dir, errorCallback); -fs.mkdirp(dir, {}, errorCallback); fs.mkdirpSync(dir); -fs.mkdirpSync(dir, {}); +fs.outputFile(file, data).then(() => { + // stub +}); fs.outputFile(file, data, errorCallback); fs.outputFileSync(file, data); -fs.outputJson(file, data, errorCallback); + +fs.outputJson(file, data, { + spaces: 2 +}).then(() => { + // stub +}); +fs.outputJson(file, data, { + spaces: 2 +}, errorCallback); fs.outputJSON(file, data, errorCallback); +fs.outputJSON(file, data).then(() => { + // stub +}); fs.outputJsonSync(file, data); fs.outputJSONSync(file, data); -fs.readJson(file, (error: Error, jsonObject: any) => {}); -fs.readJson(file, readOptions, (error: Error, jsonObject: any) => {}); -fs.readJSON(file, (error: Error, jsonObject: any) => {}); -fs.readJSON(file, readOptions, (error: Error, jsonObject: any) => {}); +fs.readJson(file).then(() => { + // stub +}); + +fs.readJson(file, readOptions).then(() => { + // stub +}); +fs.readJson(file, (error: Error, jsonObject: any) => { }); +fs.readJson(file, readOptions, (error: Error, jsonObject: any) => { }); +fs.readJSON(file, (error: Error, jsonObject: any) => { }); +fs.readJSON(file, readOptions, (error: Error, jsonObject: any) => { }); fs.readJsonSync(file, readOptions); fs.readJSONSync(file, readOptions); fs.remove(dir, errorCallback); +fs.remove(dir).then(() => { + // stub +}); fs.removeSync(dir); +fs.writeJson(file, object).then(() => { + // stub +}); +fs.writeJSON(file, object).then(() => { + // stub +}); fs.writeJson(file, object, errorCallback); fs.writeJson(file, object, writeOptions, errorCallback); fs.writeJSON(file, object, errorCallback); fs.writeJSON(file, object, writeOptions, errorCallback); - +fs.writeJson(file, object, writeOptions).then(() => { + // stub +}); +fs.writeJSON(file, object, writeOptions).then(() => { + // stub +}); fs.writeJsonSync(file, object, writeOptions); fs.writeJSONSync(file, object, writeOptions); +fs.ensureDir(path).then(() => { + // stub +}); fs.ensureDir(path, errorCallback); fs.ensureDirSync(path); + +fs.ensureFile(path).then(() => { + // stub +}); fs.ensureFile(path, errorCallback); fs.ensureFileSync(path); +fs.ensureLink(path).then(() => { + // stub +}); fs.ensureLink(path, errorCallback); fs.ensureLinkSync(path); +fs.ensureSymlink(path).then(() => { + // stub +}); fs.ensureSymlink(path, errorCallback); fs.ensureSymlinkSync(path); +fs.emptyDir(path).then(() => { + // stub +}); fs.emptyDir(path, errorCallback); fs.emptyDirSync(path); +fs.pathExists(path).then((_exist: boolean) => { + // stub +}); +fs.pathExists(path, (_err: Error, _exists: boolean) => { }); +const x: boolean = fs.pathExistsSync(path); + +fs.rename(src, dest, errorCallback); +fs.renameSync(src, dest); +fs.truncate(path, len, errorCallback); +fs.truncateSync(path, len); +fs.chown(path, uid, gid, errorCallback); +fs.chownSync(path, uid, gid); +fs.fchown(fd, uid, gid, errorCallback); +fs.fchownSync(fd, uid, gid); +fs.lchown(path, uid, gid, errorCallback); +fs.lchownSync(path, uid, gid); +fs.chmod(path, modeNum, errorCallback); +fs.chmod(path, modeStr, errorCallback); +fs.chmodSync(path, modeNum); +fs.chmodSync(path, modeStr); +fs.fchmod(fd, modeNum, errorCallback); +fs.fchmod(fd, modeStr, errorCallback); +fs.fchmodSync(fd, modeNum); +fs.fchmodSync(fd, modeStr); +fs.lchmod(path, modeStr, errorCallback); +fs.lchmod(path, modeNum, errorCallback); +fs.lchmodSync(path, modeNum); +fs.lchmodSync(path, modeStr); +fs.statSync(path); +fs.lstatSync(path); diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index c46dddba85..3d65d617b0 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -1,9 +1,8 @@ -// Type definitions for fs-extra 2.1 +// Type definitions for fs-extra 3.0 // Project: https://github.com/jprichardson/node-fs-extra -// Definitions by: midknight41 , Brendan Forster +// Definitions by: Alan Agius , midknight41 , Brendan Forster // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts +// TypeScript Version: 2.2 /// @@ -11,123 +10,255 @@ import { Stats } from "fs"; export * from "fs"; -export declare function copy(src: string, dest: string, callback?: (err: Error) => void): void; -export declare function copy(src: string, dest: string, filter: CopyFilter, callback?: (err: Error) => void): void; -export declare function copy(src: string, dest: string, options: CopyOptions, callback?: (err: Error) => void): void; +export function copy(src: string, dest: string, options?: CopyOptions): Promise; +export function copy(src: string, dest: string, callback: (err: Error) => void): void; +export function copy(src: string, dest: string, options: CopyOptions, callback: (err: Error) => void): void; +export function copySync(src: string, dest: string, options?: CopyOptions): void; -export declare function copySync(src: string, dest: string): void; -export declare function copySync(src: string, dest: string, filter: CopyFilter): void; -export declare function copySync(src: string, dest: string, options: CopyOptions): void; +export function move(src: string, dest: string, options?: MoveOptions): Promise; +export function move(src: string, dest: string, callback: (err: Error) => void): void; +export function move(src: string, dest: string, options: MoveOptions, callback: (err: Error) => void): void; +export function moveSync(src: string, dest: string, options?: MoveOptions): void; -export declare function move(src: string, dest: string, callback?: (err: Error) => void): void; -export declare function move(src: string, dest: string, options: MoveOptions, callback?: (err: Error) => void): void; +export function createFile(file: string): Promise; +export function createFile(file: string, callback: (err: Error) => void): void; +export function createFileSync(file: string): void; -export declare function createFile(file: string, callback?: (err: Error) => void): void; -export declare function createFileSync(file: string): void; +export function ensureDir(path: string): Promise; +export function ensureDir(path: string, callback: (err: Error) => void): void; +export function ensureDirSync(path: string): void; -export declare function mkdirs(dir: string, callback?: (err: Error) => void): void; -export declare function mkdirp(dir: string, callback?: (err: Error) => void): void; -export declare function mkdirs(dir: string, options?: MkdirOptions, callback?: (err: Error) => void): void; -export declare function mkdirp(dir: string, options?: MkdirOptions, callback?: (err: Error) => void): void; -export declare function mkdirsSync(dir: string, options?: MkdirOptions): void; -export declare function mkdirpSync(dir: string, options?: MkdirOptions): void; +export function mkdirs(dir: string): Promise; +export function mkdirs(dir: string, callback: (err: Error) => void): void; +export function mkdirp(dir: string): Promise; +export function mkdirp(dir: string, callback: (err: Error) => void): void; +export function mkdirsSync(dir: string): void; +export function mkdirpSync(dir: string): void; -export declare function outputFile(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputFileSync(file: string, data: any): void; +export function outputFile(file: string, data: any): Promise; +export function outputFile(file: string, data: any, callback: (err: Error) => void): void; +export function outputFileSync(file: string, data: any): void; -export declare function outputJson(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputJSON(file: string, data: any, callback?: (err: Error) => void): void; -export declare function outputJsonSync(file: string, data: any): void; -export declare function outputJSONSync(file: string, data: any): void; +export function readJson(file: string, options?: ReadOptions): Promise; +export function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options?: ReadOptions): Promise; +export function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; +export function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJson(file: string, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJson(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJSON(file: string, callback: (err: Error, jsonObject: any) => void): void; -export declare function readJSON(file: string, options: ReadOptions, callback: (err: Error, jsonObject: any) => void): void; +export function readJsonSync(file: string, options?: ReadOptions): any; +export function readJSONSync(file: string, options?: ReadOptions): any; -export declare function readJsonSync(file: string, options?: ReadOptions): any; -export declare function readJSONSync(file: string, options?: ReadOptions): any; +export function remove(dir: string): Promise; +export function remove(dir: string, callback: (err: Error) => void): void; +export function removeSync(dir: string): void; -export declare function remove(dir: string, callback?: (err: Error) => void): void; -export declare function removeSync(dir: string): void; +export function outputJSON(file: string, data: any, options?: WriteOptions): Promise; +export function outputJSON(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJSON(file: string, data: any, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, options?: WriteOptions): Promise; +export function outputJson(file: string, data: any, options: WriteOptions, callback: (err: Error) => void): void; +export function outputJson(file: string, data: any, callback: (err: Error) => void): void; +export function outputJsonSync(file: string, data: any, options?: WriteOptions): void; +export function outputJSONSync(file: string, data: any, options?: WriteOptions): void; -export declare function writeJson(file: string, object: any, callback?: (err: Error) => void): void; -export declare function writeJson(file: string, object: any, options?: WriteOptions, callback?: (err: Error) => void): void; -export declare function writeJSON(file: string, object: any, callback?: (err: Error) => void): void; -export declare function writeJSON(file: string, object: any, options?: WriteOptions, callback?: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options?: WriteOptions): Promise; +export function writeJSON(file: string, object: any, callback: (err: Error) => void): void; +export function writeJSON(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options?: WriteOptions): Promise; +export function writeJson(file: string, object: any, callback: (err: Error) => void): void; +export function writeJson(file: string, object: any, options: WriteOptions, callback: (err: Error) => void): void; -export declare function writeJsonSync(file: string, object: any, options?: WriteOptions): void; -export declare function writeJSONSync(file: string, object: any, options?: WriteOptions): void; +export function writeJsonSync(file: string, object: any, options?: WriteOptions): void; +export function writeJSONSync(file: string, object: any, options?: WriteOptions): void; -export declare function ensureDir(path: string, callback: (err: Error) => void): void; -export declare function ensureDirSync(path: string): void; +export function ensureFile(path: string): Promise; +export function ensureFile(path: string, callback: (err: Error) => void): void; +export function ensureFileSync(path: string): void; -export declare function ensureFile(path: string, callback: (err: Error) => void): void; -export declare function ensureFileSync(path: string): void; +export function ensureLink(path: string): Promise; +export function ensureLink(path: string, callback: (err: Error) => void): void; +export function ensureLinkSync(path: string): void; -export declare function ensureLink(path: string, callback: (err: Error) => void): void; -export declare function ensureLinkSync(path: string): void; +export function ensureSymlink(path: string): Promise; +export function ensureSymlink(path: string, callback: (err: Error) => void): void; +export function ensureSymlinkSync(path: string): void; -export declare function ensureSymlink(path: string, callback: (err: Error) => void): void; -export declare function ensureSymlinkSync(path: string): void; +export function emptyDir(path: string): Promise; +export function emptyDir(path: string, callback: (err: Error) => void): void; +export function emptyDirSync(path: string): void; -export declare function emptyDir(path: string, callback?: (err: Error) => void): void; -export declare function emptyDirSync(path: string): boolean; +export function pathExists(path: string): Promise; +export function pathExists(path: string, callback: (err: Error, exists: boolean) => void): void; +export function pathExistsSync(path: string): boolean; -export interface WalkEventEmitter extends NodeJS.ReadableStream { - on(event: 'data', callback: (file: WalkEventFile) => void): this; - on(event: 'readable', callback: (this: PathEntryStream) => void): this; - on(event: 'error', callback: (error: Error, item: PathEntry) => void): this; - on(event: 'end', callback: () => void): this; - on(event: string | symbol, callback: Function): this; -} +// fs async methods +// copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/v6/index.d.ts -export interface WalkEventFile { +/** Tests a user's permissions for the file specified by path. */ +export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; +export function access(path: string | Buffer, mode?: number): Promise; + +export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number | string; flag?: string; }, callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(filename: string, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function appendFile(filename: string, data: any, options?: { encoding?: string; mode?: number | string; flag?: string; }): Promise; + +export function chmod(path: string | Buffer, mode: string | number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function chmod(path: string | Buffer, mode: string | number): Promise; + +export function chown(path: string | Buffer, uid: number, gid: number): Promise; +export function chown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; + +export function close(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function close(fd: number): Promise; + +export function fchmod(fd: number, mode: string | number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fchmod(fd: number, mode: string | number): Promise; + +export function fchown(fd: number, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fchown(fd: number, uid: number, gid: number): Promise; + +export function fdatasync(fd: number, callback: () => void): void; +export function fdatasync(fd: number): Promise; + +export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function fstat(fd: number): Promise; + +export function fsync(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function fsync(fd: number): Promise; + +export function ftruncate(fd: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function ftruncate(fd: number, len?: number): Promise; + +export function futimes(fd: number, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException) => void): void; +export function futimes(fd: number, atime: number, mtime: number): Promise; +export function futimes(fd: number, atime: Date, mtime: Date): Promise; + +export function lchown(path: string | Buffer, uid: number, gid: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function lchown(path: string | Buffer, uid: number, gid: number): Promise; + +export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function link(srcpath: string | Buffer, dstpath: string | Buffer): Promise; + +export function lstat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function lstat(path: string | Buffer): Promise; + +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +/** + * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. + * + * @param path + * @param mode + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function mkdir(path: string | Buffer, mode: number | string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function mkdir(path: string | Buffer): Promise; + +export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; +export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; + +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise<[number, Buffer]>; + +export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; +export function readFile(filename: string, options: { flag?: string; } | { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; +export function readFile(filename: string, options: { flag?: string; } | { encoding: string; flag?: string; }): Promise; +// tslint:disable-next-line:unified-signatures +export function readFile(filename: string, encoding: string): Promise; +export function readFile(filename: string): Promise; + +export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; +export function readdir(path: string | Buffer): Promise; + +export function readlink(path: string | Buffer, callback: (err: NodeJS.ErrnoException, linkString: string) => any): void; +export function readlink(path: string | Buffer): Promise; + +export function realpath(path: string | Buffer, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; +export function realpath(path: string | Buffer, cache?: { [path: string]: string }): Promise; + +export function rename(oldPath: string, newPath: string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function rename(oldPath: string, newPath: string): Promise; + +/** + * Asynchronous rmdir - removes the directory specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function rmdir(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function rmdir(path: string | Buffer): Promise; + +export function stat(path: string | Buffer, callback: (err: NodeJS.ErrnoException, stats: Stats) => any): void; +export function stat(path: string | Buffer): Promise; + +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type: string, callback: (err?: NodeJS.ErrnoException) => void): void; +export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): Promise; + +export function truncate(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function truncate(path: string | Buffer, len?: number): Promise; + +/** + * Asynchronous unlink - deletes the file specified in {path} + * + * @param path + * @param callback No arguments other than a possible exception are given to the completion callback. + */ +export function unlink(path: string | Buffer, callback: (err?: NodeJS.ErrnoException) => void): void; +export function unlink(path: string | Buffer): Promise; + +export function utimes(path: string | Buffer, atime: number, mtime: number, callback: (err?: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback: (err?: NodeJS.ErrnoException) => void): void; +export function utimes(path: string | Buffer, atime: number, mtime: number): Promise; +export function utimes(path: string | Buffer, atime: Date, mtime: Date): Promise; + +export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, callback: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; +export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; +export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise<[number, Buffer]>; +export function write(fd: number, data: any, offset: number, encoding?: string): Promise<[number, string]>; + +export function writeFile(filename: string, data: any, callback: (err: NodeJS.ErrnoException) => void): void; +export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; +export function writeFile(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): Promise; + +/** + * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * + * @param prefix + * @param callback The created folder path is passed as a string to the callback's second parameter. + */ +export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; +export function mkdtemp(prefix: string): Promise; + +export interface PathEntry { path: string; stats: Stats; } -export interface WalkOptions { - /** - * Control how results are enumerated from `readdir`: - * - 'shift' will return the first element from the array. - * - 'pop' will return the last element from the array. - * - * If not specified, the default behaviour is 'shift' - */ - queueMethod?: 'pop' | 'shift'; - /** - * Provide a function to sort the paths before they are enumerated - */ - pathSorter?: (left: string, right: string) => number; - /** - * An optional object to override the default `fs` APIs for testing purposes - */ - fs?: Object; - /** - * Provide a function to exclude certain file paths. The function should - * return true when the element should be kept, and false otherwise. - */ - filter?: (path: string, index: number, array: Array) => boolean; +export interface PathEntryStream { + read(): PathEntry | null; } -export type PathEntry = { - path: string; - stats: Stats; -} - -export type PathEntryStream = { - read(): PathEntry | null -} - -export interface CopyFilterFunction { - (src: string): boolean -} +export type CopyFilterFunction = (src: string) => boolean; export type CopyFilter = CopyFilterFunction | RegExp; export interface CopyOptions { - clobber?: boolean; dereference?: boolean; overwrite?: boolean; preserveTimestamps?: boolean; @@ -137,28 +268,23 @@ export interface CopyOptions { } export interface MoveOptions { - clobber? : boolean; + overwrite?: boolean; limit?: number; } export interface ReadOptions { throws?: boolean; - fs?: Object; + fs?: object; reviver?: any; encoding?: string; flag?: string; } export interface WriteOptions { - fs?: Object; + fs?: object; replacer?: any; spaces?: number; encoding?: string; flag?: string; mode?: number; } - -export interface MkdirOptions { - fs?: any; - mode?: number; -} diff --git a/types/fs-extra/tsconfig.json b/types/fs-extra/tsconfig.json index 6337361eed..818b38896c 100644 --- a/types/fs-extra/tsconfig.json +++ b/types/fs-extra/tsconfig.json @@ -1,22 +1,22 @@ { - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "fs-extra-tests.ts" - ] -} \ No newline at end of file + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fs-extra-tests.ts" + ] +} diff --git a/types/fs-extra/tslint.json b/types/fs-extra/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/fs-extra/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fullcalendar/fullcalendar-tests.ts b/types/fullcalendar/fullcalendar-tests.ts index 4557a94eef..ca456013af 100644 --- a/types/fullcalendar/fullcalendar-tests.ts +++ b/types/fullcalendar/fullcalendar-tests.ts @@ -417,13 +417,7 @@ $('#calendar').fullCalendar({ }); $('#calendar').fullCalendar({ - dayClick(date, allDay, jsEvent, view) { - if (allDay) { - alert('Clicked on the entire day: ' + date); - } else { - alert('Clicked on the slot: ' + date); - } - + dayClick(date, jsEvent, view) { alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY); alert('Current view: ' + view.name); diff --git a/types/fullcalendar/index.d.ts b/types/fullcalendar/index.d.ts index e040d613f9..2fedd216c6 100644 --- a/types/fullcalendar/index.d.ts +++ b/types/fullcalendar/index.d.ts @@ -90,7 +90,7 @@ export interface Options extends AgendaOptions, EventDraggingResizingOptions, Dr // Clicking & Hovering - http://fullcalendar.io/docs/mouse/ - dayClick?(date: Date, allDay: boolean, jsEvent: MouseEvent, view: ViewObject): void; + dayClick?(date: Date, jsEvent: MouseEvent, view: ViewObject): void; eventClick?(event: EventObject, jsEvent: MouseEvent, view: ViewObject): any; // return type boolean or void eventMouseover?(event: EventObject, jsEvent: MouseEvent, view: ViewObject): void; eventMouseout?(event: EventObject, jsEvent: MouseEvent, view: ViewObject): void; diff --git a/types/googlemaps/googlemaps-tests.ts b/types/googlemaps/googlemaps-tests.ts index f57a4e80e0..20d2bc51c8 100644 --- a/types/googlemaps/googlemaps-tests.ts +++ b/types/googlemaps/googlemaps-tests.ts @@ -11,6 +11,7 @@ let map = new google.maps.Map( fullscreenControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP }, + gestureHandling: "cooperative", scrollwheel: true, zoom: 4 }); diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index 1ca49880c9..0e12a8e643 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Maps JavaScript API 3.26 // Project: https://developers.google.com/maps/ -// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin +// Definitions by: Folia A/S , Chris Wrench , Kiarash Ghiaseddin , Grant Hutchins , Denis Atyasov , Michael McMullin , Martin Costello // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* @@ -95,6 +95,10 @@ declare namespace google.maps { fullscreenControl?: boolean; /** The display options for the Fullscreen control. */ fullscreenControlOptions?: FullscreenControlOptions; + /** + * This setting controls how gestures on the map are handled. + */ + gestureHandling?: GestureHandlingOptions; /** * The heading for aerial imagery in degrees measured clockwise from cardinal * direction North. Headings are snapped to the nearest available angle for @@ -250,6 +254,12 @@ declare namespace google.maps { opened?: boolean; } + export type GestureHandlingOptions = + "cooperative" | + "greedy" | + "none" | + "auto"; + /** Options for the rendering of the pan control. */ export interface PanControlOptions { /** diff --git a/types/grecaptcha/grecaptcha-tests.ts b/types/grecaptcha/grecaptcha-tests.ts index 3546ac3433..f1da1b35b4 100644 --- a/types/grecaptcha/grecaptcha-tests.ts +++ b/types/grecaptcha/grecaptcha-tests.ts @@ -1,22 +1,33 @@ - - -var params: ReCaptchaV2.Parameters = { - "sitekey": "mySuperSecretKey", - "theme": "light", - "type": "image", - "size": "normal", - "tabindex": 5, - "callback": (response: string) => { }, +const params: ReCaptchaV2.Parameters = { + sitekey: "mySuperSecretKey", + theme: "light", + type: "image", + size: "normal", + tabindex: 5, + callback: (response: string) => { }, "expired-callback": () => { }, -} +}; -var id1: number = grecaptcha.render("foo"); -var id2: number = grecaptcha.render("foo", params); -var id3: number = grecaptcha.render(document.getElementById("foo")); -var id4: number = grecaptcha.render(document.getElementById("foo"), params); +const size1: ReCaptchaV2.Size = "compact"; +const size2: ReCaptchaV2.Size = "invisible"; +const size3: ReCaptchaV2.Size = "normal"; + +const badge1: ReCaptchaV2.Badge = "bottomleft"; +const badge2: ReCaptchaV2.Badge = "bottomright"; +const badge3: ReCaptchaV2.Badge = "inline"; + +const invisibleParams: ReCaptchaV2.Parameters = { + sitekey: "siteKey", + badge: badge1, +}; + +const id1: number = grecaptcha.render("foo"); +const id2: number = grecaptcha.render("foo", params); +const id3: number = grecaptcha.render(document.getElementById("foo")); +const id4: number = grecaptcha.render(document.getElementById("foo"), params); // response takes a number and returns a string -var response1: string = grecaptcha.getResponse(id1); +const response1: string = grecaptcha.getResponse(id1); // reset takes a number grecaptcha.reset(id1); diff --git a/types/grecaptcha/index.d.ts b/types/grecaptcha/index.d.ts index 26f4e69507..59d1fa6699 100644 --- a/types/grecaptcha/index.d.ts +++ b/types/grecaptcha/index.d.ts @@ -1,85 +1,90 @@ // Type definitions for Google Recaptcha 2.0 // Project: https://www.google.com/recaptcha -// Definitions by: Kristof Mattei , Martin Costello +// Definitions by: Kristof Mattei , Martin Costello , Ruslan Arkhipau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare var grecaptcha: ReCaptchaV2.ReCaptcha; -declare namespace ReCaptchaV2 -{ - class ReCaptcha - { +declare namespace ReCaptchaV2 { + class ReCaptcha { /** - * Renders the container as a reCAPTCHA widget and returns the ID of the newly created widget. - * @param container The HTML element to render the reCAPTCHA widget. Specify either the ID of the container (string) or the DOM element itself. - * @param parameters An object containing parameters as key=value pairs, for example, {"sitekey": "your_site_key", "theme": "light"}. See @see render parameters. - * @return the ID of the newly created widget. - **/ + * Renders the container as a reCAPTCHA widget and returns the ID of the newly created widget. + * @param container The HTML element to render the reCAPTCHA widget. Specify either the ID of the container (string) or the DOM element itself. + * @param parameters An object containing parameters as key=value pairs, for example, {"sitekey": "your_site_key", "theme": "light"}. See @see render parameters. + * @return the ID of the newly created widget. + */ render(container: (string | HTMLElement), parameters?: Parameters): number; /** - * Resets the reCAPTCHA widget. - * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. - **/ + * Resets the reCAPTCHA widget. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + */ reset(opt_widget_id?: number): void; /** - * Gets the response for the reCAPTCHA widget. - * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. - * @return the response of the reCAPTCHA widget. - **/ + * Gets the response for the reCAPTCHA widget. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + * @return the response of the reCAPTCHA widget. + */ getResponse(opt_widget_id?: number): string; /** - * Programatically invoke the reCAPTCHA check. Used if the invisible reCAPTCHA is on a div instead of a button. - * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. - **/ + * Programatically invoke the reCAPTCHA check. Used if the invisible reCAPTCHA is on a div instead of a button. + * @param opt_widget_id Optional widget ID, defaults to the first widget created if unspecified. + */ execute(opt_widget_id?: number): void; } type Theme = "light" | "dark"; type Type = "image" | "audio"; - type Size = "normal" | "compact"; + type Size = "normal" | "compact" | "invisible"; + type Badge = "bottomright" | "bottomleft" | "inline"; - interface Parameters - { + interface Parameters { /** - * Your sitekey. - **/ + * Your sitekey. + */ sitekey: string; /** - * Optional. The color theme of the widget. - * Accepted values: "light", "dark" - * @default "light" - * @type {Theme} - **/ + * Optional. The color theme of the widget. + * Accepted values: "light", "dark" + * @default "light" + * @type {Theme} + */ theme?: Theme; /** - * Optional. The type of CAPTCHA to serve. - * Accepted values: "audio", "image" - * @default "image" - * @type {Type} - **/ + * Optional. The type of CAPTCHA to serve. + * Accepted values: "audio", "image" + * @default "image" + * @type {Type} + */ type?: Type; /** - * Optional. The size of the widget. - * Accepted values: "compact", "normal" - * @default "compact" - * @type {Size} - */ + * Optional. The size of the widget. + * Accepted values: "compact", "normal", "invisible". + * @default "compact" + * @type {Size} + */ size?: Size; /** - * Optional. The tabindex of the widget and challenge. - * If other elements in your page use tabindex, it should be set to make user navigation easier. - **/ + * Optional. The tabindex of the widget and challenge. + * If other elements in your page use tabindex, it should be set to make user navigation easier. + */ tabindex?: number; /** - * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. - * The user's response, g-recaptcha-response, will be the input for your callback function. - **/ - callback?: (response: string) => void; + * Optional. Your callback function that's executed when the user submits a successful CAPTCHA response. + * The user's response, g-recaptcha-response, will be the input for your callback function. + */ + callback?(response: string): void; /** - * Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. - **/ + * Optional. The badge location for g-recaptcha with size of "invisible". + * + * @default "bottomright" + * @type {Badge} + */ + badge?: Badge; + /** + * Optional. Your callback function that's executed when the recaptcha response expires and the user needs to solve a new CAPTCHA. + */ // Notice to the reader // I need to surround this object with quotes, this will however break intellisense in VS 2013. - "expired-callback"?: () => void; + "expired-callback"?(): void; } } diff --git a/types/grecaptcha/tslint.json b/types/grecaptcha/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/grecaptcha/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts b/types/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts index d0bf1b8688..640706f856 100644 --- a/types/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts +++ b/types/hapi-auth-jwt2/hapi-auth-jwt2-tests.ts @@ -29,13 +29,14 @@ function validate(decoded: User, request: Hapi.Request, callback: hapiAuthJwt2.V } server.register(hapiAuthJwt2, err => { - server.auth.strategy('jwt', 'jwt', { + const options: hapiAuthJwt2.Options = { key: 'NeverShareYourSecret', validateFunc: validate, verifyOptions: { algorithms: ['HS256'] } - }); + }; + server.auth.strategy('jwt', 'jwt', options); }); server.start(); diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index d4c8861a78..6fdef94dec 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -120,8 +120,8 @@ export interface IServerConnectionOptions extends IConnectionConfigurationServer export interface IConnectionConfigurationServerDefaults { /** application-specific connection configuration which can be accessed via connection.settings.app. Provides a safe place to store application configuration without potential conflicts with the framework internals. Should not be used to configure plugins which should use plugins[name]. Note the difference between connection.settings.app which is used to store configuration values and connection.app which is meant for storing run-time state. */ app?: any; - /** if false, response content encoding is disabled. Defaults to true */ - compression?: boolean; + /** if false, response content encoding is disabled. Defaults to true */ + compression?: boolean; /** connection load limits configuration where: */ load?: { /** maximum V8 heap size over which incoming requests are rejected with an HTTP Server Timeout (503) response. Defaults to 0 (no limit). */ @@ -408,7 +408,7 @@ export interface IProxyHandlerConfig { maxSockets?: boolean | number; } /** TODO: fill in joi definition */ -export interface IJoi {} +export interface IJoi { } /** a validation function using the signature function(value, options, next) */ export interface IValidationFunction { @@ -514,7 +514,7 @@ export interface IRouteAdditionalConfigurationOptions { }; /** an alternative location for the route handler option. */ - handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** an optional unique identifier used to look up the route using server.lookup(). */ id?: number; /** optional arguments passed to JSON.stringify() when converting an object or error response to a string payload.Supports the following: */ @@ -764,14 +764,21 @@ export interface IServerRealm { /** server.state(name, [options]) http://hapijs.com/api#serverstatename-options HTTP state management uses client cookies to persist a state across multiple requests. Registers a cookie definitions where:*/ export interface IServerState { - /** - the cookie name string. */name: string; + /** - the cookie name string. */ + name: string; - /** - are the optional cookie settings: */options: { - /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ttl: number; - /** - sets the 'Secure' flag.Defaults to false.*/isSecure: boolean; - /** - sets the 'HttpOnly' flag.Defaults to false.*/isHttpOnly: boolean - /** - the path scope.Defaults to null (no path).*/path: any; - /** - the domain scope.Defaults to null (no domain). */domain: any; + /** - are the optional cookie settings: */ + options: { + /** - time - to - live in milliseconds.Defaults to null (session time- life - cookies are deleted when the browser is closed).*/ + ttl: number; + /** - sets the 'Secure' flag.Defaults to false.*/ + isSecure: boolean; + /** - sets the 'HttpOnly' flag.Defaults to false.*/ + isHttpOnly: boolean + /** - the path scope.Defaults to null (no path).*/ + path: any; + /** - the domain scope.Defaults to null (no domain). */ + domain: any; /** if present and the cookie was not received from the client or explicitly set by the route handler, the cookie is automatically added to the response with the provided value. The value can be a function with signature function(request, next) where: request - the request object. next - the continuation function using the function(err, value) signature.*/ @@ -783,16 +790,25 @@ export interface IServerState { 'form' - object value is encoded using the x-www-form-urlencoded method. 'iron' - Encrypts and sign the value using iron.*/ encoding: string; - /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/sign: { - /** - algorithm options.Defaults to require('iron').defaults.integrity.*/integrity: any; - /** - password used for HMAC key generation.*/password: string; + /** - an object used to calculate an HMAC for cookie integrity validation.This does not provide privacy, only a mean to verify that the cookie value was generated by the server.Redundant when 'iron' encoding is used.Options are:*/ + sign: { + /** - algorithm options.Defaults to require('iron').defaults.integrity.*/ + integrity: any; + /** - password used for HMAC key generation.*/ + password: string; }; - /** - password used for 'iron' encoding.*/password: string; - /** - options for 'iron' encoding.Defaults to require('iron').defaults.*/iron: any; - /** - if false, errors are ignored and treated as missing cookies.*/ignoreErrors: boolean; - /** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/clearInvalid: boolean; - /** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/strictHeader: boolean; - /** - overrides the default proxy localStatePassThrough setting.*/passThrough: any; + /** - password used for 'iron' encoding.*/ + password: string; + /** - options for 'iron' encoding.Defaults to require('iron').defaults.*/ + iron: any; + /** - if false, errors are ignored and treated as missing cookies.*/ + ignoreErrors: boolean; + /** - if true, automatically instruct the client to remove invalid cookies.Defaults to false.*/ + clearInvalid: boolean; + /** - if false, allows any cookie value including values in violation of RFC 6265. Defaults to true.*/ + strictHeader: boolean; + /** - overrides the default proxy localStatePassThrough setting.*/ + passThrough: any; }; } @@ -915,7 +931,7 @@ export interface IRouteConfiguration { /** - an optional domain string or an array of domain strings for limiting the route to only requests with a matching host header field.Matching is done against the hostname part of the header only (excluding the port).Defaults to all hosts.*/ vhost?: string; /** - (required) the function called to generate the response after successful authentication and validation.The handler function is described in Route handler.If set to a string, the value is parsed the same way a prerequisite server method string shortcut is processed.Alternatively, handler can be assigned an object with a single key using the name of a registered handler type and value with the options passed to the registered handler.*/ - handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; + handler?: ISessionHandler | IStrictSessionHandler | string | IRouteHandlerConfig; /** - additional route options.*/ config?: IRouteAdditionalConfigurationOptions; } @@ -1122,7 +1138,7 @@ export interface IServerMethod { generateKey - a function used to generate a unique key (for caching) from the arguments passed to the method function (the callback argument is not passed as input). The server will automatically generate a unique key if the function's arguments are all of types 'string', 'number', or 'boolean'. However if the method uses other types of arguments, a key generation function must be provided which takes the same arguments as the function and returns a unique string (or null if no key can be generated).*/ export interface IServerMethodOptions { bind?: any; - cache?: ICatBoxCachePolicyOptions; + cache?: ICatBoxCachePolicyOptions; callback?: boolean; generateKey?(args: any[]): string; } @@ -1891,9 +1907,9 @@ export class Server extends Events.EventEmitter { * } * }); */ - strategy(name: string, scheme: string, mode?: boolean | string, options?: any): void; - strategy(name: string, scheme: string, mode?: boolean | string): void; - strategy(name: string, scheme: string, options?: any): void; + strategy(name: string, scheme: string, mode?: boolean | string, options?: any): void; + strategy(name: string, scheme: string, mode?: boolean | string): void; + strategy(name: string, scheme: string, options?: any): void; /** server.auth.test(strategy, request, next) Tests a request against an authentication strategy where: @@ -1959,7 +1975,7 @@ export class Server extends Events.EventEmitter { // value === { capital: 'oslo' }; }); });*/ - cache(options: ICatBoxCachePolicyOptions): void; + cache(options: ICatBoxCachePolicyOptions): void; /** server.connection([options]) Adds an incoming server connection @@ -2295,7 +2311,7 @@ export class Server extends Events.EventEmitter { register( plugins: any | any[], options: { - select: string | string[]; + select?: string | string[]; routes: { prefix: string; vhost?: string | string[] }; @@ -2304,7 +2320,7 @@ export class Server extends Events.EventEmitter { register( plugins: any | any[], options: { - select: string | string[]; + select?: string | string[]; routes: { prefix: string; vhost?: string | string[] }; diff --git a/types/i18next/i18next-tests.ts b/types/i18next/i18next-tests.ts index 744fd950d4..2d3f6d3b04 100644 --- a/types/i18next/i18next-tests.ts +++ b/types/i18next/i18next-tests.ts @@ -59,6 +59,18 @@ i18n.init({ wait: false }); +i18n.init({ + fallbackLng: ['en', 'ru'], +}); + +i18n.init({ + fallbackLng: { + 'de-CH': ['fr', 'it'], + 'zh-HANT': ['zh-HANS', 'en'], + 'default': ['en'] + }, +}); + i18n.t('helloWorld', { defaultValue: 'default', count: 10 @@ -70,6 +82,22 @@ i18n.t('helloWorldInterpolated', { name: "world" }); +i18n.t('helloSingleFallbackLng', { + fallbackLng: 'en' +}); + +i18n.t('helloMultiFallbackLng', { + fallbackLng: ['en', 'ru'] +}); + +i18n.t('helloObjectFallbackLng', { + fallbackLng: { + 'de-CH': ['fr', 'it'], + 'zh-HANT': ['zh-HANS', 'en'], + 'default': ['en'] + }, +}); + i18n.exists("helloWorld"); const options:i18n.Options = i18n.options; diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index c0b0c82d81..1cacdeb7c3 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for i18next v2.3.4 +// Type definitions for i18next v2.3.5 // Project: http://i18next.com -// Definitions by: Michael Ledin +// Definitions by: Michael Ledin , Budi Irawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Sources: https://github.com/i18next/i18next/ @@ -19,6 +19,12 @@ declare namespace i18n { [key: string]: any; } + interface FallbackLngObjList { + [language: string]: string[] + } + + type FallbackLng = string | string[] | FallbackLngObjList; + interface InterpolationOptions { escapeValue?: boolean; prefix?: string; @@ -41,7 +47,7 @@ declare namespace i18n { replace?: any; lng?: string; lngs?: string[]; - fallbackLng?: string; + fallbackLng?: FallbackLng; ns?: string | string[]; keySeparator?: string; nsSeparator?: string; @@ -57,7 +63,7 @@ declare namespace i18n { debug?: boolean; resources?: ResourceStore; lng?: string; - fallbackLng?: string; + fallbackLng?: FallbackLng; ns?: string | string[]; defaultNS?: string; fallbackNS?: string | string[]; diff --git a/types/jasmine-ajax/index.d.ts b/types/jasmine-ajax/index.d.ts index 4762ba085a..dcc6720f04 100644 --- a/types/jasmine-ajax/index.d.ts +++ b/types/jasmine-ajax/index.d.ts @@ -27,13 +27,13 @@ interface JasmineAjaxRequest extends XMLHttpRequest { } interface JasmineAjaxRequestTracker { - track(request: JasmineAjaxRequest): void; - first(): JasmineAjaxRequest; - count(): number; - reset(): void; - mostRecent(): JasmineAjaxRequest; - at(index: number): JasmineAjaxRequest; - filter(urlToMatch: RegExp): JasmineAjaxRequest[]; + track(request: JasmineAjaxRequest): void; + first(): JasmineAjaxRequest; + count(): number; + reset(): void; + mostRecent(): JasmineAjaxRequest; + at(index: number): JasmineAjaxRequest; + filter(urlToMatch: RegExp): JasmineAjaxRequest[]; filter(urlToMatch: Function): JasmineAjaxRequest[]; filter(urlToMatch: string): JasmineAjaxRequest[]; } @@ -48,14 +48,14 @@ interface JasmineAjaxRequestStubReturnOptions { interface JasmineAjaxRequestStub { data?: string; - method?: string; - andReturn(options: JasmineAjaxRequestStubReturnOptions): void; - matches(fullUrl: string, data: string, method: string): boolean; + method?: string; + andReturn(options: JasmineAjaxRequestStubReturnOptions): void; + matches(fullUrl: string, data: string, method: string): boolean; } interface JasmineAjaxStubTracker { - addStub(stub: JasmineAjaxRequestStub): void; - reset(): void; + addStub(stub: JasmineAjaxRequestStub): void; + reset(): void; findStub(url: string, data?: string, method?: string): JasmineAjaxRequestStub; } diff --git a/types/jasmine-ajax/jasmine-ajax-tests.ts b/types/jasmine-ajax/jasmine-ajax-tests.ts index b2c963c6c1..fabd525012 100644 --- a/types/jasmine-ajax/jasmine-ajax-tests.ts +++ b/types/jasmine-ajax/jasmine-ajax-tests.ts @@ -1779,7 +1779,7 @@ describe("mockAjax", () => { mockAjax.install(); - mockAjax.requests.track( { url: '/testurl' }); + // mockAjax.requests.track( { url: '/testurl' }); mockAjax.stubRequest('/bobcat'); expect(mockAjax.requests.count()).toEqual(1); diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 595a42ea2b..36011e67a7 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -291,6 +291,7 @@ declare function pending(reason?: string): void; /** Fails a test when called within one. */ declare function fail(error?: any): void; declare namespace jasmine { + var DEFAULT_TIMEOUT_INTERVAL: number; var clock: () => Clock; function any(aclass: any): Any; function anything(): Any; diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index b1696bb7ad..dbf134e541 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -167,6 +167,14 @@ export interface Reference extends Schema { } export interface AnySchema> { + /** + * Validates a value using the schema and options. + */ + validate(value: T): ValidationResult; + validate(value: T, options: ValidationOptions): ValidationResult; + validate(value: T, callback: (err: ValidationError, value: T) => R): R; + validate(value: T, options: ValidationOptions, callback: (err: ValidationError, value: T) => R): R; + /** * Whitelists a value */ diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index a58623ea06..3cd2e28b73 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -50,87 +50,87 @@ var ref: Joi.Reference = null; var validOpts: Joi.ValidationOptions = null; -validOpts = {abortEarly: bool}; -validOpts = {convert: bool}; -validOpts = {allowUnknown: bool}; -validOpts = {skipFunctions: bool}; -validOpts = {stripUnknown: bool}; -validOpts = {stripUnknown: {arrays: bool}}; -validOpts = {stripUnknown: {objects: bool}}; -validOpts = {stripUnknown: {arrays: bool, objects: bool}}; -validOpts = {language: bool}; -validOpts = {presence: str}; -validOpts = {context: obj}; -validOpts = {noDefaults: bool}; +validOpts = { abortEarly: bool }; +validOpts = { convert: bool }; +validOpts = { allowUnknown: bool }; +validOpts = { skipFunctions: bool }; +validOpts = { stripUnknown: bool }; +validOpts = { stripUnknown: { arrays: bool } }; +validOpts = { stripUnknown: { objects: bool } }; +validOpts = { stripUnknown: { arrays: bool, objects: bool } }; +validOpts = { language: bool }; +validOpts = { presence: str }; +validOpts = { context: obj }; +validOpts = { noDefaults: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var renOpts: Joi.RenameOptions = null; -renOpts = {alias: bool}; -renOpts = {multiple: bool}; -renOpts = {override: bool}; -renOpts = {ignoreUndefined: bool}; +renOpts = { alias: bool }; +renOpts = { multiple: bool }; +renOpts = { override: bool }; +renOpts = { ignoreUndefined: bool }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var emailOpts: Joi.EmailOptions = null; -emailOpts = {errorLevel: num}; -emailOpts = {errorLevel: bool}; -emailOpts = {tldWhitelist: strArr}; -emailOpts = {tldWhitelist: obj}; -emailOpts = {minDomainAtoms: num}; +emailOpts = { errorLevel: num }; +emailOpts = { errorLevel: bool }; +emailOpts = { tldWhitelist: strArr }; +emailOpts = { tldWhitelist: obj }; +emailOpts = { minDomainAtoms: num }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var ipOpts: Joi.IpOptions = null; -ipOpts = {version: str}; -ipOpts = {version: strArr}; -ipOpts = {cidr: str}; +ipOpts = { version: str }; +ipOpts = { version: strArr }; +ipOpts = { cidr: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var uriOpts: Joi.UriOptions = null; -uriOpts = {scheme: str}; -uriOpts = {scheme: exp}; -uriOpts = {scheme: strArr}; -uriOpts = {scheme: expArr}; +uriOpts = { scheme: str }; +uriOpts = { scheme: exp }; +uriOpts = { scheme: strArr }; +uriOpts = { scheme: expArr }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var whenOpts: Joi.WhenOptions = null; -whenOpts = {is: x}; -whenOpts = {is: schema, then: schema}; -whenOpts = {is: schema, otherwise: schema}; +whenOpts = { is: x }; +whenOpts = { is: schema, then: schema }; +whenOpts = { is: schema, otherwise: schema }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var refOpts: Joi.ReferenceOptions = null; -refOpts = {separator: str}; -refOpts = {contextPrefix: str}; +refOpts = { separator: str }; +refOpts = { contextPrefix: str }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- var validErr: Joi.ValidationError = null; var validErrItem: Joi.ValidationErrorItem; -validErrItem= { - message: str, - type: str, - path: str +validErrItem = { + message: str, + type: str, + path: str }; validErrItem = { - message: str, - type: str, - path: str, - options: validOpts, - context: obj + message: str, + type: str, + path: str, + options: validOpts, + context: obj }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -162,23 +162,23 @@ anySchema = objSchema; var schemaMap: Joi.SchemaMap = null; schemaMap = { - a: numSchema, - b: strSchema + a: numSchema, + b: strSchema }; schemaMap = { - a: numSchema, - b: { - b1: strSchema, - b2: anySchema - } + a: numSchema, + b: { + b1: strSchema, + b2: anySchema + } }; schemaMap = { - a: numSchema, - b: [ - { b1: strSchema }, - { b2: anySchema } - ], - c: arrSchema + a: numSchema, + b: [ + { b1: strSchema }, + { b2: anySchema } + ], + c: arrSchema }; // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -186,63 +186,63 @@ schemaMap = { anySchema = Joi.any(); namespace common { - anySchema = anySchema.allow(x); - anySchema = anySchema.allow(x, x); - anySchema = anySchema.allow([x, x, x]); - anySchema = anySchema.valid(x); - anySchema = anySchema.valid(x, x); - anySchema = anySchema.valid([x, x, x]); - anySchema = anySchema.only(x); - anySchema = anySchema.only(x, x); - anySchema = anySchema.only([x, x, x]); - anySchema = anySchema.equal(x); - anySchema = anySchema.equal(x, x); - anySchema = anySchema.equal([x, x, x]); - anySchema = anySchema.invalid(x); - anySchema = anySchema.invalid(x, x); - anySchema = anySchema.invalid([x, x, x]); - anySchema = anySchema.disallow(x); - anySchema = anySchema.disallow(x, x); - anySchema = anySchema.disallow([x, x, x]); - anySchema = anySchema.not(x); - anySchema = anySchema.not(x, x); - anySchema = anySchema.not([x, x, x]); + anySchema = anySchema.allow(x); + anySchema = anySchema.allow(x, x); + anySchema = anySchema.allow([x, x, x]); + anySchema = anySchema.valid(x); + anySchema = anySchema.valid(x, x); + anySchema = anySchema.valid([x, x, x]); + anySchema = anySchema.only(x); + anySchema = anySchema.only(x, x); + anySchema = anySchema.only([x, x, x]); + anySchema = anySchema.equal(x); + anySchema = anySchema.equal(x, x); + anySchema = anySchema.equal([x, x, x]); + anySchema = anySchema.invalid(x); + anySchema = anySchema.invalid(x, x); + anySchema = anySchema.invalid([x, x, x]); + anySchema = anySchema.disallow(x); + anySchema = anySchema.disallow(x, x); + anySchema = anySchema.disallow([x, x, x]); + anySchema = anySchema.not(x); + anySchema = anySchema.not(x, x); + anySchema = anySchema.not([x, x, x]); - anySchema = anySchema.default(); - anySchema = anySchema.default(x); - anySchema = anySchema.default(x, str); + anySchema = anySchema.default(); + anySchema = anySchema.default(x); + anySchema = anySchema.default(x, str); - anySchema = anySchema.required(); - anySchema = anySchema.optional(); - anySchema = anySchema.forbidden(); - anySchema = anySchema.strip(); + anySchema = anySchema.required(); + anySchema = anySchema.optional(); + anySchema = anySchema.forbidden(); + anySchema = anySchema.strip(); - anySchema = anySchema.description(str); - anySchema = anySchema.notes(str); - anySchema = anySchema.notes(strArr); - anySchema = anySchema.tags(str); - anySchema = anySchema.tags(strArr); + anySchema = anySchema.description(str); + anySchema = anySchema.notes(str); + anySchema = anySchema.notes(strArr); + anySchema = anySchema.tags(str); + anySchema = anySchema.tags(strArr); - anySchema = anySchema.meta(obj); - anySchema = anySchema.example(obj); - anySchema = anySchema.unit(str); + anySchema = anySchema.meta(obj); + anySchema = anySchema.example(obj); + anySchema = anySchema.unit(str); - anySchema = anySchema.options(validOpts); - anySchema = anySchema.strict(); - anySchema = anySchema.strict(bool); - anySchema = anySchema.concat(x); + anySchema = anySchema.options(validOpts); + anySchema = anySchema.strict(); + anySchema = anySchema.strict(bool); + anySchema = anySchema.concat(x); - altSchema = anySchema.when(str, whenOpts); - altSchema = anySchema.when(ref, whenOpts); + altSchema = anySchema.when(str, whenOpts); + altSchema = anySchema.when(ref, whenOpts); - anySchema = anySchema.label(str); - anySchema = anySchema.raw(); - anySchema = anySchema.raw(bool); - anySchema = anySchema.empty(); - anySchema = anySchema.empty(str); - anySchema = anySchema.empty(anySchema); + anySchema = anySchema.label(str); + anySchema = anySchema.raw(); + anySchema = anySchema.raw(bool); + anySchema = anySchema.empty(); + anySchema = anySchema.empty(str); + anySchema = anySchema.empty(anySchema); - anySchema = anySchema.error(err); + anySchema = anySchema.error(err); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -275,51 +275,51 @@ arrSchema = arrSchema.items([schemaMap, schemaMap]); // - - - - - - - - namespace common_copy_paste { - // use search & replace from any - arrSchema = arrSchema.allow(x); - arrSchema = arrSchema.allow(x, x); - arrSchema = arrSchema.allow([x, x, x]); - arrSchema = arrSchema.valid(x); - arrSchema = arrSchema.valid(x, x); - arrSchema = arrSchema.valid([x, x, x]); - arrSchema = arrSchema.only(x); - arrSchema = arrSchema.only(x, x); - arrSchema = arrSchema.only([x, x, x]); - arrSchema = arrSchema.equal(x); - arrSchema = arrSchema.equal(x, x); - arrSchema = arrSchema.equal([x, x, x]); - arrSchema = arrSchema.invalid(x); - arrSchema = arrSchema.invalid(x, x); - arrSchema = arrSchema.invalid([x, x, x]); - arrSchema = arrSchema.disallow(x); - arrSchema = arrSchema.disallow(x, x); - arrSchema = arrSchema.disallow([x, x, x]); - arrSchema = arrSchema.not(x); - arrSchema = arrSchema.not(x, x); - arrSchema = arrSchema.not([x, x, x]); + // use search & replace from any + arrSchema = arrSchema.allow(x); + arrSchema = arrSchema.allow(x, x); + arrSchema = arrSchema.allow([x, x, x]); + arrSchema = arrSchema.valid(x); + arrSchema = arrSchema.valid(x, x); + arrSchema = arrSchema.valid([x, x, x]); + arrSchema = arrSchema.only(x); + arrSchema = arrSchema.only(x, x); + arrSchema = arrSchema.only([x, x, x]); + arrSchema = arrSchema.equal(x); + arrSchema = arrSchema.equal(x, x); + arrSchema = arrSchema.equal([x, x, x]); + arrSchema = arrSchema.invalid(x); + arrSchema = arrSchema.invalid(x, x); + arrSchema = arrSchema.invalid([x, x, x]); + arrSchema = arrSchema.disallow(x); + arrSchema = arrSchema.disallow(x, x); + arrSchema = arrSchema.disallow([x, x, x]); + arrSchema = arrSchema.not(x); + arrSchema = arrSchema.not(x, x); + arrSchema = arrSchema.not([x, x, x]); - arrSchema = arrSchema.default(x); + arrSchema = arrSchema.default(x); - arrSchema = arrSchema.required(); - arrSchema = arrSchema.optional(); - arrSchema = arrSchema.forbidden(); + arrSchema = arrSchema.required(); + arrSchema = arrSchema.optional(); + arrSchema = arrSchema.forbidden(); - arrSchema = arrSchema.description(str); - arrSchema = arrSchema.notes(str); - arrSchema = arrSchema.notes(strArr); - arrSchema = arrSchema.tags(str); - arrSchema = arrSchema.tags(strArr); + arrSchema = arrSchema.description(str); + arrSchema = arrSchema.notes(str); + arrSchema = arrSchema.notes(strArr); + arrSchema = arrSchema.tags(str); + arrSchema = arrSchema.tags(strArr); - arrSchema = arrSchema.meta(obj); - arrSchema = arrSchema.example(obj); - arrSchema = arrSchema.unit(str); + arrSchema = arrSchema.meta(obj); + arrSchema = arrSchema.example(obj); + arrSchema = arrSchema.unit(str); - arrSchema = arrSchema.options(validOpts); - arrSchema = arrSchema.strict(); - arrSchema = arrSchema.concat(x); + arrSchema = arrSchema.options(validOpts); + arrSchema = arrSchema.strict(); + arrSchema = arrSchema.concat(x); - altSchema = arrSchema.when(str, whenOpts); - altSchema = arrSchema.when(ref, whenOpts); + altSchema = arrSchema.when(str, whenOpts); + altSchema = arrSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -328,68 +328,68 @@ boolSchema = Joi.bool(); boolSchema = Joi.boolean(); namespace common_copy_paste { - boolSchema = boolSchema.allow(x); - boolSchema = boolSchema.allow(x, x); - boolSchema = boolSchema.allow([x, x, x]); - boolSchema = boolSchema.valid(x); - boolSchema = boolSchema.valid(x, x); - boolSchema = boolSchema.valid([x, x, x]); - boolSchema = boolSchema.only(x); - boolSchema = boolSchema.only(x, x); - boolSchema = boolSchema.only([x, x, x]); - boolSchema = boolSchema.equal(x); - boolSchema = boolSchema.equal(x, x); - boolSchema = boolSchema.equal([x, x, x]); - boolSchema = boolSchema.invalid(x); - boolSchema = boolSchema.invalid(x, x); - boolSchema = boolSchema.invalid([x, x, x]); - boolSchema = boolSchema.disallow(x); - boolSchema = boolSchema.disallow(x, x); - boolSchema = boolSchema.disallow([x, x, x]); - boolSchema = boolSchema.not(x); - boolSchema = boolSchema.not(x, x); - boolSchema = boolSchema.not([x, x, x]); + boolSchema = boolSchema.allow(x); + boolSchema = boolSchema.allow(x, x); + boolSchema = boolSchema.allow([x, x, x]); + boolSchema = boolSchema.valid(x); + boolSchema = boolSchema.valid(x, x); + boolSchema = boolSchema.valid([x, x, x]); + boolSchema = boolSchema.only(x); + boolSchema = boolSchema.only(x, x); + boolSchema = boolSchema.only([x, x, x]); + boolSchema = boolSchema.equal(x); + boolSchema = boolSchema.equal(x, x); + boolSchema = boolSchema.equal([x, x, x]); + boolSchema = boolSchema.invalid(x); + boolSchema = boolSchema.invalid(x, x); + boolSchema = boolSchema.invalid([x, x, x]); + boolSchema = boolSchema.disallow(x); + boolSchema = boolSchema.disallow(x, x); + boolSchema = boolSchema.disallow([x, x, x]); + boolSchema = boolSchema.not(x); + boolSchema = boolSchema.not(x, x); + boolSchema = boolSchema.not([x, x, x]); - boolSchema = boolSchema.default(x); + boolSchema = boolSchema.default(x); - boolSchema = boolSchema.required(); - boolSchema = boolSchema.optional(); - boolSchema = boolSchema.forbidden(); + boolSchema = boolSchema.required(); + boolSchema = boolSchema.optional(); + boolSchema = boolSchema.forbidden(); - boolSchema = boolSchema.description(str); - boolSchema = boolSchema.notes(str); - boolSchema = boolSchema.notes(strArr); - boolSchema = boolSchema.tags(str); - boolSchema = boolSchema.tags(strArr); + boolSchema = boolSchema.description(str); + boolSchema = boolSchema.notes(str); + boolSchema = boolSchema.notes(strArr); + boolSchema = boolSchema.tags(str); + boolSchema = boolSchema.tags(strArr); - boolSchema = boolSchema.meta(obj); - boolSchema = boolSchema.example(obj); - boolSchema = boolSchema.unit(str); + boolSchema = boolSchema.meta(obj); + boolSchema = boolSchema.example(obj); + boolSchema = boolSchema.unit(str); - boolSchema = boolSchema.options(validOpts); - boolSchema = boolSchema.strict(); - boolSchema = boolSchema.concat(x); + boolSchema = boolSchema.options(validOpts); + boolSchema = boolSchema.strict(); + boolSchema = boolSchema.concat(x); - boolSchema = boolSchema.truthy(str); - boolSchema = boolSchema.truthy(num); - boolSchema = boolSchema.truthy(strArr); - boolSchema = boolSchema.truthy(numArr); - boolSchema = boolSchema.truthy(str, str); - boolSchema = boolSchema.truthy(strArr, str); - boolSchema = boolSchema.truthy(str, strArr); - boolSchema = boolSchema.truthy(strArr, strArr); - boolSchema = boolSchema.falsy(str); - boolSchema = boolSchema.falsy(num); - boolSchema = boolSchema.falsy(strArr); - boolSchema = boolSchema.falsy(numArr); - boolSchema = boolSchema.falsy(str, str); - boolSchema = boolSchema.falsy(strArr, str); - boolSchema = boolSchema.falsy(str, strArr); - boolSchema = boolSchema.falsy(strArr, strArr); - boolSchema = boolSchema.insensitive(bool); + boolSchema = boolSchema.truthy(str); + boolSchema = boolSchema.truthy(num); + boolSchema = boolSchema.truthy(strArr); + boolSchema = boolSchema.truthy(numArr); + boolSchema = boolSchema.truthy(str, str); + boolSchema = boolSchema.truthy(strArr, str); + boolSchema = boolSchema.truthy(str, strArr); + boolSchema = boolSchema.truthy(strArr, strArr); + boolSchema = boolSchema.falsy(str); + boolSchema = boolSchema.falsy(num); + boolSchema = boolSchema.falsy(strArr); + boolSchema = boolSchema.falsy(numArr); + boolSchema = boolSchema.falsy(str, str); + boolSchema = boolSchema.falsy(strArr, str); + boolSchema = boolSchema.falsy(str, strArr); + boolSchema = boolSchema.falsy(strArr, strArr); + boolSchema = boolSchema.insensitive(bool); - altSchema = boolSchema.when(str, whenOpts); - altSchema = boolSchema.when(ref, whenOpts); + altSchema = boolSchema.when(str, whenOpts); + altSchema = boolSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -402,50 +402,50 @@ binSchema = binSchema.max(num); binSchema = binSchema.length(num); namespace common { - binSchema = binSchema.allow(x); - binSchema = binSchema.allow(x, x); - binSchema = binSchema.allow([x, x, x]); - binSchema = binSchema.valid(x); - binSchema = binSchema.valid(x, x); - binSchema = binSchema.valid([x, x, x]); - binSchema = binSchema.only(x); - binSchema = binSchema.only(x, x); - binSchema = binSchema.only([x, x, x]); - binSchema = binSchema.equal(x); - binSchema = binSchema.equal(x, x); - binSchema = binSchema.equal([x, x, x]); - binSchema = binSchema.invalid(x); - binSchema = binSchema.invalid(x, x); - binSchema = binSchema.invalid([x, x, x]); - binSchema = binSchema.disallow(x); - binSchema = binSchema.disallow(x, x); - binSchema = binSchema.disallow([x, x, x]); - binSchema = binSchema.not(x); - binSchema = binSchema.not(x, x); - binSchema = binSchema.not([x, x, x]); + binSchema = binSchema.allow(x); + binSchema = binSchema.allow(x, x); + binSchema = binSchema.allow([x, x, x]); + binSchema = binSchema.valid(x); + binSchema = binSchema.valid(x, x); + binSchema = binSchema.valid([x, x, x]); + binSchema = binSchema.only(x); + binSchema = binSchema.only(x, x); + binSchema = binSchema.only([x, x, x]); + binSchema = binSchema.equal(x); + binSchema = binSchema.equal(x, x); + binSchema = binSchema.equal([x, x, x]); + binSchema = binSchema.invalid(x); + binSchema = binSchema.invalid(x, x); + binSchema = binSchema.invalid([x, x, x]); + binSchema = binSchema.disallow(x); + binSchema = binSchema.disallow(x, x); + binSchema = binSchema.disallow([x, x, x]); + binSchema = binSchema.not(x); + binSchema = binSchema.not(x, x); + binSchema = binSchema.not([x, x, x]); - binSchema = binSchema.default(x); + binSchema = binSchema.default(x); - binSchema = binSchema.required(); - binSchema = binSchema.optional(); - binSchema = binSchema.forbidden(); + binSchema = binSchema.required(); + binSchema = binSchema.optional(); + binSchema = binSchema.forbidden(); - binSchema = binSchema.description(str); - binSchema = binSchema.notes(str); - binSchema = binSchema.notes(strArr); - binSchema = binSchema.tags(str); - binSchema = binSchema.tags(strArr); + binSchema = binSchema.description(str); + binSchema = binSchema.notes(str); + binSchema = binSchema.notes(strArr); + binSchema = binSchema.tags(str); + binSchema = binSchema.tags(strArr); - binSchema = binSchema.meta(obj); - binSchema = binSchema.example(obj); - binSchema = binSchema.unit(str); + binSchema = binSchema.meta(obj); + binSchema = binSchema.example(obj); + binSchema = binSchema.unit(str); - binSchema = binSchema.options(validOpts); - binSchema = binSchema.strict(); - binSchema = binSchema.concat(x); + binSchema = binSchema.options(validOpts); + binSchema = binSchema.strict(); + binSchema = binSchema.concat(x); - altSchema = binSchema.when(str, whenOpts); - altSchema = binSchema.when(ref, whenOpts); + altSchema = binSchema.when(str, whenOpts); + altSchema = binSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -474,50 +474,50 @@ dateSchema = dateSchema.timestamp('javascript'); dateSchema = dateSchema.timestamp('unix'); namespace common { - dateSchema = dateSchema.allow(x); - dateSchema = dateSchema.allow(x, x); - dateSchema = dateSchema.allow([x, x, x]); - dateSchema = dateSchema.valid(x); - dateSchema = dateSchema.valid(x, x); - dateSchema = dateSchema.valid([x, x, x]); - dateSchema = dateSchema.only(x); - dateSchema = dateSchema.only(x, x); - dateSchema = dateSchema.only([x, x, x]); - dateSchema = dateSchema.equal(x); - dateSchema = dateSchema.equal(x, x); - dateSchema = dateSchema.equal([x, x, x]); - dateSchema = dateSchema.invalid(x); - dateSchema = dateSchema.invalid(x, x); - dateSchema = dateSchema.invalid([x, x, x]); - dateSchema = dateSchema.disallow(x); - dateSchema = dateSchema.disallow(x, x); - dateSchema = dateSchema.disallow([x, x, x]); - dateSchema = dateSchema.not(x); - dateSchema = dateSchema.not(x, x); - dateSchema = dateSchema.not([x, x, x]); + dateSchema = dateSchema.allow(x); + dateSchema = dateSchema.allow(x, x); + dateSchema = dateSchema.allow([x, x, x]); + dateSchema = dateSchema.valid(x); + dateSchema = dateSchema.valid(x, x); + dateSchema = dateSchema.valid([x, x, x]); + dateSchema = dateSchema.only(x); + dateSchema = dateSchema.only(x, x); + dateSchema = dateSchema.only([x, x, x]); + dateSchema = dateSchema.equal(x); + dateSchema = dateSchema.equal(x, x); + dateSchema = dateSchema.equal([x, x, x]); + dateSchema = dateSchema.invalid(x); + dateSchema = dateSchema.invalid(x, x); + dateSchema = dateSchema.invalid([x, x, x]); + dateSchema = dateSchema.disallow(x); + dateSchema = dateSchema.disallow(x, x); + dateSchema = dateSchema.disallow([x, x, x]); + dateSchema = dateSchema.not(x); + dateSchema = dateSchema.not(x, x); + dateSchema = dateSchema.not([x, x, x]); - dateSchema = dateSchema.default(x); + dateSchema = dateSchema.default(x); - dateSchema = dateSchema.required(); - dateSchema = dateSchema.optional(); - dateSchema = dateSchema.forbidden(); + dateSchema = dateSchema.required(); + dateSchema = dateSchema.optional(); + dateSchema = dateSchema.forbidden(); - dateSchema = dateSchema.description(str); - dateSchema = dateSchema.notes(str); - dateSchema = dateSchema.notes(strArr); - dateSchema = dateSchema.tags(str); - dateSchema = dateSchema.tags(strArr); + dateSchema = dateSchema.description(str); + dateSchema = dateSchema.notes(str); + dateSchema = dateSchema.notes(strArr); + dateSchema = dateSchema.tags(str); + dateSchema = dateSchema.tags(strArr); - dateSchema = dateSchema.meta(obj); - dateSchema = dateSchema.example(obj); - dateSchema = dateSchema.unit(str); + dateSchema = dateSchema.meta(obj); + dateSchema = dateSchema.example(obj); + dateSchema = dateSchema.unit(str); - dateSchema = dateSchema.options(validOpts); - dateSchema = dateSchema.strict(); - dateSchema = dateSchema.concat(x); + dateSchema = dateSchema.options(validOpts); + dateSchema = dateSchema.strict(); + dateSchema = dateSchema.concat(x); - altSchema = dateSchema.when(str, whenOpts); - altSchema = dateSchema.when(ref, whenOpts); + altSchema = dateSchema.when(str, whenOpts); + altSchema = dateSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -548,50 +548,50 @@ numSchema = numSchema.positive(); numSchema = numSchema.negative(); namespace common { - numSchema = numSchema.allow(x); - numSchema = numSchema.allow(x, x); - numSchema = numSchema.allow([x, x, x]); - numSchema = numSchema.valid(x); - numSchema = numSchema.valid(x, x); - numSchema = numSchema.valid([x, x, x]); - numSchema = numSchema.only(x); - numSchema = numSchema.only(x, x); - numSchema = numSchema.only([x, x, x]); - numSchema = numSchema.equal(x); - numSchema = numSchema.equal(x, x); - numSchema = numSchema.equal([x, x, x]); - numSchema = numSchema.invalid(x); - numSchema = numSchema.invalid(x, x); - numSchema = numSchema.invalid([x, x, x]); - numSchema = numSchema.disallow(x); - numSchema = numSchema.disallow(x, x); - numSchema = numSchema.disallow([x, x, x]); - numSchema = numSchema.not(x); - numSchema = numSchema.not(x, x); - numSchema = numSchema.not([x, x, x]); + numSchema = numSchema.allow(x); + numSchema = numSchema.allow(x, x); + numSchema = numSchema.allow([x, x, x]); + numSchema = numSchema.valid(x); + numSchema = numSchema.valid(x, x); + numSchema = numSchema.valid([x, x, x]); + numSchema = numSchema.only(x); + numSchema = numSchema.only(x, x); + numSchema = numSchema.only([x, x, x]); + numSchema = numSchema.equal(x); + numSchema = numSchema.equal(x, x); + numSchema = numSchema.equal([x, x, x]); + numSchema = numSchema.invalid(x); + numSchema = numSchema.invalid(x, x); + numSchema = numSchema.invalid([x, x, x]); + numSchema = numSchema.disallow(x); + numSchema = numSchema.disallow(x, x); + numSchema = numSchema.disallow([x, x, x]); + numSchema = numSchema.not(x); + numSchema = numSchema.not(x, x); + numSchema = numSchema.not([x, x, x]); - numSchema = numSchema.default(x); + numSchema = numSchema.default(x); - numSchema = numSchema.required(); - numSchema = numSchema.optional(); - numSchema = numSchema.forbidden(); + numSchema = numSchema.required(); + numSchema = numSchema.optional(); + numSchema = numSchema.forbidden(); - numSchema = numSchema.description(str); - numSchema = numSchema.notes(str); - numSchema = numSchema.notes(strArr); - numSchema = numSchema.tags(str); - numSchema = numSchema.tags(strArr); + numSchema = numSchema.description(str); + numSchema = numSchema.notes(str); + numSchema = numSchema.notes(strArr); + numSchema = numSchema.tags(str); + numSchema = numSchema.tags(strArr); - numSchema = numSchema.meta(obj); - numSchema = numSchema.example(obj); - numSchema = numSchema.unit(str); + numSchema = numSchema.meta(obj); + numSchema = numSchema.example(obj); + numSchema = numSchema.unit(str); - numSchema = numSchema.options(validOpts); - numSchema = numSchema.strict(); - numSchema = numSchema.concat(x); + numSchema = numSchema.options(validOpts); + numSchema = numSchema.strict(); + numSchema = numSchema.concat(x); - altSchema = numSchema.when(str, whenOpts); - altSchema = numSchema.when(ref, whenOpts); + altSchema = numSchema.when(str, whenOpts); + altSchema = numSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -657,50 +657,50 @@ objSchema = objSchema.optionalKeys(str, str); objSchema = objSchema.optionalKeys(strArr); namespace common { - objSchema = objSchema.allow(x); - objSchema = objSchema.allow(x, x); - objSchema = objSchema.allow([x, x, x]); - objSchema = objSchema.valid(x); - objSchema = objSchema.valid(x, x); - objSchema = objSchema.valid([x, x, x]); - objSchema = objSchema.only(x); - objSchema = objSchema.only(x, x); - objSchema = objSchema.only([x, x, x]); - objSchema = objSchema.equal(x); - objSchema = objSchema.equal(x, x); - objSchema = objSchema.equal([x, x, x]); - objSchema = objSchema.invalid(x); - objSchema = objSchema.invalid(x, x); - objSchema = objSchema.invalid([x, x, x]); - objSchema = objSchema.disallow(x); - objSchema = objSchema.disallow(x, x); - objSchema = objSchema.disallow([x, x, x]); - objSchema = objSchema.not(x); - objSchema = objSchema.not(x, x); - objSchema = objSchema.not([x, x, x]); + objSchema = objSchema.allow(x); + objSchema = objSchema.allow(x, x); + objSchema = objSchema.allow([x, x, x]); + objSchema = objSchema.valid(x); + objSchema = objSchema.valid(x, x); + objSchema = objSchema.valid([x, x, x]); + objSchema = objSchema.only(x); + objSchema = objSchema.only(x, x); + objSchema = objSchema.only([x, x, x]); + objSchema = objSchema.equal(x); + objSchema = objSchema.equal(x, x); + objSchema = objSchema.equal([x, x, x]); + objSchema = objSchema.invalid(x); + objSchema = objSchema.invalid(x, x); + objSchema = objSchema.invalid([x, x, x]); + objSchema = objSchema.disallow(x); + objSchema = objSchema.disallow(x, x); + objSchema = objSchema.disallow([x, x, x]); + objSchema = objSchema.not(x); + objSchema = objSchema.not(x, x); + objSchema = objSchema.not([x, x, x]); - objSchema = objSchema.default(x); + objSchema = objSchema.default(x); - objSchema = objSchema.required(); - objSchema = objSchema.optional(); - objSchema = objSchema.forbidden(); + objSchema = objSchema.required(); + objSchema = objSchema.optional(); + objSchema = objSchema.forbidden(); - objSchema = objSchema.description(str); - objSchema = objSchema.notes(str); - objSchema = objSchema.notes(strArr); - objSchema = objSchema.tags(str); - objSchema = objSchema.tags(strArr); + objSchema = objSchema.description(str); + objSchema = objSchema.notes(str); + objSchema = objSchema.notes(strArr); + objSchema = objSchema.tags(str); + objSchema = objSchema.tags(strArr); - objSchema = objSchema.meta(obj); - objSchema = objSchema.example(obj); - objSchema = objSchema.unit(str); + objSchema = objSchema.meta(obj); + objSchema = objSchema.example(obj); + objSchema = objSchema.unit(str); - objSchema = objSchema.options(validOpts); - objSchema = objSchema.strict(); - objSchema = objSchema.concat(x); + objSchema = objSchema.options(validOpts); + objSchema = objSchema.strict(); + objSchema = objSchema.concat(x); - altSchema = objSchema.when(str, whenOpts); - altSchema = objSchema.when(ref, whenOpts); + altSchema = objSchema.when(str, whenOpts); + altSchema = objSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -734,8 +734,8 @@ strSchema = strSchema.ip(ipOpts); strSchema = strSchema.uri(); strSchema = strSchema.uri(uriOpts); strSchema = strSchema.guid(); -strSchema = strSchema.guid({version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5']}); -strSchema = strSchema.guid({version: 'uuidv4'}); +strSchema = strSchema.guid({ version: ['uuidv1', 'uuidv2', 'uuidv3', 'uuidv4', 'uuidv5'] }); +strSchema = strSchema.guid({ version: 'uuidv4' }); strSchema = strSchema.hex(); strSchema = strSchema.hostname(); strSchema = strSchema.isoDate(); @@ -744,50 +744,50 @@ strSchema = strSchema.uppercase(); strSchema = strSchema.trim(); namespace common { - strSchema = strSchema.allow(x); - strSchema = strSchema.allow(x, x); - strSchema = strSchema.allow([x, x, x]); - strSchema = strSchema.valid(x); - strSchema = strSchema.valid(x, x); - strSchema = strSchema.valid([x, x, x]); - strSchema = strSchema.only(x); - strSchema = strSchema.only(x, x); - strSchema = strSchema.only([x, x, x]); - strSchema = strSchema.equal(x); - strSchema = strSchema.equal(x, x); - strSchema = strSchema.equal([x, x, x]); - strSchema = strSchema.invalid(x); - strSchema = strSchema.invalid(x, x); - strSchema = strSchema.invalid([x, x, x]); - strSchema = strSchema.disallow(x); - strSchema = strSchema.disallow(x, x); - strSchema = strSchema.disallow([x, x, x]); - strSchema = strSchema.not(x); - strSchema = strSchema.not(x, x); - strSchema = strSchema.not([x, x, x]); + strSchema = strSchema.allow(x); + strSchema = strSchema.allow(x, x); + strSchema = strSchema.allow([x, x, x]); + strSchema = strSchema.valid(x); + strSchema = strSchema.valid(x, x); + strSchema = strSchema.valid([x, x, x]); + strSchema = strSchema.only(x); + strSchema = strSchema.only(x, x); + strSchema = strSchema.only([x, x, x]); + strSchema = strSchema.equal(x); + strSchema = strSchema.equal(x, x); + strSchema = strSchema.equal([x, x, x]); + strSchema = strSchema.invalid(x); + strSchema = strSchema.invalid(x, x); + strSchema = strSchema.invalid([x, x, x]); + strSchema = strSchema.disallow(x); + strSchema = strSchema.disallow(x, x); + strSchema = strSchema.disallow([x, x, x]); + strSchema = strSchema.not(x); + strSchema = strSchema.not(x, x); + strSchema = strSchema.not([x, x, x]); - strSchema = strSchema.default(x); + strSchema = strSchema.default(x); - strSchema = strSchema.required(); - strSchema = strSchema.optional(); - strSchema = strSchema.forbidden(); + strSchema = strSchema.required(); + strSchema = strSchema.optional(); + strSchema = strSchema.forbidden(); - strSchema = strSchema.description(str); - strSchema = strSchema.notes(str); - strSchema = strSchema.notes(strArr); - strSchema = strSchema.tags(str); - strSchema = strSchema.tags(strArr); + strSchema = strSchema.description(str); + strSchema = strSchema.notes(str); + strSchema = strSchema.notes(strArr); + strSchema = strSchema.tags(str); + strSchema = strSchema.tags(strArr); - strSchema = strSchema.meta(obj); - strSchema = strSchema.example(obj); - strSchema = strSchema.unit(str); + strSchema = strSchema.meta(obj); + strSchema = strSchema.example(obj); + strSchema = strSchema.unit(str); - strSchema = strSchema.options(validOpts); - strSchema = strSchema.strict(); - strSchema = strSchema.concat(x); + strSchema = strSchema.options(validOpts); + strSchema = strSchema.strict(); + strSchema = strSchema.concat(x); - altSchema = strSchema.when(str, whenOpts); - altSchema = strSchema.when(ref, whenOpts); + altSchema = strSchema.when(str, whenOpts); + altSchema = strSchema.when(ref, whenOpts); } // --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- @@ -811,22 +811,22 @@ namespace validate_tests { Joi.validate(value, schema); Joi.validate(value, schema, validOpts); Joi.validate(value, schema, validOpts, (err, value) => { - x = value; - str = err.message; - str = err.details[0].path; - str = err.details[0].message; - str = err.details[0].type; + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; }); Joi.validate(value, schema, (err, value) => { - x = value; - str = err.message; - str = err.details[0].path; - str = err.details[0].message; - str = err.details[0].type; + x = value; + str = err.message; + str = err.details[0].path; + str = err.details[0].message; + str = err.details[0].type; }); // variant Joi.validate(num, schema, validOpts, (err, value) => { - num = value; + num = value; }); // plain opts @@ -853,6 +853,11 @@ namespace validate_tests { returnValue = Joi.validate(value, obj, validOpts); value = Joi.validate(value, obj, validOpts, (err, value) => value); value = Joi.validate(value, schema, validOpts, (err, value) => value); + + returnValue = schema.validate(value); + returnValue = schema.validate(value, validOpts); + value = schema.validate(value, (err, value) => value); + value = schema.validate(value, validOpts, (err, value) => value); } } diff --git a/types/jquery.growl/index.d.ts b/types/jquery.growl/index.d.ts new file mode 100644 index 0000000000..2a847b8ef7 --- /dev/null +++ b/types/jquery.growl/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for jquery.growl 1.3 +// Project: https://github.com/ksylvest/jquery-growl#readme +// Definitions by: Amir.h Yeganemehr +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace growl { + interface Options { + // Message + message: string; + // Title + title?: string; + // URL + url?: string; + // while hovering over the alert, prevent it from being dismissed (true | false - default: true) + delayOnHover?: boolean; + // the duration (in milliseconds) for which the alert is displayed (default: 3200) + duration?: number; + // whether the alert should be fixed rather than auto- dismissed(true | false - default: false) + fixed?: boolean; + // the alert's position ('tl' | 'tr' | 'bl' | 'br' | 'tc' | 'bc' - default: 'tr') + location?: string; + // the alert's size ('small' | 'medium' | 'large' - default: 'medium') + size?: string; + // the alert's style ('default' | 'error' | 'notice' | 'warning' - default: 'default') + style?: string; + } +} + +interface growl { + (options: growl.Options): void; + error(options: growl.Options): void; + notice(options: growl.Options): void; + warning(options: growl.Options): void; +} + +interface JQueryStatic { + growl: growl; +} diff --git a/types/jquery.growl/jquery.growl-tests.ts b/types/jquery.growl/jquery.growl-tests.ts new file mode 100644 index 0000000000..3391441bf1 --- /dev/null +++ b/types/jquery.growl/jquery.growl-tests.ts @@ -0,0 +1,4 @@ +$.growl({ title: "Growl", message: "The kitten is awake!" }); +$.growl.error({ message: "The kitten is attacking!" }); +$.growl.notice({ message: "The kitten is cute!" }); +$.growl.warning({ message: "The kitten is ugly!" }); diff --git a/types/jquery.growl/tsconfig.json b/types/jquery.growl/tsconfig.json new file mode 100644 index 0000000000..8eb3a19e35 --- /dev/null +++ b/types/jquery.growl/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jquery.growl-tests.ts" + ] +} diff --git a/types/jquery.growl/tslint.json b/types/jquery.growl/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jquery.growl/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery.validation/index.d.ts b/types/jquery.validation/index.d.ts index 9b77a80e23..5e0e2cfa01 100644 --- a/types/jquery.validation/index.d.ts +++ b/types/jquery.validation/index.d.ts @@ -10,7 +10,7 @@ declare namespace JQueryValidation { type ValidatePredicate = ((element: HTMLElement, event: JQueryEventObject) => void); - type ShouldValidatePredicate = boolean|ValidatePredicate; + type ShouldValidatePredicate = boolean | ValidatePredicate; interface ValidationOptions { /** @@ -218,7 +218,7 @@ declare namespace JQueryValidation { * * @param template The string to format. */ - format(template: string): ( (...args: any[]) => string); + format(template: string): ((...args: any[]) => string); format(template: string, ...args: any[]): string; /** * Modify default settings for validation. @@ -232,7 +232,7 @@ declare namespace JQueryValidation { } interface Validator { - element(element: string|JQuery): boolean; + element(element: string | JQuery): boolean; checkForm(): boolean; /** * Validates the form, returns true if it is valid, false otherwise. diff --git a/types/jquery.validation/jquery.validation-tests.ts b/types/jquery.validation/jquery.validation-tests.ts index 08bc439973..37273e0f51 100644 --- a/types/jquery.validation/jquery.validation-tests.ts +++ b/types/jquery.validation/jquery.validation-tests.ts @@ -15,8 +15,8 @@ function test_validate() { const errors = validator.numberOfInvalids(); if (errors) { const message = errors === 1 - ? 'You missed 1 field. It has been highlighted' - : 'You missed ' + errors + ' fields. They have been highlighted'; + ? 'You missed 1 field. It has been highlighted' + : 'You missed ' + errors + ' fields. They have been highlighted'; $("div.error span").html(message); $("div.error").show(); } else { @@ -56,7 +56,7 @@ function test_validate() { }, errorPlacement: (error, element) => { if (element.attr("name") === "fname" - || element.attr("name") === "lname") + || element.attr("name") === "lname") error.insertAfter("#lastname"); else error.insertAfter(element); @@ -84,7 +84,7 @@ function test_validate() { onclick: (elt) => { } }); $(".selector").validate({ - onfocusout: (elt, event) => { }, + onfocusout: (elt, event) => { }, onkeyup: (elt, event) => { }, onclick: (elt, event) => { } }); @@ -155,12 +155,12 @@ function test_validate() { highlight: (element: HTMLInputElement, errorClass, validClass) => { $(element).addClass(errorClass).removeClass(validClass); $(( element).form).find("label[for=" + element.id + "]") - .addClass(errorClass); + .addClass(errorClass); }, unhighlight: (element: HTMLInputElement, errorClass, validClass) => { $(element).removeClass(errorClass).addClass(validClass); $(( element).form).find("label[for=" + element.id + "]") - .removeClass(errorClass); + .removeClass(errorClass); } }); $(".selector").validate({ @@ -174,8 +174,8 @@ function test_validate() { onclick: false, }); $('.selector').validate({ - onfocusout: () => {}, - onkeyup: () => {}, + onfocusout: () => { }, + onkeyup: () => { }, onclick: elt => 2, }); } diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 0a47546193..f944f93ba3 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -2767,7 +2767,7 @@ interface JQuery { * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/on/#on-events-selector-data} */ - on(events: { [key: string]: any; }, selector?: string, data?: any): JQuery; + on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, selector?: string, data?: any): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * @@ -2775,7 +2775,7 @@ interface JQuery { * @param data Data to be passed to the handler in event.data when an event occurs. * @see {@link https://api.jquery.com/on/#on-events-selector-data} */ - on(events: { [key: string]: any; }, data?: any): JQuery; + on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, data?: any): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. diff --git a/types/js-search/index.d.ts b/types/js-search/index.d.ts new file mode 100644 index 0000000000..49c10251eb --- /dev/null +++ b/types/js-search/index.d.ts @@ -0,0 +1,143 @@ +// Type definitions for js-search v1.4.0 +// Project: https://github.com/bvaughn/js-search +// Definitions by: Guo Yunhe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "js-search" { + + class Search { + + constructor( + uidFieldName: string | Array + ); + + public indexStrategy: IIndexStrategy; + public sanitizer: ISanitizer; + public searchIndex: ISearchIndex; + public tokenizer: ITokenizer; + + public addDocument(document: Object): void; + public addDocuments(documents: Array): void; + + public addIndex(field: string | Array): void; + + public search(query: string): Array; + + } + + interface IIndexStrategy { + expandToken(token: string): Array; + } + + class AllSubstringsIndexStrategy implements IIndexStrategy { + expandToken(token: string): Array; + } + + class ExactWordIndexStrategy implements IIndexStrategy { + expandToken(token: string): Array; + } + + class PrefixIndexStrategy implements IIndexStrategy { + expandToken(token: string): Array; + } + + interface ISanitizer { + sanitize(text: string): string; + } + + class CaseSensitiveSanitizer implements ISanitizer { + sanitize(text: string): string; + } + + class LowerCaseSanitizer implements ISanitizer { + sanitize(text: string): string; + } + + interface ISearchIndex { + indexDocument( + token: string, + uid: string, + document: Object + ): void; + + search( + tokens: Array, + corpus: Array + ): Array; + } + + type ITfIdfTokenMap = { + [token: string]: ITfIdfTokenMetadata; + }; + + type ITfIdfUidMap = { + [uid: string]: ITfIdfUidMetadata; + }; + + type ITfIdfTokenMetadata = { + $numDocumentOccurrences: number; + $totalNumOccurrences: number; + $uidMap: ITfIdfUidMap; + }; + + type ITfIdfUidMetadata = { + $document: Object; + $numTokenOccurrences: number; + }; + + class TfIdfSearchIndex implements ISearchIndex { + constructor(uidFieldName: string | Array); + + indexDocument(token: string, uid: string, doc: Object): void; + + search(tokens: Array, corpus: Array): Array; + } + + class UnorderedSearchIndex implements ISearchIndex { + constructor(); + + indexDocument(token: string, uid: string, doc: Object): void; + + search(tokens: Array, corpus: Array): Array; + } + + interface ITokenizer { + tokenize(text: string): Array; + } + + class SimpleTokenizer implements ITokenizer { + tokenize(text: string): Array; + } + + type StemmingFunction = (text: string) => string; + + class StemmingTokenizer implements ITokenizer { + constructor( + stemmingFunction: StemmingFunction, + decoratedTokenizer: ITokenizer + ); + + tokenize(text: string): Array; + } + + class StopWordsTokenizer implements ITokenizer { + constructor(decoratedTokenizer: ITokenizer); + + tokenize(text: string): Array; + } + + var StopWordsMap: any; + + class TokenHighlighter { + + constructor( + opt_indexStrategy: IIndexStrategy, + opt_sanitizer: ISanitizer, + opt_wrapperTagName: string + ); + + public highlight(text: string, tokens: Array): string; + + } + +} diff --git a/types/js-search/js-search-tests.ts b/types/js-search/js-search-tests.ts new file mode 100644 index 0000000000..b852e000cc --- /dev/null +++ b/types/js-search/js-search-tests.ts @@ -0,0 +1,58 @@ +import { Search, ITokenizer, StopWordsMap, StopWordsTokenizer, StemmingTokenizer, SimpleTokenizer, UnorderedSearchIndex } from "js-search"; + +var theGreatGatsby = { + isbn: '9781597226769', + title: 'The Great Gatsby', + author: { + name: 'F. Scott Fitzgerald' + }, + tags: ['book', 'inspirational'] +}; +var theDaVinciCode = { + isbn: '0307474275', + title: 'The DaVinci Code', + author: { + name: 'Dan Brown' + }, + tags: ['book', 'mystery'] +}; +var angelsAndDemons = { + isbn: '074349346X', + title: 'Angels & Demons', + author: { + name: 'Dan Brown', + }, + tags: ['book', 'mystery'] +}; + +var search = new Search('isbn'); +search.addIndex('title'); +search.addIndex(['author', 'name']); +search.addIndex('tags') + +search.addDocuments([theGreatGatsby, theDaVinciCode, angelsAndDemons]); + +search.search('The'); // [theGreatGatsby, theDaVinciCode] +search.search('scott'); // [theGreatGatsby] +search.search('dan'); // [angelsAndDemons, theDaVinciCode] +search.search('mystery') // [angelsAndDemons, theDaVinciCode] + +search.tokenizer = { + tokenize(text: any) { + // Convert text to an Array of strings and return the Array + } +}; + + +// Function should accept a string param and return a string +var stemmer = function () { return 'foobar' }; + +search.tokenizer = new StemmingTokenizer(stemmer, new SimpleTokenizer()); + + +search.tokenizer = new StopWordsTokenizer(new SimpleTokenizer()); + +StopWordsMap.the = false; // Do not treat "the" as a stop word +StopWordsMap.bob = true; // Treat "bob" as a stop word + +search.searchIndex = new UnorderedSearchIndex(); diff --git a/types/js-search/tsconfig.json b/types/js-search/tsconfig.json new file mode 100644 index 0000000000..83ce87381c --- /dev/null +++ b/types/js-search/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "js-search-tests.ts" + ] +} diff --git a/types/js-search/tslint.json b/types/js-search/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/js-search/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jui-core/index.d.ts b/types/jui-core/index.d.ts index 2bea574d7c..d8143aaa28 100644 --- a/types/jui-core/index.d.ts +++ b/types/jui-core/index.d.ts @@ -34,7 +34,7 @@ export interface UtilBase { * @param {Function} ctor base Class * @param {Function} superCtor super Class */ - inherit( ctor: ((...args: any[]) => any), superCtor: ((...args: any[]) => any) ): void; + inherit(ctor: ((...args: any[]) => any), superCtor: ((...args: any[]) => any)): void; /** * @method extend @@ -53,7 +53,7 @@ export interface UtilBase { * @param {String or Number} px * @return {Number} */ - pxToInt(px: string| number): number; + pxToInt(px: string | number): number; /** * @method clone @@ -145,7 +145,7 @@ export interface UtilBase { * @param {Number} dataSize * @return {String} 변환된 csv 문자열 */ - dataToCsv(keys: string[] , dataList: any[], dataSize: number): string; + dataToCsv(keys: string[], dataList: any[], dataSize: number): string; /** * @method dataToCsv2 @@ -268,7 +268,7 @@ export interface UtilBase { * @param {Object} [context=null] * @return {Function} 최적화된 루프 콜백 (index, groupIndex 2가지 파라미터를 받는다.) */ - loop(total: number, context?: any): ((index: number, groupIndex: number) => void ); + loop(total: number, context?: any): ((index: number, groupIndex: number) => void); /** * @method loopArray @@ -280,7 +280,7 @@ export interface UtilBase { * @param {Object} [context=null] * @return {Function} 최적화된 루프 콜백 (data, index, groupIndex 3가지 파라미터를 받는다.) */ - loopArray(data: any[], context?: any): ((data: any, index: number, groupIndex: number) => void ); + loopArray(data: any[], context?: any): ((data: any, index: number, groupIndex: number) => void); /** * @method makeIndex @@ -405,7 +405,7 @@ export interface JuiStatic { * @param {String} type Event type * @param {Array} args Event arguments */ - emit(key: string, type: string, args: any[]): void; + emit(key: string, type: string, args: any[]): void; /** * @method get @@ -414,7 +414,7 @@ export interface JuiStatic { * @param {Integer/String} key * @returns {Object/Array} UI instance */ - get(key: number|string): any; + get(key: number | string): any; /** * @method getAll @@ -422,7 +422,7 @@ export interface JuiStatic { * * @return {Array} UI instances */ - getAll(): any[]; + getAll(): any[]; /** * @method create @@ -433,7 +433,7 @@ export interface JuiStatic { * @param {Object} options * @return {Object} */ - create(type: string, selector: any, options?: {}): any; + create(type: string, selector: any, options?: {}): any; } export interface UICollection { @@ -455,7 +455,7 @@ export interface UICore { * @param {Function} args Event Arguments * @return {Mixed} */ - emit(type: string, args: () => void): any; + emit(type: string, args: () => void): any; /** * @method on @@ -464,7 +464,7 @@ export interface UICore { * @param {String} type Event type * @param {Function} callback */ - on(type: string, callback: () => void): void; + on(type: string, callback: () => void): void; /** * @method off @@ -472,7 +472,7 @@ export interface UICore { * * @param {String} type Event type */ - off(type: string): void; + off(type: string): void; /** * @method addValid @@ -481,7 +481,7 @@ export interface UICore { * @param {String} name Method name * @param {Array} params Parameters */ - addValid(name: string, params: any[]): void; + addValid(name: string, params: any[]): void; /** * @method callBefore @@ -491,7 +491,7 @@ export interface UICore { * @param {Function} callback * @return {Mixed} */ - callBefore(name: string, callback: () => void): void; + callBefore(name: string, callback: () => void): void; /** * @method callAfter @@ -501,7 +501,7 @@ export interface UICore { * @param {Function} callback * @return {Mixed} */ - callAfter(name: string, callback: () => void): void; + callAfter(name: string, callback: () => void): void; /** * @method callDelay @@ -510,7 +510,7 @@ export interface UICore { * @param {String} name Method name * @param {Function} callback */ - callDelay(name: string, callObj: () => void): void; + callDelay(name: string, callObj: () => void): void; /** * @method setTpl @@ -519,7 +519,7 @@ export interface UICore { * @param {String} name Template name * @param {String} html Template markup */ - setTpl(name: string, html: string): void; + setTpl(name: string, html: string): void; /** * @method setOption @@ -528,14 +528,14 @@ export interface UICore { * @param {String} key * @param {Mixed} value */ - setOption(key: string, value: any): void; + setOption(key: string, value: any): void; /** * @method destroy * Removes all events set in a UI obejct and the DOM element * */ - destroy(): void; + destroy(): void; } //noinspection TypeScriptUnresolvedVariable @@ -549,7 +549,7 @@ export interface UIEvent extends UICore { * @param {String/HTMLElement} Selector * @returns {*|jQuery} */ - find(selector: any): JQuery; + find(selector: any): JQuery; } export class ColorScale { @@ -807,7 +807,7 @@ export interface UtilMath { inverseMatrix3d(a: any[]): any[]; } -export interface UtilScaleOrdinal extends Function { +export interface UtilScaleOrdinal extends Function { (x: number): number; domain(values: any[]): UtilScaleOrdinal; range(values: any[]): UtilScaleOrdinal; diff --git a/types/jui-grid/index.d.ts b/types/jui-grid/index.d.ts index 8ced2164e4..5da7d23c43 100644 --- a/types/jui-grid/index.d.ts +++ b/types/jui-grid/index.d.ts @@ -3,16 +3,16 @@ // Definitions by: Jin-Ho Park // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {UIEvent} from 'jui-core'; +import { UIEvent } from 'jui-core'; export interface GridColumn { - (index: number|string): this; + (index: number | string): this; /** @property {HTMLElement} [element=null] TH element of a specified column */ element: any; /** @property {String} [order="asc"] Column sort state */ - order: "asc"|"desc"; + order: "asc" | "desc"; /** @property {String} [name=null] Column name */ name?: string; @@ -27,7 +27,7 @@ export interface GridColumn { index: number; /** @property {"show"/"hide"/"resize"} [type="show"] The current column state */ - type: "show"|"hide"|"resize"; + type: "show" | "hide" | "resize"; /** @property {Integer} [width=null] Column width */ width?: number; @@ -47,7 +47,7 @@ export interface GridRow { rownum?: number; /** @property {String/Integer} [index=null] Index of a specified row. In the case of a tree structure, a depth is given. */ - index: number|string; + index: number | string; /** @property {HTMLElement} [element=null] TR element of a specified row. */ element: any; @@ -68,12 +68,12 @@ export interface GridRow { depth: number; /** @property {"open"/"fold"} [type="fold"] State value that indicates whether a child row is shown or hidden. */ - type: "open"|"fold"; + type: "open" | "fold"; /** @property {Function} [type="null"] State value that indicates whether a child row is shown or hidden. */ tpl?(): void; - setIndex(rownum: number|string): void; + setIndex(rownum: number | string): void; reload(columns: GridColumn[], seq: any, xssFilter: any): void; destroy(): void; isLeaf(): boolean; @@ -81,37 +81,37 @@ export interface GridRow { open(): void; appendChild(row: GridRow): void; insertChild(rownum: number, row: GridRow, isReload?: any): void; - removeChild(index: number|string): void; + removeChild(index: number | string): void; lastChild(): GridRow; - lastChildLeaf(lastRow: GridRow): GridRow|any; + lastChildLeaf(lastRow: GridRow): GridRow | any; showCell(index: number): void; hideCell(index: number): void; } export interface GridBase { - appendRow(index: number|string, data?: {}): GridRow; - insertRow(index: number|string, data: {}): GridRow; - updateRow(index: number|string, data: {}): GridRow; - moveRow(index: number|string, targetIndex: number|string): void; - removeRow(index: number|string): void; - openRow(index: number|string): void; + appendRow(index: number | string, data?: {}): GridRow; + insertRow(index: number | string, data: {}): GridRow; + updateRow(index: number | string, data: {}): GridRow; + moveRow(index: number | string, targetIndex: number | string): void; + removeRow(index: number | string): void; + openRow(index: number | string): void; openRowAll(): void; - foldRow(index: number|string): void; + foldRow(index: number | string): void; foldRowAll(): void; removeRows(): void; sortRows(name: string, isDesc: boolean): void; appendColumn(tplType: string, dataList: any[]): void; - removeColumn(index: number|string): void; - hideColumn(index: number|string): void; - showColumn(index: number|string): void; + removeColumn(index: number | string): void; + hideColumn(index: number | string): void; + showColumn(index: number | string): void; getColumnCount(): number; getRowCount(): number; - getColumn(index?: number|string): GridColumn|GridColumn[]; - getRow(index?: number|string): GridRow|GridRow[]; - getRowAll(index: number|string): GridRow[]; - getRowParent(index: number|string): GridRow; - setColumn(index: number|string, column: GridColumn): void; - setRow(index: number|string, row: GridRow): void; + getColumn(index?: number | string): GridColumn | GridColumn[]; + getRow(index?: number | string): GridRow | GridRow[]; + getRowAll(index: number | string): GridRow[]; + getRowParent(index: number | string): GridRow; + setColumn(index: number | string, column: GridColumn): void; + setRow(index: number | string, row: GridRow): void; } export interface GridTable extends UIEvent { @@ -153,7 +153,7 @@ export interface GridTable extends UIEvent { * @cfg {Boolean/Array} [colshow=false] * Sets a column index shown when the Show/Hide Column menu is enabled. */ - colshow?: boolean|any[], + colshow?: boolean | any[], /** * @cfg {Boolean} [scroll=false] @@ -189,7 +189,7 @@ export interface GridTable extends UIEvent { * @cfg {Boolean|Array} [editRow=false] * Determines whether to use a modified row area. */ - editRow?: boolean|any[], + editRow?: boolean | any[], /** * @cfg {Boolean} [editEvent=true] @@ -207,7 +207,7 @@ export interface GridTable extends UIEvent { * @cfg {Boolean/Array} [sort=false] * Determines whether to use the table sort function. */ - sort?: boolean|any[], + sort?: boolean | any[], /** * @cfg {Integer} [sortIndex=null] @@ -219,7 +219,7 @@ export interface GridTable extends UIEvent { * @cfg {String} [sortOrder="asc"] * Determines whether to use the table sort function. */ - sortOrder?: "asc"|"desc", + sortOrder?: "asc" | "desc", /** * @cfg {Boolean} [sortEvent=true] @@ -242,7 +242,7 @@ export interface GridTable extends UIEvent { * * @param {Array} rows */ - update(indexOrRows?: any, rows?: any): void; + update(indexOrRows?: any, rows?: any): void; /** * @method updateTree * It is possible to configure a tree table using an object array with the index and data properties. @@ -257,7 +257,7 @@ export interface GridTable extends UIEvent { * * @param {RowObject} row */ - append(rowOrIndex?: number|any, row?: any): void; + append(rowOrIndex?: number | any, row?: any): void; /** * @method insert @@ -468,7 +468,7 @@ export interface GridTable extends UIEvent { * @param {"Integer"/"String"} key index or column key * @return {ColumnObject} column */ - getColumn(index: number|string): GridColumn; + getColumn(index: number | string): GridColumn; /** * @method showColumn @@ -476,7 +476,7 @@ export interface GridTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - showColumn(index: number|string, e?: any): void; + showColumn(index: number | string, e?: any): void; /** * @method hideColumn @@ -484,7 +484,7 @@ export interface GridTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - hideColumn(index: number|string, e?: any): void; + hideColumn(index: number | string, e?: any): void; /** * @method initColumns @@ -662,7 +662,7 @@ export interface GridXTable extends UIEvent { * * @param {Integer} index */ - open(index: number|string): void; + open(index: number | string): void; /** * @method fold @@ -670,19 +670,19 @@ export interface GridXTable extends UIEvent { * * @param {Integer} index */ - fold(index: number|string): void; + fold(index: number | string): void; /** * @method openAll * Shows all child rows of a specified index. */ - openAll(index: number|string): void; + openAll(index: number | string): void; /** * @method foldAll * Hides all child rows of a specified index. */ - foldAll(index: number|string): void; + foldAll(index: number | string): void; /** * @method next @@ -705,7 +705,7 @@ export interface GridXTable extends UIEvent { * @param {Integer} index * @param {String} order "asc" or "desc" */ - sort(index: number, order: "asc"|"desc", e?: any, isNotLoading?: any): void; + sort(index: number, order: "asc" | "desc", e?: any, isNotLoading?: any): void; /** * @method filter @@ -762,7 +762,7 @@ export interface GridXTable extends UIEvent { * @param {Integer|String} index * @param {Integer} dist */ - scrollTop(index: number|string, dist: number): void; + scrollTop(index: number | string, dist: number): void; /** * @deprecated @@ -831,7 +831,7 @@ export interface GridXTable extends UIEvent { * @param {"Integer"/"String"} key index or column key * @return {ColumnObject} column */ - getColumn(index: number|string): GridColumn; + getColumn(index: number | string): GridColumn; /** * @method getData @@ -840,7 +840,7 @@ export interface GridXTable extends UIEvent { * @param {"Integer"/"String"} key index * @return {ColumnObject} data */ - getData(index: number|string): any; + getData(index: number | string): any; /** * @method showColumn @@ -848,7 +848,7 @@ export interface GridXTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - showColumn(index: number|string): void; + showColumn(index: number | string): void; /** * @method hideColumn @@ -856,7 +856,7 @@ export interface GridXTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - hideColumn(index: number|string): void; + hideColumn(index: number | string): void; /** * @method initColumns @@ -864,7 +864,7 @@ export interface GridXTable extends UIEvent { * * @param {"Integer"/"String"} key index or column name */ - initColumns(keys: number|string): void; + initColumns(keys: number | string): void; /** * @method showColumnMenu @@ -973,7 +973,7 @@ export interface GridXTable extends UIEvent { * @param {Integer} columnIndex * @param {Function} callback */ - rowFunc(type: "sum"|"avg", index: number, callback: (data: any) => void): any; + rowFunc(type: "sum" | "avg", index: number, callback: (data: any) => void): any; /** * @method getPage diff --git a/types/jui/index.d.ts b/types/jui/index.d.ts index 24e5ed215c..93372f898d 100644 --- a/types/jui/index.d.ts +++ b/types/jui/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jin-Ho Park // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import {UIEvent} from 'jui-core'; +import { UIEvent } from 'jui-core'; export interface UIAccordion extends UIEvent { (selector: any, options?: { @@ -26,7 +26,7 @@ export interface UIAccordion extends UIEvent { * */ multipanel?: boolean - }) : this; + }): this; /** * @method activeIndex @@ -52,7 +52,7 @@ export interface UIAutoComplete { * Designates words subject to autofill */ words?: string[] - }) : this; + }): this; /** * @method update @@ -61,14 +61,14 @@ export interface UIAutoComplete { * @param {Array} words * */ - update(newWords: string[]): void; + update(newWords: string[]): void; /** * @method close * Close the active drop-down * */ - close(): void; + close(): void; /** * @method list @@ -76,7 +76,7 @@ export interface UIAutoComplete { * * @return {Array} words */ - list(): string[]; + list(): string[]; } export interface UIColorPicker { @@ -85,11 +85,11 @@ export interface UIColorPicker { event?: any, type?: string, color?: string - }) : this; + }): this; - getColor(type: string): string|{}; + getColor(type: string): string | {}; - setColor(value: string|{}): void; + setColor(value: string | {}): void; } export interface UICombo { @@ -130,14 +130,14 @@ export interface UICombo { * @cfg {"top"/"bottom"} [position="bottom"] * It is possible to determine an initial selection button with a specified value */ - position?: "top"|"bottom", + position?: "top" | "bottom", /** * @cfg {Boolean} [flex=true] * Drop-down menu is varied by changing the width function */ flex?: boolean - }) : this; + }): this; /** * @method setIndex @@ -145,7 +145,7 @@ export interface UICombo { * * @param {Number} index */ - setIndex(index: number): void; + setIndex(index: number): void; /** * @method setValue @@ -153,7 +153,7 @@ export interface UICombo { * * @param {Mixed} value */ - setValue(value: any): void; + setValue(value: any): void; /** * @method getData @@ -161,7 +161,7 @@ export interface UICombo { * * @return {Object} */ - getData(): {}; + getData(): {}; /** * @method getValue @@ -169,7 +169,7 @@ export interface UICombo { * * @return {Mixed} */ - getValue(): any; + getValue(): any; /** * @method getText @@ -177,25 +177,25 @@ export interface UICombo { * * @return {String} */ - getText(): string; + getText(): string; /** * @method open * Shows the element list of a combo box */ - open(e: any): void; + open(e: any): void; /** * @method fold * Hides the element list of a combo box */ - fold(): void; + fold(): void; /** * @method reload * Re-defines a combo box */ - reload(): void; + reload(): void; } export interface UIDatePicker { @@ -206,7 +206,7 @@ export interface UIDatePicker { * @cfg {"daily"/"monthly"/"yearly"} [type="daily"] * Determines the type of a calendar */ - type?: "daily"|"monthly"|"yearly", + type?: "daily" | "monthly" | "yearly", /** * @cfg {String} [titleFormat="yyyy.MM"] @@ -224,7 +224,7 @@ export interface UIDatePicker { * @cfg {Date} [date="now"] * Selects a specific date as a basic */ - date?: "now"|Date, + date?: "now" | Date, /** * @cfg {Date} [minDate="null"] @@ -237,7 +237,7 @@ export interface UIDatePicker { * Selects a specific maximum date */ maxDate?: Date - }) : this; + }): this; /** * @method page @@ -246,7 +246,7 @@ export interface UIDatePicker { * @param {Integer} year * @param {Integer} month */ - page(y: number, m: number): void; + page(y: number, m: number): void; /** * @method prev @@ -260,7 +260,7 @@ export interface UIDatePicker { * Outputs a calendar that fits the next year/month * */ - next(e: any, moveYear?: boolean): void; + next(e: any, moveYear?: boolean): void; /** * @method select @@ -268,7 +268,7 @@ export interface UIDatePicker { * * @param {"year"/"month"/"date"/"timestamp"/"Date"} */ - select( ...args: any[]): void; + select(...args: any[]): void; /** * @method addTime @@ -276,7 +276,7 @@ export interface UIDatePicker { * * @param {"Integer"/"Date"} time Timestamp or Date */ - addTime(time: number|Date): void; + addTime(time: number | Date): void; /** * @method getDate @@ -284,7 +284,7 @@ export interface UIDatePicker { * * @return {Date} Date object */ - getDate(): Date; + getDate(): Date; /** * @method getTime @@ -292,7 +292,7 @@ export interface UIDatePicker { * * @return {Integer} Timestamp */ - getTime(): number; + getTime(): number; /** * @method getFormat @@ -300,13 +300,13 @@ export interface UIDatePicker { * * @return {String} format Formatted date string */ - getFormat(format: string): string; + getFormat(format: string): string; /** * @method reload * Reloads the datepicker */ - reload(): void; + reload(): void; } export interface UIDropdown { @@ -377,7 +377,7 @@ export interface UIDropdown { * @param {Integer} x * @param {Integer} y */ - show(x: number, y: number): void; + show(x: number, y: number): void; /** * @method move @@ -386,13 +386,13 @@ export interface UIDropdown { * @param {Integer} x * @param {Integer} y */ - move(x: number, y: number): void; + move(x: number, y: number): void; /** * @method reload * Reloads the dropdown list */ - reload(): void; + reload(): void; } export interface UIModal { @@ -403,7 +403,7 @@ export interface UIModal { * @cfg {"black"/"gray"} [color="black"] * Determines the color of a modal */ - color?: "black"|"gray", + color?: "black" | "gray", /** * @cfg {Float} [opacity=0.4] @@ -415,7 +415,7 @@ export interface UIModal { * @cfg {String/DOMElement} [target="body"] * Sets a selector on which a modal is shown */ - target?: string|any, + target?: string | any, /** * @cfg {Integer} [index=0] @@ -434,19 +434,19 @@ export interface UIModal { * Automatically hides a modal when clicking on it */ autoHide?: boolean - }): this; + }): this; /** * @method hide * Hides a modal */ - hide(): void; + hide(): void; /** * @method show * Shows a modal */ - show(): void; + show(): void; /** * @method resize @@ -463,7 +463,7 @@ export interface UINotify { * @cfg {"top"/"top-lefet"/"top-right"/"bottom"/"bottom-left"/"bottom-right"} [position="top-right"] * Designates the location where a notice message is added */ - position?: "top"|"top-lefet"|"top-right"|"bottom"|"bottom-left"|"bottom-right", + position?: "top" | "top-lefet" | "top-right" | "bottom" | "bottom-left" | "bottom-right", /** * @cfg {Integer} [padding=12] @@ -524,7 +524,7 @@ export interface UINotify { reset(): void; } -export interface UIPaging { +export interface UIPaging { (selector: any, options?: { tpl?: any, event?: any, @@ -593,7 +593,7 @@ export interface UIProgress { tpl?: any, event?: any, type?: "simple" | "flat", // simple or flat - orient?: "horizontal"|"vertical", // or vertical, + orient?: "horizontal" | "vertical", // or vertical, min?: number, max?: number, value?: number, @@ -618,7 +618,7 @@ export interface UIProperty { loadItems(newItems: any[]): void; - addItem(item: {}|any[]): void; + addItem(item: {} | any[]): void; // remove item by key or title removeItem(item: {}): void; @@ -628,7 +628,7 @@ export interface UIProperty { * * get a list of group's title. */ - getGroupList(): any[]; + getGroupList(): any[]; /** * @method collapsed @@ -637,7 +637,7 @@ export interface UIProperty { * * @param {String} id */ - collapsed(id: string): void; + collapsed(id: string): void; /** * @method expanded @@ -683,13 +683,13 @@ export interface UISelect { event?: any, items?: any[], placeholder?: string, - align?: 'left'|'right', - valign?: 'top'|'bottom', + align?: 'left' | 'right', + valign?: 'top' | 'bottom', multi?: boolean }): this; - setValue(value: any|any[]): void; - getValue(): any| any[]; + setValue(value: any | any[]): void; + getValue(): any | any[]; setSelectedIndex(index: number): void; getSelectedIndex(): number; update(data: any[]): void; @@ -699,8 +699,8 @@ export interface UISlider { (selector: any, options?: { tpl?: any, event?: any, - type?: "single"|"double", // or double - orient?: "horizontal"|"vertical", // or vertical, + type?: "single" | "double", // or double + orient?: "horizontal" | "vertical", // or vertical, min?: number, max?: number, step?: number, @@ -776,13 +776,13 @@ export interface UISplitter { * @cfg {"vertical"/"horizontal"} [direction='vertical'] * set bar's direction */ - direction?: 'vertical'|'horizontal', + direction?: 'vertical' | 'horizontal', /** * @cfg {String/Number} [initSize='50%'] * set first panel's default width or height */ - initSize?: string|number, + initSize?: string | number, /** * @cfg {Number/Array} [minSize=30] @@ -794,7 +794,7 @@ export interface UISplitter { * minSize[1] is second panel's minimum size * */ - minSize?: number|number[], + minSize?: number | number[], /** * @cfg {String} [items=[]] @@ -846,7 +846,7 @@ export interface UITab { * @cfg {String/DOMElement} [target=""] * Determines a selector in the area to become the content of a tab */ - target?: string|any, + target?: string | any, /** * @cfg {Integer} [index=0] @@ -963,7 +963,7 @@ export interface UITooltip { * @cfg {"top"/"bottom"/"left"/"right"} [position="top"] * Determines the location where a tooltip is shown */ - position?: "top"|"bottom"|"left"|"right", + position?: "top" | "bottom" | "left" | "right", /** * @cfg {Integer} [width=150] @@ -975,7 +975,7 @@ export interface UITooltip { * @cfg {"left"/"right"/"center"} [align="left"] * Determines the alignment state inside a tooltip */ - align?: "left"|"right"|"center", + align?: "left" | "right" | "center", /** * @cfg {Integer} [delay=0] @@ -1260,25 +1260,25 @@ export interface UIWindow { * @cfg {String/Integer} [left="auto"] * Determines the X coordinate of a window */ - left?: string|number, + left?: string | number, /** * @cfg {String/Integer} [top="auto"] * Determines the Y coordinate of a window */ - top?: string|number, + top?: string | number, /** * @cfg {String/Integer} [right="auto"] * Determines the X coordinate based on the right side of a window */ - right?: string|number, + right?: string | number, /** * @cfg {String/Integer} [bottom="auto"] * Determines the Y coordinate based on the bottom side of a window */ - bottom?: string|number, + bottom?: string | number, /** * @cfg {Boolean} [modal=false] diff --git a/types/kendo-ui/index.d.ts b/types/kendo-ui/index.d.ts index f1d3fa0437..9848335e49 100644 --- a/types/kendo-ui/index.d.ts +++ b/types/kendo-ui/index.d.ts @@ -5409,6 +5409,7 @@ declare namespace kendo.ui { slotByElement(element: Element): any; slotByElement(element: JQuery): any; view(type?: string): void; + view(): kendo.ui.SchedulerView; viewName(): string; } @@ -5627,7 +5628,8 @@ declare namespace kendo.ui { dateHeaderTemplate?: string|Function; dayTemplate?: string|Function; editable?: boolean|SchedulerViewEditable; - endTime?: Date; + endDate?(): Date; + endTime?: Date; eventHeight?: number; eventTemplate?: string|Function; eventTimeTemplate?: string|Function; @@ -5641,6 +5643,7 @@ declare namespace kendo.ui { selectedShortDateFormat?: string; showWorkHours?: boolean; slotTemplate?: string|Function; + startDate?(): Date; startTime?: Date; title?: string; type?: string; diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index e95373120e..16330b4e3a 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -173,6 +173,7 @@ declare namespace Knex { interface Join { (raw: Raw): QueryBuilder; + (builder: QueryBuilder, clause: (this: JoinClause) => void): QueryBuilder; (tableName: string, columns: { [key: string]: string | number | Raw }): QueryBuilder; (tableName: string, callback: Function): QueryBuilder; (tableName: TableName, raw: Raw): QueryBuilder; diff --git a/types/koa-helmet/index.d.ts b/types/koa-helmet/index.d.ts new file mode 100644 index 0000000000..f97480f505 --- /dev/null +++ b/types/koa-helmet/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for koa-helmet 3.1 +// Project: https://github.com/venables/koa-helmet#readme +// Definitions by: Nick Simmons +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { + IHelmetConfiguration, + IHelmetFrameguardConfiguration, + IHelmetHstsConfiguration, + IHelmetXssFilterConfiguration, + IHelmetDnsPrefetchControlConfiguration, + IHelmetHpkpConfiguration, + IHelmetReferrerPolicyConfiguration } from 'helmet'; +import {Middleware, Context} from 'koa'; + +declare namespace koaHelmet { + type KoaHelmetContentSecurityPolicyDirectiveFunction = (ctx: Context) => string; + + type KoaHelmetCspDirectiveValue = string | KoaHelmetContentSecurityPolicyDirectiveFunction; + + interface KoaHelmetContentSecurityPolicyDirectives { + baseUri?: KoaHelmetCspDirectiveValue[]; + childSrc?: KoaHelmetCspDirectiveValue[]; + connectSrc?: KoaHelmetCspDirectiveValue[]; + defaultSrc?: KoaHelmetCspDirectiveValue[]; + fontSrc?: KoaHelmetCspDirectiveValue[]; + formAction?: KoaHelmetCspDirectiveValue[]; + frameAncestors?: KoaHelmetCspDirectiveValue[]; + frameSrc?: KoaHelmetCspDirectiveValue[]; + imgSrc?: KoaHelmetCspDirectiveValue[]; + mediaSrc?: KoaHelmetCspDirectiveValue[]; + objectSrc?: KoaHelmetCspDirectiveValue[]; + pluginTypes?: KoaHelmetCspDirectiveValue[]; + reportUri?: string; + sandbox?: KoaHelmetCspDirectiveValue[]; + scriptSrc?: KoaHelmetCspDirectiveValue[]; + styleSrc?: KoaHelmetCspDirectiveValue[]; + } + + interface KoaHelmetContentSecurityPolicyConfiguration { + reportOnly?: boolean; + setAllHeaders?: boolean; + disableAndroid?: boolean; + browserSniff?: boolean; + directives?: KoaHelmetContentSecurityPolicyDirectives; + } + + interface KoaHelmet { + (options?: IHelmetConfiguration): Middleware; + contentSecurityPolicy(options?: KoaHelmetContentSecurityPolicyConfiguration): Middleware; + dnsPrefetchControl(options?: IHelmetDnsPrefetchControlConfiguration): Middleware; + frameguard(options?: IHelmetFrameguardConfiguration): Middleware; + hpkp(options?: IHelmetHpkpConfiguration): Middleware; + hsts(options?: IHelmetHstsConfiguration): Middleware; + ieNoOpen(): Middleware; + noCache(options?: any): Middleware; + noSniff(): Middleware; + referrerPolicy(options?: IHelmetReferrerPolicyConfiguration): Middleware; + xssFilter(options?: IHelmetXssFilterConfiguration): Middleware; + } +} + +declare const koaHelmet: koaHelmet.KoaHelmet; +export = koaHelmet; diff --git a/types/koa-helmet/koa-helmet-tests.ts b/types/koa-helmet/koa-helmet-tests.ts new file mode 100644 index 0000000000..1f50ea5c6b --- /dev/null +++ b/types/koa-helmet/koa-helmet-tests.ts @@ -0,0 +1,197 @@ +import * as Koa from 'koa'; +import helmet = require('koa-helmet'); + +const app = new Koa(); + +/** + * @summary Test for {@see helmet}. + */ +function helmetTest() { + app.use(helmet()); + app.use(helmet({})); + app.use(helmet({ frameguard: false })); + app.use(helmet({ frameguard: true })); + app.use(helmet({ + frameguard: { + action: 'deny' + } + })); +} + +/** + * @summary Test for {@see helmet#contentSecurityPolicy} function. + */ +function contentSecurityPolicyTest() { + const emptyArray: string[] = []; + const config = { + directives: { + baseUri: ['base.example.com'], + childSrc: ['child.example.com'], + connectSrc: ['connect.example.com'], + defaultSrc: ['*'], + fontSrc: ['font.example.com'], + formAction: ['formaction.example.com'], + frameAncestors: ["'none'"], + frameSrc: emptyArray, + imgSrc: ['images.example.com'], + mediaSrc: ['media.example.com'], + objectSrc: ['objects.example.com'], + pluginTypes: emptyArray, + reportUri: '/some-url', + sandbox: emptyArray, + scriptSrc: ['scripts.example.com', (ctx: Koa.Context) => { + return "'nonce-abc123'"; + }], + styleSrc: ['css.example.com'] + }, + reportOnly: false, + setAllHeaders: false, + disableAndroid: false + }; + + app.use(helmet.contentSecurityPolicy()); + app.use(helmet.contentSecurityPolicy({})); + app.use(helmet.contentSecurityPolicy(config)); + app.use(helmet.contentSecurityPolicy({ + directives: { + defaultSrc: ["'self'"] + }, + setAllHeaders: true + })); +} + +/** + * @summary Test for {@see helmet#dnsPrefetchControl} function. + */ +function dnsPrefetchControlTest() { + app.use(helmet.dnsPrefetchControl()); + app.use(helmet.dnsPrefetchControl({ allow: false })); + app.use(helmet.dnsPrefetchControl({ allow: true })); +} + +/** + * @summary Test for {@see helmet#frameguard} function. + */ +function frameguardTest() { + app.use(helmet.frameguard()); + app.use(helmet.frameguard({})); + app.use(helmet.frameguard({ action: 'deny' })); + app.use(helmet.frameguard({ action: 'sameorigin' })); + app.use(helmet.frameguard({ + action: 'allow-from', + domain: 'http://example.com' + })); +} + +/** + * @summary Test for {@see helmet#hpkp} function. + */ +function hpkpTest() { + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + includeSubdomains: false + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + includeSubdomains: true + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + reportUri: 'http://example.com' + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + reportOnly: true + })); + + app.use(helmet.hpkp({ + maxAge: 7776000000, + sha256s: ['AbCdEf123=', 'ZyXwVu456='], + setIf: (req, res) => true + })); +} + +/** + * @summary Test for {@see helmet#hsts} function. + */ +function hstsTest() { + app.use(helmet.hsts()); + + app.use(helmet.hsts({ maxAge: 7776000000 })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + includeSubdomains: true + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + preload: true + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + force: true + })); + + app.use(helmet.hsts({ + maxAge: 7776000000, + setIf: (req, res) => true + })); +} + +/** + * @summary Test for {@see helmet#ieNoOpen} function. + */ +function ieNoOpenTest() { + app.use(helmet.ieNoOpen()); +} + +/** + * @summary Test for {@see helmet#noCache} function. + */ +function noCacheTest() { + app.use(helmet.noCache()); + app.use(helmet.noCache({})); + app.use(helmet.noCache({ noEtag: true })); +} + +/** + * @summary Test for {@see helmet#noSniff} function. + */ +function noSniffTest() { + app.use(helmet.noSniff()); +} + +/** + * @summary Test for {@see helmet#referrerPolicy} function. + */ +function referrerPolicyTest() { + app.use(helmet.referrerPolicy({ policy: 'same-origin' })); +} + +/** + * @summary Test for {@see helmet#xssFilter} function. + */ +function xssFilterTest() { + app.use(helmet.xssFilter()); + app.use(helmet.xssFilter({})); + app.use(helmet.xssFilter({ setOnOldIE: false })); + app.use(helmet.xssFilter({ setOnOldIE: true })); +} diff --git a/types/koa-helmet/tsconfig.json b/types/koa-helmet/tsconfig.json new file mode 100644 index 0000000000..53162f08e8 --- /dev/null +++ b/types/koa-helmet/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-helmet-tests.ts" + ] +} diff --git a/types/koa-helmet/tslint.json b/types/koa-helmet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-helmet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-jwt/index.d.ts b/types/koa-jwt/index.d.ts index 4c123ff4a8..52836a6dce 100644 --- a/types/koa-jwt/index.d.ts +++ b/types/koa-jwt/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for koa-jwt 2.1 +// Type definitions for koa-jwt 3.2 // Project: https://github.com/koajs/jwt // Definitions by: Bruno Krebs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -11,7 +11,7 @@ declare function jwt(options: jwt.Options): jwt.Middleware; declare namespace jwt { interface Options { - secret: string | Buffer; + secret: string | Buffer | jwt.SecretProvider; key?: string; getToken?(opts: jwt.Options): string; passthrough?: boolean; @@ -30,4 +30,12 @@ declare namespace jwt { type Middleware = Koa.Middleware & { unless(options?: jwt.UnlessOptions): any; }; + + type SecretProvider = (header: jwt.TokenHeader) => Promise; + + interface TokenHeader { + alg: string; + kid: string; + typ: string; + } } diff --git a/types/koa-jwt/koa-jwt-tests.ts b/types/koa-jwt/koa-jwt-tests.ts index 646bb6d826..cdfc25fffa 100644 --- a/types/koa-jwt/koa-jwt-tests.ts +++ b/types/koa-jwt/koa-jwt-tests.ts @@ -15,3 +15,9 @@ app.use(jwt({ app.use(jwt({ secret: 'some-secret-key' }).unless({method: 'OPTIONS'})); + +app.use(jwt({ + secret: (header: jwt.TokenHeader): Promise => { + return Promise.resolve("some-secret-key"); + } +})); diff --git a/types/koa-route/index.d.ts b/types/koa-route/index.d.ts new file mode 100644 index 0000000000..4ee63b7b14 --- /dev/null +++ b/types/koa-route/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for koa-route 3.2 +// Project: https://github.com/koajs/route#readme +// Definitions by: Mike Cook +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as Koa from 'koa'; +import * as pathToRegexp from 'path-to-regexp'; + +type RoutePath = string | RegExp | Array; + +type RouteHandler = (this: Koa.Context, ctx: Koa.Context, ...params: any[]) => any; + +type CreateRoute = (routeFunc: RouteHandler) => Koa.Middleware; + +interface RouteMethod { + (path: RoutePath): CreateRoute; + (path: RoutePath, fn: RouteHandler, opts?: pathToRegexp.ParseOptions & pathToRegexp.RegExpOptions): Koa.Middleware; +} + +type CreateRouteMethod = (method: string) => RouteMethod; + +interface KoaRoutes { + all: CreateRouteMethod; + acl: RouteMethod; + bind: RouteMethod; + checkout: RouteMethod; + connect: RouteMethod; + copy: RouteMethod; + delete: RouteMethod; + del: RouteMethod; + get: RouteMethod; + head: RouteMethod; + link: RouteMethod; + lock: RouteMethod; + msearch: RouteMethod; + merge: RouteMethod; + mkactivity: RouteMethod; + mkcalendar: RouteMethod; + mkcol: RouteMethod; + move: RouteMethod; + notify: RouteMethod; + options: RouteMethod; + patch: RouteMethod; + post: RouteMethod; + propfind: RouteMethod; + proppatch: RouteMethod; + purge: RouteMethod; + put: RouteMethod; + rebind: RouteMethod; + report: RouteMethod; + search: RouteMethod; + subscribe: RouteMethod; + trace: RouteMethod; + unbind: RouteMethod; + unlink: RouteMethod; + unlock: RouteMethod; + unsubscribe: RouteMethod; +} + +declare const routes: KoaRoutes; + +export = routes; diff --git a/types/koa-route/koa-route-tests.ts b/types/koa-route/koa-route-tests.ts new file mode 100644 index 0000000000..331c7d6b53 --- /dev/null +++ b/types/koa-route/koa-route-tests.ts @@ -0,0 +1,21 @@ +import * as Koa from 'koa'; +import * as route from 'koa-route'; + +const app = new Koa(); + +const getData = async (param: string) => Promise.resolve({ foo: param }); + +const getter = route.get('/'); +const getterMiddleware = getter((ctx, next) => { + ctx.body = { status: 'OK' }; + next(); +}); + +const putter = route.put('/api/:param', async (ctx, param, next) => { + const data = await getData(param); + ctx.body = { status: 'OK', ...data }; + next(); +}); + +app.use(getterMiddleware); +app.use(putter); diff --git a/types/koa-route/package.json b/types/koa-route/package.json new file mode 100644 index 0000000000..1bac4155dc --- /dev/null +++ b/types/koa-route/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "path-to-regexp": "^1.7.0" + } +} diff --git a/types/koa-route/tsconfig.json b/types/koa-route/tsconfig.json new file mode 100644 index 0000000000..7b54228aaa --- /dev/null +++ b/types/koa-route/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-route-tests.ts" + ] +} diff --git a/types/koa-route/tslint.json b/types/koa-route/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-route/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/koa-websocket/index.d.ts b/types/koa-websocket/index.d.ts new file mode 100644 index 0000000000..115dbb43f6 --- /dev/null +++ b/types/koa-websocket/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for koa-websocket 2.1 +// Project: https://github.com/kudos/koa-websocket +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as Koa from 'koa'; +import * as ws from 'ws'; +import * as http from 'http'; +import * as https from 'https'; + +type KoaWebsocketConnectionHandler = (socket: ws) => void; +type KoaWebsocketMiddleware = (this: KoaWebsocketMiddlewareContext, context: Koa.Context, next: () => Promise) => any; +interface KoaWebsocketMiddlewareContext extends Koa.Context { + websocket: ws; + path: string; +} + +declare class KoaWebsocketServer { + app: Koa; + middleware: Koa.Middleware[]; + + constructor(app: Koa); + listen(server: http.Server | https.Server): ws.Server; + onConnection(handler: KoaWebsocketConnectionHandler): void; + use(middleware: KoaWebsocketMiddleware): this; +} + +interface KoaWebsocketApp extends Koa { + ws: KoaWebsocketServer; +} + +type KoaWebsockets = (app: Koa) => KoaWebsocketApp; + +declare const websockets: KoaWebsockets; +export = websockets; diff --git a/types/koa-websocket/koa-websocket-tests.ts b/types/koa-websocket/koa-websocket-tests.ts new file mode 100644 index 0000000000..66bd4bf4d2 --- /dev/null +++ b/types/koa-websocket/koa-websocket-tests.ts @@ -0,0 +1,14 @@ +import * as Koa from 'koa'; +import * as websocket from 'koa-websocket'; + +const app = websocket(new Koa()); + +app.ws.use(async function(context, next) { + this.websocket.on('message', (message) => { + console.log(message); + }); + this.websocket.send('Hello world'); + await next(); +}); + +app.listen(3000); diff --git a/types/koa-websocket/tsconfig.json b/types/koa-websocket/tsconfig.json new file mode 100644 index 0000000000..effcb59356 --- /dev/null +++ b/types/koa-websocket/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-websocket-tests.ts" + ] +} diff --git a/types/koa-websocket/tslint.json b/types/koa-websocket/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-websocket/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/launchpad/index.d.ts b/types/launchpad/index.d.ts index c39db51f2e..158485f818 100644 --- a/types/launchpad/index.d.ts +++ b/types/launchpad/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for launchpad +// Type definitions for launchpad 0.6.0 // Project: https://www.npmjs.com/package/launchpad // Definitions by: Peter Burns // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -34,16 +34,6 @@ export function browserstack( authCreds: BrowserstackAuth, cb: (err: any, browserstack: Launcher) => void): void; -interface RemoteConnectionOptions { - host: string; - username: string; - password: string; -} - -export function remote( - connectionOpts: RemoteConnectionOptions, - cb: (err: any, remoteLauncher: Launcher) => void): void; - interface BrowserPlatformDetails { pathQuery?: string; plistPath?: string; diff --git a/types/launchpad/launchpad-tests.ts b/types/launchpad/launchpad-tests.ts index e73beb47e5..0aa9d81104 100644 --- a/types/launchpad/launchpad-tests.ts +++ b/types/launchpad/launchpad-tests.ts @@ -43,19 +43,3 @@ launch.browserstack({ }, 5000); }); }); - -launch.remote({ - host : "ie7machine", - username : "launcher", - password : "testing" -}, function(err, api) { - api.browsers(function(error, browsers) { - // -> List of all browsers found on ie7machine - }); - - api("http://github.com", { - browser : "safari", - version : "latest" - }, function(err, instance) { - }); -}); diff --git a/types/leaflet.awesome-markers/index.d.ts b/types/leaflet.awesome-markers/index.d.ts index ee6b65eaa4..48c58b8f60 100644 --- a/types/leaflet.awesome-markers/index.d.ts +++ b/types/leaflet.awesome-markers/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for Leaflet.awesome-markers plugin v2.0 -// Project: https://github.com/lvoogdt/Leaflet.awesome-markers +// Project: https://github.com/sigma-geosistemas/Leaflet.awesome-markers#properties // Definitions by: Egor Komarov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -45,7 +45,7 @@ declare global { namespace L { /** * Color of the marker */ - markerColor?: 'red' | 'darkred' | 'orange' | 'green' | 'darkgreen' | 'blue' | 'purple' | 'darkpuple' | 'cadetblue'; + markerColor?: 'red' | 'darkred' | 'orange' | 'green' | 'darkgreen' | 'blue' | 'purple' | 'darkpurple' | 'cadetblue'; /** * Color of the icon. 'white', 'black' or css code (hex, rgba etc). diff --git a/types/leaflet-markercluster/index.d.ts b/types/leaflet.markercluster/index.d.ts similarity index 96% rename from types/leaflet-markercluster/index.d.ts rename to types/leaflet.markercluster/index.d.ts index f2323f4573..b6780ec357 100644 --- a/types/leaflet-markercluster/index.d.ts +++ b/types/leaflet.markercluster/index.d.ts @@ -3,10 +3,12 @@ // Definitions by: Robert Imig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as Leaflet from "leaflet"; -declare namespace L { - interface MarkerCluster extends L.Marker { +export = Leaflet; + +declare global { namespace L { + interface MarkerCluster extends Marker { /* * Recursively retrieve all child markers of this cluster. */ @@ -103,7 +105,7 @@ declare namespace L { /* * Function used to create the cluster icon */ - iconCreateFunction?: ((cluster: L.MarkerCluster) => L.Icon | L.DivIcon); + iconCreateFunction?: ((cluster: MarkerCluster) => Icon | DivIcon); /* * Boolean to split the addLayers processing in to small intervals so that the page does not freeze. @@ -164,4 +166,4 @@ declare namespace L { * Create a marker cluster group, optionally given marker cluster group options. */ function markerClusterGroup(options?: MarkerClusterGroupOptions): MarkerClusterGroup; -} +} } diff --git a/types/leaflet-markercluster/leaflet-markercluster-tests.ts b/types/leaflet.markercluster/leaflet.markercluster-tests.ts similarity index 98% rename from types/leaflet-markercluster/leaflet-markercluster-tests.ts rename to types/leaflet.markercluster/leaflet.markercluster-tests.ts index 73b98586e9..2a2a4969e1 100644 --- a/types/leaflet-markercluster/leaflet-markercluster-tests.ts +++ b/types/leaflet.markercluster/leaflet.markercluster-tests.ts @@ -1,3 +1,5 @@ +import L = require("leaflet.markercluster"); + const polylineOptions: L.PolylineOptions = {}; const icon: L.Icon = L.icon({ iconUrl: 'foo' }); diff --git a/types/leaflet-markercluster/tsconfig.json b/types/leaflet.markercluster/tsconfig.json similarity index 91% rename from types/leaflet-markercluster/tsconfig.json rename to types/leaflet.markercluster/tsconfig.json index d5e7d33df8..6cc587aa00 100644 --- a/types/leaflet-markercluster/tsconfig.json +++ b/types/leaflet.markercluster/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "leaflet-markercluster-tests.ts" + "leaflet.markercluster-tests.ts" ] } \ No newline at end of file diff --git a/types/leaflet.markercluster/tslint.json b/types/leaflet.markercluster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/leaflet.markercluster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lestate/index.d.ts b/types/lestate/index.d.ts index c606b93c36..ca9f6aab47 100644 --- a/types/lestate/index.d.ts +++ b/types/lestate/index.d.ts @@ -1,25 +1,21 @@ -// Type definitions for LeState v0.1.3 +// Type definitions for LeState 0.1 // Project: https://github.com/LeTools/LeState // Definitions by: Hadrian Oliveira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare let LeState : { - createState: (props?: { - initialState: {}; - }) => { - set(newValue: {}): [{ - id: number; - state: {}; - }]; - get(): any; - insert(newValue: {}): void; - getDescription(): {}; - createListener({ id, selector, force }: { - id: number; - selector: (state :any) => {}; - force?: boolean; - }): void; - }; -}; +export interface LeState { + set(newValue: {}): [{ + id: number; + state: {}; + }]; + get(): any; + insert(newValue: {}): void; + getDescription(): {}; + createListener(options: { + id: number; + selector(state: any): {}; + force?: boolean; + }): void; +} -export = LeState; +export function createState(props?: { initialState: {} }): LeState; diff --git a/types/lestate/lestate-tests.ts b/types/lestate/lestate-tests.ts index 3c2b074d2d..6eb3ad6d96 100644 --- a/types/lestate/lestate-tests.ts +++ b/types/lestate/lestate-tests.ts @@ -1,19 +1,19 @@ import LeState = require("lestate"); -let State = LeState.createState() +let State = LeState.createState(); State.set({ test : {} -}) +}); -let currentState = State.get() +let currentState = State.get(); State.insert({ test : {} -}) +}); -let currentDescription = State.getDescription() +let currentDescription = State.getDescription(); State.createListener({ id : 0, selector : state => ({ test : state.test }) -}) +}); diff --git a/types/lestate/tslint.json b/types/lestate/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/lestate/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/lodash-decorators/index.d.ts b/types/lodash-decorators/index.d.ts index 26f755813c..1085db3a3a 100644 --- a/types/lodash-decorators/index.d.ts +++ b/types/lodash-decorators/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for lodash-decorators 1.0.5 +// Type definitions for lodash-decorators 3.0 // Project: https://github.com/steelsojka/lodash-decorators -// Definitions by: Qubo +// Definitions by: Alan Agius , Qubo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -8,75 +8,56 @@ declare module "lodash-decorators" { // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts - export interface ClassDecorator { - (target: TFunction): TFunction|void; - } - export interface PropertyDecorator { - (target: Object, propertyKey: string | symbol): void; - } - export interface MethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } - export interface ParameterDecorator { - (target: Object, propertyKey: string | symbol, parameterIndex: number): void; - } - export interface TypedMethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } + type ClassDecorator = (target: TFunction) => TFunction | void; - export interface MethodDecoratorWithAccessor extends MethodDecorator, Accessor { - } + type PropertyDecorator = (target: object, propertyKey: string | symbol) => void; - export interface Accessor { + type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; + + type ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => void; + + type TypedMethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; + + interface MethodDecoratorWithAccessor extends MethodDecorator, Accessor { } + + interface Accessor { set: T; get: T; proto: T; } - export interface DebounceDecorator { - (wait: number, options?: _.DebounceSettings): MethodDecorator; - } - export interface ThrottleDecorator { - (wait: number, options?: _.ThrottleSettings): MethodDecorator; - } - export interface MemoizeDecorator { - (resolver?: Function): MethodDecorator; - } - export interface AfterDecorator { - (n: number): MethodDecorator; - } - export interface BeforeDecorator { - (n: number): MethodDecorator; - } - export interface AryDecorator { - (n: number): MethodDecorator; - } - export interface CurryDecorator { - (arity?: number): MethodDecorator; - } - export interface CurryRightDecorator { - (arity?: number): MethodDecorator; - } - export interface RestParamDecorator { - (start?: number): MethodDecorator; - } - export interface PartialDecorator { - (func: Function|string, ...args: any[]): MethodDecorator; - } - export interface WrapDecorator { - (wrapper: ((func: Function, ...args: any[]) => any)|string): MethodDecorator; - } - export interface ComposeDecorator { - (...funcs: (Function|string)[]): MethodDecorator; - } - export interface DelayDecorator { - (wait: number, ...args: any[]): MethodDecorator; - } - export interface DeferDecorator { - (...args: any[]): MethodDecorator; - } - export interface BindDecorator { + type DebounceDecorator = (wait: number, options?: _.DebounceSettings) => MethodDecorator; + + type ThrottleDecorator = (wait: number, options?: _.ThrottleSettings) => MethodDecorator; + + type MemoizeDecorator = (resolver?: Function) => MethodDecorator; + + type AfterDecorator = (n: number) => MethodDecorator; + + type BeforeDecorator = (n: number) => MethodDecorator; + + type AryDecorator = (n: number) => MethodDecorator; + + type CurryDecorator = (arity?: number) => MethodDecorator; + + type CurryRightDecorator = (arity?: number) => MethodDecorator; + + type RestDecorator = (start?: number) => MethodDecorator; + + type OverArgsDecorator = (func: Function, ...transforms: Function[]) => MethodDecorator; + + type PartialDecorator = (func: Function | string, ...args: any[]) => MethodDecorator; + + type WrapDecorator = (wrapper: ((func: Function, ...args: any[]) => any) | string) => MethodDecorator; + + type ComposeDecorator = (...funcs: Array<(Function | string)>) => MethodDecorator; + + type DelayDecorator = (wait: number, ...args: any[]) => MethodDecorator; + + type DeferDecorator = (...args: any[]) => MethodDecorator; + + interface BindDecorator { (): TypedMethodDecorator<(() => R)>; (param1?: T1): TypedMethodDecorator<((param1: T1) => R)>; @@ -91,161 +72,144 @@ declare module "lodash-decorators" { (param1?: T1, param2?: T2, param3?: T3, param4?: T4, param5?: T5, param6?: T6): TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4, param5: T5, param6: T6) => R)>; } - export interface BindAllDecorator { - (...methodNames: string[]): ClassDecorator; - } - export interface ModArgsDecorator { - (...transforms: Function[]): MethodDecorator; - } - export const debounce: DebounceDecorator & Accessor; - export const Debounce: DebounceDecorator & Accessor; + type BindAllDecorator = (...methodNames: string[]) => ClassDecorator; - export const throttle: ThrottleDecorator & Accessor; - export const Throttle: ThrottleDecorator & Accessor; + const debounce: DebounceDecorator & Accessor; + const Debounce: DebounceDecorator & Accessor; - export const memoize: MemoizeDecorator & Accessor; - export const Memoize: MemoizeDecorator & Accessor; + const throttle: ThrottleDecorator & Accessor; + const Throttle: ThrottleDecorator & Accessor; - export const after: AfterDecorator & Accessor; - export const After: AfterDecorator & Accessor; + const memoize: MemoizeDecorator & Accessor; + const Memoize: MemoizeDecorator & Accessor; - export const before: BeforeDecorator & Accessor; - export const Before: BeforeDecorator & Accessor; + const after: AfterDecorator & Accessor; + const After: AfterDecorator & Accessor; - export const ary: AryDecorator & Accessor; - export const Ary: AryDecorator & Accessor; + const before: BeforeDecorator & Accessor; + const Before: BeforeDecorator & Accessor; - export const curry: CurryDecorator & Accessor; - export const Curry: CurryDecorator & Accessor; + const ary: AryDecorator & Accessor; + const Ary: AryDecorator & Accessor; - export const curryRight: CurryRightDecorator & Accessor; - export const CurryRight: CurryRightDecorator & Accessor; + const curry: CurryDecorator & Accessor; + const Curry: CurryDecorator & Accessor; - export const restParam: RestParamDecorator & Accessor; - export const RestParam: RestParamDecorator & Accessor; + const curryRight: CurryRightDecorator & Accessor; + const CurryRight: CurryRightDecorator & Accessor; - export const partial: PartialDecorator & Accessor; - export const Partial: PartialDecorator & Accessor; + const overArgs: OverArgsDecorator & Accessor; + const OverArgs: OverArgsDecorator & Accessor; - export const partialRight: PartialDecorator & Accessor; - export const PartialRight: PartialDecorator & Accessor; + const rest: RestDecorator & Accessor; + const Rest: RestDecorator & Accessor; - export const wrap: WrapDecorator & Accessor; - export const Wrap: WrapDecorator & Accessor; + const partial: PartialDecorator & Accessor; + const Partial: PartialDecorator & Accessor; - export const compose: ComposeDecorator & Accessor; - export const Compose: ComposeDecorator & Accessor; + const partialRight: PartialDecorator & Accessor; + const PartialRight: PartialDecorator & Accessor; - export const flow: ComposeDecorator & Accessor; - export const Flow: ComposeDecorator & Accessor; + const wrap: WrapDecorator & Accessor; + const Wrap: WrapDecorator & Accessor; - export const flowRight: ComposeDecorator & Accessor; - export const FlowRight: ComposeDecorator & Accessor; + const flow: ComposeDecorator & Accessor; + const Flow: ComposeDecorator & Accessor; - export const backflow: ComposeDecorator & Accessor; - export const Backflow: ComposeDecorator & Accessor; + const flowRight: ComposeDecorator & Accessor; + const FlowRight: ComposeDecorator & Accessor; - export const delay: DelayDecorator & Accessor; - export const Delay: DelayDecorator & Accessor; + const delay: DelayDecorator & Accessor; + const Delay: DelayDecorator & Accessor; - export const defer: DeferDecorator & Accessor; - export const Defer: DeferDecorator & Accessor; + const defer: DeferDecorator & Accessor; + const Defer: DeferDecorator & Accessor; - export const bind: BindDecorator & Accessor; - export const Bind: BindDecorator & Accessor; + const bind: BindDecorator & Accessor; + const Bind: BindDecorator & Accessor; - export const bindAll: BindAllDecorator; - export const BindAll: BindAllDecorator; + const bindAll: BindAllDecorator; + const BindAll: BindAllDecorator; - export const modArgs: ModArgsDecorator & Accessor; - export const ModArgs: ModArgsDecorator & Accessor; + const once: MethodDecoratorWithAccessor; + const Once: MethodDecoratorWithAccessor; - export const once: MethodDecoratorWithAccessor; - export const Once: MethodDecoratorWithAccessor; + const attempt: MethodDecoratorWithAccessor; + const Attempt: MethodDecoratorWithAccessor; - export const spread: MethodDecoratorWithAccessor; - export const Spread: MethodDecoratorWithAccessor; + const spread: MethodDecoratorWithAccessor; + const Spread: MethodDecoratorWithAccessor; - export const rearg: MethodDecoratorWithAccessor; - export const Rearg: MethodDecoratorWithAccessor; + const rearg: MethodDecoratorWithAccessor; + const Rearg: MethodDecoratorWithAccessor; - export const negate: MethodDecoratorWithAccessor; - export const Negate: MethodDecoratorWithAccessor; + const negate: MethodDecoratorWithAccessor; + const Negate: MethodDecoratorWithAccessor; - export const tap: MethodDecoratorWithAccessor; - export const Tap: MethodDecoratorWithAccessor; + const tap: MethodDecoratorWithAccessor; + const Tap: MethodDecoratorWithAccessor; + + const flip: MethodDecoratorWithAccessor; + const Flip: MethodDecoratorWithAccessor; } declare module "lodash-decorators/extensions" { // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts - export interface ClassDecorator { - (target: TFunction): TFunction|void; - } - export interface PropertyDecorator { - (target: Object, propertyKey: string | symbol): void; - } - export interface MethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } - export interface ParameterDecorator { - (target: Object, propertyKey: string | symbol, parameterIndex: number): void; - } + type ClassDecorator = (target: TFunction) => TFunction | void; - export interface DeprecatedDecorator extends MethodDecorator, ClassDecorator { + type PropertyDecorator = (target: object, propertyKey: string | symbol) => void; + + type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; + + type ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => void; + + interface DeprecatedDecorator extends MethodDecorator, ClassDecorator { methodAction(fn: Function & { name: string }): void; } - export const deprecated: DeprecatedDecorator; - export const Deprecated: DeprecatedDecorator; + const deprecated: DeprecatedDecorator; + const Deprecated: DeprecatedDecorator; - export const writable: (writable?: boolean) => MethodDecorator; - export const Writable: (writable?: boolean) => MethodDecorator; + function writable(writable?: boolean): MethodDecorator; + function Writable(writable?: boolean): MethodDecorator; - export const configurable: (configurable?: boolean) => MethodDecorator; - export const Configurable: (configurable?: boolean) => MethodDecorator; + function configurable(configurable?: boolean): MethodDecorator; + function Configurable(configurable?: boolean): MethodDecorator; - export const returnsArg: (index?: number) => MethodDecorator; - export const ReturnsArg: (index?: number) => MethodDecorator; + function returnsArg(index?: number): MethodDecorator; + function ReturnsArg(index?: number): MethodDecorator; - export const enumerable: (enumerable?: boolean) => MethodDecorator; - export const Enumerable: (enumerable?: boolean) => MethodDecorator; + function enumerable(enumerable?: boolean): MethodDecorator; + function Enumerable(enumerable?: boolean): MethodDecorator; - export const nonenumerable: MethodDecorator; - export const Nonenumerable: MethodDecorator; + const nonenumerable: MethodDecorator; + const Nonenumerable: MethodDecorator; - export const nonconfigurable: MethodDecorator; - export const Nonconfigurable: MethodDecorator; + const nonconfigurable: MethodDecorator; + const Nonconfigurable: MethodDecorator; - export const readonly: MethodDecorator; - export const Readonly: MethodDecorator; + const readonly: MethodDecorator; + const Readonly: MethodDecorator; } declare module "lodash-decorators/validate" { // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts - export interface ClassDecorator { - (target: TFunction): TFunction|void; - } - export interface PropertyDecorator { - (target: Object, propertyKey: string | symbol): void; - } - export interface MethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } - export interface ParameterDecorator { - (target: Object, propertyKey: string | symbol, parameterIndex: number): void; - } + type ClassDecorator = (target: TFunction) => TFunction | void; - export interface TypedMethodDecorator { - (target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void; - } + type PropertyDecorator = (target: object, propertyKey: string | symbol) => void; - export interface Predicate { - (t: T): boolean; - } - type Predicates = Predicate|Predicate[]; + type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; - export interface ValidateDecorator { + type ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => void; + + type TypedMethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; + + type Predicate = (t: T) => boolean; + + type Predicates = Predicate | Array>; + + interface ValidateDecorator { (p1: Predicates): TypedMethodDecorator<((param1: T1) => R)>; (p1: Predicates, p2?: Predicates): @@ -260,13 +224,11 @@ declare module "lodash-decorators/validate" { TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4, param5: T5, param6: T6) => R)>; } - export interface ValidateReturnDecorator { - (p1: Predicates): TypedMethodDecorator<((...args: any[]) => R)>; - } + type ValidateReturnDecorator = (p1: Predicates) => TypedMethodDecorator<((...args: any[]) => R)>; - export const validate: ValidateDecorator; - export const Validate: ValidateDecorator; + const validate: ValidateDecorator; + const Validate: ValidateDecorator; - export const validateReturn: ValidateReturnDecorator; - export const ValidateReturn: ValidateReturnDecorator; + const validateReturn: ValidateReturnDecorator; + const ValidateReturn: ValidateReturnDecorator; } diff --git a/types/lodash-decorators/lodash-decorators-tests.ts b/types/lodash-decorators/lodash-decorators-tests.ts index e22d6911f3..61c23f1ddb 100644 --- a/types/lodash-decorators/lodash-decorators-tests.ts +++ b/types/lodash-decorators/lodash-decorators-tests.ts @@ -2,7 +2,7 @@ // With Arguments // -import { after, debounce, memoize, curry } from 'lodash-decorators' +import { after, debounce, memoize, curry } from 'lodash-decorators'; class Person { firstName: string; @@ -15,7 +15,7 @@ class Person { @after(3) @debounce(100) getFullName(): string { - return `${this.firstName} ${this.lastName}` + return `${this.firstName} ${this.lastName}`; } @curry(2) @@ -28,7 +28,7 @@ class Person { // Without Arguments // -import { tap } from 'lodash-decorators' +import { tap } from 'lodash-decorators'; class Person2 { firstName: string; @@ -40,7 +40,7 @@ class Person2 { @once getFullName(): string { - return `${this.firstName} ${this.lastName}` + return `${this.firstName} ${this.lastName}`; } @tap @@ -51,13 +51,13 @@ class Person2 { const person2 = new Person2(); -person2.popIt([1, 2, 3]); //=> [1, 2] +person2.popIt([1, 2, 3]); // => [1, 2] // // Partials // -import { partial, wrap } from 'lodash-decorators' +import { partial, wrap } from 'lodash-decorators'; class Person3 { firstName: string; @@ -68,7 +68,7 @@ class Person3 { } getName(type: string) { - return type === 'firstName' ? this.firstName : this.lastName + return type === 'firstName' ? this.firstName : this.lastName; } @partial('getName', 'firstName') @@ -83,7 +83,7 @@ class Person3 { } } -//by .d.ts author: a workaround to ensure type +// by .d.ts author: a workaround to ensure type interface Person3Ex extends Person3 { getUpperCaseName(): string; } @@ -97,8 +97,6 @@ person3.getUpperCaseName(); // JOE SMITH // // Composition // - -//import { kebabCase } from 'lodash'; import * as _ from 'lodash'; class Person4 { @@ -113,13 +111,13 @@ class Person4 { return `${this.firstName} ${this.lastName}`; } - @compose(_.kebabCase, 'getName') + @flow(_.kebabCase, 'getName') logName(name: string): void { console.log(name); } } -//by .d.ts author: a workaround to ensure type +// by .d.ts author: a workaround to ensure type interface Person4Ex extends Person4 { logName(): void; } @@ -133,63 +131,62 @@ person4.logName(); // joe-smith // class Person5 { - @curry(2) // <= prototype decorator @debounce(100) // <= instance decorator - getName() {} //=> Throws an error. (╯°□°)╯︵ ┻━┻ + getName() { } // => Throws an error. (╯°□°)╯︵ ┻━┻ @debounce(100) // <= instance decorator @curry(2) // <= prototype decorator - getName2() {} //=> All is well :) + getName2() { } // => All is well :) } // // Getters and Setters // -import { once, compose } from 'lodash-decorators' +import { once, flow } from 'lodash-decorators'; -function alwaysArray(value: string|string[]): string[] { +function alwaysArray(value: string | string[]): string[] { return Array.isArray(value) ? value : _.isUndefined(value) ? [] : [value]; } class Person6 { - constructor() {} + constructor() { } private nameList: string[]; - //TODO: So far, TypeScript doesn't allow to put multiple decoratoes on set/get accessors. + // TODO: So far, TypeScript doesn't allow to put multiple decoratoes on set/get accessors. // see https://github.com/Microsoft/TypeScript/issues/2249#issuecomment-141684146 - //@once.get + // @once.get get names(): string[] { - //MEMO: Resolve type inconsistency + // MEMO: Resolve type inconsistency return [this.nameList.join(' ')]; - //MEMO: Original expression in repo - //return this.nameList.join(' '); + // MEMO: Original expression in repo + // return this.nameList.join(' '); } - @compose.set(alwaysArray) + @flow.set(alwaysArray) set names(names: string[]) { this.nameList = names; } } -//by .d.ts author: a workaround to ensure type +// by .d.ts author: a workaround to ensure type interface Person6Alt { - names: string[]|string; + names: string[] | string; } const person6 = new Person6(); // nameList will always be an array. -person6.names = undefined; //=> [] -(person6 as Person6Alt).names = 'Joe'; //=> ['Joe'] -person6.names = ['Jim']; //=> ['Jim'] +person6.names = undefined; // => [] +(person6 as Person6Alt).names = 'Joe'; // => ['Joe'] +person6.names = ['Jim']; // => ['Jim'] // // Bind // -import { bind } from 'lodash-decorators' +import { bind } from 'lodash-decorators'; class Person7 { firstName: string; @@ -211,7 +208,7 @@ class Person7 { } } -//by .d.ts author: a workaround to ensure type +// by .d.ts author: a workaround to ensure type interface Person7Ex extends Person7 { getUpperCaseName(): string; } @@ -221,8 +218,7 @@ const person7 = new Person7('Joe', 'Smith') as Person7Ex; person7.getName.call(null); // Joe Smith person7.getUpperCaseName(); // JOE - -import { bindAll } from 'lodash-decorators' +import { bindAll } from 'lodash-decorators'; @bindAll() class Person8 { @@ -250,16 +246,16 @@ import { throttle } from 'lodash-decorators'; class Person9 { @throttle(1000) - doStuff() {} + doStuff() { } @throttle.proto(1000) - doStuffMore() {} + doStuffMore() { } } const person9_1 = new Person9(); const person9_2 = new Person9(); -person9_1.doStuff(); //=> Both are called +person9_1.doStuff(); // => Both are called person9_2.doStuff(); person9_1.doStuffMore(); @@ -272,26 +268,25 @@ person9_2.doStuffMore(); // Extensions // -import { deprecated } from 'lodash-decorators/extensions' +import { deprecated } from 'lodash-decorators/extensions'; // This is applied globally. deprecated.methodAction = fn => console.log(`Don't use ${fn.name}!`); @deprecated class Person10 { - constructor() {} + constructor() { } } class OtherPerson { @deprecated - fn() {} + fn() { } } -let person10 = new Person10(); //=> Warning! - -let otherPerson = new OtherPerson(); -otherPerson.fn(); //=> Don't use fn! +const person10 = new Person10(); // => Warning! +const otherPerson = new OtherPerson(); +otherPerson.fn(); // => Don't use fn! // // https://github.com/steelsojka/lodash-decorators/tree/master/src/extensions @@ -300,10 +295,10 @@ otherPerson.fn(); //=> Don't use fn! import { Writable, ReturnsArg } from 'lodash-decorators/extensions'; class Person11 { - constructor() {} + constructor() { } @Writable(false) - getName() {} + getName() { } @ReturnsArg(1) doSomething(x: any, y: any, z: any) { @@ -319,7 +314,7 @@ import { Validate } from 'lodash-decorators/validate'; class Person12 { name: string; - constructor() {} + constructor() { } @Validate(_.isString) setName(name: any) { @@ -330,7 +325,7 @@ class Person12 { class Person13 { name: string; age: number; - constructor() {} + constructor() { } @Validate( _.isString, @@ -344,9 +339,8 @@ class Person13 { const person13 = new Person13(); -person13.setData('test', 5); //=> TypeError -person13.setData('test', 12); //=> Valid - +person13.setData('test', 5); // => TypeError +person13.setData('test', 12); // => Valid // // Additional typings diff --git a/types/loopback-boot/loopback-boot-tests.ts b/types/loopback-boot/loopback-boot-tests.ts index 5b0e8d54a9..5de95d00c6 100644 --- a/types/loopback-boot/loopback-boot-tests.ts +++ b/types/loopback-boot/loopback-boot-tests.ts @@ -3,18 +3,18 @@ import * as boot from 'loopback-boot'; import * as cookieParser from 'cookie-parser'; class Server { - app: loopback.LoopBackApplication; + app: loopback.LoopBackApplication; - static boostrap(): Server { - return new Server(); - } - constructor() { - this.app = loopback(); + static boostrap(): Server { + return new Server(); + } + constructor() { + this.app = loopback(); - this.app.use(cookieParser()); + this.app.use(cookieParser()); - this.config(); - } + this.config(); + } private config(): void { boot(this.app, __dirname, (err: Error) => { diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index b7a9064f86..99c9854791 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.30.0 +// Type definitions for Mapbox GL JS v0.35.1 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,6 +9,7 @@ declare namespace mapboxgl { let accessToken: string; let version: string; export function supported(options?: {failIfMajorPerformanceCaveat?: boolean}): boolean; + export function setRTLTextPlugin(pluginURL: string, callback: Function): void; /** * Map @@ -50,7 +51,7 @@ declare namespace mapboxgl { queryRenderedFeatures(pointOrBox?: mapboxgl.Point|number[]|mapboxgl.Point[]|number[][], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; - querySourceFeatures(sourceID: string, parameters: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; + querySourceFeatures(sourceID: string, parameters?: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; setStyle(style: mapboxgl.Style | string): this; @@ -58,10 +59,18 @@ declare namespace mapboxgl { addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + isSourceLoaded(id: string): boolean; + removeSource(id: string): this; getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + addImage(name: string, image: HTMLImageElement | ArrayBufferView, options?: {width?: number, height?: number, pixelRatio?: number}): this; + + removeImage(name: string): this; + + loadImage(url: string, callback: Function): this; + addLayer(layer: mapboxgl.Layer, before?: string): this; moveLayer(id: string, beforeId?: string): this; @@ -84,6 +93,10 @@ declare namespace mapboxgl { getLayoutProperty(layer: string, name: string, klass?: string): any; + setLight(options: mapboxgl.Light, lightOptions: any): this; + + getLight(): mapboxgl.Light; + getContainer(): HTMLElement; getCanvasContainer(): HTMLElement; @@ -134,7 +147,7 @@ declare namespace mapboxgl { setPitch(pitch: number, eventData?: EventData): this; - fitBounds(bounds: mapboxgl.LngLatBounds | number[][], options?: { linear?: boolean, easing?: Function, padding?: number, offset?: Point|number[],maxZoom?: number }): this; + fitBounds(bounds: mapboxgl.LngLatBounds | number[][], options?: { linear?: boolean, easing?: Function, padding?: number | mapboxgl.PaddingOptions, offset?: Point|number[],maxZoom?: number }, eventData?: mapboxgl.EventData): this; jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; @@ -142,6 +155,8 @@ declare namespace mapboxgl { flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; + isMoving(): boolean; + stop(): this; scrollZoom: ScrollZoomHandler; @@ -201,6 +216,8 @@ declare namespace mapboxgl { /** If true, enable keyboard shortcuts (see KeyboardHandler). */ keyboard?: boolean; + logoPosition?: boolean; + /** If set, the map is constrained to the given bounds. */ maxBounds?: mapboxgl.LngLatBounds | number[][]; @@ -215,6 +232,10 @@ declare namespace mapboxgl { pitch?: number; + refreshExpiredTiles?: boolean; + + renderWorldCopies?: boolean; + /** If true, enable the "scroll to zoom" interaction */ scrollZoom?: boolean; @@ -231,6 +252,13 @@ declare namespace mapboxgl { zoom?: number; } + export class PaddingOptions extends Evented { + top: number; + bottom: number; + left: number; + right: number; + } + /** * BoxZoomHandler */ @@ -368,7 +396,7 @@ declare namespace mapboxgl { * Attribution */ export class AttributionControl extends Control { - constructor(); + constructor(options?: {compact?: boolean}); } /** @@ -378,6 +406,13 @@ declare namespace mapboxgl { constructor(options?: {maxWidth?: number, unit?: string}) } + /** + * Fullscreen + */ + export class FullscreenControl extends Control { + constructor(); + } + /** * Popup */ @@ -440,7 +475,7 @@ declare namespace mapboxgl { } export interface Source { - type: "vector" | "raster" | "geojson" | "image" | "video"; + type: "vector" | "raster" | "geojson" | "image" | "video" | "canvas"; } /** @@ -511,6 +546,29 @@ declare namespace mapboxgl { coordinates?: number[][]; } + /** + * CanvasSource + */ + export class CanvasSource implements Source, CanvasSourceOptions { + type: "canvas"; + + coordinates: number[][]; + + canvas: string; + + getCanvas(): HTMLCanvasElement; + + setCoordinates(coordinates: number[][]): this; + } + + export interface CanvasSourceOptions { + coordinates: number[][]; + + animate?: boolean; + + canvas: string; + } + interface VectorSource extends Source { type: "vector"; url?: string; @@ -540,6 +598,8 @@ declare namespace mapboxgl { /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ wrap(): mapboxgl.LngLat; + wrapToBestWorld(center: mapboxgl.LngLat): mapboxgl.LngLat; + /** Return a LngLat as an array */ toArray(): number[]; @@ -665,8 +725,12 @@ declare namespace mapboxgl { export class Evented { on(type: string, listener: Function): this; + on(type: string, layer: string, listener: Function): this; + off(type?: string | any, listener?: Function): this; + off(type?: string | any, layer?: string, listener?: Function): this; + once(type: string, listener: Function): this; fire(type: string, data?: mapboxgl.EventData | Object): this; @@ -810,7 +874,7 @@ declare namespace mapboxgl { export interface Layer { id: string; - type?: "fill" | "line" | "symbol" | "circle" | "raster" | "background" | string; //TODO: Ideally we wouldn't accept string here, just these specific strings + type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background"; metadata?: any; ref?: string; @@ -834,6 +898,7 @@ declare namespace mapboxgl { property?: string; base?: number; type?: "identity" | "exponential" | "interval" | "categorical"; + default?: any; "colorSpace"?: "rgb" | "lab" | "interval"; } @@ -881,14 +946,14 @@ declare namespace mapboxgl { "line-round-limit"?: number; } export interface LinePaint { - "line-opacity"?: number; + "line-opacity"?: number | StyleFunction; "line-color"?: string| StyleFunction; "line-translate"?: number[]; "line-translate-anchor"?: "map" | "viewport"; "line-width"?: number; - "line-gap-width"?: number; - "line-offset"?: number; - "line-blur"?: number; + "line-gap-width"?: number | StyleFunction; + "line-offset"?: number | StyleFunction; + "line-blur"?: number | StyleFunction; "line-dasharray"?: number[]; "line-dasharray-transition"?: Transition; "line-pattern"?: string; @@ -904,29 +969,29 @@ declare namespace mapboxgl { "icon-ignore-placement"?: boolean; "icon-optional"?: boolean; "icon-rotation-alignment"?: "map" | "viewport" | "auto"; - "icon-size"?: number; + "icon-size"?: number | StyleFunction; "icon-text-fit"?: "none" | "both" | "width" | "height"; "icon-text-fit-padding"?: number[]; - "icon-image"?: string; + "icon-image"?: string | StyleFunction; "icon-rotate"?: number | StyleFunction; "icon-padding"?: number; "icon-keep-upright"?: boolean; "icon-offset"?: number[] | StyleFunction; "text-pitch-alignment"?: "map" | "viewport" | "auto"; "text-rotation-alignment"?: "map" | "viewport" | "auto"; - "text-field"?: string; + "text-field"?: string | StyleFunction; "text-font"?: string | string[]; - "text-size"?: number; + "text-size"?: number | StyleFunction; "text-max-width"?: number; "text-line-height"?: number; "text-letter-spacing"?: number; "text-justify"?: "left" | "center" | "right"; "text-anchor"?: "center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right"; "text-max-angle"?: number; - "text-rotate"?: number; + "text-rotate"?: number | StyleFunction; "text-padding"?: number; "text-keep-upright"?: boolean; - "text-transform"?: "none" | "uppercase" | "lowercase"; + "text-transform"?: "none" | "uppercase" | "lowercase" | StyleFunction; "text-offset"?: number[]; "text-allow-overlap"?: boolean; "text-ignore-placement"?: boolean; @@ -934,18 +999,18 @@ declare namespace mapboxgl { } export interface SymbolPaint { - "icon-opacity"?: number; - "icon-color"?: string; - "icon-halo-color"?: string; - "icon-halo-width"?: number; - "icon-halo-blur"?: number; + "icon-opacity"?: number | StyleFunction; + "icon-color"?: string | StyleFunction; + "icon-halo-color"?: string | StyleFunction; + "icon-halo-width"?: number | StyleFunction; + "icon-halo-blur"?: number | StyleFunction; "icon-translate"?: number[]; "icon-translate-anchor"?: "map" | "viewport"; - "text-opacity"?: number; - "text-color"?: "string"; - "text-halo-color"?: "string"; - "text-halo-width"?: number; - "text-halo-blur"?: number; + "text-opacity"?: number | StyleFunction; + "text-color"?: string | StyleFunction; + "text-halo-color"?: string | StyleFunction; + "text-halo-width"?: number | StyleFunction; + "text-halo-blur"?: number | StyleFunction; "text-translate"?: number[]; "text-translate-anchor"?: "map" | "viewport"; } diff --git a/types/markdown-it-container/index.d.ts b/types/markdown-it-container/index.d.ts new file mode 100644 index 0000000000..f2d3722a3d --- /dev/null +++ b/types/markdown-it-container/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for MarkdownItContainer (markdown-it-container) 2.0 +// Project: https://github.com/markdown-it/markdown-it-container +// Definitions by: Vyacheslav Demot +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { MarkdownIt, Token, Renderer } from 'markdown-it'; + +declare namespace markdownItContainer { + interface ContainerOpts { + marker?: string; + validate?(params: string): boolean; + render?(tokens: Token[], index: number, options: any, env: any, self: Renderer): void; + } + + function container_plugin(md: MarkdownIt, name: string, opts: ContainerOpts): void; +} + +declare var MarkdownItContainer: typeof markdownItContainer.container_plugin; +export = MarkdownItContainer; diff --git a/types/markdown-it-container/markdown-it-container-tests.ts b/types/markdown-it-container/markdown-it-container-tests.ts new file mode 100644 index 0000000000..f3ef2dbba1 --- /dev/null +++ b/types/markdown-it-container/markdown-it-container-tests.ts @@ -0,0 +1,32 @@ +import * as MarkdownIt from "markdown-it"; +import MarkdownItContainer = require("markdown-it-container"); + +const md = new MarkdownIt(); + +md.use(MarkdownItContainer, 'spoiler', { + validate: (params: any) => params.trim().match(/^spoiler\s+(.*)$/), + render: (tokens: MarkdownIt.Token[], index: number) => { + const match = tokens[index].info.trim().match(/^spoiler\s+(.*)$/); + const onClick = + "this.parentNode.classList.toggle('_expanded');" + + "event.preventDefault();"; + + if (tokens[index].nesting === 1) { + return ( + '
\n' + + '
\n' + + md.utils.escapeHtml(match && match[1] || '') + '\n' + + '
\n' + + '
\n' + ); + } else { + return '
\n'; + } + } +}); + +const src = `:::spoiler This Is Spoiler Title +Here is spoiler content. +:::`; + +md.render(src); diff --git a/types/markdown-it-container/tsconfig.json b/types/markdown-it-container/tsconfig.json new file mode 100644 index 0000000000..270b4284f0 --- /dev/null +++ b/types/markdown-it-container/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "markdown-it-container-tests.ts" + ] +} \ No newline at end of file diff --git a/types/markdown-it-container/tslint.json b/types/markdown-it-container/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/markdown-it-container/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 9c815ada38..ce98d40903 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -823,6 +823,8 @@ declare namespace __MaterialUI { titleColor?: string; titleStyle?: React.CSSProperties; className?: string; + openIcon?: React.ReactNode; + closeIcon?: React.ReactNode; } export class CardHeader extends React.Component { } diff --git a/types/microsoft-ajax/index.d.ts b/types/microsoft-ajax/index.d.ts index 6c6d34dc9d..27aeeb441f 100644 --- a/types/microsoft-ajax/index.d.ts +++ b/types/microsoft-ajax/index.d.ts @@ -1406,6 +1406,31 @@ declare namespace Sys { */ static nullWebRequest: string; + /** + * @return "'{0}' is not an event." + */ + static undefinedEvent: string; + + /** + * @return "Handler must be a function." + */ + static eventHandlerNotFunction: string; + + /** + * @return "'{0}' is not a property or an existing field." + */ + static propertyUndefined: string; + + /** + * @return "'{0}' is not an Array property." + */ + static propertyNotAnArray: string; + + /** + * @return "'{0}' is not a writable property." + */ + static propertyNotWritable: string; + //#endregion } diff --git a/types/microsoft-ajax/microsoft-ajax-tests.ts b/types/microsoft-ajax/microsoft-ajax-tests.ts index fb0ebff654..d392dbbe2c 100644 --- a/types/microsoft-ajax/microsoft-ajax-tests.ts +++ b/types/microsoft-ajax/microsoft-ajax-tests.ts @@ -548,6 +548,11 @@ function Sys_Res_Tests() { var invokeCalledTwice = Sys.Res.invokeCalledTwice; var notImplemented = Sys.Res.notImplemented; var nullWebRequest = Sys.Res.nullWebRequest; + var undefinedEvent = Sys.Res.undefinedEvent; + var eventHandlerNotFunction = Sys.Res.eventHandlerNotFunction; + var propertyUndefined = Sys.Res.propertyUndefined; + var propertyNotAnArray = Sys.Res.propertyNotAnArray; + var propertyNotWritable = Sys.Res.propertyNotWritable; } function Sys_StringBuilder_Tests() { diff --git a/types/mithril/index.d.ts b/types/mithril/index.d.ts index 1115d7c1f5..46fbb061ab 100644 --- a/types/mithril/index.d.ts +++ b/types/mithril/index.d.ts @@ -61,11 +61,11 @@ declare namespace Mithril { trust(html: string): Vnode; } - interface RouteResolver { + interface RouteResolver { /** The onmatch hook is called when the router needs to find a component to render. */ - render?(this: State, vnode: Vnode): Children; + onmatch?(this: this, args: Attrs, requestedPath: string): Component | Promise | void; /** The render method is called on every redraw for a matching route. */ - onmatch?(args: Params, requestedPath: string): Component | Promise | void; + render?(this: this, vnode: Vnode): Children; } /** This represents a key-value mapping linking routes to components. */ @@ -232,7 +232,7 @@ declare namespace Mithril { /** The onremove hook is called before a DOM element is removed from the document. */ onupdate?(vnode: VnodeDOM): any; /** Creates a view out of virtual elements. */ - view(vnode: CVnode): Children | null | void; + view(vnode: Vnode): Children | null | void; } /** diff --git a/types/mithril/test/test-class-component.ts b/types/mithril/test/test-class-component.ts index 7c1348683e..19f3aa343a 100644 --- a/types/mithril/test/test-class-component.ts +++ b/types/mithril/test/test-class-component.ts @@ -1,5 +1,5 @@ import * as m from 'mithril'; -import {ClassComponent, CVnode, CVnodeDOM} from 'mithril'; +import {ClassComponent, Vnode, CVnode, CVnodeDOM} from 'mithril'; /////////////////////////////////////////////////////////// // 0. @@ -95,12 +95,13 @@ class Comp4 implements ClassComponent { add(num: number) { this.count += num; } - view({attrs}: CVnode) { + view(vnode: Vnode) { return [ - m('h1', `This ${attrs.name} has been clicked ${this.count} times`), + m('h1', `This ${vnode.attrs.name} has been clicked ${this.count} times`), m('button', { - onclick: () => this.add(1) + // Can access 'this' via vnode.state + onclick: () => vnode.state.add(1) }, "Click me") ]; @@ -129,7 +130,7 @@ export interface Attrs { export default class MyComponent implements ClassComponent { count = 0; - view({attrs}: CVnode) { + view({attrs}: Vnode) { return m('span', `name: ${attrs.name}, count: ${this.count}`); } } diff --git a/types/mithril/test/test-route.ts b/types/mithril/test/test-route.ts index 5e584a8184..b18a92212c 100644 --- a/types/mithril/test/test-route.ts +++ b/types/mithril/test/test-route.ts @@ -1,4 +1,4 @@ -import {Component} from 'mithril'; +import {Component, Comp, RouteResolver} from 'mithril'; import * as h from 'mithril/hyperscript'; import * as route from 'mithril/route'; @@ -14,6 +14,39 @@ const component2 = { } } as Component<{title: string}, {}>; +interface Attrs { + id: string; +} + +interface State { + text: string; +} + +const component3: Comp = { + text: "Uninitialized", + oninit({state}) { + state.text = "Initialized"; + }, + view({attrs}) { + return h('p', 'id: ' + attrs.id); + } +}; + +// RouteResolver example using Attrs type and this context +const routeResolver: RouteResolver & {message: string} = { + message: "", + onmatch(attrs, path) { + this.message = "Match"; + const id: string = attrs.id; + return component3; + }, + render(vnode) { + this.message = "Render"; + vnode.key = vnode.attrs.id; + return vnode; + } +}; + route(document.body, '/', { '/': component1, '/test1': { @@ -41,7 +74,8 @@ route(document.body, '/', { resolve(component2); }); } - } + }, + 'test5/:id': routeResolver }); route.prefix('/app'); diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 859dc87b26..5fe6332350 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -35,6 +35,7 @@ export interface MongoCallback { export class MongoError extends Error { constructor(message: string); static create(options: Object): MongoError; + code?: number; } //http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html#.connect @@ -634,7 +635,7 @@ export interface CollectionAggregationOptions { allowDiskUse?: boolean; // specifies a cumulative time limit in milliseconds for processing operations // on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - maxTimeMS?: boolean; + maxTimeMS?: number; // Allow driver to bypass schema validation in MongoDB 3.2 or higher. bypassDocumentValidation?: boolean; } diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index 80dbf2cf43..390f487444 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -176,6 +176,7 @@ export declare class ConnectionPool extends events.EventEmitter { public driver: string; public constructor(config: config, callback?: (err?: any) => void); public constructor(connectionString: string, callback?: (err?: any) => void); + public query(strings: TemplateStringsArray, ...interpolations: any[]): Promise>; public connect(): Promise; public connect(callback: (err: any) => void): void; public close(): Promise; @@ -235,7 +236,6 @@ export declare class Request extends events.EventEmitter { public input(name: string, type: any, value: any): Request; public output(name: string, type: any, value?: any): Request; public pipe(stream: NodeJS.WritableStream): NodeJS.WritableStream; - public query(strings: TemplateStringsArray, ...interpolations: any[]): Promise>; public query(command: string): Promise>; public query(command: string): Promise>; public query(command: string, callback: (err?: Error, recordset?: IResult) => void): void; diff --git a/types/mssql/mssql-tests.ts b/types/mssql/mssql-tests.ts index 4bda996f85..c5e4535e44 100644 --- a/types/mssql/mssql-tests.ts +++ b/types/mssql/mssql-tests.ts @@ -26,6 +26,7 @@ var connection: sql.ConnectionPool = new sql.ConnectionPool(config, function (er console.warn("Issue with connecting to SQL Server!"); } else { + connection.query`SELECT ${1} as value`.then(res => { }); var requestQuery = new sql.Request(connection); var getArticlesQuery = "SELECT * FROM TABLE"; @@ -150,7 +151,6 @@ function test_promise_returns() { request.bulk(new sql.Table("table_name")).then(() => { }); request.query('SELECT 1').then((recordset) => { }); request.query('SELECT 1 as value').then(res => { }); - request.query`SELECT ${1} as value`.then(res => { }); request.execute('procedure_name').then((recordset) => { }); } diff --git a/types/multer-gridfs-storage/index.d.ts b/types/multer-gridfs-storage/index.d.ts new file mode 100644 index 0000000000..752609b4e3 --- /dev/null +++ b/types/multer-gridfs-storage/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for multer-gridfs-storage 1.1 +// Project: https://github.com/devconcept/multer-gridfs-storage +// Definitions by: devconcept +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import {EventEmitter} from 'events'; +import {Express} from 'express'; +import * as Multer from 'multer'; +import {Grid} from 'gridfs-stream'; + +type logConfig = 'file' | 'all'; + +interface StorageLog { + message: string; + extra: any; +} + +type NodeCb = (err: Error | null, value: T | null) => void; + +type ConfigFn = (req: Express.Request, file: Express.Multer.File, cb: T) => void; + +// TODO: PR and add this interface to the mongodb types +interface GridFile { + _id: any; + filename: string; + contentType: string; + length: number; + chunkSize: number; + uploadDate: Date; + aliases: any; + metadata: any; + md5: string; +} + +interface MulterGfsOptions { + filename?: ConfigFn>; + identifier?: ConfigFn>; + metadata?: ConfigFn>; + chunkSize?: number | ConfigFn>; + root?: string | ConfigFn>; + log?: boolean | NodeCb; + logLevel?: logConfig; +} + +declare class MulterGridfsStorage extends EventEmitter implements Multer.StorageEngine { + constructor(settings: MulterGridfsStorage.UrlStorageOptions | MulterGridfsStorage.GfsStorageOptions); + + _handleFile(req: Express.Request, file: Express.Multer.File, callback: (error?: any, info?: Express.Multer.File) => void): void; + + _removeFile(req: Express.Request, file: Express.Multer.File, callback: (error: Error) => void): void; +} + +declare namespace MulterGridfsStorage { + interface UrlStorageOptions extends MulterGfsOptions { + url: string; + } + + interface GfsStorageOptions extends MulterGfsOptions { + gfs: Promise | Grid; + } +} + +// Merge multer's file declaration with ours +declare global { + namespace Express { + namespace Multer { + interface File { + filename: string; + metadata: any; + id: any; + grid: GridFile; + size: number; + } + } + } +} + +export = MulterGridfsStorage; diff --git a/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts b/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts new file mode 100644 index 0000000000..229fd7877d --- /dev/null +++ b/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts @@ -0,0 +1,43 @@ +import * as MulterGridfsStorage from 'multer-gridfs-storage'; +import {Grid} from "gridfs-stream"; + +// Exported interfaces +let opt1: MulterGridfsStorage.GfsStorageOptions; +let opt2: MulterGridfsStorage.UrlStorageOptions; + +// All options +let gfsCtr = new MulterGridfsStorage({ + gfs: new Grid(), + filename: (req, file, cb) => cb(null, ''), + chunkSize: (req, file, cb) => cb(null, 1), + identifier: (req, file, cb) => cb(null, ''), + metadata: (req, file, cb) => cb(new Error(), null), + logLevel: 'all', + root: (req, file, cb) => cb(null, 'unicorns') +}); + +let urlCtr = new MulterGridfsStorage({ + url: '', + filename: (req, file, cb) => cb(null, ''), + chunkSize: (req, file, cb) => cb(null, 1), + identifier: (req, file, cb) => cb(null, ''), + metadata: (req, file, cb) => cb(new Error(), {}), + logLevel: 'all', + root: (req, file, cb) => cb(null, '') +}); + +// Other properties are optional +let gfsOnly = new MulterGridfsStorage({ + gfs: new Grid() +}); + +let urlOnly = new MulterGridfsStorage({ + url: '' +}); + +function noop() { +} +// Extends event emitter +gfsCtr.on('connection', noop); +urlCtr.addListener('conection', noop); +gfsOnly.removeAllListeners('conection'); diff --git a/types/multer-gridfs-storage/tsconfig.json b/types/multer-gridfs-storage/tsconfig.json new file mode 100644 index 0000000000..46054115e0 --- /dev/null +++ b/types/multer-gridfs-storage/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "multer-gridfs-storage-tests.ts" + ] +} diff --git a/types/multer-gridfs-storage/tslint.json b/types/multer-gridfs-storage/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/multer-gridfs-storage/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ndarray/index.d.ts b/types/ndarray/index.d.ts index 52d86ff0c8..f409e7fe74 100644 --- a/types/ndarray/index.d.ts +++ b/types/ndarray/index.d.ts @@ -1,34 +1,36 @@ -// Type definitions for ndarray v1.0.18 +// Type definitions for ndarray 1.0 // Project: https://github.com/scijs/ndarray // Definitions by: Giff Song // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -type Data = Array | Int8Array | Int16Array | Int32Array | - Uint8Array | Uint16Array | Uint32Array | - Float32Array | Float64Array | Uint8ClampedArray; - -interface ndarray { - data: Data; - shape: number[]; - stride: number[]; - offset: number; - dtype: 'int8' | 'int16' | 'int32' | 'uint8' | 'uint16' |'uint32' | - 'float32' | 'float64' | 'array'| 'uint8_clamped' | 'buffer' | 'generic'; - size: number; - order: number[]; - dimension: number; - get(...args: number[]): number; - set(...args: number[]): number; - index(...args: number[]): number; - lo(...args: number[]): ndarray; - hi(...args: number[]): ndarray; - step(...args: number[]): ndarray; - transpose(...args: number[]): ndarray; - pick(...args: number[]): ndarray; -} - declare function ndarray( - data: Data, shape?: number[], stride?: number[], offset?: number + data: ndarray.Data, shape?: number[], stride?: number[], offset?: number ): ndarray; +interface ndarray { + data: ndarray.Data; + shape: number[]; + stride: number[]; + offset: number; + dtype: 'int8' | 'int16' | 'int32' | 'uint8' | 'uint16' | 'uint32' | + 'float32' | 'float64' | 'array' | 'uint8_clamped' | 'buffer' | 'generic'; + size: number; + order: number[]; + dimension: number; + get(...args: number[]): number; + set(...args: number[]): number; + index(...args: number[]): number; + lo(...args: number[]): ndarray; + hi(...args: number[]): ndarray; + step(...args: number[]): ndarray; + transpose(...args: number[]): ndarray; + pick(...args: number[]): ndarray; +} + +declare namespace ndarray { + type Data = number[] | Int8Array | Int16Array | Int32Array | + Uint8Array | Uint16Array | Uint32Array | + Float32Array | Float64Array | Uint8ClampedArray; +} + export = ndarray; diff --git a/types/ndarray/ndarray-tests.ts b/types/ndarray/ndarray-tests.ts index a72a9acad5..899f43efd5 100644 --- a/types/ndarray/ndarray-tests.ts +++ b/types/ndarray/ndarray-tests.ts @@ -1,5 +1,4 @@ - -import ndarray = require('ndarray'); +import * as ndarray from 'ndarray'; const data = new Int32Array(2 * 2 * 2 + 10); const a = ndarray(data, [2, 2, 2], [1, 2, 4], 5); diff --git a/types/ndarray/tslint.json b/types/ndarray/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/ndarray/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/nedb/index.d.ts b/types/nedb/index.d.ts index d85016493e..15a2fd4e83 100644 --- a/types/nedb/index.d.ts +++ b/types/nedb/index.d.ts @@ -60,7 +60,7 @@ declare class Nedb { * If one update violates a constraint, all changes are rolled back */ updateIndexes(oldDoc: T, newDoc: T): void; - updateIndexes(updates: Array<{oldDoc: T; newDoc: T}>): void; + updateIndexes(updates: Array<{ oldDoc: T; newDoc: T }>): void; /** * Return the list of candidates for a given query diff --git a/types/nedb/nedb-tests.ts b/types/nedb/nedb-tests.ts index 9b5527051c..47af1b137f 100644 --- a/types/nedb/nedb-tests.ts +++ b/types/nedb/nedb-tests.ts @@ -54,7 +54,7 @@ class BaseCollection { findByID(id: string): Promise { return new Promise((resolve, reject) => { - this.dataStore.findOne({_id: id}, (err: Error, doc: T) => { + this.dataStore.findOne({ _id: id }, (err: Error, doc: T) => { if (err) { reject(err); } else { @@ -102,7 +102,7 @@ class BaseCollection { upsert(query: any, updateQuery: any): Promise { const a: Promise = new Promise((resolve, reject) => { - this.dataStore.update(query, updateQuery, {upsert: true}, (err: Error, numberOfUpdated: number, upsert: boolean) => { + this.dataStore.update(query, updateQuery, { upsert: true }, (err: Error, numberOfUpdated: number, upsert: boolean) => { if (err) { reject(err); } else { @@ -112,7 +112,7 @@ class BaseCollection { }); const b: Promise = new Promise((resolve, reject) => { - this.dataStore.update(query, updateQuery, {upsert: true}, (err: Error, numberOfUpdated: number, affectedDocs: any, upsert: boolean) => { + this.dataStore.update(query, updateQuery, { upsert: true }, (err: Error, numberOfUpdated: number, affectedDocs: any, upsert: boolean) => { if (err) { reject(err); } else { @@ -154,19 +154,19 @@ import Datastore = require('nedb'); let db = new Datastore(); // Type 2: Persistent datastore with manual loading -db = new Datastore({filename: 'path/to/datafile'}); +db = new Datastore({ filename: 'path/to/datafile' }); db.loadDatabase((err) => { // Callback is optional // Now commands will be executed }); // Type 3: Persistent datastore with automatic loading -db = new Datastore({filename: 'path/to/datafile', autoload: true}); +db = new Datastore({ filename: 'path/to/datafile', autoload: true }); // You can issue commands right away // Type 4: Persistent datastore for a Node Webkit app called 'nwtest' // For example on Linux, the datafile will be ~/.config/nwtest/nedb-data/something.db import path = require('path'); -db = new Datastore({filename: path.join(require('nw.gui').App.dataPath, 'something.db')}); +db = new Datastore({ filename: path.join(require('nw.gui').App.dataPath, 'something.db') }); // Of course you can create multiple datastores if you need several // collections. In this case it's usually a good idea to use autoload for all collections. @@ -179,14 +179,14 @@ dbContainer.users.loadDatabase(); dbContainer.robots.loadDatabase(); const doc: any = { - hello: 'world' - , n: 5 - , today: new Date() - , nedbIsAwesome: true - , notthere: null - , notToBeSaved: undefined // Will not be saved - , fruits: ['apple', 'orange', 'pear'] - , infos: {name: 'nedb'} + hello: 'world', + n: 5, + today: new Date(), + nedbIsAwesome: true, + notthere: null, + notToBeSaved: undefined, // Will not be saved + fruits: ['apple', 'orange', 'pear'], + infos: { name: 'nedb' } }; db.insert(doc, (err: Error, newDoc: any) => { // Callback is optional @@ -194,54 +194,54 @@ db.insert(doc, (err: Error, newDoc: any) => { // Callback is optional // newDoc has no key called notToBeSaved since its value was undefined }); -db.insert([{a: 5}, {a: 42}], (err: Error, newdocs: any[]) => { +db.insert([{ a: 5 }, { a: 42 }], (err: Error, newdocs: any[]) => { // Two documents were inserted in the database // newDocs is an array with these documents, augmented with their _id }); // If there is a unique constraint on field 'a', this will fail -db.insert([{a: 5}, {a: 42}, {a: 5}], (err: Error) => { +db.insert([{ a: 5 }, { a: 42 }, { a: 5 }], (err: Error) => { // err is a 'uniqueViolated' error // The database was not modified }); // Finding all planets in the solar system -db.find({system: 'solar'}, (err: Error, docs: any[]) => { +db.find({ system: 'solar' }, (err: Error, docs: any[]) => { // docs is an array containing documents Mars, Earth, Jupiter // If no document is found, docs is equal to [] }); // Finding all planets whose name contain the substring 'ar' using a regular expression -db.find({planet: /ar/}, (err: Error, docs: any[]) => { +db.find({ planet: /ar/ }, (err: Error, docs: any[]) => { // docs contains Mars and Earth }); // Finding all inhabited planets in the solar system -db.find({system: 'solar', inhabited: true}, (err: Error, docs: any[]) => { +db.find({ system: 'solar', inhabited: true }, (err: Error, docs: any[]) => { // docs is an array containing document Earth only }); // Use the dot-notation to match fields in subdocuments -db.find({"humans.genders": 2}, (err: Error, docs: any[]) => { +db.find({ "humans.genders": 2 }, (err: Error, docs: any[]) => { // docs contains Earth }); // Use the dot-notation to navigate arrays of subdocuments -db.find({"completeData.planets.name": "Mars"}, (err: Error, docs: any[]) => { +db.find({ "completeData.planets.name": "Mars" }, (err: Error, docs: any[]) => { // docs contains document 5 }); -db.find({"completeData.planets.name": "Jupiter"}, (err: Error, docs: any[]) => { +db.find({ "completeData.planets.name": "Jupiter" }, (err: Error, docs: any[]) => { // docs is empty }); -db.find({"completeData.planets.0.name": "Earth"}, (err: Error, docs: any[]) => { +db.find({ "completeData.planets.0.name": "Earth" }, (err: Error, docs: any[]) => { // docs contains document 5 // If we had tested against "Mars" docs would be empty because we are matching against a specific array element }); // You can also deep-compare objects. Don't confuse this with dot-notation! -db.find({humans: {genders: 2}}, (err: Error, docs: any[]) => { +db.find({ humans: { genders: 2 } }, (err: Error, docs: any[]) => { // docs is empty, because { genders: 2 } is not equal to { genders: 2, eyes: true } }); @@ -250,66 +250,66 @@ db.find({}, (err: Error, docs: any[]) => { }); // The same rules apply when you want to only find one document -db.findOne({_id: 'id1'}, (err: Error, doc: any) => { +db.findOne({ _id: 'id1' }, (err: Error, doc: any) => { // doc is the document Mars // If no document is found, doc is null }); // $lt, $lte, $gt and $gte work on numbers and strings -db.find({"humans.genders": {$gt: 5}}, (err: Error, docs: any[]) => { +db.find({ "humans.genders": { $gt: 5 } }, (err: Error, docs: any[]) => { // docs contains Omicron Persei 8, whose humans have more than 5 genders (7). }); // When used with strings, lexicographical order is used -db.find({planet: {$gt: 'Mercury'}}, (err: Error, docs: any[]) => { +db.find({ planet: { $gt: 'Mercury' } }, (err: Error, docs: any[]) => { // docs contains Omicron Persei 8 }); // Using $in. $nin is used in the same way -db.find({planet: {$in: ['Earth', 'Jupiter']}}, (err: Error, docs: any[]) => { +db.find({ planet: { $in: ['Earth', 'Jupiter'] } }, (err: Error, docs: any[]) => { // docs contains Earth and Jupiter }); // Using $exists -db.find({satellites: {$exists: true}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $exists: true } }, (err: Error, docs: any[]) => { // docs contains only Mars }); // Using $regex with another operator -db.find({planet: {$regex: /ar/, $nin: ['Jupiter', 'Earth']}}, (err: Error, docs: any[]) => { +db.find({ planet: { $regex: /ar/, $nin: ['Jupiter', 'Earth'] } }, (err: Error, docs: any[]) => { // docs only contains Mars because Earth was excluded from the match by $nin }); // Using an array-specific comparison function // Note: you can't use nested comparison functions, e.g. { $size: { $lt: 5 } } will throw an error -db.find({satellites: {$size: 2}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $size: 2 } }, (err: Error, docs: any[]) => { // docs contains Mars }); -db.find({satellites: {$size: 1}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $size: 1 } }, (err: Error, docs: any[]) => { // docs is empty }); // If a document's field is an array, matching it means matching any element of the array -db.find({satellites: 'Phobos'}, (err: Error, docs: any[]) => { +db.find({ satellites: 'Phobos' }, (err: Error, docs: any[]) => { // docs contains Mars. Result would have been the same if query had been { satellites: 'Deimos' } }); // This also works for queries that use comparison operators -db.find({satellites: {$lt: 'Amos'}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $lt: 'Amos' } }, (err: Error, docs: any[]) => { // docs is empty since Phobos and Deimos are after Amos in lexicographical order }); // This also works with the $in and $nin operator -db.find({satellites: {$in: ['Moon', 'Deimos']}}, (err: Error, docs: any[]) => { +db.find({ satellites: { $in: ['Moon', 'Deimos'] } }, (err: Error, docs: any[]) => { // docs contains Mars (the Earth document is not complete!) }); -db.find({$or: [{planet: 'Earth'}, {planet: 'Mars'}]}, (err: Error, docs: any[]) => { +db.find({ $or: [{ planet: 'Earth' }, { planet: 'Mars' }] }, (err: Error, docs: any[]) => { // docs contains Earth and Mars }); -db.find({$not: {planet: 'Earth'}}, (err: Error, docs: any[]) => { +db.find({ $not: { planet: 'Earth' } }, (err: Error, docs: any[]) => { // docs contains Mars, Jupiter, Omicron Persei 8 }); @@ -322,53 +322,53 @@ db.find({ }); // You can mix normal queries, comparison queries and logical operators -db.find({$or: [{planet: 'Earth'}, {planet: 'Mars'}], inhabited: true}, (err: Error, docs: any[]) => { +db.find({ $or: [{ planet: 'Earth' }, { planet: 'Mars' }], inhabited: true }, (err: Error, docs: any[]) => { // docs contains Earth }); // No query used means all results are returned (before the Cursor modifiers) -db.find({}).sort({planet: 1}).skip(1).limit(2).exec((err: Error, docs: any[]) => { +db.find({}).sort({ planet: 1 }).skip(1).limit(2).exec((err: Error, docs: any[]) => { // docs is [doc3, doc1] }); // You can sort in reverse order like this -db.find({system: 'solar'}).sort({planet: -1}).exec((err: Error, docs: any[]) => { +db.find({ system: 'solar' }).sort({ planet: -1 }).exec((err: Error, docs: any[]) => { // docs is [doc1, doc3, doc2] }); // You can sort on one field, then another, and so on like this: -db.find({}).sort({firstField: 1, secondField: -1}); +db.find({}).sort({ firstField: 1, secondField: -1 }); // Same database as above // Keeping only the given fields -db.find({planet: 'Mars'}, {planet: 1, system: 1}, (err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }, { planet: 1, system: 1 }, (err: Error, docs: any[]) => { // docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }] }); // Keeping only the given fields but removing _id -db.find({planet: 'Mars'}, {planet: 1, system: 1, _id: 0}, (err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }, { planet: 1, system: 1, _id: 0 }, (err: Error, docs: any[]) => { // docs is [{ planet: 'Mars', system: 'solar' }] }); // Omitting only the given fields and removing _id -db.find({planet: 'Mars'}, {planet: 0, system: 0, _id: 0}, (err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }, { planet: 0, system: 0, _id: 0 }, (err: Error, docs: any[]) => { // docs is [{ inhabited: false, satellites: ['Phobos', 'Deimos'] }] }); // Failure: using both modes at the same time -db.find({planet: 'Mars'}, {planet: 0, system: 1}, (err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }, { planet: 0, system: 1 }, (err: Error, docs: any[]) => { // err is the error message, docs is undefined }); // You can also use it in a Cursor way but this syntax is not compatible with MongoDB // If upstream compatibility is important don't use this method -db.find({planet: 'Mars'}).projection({planet: 1, system: 1}).exec((err: Error, docs: any[]) => { +db.find({ planet: 'Mars' }).projection({ planet: 1, system: 1 }).exec((err: Error, docs: any[]) => { // docs is [{ planet: 'Mars', system: 'solar', _id: 'id1' }] }); // Count all planets in the solar system -db.count({system: 'solar'}, (err: Error, count: number) => { +db.count({ system: 'solar' }, (err: Error, count: number) => { // count equals to 3 }); @@ -384,7 +384,7 @@ db.count({}, (err: Error, count: number) => { // { _id: 'id4', planet: 'Omicron Persia 8', system: 'futurama', inhabited: true } // Replace a document by another -db.update({planet: 'Jupiter'}, {planet: 'Pluton'}, {}, (err: Error, numReplaced: number) => { +db.update({ planet: 'Jupiter' }, { planet: 'Pluton' }, {}, (err: Error, numReplaced: number) => { // numReplaced = 1 // The doc #3 has been replaced by { _id: 'id3', planet: 'Pluton' } // Note that the _id is kept unchanged, and the document has been replaced @@ -392,19 +392,19 @@ db.update({planet: 'Jupiter'}, {planet: 'Pluton'}, {}, (err: Error, numReplaced: }); // Set an existing field's value -db.update({system: 'solar'}, {$set: {system: 'solar system'}}, {multi: true}, (err: Error, numReplaced: number) => { +db.update({ system: 'solar' }, { $set: { system: 'solar system' } }, { multi: true }, (err: Error, numReplaced: number) => { // numReplaced = 3 // Field 'system' on Mars, Earth, Jupiter now has value 'solar system' }); // Setting the value of a non-existing field in a subdocument by using the dot-notation -db.update({planet: 'Mars'}, {$set: {"data.satellites": 2, "data.red": true}}, {}, () => { +db.update({ planet: 'Mars' }, { $set: { "data.satellites": 2, "data.red": true } }, {}, () => { // Mars document now is { _id: 'id1', system: 'solar', inhabited: false // , data: { satellites: 2, red: true } // } // Not that to set fields in subdocuments, you HAVE to use dot-notation // Using object-notation will just replace the top-level field - db.update({planet: 'Mars'}, {$set: {data: {satellites: 3}}}, {}, () => { + db.update({ planet: 'Mars' }, { $set: { data: { satellites: 3 } } }, {}, () => { // Mars document now is { _id: 'id1', system: 'solar', inhabited: false // , data: { satellites: 3 } // } @@ -413,23 +413,23 @@ db.update({planet: 'Mars'}, {$set: {"data.satellites": 2, "data.red": true}}, {} }); // Deleting a field -db.update({planet: 'Mars'}, {$unset: {planet: true}}, {}, () => { +db.update({ planet: 'Mars' }, { $unset: { planet: true } }, {}, () => { // Now the document for Mars doesn't contain the planet field // You can unset nested fields with the dot notation of course }); // Upserting a document -db.update({planet: 'Pluton'}, { +db.update({ planet: 'Pluton' }, { planet: 'Pluton', inhabited: false -}, {upsert: true}, (err: Error, numReplaced: number, upsert: boolean) => { +}, { upsert: true }, (err: Error, numReplaced: number, upsert: boolean) => { // numReplaced = 1, upsert = { _id: 'id5', planet: 'Pluton', inhabited: false } // A new document { _id: 'id5', planet: 'Pluton', inhabited: false } has been added to the collection }); // If you upsert with a modifier, the upserted doc is the query modified by the modifier // This is simpler than it sounds :) -db.update({planet: 'Pluton'}, {$inc: {distance: 38}}, {upsert: true}, () => { +db.update({ planet: 'Pluton' }, { $inc: { distance: 38 } }, { upsert: true }, () => { // A new document { _id: 'id5', planet: 'Pluton', distance: 38 } has been added to the collection }); @@ -437,12 +437,12 @@ db.update({planet: 'Pluton'}, {$inc: {distance: 38}}, {upsert: true}, () => { // let's see how we can modify the array field atomically // $push inserts new elements at the end of the array -db.update({_id: 'id6'}, {$push: {fruits: 'banana'}}, {}, () => { +db.update({ _id: 'id6' }, { $push: { fruits: 'banana' } }, {}, () => { // Now the fruits array is ['apple', 'orange', 'pear', 'banana'] }); // $pop removes an element from the end (if used with 1) or the front (if used with -1) of the array -db.update({_id: 'id6'}, {$pop: {fruits: 1}}, {}, () => { +db.update({ _id: 'id6' }, { $pop: { fruits: 1 } }, {}, () => { // Now the fruits array is ['apple', 'orange'] // With { $pop: { fruits: -1 } }, it would have been ['orange', 'pear'] }); @@ -450,22 +450,22 @@ db.update({_id: 'id6'}, {$pop: {fruits: 1}}, {}, () => { // $addToSet adds an element to an array only if it isn't already in it // Equality is deep-checked (i.e. $addToSet will not insert an object in an array already containing the same object) // Note that it doesn't check whether the array contained duplicates before or not -db.update({_id: 'id6'}, {$addToSet: {fruits: 'apple'}}, {}, () => { +db.update({ _id: 'id6' }, { $addToSet: { fruits: 'apple' } }, {}, () => { // The fruits array didn't change // If we had used a fruit not in the array, e.g. 'banana', it would have been added to the array }); // $pull removes all values matching a value or even any NeDB query from the array -db.update({_id: 'id6'}, {$pull: {fruits: 'apple'}}, {}, () => { +db.update({ _id: 'id6' }, { $pull: { fruits: 'apple' } }, {}, () => { // Now the fruits array is ['orange', 'pear'] }); -db.update({_id: 'id6'}, {$pull: {fruits: {$in: ['apple', 'pear']}}}, {}, () => { +db.update({ _id: 'id6' }, { $pull: { fruits: { $in: ['apple', 'pear'] } } }, {}, () => { // Now the fruits array is ['orange'] }); // $each can be used to $push or $addToSet multiple values at once // This example works the same way with $addToSet -db.update({_id: 'id6'}, {$push: {fruits: {$each: ['banana', 'orange']}}}, {}, () => { +db.update({ _id: 'id6' }, { $push: { fruits: { $each: ['banana', 'orange'] } } }, {}, () => { // Now the fruits array is ['apple', 'orange', 'pear', 'banana', 'orange'] }); @@ -477,32 +477,32 @@ db.update({_id: 'id6'}, {$push: {fruits: {$each: ['banana', 'orange']}}}, {}, () // Remove one document from the collection // options set to {} since the default for multi is false -db.remove({_id: 'id2'}, {}, (err: Error, numRemoved: number) => { +db.remove({ _id: 'id2' }, {}, (err: Error, numRemoved: number) => { // numRemoved = 1 }); // Remove multiple documents -db.remove({system: 'solar'}, {multi: true}, (err: Error, numRemoved: number) => { +db.remove({ system: 'solar' }, { multi: true }, (err: Error, numRemoved: number) => { // numRemoved = 3 // All planets from the solar system were removed }); -db.ensureIndex({fieldName: 'somefield'}, (err: Error) => { +db.ensureIndex({ fieldName: 'somefield' }, (err: Error) => { // If there was an error, err is not null }); // Using a unique constraint with the index -db.ensureIndex({fieldName: 'somefield', unique: true}, (err: Error) => { +db.ensureIndex({ fieldName: 'somefield', unique: true }, (err: Error) => { }); // Using a sparse unique index -db.ensureIndex({fieldName: 'somefield', unique: true, sparse: true}, (err: Error) => { +db.ensureIndex({ fieldName: 'somefield', unique: true, sparse: true }, (err: Error) => { }); // Format of the error message when the unique constraint is not met -db.insert({somefield: 'nedb'}, (err: Error) => { +db.insert({ somefield: 'nedb' }, (err: Error) => { // err is null - db.insert({somefield: 'nedb'}, (err: Error) => { + db.insert({ somefield: 'nedb' }, (err: Error) => { // err is { errorType: 'uniqueViolated' // , key: 'name' // , message: 'Unique constraint violated for key name' } diff --git a/types/ngstorage/index.d.ts b/types/ngstorage/index.d.ts index 15fb3c0481..83c740ff0e 100644 --- a/types/ngstorage/index.d.ts +++ b/types/ngstorage/index.d.ts @@ -1,23 +1,48 @@ -// Type definitions for ngstorage 0.3.11 +// Type definitions for ngstorage 0.3 // Project: https://github.com/gsklee/ngStorage // Definitions by: Jakub Pistek // Definitions: https://github.com/kubiq/DefinitelyTyped -declare module 'ngstorage' { +export namespace ngStorage { + interface StorageService { + /** + * @return true if the storage service is supported by the browser. + */ + $supported(): boolean; + + /** + * Adds default values to the store. + * Copies all properties of the default items to the store. + * If the store already has one of these properties it will skip it. + * + * @param items object holding the default values. + * @return the modified storage service. + */ + $default(items: T): StorageService & T; + + /** + * Removes all properties from the store. + * + * @param items optional object holding the default values to initialize the store after reset. + * @return the modified storage service. + */ + $reset(items?: T): StorageService & T; - interface IStorageService { - $default(items: {}): IStorageService; - $reset(items?: {}): IStorageService; $apply(): void; $sync(): void; - get(key: string): T; + + /** + * Access to the properties of the store. + */ + [key: string]: any; } - interface IStorageProvider extends angular.IServiceProvider { - - get(key: string): T; - set(key: string, value: T): T; + interface StorageProvider extends angular.IServiceProvider { + get(key: string): T | boolean; + set(key: string, value: T): T | boolean; + remove(key: string): void; + supported(): boolean; setKeyPrefix(prefix: string): void; setSerializer(serializer: (value: any) => string): void; setDeserializer(deserializer: (value: string) => any): void; diff --git a/types/ngstorage/ngstorage-tests.ts b/types/ngstorage/ngstorage-tests.ts index abddf19bb7..a69d905a55 100644 --- a/types/ngstorage/ngstorage-tests.ts +++ b/types/ngstorage/ngstorage-tests.ts @@ -1,78 +1,81 @@ -/// +import * as angular from "angular"; +import { ngStorage } from "ngstorage"; -import {IStorageService, IStorageProvider} from "ngstorage"; +let app: angular.IModule = angular.module('at', ['ngStorage']); -var app: any; -app.controller('LocalCtrl', function ($localStorage: IStorageService) { +app.controller('LocalCtrl', ($localStorage: ngStorage.StorageService) => { + if ($localStorage.$supported()) { + const store: MyStore & ngStorage.StorageService = $localStorage.$default({ + counter: 1 + }); - $localStorage.$default({ - counter: 1 - }); + store.$reset({ + counter: 1 + }); - $localStorage.$reset({ - counter: 1 - }); - - $localStorage.$reset(); - - $localStorage.$apply(); - - $localStorage.$sync(); + store.$reset(); + store.$apply(); + store.$sync(); + } }); -app.controller('SessionCtrl', function ($sessionStorage: IStorageService) { +app.controller('SessionCtrl', ($sessionStorage: ngStorage.StorageService) => { + if ($sessionStorage.$supported()) { + const store: MyStore & ngStorage.StorageService = $sessionStorage.$default({ + counter: 1 + }); - $sessionStorage.$default({ - counter: 1 - }); + store.$reset({ + counter: 1 + }); - $sessionStorage.$reset({ - counter: 1 - }); - - $sessionStorage.$reset(); - - $sessionStorage.$apply(); - - $sessionStorage.$sync(); + store.$reset(); + store.$apply(); + store.$sync(); + } }); -app.config(['$localStorageProvider', function ($localStorageProvider: IStorageProvider) { +app.config(($localStorageProvider: ngStorage.StorageProvider) => { + if ($localStorageProvider.supported()) { + $localStorageProvider.setKeyPrefix('NewPrefix'); + $localStorageProvider.set('MyKey', { counter: 'value' }); + $localStorageProvider.get('MyKey'); + $localStorageProvider.remove('MyKey'); - $localStorageProvider.setKeyPrefix('NewPrefix'); + const mySerializer = (value: any): string => { + return value.toString(); + }; - $localStorageProvider.get('MyKey'); + const myDeserializer = (value: string): any => { + return value; + }; - $localStorageProvider.set('MyKey', {counter: 'value'}); + $localStorageProvider.setSerializer(mySerializer); + $localStorageProvider.setDeserializer(myDeserializer); + } +}); - var mySerializer = function (value: any): string { - return value.toString(); - }; +app.config(($sessionStorageProvider: ngStorage.StorageProvider) => { + if ($sessionStorageProvider.supported()) { + $sessionStorageProvider.setKeyPrefix('NewPrefix'); + $sessionStorageProvider.set('MyKey', { counter: 'value' }); + $sessionStorageProvider.get('MyKey'); + $sessionStorageProvider.remove('MyKey'); - var myDeserializer = function (value: string): any { - return value; - }; + const mySerializer = (value: any): string => { + return value.toString(); + }; - $localStorageProvider.setSerializer(mySerializer); - $localStorageProvider.setDeserializer(myDeserializer); + const myDeserializer = (value: string): any => { + return value; + }; + + $sessionStorageProvider.setSerializer(mySerializer); + $sessionStorageProvider.setDeserializer(myDeserializer); + } +}); + +interface MyStore { + counter?: number; + foo?: string; } -]).config(['$sessionStorageProvider', function ($sessionStorageProvider: IStorageProvider) { - - $sessionStorageProvider.setKeyPrefix('NewPrefix'); - - $sessionStorageProvider.get('MyKey'); - - $sessionStorageProvider.set('MyKey', {counter: 'value'}); - - var mySerializer = function (value: any): string { - return value.toString(); - }; - - var myDeserializer = function (value: string): any { - return value; - }; - - $sessionStorageProvider.setSerializer(mySerializer); - $sessionStorageProvider.setDeserializer(myDeserializer); -} -]); diff --git a/types/ngstorage/tsconfig.json b/types/ngstorage/tsconfig.json index a3cdb4a204..fffe367328 100644 --- a/types/ngstorage/tsconfig.json +++ b/types/ngstorage/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/ngstorage/tslint.json b/types/ngstorage/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ngstorage/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 0f2a6e663e..7b81878fee 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1891,8 +1891,35 @@ declare module "dns" { priority: number } - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + + export interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + } + + export interface LookupOneOptions extends LookupOptions { + all?: false; + } + + export interface LookupAllOptions extends LookupOptions { + all: true; + } + + export interface LookupAddress { + address: string; + family: number; + } + + export function lookup(domain: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(domain: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(domain: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + export function lookup(domain: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + export function lookup(domain: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; @@ -2122,7 +2149,7 @@ declare module "net" { prependOnceListener(event: "listening", listener: () => void): this; } export function createServer(connectionListener?: (socket: Socket) => void): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void): Server; export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function connect(port: number, host?: string, connectionListener?: Function): Socket; export function connect(path: string, connectionListener?: Function): Socket; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 568d15d096..256d9a57b2 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -25,6 +25,7 @@ import * as stream from "stream"; import * as timers from "timers"; import * as repl from "repl"; import * as v8 from "v8"; +import * as dns from "dns"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -2127,6 +2128,59 @@ namespace repl_tests { } } +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +namespace dns_tests { + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup( + "nodejs.org", + { + family: 4, + hints: dns.ADDRCONFIG | dns.V4MAPPED, + all: false + }, + (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", {all: true}, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); + + function trueOrFalse(): boolean { + return Math.random() > 0.5 ? true : false; + } + dns.lookup("nodejs.org", {all: trueOrFalse()}, (err, addresses, family) => { + const _err: NodeJS.ErrnoException = err; + const _addresses: string | dns.LookupAddress[] = addresses; + const _family: number | undefined = family; + }); +} + /***************************************************************************** * * * The following tests are the modules not mentioned in document but existed * diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index f9d804c7eb..8d32f09744 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1242,8 +1242,35 @@ declare module "url" { } declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + + export interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + } + + export interface LookupOneOptions extends LookupOptions { + all?: false; + } + + export interface LookupAllOptions extends LookupOptions { + all: true; + } + + export interface LookupAddress { + address: string; + family: number; + } + + export function lookup(domain: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(domain: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(domain: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + export function lookup(domain: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + export function lookup(domain: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index d61693f1a6..43ce0f9f42 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -19,6 +19,7 @@ import * as cluster from "cluster"; import * as os from "os"; import * as vm from "vm"; import * as string_decoder from "string_decoder"; +import * as dns from "dns"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -968,3 +969,56 @@ namespace net_tests { net.createServer().listen(0).close().address(); } } + +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +namespace dns_tests { + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup( + "nodejs.org", + { + family: 4, + hints: dns.ADDRCONFIG | dns.V4MAPPED, + all: false + }, + (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", {all: true}, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); + + function trueOrFalse(): boolean { + return Math.random() > 0.5 ? true : false; + } + dns.lookup("nodejs.org", {all: trueOrFalse()}, (err, addresses, family) => { + const _err: NodeJS.ErrnoException = err; + const _addresses: string | dns.LookupAddress[] = addresses; + const _family: number | undefined = family; + }); +} diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 0c1796368e..664a037dd9 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -1812,8 +1812,35 @@ declare module "dns" { priority: number } - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + // Supported getaddrinfo flags. + export const ADDRCONFIG: number; + export const V4MAPPED: number; + + export interface LookupOptions { + family?: number; + hints?: number; + all?: boolean; + } + + export interface LookupOneOptions extends LookupOptions { + all?: false; + } + + export interface LookupAllOptions extends LookupOptions { + all: true; + } + + export interface LookupAddress { + address: string; + family: number; + } + + export function lookup(domain: string, family: number, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(domain: string, options: LookupOneOptions, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function lookup(domain: string, options: LookupAllOptions, callback: (err: NodeJS.ErrnoException, addresses: LookupAddress[]) => void): void; + export function lookup(domain: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; + export function lookup(domain: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 0e03b1d94a..4792c5edf1 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -24,6 +24,7 @@ import * as string_decoder from "string_decoder"; import * as stream from "stream"; import * as timers from "timers"; import * as repl from "repl"; +import * as dns from "dns"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -2039,6 +2040,59 @@ namespace repl_tests { } } +/////////////////////////////////////////////////// +/// DNS Tests : https://nodejs.org/api/dns.html /// +/////////////////////////////////////////////////// + +namespace dns_tests { + dns.lookup("nodejs.org", (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 4, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", 6, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup("nodejs.org", {}, (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + }); + dns.lookup( + "nodejs.org", + { + family: 4, + hints: dns.ADDRCONFIG | dns.V4MAPPED, + all: false + }, + (err, address, family) => { + const _err: NodeJS.ErrnoException = err; + const _address: string = address; + const _family: number = family; + } + ); + dns.lookup("nodejs.org", {all: true}, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); + + function trueOrFalse(): boolean { + return Math.random() > 0.5 ? true : false; + } + dns.lookup("nodejs.org", {all: trueOrFalse()}, (err, addresses, family) => { + const _err: NodeJS.ErrnoException = err; + const _addresses: string | dns.LookupAddress[] = addresses; + const _family: number | undefined = family; + }); +} + /***************************************************************************** * * * The following tests are the modules not mentioned in document but existed * diff --git a/types/nvd3/index.d.ts b/types/nvd3/index.d.ts index de2bbddefe..862aa38d99 100644 --- a/types/nvd3/index.d.ts +++ b/types/nvd3/index.d.ts @@ -67,7 +67,7 @@ declare namespace nv { } interface Nvd3TooltipStatic { - show([left, top]: [number, number], content: string, gravity?: string): void; //todo sort out use on nv.tooltip. + show(leftTop: [number, number], content: string, gravity?: string): void; //todo sort out use on nv.tooltip. cleanup(): void; //todo sort out use on nv.tooltip. } diff --git a/types/openlayers/v3/index.d.ts b/types/openlayers/v3/index.d.ts new file mode 100644 index 0000000000..c9791bc109 --- /dev/null +++ b/types/openlayers/v3/index.d.ts @@ -0,0 +1,13931 @@ +// Type definitions for OpenLayers v3.20.0 +// Project: http://openlayers.org/ +// Definitions by: Olivier Sechet , Matthias Dailey +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Definitions partially generated using tsd-jsdoc (https://github.com/englercj/tsd-jsdoc) + +declare type GlobalObject = Object; + +/** + * @namespace ol + */ +declare module ol { + /** + * The animation static methods are designed to be used with the + * {@link ol.Map#beforeRender} method. For example: + * + * var map = new ol.Map({ ... }); + * var zoom = ol.animation.zoom({ + * resolution: map.getView().getResolution() + * }); + * map.beforeRender(zoom); + * map.getView().setResolution(map.getView().getResolution() * 2); + * + * @namespace ol.animation + */ + module animation { + /** + * Generate an animated transition that will "bounce" the resolution as it + * approaches the final value. + * @param {olx.animation.BounceOptions} options Bounce options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view center. + * @param {olx.animation.PanOptions} options Pan options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view rotation. + * @param {olx.animation.RotateOptions} options Rotate options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view resolution. + * @param {olx.animation.ZoomOptions} options Zoom options. + * @return {ol.PreRenderFunction} Pre-render function. + * @api + */ + function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; + + } + + /** + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. + */ + class AssertionError extends Error { + /** + * Error object thrown when an assertion failed. This is an ECMA-262 Error, + * extended with a `code` property. + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error} + * @constructor + * @extends {Error} + * @implements {oli.AssertionError} + * @param {number} code Error code. + */ + constructor(code: number); + + /** + * Error code. The meaning of the code can be found on + * {@link http://openlayers.org/en/latest/errors.html} (replace `latest` with + * the version found in the OpenLayers script's header comment if a version + * other than the latest is used). + * @type {number} + * @api + */ + code: number; + + } + + /** + * @classdesc + * An attribution for a layer source. + * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable + */ + class Attribution { + /** + * @classdesc + * An attribution for a layer source. + * + * Example: + * + * source: new ol.source.OSM({ + * attributions: [ + * new ol.Attribution({ + * html: 'All maps © ' + + * 'OpenCycleMap' + * }), + * ol.source.OSM.ATTRIBUTION + * ], + * .. + * + * @constructor + * @param {olx.AttributionOptions} options Attribution options. + * @struct + * @api stable + */ + constructor(options: olx.AttributionOptions); + + /** + * Get the attribution markup. + * @return {string} The attribution HTML. + * @api stable + */ + getHTML(): string; + + } + + /** + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable + */ + class Collection extends ol.Object { + /** + * @classdesc + * An expanded version of standard JS Array, adding convenience methods for + * manipulation. Add and remove changes to the Collection trigger a Collection + * event. Note that this does not cover changes to the objects _within_ the + * Collection; they trigger events on the appropriate object, not on the + * Collection as a whole. + * + * @constructor + * @extends {ol.Object} + * @fires ol.Collection.Event + * @param {!Array.=} opt_array Array. + * @template T + * @api stable + */ + constructor(opt_array?: T[]); + + /** + * Remove all elements from the collection. + * @api stable + */ + clear(): void; + + /** + * Add elements to the collection. This pushes each item in the provided array + * to the end of the collection. + * @param {!Array.} arr Array. + * @return {ol.Collection.} This collection. + * @api stable + */ + extend(arr: T[]): ol.Collection; + + /** + * Iterate over each element, calling the provided callback. + * @param {function(this: S, T, number, Array.): *} f The function to call + * for every element. This function takes 3 arguments (the element, the + * index and the array). The return value is ignored. + * @param {S=} opt_this The object to use as `this` in `f`. + * @template S + * @api stable + */ + forEach(f: ((item: T, index: number, array: T[]) => any), opt_this?: S): void; + + /** + * Get a reference to the underlying Array object. Warning: if the array + * is mutated, no events will be dispatched by the collection, and the + * collection's "length" property won't be in sync with the actual length + * of the array. + * @return {!Array.} Array. + * @api stable + */ + getArray(): T[]; + + /** + * Get the element at the provided index. + * @param {number} index Index. + * @return {T} Element. + * @api stable + */ + item(index: number): T; + + /** + * Get the length of this collection. + * @return {number} The length of the array. + * @observable + * @api stable + */ + getLength(): number; + + /** + * Insert an element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + insertAt(index: number, elem: T): void; + + /** + * Remove the last element of the collection and return it. + * Return `undefined` if the collection is empty. + * @return {T|undefined} Element. + * @api stable + */ + pop(): (T); + + /** + * Insert the provided element at the end of the collection. + * @param {T} elem Element. + * @return {number} Length. + * @api stable + */ + push(elem: T): number; + + /** + * Remove the first occurrence of an element from the collection. + * @param {T} elem Element. + * @return {T|undefined} The removed element or undefined if none found. + * @api stable + */ + remove(elem: T): (T); + + /** + * Remove the element at the provided index and return it. + * Return `undefined` if the collection does not contain this index. + * @param {number} index Index. + * @return {T|undefined} Value. + * @api stable + */ + removeAt(index: number): (T); + + /** + * Set the element at the provided index. + * @param {number} index Index. + * @param {T} elem Element. + * @api stable + */ + setAt(index: number, elem: T): void; + + } + + module Collection { + + type EventType = string; + + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + class Event extends ol.events.Event { + /** + * @classdesc + * Events emitted by {@link ol.Collection} instances are instances of this + * type. + * + * @constructor + * @extends {ol.events.Event} + * @implements {oli.Collection.Event} + * @param {ol.Collection.EventType} type Type. + * @param {*=} opt_element Element. + */ + constructor(type: ol.Collection.EventType, opt_element?: any); + + /** + * The element that is added to or removed from the collection. + * @type {*} + * @api stable + */ + element: any; + + } + } + + /** + * Colors can be defined as a {@link ol.Color} array, or as strings in + * `rgb(r,g,b)` or `rgba(r,g,b,a)` format, or in hex `#rrggbb` or `#rgb` format. + * Color names, like 'red', 'blue' or 'green', may also be used with the + * Canvas renderer. + * + * @namespace ol.color + */ + module color { + /** + * Return the color as an array. This function maintains a cache of calculated + * arrays which means the result should not be modified. + * @param {ol.Color|string} color Color. + * @return {ol.Color} Color. + * @api + */ + function asArray(color: (ol.Color | string)): ol.Color; + + /** + * Return the color as an rgba string. + * @param {ol.Color|string} color Color. + * @return {string} Rgba string. + * @api + */ + function asString(color: (ol.Color | string)): string; + + } + + /** + * An {@link ol.ColorLike} can be a color, gradient or pattern accepted by + * [CanvasRenderingContext2D.fillStyle](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle). + * @namespace ol.colorlike + */ + module colorlike { + /** + * @param {ol.Color|ol.ColorLike} color Color. + * @return {ol.ColorLike} The color as an ol.ColorLike + * @api + */ + function asColorLike(color: (ol.Color | ol.ColorLike)): ol.ColorLike; + + } + + /** + * @namespace ol.control + */ + module control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + class Attribution extends ol.control.Control { + /** + * @classdesc + * Control to show all the attributions associated with the layer sources + * in the map. This control is one of the default controls included in maps. + * By default it will show in the bottom right portion of the map, but this can + * be changed by using a css selector for `.ol-attribution`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.AttributionOptions=} opt_options Attribution options. + * @api stable + */ + constructor(opt_options?: olx.control.AttributionOptions); + + /** + * Update the attribution element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Attribution} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the attribution is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the attribution should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the attribution according to the passed parameter. Will + * not do anything if the attribution isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Return `true` when the attribution is currently collapsed or `false` + * otherwise. + * @return {boolean} True if the widget is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + } + + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + class Control extends ol.Object { + /** + * @classdesc + * A control is a visible widget with a DOM element in a fixed position on the + * screen. They can involve user input (buttons), or be informational only; + * the position is determined using CSS. By default these are placed in the + * container with CSS class name `ol-overlaycontainer-stopevent`, but can use + * any outside DOM element. + * + * This is the base class for controls. You can use it for simple custom + * controls by creating the element with listeners, creating an instance: + * ```js + * var myControl = new ol.control.Control({element: myElement}); + * ``` + * and then adding this to the map. + * + * The main advantage of having this as a control rather than a simple separate + * DOM element is that preventing propagation is handled for you. Controls + * will also be `ol.Object`s in a `ol.Collection`, so you can use their + * methods. + * + * You can also extend this base for your own control class. See + * examples/custom-controls for an example of how to do this. + * + * @constructor + * @extends {ol.Object} + * @implements {oli.control.Control} + * @param {olx.control.ControlOptions} options Control options. + * @api stable + */ + constructor(options: olx.control.ControlOptions); + + /** + * Get the map associated with this control. + * @return {ol.Map} Map. + * @api stable + */ + getMap(): ol.Map; + + /** + * Remove the control from its current map and attach it to the new map. + * Subclasses may set up event handlers to get notified about changes to + * the map here. + * @param {ol.Map} map Map. + * @api stable + */ + setMap(map: ol.Map): void; + + /** + * This function is used to set a target element for the control. It has no + * effect if it is called after the control has been added to the map (i.e. + * after `setMap` is called on the control). If no `target` is set in the + * options passed to the control constructor and if `setTarget` is not called + * then the control is added to the map's overlay container. + * @param {Element|string} target Target. + * @api + */ + setTarget(target: (Element | string)): void; + + } + + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + class FullScreen extends ol.control.Control { + /** + * @classdesc + * Provides a button that when clicked fills up the full screen with the map. + * The full screen source element is by default the element containing the map viewport unless + * overriden by providing the `source` option. In which case, the dom + * element introduced using this parameter will be displayed in full screen. + * + * When in full screen mode, a close button is shown to exit full screen mode. + * The [Fullscreen API](http://www.w3.org/TR/fullscreen/) is used to + * toggle the map in full screen mode. + * + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.FullScreenOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.FullScreenOptions); + + } + + /** + * Set of controls included in maps by default. Unless configured otherwise, + * this returns a collection containing an instance of each of the following + * controls: + * * {@link ol.control.Zoom} + * * {@link ol.control.Rotate} + * * {@link ol.control.Attribution} + * + * @param {olx.control.DefaultsOptions=} opt_options Defaults options. + * @return {ol.Collection.} Controls. + * @api stable + */ + function defaults(opt_options?: olx.control.DefaultsOptions): ol.Collection; + + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + class MousePosition extends ol.control.Control { + /** + * @classdesc + * A control to show the 2D coordinates of the mouse cursor. By default, these + * are in the view projection, but can be in any supported projection. + * By default the control is shown in the top right corner of the map, but this + * can be changed by using the css selector `.ol-mouse-position`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.MousePositionOptions=} opt_options Mouse position + * options. + * @api stable + */ + constructor(opt_options?: olx.control.MousePositionOptions); + + /** + * Update the mouseposition element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.MousePosition} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return the coordinate format type used to render the current position or + * undefined. + * @return {ol.CoordinateFormatType|undefined} The format to render the current + * position in. + * @observable + * @api stable + */ + getCoordinateFormat(): (ol.CoordinateFormatType); + + /** + * Return the projection that is used to report the mouse position. + * @return {ol.proj.Projection|undefined} The projection to report mouse + * position in. + * @observable + * @api stable + */ + getProjection(): (ol.proj.Projection); + + /** + * Set the coordinate format type used to render the current position. + * @param {ol.CoordinateFormatType} format The format to render the current + * position in. + * @observable + * @api stable + */ + setCoordinateFormat(format: ol.CoordinateFormatType): void; + + /** + * Set the projection that is used to report the mouse position. + * @param {ol.proj.Projection} projection The projection to report mouse + * position in. + * @observable + * @api stable + */ + setProjection(projection: ol.proj.Projection): void; + + } + + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + class OverviewMap extends ol.control.Control { + /** + * Create a new control with a map acting as an overview map for an other + * defined map. + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.OverviewMapOptions=} opt_options OverviewMap options. + * @api + */ + constructor(opt_options?: olx.control.OverviewMapOptions); + + /** + * Update the overview map element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.OverviewMap} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Return `true` if the overview map is collapsible, `false` otherwise. + * @return {boolean} True if the widget is collapsible. + * @api stable + */ + getCollapsible(): boolean; + + /** + * Set whether the overview map should be collapsible. + * @param {boolean} collapsible True if the widget is collapsible. + * @api stable + */ + setCollapsible(collapsible: boolean): void; + + /** + * Collapse or expand the overview map according to the passed parameter. Will + * not do anything if the overview map isn't collapsible or if the current + * collapsed state is already the one requested. + * @param {boolean} collapsed True if the widget is collapsed. + * @api stable + */ + setCollapsed(collapsed: boolean): void; + + /** + * Determine if the overview map is collapsed. + * @return {boolean} The overview map is collapsed. + * @api stable + */ + getCollapsed(): boolean; + + /** + * Return the overview map. + * @return {ol.Map} Overview map. + * @api + */ + getOverviewMap(): ol.Map; + + } + + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + class Rotate extends ol.control.Control { + /** + * @classdesc + * A button control to reset rotation to 0. + * To style this control use css selector `.ol-rotate`. A `.ol-hidden` css + * selector is added to the button when the rotation is 0. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.RotateOptions=} opt_options Rotate options. + * @api stable + */ + constructor(opt_options?: olx.control.RotateOptions); + + /** + * Update the rotate control element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.Rotate} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + class ScaleLine extends ol.control.Control { + /** + * @classdesc + * A control displaying rough y-axis distances, calculated for the center of the + * viewport. For conformal projections (e.g. EPSG:3857, the default view + * projection in OpenLayers), the scale is valid for all directions. + * No scale line will be shown when the y-axis distance of a pixel at the + * viewport center cannot be calculated in the view projection. + * By default the scale line will show in the bottom left portion of the map, + * but this can be changed by using the css selector `.ol-scale-line`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ScaleLineOptions=} opt_options Scale line options. + * @api stable + */ + constructor(opt_options?: olx.control.ScaleLineOptions); + + /** + * Return the units to use in the scale line. + * @return {ol.control.ScaleLine.Units|undefined} The units to use in the scale + * line. + * @observable + * @api stable + */ + getUnits(): (ol.control.ScaleLine.Units); + + /** + * Update the scale line element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ScaleLine} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + /** + * Set the units to use in the scale line. + * @param {ol.control.ScaleLine.Units} units The units to use in the scale line. + * @observable + * @api stable + */ + setUnits(units: ol.control.ScaleLine.Units): void; + } + + module ScaleLine { + /** + * @enum {string} + * @api + */ + type Property = string; + + /** + * Units for the scale line. Supported values are `'degrees'`, `'imperial'`, + * `'nautical'`, `'metric'`, `'us'`. + * @enum {string} + */ + type Units = "degrees" | "imperial" | "nautical" | "metric" | "us"; + } + + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + class Zoom extends ol.control.Control { + /** + * @classdesc + * A control with 2 buttons, one for zoom in and one for zoom out. + * This control is one of the default controls of a map. To style this control + * use css selectors `.ol-zoom-in` and `.ol-zoom-out`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomOptions=} opt_options Zoom options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomOptions); + + } + + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + class ZoomSlider extends ol.control.Control { + /** + * @classdesc + * A slider type of control for zooming. + * + * Example: + * + * map.addControl(new ol.control.ZoomSlider()); + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomSliderOptions=} opt_options Zoom slider options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomSliderOptions); + + /** + * Update the zoomslider element. + * @param {ol.MapEvent} mapEvent Map event. + * @this {ol.control.ZoomSlider} + * @api + */ + static render(mapEvent: ol.MapEvent): void; + + } + + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + class ZoomToExtent extends ol.control.Control { + /** + * @classdesc + * A button control which, when pressed, changes the map view to a specific + * extent. To style this control use the css selector `.ol-zoom-extent`. + * + * @constructor + * @extends {ol.control.Control} + * @param {olx.control.ZoomToExtentOptions=} opt_options Options. + * @api stable + */ + constructor(opt_options?: olx.control.ZoomToExtentOptions); + + } + + } + + /** + * @namespace ol.coordinate + */ + module coordinate { + /** + * Add `delta` to `coordinate`. `coordinate` is modified in place and returned + * by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * ol.coordinate.add(coord, [-2, 4]); + * // coord is now [5.85, 51.983333] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {ol.Coordinate} delta Delta. + * @return {ol.Coordinate} The input coordinate adjusted by the given delta. + * @api stable + */ + function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; + + /** + * Returns a {@link ol.CoordinateFormatType} function that can be used to format + * a {ol.Coordinate} to a string. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(); + * var out = stringifyFunc(coord); + * // out is now '8, 48' + * + * Example with explicitly specifying 2 fractional digits: + * + * var coord = [7.85, 47.983333]; + * var stringifyFunc = ol.coordinate.createStringXY(2); + * var out = stringifyFunc(coord); + * // out is now '7.85, 47.98' + * + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {ol.CoordinateFormatType} Coordinate format. + * @api stable + */ + function createStringXY(opt_fractionDigits?: number): ol.CoordinateFormatType; + + /** + * Transforms the given {@link ol.Coordinate} to a string using the given string + * template. The strings `{x}` and `{y}` in the template will be replaced with + * the first and second coordinate values respectively. + * + * Example without specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template); + * // out is now 'Coordinate is (8|48).' + * + * Example explicitly specifying the fractional digits: + * + * var coord = [7.85, 47.983333]; + * var template = 'Coordinate is ({x}|{y}).'; + * var out = ol.coordinate.format(coord, template, 2); + * // out is now 'Coordinate is (7.85|47.98).' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {string} template A template string with `{x}` and `{y}` placeholders + * that will be replaced by first and second coordinate values. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Formatted coordinate. + * @api stable + */ + function format(coordinate: (ol.Coordinate), template: string, opt_fractionDigits?: number): string; + + /** + * Rotate `coordinate` by `angle`. `coordinate` is modified in place and + * returned by the function. + * + * Example: + * + * var coord = [7.85, 47.983333]; + * var rotateRadians = Math.PI / 2; // 90 degrees + * ol.coordinate.rotate(coord, rotateRadians); + * // coord is now [-47.983333, 7.85] + * + * @param {ol.Coordinate} coordinate Coordinate. + * @param {number} angle Angle in radian. + * @return {ol.Coordinate} Coordinate. + * @api stable + */ + function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; + + /** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and + * seconds. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord); + * // out is now '47° 58′ 60″ N 7° 50′ 60″ E' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringHDMS(coord, 1); + * // out is now '47° 58′ 60.0″ N 7° 50′ 60.0″ E' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} Hemisphere, degrees, minutes and seconds. + * @api stable + */ + function toStringHDMS(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + /** + * Format a coordinate as a comma delimited string. + * + * Example without specifying fractional digits: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord); + * // out is now '8, 48' + * + * Example explicitly specifying 1 fractional digit: + * + * var coord = [7.85, 47.983333]; + * var out = ol.coordinate.toStringXY(coord, 1); + * // out is now '7.8, 48.0' + * + * @param {ol.Coordinate|undefined} coordinate Coordinate. + * @param {number=} opt_fractionDigits The number of digits to include + * after the decimal point. Default is `0`. + * @return {string} XY. + * @api stable + */ + function toStringXY(coordinate?: ol.Coordinate, opt_fractionDigits?: number): string; + + } + + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + class DeviceOrientation extends ol.Object { + /** + * @classdesc + * The ol.DeviceOrientation class provides access to information from + * DeviceOrientation events. See the [HTML 5 DeviceOrientation Specification]( + * http://www.w3.org/TR/orientation-event/) for more details. + * + * Many new computers, and especially mobile phones + * and tablets, provide hardware support for device orientation. Web + * developers targeting mobile devices will be especially interested in this + * class. + * + * Device orientation data are relative to a common starting point. For mobile + * devices, the starting point is to lay your phone face up on a table with the + * top of the phone pointing north. This represents the zero state. All + * angles are then relative to this state. For computers, it is the same except + * the screen is open at 90 degrees. + * + * Device orientation is reported as three angles - `alpha`, `beta`, and + * `gamma` - relative to the starting position along the three planar axes X, Y + * and Z. The X axis runs from the left edge to the right edge through the + * middle of the device. Similarly, the Y axis runs from the bottom to the top + * of the device through the middle. The Z axis runs from the back to the front + * through the middle. In the starting position, the X axis points to the + * right, the Y axis points away from you and the Z axis points straight up + * from the device lying flat. + * + * The three angles representing the device orientation are relative to the + * three axes. `alpha` indicates how much the device has been rotated around the + * Z axis, which is commonly interpreted as the compass heading (see note + * below). `beta` indicates how much the device has been rotated around the X + * axis, or how much it is tilted from front to back. `gamma` indicates how + * much the device has been rotated around the Y axis, or how much it is tilted + * from left to right. + * + * For most browsers, the `alpha` value returns the compass heading so if the + * device points north, it will be 0. With Safari on iOS, the 0 value of + * `alpha` is calculated from when device orientation was first requested. + * ol.DeviceOrientation provides the `heading` property which normalizes this + * behavior across all browsers for you. + * + * It is important to note that the HTML 5 DeviceOrientation specification + * indicates that `alpha`, `beta` and `gamma` are in degrees while the + * equivalent properties in ol.DeviceOrientation are in radians for consistency + * with all other uses of angles throughout OpenLayers. + * + * To get notified of device orientation changes, register a listener for the + * generic `change` event on your `ol.DeviceOrientation` instance. + * + * @see {@link http://www.w3.org/TR/orientation-event/} + * + * @constructor + * @extends {ol.Object} + * @param {olx.DeviceOrientationOptions=} opt_options Options. + * @api + */ + constructor(opt_options?: olx.DeviceOrientationOptions); + + /** + * Rotation around the device z-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * standard Z axis. + * @observable + * @api + */ + getAlpha(): (number); + + /** + * Rotation around the device x-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar X axis. + * @observable + * @api + */ + getBeta(): (number); + + /** + * Rotation around the device y-axis (in radians). + * @return {number|undefined} The euler angle in radians of the device from the + * planar Y axis. + * @observable + * @api + */ + getGamma(): (number); + + /** + * The heading of the device relative to north (in radians). + * @return {number|undefined} The heading of the device relative to north, in + * radians, normalizing for different browser behavior. + * @observable + * @api + */ + getHeading(): (number); + + /** + * Determine if orientation is being tracked. + * @return {boolean} Changes in device orientation are being tracked. + * @observable + * @api + */ + getTracking(): boolean; + + /** + * Enable or disable tracking of device orientation events. + * @param {boolean} tracking The status of tracking changes to alpha, beta and + * gamma. If true, changes are tracked and reported immediately. + * @observable + * @api + */ + setTracking(tracking: boolean): void; + + } + + /** + * Objects that need to clean up after themselves. + * @constructor + */ + class Disposable { + /** + * Objects that need to clean up after themselves. + * @constructor + */ + constructor(); + + } + + /** + * Easing functions for {@link ol.animation}. + * @namespace ol.easing + */ + module easing { + /** + * Start slow and speed up. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeIn(t: number): number; + + /** + * Start fast and slow down. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function easeOut(t: number): number; + + /** + * Start slow, speed up, and then slow down again. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function inAndOut(t: number): number; + + /** + * Maintain a constant speed over time. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function linear(t: number): number; + + /** + * Start slow, speed up, and at the very end slow down again. This has the + * same general behavior as {@link ol.easing.inAndOut}, but the final slowdown + * is delayed. + * @param {number} t Input between 0 and 1. + * @return {number} Output between 0 and 1. + * @api + */ + function upAndDown(t: number): number; + + } + + /** + * Applications do not normally create event instances. They register (and + * unregister) event listener functions, which, when called by the library as + * the result of an event being dispatched, are passed event instances as their + * first argument. Listeners can be registered and unregistered on all objects + * descending from {@link ol.Observable}. All event instances have a `target` + * property, which corresponds to the object on which the event was dispatched. + * By default, `this` within the listener also refers to the target, though + * this can be configured in the listener registration function. + * Some classes have their own event type, which return additional + * properties; see the specific event class page for details. + * + * @namespace ol.events + */ + module events { + /** + * @namespace ol.events.condition + */ + module condition { + /** + * Return `true` if only the alt-key is pressed, `false` otherwise (e.g. when + * additionally the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt key is pressed. + * @api stable + */ + function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the alt-key and shift-key is pressed, `false` otherwise + * (e.g. when additionally the platform-modifier-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the alt and shift keys are pressed. + * @api stable + */ + function altShiftKeysOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always true. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True. + * @function + * @api stable + */ + function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a `click` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `click` event. + * @api stable + */ + function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return always false. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} False. + * @function + * @api stable + */ + function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the browser event is a `pointermove` event, `false` + * otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the browser event is a `pointermove` event. + * @api + */ + function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `singleclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `singleclick` event. + * @api stable + */ + function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the event is a map `dblclick` event, `false` otherwise. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if the event is a map `dblclick` event. + * @api stable + */ + function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if no modifier key (alt-, shift- or platform-modifier-key) is + * pressed. + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True only if there no modifier keys are pressed. + * @api stable + */ + function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the platform-modifier-key (the meta-key on Mac, + * ctrl-key otherwise) is pressed, `false` otherwise (e.g. when additionally + * the shift-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the platform modifier key is pressed. + * @api stable + */ + function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if only the shift-key is pressed, `false` otherwise (e.g. when + * additionally the alt-key is pressed). + * + * @param {ol.MapBrowserEvent} mapBrowserEvent Map browser event. + * @return {boolean} True if only the shift key is pressed. + * @api stable + */ + function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + + /** + * Return `true` if the target element is not editable, i.e. not a ``-, + * `