From dc124b25ba5bdffd722576a6eaa6595deb8a35e6 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 7 Aug 2016 23:38:46 -0400 Subject: [PATCH 01/68] reverts to interfaces --- mongoose/mongoose-tests.ts | 52 +- mongoose/mongoose.d.ts | 4661 ++++++++++++++++++------------------ 2 files changed, 2302 insertions(+), 2411 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 9aebb3ea1c..12d84cef3e 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -52,7 +52,7 @@ mongoose.model('Actor', new mongoose.Schema({ }), 'collectionName', true).find({}); mongoose.model('Actor').find({}); mongoose.modelNames()[0].toLowerCase(); -new (new mongoose.Mongoose()).Mongoose().connect(''); +new (new mongoose.Mongoose(9, 8, 7)).Mongoose(1, 2, 3).connect(''); mongoose.plugin(cb, {}).connect(''); mongoose.set('test', 'value'); mongoose.set('debug', function(collectionName: any, methodName: any, arg1: any, arg2: any) {}); @@ -136,7 +136,6 @@ conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); interface IStatics { staticMethod1: (a: number) => string; } -conn1.model<{}, IStatics>('').staticMethod1; conn1.modelNames()[0].toLowerCase(); conn1.config.hasOwnProperty(''); conn1.db.bufferMaxEntries; @@ -350,7 +349,7 @@ new mongoose.Schema({ * section document.js * http://mongoosejs.com/docs/api.html#document-js */ -var doc: mongoose.Document; +var doc: mongoose.MongooseDocument; doc.$isDefault('path').valueOf(); doc.depopulate('path'); doc.equals(doc).valueOf(); @@ -465,7 +464,7 @@ mongooseArray.length; * http://mongoosejs.com/docs/api.html#types-documentarray-js */ // The constructor is private api, but we'll use it to test -var documentArray: mongoose.Types.DocumentArray = +var documentArray: mongoose.Types.DocumentArray = new mongoose.Types.DocumentArray(); documentArray.create({}).errors; documentArray.id(new Buffer('hi')); @@ -500,7 +499,7 @@ var objectId: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexStr objectId = new mongoose.Types.ObjectId(12345); objectId.getTimestamp(); /* practical examples */ -export interface IManagerSchema extends mongoose.Document { +export interface IManagerSchema extends mongoose.MongooseDocument { user: mongoose.Schema.Types.ObjectId; } export var ManagerSchema = new mongoose.Schema({ @@ -530,7 +529,7 @@ embeddedDocument.execPopulate(); * section query.js * http://mongoosejs.com/docs/api.html#query-js */ -var query: mongoose.Query; +var query: mongoose.Query; query.$where('').$where(cb); query.all(99).all('path', 99); query.and([{ color: 'green' }, { status: 'ok' }]).and([]); @@ -761,8 +760,9 @@ schemaArray.sparse(true); * section schema/string.js * http://mongoosejs.com/docs/api.html#schema-string-js */ +var MongoDocument: mongoose.Document; var schemastring: mongoose.Schema.Types.String = new mongoose.Schema.Types.String('hello'); -schemastring.checkRequired(234, new mongoose.Document()).valueOf(); +schemastring.checkRequired(234, MongoDocument).valueOf(); schemastring.enum(['hi', 'a', 'b']).enum('hi').enum({}); schemastring.lowercase().lowercase(); schemastring.match(/re/, 'error').match(/re/); @@ -790,7 +790,7 @@ documentarray.sparse(true); * http://mongoosejs.com/docs/api.html#schema-number-js */ var schemanumber: mongoose.Schema.Types.Number = new mongoose.Schema.Types.Number('num', {}); -schemanumber.checkRequired(999, new mongoose.Document()).valueOf(); +schemanumber.checkRequired(999, MongoDocument).valueOf(); schemanumber.max(999, 'error').max(999); schemanumber.min(999, 'error').min(999); /* static properties */ @@ -803,7 +803,7 @@ schemanumber.sparse(true); * http://mongoosejs.com/docs/api.html#schema-date-js */ var schemadate: mongoose.Schema.Types.Date = new mongoose.Schema.Types.Date('99'); -schemadate.checkRequired([], new mongoose.Document()).valueOf(); +schemadate.checkRequired([], MongoDocument).valueOf(); schemadate.expires(99).expires('now'); schemadate.max(new Date(), 'error').max(new Date('')); schemadate.min(new Date(), 'error').min(new Date('')); @@ -817,7 +817,7 @@ schemadate.sparse(true); * http://mongoosejs.com/docs/api.html#schema-buffer-js */ var schemabuffer: mongoose.Schema.Types.Buffer = new mongoose.Schema.Types.Buffer('99'); -schemabuffer.checkRequired(999, new mongoose.Document()).valueOf(); +schemabuffer.checkRequired(999, MongoDocument).valueOf(); /* static properties */ mongoose.Schema.Types.Buffer.schemaName.toLowerCase(); /* inherited properties */ @@ -840,7 +840,7 @@ schemaboolean.sparse(true); */ var schemaobjectid: mongoose.Schema.Types.ObjectId = new mongoose.Schema.Types.ObjectId('99'); schemaobjectid.auto(true).auto(false); -schemaobjectid.checkRequired(99, new mongoose.Document()).valueOf(); +schemaobjectid.checkRequired(99, MongoDocument).valueOf(); /* static properties */ mongoose.Schema.Types.ObjectId.schemaName.toLowerCase(); /* inherited properties */ @@ -1078,7 +1078,7 @@ var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({ required: true } }), 'myCollection', true); -MongoModel.$where('indexOf("val") !== -1').exec(function (err, docs) { +MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) { docs[0].save(); }); MongoModel.findById(999, function (err, doc) { @@ -1310,7 +1310,7 @@ LocModel.find() }); }); }); -LocModel.$where('') +LocModel.find({}).$where('') .exec(function (err, locations) { locations[0].name; locations[1].openingTimes; @@ -1346,10 +1346,22 @@ LocModel.geoSearch({}, { interface IStatics { staticMethod2: (a: number) => string; } -var StaticModel = mongoose.model('Location'); -StaticModel.staticMethod2(9).toUpperCase(); -(new StaticModel()).save(function (err, doc) { - doc.openingTimes; - doc.model('').staticMethod2; -}); -StaticModel.model('').staticMethod2; \ No newline at end of file +interface MyDocument extends mongoose.Document { + prop: string; + method: () => void; +} +interface MyModel extends mongoose.Model { + staticProp: string; + staticMethod: () => void; +} +interface ModelStruct { + doc: MyDocument, + model: MyModel +} +var mySchema = new mongoose.Schema({}); +export var Final: MyModel = mongoose.connection.model('Final', mySchema); +Final.findOne(function (err: any, doc: MyDocument) { + doc.save(); + doc.remove(); + doc.model(null, null); +}); \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 421129320f..430b3a2b0c 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -27,43 +27,43 @@ * is just a simple heuristic to keep track of our progress. * * TODO for version 4.x [updated][tested]: - * [x][x] index.js - * [x][x] querystream.js - * [x][x] connection.js - * [x][x] utils.js - * [x][x] browser.js - * [x][x] drivers/node-mongodb-native/collection.js - * [x][x] drivers/node-mongodb-native/connection.js - * [x][x] error/messages.js - * [x][x] error/validation.js - * [x][x] error.js - * [x][x] querycursor.js - * [x][x] virtualtype.js - * [x][x] schema.js - * [x][x] document.js - * [x][x] types/subdocument.js - * [x][x] types/array.js - * [x][x] types/documentarray.js - * [x][x] types/buffer.js - * [x][x] types/objectid.js - * [x][x] types/embedded.js - * [x][x] query.js - * [x][x] schema/array.js - * [x][x] schema/string.js - * [x][x] schema/documentarray.js - * [x][x] schema/number.js - * [x][x] schema/date.js - * [x][x] schema/buffer.js - * [x][x] schema/boolean.js - * [x][x] schema/objectid.js - * [x][x] schema/mixed.js - * [x][x] schema/embedded.js - * [x][x] aggregate.js - * [x][x] schematype.js - * [x][x] promise.js - * [x][x] ES6Promise.js - * [x][x] model.js - * [x][x] collection.js + * [x][ ] index.js + * [x][ ] querystream.js + * [x][ ] connection.js + * [x][ ] utils.js + * [x][ ] browser.js + * [x][ ] drivers/node-mongodb-native/collection.js + * [x][ ] drivers/node-mongodb-native/connection.js + * [x][ ] error/messages.js + * [x][ ] error/validation.js + * [x][ ] error.js + * [x][ ] querycursor.js + * [x][ ] virtualtype.js + * [x][ ] schema.js + * [x][ ] document.js + * [x][ ] types/subdocument.js + * [x][ ] types/array.js + * [x][ ] types/documentarray.js + * [x][ ] types/buffer.js + * [x][ ] types/objectid.js + * [x][ ] types/embedded.js + * [x][ ] query.js + * [x][ ] schema/array.js + * [x][ ] schema/string.js + * [x][ ] schema/documentarray.js + * [x][ ] schema/number.js + * [x][ ] schema/date.js + * [x][ ] schema/buffer.js + * [x][ ] schema/boolean.js + * [x][ ] schema/objectid.js + * [x][ ] schema/mixed.js + * [x][ ] schema/embedded.js + * [x][ ] aggregate.js + * [x][ ] schematype.js + * [x][ ] promise.js + * [x][ ] ES6Promise.js + * [x][ ] model.js + * [x][ ] collection.js */ /* @@ -84,70 +84,26 @@ declare module "mongoose" { * Some mongoose classes have the same name as the native JS classes * Keep references to native classes using a "Native" prefix */ - type NativeBuffer = Buffer; - type NativeDate = Date; - type NativeError = Error; - - /* - * Public API - */ + class NativeBuffer extends global.Buffer {} + class NativeDate extends global.Date {} + class NativeError extends global.Error {} /* * section index.js * http://mongoosejs.com/docs/api.html#index-js */ - - /* Class constructors */ - export var Aggregate: typeof _mongoose.Aggregate; - export var CastError: typeof _mongoose.CastError; - export var Collection: _mongoose.Collection; - export var Connection: typeof _mongoose.Connection; - export var Document: typeof _mongoose.Document; export var DocumentProvider: any; - export var Error: typeof _mongoose.Error; - export var Model: _mongoose.ModelConstructor<{}>; - export var Mongoose: { - // recursive constructor - new(...args: any[]): typeof mongoose; - } - - /** - * To assign your own promise library: - * - * 1. Include this somewhere in your code: - * mongoose.Promise = YOUR_PROMISE; - * - * 2. Include this somewhere in your main .d.ts file: - * type MongoosePromise = YOUR_PROMISE; - */ - - export var Promise: any; - export var PromiseProvider: any; - export var Query: typeof _mongoose.ModelQuery; - export var Schema: typeof _mongoose.Schema; - export var SchemaType: typeof _mongoose.SchemaType; - export var SchemaTypes: typeof _mongoose.Schema.Types; - export var Types: { - Subdocument: typeof _mongoose.Types.Subdocument; - Array: typeof _mongoose.Types.Array; - DocumentArray: typeof _mongoose.Types.DocumentArray; - Buffer: typeof _mongoose.Types.Buffer; - ObjectId: typeof _mongoose.Types.ObjectId; - Embedded: typeof _mongoose.Types.Embedded; - } - export var VirtualType: typeof _mongoose.VirtualType; + export var Model: Model; + // recursive constructor + export var Mongoose: new(...args: any[]) => typeof mongoose; + export var SchemaTypes: typeof Schema.Types; /** Expose connection states for user-land */ export var STATES: Object /** The default connection of the mongoose module. */ - export var connection: _mongoose.Connection; + export var connection: Connection; /** The node-mongodb-native driver Mongoose uses. */ export var mongo: typeof mongodb; - /** - * The mquery query builder Mongoose uses. - * Currently there is no mquery type definition. - */ - export var mquery: any; /** The Mongoose version */ export var version: string; @@ -158,10 +114,10 @@ declare module "mongoose" { * @returns pseudo-promise wrapper around this */ export function connect(uris: string, - options?: _mongoose.MongooseConnectOptions, - callback?: (err: mongodb.MongoError) => void): _mongoose.MongooseThenable; + options?: ConnectOptions, + callback?: (err: mongodb.MongoError) => void): MongooseThenable; export function connect(uris: string, - callback?: (err: mongodb.MongoError) => void): _mongoose.MongooseThenable; + callback?: (err: mongodb.MongoError) => void): MongooseThenable; /** * Creates a Connection instance. @@ -171,20 +127,20 @@ declare module "mongoose" { * @param options options to pass to the driver * @returns the created Connection object */ - export function createConnection(): _mongoose.Connection; + export function createConnection(): Connection; export function createConnection(uri: string, - options?: _mongoose.MongooseConnectOptions - ): _mongoose.Connection; + options?: ConnectOptions + ): Connection; export function createConnection(host: string, database_name: string, port?: number, - options?: _mongoose.MongooseConnectOptions - ): _mongoose.Connection; + options?: ConnectOptions + ): Connection; /** * Disconnects all connections. * @param fn called after all connection close. * @returns pseudo-promise wrapper around this */ - export function disconnect(fn?: (error: any) => void): _mongoose.MongooseThenable; + export function disconnect(fn?: (error: any) => void): MongooseThenable; /** Gets mongoose options */ export function get(key: string): any; @@ -197,10 +153,8 @@ declare module "mongoose" { * @param collection (optional, induced from model name) * @param skipInit whether to skip initialization (defaults to false) */ - export function model(name: string, schema?: _mongoose.Schema, collection?: string, - skipInit?: boolean): _mongoose.ModelConstructor; - export function model(name: string, schema?: _mongoose.Schema, collection?: string, - skipInit?: boolean): Statics & _mongoose.ModelConstructor; + export function model(name: string, schema?: Schema, collection?: string, + skipInit?: boolean): Model; /** * Returns an array of model names created on this instance of Mongoose. @@ -219,2388 +173,2313 @@ declare module "mongoose" { /** Sets mongoose options */ export function set(key: string, value: any): void; + type MongooseThenable = typeof mongoose & _MongooseThenable; + interface _MongooseThenable { + /** + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. + */ + then(onFulfill?: () => void | TRes | PromiseLike, + onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + + /** + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. + */ + catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + } + + class CastError extends Error { + /** + * The Mongoose CastError constructor + * @param type The name of the type + * @param value The value that failed to cast + * @param path The path a.b.c in the doc where this cast error occurred + * @param reason The original error that was thrown + */ + constructor(type: string, value: any, path: string, reason?: NativeError); + } /* - * All the types that are exposed for type checking. + * section querystream.js + * http://mongoosejs.com/docs/api.html#querystream-js + * + * QueryStream can only be accessed using query#stream(), we only + * expose its interface here to enable type-checking. */ - export type Aggregate = _mongoose.Aggregate; - export type CastError = _mongoose.CastError; - export type Collection = _mongoose.Collection; - export type Connection = _mongoose.Connection; - export type Document = _mongoose.Document; - export type Error = _mongoose.Error; - export type ValidationError = _mongoose.ValidationError; + interface QueryStream extends stream.Stream { + /** + * Provides a Node.js 0.8 style ReadStream interface for Queries. + * @event data emits a single Mongoose document + * @event error emits when an error occurs during streaming. This will emit before the close event. + * @event close emits when the stream reaches the end of the cursor or an error occurs, or the stream + * is manually destroyed. After this event, no more events are emitted. + */ + constructor(query: Query, options?: { + /** + * optional function which accepts a mongoose document. The return value + * of the function will be emitted on data. + */ + transform?: Function; + [other: string]: any; + }): QueryStream; - /** Document created from model constructors. */ - export type model = _mongoose.Model; - /** Model Constructor. */ - export type Model = _mongoose.ModelConstructor; + /** + * Destroys the stream, closing the underlying cursor, which emits the close event. + * No more events will be emitted after the close event. + */ + destroy(err?: NativeError): void; - export type Mongoose = typeof mongoose; - export type Promise = _mongoose._MongoosePromise; - export type Query = _mongoose.Query; - export type QueryCursor = _mongoose.QueryCursor; - export type QueryStream = _mongoose.QueryStream; - export type Schema = _mongoose.Schema; - namespace Schema { - namespace Types { - export type Array = _mongoose.Schema._Types.Array; - export type String = _mongoose.Schema._Types.String; - export type DocumentArray = _mongoose.Schema._Types.DocumentArray; - export type Number = _mongoose.Schema._Types.Number; - export type Date = _mongoose.Schema._Types.Date; - export type Buffer = _mongoose.Schema._Types.Buffer; - export type Boolean = _mongoose.Schema._Types.Boolean; - export type Bool = _mongoose.Schema._Types.Boolean; - export type ObjectId = _mongoose.Schema._Types.ObjectId; - export type Oid = _mongoose.Schema._Types.ObjectId; - export type Mixed = _mongoose.Schema._Types.Mixed; - export type Object = _mongoose.Schema._Types.Mixed; - export type Embedded = _mongoose.Schema._Types.Embedded; - } + /** Pauses this stream. */ + pause(): void; + /** Pipes this query stream into another stream. This method is inherited from NodeJS Streams. */ + pipe(destination: T, options?: { end?: boolean; }): T; + /** Resumes this stream. */ + resume(): void; + + /** Flag stating whether or not this stream is paused. */ + paused: boolean; + /** Flag stating whether or not this stream is readable. */ + readable: boolean; } - export type SchemaType = _mongoose.SchemaType; - namespace Types { - export type Subdocument = _mongoose.Types.Subdocument; - export type Array = _mongoose.Types.Array; - export type DocumentArray = _mongoose.Types.DocumentArray; - export type Buffer = _mongoose.Types.Buffer; - export type ObjectId = _mongoose.Types.ObjectId; - export type Embedded = _mongoose.Types.Embedded; + + /* + * section connection.js + * http://mongoosejs.com/docs/api.html#connection-js + * + * The Connection class exposed by require('mongoose') + * is actually the driver's NativeConnection class. + * connection.js defines a base class that the native + * versions extend. See: + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ + abstract class ConnectionBase extends events.EventEmitter { + /** + * For practical reasons, a Connection equals a Db. + * @param base a mongoose instance + * @event connecting Emitted when connection.{open,openSet}() is executed on this connection. + * @event connected Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios. + * @event open Emitted after we connected and onOpen is executed on all of this connections models. + * @event disconnecting Emitted when connection.close() was executed. + * @event disconnected Emitted after getting disconnected from the db. + * @event close Emitted after we disconnected and onClose executed on all of this connections models. + * @event reconnected Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection. + * @event error Emitted when an error occurs on this connection. + * @event fullsetup Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected. + * @event all Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. + */ + constructor(base: typeof mongoose); + + /** + * Opens the connection to MongoDB. + * @param mongodb://uri or the host to which you are connecting + * @param database database name + * @param port database port + * @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden. + * Mongoose defaults the server auto_reconnect options to true which can be overridden. + * See the node-mongodb-native driver instance for options that it understands. + * Options passed take precedence over options included in connection strings. + */ + open(connection_string: string, database?: string, port?: number, + options?: ConnectionOpenOptions, callback?: (err: any) => void): any; + + /** + * Opens the connection to a replica set. + * @param uris comma-separated mongodb:// URIs + * @param database database name if not included in uris + * @param options passed to the internal driver + */ + openSet(uris: string, database?: string, options?: ConnectionOpenSetOptions, + callback?: (err: any) => void): any; + + /** Closes the connection */ + close(callback?: (err: any) => void): _MongoosePromise; + + /** + * Retrieves a collection, creating it if not cached. + * Not typically needed by applications. Just talk to your collection through your model. + * @param name name of the collection + * @param options optional collection options + */ + collection(name: string, options?: Object): Collection; + + /** + * Defines or retrieves a model. + * When no collection argument is passed, Mongoose produces a collection name by passing + * the model name to the utils.toCollectionName method. This method pluralizes the name. + * If you don't like this behavior, either pass a collection name or set your schemas + * collection name option. + * @param name the model name + * @param schema a schema. necessary when defining a model + * @param collection name of mongodb collection (optional) if not given it will be induced from model name + * @returns The compiled model + */ + model(name: string, schema?: Schema, collection?: string): Model; + + /** Returns an array of model names created on this connection. */ + modelNames(): string[]; + + /** A hash of the global options that are associated with this connection */ + config: Object; + + /** The mongodb.Db instance, set when the connection is opened */ + db: mongodb.Db; + + /** A hash of the collections associated with this connection */ + collections: { [index: string]: Collection }; + + /** + * Connection ready state + * 0 = disconnected + * 1 = connected + * 2 = connecting + * 3 = disconnecting + * Each state change emits its associated event name. + */ + readyState: number; } - export type VirtualType = _mongoose.VirtualType; - export type ConnectionOptions = _mongoose.MongooseConnectOptions; + interface ConnectionOptionsBase { + /** passed to the connection db instance */ + db?: any; + /** passed to the connection server instance(s) */ + server?: any; + /** passed to the connection ReplSet instance */ + replset?: any; + /** username for authentication */ + user?: string; + /** password for authentication */ + pass?: string; + /** options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) */ + auth?: any; + } - /** Private */ - namespace _mongoose { - /* - * section index.js - * http://mongoosejs.com/docs/api.html#index-js - */ - type MongooseThenable = typeof mongoose & _MongooseThenable; - interface _MongooseThenable { + /** See the node-mongodb-native driver instance for options that it understands. */ + interface ConnectionOpenOptions extends ConnectionOptionsBase { + /** mongoose-specific options */ + config?: { /** - * Ability to use mongoose object as a pseudo-promise so .connect().then() - * and .disconnect().then() are viable. + * set to false to disable automatic index creation for all + * models associated with this connection. */ - then(onFulfill?: () => void | TRes | PromiseLike, - onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; - - /** - * Ability to use mongoose object as a pseudo-promise so .connect().then() - * and .disconnect().then() are viable. - */ - catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; - } - - class CastError extends _mongoose.Error { - /** - * The Mongoose CastError constructor - * @param type The name of the type - * @param value The value that failed to cast - * @param path The path a.b.c in the doc where this cast error occurred - * @param reason The original error that was thrown - */ - constructor(type: string, value: any, path: string, reason?: NativeError); - } - - interface MongooseConnectOptions extends - ConnectionOpenOptions, - ConnectionOpenSetOptions {} - - /* - * section querystream.js - * http://mongoosejs.com/docs/api.html#querystream-js - * - * QueryStream can only be accessed using query#stream(), we only - * expose its interface here to enable type-checking. - */ - interface QueryStream extends stream.Stream { - /** - * Provides a Node.js 0.8 style ReadStream interface for Queries. - * @event data emits a single Mongoose document - * @event error emits when an error occurs during streaming. This will emit before the close event. - * @event close emits when the stream reaches the end of the cursor or an error occurs, or the stream - * is manually destroyed. After this event, no more events are emitted. - */ - constructor(query: Query, options?: { - /** - * optional function which accepts a mongoose document. The return value - * of the function will be emitted on data. - */ - transform?: Function; - [other: string]: any; - }): QueryStream; - - /** - * Destroys the stream, closing the underlying cursor, which emits the close event. - * No more events will be emitted after the close event. - */ - destroy(err?: NativeError): void; - - /** Pauses this stream. */ - pause(): void; - /** Pipes this query stream into another stream. This method is inherited from NodeJS Streams. */ - pipe(destination: T, options?: { end?: boolean; }): T; - /** Resumes this stream. */ - resume(): void; - - /** Flag stating whether or not this stream is paused. */ - paused: boolean; - /** Flag stating whether or not this stream is readable. */ - readable: boolean; - } - - /* - * section connection.js - * http://mongoosejs.com/docs/api.html#connection-js - * - * The Connection class exposed by require('mongoose') - * is actually the driver's NativeConnection class. - * connection.js defines a base class that the native - * versions extend. See: - * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js - */ - abstract class ConnectionBase extends events.EventEmitter { - /** - * For practical reasons, a Connection equals a Db. - * @param base a mongoose instance - * @event connecting Emitted when connection.{open,openSet}() is executed on this connection. - * @event connected Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios. - * @event open Emitted after we connected and onOpen is executed on all of this connections models. - * @event disconnecting Emitted when connection.close() was executed. - * @event disconnected Emitted after getting disconnected from the db. - * @event close Emitted after we disconnected and onClose executed on all of this connections models. - * @event reconnected Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection. - * @event error Emitted when an error occurs on this connection. - * @event fullsetup Emitted in a replica-set scenario, when primary and at least one seconaries specified in the connection string are connected. - * @event all Emitted in a replica-set scenario, when all nodes specified in the connection string are connected. - */ - constructor(base: typeof mongoose); - - /** - * Opens the connection to MongoDB. - * @param mongodb://uri or the host to which you are connecting - * @param database database name - * @param port database port - * @param options Mongoose forces the db option forceServerObjectId false and cannot be overridden. - * Mongoose defaults the server auto_reconnect options to true which can be overridden. - * See the node-mongodb-native driver instance for options that it understands. - * Options passed take precedence over options included in connection strings. - */ - open(connection_string: string, database?: string, port?: number, - options?: ConnectionOpenOptions, callback?: (err: any) => void): any; - - /** - * Opens the connection to a replica set. - * @param uris comma-separated mongodb:// URIs - * @param database database name if not included in uris - * @param options passed to the internal driver - */ - openSet(uris: string, database?: string, options?: ConnectionOpenSetOptions, - callback?: (err: any) => void): any; - - /** Closes the connection */ - close(callback?: (err: any) => void): _MongoosePromise; - - /** - * Retrieves a collection, creating it if not cached. - * Not typically needed by applications. Just talk to your collection through your model. - * @param name name of the collection - * @param options optional collection options - */ - collection(name: string, options?: Object): Collection; - - /** - * Defines or retrieves a model. - * When no collection argument is passed, Mongoose produces a collection name by passing - * the model name to the utils.toCollectionName method. This method pluralizes the name. - * If you don't like this behavior, either pass a collection name or set your schemas - * collection name option. - * @param name the model name - * @param schema a schema. necessary when defining a model - * @param collection name of mongodb collection (optional) if not given it will be induced from model name - * @returns The compiled model - */ - model(name: string, schema?: Schema, collection?: string): ModelConstructor; - model(name: string, schema?: Schema, collection?: string): Statics & ModelConstructor; - - /** Returns an array of model names created on this connection. */ - modelNames(): string[]; - - /** A hash of the global options that are associated with this connection */ - config: Object; - - /** The mongodb.Db instance, set when the connection is opened */ - db: mongodb.Db; - - /** A hash of the collections associated with this connection */ - collections: { [index: string]: Collection }; - - /** - * Connection ready state - * 0 = disconnected - * 1 = connected - * 2 = connecting - * 3 = disconnecting - * Each state change emits its associated event name. - */ - readyState: number; - } - - interface ConnectionOptionsBase { - /** passed to the connection db instance */ - db?: any; - /** passed to the connection server instance(s) */ - server?: any; - /** passed to the connection ReplSet instance */ - replset?: any; - /** username for authentication */ - user?: string; - /** password for authentication */ - pass?: string; - /** options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) */ - auth?: any; - } - - /** See the node-mongodb-native driver instance for options that it understands. */ - interface ConnectionOpenOptions extends ConnectionOptionsBase { - /** mongoose-specific options */ - config?: { - /** - * set to false to disable automatic index creation for all - * models associated with this connection. - */ - autoIndex?: boolean; - }; - } - - /** See the node-mongodb-native driver instance for options that it understands. */ - interface ConnectionOpenSetOptions extends ConnectionOptionsBase { - /** - * If true, enables High Availability support for mongos - * If connecting to multiple mongos servers, set the mongos option to true. - */ - mongos?: boolean; - } - - /* - * section drivers/node-mongodb-native/collection.js - * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js - */ - interface Collection extends CollectionBase { - /** - * Collection constructor - * @param name name of the collection - * @param conn A MongooseConnection instance - * @param opts optional collection options - */ - new(name: string, conn: Connection, opts?: Object): Collection; - /** Formatter for debug print args */ - $format(arg: any): string; - /** Debug print helper */ - $print(name: any, i: any, args: any[]): void; - /** Retreives information about this collections indexes. */ - getIndexes(): any; - } - - /* - * section drivers/node-mongodb-native/connection.js - * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js - */ - class Connection extends ConnectionBase { - /** - * Switches to a different database using the same connection pool. - * @param name The database name - * @returns New Connection Object - */ - useDb(name: string): Connection; - - /** Expose the possible connection states. */ - static STATES: Object; - } - - /* - * section error/validation.js - * http://mongoosejs.com/docs/api.html#error-validation-js - */ - class ValidationError extends Error { - /** Console.log helper */ - toString(): string; - } - - /* - * section error.js - * http://mongoosejs.com/docs/api.html#error-js - */ - class Error extends global.Error { - /** - * MongooseError constructor - * @param msg Error message - */ - constructor(msg: string); - - /** - * The default built-in validator error messages. These may be customized. - * As you might have noticed, error messages support basic templating - * {PATH} is replaced with the invalid document path - * {VALUE} is replaced with the invalid value - * {TYPE} is replaced with the validator type such as "regexp", "min", or "user defined" - * {MIN} is replaced with the declared min value for the Number.min validator - * {MAX} is replaced with the declared max value for the Number.max validator - */ - static messages: Object; - - /** For backwards compatibility. Same as mongoose.Error.messages */ - static Messages: Object; - } - - /* - * section querycursor.js - * http://mongoosejs.com/docs/api.html#querycursor-js - * - * Callback signatures are from: http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close - * QueryCursor can only be accessed by query#cursor(), we only - * expose its interface to enable type-checking. - */ - interface QueryCursor extends stream.Readable { - /** - * A QueryCursor is a concurrency primitive for processing query results - * one document at a time. A QueryCursor fulfills the Node.js streams3 API, - * in addition to several other mechanisms for loading documents from MongoDB - * one at a time. - * Unless you're an advanced user, do not instantiate this class directly. - * Use Query#cursor() instead. - * @param options query options passed to .find() - * @event cursor Emitted when the cursor is created - * @event error Emitted when an error occurred - * @event data Emitted when the stream is flowing and the next doc is ready - * @event end Emitted when the stream is exhausted - */ - constructor(query: Query, options: Object): QueryCursor; - - /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ - close(callback?: (error: any, result: any) => void): _MongoosePromise; - - /** - * Execute fn for every document in the cursor. If fn returns a promise, - * will wait for the promise to resolve before iterating on to the next one. - * Returns a promise that resolves when done. - * @param callback executed when all docs have been processed - */ - eachAsync(fn: (doc: Model) => any, callback?: (err: any) => void): _MongoosePromise>; - - /** - * Get the next document from this cursor. Will return null when there are - * no documents left. - */ - next(callback?: (err: any) => void): _MongoosePromise; - } - - /* - * section virtualtype.js - * http://mongoosejs.com/docs/api.html#virtualtype-js - */ - class VirtualType { - /** This is what mongoose uses to define virtual attributes via Schema.prototype.virtual. */ - constructor(options: Object, name: string); - /** Applies getters to value using optional scope. */ - applyGetters(value: Object, scope: Object): any; - /** Applies setters to value using optional scope. */ - applySetters(value: Object, scope: Object): any; - /** Defines a getter. */ - get(fn: Function): this; - /** Defines a setter. */ - set(fn: Function): this; - } - - /* - * section schema.js - * http://mongoosejs.com/docs/api.html#schema-js - */ - class Schema extends events.EventEmitter { - /** - * Schema constructor. - * When nesting schemas, (children in the example above), always declare - * the child schema first before passing it into its parent. - * @event init Emitted after the schema is compiled into a Model. - */ - constructor(definition?: Object, options?: SchemaOptions); - - /** Adds key path / schema type pairs to this schema. */ - add(obj: Object, prefix?: string): void; - - /** - * Iterates the schemas paths similar to Array.forEach. - * @param fn callback function - * @returns this - */ - eachPath(fn: (path: string, type: SchemaType) => void): this; - - /** - * Gets a schema option. - * @param key option name - */ - get(key: string): any; - - /** - * Defines an index (most likely compound) for this schema. - * @param options Options to pass to MongoDB driver's createIndex() function - * @param options.expires Mongoose-specific syntactic sugar, uses ms to convert - * expires option into seconds for the expireAfterSeconds in the above link. - */ - index(fields: Object, options?: { - expires?: string; - [other: string]: any; - }): this; - - /** Compiles indexes from fields and schema-level indexes */ - indexes(): any[]; - - /** - * Adds an instance method to documents constructed from Models compiled from this schema. - * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. - */ - method(method: string, fn: Function): this; - method(methodObj: { [name: string]: Function }): this; - - /** - * Gets/sets schema paths. - * Sets a path (if arity 2) - * Gets a path (if arity 1) - */ - path(path: string): SchemaType; - path(path: string, constructor: any): this; - - /** - * Returns the pathType of path for this schema. - * @returns whether it is a real, virtual, nested, or ad-hoc/undefined path. - */ - pathType(path: string): string; - - /** - * Registers a plugin for this schema. - * @param plugin callback - */ - plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; - - /** - * Defines a post hook for the document - * Post hooks fire on the event emitted from document instances of Models compiled - * from this schema. - * @param method name of the method to hook - * @param fn callback - */ - post(method: string, fn: (doc: Model) => void, ...args: any[]): this; - post(method: string, fn: (doc: Model, next: (err?: NativeError) => void, - ...otherArgs: any[]) => void): this; - - /** - * Defines a pre hook for the document. - */ - pre(method: string, fn: (next: (err?: NativeError) => void) => void, - errorCb?: (err: Error) => void): this; - pre(method: string, parallel: boolean, fn: (next: (err?: NativeError) => void, done: () => void) => void, - errorCb?: (err: Error) => void): this; - - /** - * Adds a method call to the queue. - * @param name name of the document method to call later - * @param args arguments to pass to the method - */ - queue(name: string, args: any[]): this; - - /** - * Removes the given path (or [paths]). - */ - remove(path: string | string[]): void; - - /** - * @param invalidate refresh the cache - * @returns an Array of path strings that are required by this schema. - */ - requiredPaths(invalidate?: boolean): string[]; - - /** - * Sets/gets a schema option. - * @param key option name - * @param value if not passed, the current option value is returned - */ - set(key: string): any; - set(key: string, value: any): this; - - /** - * Adds static "class" methods to Models compiled from this schema. - */ - static(name: string, fn: Function): this; - static(nameObj: { [name: string]: Function }): this; - - /** Creates a virtual type with the given name. */ - virtual(name: string, options?: Object): VirtualType; - - /** Returns the virtual type with the given name. */ - virtualpath(name: string): VirtualType; - - /** The allowed index types */ - static indexTypes: string[]; - - /** - * Reserved document keys. - * Keys in this object are names that are rejected in schema declarations - * b/c they conflict with mongoose functionality. Using these key name - * will throw an error. - */ - static reserved: Object; - - static Types: { - Array: typeof _mongoose.Schema._Types.Array; - String: typeof _mongoose.Schema._Types.String; - DocumentArray: typeof _mongoose.Schema._Types.DocumentArray; - Number: typeof _mongoose.Schema._Types.Number; - Date: typeof _mongoose.Schema._Types.Date; - Buffer: typeof _mongoose.Schema._Types.Buffer; - Boolean: typeof _mongoose.Schema._Types.Boolean; - Bool: typeof _mongoose.Schema._Types.Boolean; - ObjectId: typeof _mongoose.Schema._Types.ObjectId; - Oid: typeof _mongoose.Schema._Types.ObjectId; - Mixed: typeof _mongoose.Schema._Types.Mixed; - Object: typeof _mongoose.Schema._Types.Mixed; - Embedded: typeof _mongoose.Schema._Types.Embedded; - } - - /** Object of currently defined methods on this schema. */ - methods: any; - /** Object of currently defined statics on this schema. */ - statics: any; - } - - interface SchemaOptions { - /** defaults to null (which means use the connection's autoIndex option) */ autoIndex?: boolean; - /** defaults to true */ - bufferCommands?: boolean; - /** defaults to false */ - capped?: boolean; - /** no default */ - collection?: string; - /** defaults to false. */ - emitIndexErrors?: boolean; - /** defaults to true */ - id?: boolean; - /** defaults to true */ - _id?: boolean; - /** controls document#toObject behavior when called manually - defaults to true */ - minimize?: boolean; - read?: string; - /** defaults to true. */ - safe?: boolean; - /** defaults to null */ - shardKey?: boolean; - /** defaults to true */ - strict?: boolean; - /** no default */ - toJSON?: Object; - /** no default */ - toObject?: Object; - /** defaults to 'type' */ - typeKey?: string; - /** defaults to false */ - useNestedStrict?: boolean; - /** defaults to true */ - validateBeforeSave?: boolean; - /** defaults to "__v" */ - versionKey?: boolean; + }; + } + + /** See the node-mongodb-native driver instance for options that it understands. */ + interface ConnectionOpenSetOptions extends ConnectionOptionsBase { + /** + * If true, enables High Availability support for mongos + * If connecting to multiple mongos servers, set the mongos option to true. + */ + mongos?: boolean; + } + + /* + * section drivers/node-mongodb-native/collection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js + */ + var Collection: Collection; + interface Collection extends CollectionBase { + /** + * Collection constructor + * @param name name of the collection + * @param conn A MongooseConnection instance + * @param opts optional collection options + */ + new(name: string, conn: Connection, opts?: Object): Collection; + /** Formatter for debug print args */ + $format(arg: any): string; + /** Debug print helper */ + $print(name: any, i: any, args: any[]): void; + /** Retreives information about this collections indexes. */ + getIndexes(): any; + } + + /* + * section drivers/node-mongodb-native/connection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ + class Connection extends ConnectionBase { + /** + * Switches to a different database using the same connection pool. + * @param name The database name + * @returns New Connection Object + */ + useDb(name: string): Connection; + + /** Expose the possible connection states. */ + static STATES: Object; + } + + interface ConnectOptions extends ConnectionOpenOptions, ConnectionOpenSetOptions {} + + /* + * section error/validation.js + * http://mongoosejs.com/docs/api.html#error-validation-js + */ + class ValidationError extends Error { + /** Console.log helper */ + toString(): string; + } + + /* + * section error.js + * http://mongoosejs.com/docs/api.html#error-js + */ + class Error extends global.Error { + /** + * MongooseError constructor + * @param msg Error message + */ + constructor(msg: string); + + /** + * The default built-in validator error messages. These may be customized. + * As you might have noticed, error messages support basic templating + * {PATH} is replaced with the invalid document path + * {VALUE} is replaced with the invalid value + * {TYPE} is replaced with the validator type such as "regexp", "min", or "user defined" + * {MIN} is replaced with the declared min value for the Number.min validator + * {MAX} is replaced with the declared max value for the Number.max validator + */ + static messages: Object; + + /** For backwards compatibility. Same as mongoose.Error.messages */ + static Messages: Object; + } + + /* + * section querycursor.js + * http://mongoosejs.com/docs/api.html#querycursor-js + * + * Callback signatures are from: http://mongodb.github.io/node-mongodb-native/2.1/api/Cursor.html#close + * QueryCursor can only be accessed by query#cursor(), we only + * expose its interface to enable type-checking. + */ + interface QueryCursor extends stream.Readable { + /** + * A QueryCursor is a concurrency primitive for processing query results + * one document at a time. A QueryCursor fulfills the Node.js streams3 API, + * in addition to several other mechanisms for loading documents from MongoDB + * one at a time. + * Unless you're an advanced user, do not instantiate this class directly. + * Use Query#cursor() instead. + * @param options query options passed to .find() + * @event cursor Emitted when the cursor is created + * @event error Emitted when an error occurred + * @event data Emitted when the stream is flowing and the next doc is ready + * @event end Emitted when the stream is exhausted + */ + constructor(query: Query, options: Object): QueryCursor; + + /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ + close(callback?: (error: any, result: any) => void): _MongoosePromise; + + /** + * Execute fn for every document in the cursor. If fn returns a promise, + * will wait for the promise to resolve before iterating on to the next one. + * Returns a promise that resolves when done. + * @param callback executed when all docs have been processed + */ + eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): _MongoosePromise; + + /** + * Get the next document from this cursor. Will return null when there are + * no documents left. + */ + next(callback?: (err: any) => void): _MongoosePromise; + } + + /* + * section virtualtype.js + * http://mongoosejs.com/docs/api.html#virtualtype-js + */ + class VirtualType { + /** This is what mongoose uses to define virtual attributes via Schema.prototype.virtual. */ + constructor(options: Object, name: string); + /** Applies getters to value using optional scope. */ + applyGetters(value: Object, scope: Object): any; + /** Applies setters to value using optional scope. */ + applySetters(value: Object, scope: Object): any; + /** Defines a getter. */ + get(fn: Function): this; + /** Defines a setter. */ + set(fn: Function): this; + } + + /* + * section schema.js + * http://mongoosejs.com/docs/api.html#schema-js + */ + class Schema extends events.EventEmitter { + /** + * Schema constructor. + * When nesting schemas, (children in the example above), always declare + * the child schema first before passing it into its parent. + * @event init Emitted after the schema is compiled into a Model. + */ + constructor(definition?: Object, options?: SchemaOptions); + + /** Adds key path / schema type pairs to this schema. */ + add(obj: Object, prefix?: string): void; + + /** + * Iterates the schemas paths similar to Array.forEach. + * @param fn callback function + * @returns this + */ + eachPath(fn: (path: string, type: SchemaType) => void): this; + + /** + * Gets a schema option. + * @param key option name + */ + get(key: string): any; + + /** + * Defines an index (most likely compound) for this schema. + * @param options Options to pass to MongoDB driver's createIndex() function + * @param options.expires Mongoose-specific syntactic sugar, uses ms to convert + * expires option into seconds for the expireAfterSeconds in the above link. + */ + index(fields: Object, options?: { + expires?: string; + [other: string]: any; + }): this; + + /** Compiles indexes from fields and schema-level indexes */ + indexes(): any[]; + + /** + * Adds an instance method to documents constructed from Models compiled from this schema. + * If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods. + */ + method(method: string, fn: Function): this; + method(methodObj: { [name: string]: Function }): this; + + /** + * Gets/sets schema paths. + * Sets a path (if arity 2) + * Gets a path (if arity 1) + */ + path(path: string): SchemaType; + path(path: string, constructor: any): this; + + /** + * Returns the pathType of path for this schema. + * @returns whether it is a real, virtual, nested, or ad-hoc/undefined path. + */ + pathType(path: string): string; + + /** + * Registers a plugin for this schema. + * @param plugin callback + */ + plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; + + /** + * Defines a post hook for the document + * Post hooks fire on the event emitted from document instances of Models compiled + * from this schema. + * @param method name of the method to hook + * @param fn callback + */ + post(method: string, fn: (doc: T) => void, ...args: any[]): this; + post(method: string, fn: (doc: T, next: (err?: NativeError) => void, + ...otherArgs: any[]) => void): this; + + /** + * Defines a pre hook for the document. + */ + pre(method: string, fn: (next: (err?: NativeError) => void) => void, + errorCb?: (err: Error) => void): this; + pre(method: string, parallel: boolean, fn: (next: (err?: NativeError) => void, done: () => void) => void, + errorCb?: (err: Error) => void): this; + + /** + * Adds a method call to the queue. + * @param name name of the document method to call later + * @param args arguments to pass to the method + */ + queue(name: string, args: any[]): this; + + /** + * Removes the given path (or [paths]). + */ + remove(path: string | string[]): void; + + /** + * @param invalidate refresh the cache + * @returns an Array of path strings that are required by this schema. + */ + requiredPaths(invalidate?: boolean): string[]; + + /** + * Sets/gets a schema option. + * @param key option name + * @param value if not passed, the current option value is returned + */ + set(key: string): any; + set(key: string, value: any): this; + + /** + * Adds static "class" methods to Models compiled from this schema. + */ + static(name: string, fn: Function): this; + static(nameObj: { [name: string]: Function }): this; + + /** Creates a virtual type with the given name. */ + virtual(name: string, options?: Object): VirtualType; + + /** Returns the virtual type with the given name. */ + virtualpath(name: string): VirtualType; + + /** The allowed index types */ + static indexTypes: string[]; + + /** + * Reserved document keys. + * Keys in this object are names that are rejected in schema declarations + * b/c they conflict with mongoose functionality. Using these key name + * will throw an error. + */ + static reserved: Object; + + /** Object of currently defined methods on this schema. */ + methods: any; + /** Object of currently defined statics on this schema. */ + statics: any; + } + + interface SchemaOptions { + /** defaults to null (which means use the connection's autoIndex option) */ + autoIndex?: boolean; + /** defaults to true */ + bufferCommands?: boolean; + /** defaults to false */ + capped?: boolean; + /** no default */ + collection?: string; + /** defaults to false. */ + emitIndexErrors?: boolean; + /** defaults to true */ + id?: boolean; + /** defaults to true */ + _id?: boolean; + /** controls document#toObject behavior when called manually - defaults to true */ + minimize?: boolean; + read?: string; + /** defaults to true. */ + safe?: boolean; + /** defaults to null */ + shardKey?: boolean; + /** defaults to true */ + strict?: boolean; + /** no default */ + toJSON?: Object; + /** no default */ + toObject?: Object; + /** defaults to 'type' */ + typeKey?: string; + /** defaults to false */ + useNestedStrict?: boolean; + /** defaults to true */ + validateBeforeSave?: boolean; + /** defaults to "__v" */ + versionKey?: boolean; + /** + * skipVersioning allows excluding paths from + * versioning (the internal revision will not be + * incremented even if these paths are updated). + */ + skipVersioning?: Object; + /** + * If set timestamps, mongoose assigns createdAt + * and updatedAt fields to your schema, the type + * assigned is Date. + */ + timestamps?: Object; + } + + /* + * section document.js + * http://mongoosejs.com/docs/api.html#document-js + */ + class MongooseDocument { + /** Checks if a path is set to its default. */ + $isDefault(path?: string): boolean; + + /** + * Takes a populated field and returns it to its unpopulated state. + * If the path was not populated, this is a no-op. + */ + depopulate(path: string): void; + + /** + * Returns true if the Document stores the same data as doc. + * Documents are considered equal when they have matching _ids, unless neither document + * has an _id, in which case this function falls back to usin deepEqual(). + * @param doc a document to compare + */ + equals(doc: MongooseDocument): boolean; + + /** + * Explicitly executes population and returns a promise. + * Useful for ES2015 integration. + * @returns promise that resolves to the document when population is done + */ + execPopulate(): _MongoosePromise; + + /** + * Returns the value of a path. + * @param type optionally specify a type for on-the-fly attributes + */ + get(path: string, type?: any): any; + + /** + * Initializes the document without setters or marking anything modified. + * Called internally after a document is returned from mongodb. + * @param doc document returned by mongo + * @param fn callback + */ + init(doc: MongooseDocument, fn?: () => void): this; + init(doc: MongooseDocument, opts: Object, fn?: () => void): this; + + /** Helper for console.log */ + inspect(options?: Object): any; + + /** + * Marks a path as invalid, causing validation to fail. + * The errorMsg argument will become the message of the ValidationError. + * The value argument (if passed) will be available through the ValidationError.value property. + * @param path the field to invalidate + * @param errorMsg the error which states the reason path was invalid + * @param value optional invalid value + * @param kind optional kind property for the error + * @returns the current ValidationError, with all currently invalidated paths + */ + invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): ValidationError | boolean; + + /** Returns true if path was directly set and modified, else false. */ + isDirectModified(path: string): boolean; + + /** Checks if path was initialized */ + isInit(path: string): boolean; + + /** + * Returns true if this document was modified, else false. + * If path is given, checks if a path or any full path containing path as part of its path + * chain has been modified. + */ + isModified(path?: string): boolean; + + /** Checks if path was selected in the source query which initialized this document. */ + isSelected(path: string): boolean; + + /** + * Marks the path as having pending changes to write to the db. + * Very helpful when using Mixed types. + * @param path the path to mark modified + */ + markModified(path: string): void; + + /** Returns the list of paths that have been modified. */ + modifiedPaths(): string[]; + + /** + * Populates document references, executing the callback when complete. + * If you want to use promises instead, use this function with + * execPopulate() + * Population does not occur unless a callback is passed or you explicitly + * call execPopulate(). Passing the same path a second time will overwrite + * the previous path options. See Model.populate() for explaination of options. + * @param path The path to populate or an options object + * @param callback When passed, population is invoked + */ + populate(callback: (err: any, res: this) => void): this; + populate(path: string, callback?: (err: any, res: this) => void): this; + populate(options: ModelPopulateOptions, callback?: (err: any, res: this) => void): this; + + /** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */ + populated(path: string): any; + + /** + * Sets the value of a path, or many paths. + * @param path path or object of key/vals to set + * @param val the value to set + * @param type optionally specify a type for "on-the-fly" attributes + * @param options optionally specify options that modify the behavior of the set + */ + set(path: string, val: any, options?: Object): void; + set(path: string, val: any, type: any, options?: Object): void; + set(value: Object): void; + + /** + * The return value of this method is used in calls to JSON.stringify(doc). + * This method accepts the same options as Document#toObject. To apply the + * options to every document of your schema by default, set your schemas + * toJSON option to the same argument. + */ + toJSON(options?: DocumentToObjectOptions): Object; + + /** + * Converts this document into a plain javascript object, ready for storage in MongoDB. + * Buffers are converted to instances of mongodb.Binary for proper storage. + */ + toObject(options?: DocumentToObjectOptions): Object; + + /** Helper for console.log */ + toString(): string; + + /** + * Clears the modified state on the specified path. + * @param path the path to unmark modified + */ + unmarkModified(path: string): void; + + /** Sends an update command with this document _id as the query selector. */ + update(doc: Object, callback?: (err: any, raw: any) => void): Query; + update(doc: Object, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + + /** + * Executes registered validation rules for this document. + * @param optional options internal options + * @param callback callback called after validation completes, passing an error if one occurred + */ + validate(callback?: (err: any) => void): _MongoosePromise; + validate(optional: Object, callback?: (err: any) => void): _MongoosePromise; + + /** + * Executes registered validation rules (skipping asynchronous validators) for this document. + * This method is useful if you need synchronous validation. + * @param pathsToValidate only validate the given paths + * @returns MongooseError if there are errors during validation, or undefined if there is no error. + */ + validateSync(pathsToValidate: string | string[]): Error; + + /** Hash containing current validation errors. */ + errors: Object; + /** The string version of this documents _id. */ + id: string; + /** This documents _id. */ + _id: any; + /** Boolean flag specifying if the document is new. */ + isNew: boolean; + /** The documents schema. */ + schema: Schema; + } + + interface DocumentToObjectOptions { + /** apply all getters (path and virtual getters) */ + getters?: boolean; + /** apply virtual getters (can override getters option) */ + virtuals?: boolean; + /** remove empty objects (defaults to true) */ + minimize?: boolean; + /** + * A transform function to apply to the resulting document before returning + * @param doc The mongoose document which is being converted + * @param ret The plain object representation which has been converted + * @param options The options in use (either schema options or the options passed inline) + */ + transform?: (doc: any, ret: Object, options: Object) => any; + /** depopulate any populated paths, replacing them with their original refs (defaults to false) */ + depopulate?: boolean; + /** whether to include the version key (defaults to true) */ + versionKey?: boolean; + /** + * keep the order of object keys. If this is set to true, + * Object.keys(new Doc({ a: 1, b: 2}).toObject()) will + * always produce ['a', 'b'] (defaults to false) + */ + retainKeyOrder?: boolean; + } + + namespace Types { + /* + * section types/subdocument.js + * http://mongoosejs.com/docs/api.html#types-subdocument-js + */ + class Subdocument extends MongooseDocument { + /** Returns the top level document of this sub-document. */ + ownerDocument(): MongooseDocument; + /** - * skipVersioning allows excluding paths from - * versioning (the internal revision will not be - * incremented even if these paths are updated). + * Null-out this subdoc + * @param callback optional callback for compatibility with Document.prototype.remove */ - skipVersioning?: Object; - /** - * If set timestamps, mongoose assigns createdAt - * and updatedAt fields to your schema, the type - * assigned is Date. - */ - timestamps?: Object; + remove(callback?: (err: any) => void): void; + remove(options: Object, callback?: (err: any) => void): void; } /* - * section document.js - * http://mongoosejs.com/docs/api.html#document-js - */ - class Document { - /** Checks if a path is set to its default. */ - $isDefault(path?: string): boolean; + * section types/array.js + * http://mongoosejs.com/docs/api.html#types-array-js + */ + class Array extends global.Array { + /** + * Atomically shifts the array at most one time per document save(). + * Calling this mulitple times on an array before saving sends the same command as + * calling it once. This update is implemented using the MongoDB $pop method which + * enforces this restriction. + */ + $shift(): T; + + /** Alias of pull */ + remove(...args: any[]): this; /** - * Takes a populated field and returns it to its unpopulated state. - * If the path was not populated, this is a no-op. + * Pops the array atomically at most one time per document save(). + * Calling this mulitple times on an array before saving sends the same command as + * calling it once. This update is implemented using the MongoDB $pop method which + * enforces this restriction. */ - depopulate(path: string): void; + $pop(): T; /** - * Returns true if the Document stores the same data as doc. - * Documents are considered equal when they have matching _ids, unless neither document - * has an _id, in which case this function falls back to usin deepEqual(). - * @param doc a document to compare + * Adds values to the array if not already present. + * @returns the values that were added */ - equals(doc: Document): boolean; + addToSet(...args: any[]): T[]; /** - * Explicitly executes population and returns a promise. - * Useful for ES2015 integration. - * @returns promise that resolves to the document when population is done + * Return the index of obj or -1 if not found. + * @param obj he item to look for */ - execPopulate(): _MongoosePromise; - - /** - * Returns the value of a path. - * @param type optionally specify a type for on-the-fly attributes - */ - get(path: string, type?: any): any; - - /** - * Initializes the document without setters or marking anything modified. - * Called internally after a document is returned from mongodb. - * @param doc document returned by mongo - * @param fn callback - */ - init(doc: Document, fn?: () => void): this; - init(doc: Document, opts: Object, fn?: () => void): this; + indexOf(obj: any): number; /** Helper for console.log */ - inspect(options?: Object): any; + inspect(): any; + + /** + * Marks the entire array as modified, which if saved, will store it as a $set + * operation, potentially overwritting any changes that happen between when you + * retrieved the object and when you save it. + * @returns new length of the array + */ + nonAtomicPush(...args: any[]): number; + + /** + * Wraps Array#pop with proper change tracking. + * marks the entire array as modified which will pass the entire thing to $set + * potentially overwritting any changes that happen between when you retrieved + * the object and when you save it. + */ + pop(): T; + + /** + * Pulls items from the array atomically. Equality is determined by casting + * the provided value to an embedded document and comparing using + * the Document.equals() function. + */ + pull(...args: any[]): this; + + /** + * Wraps Array#push with proper change tracking. + * @returns new length of the array + */ + push(...args: any[]): number; + + /** Sets the casted val at index i and marks the array modified. */ + set(i: number, val: any): this; + + /** + * Wraps Array#shift with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + shift(): T; + + /** + * Wraps Array#sort with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + // some lib.d.ts have return type "this" and others have return type "T[]" + // which causes errors. Let the inherited array provide the sort() method. + //sort(compareFn?: (a: T, b: T) => number): T[]; + + /** + * Wraps Array#splice with proper change tracking and casting. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + splice(...args: any[]): T[]; + + /** Returns a native js Array. */ + toObject(options?: Object): T[]; + + /** + * Wraps Array#unshift with proper change tracking. + * Marks the entire array as modified, which if saved, will store it as a $set operation, + * potentially overwritting any changes that happen between when you retrieved the object + * and when you save it. + */ + unshift(...args: any[]): number; + } + + /* + * section types/documentarray.js + * http://mongoosejs.com/docs/api.html#types-documentarray-js + */ + class DocumentArray extends Types.Array { + /** + * Creates a subdocument casted to this schema. + * This is the same subdocument constructor used for casting. + * @param obj the value to cast to this arrays SubDocument schema + */ + create(obj: Object): Subdocument; + + /** + * Searches array items for the first document with a matching _id. + * @returns the subdocument or null if not found. + */ + id(id: ObjectId | string | number | NativeBuffer): Embedded; + + /** Helper for console.log */ + inspect(): T[]; + + /** + * Returns a native js Array of plain js objects + * @param options optional options to pass to each documents toObject + * method call during conversion + */ + toObject(options?: Object): T[]; + } + + /* + * section types/buffer.js + * http://mongoosejs.com/docs/api.html#types-buffer-js + */ + class Buffer extends global.Buffer { + /** + * Copies the buffer. + * Buffer#copy does not mark target as modified so you must copy + * from a MongooseBuffer for it to work as expected. This is a + * work around since copy modifies the target, not this. + */ + copy(target: NativeBuffer, ...nodeBufferArgs: any[]): number; + + /** Determines if this buffer is equals to other buffer */ + equals(other: NativeBuffer): boolean; + + /** Sets the subtype option and marks the buffer modified. */ + subtype(subtype: number): void; + + /** Converts this buffer to its Binary type representation. */ + toObject(subtype?: number): mongodb.Binary; + + /** Writes the buffer. */ + write(string: string, ...nodeBufferArgs: any[]): number; + } + + /* + * section types/objectid.js + * http://mongoosejs.com/docs/api.html#types-objectid-js + */ + var ObjectId: typeof mongodb.ObjectID; + interface ObjectId extends mongodb.ObjectID {} + + /* + * section types/embedded.js + * http://mongoosejs.com/docs/api.html#types-embedded-js + */ + class Embedded extends MongooseDocument { + /** Helper for console.log */ + inspect(): Object; /** * Marks a path as invalid, causing validation to fail. - * The errorMsg argument will become the message of the ValidationError. - * The value argument (if passed) will be available through the ValidationError.value property. * @param path the field to invalidate - * @param errorMsg the error which states the reason path was invalid - * @param value optional invalid value - * @param kind optional kind property for the error - * @returns the current ValidationError, with all currently invalidated paths + * @param err error which states the reason path was invalid */ - invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): ValidationError | boolean; + invalidate(path: string, err: string | NativeError): boolean; - /** Returns true if path was directly set and modified, else false. */ - isDirectModified(path: string): boolean; + /** Returns the top level document of this sub-document. */ + ownerDocument(): MongooseDocument; + /** Returns this sub-documents parent document. */ + parent(): MongooseDocument; + /** Returns this sub-documents parent array. */ + parentArray(): DocumentArray; - /** Checks if path was initialized */ - isInit(path: string): boolean; + /** Removes the subdocument from its parent array. */ + remove(options?: { + noop?: boolean; + }, fn?: (err: any) => void): this; /** - * Returns true if this document was modified, else false. - * If path is given, checks if a path or any full path containing path as part of its path - * chain has been modified. - */ - isModified(path?: string): boolean; - - /** Checks if path was selected in the source query which initialized this document. */ - isSelected(path: string): boolean; - - /** - * Marks the path as having pending changes to write to the db. - * Very helpful when using Mixed types. - * @param path the path to mark modified + * Marks the embedded doc modified. + * @param path the path which changed */ markModified(path: string): void; - - /** Returns the list of paths that have been modified. */ - modifiedPaths(): string[]; - - /** - * Populates document references, executing the callback when complete. - * If you want to use promises instead, use this function with - * execPopulate() - * Population does not occur unless a callback is passed or you explicitly - * call execPopulate(). Passing the same path a second time will overwrite - * the previous path options. See Model.populate() for explaination of options. - * @param path The path to populate or an options object - * @param callback When passed, population is invoked - */ - populate(callback: (err: any, res: this) => void): this; - populate(path: string, callback?: (err: any, res: this) => void): this; - populate(options: ModelPopulateOptions, callback?: (err: any, res: this) => void): this; - - /** Gets _id(s) used during population of the given path. If the path was not populated, undefined is returned. */ - populated(path: string): any; - - /** - * Sets the value of a path, or many paths. - * @param path path or object of key/vals to set - * @param val the value to set - * @param type optionally specify a type for "on-the-fly" attributes - * @param options optionally specify options that modify the behavior of the set - */ - set(path: string, val: any, options?: Object): void; - set(path: string, val: any, type: any, options?: Object): void; - set(value: Object): void; - - /** - * The return value of this method is used in calls to JSON.stringify(doc). - * This method accepts the same options as Document#toObject. To apply the - * options to every document of your schema by default, set your schemas - * toJSON option to the same argument. - */ - toJSON(options?: DocumentToObjectOptions): Object; - - /** - * Converts this document into a plain javascript object, ready for storage in MongoDB. - * Buffers are converted to instances of mongodb.Binary for proper storage. - */ - toObject(options?: DocumentToObjectOptions): Object; - - /** Helper for console.log */ - toString(): string; - - /** - * Clears the modified state on the specified path. - * @param path the path to unmark modified - */ - unmarkModified(path: string): void; - - /** Sends an update command with this document _id as the query selector. */ - update(doc: Object, callback?: (err: any, raw: any) => void): Query; - update(doc: Object, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; - - /** - * Executes registered validation rules for this document. - * @param optional options internal options - * @param callback callback called after validation completes, passing an error if one occurred - */ - validate(callback?: (err: any) => void): _MongoosePromise; - validate(optional: Object, callback?: (err: any) => void): _MongoosePromise; - - /** - * Executes registered validation rules (skipping asynchronous validators) for this document. - * This method is useful if you need synchronous validation. - * @param pathsToValidate only validate the given paths - * @returns MongooseError if there are errors during validation, or undefined if there is no error. - */ - validateSync(pathsToValidate: string | string[]): _mongoose.Error; - - /** Hash containing current validation errors. */ - errors: Object; - /** The string version of this documents _id. */ - id: string; - /** This documents _id. */ - _id: any; - /** Boolean flag specifying if the document is new. */ - isNew: boolean; - /** The documents schema. */ - schema: Schema; } + } - interface DocumentToObjectOptions { - /** apply all getters (path and virtual getters) */ - getters?: boolean; - /** apply virtual getters (can override getters option) */ - virtuals?: boolean; - /** remove empty objects (defaults to true) */ - minimize?: boolean; - /** - * A transform function to apply to the resulting document before returning - * @param doc The mongoose document which is being converted - * @param ret The plain object representation which has been converted - * @param options The options in use (either schema options or the options passed inline) - */ - transform?: (doc: Model, ret: Object, options: Object) => any; - /** depopulate any populated paths, replacing them with their original refs (defaults to false) */ - depopulate?: boolean; - /** whether to include the version key (defaults to true) */ - versionKey?: boolean; - /** - * keep the order of object keys. If this is set to true, - * Object.keys(new Doc({ a: 1, b: 2}).toObject()) will - * always produce ['a', 'b'] (defaults to false) - */ - retainKeyOrder?: boolean; - } + /* + * section query.js + * http://mongoosejs.com/docs/api.html#query-js + */ + class Query extends ModelQuery {} - namespace Types { - /* - * section types/subdocument.js - * http://mongoosejs.com/docs/api.html#types-subdocument-js - */ - class Subdocument extends Document { - /** Returns the top level document of this sub-document. */ - ownerDocument(): Document; - - /** - * Null-out this subdoc - * @param callback optional callback for compatibility with Document.prototype.remove - */ - remove(callback?: (err: any) => void): void; - remove(options: Object, callback?: (err: any) => void): void; - } - - /* - * section types/array.js - * http://mongoosejs.com/docs/api.html#types-array-js - */ - class Array extends global.Array { - /** - * Atomically shifts the array at most one time per document save(). - * Calling this mulitple times on an array before saving sends the same command as - * calling it once. This update is implemented using the MongoDB $pop method which - * enforces this restriction. - */ - $shift(): T; - - /** Alias of pull */ - remove(...args: any[]): this; - - /** - * Pops the array atomically at most one time per document save(). - * Calling this mulitple times on an array before saving sends the same command as - * calling it once. This update is implemented using the MongoDB $pop method which - * enforces this restriction. - */ - $pop(): T; - - /** - * Adds values to the array if not already present. - * @returns the values that were added - */ - addToSet(...args: any[]): T[]; - - /** - * Return the index of obj or -1 if not found. - * @param obj he item to look for - */ - indexOf(obj: any): number; - - /** Helper for console.log */ - inspect(): any; - - /** - * Marks the entire array as modified, which if saved, will store it as a $set - * operation, potentially overwritting any changes that happen between when you - * retrieved the object and when you save it. - * @returns new length of the array - */ - nonAtomicPush(...args: any[]): number; - - /** - * Wraps Array#pop with proper change tracking. - * marks the entire array as modified which will pass the entire thing to $set - * potentially overwritting any changes that happen between when you retrieved - * the object and when you save it. - */ - pop(): T; - - /** - * Pulls items from the array atomically. Equality is determined by casting - * the provided value to an embedded document and comparing using - * the Document.equals() function. - */ - pull(...args: any[]): this; - - /** - * Wraps Array#push with proper change tracking. - * @returns new length of the array - */ - push(...args: any[]): number; - - /** Sets the casted val at index i and marks the array modified. */ - set(i: number, val: any): this; - - /** - * Wraps Array#shift with proper change tracking. - * Marks the entire array as modified, which if saved, will store it as a $set operation, - * potentially overwritting any changes that happen between when you retrieved the object - * and when you save it. - */ - shift(): T; - - /** - * Wraps Array#sort with proper change tracking. - * Marks the entire array as modified, which if saved, will store it as a $set operation, - * potentially overwritting any changes that happen between when you retrieved the object - * and when you save it. - */ - // some lib.d.ts have return type "this" and others have return type "T[]" - // which causes errors. Let the inherited array provide the sort() method. - //sort(compareFn?: (a: T, b: T) => number): T[]; - - /** - * Wraps Array#splice with proper change tracking and casting. - * Marks the entire array as modified, which if saved, will store it as a $set operation, - * potentially overwritting any changes that happen between when you retrieved the object - * and when you save it. - */ - splice(...args: any[]): T[]; - - /** Returns a native js Array. */ - toObject(options?: Object): T[]; - - /** - * Wraps Array#unshift with proper change tracking. - * Marks the entire array as modified, which if saved, will store it as a $set operation, - * potentially overwritting any changes that happen between when you retrieved the object - * and when you save it. - */ - unshift(...args: any[]): number; - } - - /* - * section types/documentarray.js - * http://mongoosejs.com/docs/api.html#types-documentarray-js - */ - class DocumentArray extends _mongoose.Types.Array { - /** - * Creates a subdocument casted to this schema. - * This is the same subdocument constructor used for casting. - * @param obj the value to cast to this arrays SubDocument schema - */ - create(obj: Object): Subdocument; - - /** - * Searches array items for the first document with a matching _id. - * @returns the subdocument or null if not found. - */ - id(id: ObjectId | string | number | NativeBuffer): Embedded; - - /** Helper for console.log */ - inspect(): T[]; - - /** - * Returns a native js Array of plain js objects - * @param options optional options to pass to each documents toObject - * method call during conversion - */ - toObject(options?: Object): T[]; - } - - /* - * section types/buffer.js - * http://mongoosejs.com/docs/api.html#types-buffer-js - */ - class Buffer extends global.Buffer { - /** - * Copies the buffer. - * Buffer#copy does not mark target as modified so you must copy - * from a MongooseBuffer for it to work as expected. This is a - * work around since copy modifies the target, not this. - */ - copy(target: NativeBuffer, ...nodeBufferArgs: any[]): number; - - /** Determines if this buffer is equals to other buffer */ - equals(other: NativeBuffer): boolean; - - /** Sets the subtype option and marks the buffer modified. */ - subtype(subtype: number): void; - - /** Converts this buffer to its Binary type representation. */ - toObject(subtype?: number): mongodb.Binary; - - /** Writes the buffer. */ - write(string: string, ...nodeBufferArgs: any[]): number; - } - - /* - * section types/objectid.js - * http://mongoosejs.com/docs/api.html#types-objectid-js - */ - var ObjectId: typeof mongodb.ObjectID; - interface ObjectId extends mongodb.ObjectID {} - - /* - * section types/embedded.js - * http://mongoosejs.com/docs/api.html#types-embedded-js - */ - class Embedded extends Document { - /** Helper for console.log */ - inspect(): Object; - - /** - * Marks a path as invalid, causing validation to fail. - * @param path the field to invalidate - * @param err error which states the reason path was invalid - */ - invalidate(path: string, err: string | NativeError): boolean; - - /** Returns the top level document of this sub-document. */ - ownerDocument(): Document; - /** Returns this sub-documents parent document. */ - parent(): Document; - /** Returns this sub-documents parent array. */ - parentArray(): DocumentArray; - - /** Removes the subdocument from its parent array. */ - remove(options?: { - noop?: boolean; - }, fn?: (err: any) => void): this; - - /** - * Marks the embedded doc modified. - * @param path the path which changed - */ - markModified(path: string): void; - } - } - - /* - * section query.js - * http://mongoosejs.com/docs/api.html#query-js + /* + * Query.find() will return Query[]> however we need the + * type T to create this so we save T in another parameter. + */ + class ModelQuery extends mquery { + /** + * Specifies a javascript function or expression to pass to MongoDBs query system. + * Only use $where when you have a condition that cannot be met using other MongoDB + * operators like $lt. Be sure to read about all of its caveats before using. + * @param js javascript string or function */ - type Query = ModelQuery; - - /* - * Query.find() will return Query[]> however we need the - * type T to create this so we save T in another parameter. - */ - class ModelQuery extends mquery { - /** - * Specifies a javascript function or expression to pass to MongoDBs query system. - * Only use $where when you have a condition that cannot be met using other MongoDB - * operators like $lt. Be sure to read about all of its caveats before using. - * @param js javascript string or function - */ - $where(js: string | Function): this; - - /** - * Specifies an $all query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - all(val: number): this; - all(path: string, val: number): this; - - /** - * Specifies arguments for a $and condition. - * @param array array of conditions - */ - and(array: Object[]): this; - - /** Specifies the batchSize option. Cannot be used with distinct() */ - batchSize(val: number): this; - - /** - * Specifies a $box condition - * @param Upper Right Coords - */ - box(val: Object): this; - box(lower: number[], upper: number[]): this; - - /** Casts this query to the schema of model, If obj is present, it is cast instead of this query.*/ - cast(model: Model | ModelConstructor, obj?: Object): Object; - - /** - * Executes the query returning a Promise which will be - * resolved with either the doc(s) or rejected with the error. - * Like .then(), but only takes a rejection handler. - */ - catch(reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; - - /** - * DEPRECATED Alias for circle - * Specifies a $center or $centerSphere condition. - * @deprecated Use circle instead. - */ - center(area: Object): this; - center(path: string, area: Object): this; - - /** - * DEPRECATED Specifies a $centerSphere condition - * @deprecated Use circle instead. - */ - centerSphere(path: string, val: Object): this; - centerSphere(val: Object): this; - - /** Specifies a $center or $centerSphere condition. */ - circle(area: Object): this; - circle(path: string, area: Object): this; - - /** Specifies the comment option. Cannot be used with distinct() */ - comment(val: string): this; - - /** - * Specifying this query as a count query. Passing a callback executes the query. - * @param criteria mongodb selector - */ - count(callback?: (err: any, count: number) => void): Query; - count(criteria: Object, callback?: (err: any, count: number) => void): Query; - - /** - * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a - * Streams3-compatible interface, as well as a .next() function. - */ - cursor(options?: Object): QueryCursor; - - /** Declares or executes a distict() operation. Passing a callback executes the query. */ - distinct(callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, criteria: Object | Query, - callback?: (err: any, res: any[]) => void): Query; - - /** Specifies an $elemMatch condition */ - elemMatch(criteria: (elem: Query) => void): this; - elemMatch(criteria: Object): this; - elemMatch(path: string | Object | Function, criteria: (elem: Query) => void): this; - elemMatch(path: string | Object | Function, criteria: Object): this; - - /** Specifies the complementary comparison value for paths specified with where() */ - equals(val: Object): this; - - /** Executes the query */ - exec(callback?: (err: any, res: T) => void): _MongoosePromise; - exec(operation: string | Function, callback?: (err: any, res: T) => void): _MongoosePromise; - - /** Specifies an $exists condition */ - exists(val?: boolean): this; - exists(path: string, val?: boolean): this; - - /** - * Finds documents. When no callback is passed, the query is not executed. When the - * query is executed, the result will be an array of documents. - * @param criteria mongodb selector - */ - find(callback?: (err: any, res: Model[]) => void): ModelQuery[], ModelType>; - find(criteria: Object, - callback?: (err: any, res: Model[]) => void): ModelQuery[], ModelType>; - - /** - * Declares the query a findOne operation. When executed, the first found document is - * passed to the callback. Passing a callback executes the query. The result of the query - * is a single document. - * @param criteria mongodb selector - * @param projection optional fields to return - */ - findOne(callback?: (err: any, res: Model) => void): ModelQuery, ModelType>; - findOne(criteria: Object, - callback?: (err: any, res: Model) => void): ModelQuery, ModelType>; - - /** - * Issues a mongodb findAndModify remove command. - * Finds a matching document, removes it, passing the found document (if any) to the - * callback. Executes immediately if callback is passed. - */ - findOneAndRemove(callback?: (error: any, doc: Model, result: any) => void): ModelQuery, ModelType>; - findOneAndRemove(conditions: Object, - callback?: (error: any, doc: Model, result: any) => void): ModelQuery, ModelType>; - findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, - callback?: (error: any, doc: Model, result: any) => void): ModelQuery, ModelType>; - - /** - * Issues a mongodb findAndModify update command. - * Finds a matching document, updates it according to the update arg, passing any options, and returns - * the found document (if any) to the callback. The query executes immediately if callback is passed. - */ - findOneAndUpdate(callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; - findOneAndUpdate(update: Object, - callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; - findOneAndUpdate(query: Object | Query, update: Object, - callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; - findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; - - /** - * Specifies a $geometry condition. geometry() must come after either intersects() or within(). - * @param object Must contain a type property which is a String and a coordinates property which - * is an Array. See the examples. - */ - geometry(object: { type: string, coordinates: any[] }): this; - - /** - * Returns the current query conditions as a JSON object. - * @returns current query conditions - */ - getQuery(): any; - - /** - * Returns the current update operations as a JSON object. - * @returns current update operations - */ - getUpdate(): any; - - /** - * Specifies a $gt query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - gt(val: number): this; - gt(path: string, val: number): this; - - /** - * Specifies a $gte query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - gte(val: number): this; - gte(path: string, val: number): this; - - /** - * Sets query hints. - * @param val a hint object - */ - hint(val: Object): this; - - /** - * Specifies an $in query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - in(val: any[]): this; - in(path: string, val: any[]): this; - - /** Declares an intersects query for geometry(). MUST be used after where(). */ - intersects(arg?: Object): this; - - /** - * Sets the lean option. - * Documents returned from queries with the lean option enabled are plain - * javascript objects, not MongooseDocuments. They have no save method, - * getters/setters or other Mongoose magic applied. - * @param bool defaults to true - */ - lean(bool?: boolean): Query; - - /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ - limit(val: number): this; - - /** - * Specifies a $lt query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - lt(val: number): this; - lt(path: string, val: number): this; - - /** - * Specifies a $lte query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - lte(val: number): this; - lte(path: string, val: number): this; - - /** - * Specifies a $maxDistance query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - maxDistance(val: number): this; - maxDistance(path: string, val: number): this; - - /** @deprecated Alias of maxScan */ - maxscan(val: number): this; - /** Specifies the maxScan option. Cannot be used with distinct() */ - maxScan(val: number): this; - - /** - * Merges another Query or conditions object into this one. - * When a Query is passed, conditions, field selection and options are merged. - */ - merge(source: Object | Query): this; - - /** Specifies a $mod condition */ - mod(val: number[]): this; - mod(path: string, val: number[]): this; - - /** - * Specifies a $ne query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - ne(val: any): this; - ne(path: string, val: any): this; - - /** Specifies a $near or $nearSphere condition. */ - near(val: Object): this; - near(path: string, val: Object): this; - - /** - * DEPRECATED Specifies a $nearSphere condition - * @deprecated Use query.near() instead with the spherical option set to true. - */ - nearSphere(val: Object): this; - nearSphere(path: string, val: Object): this; - - /** - * Specifies a $nin query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - nin(val: any[]): this; - nin(path: string, val: any[]): this; - - /** - * Specifies arguments for a $nor condition. - * @param array array of conditions - */ - nor(array: Object[]): this; - - /** - * Specifies arguments for an $or condition. - * @param array array of conditions - */ - or(array: Object[]): this; - - /** Specifies a $polygon condition */ - polygon(...coordinatePairs: number[][]): this; - polygon(path: string, ...coordinatePairs: number[][]): this; - - /** - * Specifies paths which should be populated with other documents. - * Paths are populated after the query executes and a response is received. A separate - * query is then executed for each path specified for population. After a response for - * each query has also been returned, the results are passed to the callback. - * @param path either the path to populate or an object specifying all parameters - * @param select Field selection for the population query - * @param model The model you wish to use for population. If not specified, populate - * will look up the model by the name in the Schema's ref field. - * @param match Conditions for the population query - * @param options Options for the population query (sort, etc) - */ - populate(path: string | Object, select?: string | Object, model?: string | Model, - match?: Object, options?: Object): this; - populate(options: ModelPopulateOptions): this; - - /** - * Determines the MongoDB nodes from which to read. - * @param pref one of the listed preference options or aliases - * @tags optional tags for this query - */ - read(pref: string, tags?: Object[]): this; - - /** - * Specifies a $regex query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - regex(val: RegExp): this; - regex(path: string, val: RegExp): this; - - /** - * Declare and/or execute this query as a remove() operation. - * The operation is only executed when a callback is passed. To force execution without a callback, - * you must first call remove() and then execute it by using the exec() method. - * @param criteria mongodb selector - */ - remove(callback?: (err: any) => void): Query; - remove(criteria: Object | Query, callback?: (err: any) => void): Query; - - /** Specifies which document fields to include or exclude (also known as the query "projection") */ - select(arg: string | Object): this; - /** Determines if field selection has been made. */ - selected(): boolean; - /** Determines if exclusive field selection has been made.*/ - selectedExclusively(): boolean; - /** Determines if inclusive field selection has been made. */ - selectedInclusively(): boolean; - /** Sets query options. */ - setOptions(options: Object): this; - - /** - * Specifies a $size query condition. - * When called with one argument, the most recent path passed to where() is used. - */ - size(val: number): this; - size(path: string, val: number): this; - - /** Specifies the number of documents to skip. Cannot be used with distinct() */ - skip(val: number): this; - - /** - * DEPRECATED Sets the slaveOk option. - * @param v defaults to true - * @deprecated in MongoDB 2.2 in favor of read preferences. - */ - slaveOk(v?: boolean): this; - - /** - * Specifies a $slice projection for an array. - * @param val number/range of elements to slice - */ - slice(val: number | number[]): this; - slice(path: string, val: number | number[]): this; - - /** Specifies this query as a snapshot query. Cannot be used with distinct() */ - snapshot(v?: boolean): this; - - /** - * Sets the sort order - * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. - * If a string is passed, it must be a space delimited list of path names. The - * sort order of each path is ascending unless the path name is prefixed with - - * which will be treated as descending. - */ - sort(arg: string | Object): this; - - /** Returns a Node.js 0.8 style read stream interface. */ - stream(options?: { transform?: Function; }): QueryStream; - - /** - * Sets the tailable option (for use with capped collections). Cannot be used with distinct() - * @param bool defaults to true - * @param opts options to set - * @param opts.numberOfRetries if cursor is exhausted, retry this many times before giving up - * @param opts.tailableRetryInterval if cursor is exhausted, wait this many milliseconds before retrying - */ - tailable(bool?: boolean, opts?: { - numberOfRetries?: number; - tailableRetryInterval?: number; - }): this; - - /** Executes this query and returns a promise */ - then(resolve?: (res: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; - - /** - * Converts this query to a customized, reusable query - * constructor with all arguments and options retained. - */ - toConstructor(): typeof ModelQuery; - - /** - * Declare and/or execute this query as an update() operation. - * All paths passed that are not $atomic operations will become $set ops. - * @param doc the update command - */ - update(callback?: (err: any, affectedRows: number) => void): Query; - update(doc: Object, callback?: (err: any, affectedRows: number) => void): Query; - update(criteria: Object, doc: Object, - callback?: (err: any, affectedRows: number) => void): Query; - update(criteria: Object, doc: Object, options: QueryUpdateOptions, - callback?: (err: any, affectedRows: number) => void): Query; - - /** Specifies a path for use with chaining. */ - where(path?: string | Object, val?: any): this; - - /** Defines a $within or $geoWithin argument for geo-spatial queries. */ - within(val?: Object): this; - within(coordinate: number[], ...coordinatePairs: number[][]): this; - - /** Flag to opt out of using $geoWithin. */ - static use$geoWithin: boolean; - } - - // https://github.com/aheckmann/mquery - // mquery currently does not have a type definition please - // replace it if one is ever created - class mquery {} - - interface QueryFindOneAndRemoveOptions { - /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ - sort?: any; - /** puts a time limit on the query - requires mongodb >= 2.6.0 */ - maxTimeMS?: number; - /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ - passRawResult?: boolean; - } - - interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions { - /** if true, return the modified document rather than the original. defaults to false (changed in 4.0) */ - new?: boolean; - /** creates the object if it doesn't exist. defaults to false. */ - upsert?: boolean; - /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ - fields?: Object | string; - /** if true, runs update validators on this command. Update validators validate the update operation against the model's schema. */ - runValidators?: boolean; - /** - * if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document - * is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator. - */ - setDefaultsOnInsert?: boolean; - /** - * if set to 'query' and runValidators is on, this will refer to the query in custom validator - * functions that update validation runs. Does nothing if runValidators is false. - */ - context?: string; - } - - interface QueryUpdateOptions extends ModelUpdateOptions { - /** - * if set to 'query' and runValidators is on, this will refer to the query - * in customvalidator functions that update validation runs. Does nothing - * if runValidators is false. - */ - context?: string; - } - - namespace Schema { - namespace _Types { - /* - * section schema/array.js - * http://mongoosejs.com/docs/api.html#schema-array-js - */ - class Array extends SchemaType { - /** Array SchemaType constructor */ - constructor(key: string, cast?: SchemaType, options?: Object); - - /** - * Check if the given value satisfies a required validator. The given value - * must be not null nor undefined, and have a non-zero length. - */ - checkRequired(value: T): boolean; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/string.js - * http://mongoosejs.com/docs/api.html#schema-string-js - */ - class String extends SchemaType { - /** String SchemaType constructor. */ - constructor(key: string, options?: Object); - - /** Check if the given value satisfies a required validator. */ - checkRequired(value: any, doc: Document): boolean; - - /** - * Adds an enum validator - * @param args enumeration values - */ - enum(args: string | string[] | Object): this; - - /** Adds a lowercase setter. */ - lowercase(): this; - - /** - * Sets a regexp validator. Any value that does not pass regExp.test(val) will fail validation. - * @param regExp regular expression to test against - * @param message optional custom error message - */ - match(regExp: RegExp, message?: string): this; - - /** - * Sets a maximum length validator. - * @param value maximum string length - * @param message optional custom error message - */ - maxlength(value: number, message?: string): this; - - /** - * Sets a minimum length validator. - * @param value minimum string length - * @param message optional custom error message - */ - minlength(value: number, message?: string): this; - - /** Adds a trim setter. The string value will be trimmed when set. */ - trim(): this; - /** Adds an uppercase setter. */ - uppercase(): this; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - - } - - /* - * section schema/documentarray.js - * http://mongoosejs.com/docs/api.html#schema-documentarray-js - */ - class DocumentArray extends Array { - /** SubdocsArray SchemaType constructor */ - constructor(key: string, schema: Schema, options?: Object); - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/number.js - * http://mongoosejs.com/docs/api.html#schema-number-js - */ - class Number extends SchemaType { - /** Number SchemaType constructor. */ - constructor(key: string, options?: Object); - - /** Check if the given value satisfies a required validator. */ - checkRequired(value: any, doc: Document): boolean; - - /** - * Sets a maximum number validator. - * @param maximum number - * @param message optional custom error message - */ - max(maximum: number, message?: string): this; - - /** - * Sets a minimum number validator. - * @param value minimum number - * @param message optional custom error message - */ - min(value: number, message?: string): this; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/date.js - * http://mongoosejs.com/docs/api.html#schema-date-js - */ - class Date extends SchemaType { - /** Date SchemaType constructor. */ - constructor(key: string, options?: Object); - - /** - * Check if the given value satisfies a required validator. To satisfy - * a required validator, the given value must be an instance of Date. - */ - checkRequired(value: any, doc: Document): boolean; - - /** Declares a TTL index (rounded to the nearest second) for Date types only. */ - expires(when: number | string): this; - - /** - * Sets a maximum date validator. - * @param maximum date - * @param message optional custom error message - */ - max(maximum: NativeDate, message?: string): this; - - /** - * Sets a minimum date validator. - * @param value minimum date - * @param message optional custom error message - */ - min(value: NativeDate, message?: string): this; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/buffer.js - * http://mongoosejs.com/docs/api.html#schema-buffer-js - */ - class Buffer extends SchemaType { - /** Buffer SchemaType constructor */ - constructor(key: string, options?: Object); - - /** - * Check if the given value satisfies a required validator. To satisfy a - * required validator, a buffer must not be null or undefined and have - * non-zero length. - */ - checkRequired(value: any, doc: Document): boolean; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - - } - - /* - * section schema/boolean.js - * http://mongoosejs.com/docs/api.html#schema-boolean-js - */ - class Boolean extends SchemaType { - /** Boolean SchemaType constructor. */ - constructor(path: string, options?: Object); - - /** - * Check if the given value satisfies a required validator. For a - * boolean to satisfy a required validator, it must be strictly - * equal to true or to false. - */ - checkRequired(value: any): boolean; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/objectid.js - * http://mongoosejs.com/docs/api.html#schema-objectid-js - */ - class ObjectId extends SchemaType { - /** ObjectId SchemaType constructor. */ - constructor(key: string, options?: Object); - - /** - * Adds an auto-generated ObjectId default if turnOn is true. - * @param turnOn auto generated ObjectId defaults - */ - auto(turnOn: boolean): this; - - /** Check if the given value satisfies a required validator. */ - checkRequired(value: any, doc: Document): boolean; - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/mixed.js - * http://mongoosejs.com/docs/api.html#schema-mixed-js - */ - class Mixed extends SchemaType { - /** Mixed SchemaType constructor. */ - constructor(path: string, options?: Object); - - /** This schema type's name, to defend against minifiers that mangle function names. */ - static schemaName: string; - } - - /* - * section schema/embedded.js - * http://mongoosejs.com/docs/api.html#schema-embedded-js - */ - class Embedded extends SchemaType { - /** Sub-schema schematype constructor */ - constructor(schema: Schema, key: string, options?: Object); - } - } - } - - /* - * section aggregate.js - * http://mongoosejs.com/docs/api.html#aggregate-js - */ - class Aggregate { - /** - * Aggregate constructor used for building aggregation pipelines. - * Returned when calling Model.aggregate(). - * @param ops aggregation operator(s) or operator array - */ - constructor(ops?: Object | any[], ...args: any[]); - - /** Adds a cursor flag */ - addCursorFlag(flag: string, value: boolean): this; - - /** - * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) - * @param value Should tell server it can use hard drive to store data during aggregation. - * @param tags optional tags for this query - */ - allowDiskUse(value: boolean, tags?: any[]): this; - - /** - * Appends new operators to this aggregate pipeline - * @param ops operator(s) to append - */ - append(...ops: Object[]): this; - - /** - * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). - * Note the different syntax below: .exec() returns a cursor object, and no callback - * is necessary. - * @param options set the cursor batch size - */ - cursor(options: Object): this; - - // If cursor option is on, could return an object - /** Executes the aggregate pipeline on the currently bound Model. */ - exec(callback?: (err: any, result: T) => void): _MongoosePromise | any; - - /** Execute the aggregation with explain */ - explain(callback?: (err: any, result: T) => void): _MongoosePromise; - - /** - * Appends a new custom $group operator to this aggregate pipeline. - * @param arg $group operator contents - */ - group(arg: Object): this; - - /** - * Appends a new $limit operator to this aggregate pipeline. - * @param num maximum number of records to pass to the next stage - */ - limit(num: number): this; - - /** - * Appends new custom $lookup operator(s) to this aggregate pipeline. - * @param options to $lookup as described in the above link - */ - lookup(options: Object): this; - - /** - * Appends a new custom $match operator to this aggregate pipeline. - * @param arg $match operator contents - */ - match(arg: Object): this; - - /** - * Binds this aggregate to a model. - * @param model the model to which the aggregate is to be bound - */ - model(model: Model): this; - - /** - * Appends a new $geoNear operator to this aggregate pipeline. - * MUST be used as the first operator in the pipeline. - */ - near(parameters: Object): this; - - /** - * Appends a new $project operator to this aggregate pipeline. - * Mongoose query selection syntax is also supported. - * @param arg field specification - */ - project(arg: string | Object): this; - - /** - * Sets the readPreference option for the aggregation query. - * @param pref one of the listed preference options or their aliases - * @param tags optional tags for this query - */ - read(pref: string, tags?: Object[]): this; - - /** - * Appends new custom $sample operator(s) to this aggregate pipeline. - * @param size number of random documents to pick - */ - sample(size: number): this; - - /** - * Appends a new $skip operator to this aggregate pipeline. - * @param num number of records to skip before next stage - */ - skip(num: number): this; - - /** - * Appends a new $sort operator to this aggregate pipeline. - * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. - * If a string is passed, it must be a space delimited list of path names. The sort order - * of each path is ascending unless the path name is prefixed with - which will be treated - * as descending. - */ - sort(arg: string | Object): this; - - /** Provides promise for aggregate. */ - then(resolve?: (val: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise - - /** - * Appends new custom $unwind operator(s) to this aggregate pipeline. - * Note that the $unwind operator requires the path name to start with '$'. - * Mongoose will prepend '$' if the specified field doesn't start '$'. - * @param fields the field(s) to unwind - */ - unwind(...fields: string[]): this; - } - - /* - * section schematype.js - * http://mongoosejs.com/docs/api.html#schematype-js - */ - class SchemaType { - /** SchemaType constructor */ - constructor(path: string, options?: Object, instance?: string); - - /** - * Sets a default value for this SchemaType. - * Defaults can be either functions which return the value to use as the - * default or the literal value itself. Either way, the value will be cast - * based on its schema type before being set during document creation. - * @param val the default value - */ - default(val: any): any; - - /** Adds a getter to this schematype. */ - get(fn: Function): this; - - /** - * Declares the index options for this schematype. - * Indexes are created in the background by default. Specify background: false to override. - */ - index(options: Object | boolean | string): this; - - /** - * Adds a required validator to this SchemaType. The validator gets added - * to the front of this SchemaType's validators array using unshift(). - * @param required enable/disable the validator - * @param message optional custom error message - */ - required(required: boolean, message?: string): this; - - /** Sets default select() behavior for this path. */ - select(val: boolean): this; - /** Adds a setter to this schematype. */ - set(fn: Function): this; - /** Declares a sparse index. */ - sparse(bool: boolean): this; - /** Declares a full text index. */ - text(bool: boolean): this; - /** Declares an unique index. */ - unique(bool: boolean): this; - - /** - * Adds validator(s) for this document path. - * Validators always receive the value to validate as their first argument - * and must return Boolean. Returning false means validation failed. - * @param obj validator - * @param errorMsg optional error message - * @param type optional validator type - */ - validate(obj: RegExp | Function | Object, errorMsg?: string, - type?: string): this; - } + $where(js: string | Function): this; /** - * section promise.js - * http://mongoosejs.com/docs/api.html#promise-js - * - * You must assign a promise library: - * - * 1. To use mongoose's default promise library: - * Install mongoose-promise.d.ts - * - * 2. To use native ES6 promises, add this line to your main .d.ts file: - * type MongoosePromise = Promise; - * - * 3. To use another promise library (for example q): - * Install q.d.ts - * Then add this line to your main .d.ts file: - * type MongoosePromise = Q.Promise; + * Specifies an $all query condition. + * When called with one argument, the most recent path passed to where() is used. */ - type _MongoosePromise = MongoosePromise; + all(val: number): this; + all(path: string, val: number): this; - /* - * section model.js - * http://mongoosejs.com/docs/api.html#model-js - * - * Mongoose Models use multiple inheritance from Document and EventEmitter. - * When calling methods that return a model such as mongoose.connect(), - * they actual return an instance of the Model constructor (think of it - * like a new class) which can then instantiate its own objects. + /** + * Specifies arguments for a $and condition. + * @param array array of conditions */ - type ModelConstructor = IModelConstructor & events.EventEmitter; - type Model = T & _Model & events.EventEmitter; + and(array: Object[]): this; - interface IModelConstructor { - /** - * Model constructor - * Provides the interface to MongoDB collections as well as creates document instances. - * @param doc values with which to create the document - * @event error If listening to this event, it is emitted when a document - * was saved without passing a callback and an error occurred. If not - * listening, the event bubbles to the connection used to create this Model. - * @event index Emitted after Model#ensureIndexes completes. If an error - * occurred it is passed with the event. - * @event index-single-start Emitted when an individual index starts within - * Model#ensureIndexes. The fields and options being used to build the index - * are also passed with the event. - * @event index-single-done Emitted when an individual index finishes within - * Model#ensureIndexes. If an error occurred it is passed with the event. - * The fields, options, and index name are also passed. - */ - new(doc?: Object): Model; + /** Specifies the batchSize option. Cannot be used with distinct() */ + batchSize(val: number): this; - /** - * Finds a single document by its _id field. findById(id) is almost* - * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. - * @param id value of _id to query by - * @param projection optional fields to return - */ - findById(id: Object | string | number, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findById(id: Object | string | number, projection: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findById(id: Object | string | number, projection: Object, options: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** + * Specifies a $box condition + * @param Upper Right Coords + */ + box(val: Object): this; + box(lower: number[], upper: number[]): this; - model(name: string): ModelConstructor; - model(name: string): Statics & ModelConstructor; + /** Casts this query to the schema of model, If obj is present, it is cast instead of this query.*/ + cast(model: any, obj?: Object): Object; - /** - * Creates a Query and specifies a $where condition. - * @param argument is a javascript string or anonymous function - */ - $where(argument: string | Function): ModelQuery[], T>; + /** + * Executes the query returning a Promise which will be + * resolved with either the doc(s) or rejected with the error. + * Like .then(), but only takes a rejection handler. + */ + catch(reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; - /** - * Performs aggregations on the models collection. - * If a callback is passed, the aggregate is executed and a Promise is returned. - * If a callback is not passed, the aggregate itself is returned. - * @param ... aggregation pipeline operator(s) or operator array - */ - aggregate(...aggregations: Object[]): Aggregate; - aggregate(...aggregationsWithCallback: Object[]): _MongoosePromise; + /** + * DEPRECATED Alias for circle + * Specifies a $center or $centerSphere condition. + * @deprecated Use circle instead. + */ + center(area: Object): this; + center(path: string, area: Object): this; - /** Counts number of matching documents in a database collection. */ - count(conditions: Object, callback?: (err: any, count: number) => void): Query; + /** + * DEPRECATED Specifies a $centerSphere condition + * @deprecated Use circle instead. + */ + centerSphere(path: string, val: Object): this; + centerSphere(val: Object): this; - /** - * Shortcut for saving one or more documents to the database. MyModel.create(docs) - * does new MyModel(doc).save() for every doc in docs. - * Triggers the save() hook. - */ - create(docs: any[], callback?: (err: any, res: Model[]) => void): _MongoosePromise[]>; - create(...docs: Object[]): _MongoosePromise>; - create(...docsWithCallback: Object[]): _MongoosePromise>; + /** Specifies a $center or $centerSphere condition. */ + circle(area: Object): this; + circle(path: string, area: Object): this; - /** - * Adds a discriminator type. - * @param name discriminator model name - * @param schema discriminator model schema - */ - discriminator(name: string, schema: Schema): Model; + /** Specifies the comment option. Cannot be used with distinct() */ + comment(val: string): this; - /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, conditions: Object, - callback?: (err: any, res: any[]) => void): Query; + /** + * Specifying this query as a count query. Passing a callback executes the query. + * @param criteria mongodb selector + */ + count(callback?: (err: any, count: number) => void): Query; + count(criteria: Object, callback?: (err: any, count: number) => void): Query; - /** - * Sends ensureIndex commands to mongo for each index declared in the schema. - * @param options internal options - * @param cb optional callback - */ - ensureIndexes(callback?: (err: any) => void): _MongoosePromise; - ensureIndexes(options: Object, callback?: (err: any) => void): _MongoosePromise; + /** + * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a + * Streams3-compatible interface, as well as a .next() function. + */ + cursor(options?: Object): QueryCursor; - /** - * Finds documents. - * @param projection optional fields to return - */ - find(callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; - find(conditions: Object, callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; - find(conditions: Object, projection: Object, - callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; - find(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; + /** Declares or executes a distict() operation. Passing a callback executes the query. */ + distinct(callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, criteria: Object | Query, + callback?: (err: any, res: any[]) => void): Query; + /** Specifies an $elemMatch condition */ + elemMatch(criteria: (elem: Query) => void): this; + elemMatch(criteria: Object): this; + elemMatch(path: string | Object | Function, criteria: (elem: Query) => void): this; + elemMatch(path: string | Object | Function, criteria: Object): this; + /** Specifies the complementary comparison value for paths specified with where() */ + equals(val: Object): this; - /** - * Issue a mongodb findAndModify remove command by a document's _id field. - * findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...). - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * Executes immediately if callback is passed, else a Query object is returned. - * @param id value of _id to query by - */ - findByIdAndRemove(): ModelQuery, T>; - findByIdAndRemove(id: Object | number | string, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findByIdAndRemove(id: Object | number | string, options: { - /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ - sort?: Object; - /** sets the document fields to return */ - select?: Object; - }, callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** Executes the query */ + exec(callback?: (err: any, res: T) => void): _MongoosePromise; + exec(operation: string | Function, callback?: (err: any, res: T) => void): _MongoosePromise; - /** - * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) - * is equivalent to findOneAndUpdate({ _id: id }, ...). - * @param id value of _id to query by - */ - findByIdAndUpdate(): ModelQuery, T>; - findByIdAndUpdate(id: Object | number | string, update: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findByIdAndUpdate(id: Object | number | string, update: Object, - options: ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** Specifies an $exists condition */ + exists(val?: boolean): this; + exists(path: string, val?: boolean): this; - /** - * Finds one document. - * The conditions are cast to their respective SchemaTypes before the command is sent. - * @param projection optional fields to return - */ - findOne(conditions?: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findOne(conditions: Object, projection: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findOne(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** + * Finds documents. When no callback is passed, the query is not executed. When the + * query is executed, the result will be an array of documents. + * @param criteria mongodb selector + */ + find(callback?: (err: any, res: ModelType[]) => void): ModelQuery; + find(criteria: Object, + callback?: (err: any, res: ModelType[]) => void): ModelQuery; + + /** + * Declares the query a findOne operation. When executed, the first found document is + * passed to the callback. Passing a callback executes the query. The result of the query + * is a single document. + * @param criteria mongodb selector + * @param projection optional fields to return + */ + findOne(callback?: (err: any, res: ModelType) => void): ModelQuery; + findOne(criteria: Object, + callback?: (err: any, res: ModelType) => void): ModelQuery; + + /** + * Issues a mongodb findAndModify remove command. + * Finds a matching document, removes it, passing the found document (if any) to the + * callback. Executes immediately if callback is passed. + */ + findOneAndRemove(callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + findOneAndRemove(conditions: Object, + callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, + callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + + /** + * Issues a mongodb findAndModify update command. + * Finds a matching document, updates it according to the update arg, passing any options, and returns + * the found document (if any) to the callback. The query executes immediately if callback is passed. + */ + findOneAndUpdate(callback?: (err: any, doc: ModelType) => void): ModelQuery; + findOneAndUpdate(update: Object, + callback?: (err: any, doc: ModelType) => void): ModelQuery; + findOneAndUpdate(query: Object | Query, update: Object, + callback?: (err: any, doc: ModelType) => void): ModelQuery; + findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: ModelType) => void): ModelQuery; + + /** + * Specifies a $geometry condition. geometry() must come after either intersects() or within(). + * @param object Must contain a type property which is a String and a coordinates property which + * is an Array. See the examples. + */ + geometry(object: { type: string, coordinates: any[] }): this; + + /** + * Returns the current query conditions as a JSON object. + * @returns current query conditions + */ + getQuery(): any; + + /** + * Returns the current update operations as a JSON object. + * @returns current update operations + */ + getUpdate(): any; + + /** + * Specifies a $gt query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + gt(val: number): this; + gt(path: string, val: number): this; + + /** + * Specifies a $gte query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + gte(val: number): this; + gte(path: string, val: number): this; + + /** + * Sets query hints. + * @param val a hint object + */ + hint(val: Object): this; + + /** + * Specifies an $in query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + in(val: any[]): this; + in(path: string, val: any[]): this; + + /** Declares an intersects query for geometry(). MUST be used after where(). */ + intersects(arg?: Object): this; + + /** + * Sets the lean option. + * Documents returned from queries with the lean option enabled are plain + * javascript objects, not MongooseDocuments. They have no save method, + * getters/setters or other Mongoose magic applied. + * @param bool defaults to true + */ + lean(bool?: boolean): Query; + + /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ + limit(val: number): this; + + /** + * Specifies a $lt query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + lt(val: number): this; + lt(path: string, val: number): this; + + /** + * Specifies a $lte query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + lte(val: number): this; + lte(path: string, val: number): this; + + /** + * Specifies a $maxDistance query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + maxDistance(val: number): this; + maxDistance(path: string, val: number): this; + + /** @deprecated Alias of maxScan */ + maxscan(val: number): this; + /** Specifies the maxScan option. Cannot be used with distinct() */ + maxScan(val: number): this; + + /** + * Merges another Query or conditions object into this one. + * When a Query is passed, conditions, field selection and options are merged. + */ + merge(source: Object | Query): this; + + /** Specifies a $mod condition */ + mod(val: number[]): this; + mod(path: string, val: number[]): this; + + /** + * Specifies a $ne query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + ne(val: any): this; + ne(path: string, val: any): this; + + /** Specifies a $near or $nearSphere condition. */ + near(val: Object): this; + near(path: string, val: Object): this; + + /** + * DEPRECATED Specifies a $nearSphere condition + * @deprecated Use query.near() instead with the spherical option set to true. + */ + nearSphere(val: Object): this; + nearSphere(path: string, val: Object): this; + + /** + * Specifies a $nin query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + nin(val: any[]): this; + nin(path: string, val: any[]): this; + + /** + * Specifies arguments for a $nor condition. + * @param array array of conditions + */ + nor(array: Object[]): this; + + /** + * Specifies arguments for an $or condition. + * @param array array of conditions + */ + or(array: Object[]): this; + + /** Specifies a $polygon condition */ + polygon(...coordinatePairs: number[][]): this; + polygon(path: string, ...coordinatePairs: number[][]): this; + + /** + * Specifies paths which should be populated with other documents. + * Paths are populated after the query executes and a response is received. A separate + * query is then executed for each path specified for population. After a response for + * each query has also been returned, the results are passed to the callback. + * @param path either the path to populate or an object specifying all parameters + * @param select Field selection for the population query + * @param model The model you wish to use for population. If not specified, populate + * will look up the model by the name in the Schema's ref field. + * @param match Conditions for the population query + * @param options Options for the population query (sort, etc) + */ + populate(path: string | Object, select?: string | Object, model?: any, + match?: Object, options?: Object): this; + populate(options: ModelPopulateOptions): this; + + /** + * Determines the MongoDB nodes from which to read. + * @param pref one of the listed preference options or aliases + * @tags optional tags for this query + */ + read(pref: string, tags?: Object[]): this; + + /** + * Specifies a $regex query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + regex(val: RegExp): this; + regex(path: string, val: RegExp): this; + + /** + * Declare and/or execute this query as a remove() operation. + * The operation is only executed when a callback is passed. To force execution without a callback, + * you must first call remove() and then execute it by using the exec() method. + * @param criteria mongodb selector + */ + remove(callback?: (err: any) => void): Query; + remove(criteria: Object | Query, callback?: (err: any) => void): Query; + + /** Specifies which document fields to include or exclude (also known as the query "projection") */ + select(arg: string | Object): this; + /** Determines if field selection has been made. */ + selected(): boolean; + /** Determines if exclusive field selection has been made.*/ + selectedExclusively(): boolean; + /** Determines if inclusive field selection has been made. */ + selectedInclusively(): boolean; + /** Sets query options. */ + setOptions(options: Object): this; + + /** + * Specifies a $size query condition. + * When called with one argument, the most recent path passed to where() is used. + */ + size(val: number): this; + size(path: string, val: number): this; + + /** Specifies the number of documents to skip. Cannot be used with distinct() */ + skip(val: number): this; + + /** + * DEPRECATED Sets the slaveOk option. + * @param v defaults to true + * @deprecated in MongoDB 2.2 in favor of read preferences. + */ + slaveOk(v?: boolean): this; + + /** + * Specifies a $slice projection for an array. + * @param val number/range of elements to slice + */ + slice(val: number | number[]): this; + slice(path: string, val: number | number[]): this; + + /** Specifies this query as a snapshot query. Cannot be used with distinct() */ + snapshot(v?: boolean): this; + + /** + * Sets the sort order + * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. + * If a string is passed, it must be a space delimited list of path names. The + * sort order of each path is ascending unless the path name is prefixed with - + * which will be treated as descending. + */ + sort(arg: string | Object): this; + + /** Returns a Node.js 0.8 style read stream interface. */ + stream(options?: { transform?: Function; }): QueryStream; + + /** + * Sets the tailable option (for use with capped collections). Cannot be used with distinct() + * @param bool defaults to true + * @param opts options to set + * @param opts.numberOfRetries if cursor is exhausted, retry this many times before giving up + * @param opts.tailableRetryInterval if cursor is exhausted, wait this many milliseconds before retrying + */ + tailable(bool?: boolean, opts?: { + numberOfRetries?: number; + tailableRetryInterval?: number; + }): this; + + /** Executes this query and returns a promise */ + then(resolve?: (res: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; + + /** + * Converts this query to a customized, reusable query + * constructor with all arguments and options retained. + */ + toConstructor(): typeof ModelQuery; + + /** + * Declare and/or execute this query as an update() operation. + * All paths passed that are not $atomic operations will become $set ops. + * @param doc the update command + */ + update(callback?: (err: any, affectedRows: number) => void): Query; + update(doc: Object, callback?: (err: any, affectedRows: number) => void): Query; + update(criteria: Object, doc: Object, + callback?: (err: any, affectedRows: number) => void): Query; + update(criteria: Object, doc: Object, options: QueryUpdateOptions, + callback?: (err: any, affectedRows: number) => void): Query; + + /** Specifies a path for use with chaining. */ + where(path?: string | Object, val?: any): this; + + /** Defines a $within or $geoWithin argument for geo-spatial queries. */ + within(val?: Object): this; + within(coordinate: number[], ...coordinatePairs: number[][]): this; + + /** Flag to opt out of using $geoWithin. */ + static use$geoWithin: boolean; + } + + // https://github.com/aheckmann/mquery + // mquery currently does not have a type definition please + // replace it if one is ever created + class mquery {} + + interface QueryFindOneAndRemoveOptions { + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: any; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + passRawResult?: boolean; + } + + interface QueryFindOneAndUpdateOptions extends QueryFindOneAndRemoveOptions { + /** if true, return the modified document rather than the original. defaults to false (changed in 4.0) */ + new?: boolean; + /** creates the object if it doesn't exist. defaults to false. */ + upsert?: boolean; + /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ + fields?: Object | string; + /** if true, runs update validators on this command. Update validators validate the update operation against the model's schema. */ + runValidators?: boolean; + /** + * if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document + * is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** + * if set to 'query' and runValidators is on, this will refer to the query in custom validator + * functions that update validation runs. Does nothing if runValidators is false. + */ + context?: string; + } + + interface QueryUpdateOptions extends ModelUpdateOptions { + /** + * if set to 'query' and runValidators is on, this will refer to the query + * in customvalidator functions that update validation runs. Does nothing + * if runValidators is false. + */ + context?: string; + } + + namespace Schema { + namespace Types { + /* + * section schema/array.js + * http://mongoosejs.com/docs/api.html#schema-array-js + */ + class Array extends SchemaType { + /** Array SchemaType constructor */ + constructor(key: string, cast?: SchemaType, options?: Object); - /** - * Issue a mongodb findAndModify remove command. - * Finds a matching document, removes it, passing the found document (if any) to the callback. - * Executes immediately if callback is passed else a Query object is returned. - */ - findOneAndRemove(): ModelQuery, T>; - findOneAndRemove(conditions: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findOneAndRemove(conditions: Object, options: { /** - * if multiple docs are found by the conditions, sets the sort order to choose - * which doc to update + * Check if the given value satisfies a required validator. The given value + * must be not null nor undefined, and have a non-zero length. */ - sort?: Object; - /** puts a time limit on the query - requires mongodb >= 2.6.0 */ - maxTimeMS?: number; - /** sets the document fields to return */ - select?: Object; - }, callback?: (err: any, res: Model) => void): ModelQuery, T>; + checkRequired(value: T): boolean; - /** - * Issues a mongodb findAndModify update command. - * Finds a matching document, updates it according to the update arg, passing any options, - * and returns the found document (if any) to the callback. The query executes immediately - * if callback is passed else a Query object is returned. - */ - findOneAndUpdate(): ModelQuery, T>; - findOneAndUpdate(conditions: Object, update: Object, - callback?: (err: any, res: Model) => void): ModelQuery, T>; - findOneAndUpdate(conditions: Object, update: Object, - options: ModelFindOneAndUpdateOptions, - callback?: (err: any, res: Model) => void): ModelQuery, T>; + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } - /** - * geoNear support for Mongoose - * @param GeoJSON point or legacy coordinate pair [x,y] to search near - * @param options for the qurery - * @param callback optional callback for the query - */ - geoNear(point: number[] | { - type: string; - coordinates: number[] - }, options: { - /** return the raw object */ - lean?: boolean; - [other: string]: any; - }, callback?: (err: any, res: Model[], stats: any) => void): ModelQuery[], T>; + /* + * section schema/string.js + * http://mongoosejs.com/docs/api.html#schema-string-js + */ + class String extends SchemaType { + /** String SchemaType constructor. */ + constructor(key: string, options?: Object); - /** - * Implements $geoSearch functionality for Mongoose - * @param conditions an object that specifies the match condition (required) - * @param options for the geoSearch, some (near, maxDistance) are required - * @param callback optional callback - */ - geoSearch(conditions: Object, options: { - /** x,y point to search for */ - near: number[]; - /** the maximum distance from the point near that a result can be */ - maxDistance: number; - /** The maximum number of results to return */ - limit?: number; - /** return the raw object instead of the Mongoose Model */ - lean?: boolean; - }, callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; - /** - * Shortcut for creating a new Document from existing raw data, - * pre-saved in the DB. The document returned has no paths marked - * as modified initially. - */ - hydrate(obj: Object): Model; + /** + * Adds an enum validator + * @param args enumeration values + */ + enum(args: string | string[] | Object): this; - /** - * Shortcut for validating an array of documents and inserting them into - * MongoDB if they're all valid. This function is faster than .create() - * because it only sends one operation to the server, rather than one for each - * document. - * This function does not trigger save middleware. - */ - insertMany(docs: any[], callback?: (error: any, docs: Model[]) => void): _MongoosePromise[]>; - insertMany(doc: any, callback?: (error: any, doc: Model) => void): _MongoosePromise>; - insertMany(...docsWithCallback: Object[]): _MongoosePromise>; + /** Adds a lowercase setter. */ + lowercase(): this; - /** - * Executes a mapReduce command. - * @param o an object specifying map-reduce options - * @param callbackoptional callback - */ - mapReduce( - o: ModelMapReduceOption, Key, Value>, - callback?: (err: any, res: any) => void - ): _MongoosePromise; + /** + * Sets a regexp validator. Any value that does not pass regExp.test(val) will fail validation. + * @param regExp regular expression to test against + * @param message optional custom error message + */ + match(regExp: RegExp, message?: string): this; - /** - * Populates document references. - * @param docs Either a single document or array of documents to populate. - * @param options A hash of key/val (path, options) used for population. - * @param callback Optional callback, executed upon completion. Receives err and the doc(s). - */ - populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: Model[]) => void): _MongoosePromise[]>; - populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: Model) => void): _MongoosePromise>; + /** + * Sets a maximum length validator. + * @param value maximum string length + * @param message optional custom error message + */ + maxlength(value: number, message?: string): this; - /** Removes documents from the collection. */ - remove(conditions: Object, callback?: (err: any) => void): Query; + /** + * Sets a minimum length validator. + * @param value minimum string length + * @param message optional custom error message + */ + minlength(value: number, message?: string): this; - /** - * Updates documents in the database without returning them. - * All update values are cast to their appropriate SchemaTypes before being sent. - */ - update(conditions: Object, doc: Object, - callback?: (err: any, raw: any) => void): Query; - update(conditions: Object, doc: Object, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + /** Adds a trim setter. The string value will be trimmed when set. */ + trim(): this; + /** Adds an uppercase setter. */ + uppercase(): this; - /** Creates a Query, applies the passed conditions, and returns the Query. */ - where(path: string, val?: Object): Query; + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + } + + /* + * section schema/documentarray.js + * http://mongoosejs.com/docs/api.html#schema-documentarray-js + */ + class DocumentArray extends Array { + /** SubdocsArray SchemaType constructor */ + constructor(key: string, schema: Schema, options?: Object); + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/number.js + * http://mongoosejs.com/docs/api.html#schema-number-js + */ + class Number extends SchemaType { + /** Number SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** + * Sets a maximum number validator. + * @param maximum number + * @param message optional custom error message + */ + max(maximum: number, message?: string): this; + + /** + * Sets a minimum number validator. + * @param value minimum number + * @param message optional custom error message + */ + min(value: number, message?: string): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/date.js + * http://mongoosejs.com/docs/api.html#schema-date-js + */ + class Date extends SchemaType { + /** Date SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** + * Check if the given value satisfies a required validator. To satisfy + * a required validator, the given value must be an instance of Date. + */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** Declares a TTL index (rounded to the nearest second) for Date types only. */ + expires(when: number | string): this; + + /** + * Sets a maximum date validator. + * @param maximum date + * @param message optional custom error message + */ + max(maximum: NativeDate, message?: string): this; + + /** + * Sets a minimum date validator. + * @param value minimum date + * @param message optional custom error message + */ + min(value: NativeDate, message?: string): this; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/buffer.js + * http://mongoosejs.com/docs/api.html#schema-buffer-js + */ + class Buffer extends SchemaType { + /** Buffer SchemaType constructor */ + constructor(key: string, options?: Object); + + /** + * Check if the given value satisfies a required validator. To satisfy a + * required validator, a buffer must not be null or undefined and have + * non-zero length. + */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + + } + + /* + * section schema/boolean.js + * http://mongoosejs.com/docs/api.html#schema-boolean-js + */ + class Boolean extends SchemaType { + /** Boolean SchemaType constructor. */ + constructor(path: string, options?: Object); + + /** + * Check if the given value satisfies a required validator. For a + * boolean to satisfy a required validator, it must be strictly + * equal to true or to false. + */ + checkRequired(value: any): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/objectid.js + * http://mongoosejs.com/docs/api.html#schema-objectid-js + */ + class ObjectId extends SchemaType { + /** ObjectId SchemaType constructor. */ + constructor(key: string, options?: Object); + + /** + * Adds an auto-generated ObjectId default if turnOn is true. + * @param turnOn auto generated ObjectId defaults + */ + auto(turnOn: boolean): this; + + /** Check if the given value satisfies a required validator. */ + checkRequired(value: any, doc: MongooseDocument): boolean; + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/mixed.js + * http://mongoosejs.com/docs/api.html#schema-mixed-js + */ + class Mixed extends SchemaType { + /** Mixed SchemaType constructor. */ + constructor(path: string, options?: Object); + + /** This schema type's name, to defend against minifiers that mangle function names. */ + static schemaName: string; + } + + /* + * section schema/embedded.js + * http://mongoosejs.com/docs/api.html#schema-embedded-js + */ + class Embedded extends SchemaType { + /** Sub-schema schematype constructor */ + constructor(schema: Schema, key: string, options?: Object); + } } + } - class _Model extends Document { - /** Signal that we desire an increment of this documents version. */ - increment(): this; + /* + * section aggregate.js + * http://mongoosejs.com/docs/api.html#aggregate-js + */ + class Aggregate { + /** + * Aggregate constructor used for building aggregation pipelines. + * Returned when calling Model.aggregate(). + * @param ops aggregation operator(s) or operator array + */ + constructor(ops?: Object | any[], ...args: any[]); - /** - * Returns another Model instance. - * @param name model name - */ - model(name: string): ModelConstructor; - model(name: string): Statics & ModelConstructor; + /** Adds a cursor flag */ + addCursorFlag(flag: string, value: boolean): this; - /** - * Removes this document from the db. - * @param fn optional callback - */ - remove(fn?: (err: any, product: Model) => void): _MongoosePromise>; + /** + * Sets the allowDiskUse option for the aggregation query (ignored for < 2.6.0) + * @param value Should tell server it can use hard drive to store data during aggregation. + * @param tags optional tags for this query + */ + allowDiskUse(value: boolean, tags?: any[]): this; - /** - * Saves this document. - * @param options options optional options - * @param options.safe overrides schema's safe option - * @param options.validateBeforeSave set to false to save without validating. - * @param fn optional callback - */ - save(fn?: (err: any, product: Model, numAffected: number) => void): _MongoosePromise>; + /** + * Appends new operators to this aggregate pipeline + * @param ops operator(s) to append + */ + append(...ops: Object[]): this; - /** Base Mongoose instance the model uses. */ - base: typeof mongoose; - /** - * If this is a discriminator model, baseModelName is the - * name of the base model. - */ - baseModelName: String; - /** Collection the model uses. */ - collection: Collection; - /** Connection the model uses. */ - db: Connection; - /** Registered discriminators for this model. */ - discriminators: any; - /** The name of the model */ - modelName: string; - /** Schema the model uses. */ - schema: Schema; - } + /** + * Sets the cursor option option for the aggregation query (ignored for < 2.6.0). + * Note the different syntax below: .exec() returns a cursor object, and no callback + * is necessary. + * @param options set the cursor batch size + */ + cursor(options: Object): this; - interface ModelFindByIdAndUpdateOptions { - /** true to return the modified document rather than the original. defaults to false */ - new?: boolean; - /** creates the object if it doesn't exist. defaults to false. */ - upsert?: boolean; - /** - * if true, runs update validators on this command. Update validators validate the - * update operation against the model's schema. - */ - runValidators?: boolean; - /** - * if this and upsert are true, mongoose will apply the defaults specified in the model's - * schema if a new document is created. This option only works on MongoDB >= 2.4 because - * it relies on MongoDB's $setOnInsert operator. - */ - setDefaultsOnInsert?: boolean; + // If cursor option is on, could return an object + /** Executes the aggregate pipeline on the currently bound Model. */ + exec(callback?: (err: any, result: T) => void): _MongoosePromise | any; + + /** Execute the aggregation with explain */ + explain(callback?: (err: any, result: T) => void): _MongoosePromise; + + /** + * Appends a new custom $group operator to this aggregate pipeline. + * @param arg $group operator contents + */ + group(arg: Object): this; + + /** + * Appends a new $limit operator to this aggregate pipeline. + * @param num maximum number of records to pass to the next stage + */ + limit(num: number): this; + + /** + * Appends new custom $lookup operator(s) to this aggregate pipeline. + * @param options to $lookup as described in the above link + */ + lookup(options: Object): this; + + /** + * Appends a new custom $match operator to this aggregate pipeline. + * @param arg $match operator contents + */ + match(arg: Object): this; + + /** + * Binds this aggregate to a model. + * @param model the model to which the aggregate is to be bound + */ + model(model: any): this; + + /** + * Appends a new $geoNear operator to this aggregate pipeline. + * MUST be used as the first operator in the pipeline. + */ + near(parameters: Object): this; + + /** + * Appends a new $project operator to this aggregate pipeline. + * Mongoose query selection syntax is also supported. + * @param arg field specification + */ + project(arg: string | Object): this; + + /** + * Sets the readPreference option for the aggregation query. + * @param pref one of the listed preference options or their aliases + * @param tags optional tags for this query + */ + read(pref: string, tags?: Object[]): this; + + /** + * Appends new custom $sample operator(s) to this aggregate pipeline. + * @param size number of random documents to pick + */ + sample(size: number): this; + + /** + * Appends a new $skip operator to this aggregate pipeline. + * @param num number of records to skip before next stage + */ + skip(num: number): this; + + /** + * Appends a new $sort operator to this aggregate pipeline. + * If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1. + * If a string is passed, it must be a space delimited list of path names. The sort order + * of each path is ascending unless the path name is prefixed with - which will be treated + * as descending. + */ + sort(arg: string | Object): this; + + /** Provides promise for aggregate. */ + then(resolve?: (val: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise + + /** + * Appends new custom $unwind operator(s) to this aggregate pipeline. + * Note that the $unwind operator requires the path name to start with '$'. + * Mongoose will prepend '$' if the specified field doesn't start '$'. + * @param fields the field(s) to unwind + */ + unwind(...fields: string[]): this; + } + + /* + * section schematype.js + * http://mongoosejs.com/docs/api.html#schematype-js + */ + class SchemaType { + /** SchemaType constructor */ + constructor(path: string, options?: Object, instance?: string); + + /** + * Sets a default value for this SchemaType. + * Defaults can be either functions which return the value to use as the + * default or the literal value itself. Either way, the value will be cast + * based on its schema type before being set during document creation. + * @param val the default value + */ + default(val: any): any; + + /** Adds a getter to this schematype. */ + get(fn: Function): this; + + /** + * Declares the index options for this schematype. + * Indexes are created in the background by default. Specify background: false to override. + */ + index(options: Object | boolean | string): this; + + /** + * Adds a required validator to this SchemaType. The validator gets added + * to the front of this SchemaType's validators array using unshift(). + * @param required enable/disable the validator + * @param message optional custom error message + */ + required(required: boolean, message?: string): this; + + /** Sets default select() behavior for this path. */ + select(val: boolean): this; + /** Adds a setter to this schematype. */ + set(fn: Function): this; + /** Declares a sparse index. */ + sparse(bool: boolean): this; + /** Declares a full text index. */ + text(bool: boolean): this; + /** Declares an unique index. */ + unique(bool: boolean): this; + + /** + * Adds validator(s) for this document path. + * Validators always receive the value to validate as their first argument + * and must return Boolean. Returning false means validation failed. + * @param obj validator + * @param errorMsg optional error message + * @param type optional validator type + */ + validate(obj: RegExp | Function | Object, errorMsg?: string, + type?: string): this; + } + + /** + * section promise.js + * http://mongoosejs.com/docs/api.html#promise-js + * + * You must assign a promise library: + * + * 1. To use mongoose's default promise library: + * Install mongoose-promise.d.ts + * + * 2. To use native ES6 promises, add this line to your main .d.ts file: + * type MongoosePromise = Promise; + * + * 3. To use another promise library (for example q): + * Install q.d.ts + * Then add this line to your main .d.ts file: + * type MongoosePromise = Q.Promise; + */ + interface _MongoosePromise extends MongoosePromise {} + interface Promise extends MongoosePromise {} + + /** + * To assign your own promise library: + * + * 1. Include this somewhere in your code: + * mongoose.Promise = YOUR_PROMISE; + * + * 2. Include this somewhere in your main .d.ts file: + * type MongoosePromise = YOUR_PROMISE; + */ + export var Promise: any; + export var PromiseProvider: any; + + /* + * section model.js + * http://mongoosejs.com/docs/api.html#model-js + */ + interface Model extends NodeJS.EventEmitter { + /** + * Model constructor + * Provides the interface to MongoDB collections as well as creates document instances. + * @param doc values with which to create the document + * @event error If listening to this event, it is emitted when a document + * was saved without passing a callback and an error occurred. If not + * listening, the event bubbles to the connection used to create this Model. + * @event index Emitted after Model#ensureIndexes completes. If an error + * occurred it is passed with the event. + * @event index-single-start Emitted when an individual index starts within + * Model#ensureIndexes. The fields and options being used to build the index + * are also passed with the event. + * @event index-single-done Emitted when an individual index finishes within + * Model#ensureIndexes. If an error occurred it is passed with the event. + * The fields, options, and index name are also passed. + */ + new(doc?: Object): T; + + /** + * Finds a single document by its _id field. findById(id) is almost* + * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. + * @param id value of _id to query by + * @param projection optional fields to return + */ + findById(id: Object | string | number, + callback?: (err: any, res: T) => void): ModelQuery; + findById(id: Object | string | number, projection: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findById(id: Object | string | number, projection: Object, options: Object, + callback?: (err: any, res: T) => void): ModelQuery; + + model(name: string): Model; + + /** + * Creates a Query and specifies a $where condition. + * @param argument is a javascript string or anonymous function + */ + $where(argument: string | Function): ModelQuery; + + /** + * Performs aggregations on the models collection. + * If a callback is passed, the aggregate is executed and a Promise is returned. + * If a callback is not passed, the aggregate itself is returned. + * @param ... aggregation pipeline operator(s) or operator array + */ + aggregate(...aggregations: Object[]): Aggregate; + aggregate(...aggregationsWithCallback: Object[]): _MongoosePromise; + + /** Counts number of matching documents in a database collection. */ + count(conditions: Object, callback?: (err: any, count: number) => void): Query; + + /** + * Shortcut for saving one or more documents to the database. MyModel.create(docs) + * does new MyModel(doc).save() for every doc in docs. + * Triggers the save() hook. + */ + create(docs: any[], callback?: (err: any, res: T[]) => void): _MongoosePromise; + create(...docs: Object[]): _MongoosePromise; + create(...docsWithCallback: Object[]): _MongoosePromise; + + /** + * Adds a discriminator type. + * @param name discriminator model name + * @param schema discriminator model schema + */ + discriminator(name: string, schema: Schema): T; + + /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ + distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, conditions: Object, + callback?: (err: any, res: any[]) => void): Query; + + /** + * Sends ensureIndex commands to mongo for each index declared in the schema. + * @param options internal options + * @param cb optional callback + */ + ensureIndexes(callback?: (err: any) => void): _MongoosePromise; + ensureIndexes(options: Object, callback?: (err: any) => void): _MongoosePromise; + + /** + * Finds documents. + * @param projection optional fields to return + */ + find(callback?: (err: any, res: T[]) => void): ModelQuery; + find(conditions: Object, callback?: (err: any, res: T[]) => void): ModelQuery; + find(conditions: Object, projection: Object, + callback?: (err: any, res: T[]) => void): ModelQuery; + find(conditions: Object, projection: Object, options: Object, + callback?: (err: any, res: T[]) => void): ModelQuery; + + + + /** + * Issue a mongodb findAndModify remove command by a document's _id field. + * findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...). + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * Executes immediately if callback is passed, else a Query object is returned. + * @param id value of _id to query by + */ + findByIdAndRemove(): ModelQuery; + findByIdAndRemove(id: Object | number | string, + callback?: (err: any, res: T) => void): ModelQuery; + findByIdAndRemove(id: Object | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: Object; /** sets the document fields to return */ select?: Object; - } + }, callback?: (err: any, res: T) => void): ModelQuery; - interface ModelFindOneAndUpdateOptions extends ModelFindByIdAndUpdateOptions { - /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ - fields?: Object | string; + /** + * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) + * is equivalent to findOneAndUpdate({ _id: id }, ...). + * @param id value of _id to query by + */ + findByIdAndUpdate(): ModelQuery; + findByIdAndUpdate(id: Object | number | string, update: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findByIdAndUpdate(id: Object | number | string, update: Object, + options: ModelFindByIdAndUpdateOptions, + callback?: (err: any, res: T) => void): ModelQuery; + + /** + * Finds one document. + * The conditions are cast to their respective SchemaTypes before the command is sent. + * @param projection optional fields to return + */ + findOne(conditions?: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findOne(conditions: Object, projection: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findOne(conditions: Object, projection: Object, options: Object, + callback?: (err: any, res: T) => void): ModelQuery; + + /** + * Issue a mongodb findAndModify remove command. + * Finds a matching document, removes it, passing the found document (if any) to the callback. + * Executes immediately if callback is passed else a Query object is returned. + */ + findOneAndRemove(): ModelQuery; + findOneAndRemove(conditions: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findOneAndRemove(conditions: Object, options: { + /** + * if multiple docs are found by the conditions, sets the sort order to choose + * which doc to update + */ + sort?: Object; /** puts a time limit on the query - requires mongodb >= 2.6.0 */ maxTimeMS?: number; - /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ - passRawResult?: boolean; - } + /** sets the document fields to return */ + select?: Object; + }, callback?: (err: any, res: T) => void): ModelQuery; - interface ModelPopulateOptions { - /** space delimited path(s) to populate */ - path: string; - /** optional fields to select */ - select?: any; - /** optional query conditions to match */ - match?: Object; - /** optional name of the model to use for population */ - model?: string; - /** optional query options like sort, limit, etc */ - options?: Object; - } - - interface ModelUpdateOptions { - /** safe mode (defaults to value set in schema (true)) */ - safe?: boolean; - /** whether to create the doc if it doesn't match (false) */ - upsert?: boolean; - /** whether multiple documents should be updated (false) */ - multi?: boolean; - /** - * If true, runs update validators on this command. Update validators validate - * the update operation against the model's schema. - */ - runValidators?: boolean; - /** - * If this and upsert are true, mongoose will apply the defaults specified in the - * model's schema if a new document is created. This option only works on MongoDB >= 2.4 - * because it relies on MongoDB's $setOnInsert operator. - */ - setDefaultsOnInsert?: boolean; - /** overrides the strict option for this update */ - strict?: boolean; - /** disables update-only mode, allowing you to overwrite the doc (false) */ - overwrite?: boolean; - /** other options */ - [other: string]: any; - } - - interface ModelMapReduceOption { - map: Function | string; - reduce: (key: Key, vals: T[]) => Val; - /** query filter object. */ - query?: Object; - /** sort input objects using this key */ - sort?: Object; - /** max number of documents */ - limit?: number; - /** keep temporary data default: false */ - keeptemp?: boolean; - /** finalize function */ - finalize?: (key: Key, val: Val) => Val; - /** scope variables exposed to map/reduce/finalize during execution */ - scope?: Object; - /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */ - jsMode?: boolean; - /** provide statistics on job execution time. default: false */ - verbose?: boolean; - readPreference?: string; - /** sets the output target for the map reduce job. default: {inline: 1} */ - out?: { - /** the results are returned in an array */ - inline?: number; - /** - * {replace: 'collectionName'} add the results to collectionName: the - * results replace the collection - */ - replace?: string; - /** - * {reduce: 'collectionName'} add the results to collectionName: if - * dups are detected, uses the reducer / finalize functions - */ - reduce?: string; - /** - * {merge: 'collectionName'} add the results to collectionName: if - * dups exist the new docs overwrite the old - */ - merge?: string; - }; - } - - interface MapReduceResult { - _id: Key; - value: Val; - } - - /* - * section collection.js - * http://mongoosejs.com/docs/api.html#collection-js + /** + * Issues a mongodb findAndModify update command. + * Finds a matching document, updates it according to the update arg, passing any options, + * and returns the found document (if any) to the callback. The query executes immediately + * if callback is passed else a Query object is returned. */ - interface CollectionBase extends mongodb.Collection { - /* - * Abstract methods. Some of these are already defined on the - * mongodb.Collection interface so they've been commented out. - */ - ensureIndex(...args: any[]): any; - //find(...args: any[]): any; - findAndModify(...args: any[]): any; - //findOne(...args: any[]): any; - getIndexes(...args: any[]): any; - //insert(...args: any[]): any; - //mapReduce(...args: any[]): any; - //save(...args: any[]): any; - //update(...args: any[]): any; + findOneAndUpdate(): ModelQuery; + findOneAndUpdate(conditions: Object, update: Object, + callback?: (err: any, res: T) => void): ModelQuery; + findOneAndUpdate(conditions: Object, update: Object, + options: ModelFindOneAndUpdateOptions, + callback?: (err: any, res: T) => void): ModelQuery; - /** The collection name */ - collectionName: string; - /** The Connection instance */ - conn: Connection; - /** The collection name */ - name: string; - } + /** + * geoNear support for Mongoose + * @param GeoJSON point or legacy coordinate pair [x,y] to search near + * @param options for the qurery + * @param callback optional callback for the query + */ + geoNear(point: number[] | { + type: string; + coordinates: number[] + }, options: { + /** return the raw object */ + lean?: boolean; + [other: string]: any; + }, callback?: (err: any, res: T[], stats: any) => void): ModelQuery; + + /** + * Implements $geoSearch functionality for Mongoose + * @param conditions an object that specifies the match condition (required) + * @param options for the geoSearch, some (near, maxDistance) are required + * @param callback optional callback + */ + geoSearch(conditions: Object, options: { + /** x,y point to search for */ + near: number[]; + /** the maximum distance from the point near that a result can be */ + maxDistance: number; + /** The maximum number of results to return */ + limit?: number; + /** return the raw object instead of the Mongoose Model */ + lean?: boolean; + }, callback?: (err: any, res: T[]) => void): ModelQuery; + + /** + * Shortcut for creating a new Document from existing raw data, + * pre-saved in the DB. The document returned has no paths marked + * as modified initially. + */ + hydrate(obj: Object): T; + + /** + * Shortcut for validating an array of documents and inserting them into + * MongoDB if they're all valid. This function is faster than .create() + * because it only sends one operation to the server, rather than one for each + * document. + * This function does not trigger save middleware. + */ + insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): _MongoosePromise; + insertMany(doc: any, callback?: (error: any, doc: T) => void): _MongoosePromise; + insertMany(...docsWithCallback: Object[]): _MongoosePromise; + + /** + * Executes a mapReduce command. + * @param o an object specifying map-reduce options + * @param callbackoptional callback + */ + mapReduce( + o: ModelMapReduceOption, + callback?: (err: any, res: any) => void + ): _MongoosePromise; + + /** + * Populates document references. + * @param docs Either a single document or array of documents to populate. + * @param options A hash of key/val (path, options) used for population. + * @param callback Optional callback, executed upon completion. Receives err and the doc(s). + */ + populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: T[]) => void): _MongoosePromise; + populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: T) => void): _MongoosePromise; + + /** Removes documents from the collection. */ + remove(conditions: Object, callback?: (err: any) => void): Query; + + /** + * Updates documents in the database without returning them. + * All update values are cast to their appropriate SchemaTypes before being sent. + */ + update(conditions: Object, doc: Object, + callback?: (err: any, raw: any) => void): Query; + update(conditions: Object, doc: Object, options: ModelUpdateOptions, + callback?: (err: any, raw: any) => void): Query; + + /** Creates a Query, applies the passed conditions, and returns the Query. */ + where(path: string, val?: Object): Query; + } + + interface Document extends MongooseDocument, NodeJS.EventEmitter { + /** Signal that we desire an increment of this documents version. */ + increment(): this; + + /** + * Returns another Model instance. + * @param name model name + */ + model(name: string): Model; + + /** + * Removes this document from the db. + * @param fn optional callback + */ + remove(fn?: (err: any, product: T) => void): _MongoosePromise; + + /** + * Saves this document. + * @param options options optional options + * @param options.safe overrides schema's safe option + * @param options.validateBeforeSave set to false to save without validating. + * @param fn optional callback + */ + save(fn?: (err: any, product: T, numAffected: number) => void): _MongoosePromise; + + /** Base Mongoose instance the model uses. */ + base: typeof mongoose; + /** + * If this is a discriminator model, baseModelName is the + * name of the base model. + */ + baseModelName: String; + /** Collection the model uses. */ + collection: Collection; + /** Connection the model uses. */ + db: Connection; + /** Registered discriminators for this model. */ + discriminators: any; + /** The name of the model */ + modelName: string; + /** Schema the model uses. */ + schema: Schema; + } + + interface ModelFindByIdAndUpdateOptions { + /** true to return the modified document rather than the original. defaults to false */ + new?: boolean; + /** creates the object if it doesn't exist. defaults to false. */ + upsert?: boolean; + /** + * if true, runs update validators on this command. Update validators validate the + * update operation against the model's schema. + */ + runValidators?: boolean; + /** + * if this and upsert are true, mongoose will apply the defaults specified in the model's + * schema if a new document is created. This option only works on MongoDB >= 2.4 because + * it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ + sort?: Object; + /** sets the document fields to return */ + select?: Object; + } + + interface ModelFindOneAndUpdateOptions extends ModelFindByIdAndUpdateOptions { + /** Field selection. Equivalent to .select(fields).findOneAndUpdate() */ + fields?: Object | string; + /** puts a time limit on the query - requires mongodb >= 2.6.0 */ + maxTimeMS?: number; + /** if true, passes the raw result from the MongoDB driver as the third callback parameter */ + passRawResult?: boolean; + } + + interface ModelPopulateOptions { + /** space delimited path(s) to populate */ + path: string; + /** optional fields to select */ + select?: any; + /** optional query conditions to match */ + match?: Object; + /** optional name of the model to use for population */ + model?: string; + /** optional query options like sort, limit, etc */ + options?: Object; + } + + interface ModelUpdateOptions { + /** safe mode (defaults to value set in schema (true)) */ + safe?: boolean; + /** whether to create the doc if it doesn't match (false) */ + upsert?: boolean; + /** whether multiple documents should be updated (false) */ + multi?: boolean; + /** + * If true, runs update validators on this command. Update validators validate + * the update operation against the model's schema. + */ + runValidators?: boolean; + /** + * If this and upsert are true, mongoose will apply the defaults specified in the + * model's schema if a new document is created. This option only works on MongoDB >= 2.4 + * because it relies on MongoDB's $setOnInsert operator. + */ + setDefaultsOnInsert?: boolean; + /** overrides the strict option for this update */ + strict?: boolean; + /** disables update-only mode, allowing you to overwrite the doc (false) */ + overwrite?: boolean; + /** other options */ + [other: string]: any; + } + + interface ModelMapReduceOption { + map: Function | string; + reduce: (key: Key, vals: T[]) => Val; + /** query filter object. */ + query?: Object; + /** sort input objects using this key */ + sort?: Object; + /** max number of documents */ + limit?: number; + /** keep temporary data default: false */ + keeptemp?: boolean; + /** finalize function */ + finalize?: (key: Key, val: Val) => Val; + /** scope variables exposed to map/reduce/finalize during execution */ + scope?: Object; + /** it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X default: false */ + jsMode?: boolean; + /** provide statistics on job execution time. default: false */ + verbose?: boolean; + readPreference?: string; + /** sets the output target for the map reduce job. default: {inline: 1} */ + out?: { + /** the results are returned in an array */ + inline?: number; + /** + * {replace: 'collectionName'} add the results to collectionName: the + * results replace the collection + */ + replace?: string; + /** + * {reduce: 'collectionName'} add the results to collectionName: if + * dups are detected, uses the reducer / finalize functions + */ + reduce?: string; + /** + * {merge: 'collectionName'} add the results to collectionName: if + * dups exist the new docs overwrite the old + */ + merge?: string; + }; + } + + interface MapReduceResult { + _id: Key; + value: Val; + } + + /* + * section collection.js + * http://mongoosejs.com/docs/api.html#collection-js + */ + interface CollectionBase extends mongodb.Collection { + /* + * Abstract methods. Some of these are already defined on the + * mongodb.Collection interface so they've been commented out. + */ + ensureIndex(...args: any[]): any; + //find(...args: any[]): any; + findAndModify(...args: any[]): any; + //findOne(...args: any[]): any; + getIndexes(...args: any[]): any; + //insert(...args: any[]): any; + //mapReduce(...args: any[]): any; + //save(...args: any[]): any; + //update(...args: any[]): any; + + /** The collection name */ + collectionName: string; + /** The Connection instance */ + conn: Connection; + /** The collection name */ + name: string; } } From 6f74da66624332e852e6ebffff3e1d944a6de907 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 7 Aug 2016 23:53:35 -0400 Subject: [PATCH 02/68] changed types of document.save() and remove() to this --- mongoose/mongoose.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 430b3a2b0c..1c18bc67f5 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2303,13 +2303,13 @@ declare module "mongoose" { * Returns another Model instance. * @param name model name */ - model(name: string): Model; + model(name: string): Model; /** * Removes this document from the db. * @param fn optional callback */ - remove(fn?: (err: any, product: T) => void): _MongoosePromise; + remove(fn?: (err: any, product: this) => void): _MongoosePromise; /** * Saves this document. @@ -2318,7 +2318,7 @@ declare module "mongoose" { * @param options.validateBeforeSave set to false to save without validating. * @param fn optional callback */ - save(fn?: (err: any, product: T, numAffected: number) => void): _MongoosePromise; + save(fn?: (err: any, product: this, numAffected: number) => void): _MongoosePromise; /** Base Mongoose instance the model uses. */ base: typeof mongoose; From c80cd0be05fb75bcc51f1c3b19f5ad0d451bc0f2 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 7 Aug 2016 23:56:11 -0400 Subject: [PATCH 03/68] changed ModelQuery to more accurate name DocumentQuery --- mongoose/mongoose.d.ts | 154 ++++++++++++++++++++--------------------- 1 file changed, 77 insertions(+), 77 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 1c18bc67f5..55bdd3393d 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -27,43 +27,43 @@ * is just a simple heuristic to keep track of our progress. * * TODO for version 4.x [updated][tested]: - * [x][ ] index.js - * [x][ ] querystream.js - * [x][ ] connection.js - * [x][ ] utils.js - * [x][ ] browser.js - * [x][ ] drivers/node-mongodb-native/collection.js - * [x][ ] drivers/node-mongodb-native/connection.js - * [x][ ] error/messages.js - * [x][ ] error/validation.js - * [x][ ] error.js - * [x][ ] querycursor.js - * [x][ ] virtualtype.js - * [x][ ] schema.js - * [x][ ] document.js - * [x][ ] types/subdocument.js - * [x][ ] types/array.js - * [x][ ] types/documentarray.js - * [x][ ] types/buffer.js - * [x][ ] types/objectid.js - * [x][ ] types/embedded.js - * [x][ ] query.js - * [x][ ] schema/array.js - * [x][ ] schema/string.js - * [x][ ] schema/documentarray.js - * [x][ ] schema/number.js - * [x][ ] schema/date.js - * [x][ ] schema/buffer.js - * [x][ ] schema/boolean.js - * [x][ ] schema/objectid.js - * [x][ ] schema/mixed.js - * [x][ ] schema/embedded.js - * [x][ ] aggregate.js - * [x][ ] schematype.js - * [x][ ] promise.js - * [x][ ] ES6Promise.js - * [x][ ] model.js - * [x][ ] collection.js + * [x][x] index.js + * [x][x] querystream.js + * [x][x] connection.js + * [x][x] utils.js + * [x][x] browser.js + * [x][x] drivers/node-mongodb-native/collection.js + * [x][x] drivers/node-mongodb-native/connection.js + * [x][x] error/messages.js + * [x][x] error/validation.js + * [x][x] error.js + * [x][x] querycursor.js + * [x][x] virtualtype.js + * [x][x] schema.js + * [x][x] document.js + * [x][x] types/subdocument.js + * [x][x] types/array.js + * [x][x] types/documentarray.js + * [x][x] types/buffer.js + * [x][x] types/objectid.js + * [x][x] types/embedded.js + * [x][x] query.js + * [x][x] schema/array.js + * [x][x] schema/string.js + * [x][x] schema/documentarray.js + * [x][x] schema/number.js + * [x][x] schema/date.js + * [x][x] schema/buffer.js + * [x][x] schema/boolean.js + * [x][x] schema/objectid.js + * [x][x] schema/mixed.js + * [x][x] schema/embedded.js + * [x][x] aggregate.js + * [x][x] schematype.js + * [x][x] promise.js + * [x][x] ES6Promise.js + * [x][x] model.js + * [x][x] collection.js */ /* @@ -1124,13 +1124,13 @@ declare module "mongoose" { * section query.js * http://mongoosejs.com/docs/api.html#query-js */ - class Query extends ModelQuery {} + class Query extends DocumentQuery {} /* * Query.find() will return Query[]> however we need the * type T to create this so we save T in another parameter. */ - class ModelQuery extends mquery { + class DocumentQuery extends mquery { /** * Specifies a javascript function or expression to pass to MongoDBs query system. * Only use $where when you have a condition that cannot be met using other MongoDB @@ -1205,7 +1205,7 @@ declare module "mongoose" { * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a * Streams3-compatible interface, as well as a .next() function. */ - cursor(options?: Object): QueryCursor; + cursor(options?: Object): QueryCursor; /** Declares or executes a distict() operation. Passing a callback executes the query. */ distinct(callback?: (err: any, res: any[]) => void): Query; @@ -1235,9 +1235,9 @@ declare module "mongoose" { * query is executed, the result will be an array of documents. * @param criteria mongodb selector */ - find(callback?: (err: any, res: ModelType[]) => void): ModelQuery; + find(callback?: (err: any, res: DocType[]) => void): DocumentQuery; find(criteria: Object, - callback?: (err: any, res: ModelType[]) => void): ModelQuery; + callback?: (err: any, res: DocType[]) => void): DocumentQuery; /** * Declares the query a findOne operation. When executed, the first found document is @@ -1246,33 +1246,33 @@ declare module "mongoose" { * @param criteria mongodb selector * @param projection optional fields to return */ - findOne(callback?: (err: any, res: ModelType) => void): ModelQuery; + findOne(callback?: (err: any, res: DocType) => void): DocumentQuery; findOne(criteria: Object, - callback?: (err: any, res: ModelType) => void): ModelQuery; + callback?: (err: any, res: DocType) => void): DocumentQuery; /** * Issues a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. */ - findOneAndRemove(callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + findOneAndRemove(callback?: (error: any, doc: DocType, result: any) => void): DocumentQuery; findOneAndRemove(conditions: Object, - callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + callback?: (error: any, doc: DocType, result: any) => void): DocumentQuery; findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, - callback?: (error: any, doc: ModelType, result: any) => void): ModelQuery; + callback?: (error: any, doc: DocType, result: any) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command. * Finds a matching document, updates it according to the update arg, passing any options, and returns * the found document (if any) to the callback. The query executes immediately if callback is passed. */ - findOneAndUpdate(callback?: (err: any, doc: ModelType) => void): ModelQuery; + findOneAndUpdate(callback?: (err: any, doc: DocType) => void): DocumentQuery; findOneAndUpdate(update: Object, - callback?: (err: any, doc: ModelType) => void): ModelQuery; + callback?: (err: any, doc: DocType) => void): DocumentQuery; findOneAndUpdate(query: Object | Query, update: Object, - callback?: (err: any, doc: ModelType) => void): ModelQuery; + callback?: (err: any, doc: DocType) => void): DocumentQuery; findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: ModelType) => void): ModelQuery; + callback?: (err: any, doc: DocType) => void): DocumentQuery; /** * Specifies a $geometry condition. geometry() must come after either intersects() or within(). @@ -1521,7 +1521,7 @@ declare module "mongoose" { * Converts this query to a customized, reusable query * constructor with all arguments and options retained. */ - toConstructor(): typeof ModelQuery; + toConstructor(): typeof DocumentQuery; /** * Declare and/or execute this query as an update() operation. @@ -2066,11 +2066,11 @@ declare module "mongoose" { * @param projection optional fields to return */ findById(id: Object | string | number, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findById(id: Object | string | number, projection: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findById(id: Object | string | number, projection: Object, options: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; model(name: string): Model; @@ -2078,7 +2078,7 @@ declare module "mongoose" { * Creates a Query and specifies a $where condition. * @param argument is a javascript string or anonymous function */ - $where(argument: string | Function): ModelQuery; + $where(argument: string | Function): DocumentQuery; /** * Performs aggregations on the models collection. @@ -2125,12 +2125,12 @@ declare module "mongoose" { * Finds documents. * @param projection optional fields to return */ - find(callback?: (err: any, res: T[]) => void): ModelQuery; - find(conditions: Object, callback?: (err: any, res: T[]) => void): ModelQuery; + find(callback?: (err: any, res: T[]) => void): DocumentQuery; + find(conditions: Object, callback?: (err: any, res: T[]) => void): DocumentQuery; find(conditions: Object, projection: Object, - callback?: (err: any, res: T[]) => void): ModelQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery; find(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: T[]) => void): ModelQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery; @@ -2141,27 +2141,27 @@ declare module "mongoose" { * Executes immediately if callback is passed, else a Query object is returned. * @param id value of _id to query by */ - findByIdAndRemove(): ModelQuery; + findByIdAndRemove(): DocumentQuery; findByIdAndRemove(id: Object | number | string, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findByIdAndRemove(id: Object | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: Object; /** sets the document fields to return */ select?: Object; - }, callback?: (err: any, res: T) => void): ModelQuery; + }, callback?: (err: any, res: T) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) * is equivalent to findOneAndUpdate({ _id: id }, ...). * @param id value of _id to query by */ - findByIdAndUpdate(): ModelQuery; + findByIdAndUpdate(): DocumentQuery; findByIdAndUpdate(id: Object | number | string, update: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findByIdAndUpdate(id: Object | number | string, update: Object, options: ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; /** * Finds one document. @@ -2169,20 +2169,20 @@ declare module "mongoose" { * @param projection optional fields to return */ findOne(conditions?: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findOne(conditions: Object, projection: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findOne(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; /** * Issue a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the callback. * Executes immediately if callback is passed else a Query object is returned. */ - findOneAndRemove(): ModelQuery; + findOneAndRemove(): DocumentQuery; findOneAndRemove(conditions: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findOneAndRemove(conditions: Object, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose @@ -2193,7 +2193,7 @@ declare module "mongoose" { maxTimeMS?: number; /** sets the document fields to return */ select?: Object; - }, callback?: (err: any, res: T) => void): ModelQuery; + }, callback?: (err: any, res: T) => void): DocumentQuery; /** * Issues a mongodb findAndModify update command. @@ -2201,12 +2201,12 @@ declare module "mongoose" { * and returns the found document (if any) to the callback. The query executes immediately * if callback is passed else a Query object is returned. */ - findOneAndUpdate(): ModelQuery; + findOneAndUpdate(): DocumentQuery; findOneAndUpdate(conditions: Object, update: Object, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; findOneAndUpdate(conditions: Object, update: Object, options: ModelFindOneAndUpdateOptions, - callback?: (err: any, res: T) => void): ModelQuery; + callback?: (err: any, res: T) => void): DocumentQuery; /** * geoNear support for Mongoose @@ -2221,7 +2221,7 @@ declare module "mongoose" { /** return the raw object */ lean?: boolean; [other: string]: any; - }, callback?: (err: any, res: T[], stats: any) => void): ModelQuery; + }, callback?: (err: any, res: T[], stats: any) => void): DocumentQuery; /** * Implements $geoSearch functionality for Mongoose @@ -2238,7 +2238,7 @@ declare module "mongoose" { limit?: number; /** return the raw object instead of the Mongoose Model */ lean?: boolean; - }, callback?: (err: any, res: T[]) => void): ModelQuery; + }, callback?: (err: any, res: T[]) => void): DocumentQuery; /** * Shortcut for creating a new Document from existing raw data, From bbce379d500ae7687d647bec3c4c47b238b5cac1 Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 8 Aug 2016 00:00:35 -0400 Subject: [PATCH 04/68] updated tests for extending mongoose.Document and mongoose.Model --- mongoose/mongoose-tests.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 12d84cef3e..2b00e665cd 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1355,9 +1355,19 @@ interface MyModel extends mongoose.Model { staticMethod: () => void; } interface ModelStruct { - doc: MyDocument, - model: MyModel + doc: MyDocument; + model: MyModel; + method1: (callback: (model: MyModel, doc: MyDocument) => void) => MyModel; } +var modelStruct1: ModelStruct; +var myModel1: MyModel; +var myDocument1: MyDocument; +modelStruct1.method1(function (myModel1, myDocument1) { + myModel1.staticProp; + myModel1.staticMethod(); + myDocument1.prop; + myDocument1.method(); +}).staticProp.toLowerCase(); var mySchema = new mongoose.Schema({}); export var Final: MyModel = mongoose.connection.model('Final', mySchema); Final.findOne(function (err: any, doc: MyDocument) { From 11b67e8ad3366c45905034ea6079a62b1b4d54b0 Mon Sep 17 00:00:00 2001 From: Louy Alakkad Date: Tue, 9 Aug 2016 21:22:15 +0100 Subject: [PATCH 05/68] Return value of DocumentQuery#remove --- mongoose/mongoose.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 55bdd3393d..45c218a94c 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -1448,8 +1448,8 @@ declare module "mongoose" { * you must first call remove() and then execute it by using the exec() method. * @param criteria mongodb selector */ - remove(callback?: (err: any) => void): Query; - remove(criteria: Object | Query, callback?: (err: any) => void): Query; + remove(callback?: (err: any) => void): Query; + remove(criteria: Object | Query, callback?: (err: any) => void): Query; /** Specifies which document fields to include or exclude (also known as the query "projection") */ select(arg: string | Object): this; From 6d2d24d72a5bb5dce3cd39c707028c2ba2d3485e Mon Sep 17 00:00:00 2001 From: Louy Alakkad Date: Tue, 9 Aug 2016 21:03:19 +0100 Subject: [PATCH 06/68] Adding Model.modelName and Model.collection See: https://github.com/Automattic/mongoose/blob/5c490f99e5d281e5303c023bade93a0624e5db66/lib/model.js#L62-L88 --- mongoose/mongoose.d.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 45c218a94c..3b6590feda 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2059,6 +2059,15 @@ declare module "mongoose" { */ new(doc?: Object): T; + /** The name of the model. */ + modelName: string; + + /** Collection the model uses. */ + collection: Collection; + + /** If this is a discriminator model, `baseModelName` is the name of the base model. */ + baseModelName: string; + /** * Finds a single document by its _id field. findById(id) is almost* * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. From a2158341d855bf1aa8b1d80e282f67d864596b0e Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 14 Aug 2016 23:53:38 -0400 Subject: [PATCH 07/68] moved properties of Model and model into a separate interface --- mongoose/mongoose-tests.ts | 4 ++++ mongoose/mongoose.d.ts | 32 ++++++++++++++++++++++++++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 2b00e665cd..ddec97e9d1 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1249,6 +1249,10 @@ mongoModel.discriminators; mongoModel.modelName.toLowerCase(); MongoModel = mongoModel.base.model('new', mongoModel.schema); /* inherited properties */ +MongoModel.modelName; +mongoModel.modelName; +MongoModel.collection; +mongoModel.collection; mongoModel._id; mongoModel.execPopulate(); mongoModel.on('data', cb); diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 3b6590feda..a6a2fc409c 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2040,7 +2040,7 @@ declare module "mongoose" { * section model.js * http://mongoosejs.com/docs/api.html#model-js */ - interface Model extends NodeJS.EventEmitter { + interface Model extends NodeJS.EventEmitter, ModelProperties { /** * Model constructor * Provides the interface to MongoDB collections as well as creates document instances. @@ -2059,14 +2059,26 @@ declare module "mongoose" { */ new(doc?: Object): T; - /** The name of the model. */ - modelName: string; + /** Base Mongoose instance the model uses. */ + base: typeof mongoose; + + /** If this is a discriminator model, `baseModelName` is the name of the base model. */ + baseModelName: string; /** Collection the model uses. */ collection: Collection; - /** If this is a discriminator model, `baseModelName` is the name of the base model. */ - baseModelName: string; + /** Connection the model uses. */ + db: Connection; + + /** Registered discriminators for this model. */ + discriminators: any; + + /** The name of the model. */ + modelName: string; + + /** Schema the model uses. */ + schema: Schema; /** * Finds a single document by its _id field. findById(id) is almost* @@ -2304,7 +2316,7 @@ declare module "mongoose" { where(path: string, val?: Object): Query; } - interface Document extends MongooseDocument, NodeJS.EventEmitter { + interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties { /** Signal that we desire an increment of this documents version. */ increment(): this; @@ -2328,22 +2340,30 @@ declare module "mongoose" { * @param fn optional callback */ save(fn?: (err: any, product: this, numAffected: number) => void): _MongoosePromise; + } + interface ModelProperties { /** Base Mongoose instance the model uses. */ base: typeof mongoose; + /** * If this is a discriminator model, baseModelName is the * name of the base model. */ baseModelName: String; + /** Collection the model uses. */ collection: Collection; + /** Connection the model uses. */ db: Connection; + /** Registered discriminators for this model. */ discriminators: any; + /** The name of the model */ modelName: string; + /** Schema the model uses. */ schema: Schema; } From 486e24d0a65e774ca301fe6119c34f53a73bbd5e Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 14 Aug 2016 23:55:56 -0400 Subject: [PATCH 08/68] removed extra Model properties --- mongoose/mongoose.d.ts | 21 --------------------- 1 file changed, 21 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index a6a2fc409c..a94644393e 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2059,27 +2059,6 @@ declare module "mongoose" { */ new(doc?: Object): T; - /** Base Mongoose instance the model uses. */ - base: typeof mongoose; - - /** If this is a discriminator model, `baseModelName` is the name of the base model. */ - baseModelName: string; - - /** Collection the model uses. */ - collection: Collection; - - /** Connection the model uses. */ - db: Connection; - - /** Registered discriminators for this model. */ - discriminators: any; - - /** The name of the model. */ - modelName: string; - - /** Schema the model uses. */ - schema: Schema; - /** * Finds a single document by its _id field. findById(id) is almost* * equivalent to findOne({ _id: id }). findById() triggers findOne hooks. From 2854c554b2ffb6b4f42229fd1aa868d72e716885 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 15:44:28 -0400 Subject: [PATCH 09/68] cleanup and update to 4.5.9, changed default promises to global promises to work with typescript 2.x --- mongoose/mongoose-tests.ts | 15 ++-- mongoose/mongoose.d.ts | 150 +++++++++++++++++++------------------ 2 files changed, 84 insertions(+), 81 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index ddec97e9d1..d846023143 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -27,7 +27,7 @@ mongoose.connect(connectUri, { autoIndex: true }, mongos: true -}).then(cb).fulfill(); +}).then(cb); mongoose.connect(connectUri, function (error) { error.stack; }); @@ -45,7 +45,7 @@ mongoose.createConnection('localhost', 'database', 3000, { autoIndex: false } }).open(''); -mongoose.disconnect(cb).then(cb).fulfill; +mongoose.disconnect(cb).then(cb); mongoose.get('test'); mongoose.model('Actor', new mongoose.Schema({ name: String @@ -540,7 +540,7 @@ query.where('loc').within().box(lowerLeft, upperRight) query.box({ ll : lowerLeft, ur : upperRight }).box({}); var queryModel = mongoose.model('QModel') query.cast(new queryModel(), {}).hasOwnProperty(''); -query.catch(function (err) {}).catch(); +query.catch(cb).catch(cb); query.center({}).center({}); query.centerSphere({ center: [50, 50], radius: 10 }).centerSphere('path', {}); query.circle({ center: [50, 50], radius: 10 }).circle('path'); @@ -695,7 +695,7 @@ query.stream().on('data', function (doc: any) { }); query.tailable().tailable(false); query.then(cb).catch(cb); -(new (query.toConstructor())()).toConstructor(); +(new (query.toConstructor())(1, 2, 3)).toConstructor(); query.update({}, doc, { }, cb); @@ -1060,12 +1060,13 @@ mongoose.model('').aggregate() }); /* pluggable promise */ -mongoose.Promise = Promise; +(mongoose).Promise = Promise; +require('mongoose').Promise = Promise; mongoose.Promise.race; mongoose.Promise.all; mongoose.model('').findOne() - .exec().addErrback(cb); + .exec().then(cb); /* * section model.js @@ -1377,5 +1378,5 @@ export var Final: MyModel = mongoose.connection.model('Fina Final.findOne(function (err: any, doc: MyDocument) { doc.save(); doc.remove(); - doc.model(null, null); + doc.model(''); }); \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index a94644393e..b28a222778 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mongoose 4.5.4 +// Type definitions for Mongoose 4.5.9 // Project: http://mongoosejs.com/ // Definitions by: simonxca , horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,6 @@ /// /// /// -/// /* * Guidelines for maintaining these definitions: @@ -93,7 +92,6 @@ declare module "mongoose" { * http://mongoosejs.com/docs/api.html#index-js */ export var DocumentProvider: any; - export var Model: Model; // recursive constructor export var Mongoose: new(...args: any[]) => typeof mongoose; export var SchemaTypes: typeof Schema.Types; @@ -107,7 +105,6 @@ declare module "mongoose" { /** The Mongoose version */ export var version: string; - /* Methods */ /** * Opens the default mongoose connection. * Options passed take precedence over options included in connection strings. @@ -173,20 +170,19 @@ declare module "mongoose" { /** Sets mongoose options */ export function set(key: string, value: any): void; - type MongooseThenable = typeof mongoose & _MongooseThenable; - interface _MongooseThenable { + type MongooseThenable = typeof mongoose & { /** * Ability to use mongoose object as a pseudo-promise so .connect().then() * and .disconnect().then() are viable. */ then(onFulfill?: () => void | TRes | PromiseLike, - onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): Promise; /** * Ability to use mongoose object as a pseudo-promise so .connect().then() * and .disconnect().then() are viable. */ - catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): _MongoosePromise; + catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): Promise; } class CastError extends Error { @@ -205,7 +201,7 @@ declare module "mongoose" { * http://mongoosejs.com/docs/api.html#querystream-js * * QueryStream can only be accessed using query#stream(), we only - * expose its interface here to enable type-checking. + * expose its interface here. */ interface QueryStream extends stream.Stream { /** @@ -293,7 +289,7 @@ declare module "mongoose" { callback?: (err: any) => void): any; /** Closes the connection */ - close(callback?: (err: any) => void): _MongoosePromise; + close(callback?: (err: any) => void): Promise; /** * Retrieves a collection, creating it if not cached. @@ -375,6 +371,10 @@ declare module "mongoose" { mongos?: boolean; } + interface ConnectOptions extends + ConnectionOpenOptions, + ConnectionOpenSetOptions {} + /* * section drivers/node-mongodb-native/collection.js * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js @@ -412,8 +412,6 @@ declare module "mongoose" { static STATES: Object; } - interface ConnectOptions extends ConnectionOpenOptions, ConnectionOpenSetOptions {} - /* * section error/validation.js * http://mongoosejs.com/docs/api.html#error-validation-js @@ -474,7 +472,7 @@ declare module "mongoose" { constructor(query: Query, options: Object): QueryCursor; /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ - close(callback?: (error: any, result: any) => void): _MongoosePromise; + close(callback?: (error: any, result: any) => void): Promise; /** * Execute fn for every document in the cursor. If fn returns a promise, @@ -482,13 +480,13 @@ declare module "mongoose" { * Returns a promise that resolves when done. * @param callback executed when all docs have been processed */ - eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): _MongoosePromise; + eachAsync(fn: (doc: T) => any, callback?: (err: any) => void): Promise; /** * Get the next document from this cursor. Will return null when there are * no documents left. */ - next(callback?: (err: any) => void): _MongoosePromise; + next(callback?: (err: any) => void): Promise; } /* @@ -729,7 +727,7 @@ declare module "mongoose" { * Useful for ES2015 integration. * @returns promise that resolves to the document when population is done */ - execPopulate(): _MongoosePromise; + execPopulate(): Promise; /** * Returns the value of a path. @@ -848,8 +846,8 @@ declare module "mongoose" { * @param optional options internal options * @param callback callback called after validation completes, passing an error if one occurred */ - validate(callback?: (err: any) => void): _MongoosePromise; - validate(optional: Object, callback?: (err: any) => void): _MongoosePromise; + validate(callback?: (err: any) => void): Promise; + validate(optional: Object, callback?: (err: any) => void): Promise; /** * Executes registered validation rules (skipping asynchronous validators) for this document. @@ -915,9 +913,9 @@ declare module "mongoose" { } /* - * section types/array.js - * http://mongoosejs.com/docs/api.html#types-array-js - */ + * section types/array.js + * http://mongoosejs.com/docs/api.html#types-array-js + */ class Array extends global.Array { /** * Atomically shifts the array at most one time per document save(). @@ -1053,9 +1051,9 @@ declare module "mongoose" { } /* - * section types/buffer.js - * http://mongoosejs.com/docs/api.html#types-buffer-js - */ + * section types/buffer.js + * http://mongoosejs.com/docs/api.html#types-buffer-js + */ class Buffer extends global.Buffer { /** * Copies the buffer. @@ -1082,8 +1080,7 @@ declare module "mongoose" { * section types/objectid.js * http://mongoosejs.com/docs/api.html#types-objectid-js */ - var ObjectId: typeof mongodb.ObjectID; - interface ObjectId extends mongodb.ObjectID {} + class ObjectId extends mongodb.ObjectID {} /* * section types/embedded.js @@ -1123,13 +1120,13 @@ declare module "mongoose" { /* * section query.js * http://mongoosejs.com/docs/api.html#query-js + * + * Query is for backwards compatibility. Example: Query.find() returns Query. + * If later in the query chain a method returns Query, we will need to know type T. + * So we save this type as the second type parameter in DocumentQuery. Since people have + * been using Query, we set it as an alias of DocumentQuery. */ class Query extends DocumentQuery {} - - /* - * Query.find() will return Query[]> however we need the - * type T to create this so we save T in another parameter. - */ class DocumentQuery extends mquery { /** * Specifies a javascript function or expression to pass to MongoDBs query system. @@ -1170,7 +1167,7 @@ declare module "mongoose" { * resolved with either the doc(s) or rejected with the error. * Like .then(), but only takes a rejection handler. */ - catch(reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; + catch(reject?: (err: any) => void | TRes | PromiseLike): Promise; /** * DEPRECATED Alias for circle @@ -1223,8 +1220,8 @@ declare module "mongoose" { equals(val: Object): this; /** Executes the query */ - exec(callback?: (err: any, res: T) => void): _MongoosePromise; - exec(operation: string | Function, callback?: (err: any, res: T) => void): _MongoosePromise; + exec(callback?: (err: any, res: T) => void): Promise; + exec(operation: string | Function, callback?: (err: any, res: T) => void): Promise; /** Specifies an $exists condition */ exists(val?: boolean): this; @@ -1515,13 +1512,14 @@ declare module "mongoose" { /** Executes this query and returns a promise */ then(resolve?: (res: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise; + reject?: (err: any) => void | TRes | PromiseLike): Promise; /** * Converts this query to a customized, reusable query * constructor with all arguments and options retained. */ - toConstructor(): typeof DocumentQuery; + toConstructor(): new(...args: any[]) => Query; + toConstructor(): new(...args: any[]) => DocumentQuery; /** * Declare and/or execute this query as an update() operation. @@ -1858,10 +1856,10 @@ declare module "mongoose" { // If cursor option is on, could return an object /** Executes the aggregate pipeline on the currently bound Model. */ - exec(callback?: (err: any, result: T) => void): _MongoosePromise | any; + exec(callback?: (err: any, result: T) => void): Promise | any; /** Execute the aggregation with explain */ - explain(callback?: (err: any, result: T) => void): _MongoosePromise; + explain(callback?: (err: any, result: T) => void): Promise; /** * Appends a new custom $group operator to this aggregate pipeline. @@ -1936,7 +1934,7 @@ declare module "mongoose" { /** Provides promise for aggregate. */ then(resolve?: (val: T) => void | TRes | PromiseLike, - reject?: (err: any) => void | TRes | PromiseLike): _MongoosePromise + reject?: (err: any) => void | TRes | PromiseLike): Promise /** * Appends new custom $unwind operator(s) to this aggregate pipeline. @@ -2004,34 +2002,37 @@ declare module "mongoose" { type?: string): this; } - /** + /* * section promise.js * http://mongoosejs.com/docs/api.html#promise-js - * - * You must assign a promise library: - * - * 1. To use mongoose's default promise library: - * Install mongoose-promise.d.ts - * - * 2. To use native ES6 promises, add this line to your main .d.ts file: - * type MongoosePromise = Promise; - * - * 3. To use another promise library (for example q): - * Install q.d.ts - * Then add this line to your main .d.ts file: - * type MongoosePromise = Q.Promise; */ - interface _MongoosePromise extends MongoosePromise {} - interface Promise extends MongoosePromise {} - /** * To assign your own promise library: * - * 1. Include this somewhere in your code: - * mongoose.Promise = YOUR_PROMISE; + * 1. Typescript does not allow assigning properties of imported modules. + * To avoid compile errors use one of the options below in your code: * - * 2. Include this somewhere in your main .d.ts file: - * type MongoosePromise = YOUR_PROMISE; + * - (mongoose).Promise = YOUR_PROMISE; + * - require('mongoose').Promise = YOUR_PROMISE; + * - import mongoose = require('mongoose'); + * mongoose.Promise = YOUR_PROMISE; + * + * 2. To assign type definitions for your promise library, you will need + * to have a .d.ts file with the following code when you compile: + * + * - import * as Q from 'q'; + * declare module 'mongoose' { + * type Promise = Q.promise; + * } + * + * - import * as Bluebird from 'bluebird'; + * declare module 'mongoose' { + * type Promise = Bluebird; + * } + * + * Uses global.Promise by default. If you would like to use mongoose default + * mpromise implementation (which is deprecated), you can omit step 1 and + * run npm install @types/mongoose-promise */ export var Promise: any; export var PromiseProvider: any; @@ -2040,6 +2041,7 @@ declare module "mongoose" { * section model.js * http://mongoosejs.com/docs/api.html#model-js */ + export var Model: Model; interface Model extends NodeJS.EventEmitter, ModelProperties { /** * Model constructor @@ -2087,7 +2089,7 @@ declare module "mongoose" { * @param ... aggregation pipeline operator(s) or operator array */ aggregate(...aggregations: Object[]): Aggregate; - aggregate(...aggregationsWithCallback: Object[]): _MongoosePromise; + aggregate(...aggregationsWithCallback: Object[]): Promise; /** Counts number of matching documents in a database collection. */ count(conditions: Object, callback?: (err: any, count: number) => void): Query; @@ -2097,9 +2099,9 @@ declare module "mongoose" { * does new MyModel(doc).save() for every doc in docs. * Triggers the save() hook. */ - create(docs: any[], callback?: (err: any, res: T[]) => void): _MongoosePromise; - create(...docs: Object[]): _MongoosePromise; - create(...docsWithCallback: Object[]): _MongoosePromise; + create(docs: any[], callback?: (err: any, res: T[]) => void): Promise; + create(...docs: Object[]): Promise; + create(...docsWithCallback: Object[]): Promise; /** * Adds a discriminator type. @@ -2118,8 +2120,8 @@ declare module "mongoose" { * @param options internal options * @param cb optional callback */ - ensureIndexes(callback?: (err: any) => void): _MongoosePromise; - ensureIndexes(options: Object, callback?: (err: any) => void): _MongoosePromise; + ensureIndexes(callback?: (err: any) => void): Promise; + ensureIndexes(options: Object, callback?: (err: any) => void): Promise; /** * Finds documents. @@ -2254,9 +2256,9 @@ declare module "mongoose" { * document. * This function does not trigger save middleware. */ - insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): _MongoosePromise; - insertMany(doc: any, callback?: (error: any, doc: T) => void): _MongoosePromise; - insertMany(...docsWithCallback: Object[]): _MongoosePromise; + insertMany(docs: any[], callback?: (error: any, docs: T[]) => void): Promise; + insertMany(doc: any, callback?: (error: any, doc: T) => void): Promise; + insertMany(...docsWithCallback: Object[]): Promise; /** * Executes a mapReduce command. @@ -2266,7 +2268,7 @@ declare module "mongoose" { mapReduce( o: ModelMapReduceOption, callback?: (err: any, res: any) => void - ): _MongoosePromise; + ): Promise; /** * Populates document references. @@ -2275,9 +2277,9 @@ declare module "mongoose" { * @param callback Optional callback, executed upon completion. Receives err and the doc(s). */ populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: T[]) => void): _MongoosePromise; + callback?: (err: any, res: T[]) => void): Promise; populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: T) => void): _MongoosePromise; + callback?: (err: any, res: T) => void): Promise; /** Removes documents from the collection. */ remove(conditions: Object, callback?: (err: any) => void): Query; @@ -2309,7 +2311,7 @@ declare module "mongoose" { * Removes this document from the db. * @param fn optional callback */ - remove(fn?: (err: any, product: this) => void): _MongoosePromise; + remove(fn?: (err: any, product: this) => void): Promise; /** * Saves this document. @@ -2318,7 +2320,7 @@ declare module "mongoose" { * @param options.validateBeforeSave set to false to save without validating. * @param fn optional callback */ - save(fn?: (err: any, product: this, numAffected: number) => void): _MongoosePromise; + save(fn?: (err: any, product: this, numAffected: number) => void): Promise; } interface ModelProperties { From 3f9a9295bf92950347ffcb7b311a9e8a0d03633c Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 15:49:27 -0400 Subject: [PATCH 10/68] updates mongoose-paginate to work with new mongoose interfaces --- mongoose-paginate/mongoose-paginate-tests.ts | 8 ++++---- mongoose-paginate/mongoose-paginate.d.ts | 7 +++---- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/mongoose-paginate/mongoose-paginate-tests.ts b/mongoose-paginate/mongoose-paginate-tests.ts index 7857ffda33..42fc42be69 100644 --- a/mongoose-paginate/mongoose-paginate-tests.ts +++ b/mongoose-paginate/mongoose-paginate-tests.ts @@ -11,14 +11,15 @@ import { model, PaginateModel, PaginateOptions, - PaginateResult + PaginateResult, + Document } from 'mongoose'; import * as mongoosePaginate from 'mongoose-paginate'; import { Router, Request, Response } from 'express'; //#region Test Models -interface User { +interface User extends Document { email: string; username: string; password: string; @@ -32,8 +33,7 @@ const UserSchema: Schema = new Schema({ UserSchema.plugin(mongoosePaginate); -type UserModel = _UserModel & PaginateModel; -interface _UserModel {} +interface UserModel extends PaginateModel {}; let UserModel: UserModel = model('User', UserSchema) as UserModel; //#endregion diff --git a/mongoose-paginate/mongoose-paginate.d.ts b/mongoose-paginate/mongoose-paginate.d.ts index 5481c42775..c90e7550fd 100644 --- a/mongoose-paginate/mongoose-paginate.d.ts +++ b/mongoose-paginate/mongoose-paginate.d.ts @@ -26,16 +26,15 @@ declare module 'mongoose' { offset?: number; } - export type PaginateModel = _PaginateModel & Model; - interface _PaginateModel { + interface PaginateModel extends Model { paginate(query?: Object, options?: PaginateOptions, callback?: (err: any, result: PaginateResult) => void): Promise>; } - export function model( + export function model( name: string, schema?: Schema, collection?: string, - skipInit?: boolean): Statics & PaginateModel; + skipInit?: boolean): PaginateModel; } declare module 'mongoose-paginate' { From f00d294bf6f8827e7396e58dfc381815729e8e00 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 15:54:13 -0400 Subject: [PATCH 11/68] updates passport-local-mongoose to use mongoose intefaces instead of type intersections --- passport-local-mongoose/passport-local-mongoose-tests.ts | 7 +++---- passport-local-mongoose/passport-local-mongoose.d.ts | 9 ++++----- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts index cf41176f08..993d5b05da 100644 --- a/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -77,10 +77,9 @@ options.errorMessages = errorMessages; UserSchema.plugin(passportLocalMongoose, options); -type UserModel = _UserModel & PassportLocalModel; -interface _UserModel {} +interface UserModel extends PassportLocalModel {} -let UserModel: UserModel = model('User', UserSchema) as UserModel; +let UserModel: UserModel = model('User', UserSchema); //#endregion @@ -96,7 +95,7 @@ passport.use('login', new LocalStrategy({ process.nextTick(() => { UserModel .findOne({ 'username': username }) - .exec((err: any, user: model) => { + .exec((err: any, user: User) => { if (err) { console.log(err); return done(err, null); diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index 8e4a6bb777..acb834d85c 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -10,14 +10,13 @@ declare module 'mongoose' { import passportLocal = require('passport-local'); // methods - export interface PassportLocalDocument { + export interface PassportLocalDocument extends Document { setPassword(password: string, cb: (err: any, res: any) => void): void; authenticate(password: string, cb: (err: any, res: any, error: any) => void): void; } // statics - export type PassportLocalModel = _PassportLocalModel & Model; - interface _PassportLocalModel { + interface PassportLocalModel extends Model { authenticate(): (username: string, password: string, cb: (err: any, res: T, error: any) => void) => void; serializeUser(): (user: PassportLocalModel, cb: (err: any) => void) => void; deserializeUser(): (username: string, cb: (err: any) => void) => void; @@ -77,11 +76,11 @@ declare module 'mongoose' { ): this; } - export function model( + export function model( name: string, schema?: PassportLocalSchema, collection?: string, - skipInit?: boolean): Statics & PassportLocalModel; + skipInit?: boolean): PassportLocalModel; } declare module 'passport-local-mongoose' { From 85290f2ffb682ab4aab67fc77253183079ec426d Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 15:54:53 -0400 Subject: [PATCH 12/68] adds a README for mongoose --- mongoose/README.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 mongoose/README.md diff --git a/mongoose/README.md b/mongoose/README.md new file mode 100644 index 0000000000..4a581dcfdb --- /dev/null +++ b/mongoose/README.md @@ -0,0 +1 @@ +# TESTING \ No newline at end of file From 5ed0b6507603f37bab7bfef280c6d7ffa372c711 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 22:24:13 -0400 Subject: [PATCH 13/68] adds a README plus better tests --- mongoose/README.md | 192 +++++++++++++++++- mongoose/mongoose-tests.ts | 8 +- mongoose/mongoose.d.ts | 15 +- .../passport-local-mongoose-tests.ts | 2 +- 4 files changed, 212 insertions(+), 5 deletions(-) diff --git a/mongoose/README.md b/mongoose/README.md index 4a581dcfdb..03b483ecd1 100644 --- a/mongoose/README.md +++ b/mongoose/README.md @@ -1 +1,191 @@ -# TESTING \ No newline at end of file +## MongooseJS Typescript Docs +Below are some examples of how to use these Definitions.
+Scenarios where the Typescript code is identical to plain Javascript code are omitted. + +#### Mongoose Methods, Properties, Constructors +You can call methods from the mongoose instance using: +``` +import * as mongoose from 'mongoose'; +var MyModel = mongoose.model(...); +var MySchema: mongoose.Schema = new mongoose.Schema(...); +``` + +Alternatively, you can import individual names and call them: +``` +import {model, Schema} from 'mongoose'; +var MyModel = model(...); +var MySchema: Schema = new Schema(...): +``` + + +#### Creating and Saving Documents +``` +import {Document, model, Model, Schema} from 'mongoose'; + +var UserSchema: Schema = new Schema({ + username: { + type: String, + required: true, + unique: true + }, + age: Number, + friends: [String], + data: [Schema.Types.Mixed] +}); + +interface IUser extends Document { + username: string; + age: number; + friends: string[]; + data: any[]; +} + +var UserModel: Model = mongoose.model('User', UserSchema); + +var user = new UserModel({name: 'Jane'}); +user.username; // IUser properties are available +user.save(); // mongoose Document methods are available + +UserModel.findOne({}, (err: any, user: IUser) => { + user.username; // IUser properties are available + user.save(); // mongoose Document methods are available +}); +``` + +#### Instance Methods and Virtual Properties +``` +import {Document, model, Model, Schema} from 'mongoose'; + +var UserSchema: Schema = new Schema({ + name: String +}); + +UserSchema.methods.method1 = function () { return '' }; +UserSchema.virtual('nameInCaps').get(function () { + return this.name.toUpperCase(); +}); +UserSchema.virtual('nameInCaps').set(function (caps) { + this.name = caps.toLowerCase(); +}); + +interface IUser extends Document { + name: string; + nameInCaps: string; + method1: () => string; +} + +var UserModel: Model = model('User', UserSchema); +var user = new UserModel({name: 'Billy'}); + +user.method1(); // IUser methods are available +user.nameInCaps; // virtual properties can be used + +UserModel.findOne({}, (err: any, user: IUser) => { + user.method1(); // IUser methods are available + user.nameInCaps; // virtual properties can be used +}); +``` + +#### Static Methods +``` +import {Document, model, Model, Schema} from 'mongoose'; + +var UserSchema = new Schema({}); +UserSchema.statics.static1 = function () { return '' }; + +interface IUserDocument extends Document {...} +interface IUserModel extends Model { + static1: () => string; +} + +var UserModel: IUserModel = model('User', UserSchema); +UserModel.static1(); // static methods are available +``` + +#### Plugins +To write definitions for plugins, extend the mongoose module and create a simple plugin module: +``` +// plugin.d.ts +declare module 'mongoose' { + export interface PassportLocalDocument {...} + export interface PassportLocalSchema extends Schema {...} + export interface PassportLocalModel extends Model {...} + ... +} + +declare module 'passport-local-mongoose' { + import mongoose = require('mongoose'); + var _: (schema: mongoose.Schema, options?: Object) => void; + export = _; +} + +// user.ts +import { + model, + PassportLocalDocument, + PassportLocalSchema, + PassportLocalModel + Schema +} from 'mongoose'; +import * as passportLocalMongoose from 'passport-local-mongoose'; + +var UserSchema: PassportLocalSchema = new Schema({}); +UserSchema.plugin(passportLocalMongoose, options); + +interface IUser extends PassportLocalDocument {...} +interface IUserModel extends PassportLocalModel {...} + +var UserModel: IUserModel = model('User', UserSchema); +``` +Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts) + +#### Promises +These definitions use global.Promise by default. If you would like to use mongoose's own mpromise +definition (which is deprecated), you can install definitions for [mongoose-promise](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/mongoose-promise). + +If you'd like to use something other than global.Promise, you'll need to create a simple .d.ts file: +``` +// promise-bluebird.d.ts +import * as Bluebird from 'bluebird'; + +declare module 'mongoose' { + type Promise = Bluebird; +} + +// promise-q.d.ts +import * as Q from 'q'; + +declare module 'mongoose' { + type Promise = Q.Promise; +} + +// another-promise.d.ts +... +``` +To use it, you will need to `/// ` in one of your source code files, +or include the `.d.ts` file in your compile. + +To assign the new promise library in your code, you will need to use one of the following options (since +Typescript does not allow assigning properties of imported modules): + +* `(mongoose).Promise = YOUR_PROMISE;` +* `require('mongoose').Promise = YOUR_PROMISE;` +* `import mongoose = require('mongoose'); ... mongoose.Promise = YOUR_PROMISE;` + +#### FAQ +Q: Why are there 2 interfaces for Documents called Document and MongooseDocument?
+A: People have been using this for a long time: +``` +interface IUser extends mongoose.Document { + ... +} +``` +When it should really be this: +``` +interface IUser extends mongoose.model { + ... +} +``` +For backwards compatibility Document is an interface for [mongoose.model](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
+And MongooseDocument is an interface for [mongoose.Document](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
+At some point in the future this may get fixed, which would require fixing your code. \ No newline at end of file diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index d846023143..51959b9e41 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1379,4 +1379,10 @@ Final.findOne(function (err: any, doc: MyDocument) { doc.save(); doc.remove(); doc.model(''); -}); \ No newline at end of file +}); +export var Final2: MyModel = mongoose.model('Final2', mySchema); +Final2.staticMethod(); +Final2.staticProp; +var final2 = new Final2(); +final2.prop; +final2.method; \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index b28a222778..81247104ef 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -152,6 +152,12 @@ declare module "mongoose" { */ export function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; + export function model>( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean + ): U; /** * Returns an array of model names created on this instance of Mongoose. @@ -311,6 +317,11 @@ declare module "mongoose" { * @returns The compiled model */ model(name: string, schema?: Schema, collection?: string): Model; + model>( + name: string, + schema?: Schema, + collection?: string + ): U; /** Returns an array of model names created on this connection. */ modelNames(): string[]; @@ -704,7 +715,7 @@ declare module "mongoose" { * section document.js * http://mongoosejs.com/docs/api.html#document-js */ - class MongooseDocument { + interface MongooseDocument { /** Checks if a path is set to its default. */ $isDefault(path?: string): boolean; @@ -2074,7 +2085,7 @@ declare module "mongoose" { findById(id: Object | string | number, projection: Object, options: Object, callback?: (err: any, res: T) => void): DocumentQuery; - model(name: string): Model; + model(name: string): Model; /** * Creates a Query and specifies a $where condition. diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts index 993d5b05da..c7d4ffc381 100644 --- a/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -34,7 +34,7 @@ interface User extends PassportLocalDocument { last: Date; } -const UserSchema: PassportLocalSchema = new Schema({ +const UserSchema: PassportLocalSchema = new Schema({ username: String, hash: String, salt: String, From 697685356ed872a4c754d86ac33cf9b56f967409 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 22:36:44 -0400 Subject: [PATCH 14/68] adds table of contents to readme --- mongoose/README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/mongoose/README.md b/mongoose/README.md index 03b483ecd1..fa3b695c91 100644 --- a/mongoose/README.md +++ b/mongoose/README.md @@ -2,6 +2,15 @@ Below are some examples of how to use these Definitions.
Scenarios where the Typescript code is identical to plain Javascript code are omitted. +### Table of Contents +* [Mongoose Methods, Properties, Constructors](#mongoose-methods-properties-constructors) +* [Creating and Saving Documents](#creating-and-saving-documents) +* [Instance Methods, Virtual Properties](#instance-methods-and-virtual-properties) +* [Static Methods](#static-methods) +* [Plugins](#plugins) +* [Promises](#promises) +* [FAQ](#faq) + #### Mongoose Methods, Properties, Constructors You can call methods from the mongoose instance using: ``` From aa1c6efe5106663df8dea5c13652af23fd1a9f28 Mon Sep 17 00:00:00 2001 From: Simon Date: Sun, 21 Aug 2016 22:40:03 -0400 Subject: [PATCH 15/68] adds links in each section to top of README --- mongoose/README.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/mongoose/README.md b/mongoose/README.md index fa3b695c91..1d8c7083f9 100644 --- a/mongoose/README.md +++ b/mongoose/README.md @@ -25,7 +25,7 @@ import {model, Schema} from 'mongoose'; var MyModel = model(...); var MySchema: Schema = new Schema(...): ``` - +[top](#mongoosejs-typescript-docs) #### Creating and Saving Documents ``` @@ -60,6 +60,7 @@ UserModel.findOne({}, (err: any, user: IUser) => { user.save(); // mongoose Document methods are available }); ``` +[top](#mongoosejs-typescript-docs) #### Instance Methods and Virtual Properties ``` @@ -94,6 +95,7 @@ UserModel.findOne({}, (err: any, user: IUser) => { user.nameInCaps; // virtual properties can be used }); ``` +[top](#mongoosejs-typescript-docs) #### Static Methods ``` @@ -110,6 +112,7 @@ interface IUserModel extends Model { var UserModel: IUserModel = model('User', UserSchema); UserModel.static1(); // static methods are available ``` +[top](#mongoosejs-typescript-docs) #### Plugins To write definitions for plugins, extend the mongoose module and create a simple plugin module: @@ -147,6 +150,7 @@ interface IUserModel extends PassportLocalModel var UserModel: IUserModel = model('User', UserSchema); ``` Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts) +[top](#mongoosejs-typescript-docs) #### Promises These definitions use global.Promise by default. If you would like to use mongoose's own mpromise @@ -180,6 +184,7 @@ Typescript does not allow assigning properties of imported modules): * `(mongoose).Promise = YOUR_PROMISE;` * `require('mongoose').Promise = YOUR_PROMISE;` * `import mongoose = require('mongoose'); ... mongoose.Promise = YOUR_PROMISE;` +[top](#mongoosejs-typescript-docs) #### FAQ Q: Why are there 2 interfaces for Documents called Document and MongooseDocument?
@@ -197,4 +202,5 @@ interface IUser extends mongoose.model { ``` For backwards compatibility Document is an interface for [mongoose.model](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
And MongooseDocument is an interface for [mongoose.Document](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
-At some point in the future this may get fixed, which would require fixing your code. \ No newline at end of file +At some point in the future this may get fixed, which would require fixing your code. +[top](#mongoosejs-typescript-docs) \ No newline at end of file From d2a6d1b94c791829b41605efbc98ba50a7569f1b Mon Sep 17 00:00:00 2001 From: Simon Xiong Date: Sun, 21 Aug 2016 22:42:19 -0400 Subject: [PATCH 16/68] Fix README formatting --- mongoose/README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/mongoose/README.md b/mongoose/README.md index 1d8c7083f9..411f6ace2e 100644 --- a/mongoose/README.md +++ b/mongoose/README.md @@ -149,7 +149,7 @@ interface IUserModel extends PassportLocalModel var UserModel: IUserModel = model('User', UserSchema); ``` -Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts) +Full example for [Passport Local Mongoose](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/passport-local-mongoose/passport-local-mongoose.d.ts)
[top](#mongoosejs-typescript-docs) #### Promises @@ -184,6 +184,7 @@ Typescript does not allow assigning properties of imported modules): * `(mongoose).Promise = YOUR_PROMISE;` * `require('mongoose').Promise = YOUR_PROMISE;` * `import mongoose = require('mongoose'); ... mongoose.Promise = YOUR_PROMISE;` + [top](#mongoosejs-typescript-docs) #### FAQ @@ -203,4 +204,5 @@ interface IUser extends mongoose.model { For backwards compatibility Document is an interface for [mongoose.model](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
And MongooseDocument is an interface for [mongoose.Document](https://github.com/Automattic/mongoose/blob/master/lib/model.js#L3162)
At some point in the future this may get fixed, which would require fixing your code. -[top](#mongoosejs-typescript-docs) \ No newline at end of file +
+[top](#mongoosejs-typescript-docs) From aff3e68242a9a63e2ff7592a82159c5ef4eadafc Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 22 Aug 2016 12:19:41 -0400 Subject: [PATCH 17/68] changes mongoose mpromise to be compatible with new mongoose promise implemenation fixes #10743 --- mongoose-promise/mongoose-promise-tests.ts | 20 +- mongoose-promise/mongoose-promise.d.ts | 231 ++++++++++----------- mongoose/mongoose.d.ts | 3 +- 3 files changed, 133 insertions(+), 121 deletions(-) diff --git a/mongoose-promise/mongoose-promise-tests.ts b/mongoose-promise/mongoose-promise-tests.ts index e7bda80c6d..a7908c3db5 100644 --- a/mongoose-promise/mongoose-promise-tests.ts +++ b/mongoose-promise/mongoose-promise-tests.ts @@ -1,8 +1,10 @@ /// +import * as mongoose from 'mongoose'; + var cb = function () {}; -var mongopromise: MongoosePromise; +var mongopromise: mongoose.Promise; mongopromise.addBack(function (err, arg) { err.stack; arg.toFixed(); @@ -40,7 +42,19 @@ mongopromise.then(function (arg) { }); mongopromise.complete(); /* static properties */ -MongoosePromise.ES6(function (complete, error) { +mongoose.Promise.ES6(function (complete, error) { complete.apply(this); error.apply(this); -}); \ No newline at end of file +}); +/* Practical Examples */ +interface IUser extends mongoose.Document { + name: string; + age: number; +} +var UserSchema = new mongoose.Schema({ + name: String, + age: Number +}); +var UserModel: mongoose.Model = mongoose.model('Model', UserSchema); +UserModel.findOne({}).exec().fulfill(); +UserModel.find({}).exec().then(() => {}).catch(() => {}).reject(''); \ No newline at end of file diff --git a/mongoose-promise/mongoose-promise.d.ts b/mongoose-promise/mongoose-promise.d.ts index d2622bb6f9..b5699e657e 100644 --- a/mongoose-promise/mongoose-promise.d.ts +++ b/mongoose-promise/mongoose-promise.d.ts @@ -3,126 +3,125 @@ // Definitions by: simonxca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/* - * These are the default promises included in the Mongoose v4.x - * definitions. They will be deprecated beginning Mongoose V5.x - * in favor of native ES6 Promises. - * - * You can switch the promise library that mongoose uses by: - * - * 1. Including this somewhere in your code: - * mongoose.Promise = YOUR_PROMISE; - * - * 2. Including this somewhere in your main .d.ts file: - * type MongoosePromise = YOUR_PROMISE; - */ +/// +/// /* * http://mongoosejs.com/docs/api.html#promise-js * - * Callback signatures are from the mPromise type definitions. + * mongoose.d.ts uses global.Promise by default. This is the MongooseJS + * mpromise implementation (which are deprecated). If you still want to + * use it, install these definitions in your project. */ -interface MongoosePromise { - /** - * Promise constructor. - * Promises are returned from executed queries. - * @param fn a function which will be called when the promise - * is resolved that accepts fn(err, ...){} as signature - * @event err Emits when the promise is rejected - * @event complete Emits when the promise is fulfilled - * @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native - * promises are not present) but still support plugging in your own ES6-compatible - * promises library. Mongoose 5.0 will not support mpromise. +declare module 'mongoose' { + import mpromise = require('mpromise'); + + type Promise = MongoosePromise; + + /* + * mpromise definitions. + * Callback signatures are from the mPromise type definitions. */ - new(fn?: (err: any, arg: T) => void): MongoosePromise; - new(fn?: (err: any, ...args: T[]) => void): MongoosePromise; + class MongoosePromise extends mpromise { + /** + * Promise constructor. + * Promises are returned from executed queries. + * @param fn a function which will be called when the promise + * is resolved that accepts fn(err, ...){} as signature + * @event err Emits when the promise is rejected + * @event complete Emits when the promise is fulfilled + * @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native + * promises are not present) but still support plugging in your own ES6-compatible + * promises library. Mongoose 5.0 will not support mpromise. + */ + constructor(fn?: (err: any, arg: T) => void); + constructor(fn?: (err: any, ...args: T[]) => void); + + /** + * Adds a single function as a listener to both err and complete. + * It will be executed with traditional node.js argument position when the promise is resolved. + * @deprecated Use onResolve instead. + */ + addBack(listener: (err: any, arg: T) => void): this; + addBack(listener: (err: any, ...args: T[]) => void): this; + + /** + * Adds a listener to the complete (success) event. + * @deprecated Adds a listener to the complete (success) event. + */ + addCallback(listener: (arg: T) => void): this; + addCallback(listener: (...args: T[]) => void): this; + + /** + * Adds a listener to the err (rejected) event. + * @deprecated Use onReject instead. + */ + addErrback(listener: (err: any) => void): this; + + /** ES6-style .catch() shorthand */ + catch(onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + + /** + * Signifies that this promise was the last in a chain of then()s: if a handler passed + * to the call to then which produced this promise throws, the exception will go uncaught. + */ + end(): void; + + /** + * Rejects this promise with err. + * If the promise has already been fulfilled or rejected, not action is taken. + * Differs from #reject by first casting err to an Error if it is not instanceof Error. + */ + error(err: any): this; + + /** + * Adds listener to the event. + * If event is either the success or failure event and the event has already been emitted, + * thelistener is called immediately and passed the results of the original emitted event. + */ + on(event: string, listener: Function): this; + + /** + * Rejects this promise with reason. + * If the promise has already been fulfilled or rejected, not action is taken. + */ + reject(reason: Object | string | Error): this; + + /** + * Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed. + * If the promise has already been fulfilled or rejected, not action is taken. + * err will be cast to an Error if not already instanceof Error. + * NOTE: overrides mpromise#resolve to provide error casting. + * @param err error or null + * @param val value to fulfill the promise with + */ + resolve(err?: any, val?: Object): this; + + /** + * Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as + * SUCCESS/ERROR callbacks to this promise after the nextTick. + * Conforms to promises/A+ specification. + */ + then(onFulFill: (arg: T) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + then(onFulfill: (...args: T[]) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + + /** + * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. + * @deprecated Use fulfill instead. + */ + complete(args: T): this; + complete(...args: T[]): this; + + /** Fulfills this promise with passed arguments. */ + fulfill(...args: T[]): this; + fulfill(arg: T): this; + + /** ES6-style promise constructor wrapper around mpromise. */ + static ES6(resolver: ( + complete: (...args: TRes[]) => void | TRes | PromiseLike, + error: (e: any) => void | TRes | PromiseLike + ) => void): MongoosePromise; + } } - -declare class MongoosePromise { - /** - * Adds a single function as a listener to both err and complete. - * It will be executed with traditional node.js argument position when the promise is resolved. - * @deprecated Use onResolve instead. - */ - addBack(listener: (err: any, arg: T) => void): this; - addBack(listener: (err: any, ...args: T[]) => void): this; - - /** - * Adds a listener to the complete (success) event. - * @deprecated Adds a listener to the complete (success) event. - */ - addCallback(listener: (arg: T) => void): this; - addCallback(listener: (...args: T[]) => void): this; - - /** - * Adds a listener to the err (rejected) event. - * @deprecated Use onReject instead. - */ - addErrback(listener: (err: any) => void): this; - - /** ES6-style .catch() shorthand */ - catch(onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; - - /** - * Signifies that this promise was the last in a chain of then()s: if a handler passed - * to the call to then which produced this promise throws, the exception will go uncaught. - */ - end(): void; - - /** - * Rejects this promise with err. - * If the promise has already been fulfilled or rejected, not action is taken. - * Differs from #reject by first casting err to an Error if it is not instanceof Error. - */ - error(err: any): this; - - /** - * Adds listener to the event. - * If event is either the success or failure event and the event has already been emitted, - * thelistener is called immediately and passed the results of the original emitted event. - */ - on(event: string, listener: Function): this; - - /** - * Rejects this promise with reason. - * If the promise has already been fulfilled or rejected, not action is taken. - */ - reject(reason: Object | string | Error): this; - - /** - * Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed. - * If the promise has already been fulfilled or rejected, not action is taken. - * err will be cast to an Error if not already instanceof Error. - * NOTE: overrides mpromise#resolve to provide error casting. - * @param err error or null - * @param val value to fulfill the promise with - */ - resolve(err?: any, val?: Object): this; - - /** - * Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as - * SUCCESS/ERROR callbacks to this promise after the nextTick. - * Conforms to promises/A+ specification. - */ - then(onFulFill: (arg: T) => void | TRes | PromiseLike, - onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; - then(onFulfill: (...args: T[]) => void | TRes | PromiseLike, - onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; - - /** - * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. - * @deprecated Use fulfill instead. - */ - complete(args: T): this; - complete(...args: T[]): this; - - /** Fulfills this promise with passed arguments. */ - fulfill(...args: T[]): this; - fulfill(arg: T): this; - - /** ES6-style promise constructor wrapper around mpromise. */ - static ES6(resolver: ( - complete: (...args: TRes[]) => void | TRes | PromiseLike, - error: (e: any) => void | TRes | PromiseLike - ) => void): MongoosePromise; -} \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 81247104ef..50784a9194 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// /// /* @@ -715,7 +714,7 @@ declare module "mongoose" { * section document.js * http://mongoosejs.com/docs/api.html#document-js */ - interface MongooseDocument { + class MongooseDocument { /** Checks if a path is set to its default. */ $isDefault(path?: string): boolean; From 9e897a190c6a4dce539b0736771815c2bb7982a1 Mon Sep 17 00:00:00 2001 From: Simon Date: Tue, 23 Aug 2016 15:47:11 -0400 Subject: [PATCH 18/68] adds missing model() overrides --- mongoose-paginate/mongoose-paginate.d.ts | 6 ++++++ passport-local-mongoose/passport-local-mongoose.d.ts | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/mongoose-paginate/mongoose-paginate.d.ts b/mongoose-paginate/mongoose-paginate.d.ts index c90e7550fd..ed8b07a2fa 100644 --- a/mongoose-paginate/mongoose-paginate.d.ts +++ b/mongoose-paginate/mongoose-paginate.d.ts @@ -35,6 +35,12 @@ declare module 'mongoose' { schema?: Schema, collection?: string, skipInit?: boolean): PaginateModel; + + export function model>( + name: string, + schema?: Schema, + collection?: string, + skipInit?: boolean): U; } declare module 'mongoose-paginate' { diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index acb834d85c..30319afc51 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -81,6 +81,12 @@ declare module 'mongoose' { schema?: PassportLocalSchema, collection?: string, skipInit?: boolean): PassportLocalModel; + + export function model>( + name: string, + schema?: PassportLocalSchema, + collection?: string, + skipInit?: boolean): U; } declare module 'passport-local-mongoose' { From 90d29903965a91b50866dfed61d8d164cf27a17f Mon Sep 17 00:00:00 2001 From: Simon Date: Tue, 23 Aug 2016 16:06:13 -0400 Subject: [PATCH 19/68] fixed connectionoption and .Mongoose travis errors --- mongoose/mongoose.d.ts | 9 +++++---- passport-local-mongoose/passport-local-mongoose.d.ts | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 50784a9194..89fc9073a4 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -93,6 +93,7 @@ declare module "mongoose" { export var DocumentProvider: any; // recursive constructor export var Mongoose: new(...args: any[]) => typeof mongoose; + type Mongoose = typeof mongoose; export var SchemaTypes: typeof Schema.Types; /** Expose connection states for user-land */ @@ -110,7 +111,7 @@ declare module "mongoose" { * @returns pseudo-promise wrapper around this */ export function connect(uris: string, - options?: ConnectOptions, + options?: ConnectionOptions, callback?: (err: mongodb.MongoError) => void): MongooseThenable; export function connect(uris: string, callback?: (err: mongodb.MongoError) => void): MongooseThenable; @@ -125,10 +126,10 @@ declare module "mongoose" { */ export function createConnection(): Connection; export function createConnection(uri: string, - options?: ConnectOptions + options?: ConnectionOptions ): Connection; export function createConnection(host: string, database_name: string, port?: number, - options?: ConnectOptions + options?: ConnectionOptions ): Connection; /** @@ -381,7 +382,7 @@ declare module "mongoose" { mongos?: boolean; } - interface ConnectOptions extends + interface ConnectionOptions extends ConnectionOpenOptions, ConnectionOpenSetOptions {} diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index 30319afc51..2c189afc6a 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -16,7 +16,7 @@ declare module 'mongoose' { } // statics - interface PassportLocalModel extends Model { + interface PassportLocalModel extends Model { authenticate(): (username: string, password: string, cb: (err: any, res: T, error: any) => void) => void; serializeUser(): (user: PassportLocalModel, cb: (err: any) => void) => void; deserializeUser(): (username: string, cb: (err: any) => void) => void; From 28b47d424e76cc0cfcb75d9299de97ee945da2d6 Mon Sep 17 00:00:00 2001 From: Simon Date: Tue, 23 Aug 2016 16:15:21 -0400 Subject: [PATCH 20/68] fixed travis errors for passport local mongoose and mongoose promise --- mongoose-promise/mongoose-promise-tests.ts | 2 +- passport-local-mongoose/passport-local-mongoose-tests.ts | 3 ++- passport-local-mongoose/passport-local-mongoose.d.ts | 4 ++-- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/mongoose-promise/mongoose-promise-tests.ts b/mongoose-promise/mongoose-promise-tests.ts index a7908c3db5..3970b2ac86 100644 --- a/mongoose-promise/mongoose-promise-tests.ts +++ b/mongoose-promise/mongoose-promise-tests.ts @@ -42,7 +42,7 @@ mongopromise.then(function (arg) { }); mongopromise.complete(); /* static properties */ -mongoose.Promise.ES6(function (complete, error) { +mongoose.Promise.ES6(function (complete: any, error: any) { complete.apply(this); error.apply(this); }); diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts index c7d4ffc381..dcdf08bbe3 100644 --- a/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -11,6 +11,7 @@ import { Schema, model, + Document, PassportLocalDocument, PassportLocalSchema, PassportLocalModel, @@ -77,7 +78,7 @@ options.errorMessages = errorMessages; UserSchema.plugin(passportLocalMongoose, options); -interface UserModel extends PassportLocalModel {} +interface UserModel extends PassportLocalModel {} let UserModel: UserModel = model('User', UserSchema); //#endregion diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index 2c189afc6a..ab2539a709 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -76,13 +76,13 @@ declare module 'mongoose' { ): this; } - export function model( + export function model( name: string, schema?: PassportLocalSchema, collection?: string, skipInit?: boolean): PassportLocalModel; - export function model>( + export function model>( name: string, schema?: PassportLocalSchema, collection?: string, From 51c51f03549a63f8791865bf26480947e22f4902 Mon Sep 17 00:00:00 2001 From: Simon Date: Fri, 26 Aug 2016 16:49:28 -0400 Subject: [PATCH 21/68] adds __v property to document --- mongoose/mongoose-tests.ts | 1 + mongoose/mongoose.d.ts | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 51959b9e41..5feb08b446 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1081,6 +1081,7 @@ var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({ }), 'myCollection', true); MongoModel.find({}).$where('indexOf("val") !== -1').exec(function (err, docs) { docs[0].save(); + docs[0].__v; }); MongoModel.findById(999, function (err, doc) { doc.increment(); diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 89fc9073a4..2d0046ea8c 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2332,6 +2332,12 @@ declare module "mongoose" { * @param fn optional callback */ save(fn?: (err: any, product: this, numAffected: number) => void): Promise; + + /** + * Version using default version key. See http://mongoosejs.com/docs/guide.html#versionKey + * If you're using another key, you will have to access it using []: doc[_myVersionKey] + */ + __v?: number; } interface ModelProperties { From fe8bcfd3ee0d844c935de26d5e1af233dcb98a91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Sun, 28 Aug 2016 20:51:25 -0600 Subject: [PATCH 22/68] Added typing definitions for jsoneditor project --- jsoneditor/jsoneditor-tests.ts | 50 ++++++++++++++++++++++++++++++++ jsoneditor/jsoneditor.d.ts | 52 ++++++++++++++++++++++++++++++++++ 2 files changed, 102 insertions(+) create mode 100644 jsoneditor/jsoneditor-tests.ts create mode 100644 jsoneditor/jsoneditor.d.ts diff --git a/jsoneditor/jsoneditor-tests.ts b/jsoneditor/jsoneditor-tests.ts new file mode 100644 index 0000000000..99bbb51b92 --- /dev/null +++ b/jsoneditor/jsoneditor-tests.ts @@ -0,0 +1,50 @@ +/// + +import JSONEditor, {JSONEditorMode, JSONEditorNode, JSONEditorOptions} from 'jsoneditor'; + +let options: JSONEditorOptions; +options = { + ace: ace, + //ajv: Ajv({allErrors: true, verbose: true}) + onChange() {}, + onEditable(node: JSONEditorNode) { + return true; + }, + onError(error: Error) {}, + onModeChange(newMode: JSONEditorMode, oldMode: JSONEditorMode) {}, + escapeUnicode: false, + sortObjectKeys: true, + history: true, + mode: 'tree', + modes: ['tree', 'view', 'form', 'code', 'text'], + name: 'foo', + schema: {}, + search: false, + indentation: 2, + theme: 'default' +}; +options = { + onEditable(node: JSONEditorNode) { + return {field: true, value: false}; + } +}; + +let jsonEditor: JSONEditor; +jsonEditor = new JSONEditor(document.body); +jsonEditor = new JSONEditor(document.body, {}); +jsonEditor = new JSONEditor(document.body, options, {foo: 'bar'}); + +jsonEditor.collapseAll(); +jsonEditor.destroy(); +jsonEditor.expandAll(); +jsonEditor.focus(); +jsonEditor.set({foo: 'bar'}); +jsonEditor.setMode('text'); +jsonEditor.setName('foo'); +jsonEditor.setName(); +jsonEditor.setSchema({}); +jsonEditor.setText('{foo: 1}'); + +const json: any = jsonEditor.get(); +const name: string = jsonEditor.getName(); +const jsonString: string = jsonEditor.getText(); diff --git a/jsoneditor/jsoneditor.d.ts b/jsoneditor/jsoneditor.d.ts new file mode 100644 index 0000000000..ea68a751a4 --- /dev/null +++ b/jsoneditor/jsoneditor.d.ts @@ -0,0 +1,52 @@ +// Type definitions for jsoneditor v5.5.7 +// Project: https://github.com/josdejong/jsoneditor +// Definitions by: Alejandro Sánchez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'jsoneditor' { + export interface JSONEditorNode { + field: string; + value: string; + path: Array; + } + + export type JSONEditorMode = 'tree' | 'view' | 'form' | 'code' | 'text'; + + export interface JSONEditorOptions { + ace?: AceAjax.Ace; + ajv?: any; // Any for now, since ajv typings aren't A-Ok + onChange?: () => void; + onEditable?: (node: JSONEditorNode) => boolean | {field: boolean, value: boolean}; + onError?: (error: Error) => void; + onModeChange?: (newMode: JSONEditorMode, oldMode: JSONEditorMode) => void; + escapeUnicode?: boolean; + sortObjectKeys?: boolean; + history?: boolean; + mode?: JSONEditorMode; + modes?: Array; + name?: string; + schema?: Object; + search?: boolean; + indentation?: number; + theme?: string; + } + + export default class JSONEditor { + constructor(container: HTMLElement, options?: JSONEditorOptions, json?: Object); + collapseAll(): void; + destroy(): void; + expandAll(): void; + focus(): void; + set(json: Object): void; + setMode(mode: JSONEditorMode): void; + setName(name?: string): void; + setSchema(schema: Object): void; + setText(jsonString: string): void; + get(): any; + getMode(): JSONEditorMode; + getName(): string; + getText(): string; + } +} From 64d00e4c05901b8c6214e9d4eab907667b8947d8 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Mon, 29 Aug 2016 12:45:06 +0900 Subject: [PATCH 23/68] feat: add secure: `auto` option --- express-serve-static-core/express-serve-static-core.d.ts | 8 ++++---- express-session/express-session-tests.ts | 3 ++- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index 745b0e6ab2..36b2da6c65 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -121,7 +121,7 @@ declare module "express-serve-static-core" { httpOnly?: boolean; path?: string; domain?: string; - secure?: boolean; + secure?: boolean | 'auto'; } interface Errback { (err: Error): void; } @@ -199,7 +199,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted charset of the specified character sets, - * based on the request’s Accept-Charset HTTP header field. + * based on the request窶冱 Accept-Charset HTTP header field. * If none of the specified charsets is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. @@ -212,7 +212,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted encoding of the specified encodings, - * based on the request’s Accept-Encoding HTTP header field. + * based on the request窶冱 Accept-Encoding HTTP header field. * If none of the specified encodings is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. @@ -225,7 +225,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted language of the specified languages, - * based on the request’s Accept-Language HTTP header field. + * based on the request窶冱 Accept-Language HTTP header field. * If none of the specified languages is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. diff --git a/express-session/express-session-tests.ts b/express-session/express-session-tests.ts index 1e1f909b14..0b8460214f 100644 --- a/express-session/express-session-tests.ts +++ b/express-session/express-session-tests.ts @@ -6,7 +6,8 @@ import session = require('express-session'); var app = express(); app.use(session({ - secret: 'keyboard cat' + secret: 'keyboard cat', + cookie: { secure: 'auto' } })); app.use(session({ secret: 'keyboard cat', From ff4757f0c652ebcdc5b717bc7787fcc955aac2d5 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Mon, 29 Aug 2016 12:48:35 +0900 Subject: [PATCH 24/68] fix: character convert bug --- express-serve-static-core/express-serve-static-core.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index 36b2da6c65..93551ffece 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -199,7 +199,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted charset of the specified character sets, - * based on the request窶冱 Accept-Charset HTTP header field. + * based on the request's Accept-Charset HTTP header field. * If none of the specified charsets is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. @@ -212,7 +212,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted encoding of the specified encodings, - * based on the request窶冱 Accept-Encoding HTTP header field. + * based on the request's Accept-Encoding HTTP header field. * If none of the specified encodings is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. @@ -225,7 +225,7 @@ declare module "express-serve-static-core" { /** * Returns the first accepted language of the specified languages, - * based on the request窶冱 Accept-Language HTTP header field. + * based on the request's Accept-Language HTTP header field. * If none of the specified languages is accepted, returns false. * * For more information, or if you have issues or concerns, see accepts. From a668601585aa895decb0daf6934f8f3314c18919 Mon Sep 17 00:00:00 2001 From: Cleison Stein Date: Mon, 29 Aug 2016 11:06:31 +0100 Subject: [PATCH 25/68] added moment type for goToDate https://fullcalendar.io/docs/current_date/gotoDate/ --- fullCalendar/fullCalendar.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts index 65df012185..1e3efd1958 100644 --- a/fullCalendar/fullCalendar.d.ts +++ b/fullCalendar/fullCalendar.d.ts @@ -318,7 +318,7 @@ interface JQuery { /** * Moves the calendar to an arbitrary date. */ - fullCalendar(method: 'gotoDate', date: Date | string): void; + fullCalendar(method: 'gotoDate', moment.Moment | Date | string): void; /** * Moves the calendar forward/backward an arbitrary amount of time. @@ -403,4 +403,4 @@ interface JQuery { interface JQueryStatic { fullCalendar: FullCalendar.Calendar; -} \ No newline at end of file +} From 1a4347bf2a28540505162f4e654c15408e446460 Mon Sep 17 00:00:00 2001 From: Brice Theurillat Date: Mon, 29 Aug 2016 13:18:10 +0200 Subject: [PATCH 26/68] Adding definitions for the "pathfinding" package --- pathfinding/pathfinding-test.ts | 17 ++++ pathfinding/pathfinding.d.ts | 167 ++++++++++++++++++++++++++++++++ 2 files changed, 184 insertions(+) create mode 100644 pathfinding/pathfinding-test.ts create mode 100644 pathfinding/pathfinding.d.ts diff --git a/pathfinding/pathfinding-test.ts b/pathfinding/pathfinding-test.ts new file mode 100644 index 0000000000..7244302fc4 --- /dev/null +++ b/pathfinding/pathfinding-test.ts @@ -0,0 +1,17 @@ +/// + +import * as PF from "pathfinding"; + +var matrix = [ + [0, 0, 0, 1, 0], + [1, 0, 0, 0, 1], + [0, 0, 1, 0, 0], +]; +var grid = new PF.Grid(matrix); +var gridBackup = grid.clone(); + +var finder = new PF.AStarFinder(); + +var path = finder.findPath(1, 2, 4, 2, grid); + +var newPath = PF.Util.smoothenPath(grid, path); \ No newline at end of file diff --git a/pathfinding/pathfinding.d.ts b/pathfinding/pathfinding.d.ts new file mode 100644 index 0000000000..44ddee3077 --- /dev/null +++ b/pathfinding/pathfinding.d.ts @@ -0,0 +1,167 @@ +declare module "pathfinding" { + namespace Pathfinding { + export namespace Heuristic { + function manhattan(dx: number, dy: number): number; + function euclidean(dx: number, dy: number): number; + function octile(dx: number, dy: number): number; + function chebyshev(dx: number, dy: number): number; + } + + export namespace Util { + function smoothenPath(grid: Grid, path: number[][]): number[][]; + function compressPath(path: number[][]): number[][]; + function expandPath(path: number[][]): number[][]; + } + + export enum DiagonalMovement { + Always = 1, + Never = 2, + IfAtMostOneObstacle = 3, + OnlyWhenNoObstacle = 4 + } + + interface Node { + x: number; + y: number; + walkable: boolean; + } + + interface Heuristic { + heuristic?: (dx: number, dy: number) => number; + } + + interface FinderOptions extends Heuristic { + diagonalMovement?: DiagonalMovement; + weight?: number; + } + + interface IDAStarFinderOptions extends FinderOptions { + trackRecursion?: boolean; + timeLimit?: number; + } + + interface JumpPointFinderBaseOptions extends Heuristic { + trackJumpRecursion?: boolean; + } + + interface JumpPointFinderOptions extends Heuristic { + diagonalMovement?: DiagonalMovement; + } + + interface BiBreadthFirstFinderOptions { + diagonalMovement?: DiagonalMovement; + } + + interface Grid { + new (width: number, height: number): Grid; + new (matrix: number[][]): Grid; + + setWalkableAt(x: number, y: number, walkable: boolean): void; + + clone(): Grid; + + getNodeAt(): Pathfinding.Node; + getNeighbors(node: Pathfinding.Node, diagonalMovement: DiagonalMovement): Pathfinding.Node[]; + isWalkableAt(x: number, y: number): boolean; + isInside(x: number, y: number): boolean; + + width: number; + height: number; + } + + interface Finder { + findPath(startX: number, startY: number, endX: number, endY: number, matrix: Grid): number[][]; + } + + interface AStarFinder extends Finder { + new (): AStarFinder; + new (opt: FinderOptions): AStarFinder; + } + + interface BestFirstFinder extends AStarFinder { + new (): BestFirstFinder; + new (opt: JumpPointFinderOptions): BestFirstFinder; + } + + interface BiAStarFinder extends Finder { + new (): BiAStarFinder; + new (opt: JumpPointFinderOptions): BiAStarFinder; + } + + interface BiBestFirstFinder extends BiAStarFinder { + new (): BiBestFirstFinder; + new (opt: JumpPointFinderOptions): BiBestFirstFinder; + } + + interface BiBreadthFirstFinder extends Finder { + new (): BiBreadthFirstFinder; + new (opt: BiBreadthFirstFinderOptions): BiBreadthFirstFinder; + } + + interface BiDijkstraFinder extends BiAStarFinder { + new (): BiDijkstraFinder; + new (opt: BiBreadthFirstFinderOptions): BiDijkstraFinder; + } + + interface BreadthFirstFinder extends Finder { + new (): BreadthFirstFinder; + new (opt: BiBreadthFirstFinderOptions): BreadthFirstFinder; + } + + interface DijkstraFinder extends AStarFinder { + new (): DijkstraFinder; + new (opt: BiBreadthFirstFinderOptions): DijkstraFinder; + } + + interface IDAStarFinder extends Finder { + new (): IDAStarFinder; + new (opt: IDAStarFinderOptions): IDAStarFinder; + } + + interface JumpPointFinderBase extends Finder { + new (): JumpPointFinderBase; + new (opt: JumpPointFinderBaseOptions): JumpPointFinderBase; + } + + interface JPFAlwaysMoveDiagonally extends JumpPointFinderBase { + new (): JPFAlwaysMoveDiagonally; + new (opt: JumpPointFinderBaseOptions): JPFAlwaysMoveDiagonally; + } + + interface JPFMoveDiagonallyIfAtMostOneObstacle extends JumpPointFinderBase { + new (): JPFMoveDiagonallyIfAtMostOneObstacle; + new (opt: JumpPointFinderBaseOptions): JPFMoveDiagonallyIfAtMostOneObstacle; + } + + interface JPFMoveDiagonallyIfNoObstacles extends JumpPointFinderBase { + new (): JPFMoveDiagonallyIfNoObstacles; + new (opt: JumpPointFinderBaseOptions): JPFMoveDiagonallyIfNoObstacles; + } + + interface JPFNeverMoveDiagonally extends JumpPointFinderBase { + new (): JPFNeverMoveDiagonally; + new (opt: JumpPointFinderBaseOptions): JPFNeverMoveDiagonally; + } + + interface JumpPointFinder { + (opt: JumpPointFinderOptions): JPFNeverMoveDiagonally | JPFAlwaysMoveDiagonally | JPFMoveDiagonallyIfNoObstacles | JPFMoveDiagonallyIfAtMostOneObstacle; + } + + export var Grid: Grid; + export var AStarFinder: AStarFinder; + export var BestFirstFinder: BestFirstFinder; + export var BiAStarFinder: BiAStarFinder; + export var BiBestFirstFinder: BiBestFirstFinder; + export var BiBreadthFirstFinder: BiBreadthFirstFinder; + export var BiDijkstraFinder: BiDijkstraFinder; + export var BreadthFirstFinder: BreadthFirstFinder; + export var DijkstraFinder: DijkstraFinder; + export var IDAStarFinder: IDAStarFinder; + export var JPFAlwaysMoveDiagonally: JPFAlwaysMoveDiagonally; + export var JPFMoveDiagonallyIfAtMostOneObstacle: JPFMoveDiagonallyIfAtMostOneObstacle; + export var JPFMoveDiagonallyIfNoObstacles: JPFMoveDiagonallyIfNoObstacles; + export var JPFNeverMoveDiagonally: JPFNeverMoveDiagonally; + export var JumpPointFinder: JumpPointFinder; + } + export = Pathfinding; +} \ No newline at end of file From 1d307c2581cd7428f75df90bd8237fd6235dedcf Mon Sep 17 00:00:00 2001 From: Brice Theurillat Date: Mon, 29 Aug 2016 13:21:23 +0200 Subject: [PATCH 27/68] Rename pathfinding tests file --- pathfinding/{pathfinding-test.ts => pathfinding-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename pathfinding/{pathfinding-test.ts => pathfinding-tests.ts} (100%) diff --git a/pathfinding/pathfinding-test.ts b/pathfinding/pathfinding-tests.ts similarity index 100% rename from pathfinding/pathfinding-test.ts rename to pathfinding/pathfinding-tests.ts From 0c9f62f58db0285e290e72dfcd392a7b56610619 Mon Sep 17 00:00:00 2001 From: Brice Theurillat Date: Mon, 29 Aug 2016 13:28:16 +0200 Subject: [PATCH 28/68] Add missing file header --- pathfinding/pathfinding.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pathfinding/pathfinding.d.ts b/pathfinding/pathfinding.d.ts index 44ddee3077..b7dd8041b1 100644 --- a/pathfinding/pathfinding.d.ts +++ b/pathfinding/pathfinding.d.ts @@ -1,3 +1,8 @@ +// Type definitions for pathfinding +// Project: https://github.com/qiao/PathFinding.js +// Definitions by: BNedry +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + declare module "pathfinding" { namespace Pathfinding { export namespace Heuristic { From 168f6b9d6a2d86ad5ff622374b394612555bb7af Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Mon, 29 Aug 2016 15:09:54 +0300 Subject: [PATCH 29/68] String is a valid storage destination option --- multer/multer.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/multer/multer.d.ts b/multer/multer.d.ts index d9abb4a87c..e6fd601ed2 100644 --- a/multer/multer.d.ts +++ b/multer/multer.d.ts @@ -81,7 +81,7 @@ declare module "multer" { interface DiskStorageOptions { /** A function used to determine within which folder the uploaded files should be stored. Defaults to the system's default temporary directory. */ - destination?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void; + destination?: string | ((req: Express.Request, file: Express.Multer.File, callback: (error: Error, destination: string) => void) => void); /** A function used to determine what the file should be named inside the folder. Defaults to a random name with no file extension. */ filename?: (req: Express.Request, file: Express.Multer.File, callback: (error: Error, filename: string) => void) => void; } From 327d35fb7a24c60b4f829a3902a37d2e582269c9 Mon Sep 17 00:00:00 2001 From: Clay Miller Date: Mon, 29 Aug 2016 12:10:40 -0700 Subject: [PATCH 30/68] Remove icon from React.HTMLAttributes (fixes #10467) --- react/react.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/react/react.d.ts b/react/react.d.ts index 788255034d..5178ad28a6 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -1968,7 +1968,6 @@ declare namespace __React { hrefLang?: string; htmlFor?: string; httpEquiv?: string; - icon?: string; id?: string; inputMode?: string; integrity?: string; From ef946711a315a6f5527a3bda25618645d91de9e3 Mon Sep 17 00:00:00 2001 From: Cleison Stein Date: Tue, 30 Aug 2016 09:49:27 +0100 Subject: [PATCH 31/68] variable name fixed --- fullCalendar/fullCalendar.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fullCalendar/fullCalendar.d.ts b/fullCalendar/fullCalendar.d.ts index 1e3efd1958..fd43e51c5f 100644 --- a/fullCalendar/fullCalendar.d.ts +++ b/fullCalendar/fullCalendar.d.ts @@ -318,7 +318,7 @@ interface JQuery { /** * Moves the calendar to an arbitrary date. */ - fullCalendar(method: 'gotoDate', moment.Moment | Date | string): void; + fullCalendar(method: 'gotoDate', date: moment.Moment | Date | string): void; /** * Moves the calendar forward/backward an arbitrary amount of time. From 37c50a8e4b176dc2663691d43be6081e349723fe Mon Sep 17 00:00:00 2001 From: Viktor Hedefalk Date: Tue, 30 Aug 2016 12:37:23 +0200 Subject: [PATCH 32/68] Fixes #10904 adds optional protocols params to client constructor --- ws/ws.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ws/ws.d.ts b/ws/ws.d.ts index 6b94bee19d..af0bb9a4ad 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -34,7 +34,7 @@ declare module "ws" { onclose: (event: {wasClean: boolean; code: number; reason: string; target: WebSocket}) => void; onmessage: (event: {data: any; type: string; target: WebSocket}) => void; - constructor(address: string, options?: { + constructor(address: string, protocols?: string | string[], options?: { protocol?: string; agent?: http.Agent; headers?: {[key: string]: string}; From 356293a4ae7ea3eced90e4e6de89102d4310251c Mon Sep 17 00:00:00 2001 From: Luca Laissue Date: Tue, 30 Aug 2016 13:26:32 +0200 Subject: [PATCH 33/68] update for 2.0.1 --- riot-api-nodejs/riot-api-nodejs-tests.ts | 2 +- riot-api-nodejs/riot-api-nodejs.d.ts | 197 +++++++++++------------ 2 files changed, 99 insertions(+), 100 deletions(-) diff --git a/riot-api-nodejs/riot-api-nodejs-tests.ts b/riot-api-nodejs/riot-api-nodejs-tests.ts index a531f52ee0..6b571d7618 100644 --- a/riot-api-nodejs/riot-api-nodejs-tests.ts +++ b/riot-api-nodejs/riot-api-nodejs-tests.ts @@ -3,4 +3,4 @@ import * as Api from "riot-api-nodejs"; let ClassicApi = new Api.ClassicAPI([""], Api.region_e.EUW); -let TournamentApi = new Api.TournamentAPI(""); +let TournamentApi = new Api.TournamentAPI(""); \ No newline at end of file diff --git a/riot-api-nodejs/riot-api-nodejs.d.ts b/riot-api-nodejs/riot-api-nodejs.d.ts index cb4c88766a..f4900a508f 100644 --- a/riot-api-nodejs/riot-api-nodejs.d.ts +++ b/riot-api-nodejs/riot-api-nodejs.d.ts @@ -3,11 +3,18 @@ // Definitions by: Luca Laissue // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// /// +/// -declare module "riot-api-nodejs"{ +declare module "riot-api-nodejs" { + export const BASE_URL: string; + export const URL_1_2: string; + export const URL_1_3: string; + export const URL_1_4: string; + export const URL_2_2: string; + export const URL_2_4: string; + export const URL_2_5: string; export enum region_e { BR = 0, EUNE = 1, @@ -22,72 +29,84 @@ declare module "riot-api-nodejs"{ PBE = 10, } /** - * Tournament API - */ - export class TournamentAPI { + * Base API + */ + export class API { private ApiKeys; private ApiKey; + constructor(ApiKeys: string[]); /** - * TournamentAPI Constructor - */ - constructor(...ApiKeys: string[]); - /** - * Change the Api Key for the next requests - */ + * Change the Api Key for the next requests + */ private switchApiKey(); /** - * Send a request to the Riot Games Api and return a formatted json via a callback - * @param {string} url request url - * @param {string} method method(post / put / get) - * @param {[type]} data body parameters - * @param {(JSON} callback callback function with formatted JSON - */ - private getJSON(url, method, data, callback); + * Send a request to the Riot Games Api and return a formatted json via a callback + * @param {string} url request url + * @param {string} method method(post / put / get) + * @param {[type]} data body parameters + * @param {(JSON} callback callback function with formatted JSON + */ + getJSON(url: string, method: string, data: any): Promise; + request(url: string, method: string, data: any, prop?: string): Promise; /** - * get tournament Codes for a given tournament + * get the API Key that is used for the requests + * @return {string} the current API Key + */ + getCurrentApiKey(): string; + /** + * set the API Keys + * @param {string[]} ApiKeys the API Keys + */ + setApikeys(ApiKeys: string[]): void; + } + /** + * Tournament API + */ + export class TournamentAPI extends API { + constructor(...apiKeys: string[]); + /** + * create tournament Codes for a given tournament * @param {number} tournamentId the ID of the tournament * @param {number} count Number of codes you want * @param {RiotGamesAPI.TournamentProvider.TournamentCodeParameters} params Tournament Code parameters * @param {number[]} callback Tournaments Codes [description] */ - getTournamentCodes(tournamentId: number, count: number, params: RiotGamesAPI.TournamentProvider.TournamentCodeParameters, callback: (tournamentCodes: number[]) => void): any; + createTournamentCodes(tournamentId: number, count: number, params: RiotGamesAPI.TournamentProvider.TournamentCodeParameters): Promise; /** * get tournament infos for a given tournament code * @param {string} tournamentCode Tournament Code * @param {RiotGamesAPI.TournamentProvider.TournamentCodeDto} callback Tournament Infos */ - getTournamentByCode(tournamentCode: string, callback: (tournament: RiotGamesAPI.TournamentProvider.TournamentCodeDto) => void): any; + getTournamentByCode(tournamentCode: string): Promise; /** * edit the tournament Code parameters for a given tournament Code * @param {string} tournamentCode Tournament Code to update * @param {RiotGamesAPI.TournamentProvider.TournamentCodeUpdateParameters} params parameters to edit * @param {(} callback callback if succes */ - editTournamentByCode(tournamentCode: string, params: RiotGamesAPI.TournamentProvider.TournamentCodeUpdateParameters, callback: () => void): any; + editTournamentByCode(tournamentCode: string, params: RiotGamesAPI.TournamentProvider.TournamentCodeUpdateParameters): Promise<() => void>; /** * get the lobby envents for a given tournament Code * @param {string} tournamentCode the tournament code to get the lobby events * @param {RiotGamesAPI.TournamentProvider.LobbyEventDto} callback lobby events */ - getLobbyEventByCode(tournamentCode: string, callback: (lobbyEventDto: RiotGamesAPI.TournamentProvider.LobbyEventDto) => void): any; + getLobbyEventByCode(tournamentCode: string): Promise; /** * Register a new tournament provider * @param {region_e} region region where you want to register the provider * @param {string} url url of callback for the POST notifications * @param {number} callback returns the tounament provider ID */ - registerProvider(region: region_e, url: string, callback: (providerId: number) => void): any; + registerProvider(region: region_e, url: string): Promise; /** * Register a new tournament * @param {string} name Name of tournament * @param {number} providerId Provider ID * @param {number} callback returns the tournament ID */ - registerTournament(name: string, providerId: number, callback: (tournamentId: number) => void): any; + registerTournament(name: string, providerId: number): Promise; } - export class ClassicAPI { - private ApiKeys; - private ApiKey; + export class ClassicAPI extends API { private region; /** * ClassicAPI Constructor @@ -95,37 +114,17 @@ declare module "riot-api-nodejs"{ * @param {region_e} region region where you want to send requests */ constructor(ApiKeys: string[], region: region_e); - /** - * change the API Key for the next requests - */ - private switchApiKey(); - /** - * get the JSON response code for a given URL - * @param {string} url Request url - * @param {Function} callback JSON formatted data - */ - private getJSON(url, callback); /** * Edit the consts for a valid url for the riot games api * @param {string} unparsedURL the URL to parse * @return {string} the Parsed URL */ - private parseURL(unparsedURL); - /** - * get the API Key that is used for the requests - * @return {string} the current API Key - */ - getCurrentApiKey(): string; + parseURL(unparsedURL: string): string; /** * get the region where send send request * @return {region_e} the current region */ getRegion(): region_e; - /** - * set the API Keys - * @param {string[]} ApiKeys the API Keys - */ - setApikeys(ApiKeys: string[]): void; /** * set the region where you want to send requests * @param {region_e} region the region @@ -135,278 +134,278 @@ declare module "riot-api-nodejs"{ * get all champions of league of legends * @param {RiotGamesAPI.Champion.ChampionListDto} callback data callback */ - getChampions(callback: (championListDto: RiotGamesAPI.Champion.ChampionListDto) => void): any; + getChampions(): Promise; /** * get the champion for a given id * @param {number} id the champion id * @param {RiotGamesAPI.Champion.ChampionDto} callback data callback */ - getChampionById(id: number, callback: (ChampionDto: RiotGamesAPI.Champion.ChampionDto) => void): any; + getChampionById(id: number): Promise; /** * get the free to play champions * @param {RiotGamesAPI.Champion.ChampionListDto} callback data callback */ - getFreeToPlayChampions(callback: (championsListDto: RiotGamesAPI.Champion.ChampionListDto) => void): any; + getFreeToPlayChampions(): Promise; /** * get Champion mastery of a player for a given champion ID * @param {number} summonerId summoner ID * @param {number} championId Champion ID * @param {RiotGamesAPI.ChampionMastery.ChampionMasteryDto} callback data callback */ - getChampionMastery(summonerId: number, championId: number, callback: (championMastery: RiotGamesAPI.ChampionMastery.ChampionMasteryDto) => void): any; + getChampionMastery(summonerId: number, championId: number): Promise; /** * get all champion masteries for a given summoner * @param {number} summonerId Summoner ID * @param {[RiotGamesAPI.ChampionMastery.ChampionMasteryDto]} callback data callback */ - getChampionMasteryBySummoner(summonerId: number, callback: (championsMastery: [RiotGamesAPI.ChampionMastery.ChampionMasteryDto]) => void): any; + getChampionMasteryBySummoner(summonerId: number): Promise<[RiotGamesAPI.ChampionMastery.ChampionMasteryDto]>; /** * get the mastery score of a summoner * @param {number} summonerId Summoner ID * @param {number} callback Mastery Score */ - getChampionMasteryScore(summonerId: number, callback: (score: number) => void): any; + getChampionMasteryScore(summonerId: number): Promise; /** * get The 3 best champion masteries * @param {[type]} summonerId Summoner ID * @param {[RiotGamesAPI.ChampionMastery.ChampionMasteryDto]} callback data callback */ - getTopChampionMastery(summonerId: any, callback: (championsMastery: [RiotGamesAPI.ChampionMastery.ChampionMasteryDto]) => void): any; + getTopChampionMastery(summonerId: any): Promise<[RiotGamesAPI.ChampionMastery.ChampionMasteryDto]>; /** * get the current game infos for a given summoner ID * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.CurrentGame.CurrentGameInfo} callback data callback */ - getCurrentGame(summonerId: number, callback: (gameInfoDto: RiotGamesAPI.CurrentGame.CurrentGameInfo) => void): any; + getCurrentGame(summonerId: number): Promise; /** * get the featured games * @param {RiotGamesAPI.FeaturedGames.FeaturedGames} callback data callback */ - getFeaturedGame(callback: (featuredGamesInfos: RiotGamesAPI.FeaturedGames.FeaturedGames) => void): any; + getFeaturedGame(): Promise; /** * get the recents games for a given Summoner ID * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.Game.RecentGamesDto} callback data callback */ - getRecentGames(summonerId: number, callback: (RecentGamesDto: RiotGamesAPI.Game.RecentGamesDto) => void): any; + getRecentGames(summonerId: number): Promise; /** * Get League infos of a summoner * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.League.LeagueDto[]} callback data callback */ - getLeagueBySummonerId(summonerId: number, callback: (LeagueDto: RiotGamesAPI.League.LeagueDto[]) => void): any; + getLeagueBySummonerId(summonerId: number): Promise; /** * get League infos of a summoner * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.League.LeagueDto[]} callback data callback */ - getLeagueBySummonerIdEntry(summonerId: number, callback: (LeagueDto: RiotGamesAPI.League.LeagueDto[]) => void): any; + getLeagueBySummonerIdEntry(summonerId: number): Promise; /** * get league infos by team * @param {string} teamId Team ID * @param {RiotGamesAPI.League.LeagueDto[]} callback data callback */ - getLeagueByTeamId(teamId: string, callback: (LeagueDto: RiotGamesAPI.League.LeagueDto[]) => void): any; + getLeagueByTeamId(teamId: string): Promise; /** * get league infos by team * @param {string} teamId Team ID * @param {RiotGamesAPI.League.LeagueDto[]} callback data callback */ - getLeagueByTeamIdEntry(teamId: string, callback: (LeagueDto: RiotGamesAPI.League.LeagueDto[]) => void): any; + getLeagueByTeamIdEntry(teamId: string): Promise; /** * get Challengers in SOLO Queue * @param {RiotGamesAPI.League.LeagueDto} callback data callback */ - getChallengers_SOLO(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any; + getChallengers_SOLO(): Promise; /** * get Challengers Teams in 3x3 * @param {RiotGamesAPI.League.LeagueDto} callback data callback */ - getChallengers_3x3(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any; + getChallengers_3x3(): Promise; /** * get Challengers Teams in 5x5 * @param {RiotGamesAPI.League.LeagueDto} callback data callback */ - getChallengers_5x5(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any; + getChallengers_5x5(): Promise; /** * get Masters in Solo Queue * @param {RiotGamesAPI.League.LeagueDto} callback data callback */ - getMasters_SOLO(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any; + getMasters_SOLO(): Promise; /** * get Master Teams in 3x3 * @param {RiotGamesAPI.League.LeagueDto} callback data callback */ - getMasters_3x3(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any; + getMasters_3x3(): Promise; /** * get Master Teams in 5x5 * @param {RiotGamesAPI.League.LeagueDto} callback data callback */ - getMasters_5x5(callback: (League: RiotGamesAPI.League.LeagueDto) => void): any; + getMasters_5x5(): Promise; /** * get Champions (static data) * @param {RiotGamesAPI.LolStaticData.ChampionListDto} callback data callback */ - staticDataChampions(callback: (championListDto: RiotGamesAPI.LolStaticData.ChampionListDto) => void): any; + staticDataChampions(): Promise; /** * get data by champion ID * @param {number} championsId Champion ID * @param {RiotGamesAPI.LolStaticData.ChampionDto} callback data callback */ - staticDataChampionById(championsId: number, callback: (championDto: RiotGamesAPI.LolStaticData.ChampionDto) => void): any; + staticDataChampionById(championsId: number): Promise; /** * get League of Legends Items * @param {RiotGamesAPI.LolStaticData.ItemListDto} callback data callback */ - staticDataItems(callback: (itemsDto: RiotGamesAPI.LolStaticData.ItemListDto) => void): any; + staticDataItems(): Promise; /** * Get item infos by ID * @param {number} itemId item ID * @param {RiotGamesAPI.LolStaticData.ItemDto} callback data callback */ - staticDataItemById(itemId: number, callback: (itemDto: RiotGamesAPI.LolStaticData.ItemDto) => void): any; + staticDataItemById(itemId: number): Promise; /** * get league of legends languages * @param {RiotGamesAPI.LolStaticData.LanguageStringsDto} callback data callback */ - staticDataLanguagesStrings(callback: (languageStringsDto: RiotGamesAPI.LolStaticData.LanguageStringsDto) => void): any; + staticDataLanguagesStrings(): Promise; /** * get league of legends languages * @param {string[]} callback data callback */ - staticDataLanguages(callback: (languages: string[]) => void): any; + staticDataLanguages(): Promise; /** * get Map data * @param {RiotGamesAPI.LolStaticData.MapDataDto} callback data callback */ - staticDataMap(callback: (mapDataDto: RiotGamesAPI.LolStaticData.MapDataDto) => void): any; + staticDataMap(): Promise; /** * get all masteries * @param {RiotGamesAPI.LolStaticData.MasteryListDto} callback data callback */ - staticDataMastery(callback: (masteryListDto: RiotGamesAPI.LolStaticData.MasteryListDto) => void): any; + staticDataMastery(): Promise; /** * get data by mastery ID * @param {number} masteryId Mastery ID * @param {RiotGamesAPI.LolStaticData.MasteryDto} callback data callback */ - staticDataMasteryById(masteryId: number, callback: (masteryDto: RiotGamesAPI.LolStaticData.MasteryDto) => void): any; - staticDataRealm(callback: (realmDto: RiotGamesAPI.LolStaticData.RealmDto) => void): any; + staticDataMasteryById(masteryId: number): Promise; + staticDataRealm(): Promise; /** * get all runes * @param {RiotGamesAPI.LolStaticData.RuneListDto} callback data callback */ - staticDataRunes(callback: (runeListDto: RiotGamesAPI.LolStaticData.RuneListDto) => void): any; + staticDataRunes(): Promise; /** * get rune by Rune ID * @param {number} runeId Rune ID * @param {RiotGamesAPI.LolStaticData.RuneDto} callback data callback */ - staticDataRuneById(runeId: number, callback: (runeDto: RiotGamesAPI.LolStaticData.RuneDto) => void): any; + staticDataRuneById(runeId: number): Promise; /** * get all summoner spells * @param {RiotGamesAPI.LolStaticData.SummonerSpellListDto} callback data callback */ - staticDataSummonerSpells(callback: (summonerSpellListDto: RiotGamesAPI.LolStaticData.SummonerSpellListDto) => void): any; + staticDataSummonerSpells(): Promise; /** * get summoner spell by summoner spell ID * @param {number} summonerSpellId Summoner spell ID * @param {RiotGamesAPI.LolStaticData.SummonerSpellDto} callback data callback */ - staticDataSummonSpellById(summonerSpellId: number, callback: (runeDto: RiotGamesAPI.LolStaticData.SummonerSpellDto) => void): any; + staticDataSummonSpellById(summonerSpellId: number): Promise; /** * get league of legends versions * @param {string[]} callback data callback */ - staticDataVersion(callback: (versions: string[]) => void): any; + staticDataVersion(): Promise; /** * get league of legends status * @param {RiotGamesAPI.LolStatus.Shard[]} callback data callback */ - getSatus(callback: (shardList: RiotGamesAPI.LolStatus.Shard[]) => void): any; + getSatus(): Promise; /** * get status for a given region * @param {region_e} region region * @param {RiotGamesAPI.LolStatus.Shard} callback data callback */ - getSatusByRegion(region: region_e, callback: (shard: RiotGamesAPI.LolStatus.Shard) => void): any; + getSatusByRegion(region: region_e): Promise; /** * get match infos for a given match ID * @param {number} matchId Match ID * @param {RiotGamesAPI.Match.MatchDetail} callback data callback */ - getMatch(matchId: number, callback: (matchDetails: RiotGamesAPI.Match.MatchDetail) => void): any; + getMatch(matchId: number): Promise; /** * get all matches for a given tournament code * @param {string} tournamentCode Tournament Code * @param {number[]} callback data callback */ - getMatchIdsByTournamentCode(tournamentCode: string, callback: (matchIds: number[]) => void): any; + getMatchIdsByTournamentCode(tournamentCode: string): Promise; /** * get match by ID in a tournament * @param {number} matchId Match ID * @param {RiotGamesAPI.Match.MatchDetail} callback data callback */ - getMatchForTournament(matchId: number, callback: (matchDetails: RiotGamesAPI.Match.MatchDetail) => void): any; + getMatchForTournament(matchId: number): Promise; /** * get match list of a summoner * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.MatchList.MatchList} callback data callback */ - getMatchList(summonerId: number, callback: (matchList: RiotGamesAPI.MatchList.MatchList) => void): any; + getMatchList(summonerId: number): Promise; /** * get ranked stats of summoner * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.Stats.RankedStatsDto} callback data callback */ - getStatsRanked(summonerId: number, callback: (rankedStatsDto: RiotGamesAPI.Stats.RankedStatsDto) => void): any; + getStatsRanked(summonerId: number): Promise; /** * get summary ranked stats of summoner * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.Stats.PlayerStatsSummaryListDto} callback data callback */ - getStatsSummary(summonerId: number, callback: (playerStatsSummaryListDto: RiotGamesAPI.Stats.PlayerStatsSummaryListDto) => void): any; + getStatsSummary(summonerId: number): Promise; /** * get summoner infos by Summoner Name * @param {string} summonerName Summoner Name * @param {RiotGamesAPI.Summoner.SummonerDto} callback data callback */ - getSummonerByName(summonerName: string, callback: (summonerDto: RiotGamesAPI.Summoner.SummonerDto) => void): any; + getSummonerByName(summonerName: string): Promise; /** * get summoner infos by summoner ID * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.Summoner.SummonerDto} callback data callback */ - getSummonerById(summonerId: number, callback: (summonerDto: RiotGamesAPI.Summoner.SummonerDto) => void): any; + getSummonerById(summonerId: number): Promise; /** * get masteries of a summoner * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.Summoner.MasteryPagesDto} callback data callback */ - getSummonerMasteries(summonerId: number, callback: (masteryPagesDto: RiotGamesAPI.Summoner.MasteryPagesDto) => void): any; + getSummonerMasteries(summonerId: number): Promise; /** * get the Summoner Name of a summoner ID * @param {number} summonerId Summoner ID * @param {string} callback data callback */ - getSummonerName(summonerId: number, callback: (summonerName: string) => void): any; + getSummonerName(summonerId: number): Promise; /** * get the runes of a summoner * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.Summoner.RunePagesDto} callback data callback */ - getSummonerRunes(summonerId: number, callback: (runePagesDto: RiotGamesAPI.Summoner.RunePagesDto) => void): any; + getSummonerRunes(summonerId: number): Promise; /** * get teams of a summoner * @param {number} summonerId Summoner ID * @param {RiotGamesAPI.Team.TeamDto[]} callback data callback */ - getTeamsBySummoner(summonerId: number, callback: (teamsList: RiotGamesAPI.Team.TeamDto[]) => void): any; + getTeamsBySummoner(summonerId: number): Promise; /** * get Team infos by Team ID * @param {string} teamId Team ID * @param {RiotGamesAPI.Team.TeamDto} callback data callback */ - getTeamById(teamId: string, callback: (teamDto: RiotGamesAPI.Team.TeamDto) => void): any; + getTeamById(teamId: string): Promise; } } From 8924d7c8a45cc619bf71ccd3eb4c01b7980e94ad Mon Sep 17 00:00:00 2001 From: Luca Laissue Date: Tue, 30 Aug 2016 13:43:24 +0200 Subject: [PATCH 34/68] remove useless lib --- riot-api-nodejs/riot-api-nodejs.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/riot-api-nodejs/riot-api-nodejs.d.ts b/riot-api-nodejs/riot-api-nodejs.d.ts index f4900a508f..05fb20e81f 100644 --- a/riot-api-nodejs/riot-api-nodejs.d.ts +++ b/riot-api-nodejs/riot-api-nodejs.d.ts @@ -4,7 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// declare module "riot-api-nodejs" { From c9848c3240ef78a222564e4cde3c0e3878724142 Mon Sep 17 00:00:00 2001 From: Pedro Pereira Date: Tue, 30 Aug 2016 13:17:45 +0100 Subject: [PATCH 35/68] Added type definitions for react-highlighter (#10786) --- react-highlighter/react-highlighter-tests.tsx | 16 ++++++++++++++++ react-highlighter/react-highlighter.d.ts | 9 +++++++++ 2 files changed, 25 insertions(+) create mode 100644 react-highlighter/react-highlighter-tests.tsx create mode 100644 react-highlighter/react-highlighter.d.ts diff --git a/react-highlighter/react-highlighter-tests.tsx b/react-highlighter/react-highlighter-tests.tsx new file mode 100644 index 0000000000..844ad875d8 --- /dev/null +++ b/react-highlighter/react-highlighter-tests.tsx @@ -0,0 +1,16 @@ +/// +/// + +import * as React from 'react'; +import * as Highlight from 'react-highlighter'; + +export class ReactHolderTest extends React.Component { + public render() { + return ( +
+ test +
+ ); + } +} \ No newline at end of file diff --git a/react-highlighter/react-highlighter.d.ts b/react-highlighter/react-highlighter.d.ts new file mode 100644 index 0000000000..c13670b0a2 --- /dev/null +++ b/react-highlighter/react-highlighter.d.ts @@ -0,0 +1,9 @@ +// Type definitions for react-highlighter +// Project: https://github.com/helior/react-highlighter +// Definitions by: Pedro Pereira +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "react-highlighter" { + var Highlight: any; + export = Highlight; +} \ No newline at end of file From ff8b4983fab2491ebe85ef23cc4d671e14a24b56 Mon Sep 17 00:00:00 2001 From: Xavier Stouder Date: Tue, 30 Aug 2016 14:21:56 +0200 Subject: [PATCH 36/68] Defintions for musicmetadata package (#10841) * Add Music Metadata * Fix some errors --- musicmetadata/musicmetadata-tests.ts | 10 ++++++ musicmetadata/musicmetadata.d.ts | 48 ++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 musicmetadata/musicmetadata-tests.ts create mode 100644 musicmetadata/musicmetadata.d.ts diff --git a/musicmetadata/musicmetadata-tests.ts b/musicmetadata/musicmetadata-tests.ts new file mode 100644 index 0000000000..bc99ba0900 --- /dev/null +++ b/musicmetadata/musicmetadata-tests.ts @@ -0,0 +1,10 @@ +/// +/// + +import * as fs from "fs"; +import * as mm from "musicmetadata"; + +mm(fs.createReadStream("hype-train.mp3"), (err: Error, metadata: MM.Metadata) => { + if (err) throw err; + console.log(`Parsed song ${metadata.title}`); +}); diff --git a/musicmetadata/musicmetadata.d.ts b/musicmetadata/musicmetadata.d.ts new file mode 100644 index 0000000000..b772468546 --- /dev/null +++ b/musicmetadata/musicmetadata.d.ts @@ -0,0 +1,48 @@ +// Type definitions for musicmetadata 2.0.4 +// Project: https://www.npmjs.com/package/musicmetadata +// Definitions by: Xavier Stouder +// Definitions: https://github.com/DefinitelyTyped/ + +/// + +declare module "musicmetadata" { + import {Readable} from "stream"; + import {EventEmitter} from "events"; + + function mm(readStream: Readable, callback: (err: Error, metadata: MM.Metadata) => void): EventEmitter; + function mm(readStream: Readable, options: MM.Options, callback: (err: Error, metadata: MM.Metadata) => void): EventEmitter; + + namespace mm { } + + export = mm; +} + +declare namespace MM { + export interface Options { + duration: boolean; + fileSize: number; + } + + export interface Metadata { + artist: string[]; + album: string; + albumartist: string[]; + title: string; + year: string; + track: NoOf; + disk: NoOf; + genre: string; + picture: Picture[]; + duration: number; + } + + export interface NoOf { + no: number; + of: number; + } + + export interface Picture { + format: string; + data: Buffer; + } +} \ No newline at end of file From a08ce8c057d0fbee840f90764f99988753b74e8b Mon Sep 17 00:00:00 2001 From: Timoteo Ponce Date: Tue, 30 Aug 2016 08:25:53 -0400 Subject: [PATCH 37/68] Adding definitions for jwt-client (#10845) * Added definitions for JWT-client * Fixed broken tests * Improved tests for es6 --- jwt-client/jwt-client-tests.ts | 6 +++++ jwt-client/jwt-client.d.ts | 42 ++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 jwt-client/jwt-client-tests.ts create mode 100644 jwt-client/jwt-client.d.ts diff --git a/jwt-client/jwt-client-tests.ts b/jwt-client/jwt-client-tests.ts new file mode 100644 index 0000000000..c686800078 --- /dev/null +++ b/jwt-client/jwt-client-tests.ts @@ -0,0 +1,6 @@ +/// + +import * as JWT from "jwt-client"; +var token = 'eyJpc3MiOiJ0b3B0YWwuY29tIiwiZXhwIjoxNDI2NDIwODAwLCJodHRwOi8vdG9wdGFsLmNvbS9qd3RfY2xhaW1zL2lzX2FkbWluIjp0cnVlLCJjb21wYW55IjoiVG9wdGFsIiwiYXdlc29tZSI6dHJ1ZX0'; +var session = JWT.read(token); +console.log('session is', session); diff --git a/jwt-client/jwt-client.d.ts b/jwt-client/jwt-client.d.ts new file mode 100644 index 0000000000..4f6ca95d88 --- /dev/null +++ b/jwt-client/jwt-client.d.ts @@ -0,0 +1,42 @@ +// Type definitions for jwt-client v0.2.1 +// Project: https://github.com/pauldijou/jwt-client +// Definitions by: Timoteo Ponce +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "jwt-client"{ + + interface JWTHeader{ + typ: string; + alg: string; + } + + interface JWTObject{ + header: JWTHeader; + claim: any; + signature: string; + } + + /** + * Read a string value (normally an HTTP header) + * from JSON Web Token to an Object + */ + function read(header:string):JWTObject; + + /** + * Given a JWT object, stringify it back to + * its JWT representation. + */ + function write(value:JWTObject):string; + + function keep(value:JWTObject, key?:any, storate?: any):void; + + function remember():void; + + function forget():void; + + function get():string; + + function validate(value:JWTObject, issuer?:any, audience?: any):boolean; +} + From 7996f3337d08241dc69589773c79c58478630c7c Mon Sep 17 00:00:00 2001 From: TonyYang Date: Tue, 30 Aug 2016 20:28:37 +0800 Subject: [PATCH 38/68] Process no exitCode (#10778) According to [node.js v4 doc - exitCode](https://nodejs.org/dist/latest-v4.x/docs/api/process.html#process_process_exitcode), there is exitCode in Process. --- node/node-4.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node-4.d.ts b/node/node-4.d.ts index d6fb33f750..4516331d7d 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -290,6 +290,7 @@ declare namespace NodeJS { cwd(): string; env: any; exit(code?: number): void; + exitCode: number; getgid(): number; setgid(id: number): void; setgid(id: string): void; From 22b7593283011f581accc470c0b6d2dc146751fe Mon Sep 17 00:00:00 2001 From: Adam Yost Date: Tue, 30 Aug 2016 08:31:21 -0400 Subject: [PATCH 39/68] Options is an optional field (#10847) --- soap/soap.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/soap/soap.d.ts b/soap/soap.d.ts index 6fcd1b703f..499b6422ee 100644 --- a/soap/soap.d.ts +++ b/soap/soap.d.ts @@ -11,7 +11,7 @@ declare module 'soap' { interface Security { } class WSSecurity implements Security { - constructor(username: string, password: string, options: any); + constructor(username: string, password: string, options?: any); } class ClientSSLSecurity implements Security { constructor(key: string, cert: string, ca: string, defaults: any); From 611c9fa7457f155a07ef92393a345fe753840a89 Mon Sep 17 00:00:00 2001 From: Dan Vanderkam Date: Tue, 30 Aug 2016 08:31:41 -0400 Subject: [PATCH 40/68] Add type definitions for graphlib (#10849) --- graphlib/graphlib-tests.ts | 24 +++ graphlib/graphlib.d.ts | 291 +++++++++++++++++++++++++++++++++++++ 2 files changed, 315 insertions(+) create mode 100644 graphlib/graphlib-tests.ts create mode 100644 graphlib/graphlib.d.ts diff --git a/graphlib/graphlib-tests.ts b/graphlib/graphlib-tests.ts new file mode 100644 index 0000000000..ff9268ab0f --- /dev/null +++ b/graphlib/graphlib-tests.ts @@ -0,0 +1,24 @@ +/// + +import * as graphlib from 'graphlib'; + +function test_graph() { + var g = new graphlib.Graph(); + g.setEdge('a', 'b'); + g.setEdge('a', 'b', 1.023); + + g.edge('a', 'b'); + g.edge({v: 'a', w: 'b'}); + + graphlib.json.read(graphlib.json.write(g)); + + graphlib.alg.dijkstra(g, 'a', e => g.edge(e)); + graphlib.alg.dijkstraAll(g, e => g.edge(e)); + graphlib.alg.dijkstraAll(g); + + graphlib.alg.findCycles(g); + graphlib.alg.isAcyclic(g); + graphlib.alg.prim(g, e => g.edge(e)); + graphlib.alg.tarjan(g); + graphlib.alg.topsort(g); +} diff --git a/graphlib/graphlib.d.ts b/graphlib/graphlib.d.ts new file mode 100644 index 0000000000..1f017d5383 --- /dev/null +++ b/graphlib/graphlib.d.ts @@ -0,0 +1,291 @@ +// Type definitions for graphlib 2.1.1 +// Project: https://github.com/cpettitt/graphlib +// Definitions by: Dan Vanderkam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +declare module "graphlib" { + export interface GraphOptions { + directed?: boolean; // default: true. + multigraph?: boolean; // default: false. + compound?: boolean; // default: false. + } + + export interface Edge { + v: string; + w: string; + /** The name that uniquely identifies a multi-edge. */ + name?: string; + } + + // TODO: add template parameters for edge and vertex labels? + export class Graph { + constructor(options?: GraphOptions); + + /** + * Creates or updates the value for the node v in the graph. If label is supplied + * it is set as the value for the node. If label is not supplied and the node was + * created by this call then the default node label will be assigned. Returns the + * graph, allowing this to be chained with other functions. Takes O(1) time. + */ + setNode(name: string, label?: any): Graph; + + hasNode(name: string): boolean; + + /** + * Remove the node with the id v in the graph or do nothing if the node is not in + * the graph. If the node was removed this function also removes any incident + * edges. Returns the graph, allowing this to be chained with other functions. + * Takes O(|E|) time. */ + removeNode(name: string): Graph; + + nodes(): string[]; + + /** Returns the label for this node. */ + node(name: string): any; + + /** + * Creates or updates the label for the edge (v, w) with the optionally supplied + * name. If label is supplied it is set as the value for the edge. If label is not + * supplied and the edge was created by this call then the default edge label will + * be assigned. The name parameter is only useful with multigraphs. Returns the + * graph, allowing this to be chained with other functions. Takes O(1) time. + */ + setEdge(v: string, w: string, label?: any): Graph; + + edges(): Edge[]; + + /** Returns the label for this edge. */ + edge(v: string, w: string): any; + edge(e: Edge): any; + + /** + * Return all edges that point to the node v. Optionally filters those edges down to just those + * coming from node u. Behavior is undefined for undirected graphs - use nodeEdges instead. + * Returns undefined if node v is not in the graph. Takes O(|E|) time. + */ + inEdges(v: string, u?: string): Edge[]; + + /** + * Return all edges that are pointed at by node v. Optionally filters those edges down to just + * those point to w. Behavior is undefined for undirected graphs - use nodeEdges instead. + * Returns undefined if node v is not in the graph. Takes O(|E|) time. + */ + outEdges(v: string, w?: string): Edge[]; + + /** + * Returns all edges to or from node v regardless of direction. Optionally filters those edges + * down to just those between nodes v and w regardless of direction. Returns undefined if node v + * is not in the graph. Takes O(|E|) time. + */ + nodeEdges(v: string, w?: string): Edge[]; + + /** + * Return all nodes that are predecessors of the specified node or undefined if node v is not in + * the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|) + * time. + */ + predecessors(node: string): string[]; + + /** + * Return all nodes that are successors of the specified node or undefined if node v is not in + * the graph. Behavior is undefined for undirected graphs - use neighbors instead. Takes O(|V|) + * time. + */ + successors(node: string): string[]; + + /** + * Return all nodes that are predecessors or successors of the specified node or undefined if + * node v is not in the graph. Takes O(|V|) time. + */ + neighbors(node: string): string[]; + + isDirected(): boolean; + isMultigraph(): boolean; + isCompound(): boolean; + + /** Sets the label for the graph to label. */ + setGraph(label: string): void; + + /** + * Returns the currently assigned label for the graph. If no label has been assigned, + * returns undefined. + */ + graph(): string; + + /** + * Returns the number of nodes in the graph. + */ + nodeCount(): number; + + /** + * Returns the number of edges in the graph. + */ + edgeCount(): number; + + /** Returns those nodes in the graph that have no in-edges. Takes O(|V|) time. */ + sources(): string[]; + + /** Returns those nodes in the graph that have no out-edges. Takes O(|V|) time. */ + sinks(): string[]; + } + + export namespace json { + /** + * Creates a JSONrepresentation of the graph that can be serialized to a string with + * JSON.stringify. The graph can later be restored using json.read. + */ + function write(g: Graph): Object; + + /** + * Takes JSON as input and returns the graph representation. For example, if we have + * serialized the graph in json-write to a string named str, we can restore it to a + * graph as follows: + * + * var g2 = graphlib.json.read(JSON.parse(str)); + * g2.nodes(); + * // ['a', 'b'] + * g2.edges() + * // [ { v: 'a', w: 'b' } ] + */ + function read(json: Object): Graph; + } + + export interface Path { + distance: number; + predecessor: string; + } + + export namespace alg { + /** + * Finds all connected components in a graph and returns an array of these components. + * Each component is itself an array that contains the ids of nodes in the component. + * This function takes O(|V|) time. + */ + function components(g: Graph): string[][]; + + /** + * This function is an implementation of Dijkstra's algorithm which finds the shortest + * path from source to all other nodes in g. This function returns a map of + * v -> { distance, predecessor }. The distance property holds the sum of the weights + * from source to v along the shortest path or Number.POSITIVE_INFINITY if there is no path + * from source. The predecessor property can be used to walk the individual elements of the + * path from source to v in reverse order. + * + * It takes an optional weightFn(e) which returns the weight of the edge e. If no weightFn + * is supplied then each edge is assumed to have a weight of 1. This function throws an + * Error if any of the traversed edges have a negative edge weight. + * + * It takes an optional edgeFn(v) which returns the ids of all edges incident to the node v + * for the purposes of shortest path traversal. By default this function uses the g.outEdges. + * + * It takes O((|E| + |V|) * log |V|) time. + */ + function dijkstra( + graph: Graph, + source: string, + weightFn?: (e: Edge) => number, + edgeFn?: (v: string) => Edge[] + ): {[node: string]: Path}; + + /** + * This function finds the shortest path from each node to every other reachable node in + * the graph. It is similar to alg.dijkstra, but instead of returning a single-source + * array, it returns a mapping of of source -> alg.dijksta(g, source, weightFn, edgeFn). + * + * This function takes an optional weightFn(e) which returns the weight of the edge e. + * If no weightFn is supplied then each edge is assumed to have a weight of 1. This + * function throws an Error if any of the traversed edges have a negative edge weight. + * + * This function takes an optional edgeFn(u) which returns the ids of all edges incident + * to the node u for the purposes of shortest path traversal. By default this function + * uses g.outEdges. + * + * This function takes O(|V| * (|E| + |V|) * log |V|) time. + */ + function dijkstraAll( + graph: Graph, + weightFn?: (e: Edge) => number, + edgeFn?: (v: string) => Edge[] + ): {[source: string]: {[node: string]: Path}}; + + /** + * Given a Graph, g, this function returns all nodes that are part of a cycle. As there + * may be more than one cycle in a graph this function return an array of these cycles, + * where each cycle is itself represented by an array of ids for each node involved in + * that cycle. + * + * alg.isAcyclic is more efficient if you only need to determine whether a graph has a + * cycle or not. + */ + function findCycles(graph: Graph): string[][]; + + /** + * This function is an implementation of the Floyd-Warshall algorithm, which finds the + * shortest path from each node to every other reachable node in the graph. It is similar + * to alg.dijkstraAll, but it handles negative edge weights and is more efficient for some types + * of graphs. This function returns a map of source -> { target -> { distance, predecessor }. + * The distance property holds the sum of the weights from source to target along the shortest + * path of Number.POSITIVE_INFINITY if there is no path from source. The predecessor property + * can be used to walk the individual elements of the path from source to target in reverse + * order. + * + * This function takes an optional weightFn(e) which returns the weight of the edge e. If no + * weightFunc is supplied then each edge is assumed to have a weight of 1. + * + * This function takes an optional edgeFn(v) which returns the ids of all edges incident to the + * node v for the purposes of shortest path traversal. By default this function uses the + * outEdges function on the supplied graph. + * + * This algorithm takes O(|V|^3) time. + */ + function floydWarshall( + graph: Graph, + weightFn?: (e: Edge) => number, + edgeFn?: (v: string) => Edge[] + ): {[source: string]: {[node: string]: Path}}; + + /** + * Given a Graph, g, this function returns true if the graph has no cycles and returns false if it + * does. This algorithm returns as soon as it detects the first cycle. You can use alg.findCycles + * to get the actual list of cycles in the graph. + */ + function isAcyclic(graph: Graph): boolean; + + /** + * Prim's algorithm takes a connected undirected graph and generates a minimum spanning tree. This + * function returns the minimum spanning tree as an undirected graph. This algorithm is derived + * from the description in "Introduction to Algorithms", Third Edition, Cormen, et al., Pg 634. + * + * This function takes a weightFn(e) which returns the weight of the edge e. It throws an Error if + * the graph is not connected. + * + * This function takes O(|E| log |V|) time. + */ + function prim(graph: Graph, weightFn: (e: Edge) => number): Graph; + + /** + * This function is an implementation of Tarjan's algorithm which finds all strongly connected + * components in the directed graph g. Each strongly connected component is composed of nodes that + * can reach all other nodes in the component via directed edges. A strongly connected component + * can consist of a single node if that node cannot both reach and be reached by any other + * specific node in the graph. Components of more than one node are guaranteed to have at least + * one cycle. + * + * This function returns an array of components. Each component is itself an array that contains + * the ids of all nodes in the component. + */ + function tarjan(graph: Graph): string[][]; + + /** + * An implementation of topological sorting. + * + * Given a Graph g this function returns an array of nodes such that for each edge u -> v, u + * appears before v in the array. If the graph has a cycle it is impossible to generate such a + * list and CycleException is thrown. + * + * Takes O(|V| + |E|) time. + */ + function topsort(graph: Graph): string[]; + } +} From cc8642a40db06f7c01bdf3dff5ed56aa296ae751 Mon Sep 17 00:00:00 2001 From: Viktor Hedefalk Date: Tue, 30 Aug 2016 14:35:05 +0200 Subject: [PATCH 41/68] adds constructor to pass tests Need two constructors because https://github.com/websockets/ws/blob/master/lib/WebSocket.js\#L58 --- ws/ws.d.ts | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/ws/ws.d.ts b/ws/ws.d.ts index af0bb9a4ad..2b16bd52ea 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -34,21 +34,8 @@ declare module "ws" { onclose: (event: {wasClean: boolean; code: number; reason: string; target: WebSocket}) => void; onmessage: (event: {data: any; type: string; target: WebSocket}) => void; - constructor(address: string, protocols?: string | string[], options?: { - protocol?: string; - agent?: http.Agent; - headers?: {[key: string]: string}; - protocolVersion?: any; - host?: string; - origin?: string; - pfx?: any; - key?: any; - passphrase?: string; - cert?: any; - ca?: any[]; - ciphers?: string; - rejectUnauthorized?: boolean; - }); + constructor(address: string, options?: WebSocket.IClientOptions); + constructor(address: string, protocols?: string | string[], options?: WebSocket.IClientOptions); close(code?: number, data?: any): void; pause(): void; @@ -92,7 +79,23 @@ declare module "ws" { type VerifyClientCallbackSync = (info: {origin: string; secure: boolean; req: http.ServerRequest}) => boolean; type VerifyClientCallbackAsync = (info: {origin: string; secure: boolean; req: http.ServerRequest} , callback: (res: boolean) => void) => void; - + + export interface IClientOptions { + protocol?: string; + agent?: http.Agent; + headers?: {[key: string]: string}; + protocolVersion?: any; + host?: string; + origin?: string; + pfx?: any; + key?: any; + passphrase?: string; + cert?: any; + ca?: any[]; + ciphers?: string; + rejectUnauthorized?: boolean; + } + export interface IServerOptions { host?: string; port?: number; From 169b4a6d0805deb3870ea76d807eae9b5b0f2753 Mon Sep 17 00:00:00 2001 From: Ezekiel Victor Date: Tue, 30 Aug 2016 05:36:40 -0700 Subject: [PATCH 42/68] For conformity to typings specs (use namespace instead of global for global typings) (#10854) * definitions for karma-fixture * return type here can be any object with any keys (arbitrary JSON) * Update karma-fixture.d.ts * update karma fixture typings --- karma-fixture/karma-fixture.d.ts | 34 ++++++++++++++++---------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/karma-fixture/karma-fixture.d.ts b/karma-fixture/karma-fixture.d.ts index 8e4d18fd47..bc89b1b723 100644 --- a/karma-fixture/karma-fixture.d.ts +++ b/karma-fixture/karma-fixture.d.ts @@ -3,25 +3,25 @@ // Definitions by: Ezekiel Victor // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module fixture { - var el: HTMLElement; - var json: any[]; +declare namespace fixture { + export var el: HTMLElement; + export var json: any[]; - function load(...files: string[]): any; - function load(file1: string, append?: boolean): any; - function load(file1: string, file2: string, append?: boolean): any; - function load(file1: string, file2: string, file3: string, append?: boolean): any; - function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any; - function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any; + export function load(...files: string[]): any; + export function load(file1: string, append?: boolean): any; + export function load(file1: string, file2: string, append?: boolean): any; + export function load(file1: string, file2: string, file3: string, append?: boolean): any; + export function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any; + export function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any; - function set(...htmlStrs: string[]): HTMLElement|HTMLElement[]; - function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[]; - function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[]; - function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[]; - function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[]; - function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(...htmlStrs: string[]): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[]; + export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[]; - function cleanup(): void; + export function cleanup(): void; - function setBase(fixtureBasePath: string): void; + export function setBase(fixtureBasePath: string): void; } From d627f43919964df1f961e8a78d9f41c4a1e40e53 Mon Sep 17 00:00:00 2001 From: Joshua Efiong Date: Tue, 30 Aug 2016 13:39:08 +0100 Subject: [PATCH 43/68] Started work on HERE Maps API for JavaScript typedefs. (#10750) * Started work on HERE Maps API for JavaScript typedefs. * Removed the license from the head of the file. * The 'data' options attribute can be undefined, so make it optional. * Fixed build failure. - Fixed build failure: 'a class member cannot be declared optional'. - 'data' class member on the class 'H.map.provider.Tile' cannot be declared optional. --- heremaps/heremaps-tests.ts | 82 + heremaps/heremaps.d.ts | 6045 ++++++++++++++++++++++++++++++++++++ 2 files changed, 6127 insertions(+) create mode 100644 heremaps/heremaps-tests.ts create mode 100644 heremaps/heremaps.d.ts diff --git a/heremaps/heremaps-tests.ts b/heremaps/heremaps-tests.ts new file mode 100644 index 0000000000..3b2e1b5c30 --- /dev/null +++ b/heremaps/heremaps-tests.ts @@ -0,0 +1,82 @@ +// Test file for HERE Maps API for JavaScript Definition file +/// + +/** + * EXAMPLE from the HERE Maps API + * Takes a snapshot of the map. + * + * @param {Element} resultContainer Reference to DOM Element to show the captured map area + * @param {H.Map} map Reference to initialized map object + * @param {H.ui.UI} ui Reference to UI component + */ +function capture(resultContainer: HTMLElement, map: H.Map, ui: H.ui.UI) { + // Capturing area of the map is asynchronous, callback function receives HTML5 canvas + // element with desired map area rendered on it. + // We also pass an H.ui.UI reference in order to see the ScaleBar in the output. + // If dimensions are omitted, whole veiw port will be captured + map.capture((canvas: HTMLCanvasElement) => { + if (canvas) { + resultContainer.innerHTML = ''; + resultContainer.appendChild(canvas); + } else { + // For example when map is in Panorama mode + resultContainer.innerHTML = 'Capturing is not supported'; + } + }, [ui], 50, 50, 500, 200); +} + +/** + * Boilerplate map initialization code starts below: + */ +// Step 1: initialize communication with the platform +var platform = new H.service.Platform({ + app_id: 'DemoAppId01082013GAL', + app_code: 'AJKnXv84fjrb0KIHawS0Tg', + useHTTPS: true, + useCIT: true +}); + +var defaultLayers = platform.createDefaultLayers(); + +var mapContainer = document.getElementById('map'); + +// Step 2: initialize a map +var map = new H.Map(mapContainer, defaultLayers.normal.map, { + // initial center and zoom level of the map + zoom: 16, + // Champs-Elysees + center: {lat: 48.869145, lng: 2.314298} +}); + +// Step 3: make the map interactive +// MapEvents enables the event system +// Behavior implements default interactions for pan/zoom (also on mobile touch environments) +var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map)); + +// Step 4: Create the default UI +var ui = H.ui.UI.createDefault(map, defaultLayers, 'en-US'); + + +// Step 6: Create "Capture" button and place for showing the captured area +var resultContainer = document.getElementById('panel'); + +// Create container for the "Capture" button +var containerNode = document.createElement('div'); +containerNode.setAttribute('style', + 'position:absolute;top:0;left:0;background-color:#fff; padding:10px;'); +containerNode.className = 'btn-group'; + +// Create the "Capture" button +var captureBtn = document.createElement('input'); +captureBtn.value = 'Capture'; +captureBtn.type = 'button'; +captureBtn.className = 'btn btn-sm btn-default'; + +// Add both button and container to the DOM +containerNode.appendChild(captureBtn); +mapContainer.appendChild(containerNode); + +// Step 7: Handle capture button click event +captureBtn.onclick = function() { + capture(resultContainer, map, ui); +}; \ No newline at end of file diff --git a/heremaps/heremaps.d.ts b/heremaps/heremaps.d.ts new file mode 100644 index 0000000000..fe79e55ecf --- /dev/null +++ b/heremaps/heremaps.d.ts @@ -0,0 +1,6045 @@ +// Type definitions for HERE Maps API for JavaScript v3.0.12.4 +// Project: https://developer.here.com/ +// Definitions by: Joshua Efiong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace H { + /***** Map *****/ + /** + * Map class defines map instance in the application. By creating this object you will initialize a visible map object which is attached to the provided dom element. Map class is an entry point to all operations related to layers, map objects and geo-screen transformations. By specifying options you can initialize map with predefined view. + */ + export class Map extends H.util.EventTarget { + /** + * Constructor + * @param element {Element} - html element into which the map will be rendered + * @param baseLayer {H.map.layer.Layer} - The layer to be used as the base (bottom most) layer. + * @param opt_options {H.Map.Options=} - additional map options + */ + constructor(element: Element, baseLayer: H.map.layer.Layer, opt_options?: H.Map.Options); + + /** + * This method returns the map root html element + * @returns {Element} + */ + getElement(): Element; + + /** + * This method sets the new center on a map. + * @param center {H.geo.IPoint} - requested center to be set + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setCenter(center: H.geo.IPoint, opt_animate?: boolean): H.Map; + + /** + * This method returns currently rendered center of the map. + * @returns {H.geo.Point} + */ + getCenter(): H.geo.Point; + + /** + * This method sets the zoom level on the map. Every zoom level represents different scale i.e map at zoom level 2 is twice as large as the map at zoom level 1. + * @param zoom {number} - requested zoom level + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setZoom(zoom: number, opt_animate?: boolean): H.Map; + + /** + * This method returns currently rendered zoom level. + * @returns {number} + */ + getZoom(): number; + + /** + * This method changes the map zoom while keeping target screen coordinates specified as x,y at the same place where they were before. + * @param zoom {number} - new zoom level + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + */ + zoomAt(zoom: number, x: number, y: number): void; + + /** + * This method sets the bounding rect to be displayed by the map. Maps display the bounding rect in a way that it fits entirely in the current viewport. + * @param boundingRect {H.geo.Rect} - view bound which should be shown on map + * @param opt_animate {boolean=} - parameter indicates if animated transition should be applied, default is false + * @returns {H.Map} - the instance itself + */ + setViewBounds(boundingRect: H.geo.Rect, opt_animate?: boolean): H.Map; + + /** + * This method returns bounding rect for the current map view. Returned bounding rect defines entire currently viewable area on the screen. + * @returns {H.geo.Rect} + */ + getViewBounds(): H.geo.Rect; + + /** + * Calculates the best CameraModel to show the provided bounding rectangle + * @param rect {H.geo.Rect} - The geographical bounding rectangle to use + * @returns {H.map.ViewModel.CameraData} - The result, represented by the properties zoom (number) and position (geo.Point) + */ + getCameraDataForBounds(rect: H.geo.Rect): H.map.ViewModel.CameraData; + + /** + * This method returns current map viewport. Viewport can be used to modify padding and margin which will reflect the position of the viewport center and the amount of extra data loaded (for margin) + * @returns {H.map.ViewPort} + */ + getViewPort(): H.map.ViewPort; + + /** + * This method returns current view model. View model can be used to modify the current view or camera. H.map.ViewModel + * @returns {H.map.ViewModel} + */ + getViewModel(): H.map.ViewModel; + + /** + * This method returns the map's current layer collection. + * @returns {H.map.DataModel} + */ + getLayers(): H.map.DataModel; + + /** + * This method returns the imprint object for this map. + * @returns {H.map.Imprint} + */ + getImprint(): H.map.Imprint; + + /** + * This method captures desired region of the map and objects on it. Result is returned as an HTML5 Canvas element. Origin of coordinate system for capturing is in the top left corner of the viewport. + * @param callback {function(HTMLCanvasElement=)} - Callback function to call once result of the capturing is ready + * @param opt_capturables {Array=} - Collection of "capturable" element(s) to draw into the resulting canvas + * @param opt_x1 {number=} - The X coordinate of the left edge of the capturing rectangle defaults to 0 + * @param opt_y1 {number=} - The Y coordinate of the top edge of the capturing rectangle defaults to 0 + * @param opt_x2 {number=} - The X coordinate of the right edge of the capturing rectangle defaults to viewport width + * @param opt_y2 {number=} - The Y coordinate of the bottom edge of the capturing rectangle defaults to viewport height + */ + capture(callback?: (canvas: HTMLCanvasElement) => void, opt_capturables?: Array, opt_x1?: number, opt_y1?: number, opt_x2?: number, opt_y2?: number): void; + + /** + * This method sets the rendering engine type for the map. Rendering engine is responsible for displaying i.e tiles and data on the map. + * @param type {H.Map.EngineType} + * @returns {H.Map} - the map itself + */ + setEngineType(type: H.Map.EngineType): H.Map; + + /** + * To persistently store the content of a map layer for a given area and range of zoom levels. It can be used to enable map rendering when no internet connection is established and also to reduce the download traffic for frequently visited map areas. + * @param opt_onprogress {function(H.util.Request)=} - A callback which is invoked every time when the progress state of the returned store request changes. + * @param opt_bounds {H.geo.Rect=} - The area to store, default is the current view bounds + * @param opt_min {number=} - The minimum zoom level to store, default is the current zoom level + * @param opt_max {number=} - The maximum zoom level to store, default is the current zoom level + * @param opt_layer {H.map.layer.BaseTileLayer=} - The layer to store, default is the current base layer + * @returns {H.util.Request} - A handle to the created storage request + */ + storeContent(opt_onprogress?: (req: H.util.Request) => void, opt_bounds?: H.geo.Rect, opt_min?: number, opt_max?: number, opt_layer?: H.map.layer.BaseTileLayer): H.util.Request; + + /** + * To clear the entire stored content + * @param opt_onprogress {function(H.util.Request)=} - A callback which is invoked every time when the progress state of the returned clear request changes + * @returns {H.util.Request} - A handle to the created flush request + */ + clearContent(opt_onprogress?: (req: H.util.Request) => void): H.util.Request; + + /** + * This method adds a layer to the map. + * @param layer {H.map.layer.Layer} - The map layer to be added + * @param opt_idx {number=} - index at which the new layer should be inserted + * @returns {H.Map} - current map instance + */ + addLayer(layer: H.map.layer.Layer, opt_idx?: number): H.Map; + + /** + * This method removes layer from the map. + * @param layer {H.map.layer.Layer} - The map layer to be removed + * @returns {H.Map} - current map instance + */ + removeLayer(layer: H.map.layer.Layer): H.Map; + + /** + * This method will set provided layer as base map. The layer will be inserted as the bottom most layer in the map. + * @param layer {H.map.layer.Layer} - The layer to use as base map + * @returns {H.Map} - the instance itself + */ + setBaseLayer(layer: H.map.layer.Layer): H.Map; + + /** + * To get the current base map layer. + * @returns {?H.map.layer.Layer} + */ + getBaseLayer(): H.map.layer.Layer; + + /** + * Returns the screen coordinates according to the given geographical coordinates. This method returns a screen pixel coordinates for the provided geo point. + * @param geoPoint {H.geo.IPoint} - point on the map + * @returns {?H.math.Point} + */ + geoToScreen(geoPoint: H.geo.IPoint): H.math.Point; + + /** + * Returns the geographical coordinates according to the given screen coordinates. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {?H.geo.Point} + */ + screenToGeo(x: number, y: number): H.geo.Point; + + /** + * Returns the camera data according to the given screen coordinates. Method converts screen pixel coordinates to correct camera data object + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {H.map.ViewModel.CameraData} + */ + screenToCameraData(x: number, y: number): H.map.ViewModel.CameraData; + + /** + * This method adds an map object to the map. Map object can be a marker or a spatial object like polygon or polyline. + * @param mapObject {!H.map.Object} - The map object to add + * @returns {!H.map.Object} - the added map object + */ + addObject(mapObject: H.map.Object): H.map.Object; + + /** + * This method removes previously added map object from the map. + * @param mapObject {!H.map.Object} - The map object to remove + * @returns {!H.map.Object} - the removed map object + */ + removeObject(mapObject: H.map.Object): H.map.Object; + + /** + * This method retrieves the list of all objects which have been added to the map. + * @returns {Array} - the list of all use objects which are currently on the map. + */ + getObjects(): Array; + + /** + * This method adds an array of objects or an object group to the map. + * @param mapObjects {Array} + * @returns {H.Map} - the map instance + */ + addObjects(mapObjects: Array): H.Map; + + /** + * This method removes an array of object or an object group from the map. + * @param mapObjects {(Array | H.map.Group)} + * @returns {H.Map} - the map instance + */ + removeObjects(mapObjects: (Array | H.map.Group)): H.Map; + + /** + * Returns the top most z-ordered map object found under the specific screen coordinates. Coordinates are viewport pixel coordinates starting from top left corner as (0, 0) point. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {?H.map.Object} - the encountered top most map object or null if no object found + */ + getObjectAt(x: number, y: number): H.map.Object; + + /** + * Returns a list of map objects in descending z-order found under the specific screen coordinates. Coordinates are viewport pixel coordinates starting from top left corner as (0, 0) point. + * @param x {number} - map viewport x-axis pixel coordinate + * @param y {number} - map viewport y-axis pixel coordinate + * @returns {Array} + */ + getObjectsAt(x: number, y: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Map { + /** + * It defines the number of lower and higher zoom levels, where cached content of the base map is rendered while content of the current zoom level is still loading. Example: if range was set to {lower: 3, higher: 2} and current level is 10 then rendering engine will try to display cached tiles from lower zoom levels 7, 8, 9 and higher levels 11 and 12. + * @property lower {number} - The number of lower zoom levels to take into account, default is 0 + * @property higher {number} - The number of higher zoom levels to take into account, default is 0 + */ + export interface BackgroundRange { + lower: number; + higher: number; + } + + /** + * Types of engines + */ + export enum EngineType { + P2D, + PANORAMA, + } + + /** + * This type defines options which can be used to initialize the map. + * @property center {H.geo.IPoint=} - The initial center of the map, default is {lat:0, lng: 0} + * @property zoom {number=} - The initial zoom level of the map, default is 0 respectively the minimal zoom level of the base map + * @property bounds {H.geo.Rect=} - The view bounds to be displayed on the map. If provided, it takes precedence over center and zoom. and zoom if provided) + * @property layers {Array=} - A list of layers to render on top of the base map + * @property engineType: {H.Map.EngineType=} - The initial engine type to use, default is P2D + * @property pixelRatio {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @property imprint {H.map.Imprint.Options=} - The imprint options or null to suppress the imprint + * @property renderBaseBackground {H.Map.BackgroundRange=} - Object describes how many cached zoom levels should be used as a base map background while base map tiles are loading. Example: {lower: 3, higher: 2} + * @property autoColor {boolean=} - Indicates whether the UI's colors should automatically adjusted to the base layer, default is true. Up to now only the copyright style will be adjusted. See H.map.layer.Layer.Options#dark + * @property margin {number=} - The size in pixel of the supplemental area to render for each side of the map + * @property padding {H.map.ViewPort.Padding=} - The padding in pixels for each side of the map + * @property fixedCenter {boolean=} - Indicates whether the center of the map should remain unchanged if the viewport's size or padding has been changed, default is true + */ + export interface Options { + center?: H.geo.IPoint; + zoom?: number; + bounds?: H.geo.Rect; + layers?: Array; + engineType?: EngineType; + pixelRatio?: number; + imprint?: H.map.Imprint.Options; + renderBaseBackground?: BackgroundRange; + autoColor?: boolean; + margin?: number; + padding?: H.map.ViewPort.Padding; + fixedCenter?: boolean; + } + } + + /***** clustering *****/ + export module clustering { + /** + * This class represents the input data structure for data points to be clustered. + * @property lat {H.geo.Latitude} - The latitude coordinate of the data point's position + * @property lng {H.geo.Longitude} - The longitude coordinate of the data point's position + * @property wt {number} - The weight of the data point + * @property data {*} - Data associated with this data point + */ + export class DataPoint implements H.geo.IPoint { + /** + * Constructor + * @param lat {H.geo.Latitude} - The latitude coordinate of the data point's position + * @param lng {H.geo.Longitude} - The longitude coordinate of the data point's position + * @param opt_weight {number=} - The weight of the data point as a positive number > 0. If not specified it , default is 1. + * @param opt_data {*=} - Optional data, which will be associated with this DataPoint + */ + constructor(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_weight?: number, opt_data?: any); + + lat: H.geo.Latitude; + lng: H.geo.Longitude; + alt: H.geo.Altitude; + ctx: H.geo.AltitudeContext; + wt: number; + data: any; + } + + /** + * This interface describes a cluster of data points, which fulfill the clustering specification (i.e. data points are within the epsilon and there are enough points to form a cluster). + */ + export interface ICluster { + /** + * Returns the maximum zoom level where this cluster doesn't fall apart into sub clusters and/or noise poinst + * @returns {number} + */ + getMaxZoom(): number; + + /** + * Returns the bounding rectangle of this cluster. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + + /** + * Invokes the specified callback for each "entry" of the cluster. That "entry" can be either a cluster which implements H.clustering.ICluster interface or a noise point which implements H.clustering.INoisePoint interface. + * @param callback {function(H.clustering.IResult)} - The callback gets the currently traversed entry as an argument, which is cluster or noise point. + */ + forEachEntry(callback: (result: H.clustering.IResult) => void): void; + + /** + * Invokes the specified callback for each data point which is part of this cluster, even indirectly. + * @param callback {function(H.clustering.INoisePoint)} - The callback gets the currently traversed noise point as argument. + */ + forEachDataPoint(callback: (noise: H.clustering.INoisePoint) => void): void; + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * This interface represents a data point which does not belong to a cluster. + */ + export interface INoisePoint { + /** + * This method returns data which coresponds to this noise point. + * @returns {*} + */ + getData(): any; + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * This interface represents the result item of a clustering operation. + */ + export interface IResult { + + /** + * Returns the geographical position of this cluster result. + * @returns {H.geo.Point} + */ + getPosition(): H.geo.Point; + + /** + * Returns the weight of this cluster result. + * @returns {number} + */ + getWeight(): number; + + /** + * To indicate whether this cluster result is a cluster or noise point + * @returns {boolean} + */ + isCluster(): boolean; + + /** + * Returns the minimum zoom level where this item is not part of another cluster + * @returns {number} + */ + getMinZoom(): number; + } + + /** + * Interface which specifies the methods a theme must implement. + */ + export interface ITheme { + + /** + * Function returns a cluster presentation as a map object. + * @param cluster {H.clustering.ICluster} + * @returns {H.map.Object} + */ + getClusterPresentation(cluster: H.clustering.ICluster): H.map.Object; + + /** + * Function returns noise point presentation as a map object + * @param noisePoint {H.clustering.INoisePoint} + * @returns {H.map.Object} + */ + getNoisePresentation(noisePoint: H.clustering.INoisePoint): H.map.Object; + } + + /** + * The clustering provider serves clusters and noise point representation for the map depending on the provided data set. Levels for clustering as well as custom cluster representation can be set via Options. + * @property min {number} - Minimum zoom level at which provider can cluster data + * @property max {number} - Maximum zoom level at which provider can cluster data + */ + export class Provider extends H.util.EventTarget { + /** + * Constructor + * @param dataPoints {Array} + * @param opt_options {H.clustering.Provider.Options=} + */ + constructor(dataPoints: Array, opt_options?: H.clustering.Provider.Options); + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + /** + * This method sets new data to the provider + * @param dataPoints {Array} + */ + setDataPoints(dataPoints: Array): void; + + /** + * This method adds a data point to the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoint {H.clustering.DataPoint} + */ + addDataPoint(dataPoint: H.clustering.DataPoint): void; + + /** + * This method adds a list of data points to the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoints {Array} + */ + addDataPoints(dataPoints: Array): void; + + /** + * This method removes a data point from the provider. Beware that this method provokes reclustering of the whole data set. + * @param dataPoint {H.clustering.DataPoint} + */ + removeDataPoint(dataPoint: H.clustering.DataPoint): void; + + /** + * This method returns current theme used for creating cluster visualization + * @returns {H.clustering.ITheme} + */ + getTheme(): H.clustering.ITheme; + + /** + * This method sets new theme on the provider. Calling this method will change visuals for displayed clusters and noise points. + * @param theme {H.clustering.ITheme} + */ + setTheme(theme: H.clustering.ITheme): void; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + + /** + * Returns all DomMarker cluster and noise point representations which intersect with the provided rectangular area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestDomMarkers(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesMarkers(): boolean; + + /** + * Returns all cluster and noise point markers which intersect with the provided rectangular area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestMarkers(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * This method always returns true as we don't have information about visual representation until we have the clustering result and apply the theme. + * @returns {boolean} + */ + providesSpatials(): boolean; + + /** + * Returns all polyline, polygon, circle and rect objects which represent cluster and noise points and intersect with the provided area. + * @param bounds {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatials(bounds: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the spatial objects which intersect the given tile + * @param tile {H.map.provider.SpatialTile} - The tile for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatialsByTile(tile: H.map.provider.Tile, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the accumulate invalidations of this provider's objects that have occurred. + * @returns {H.map.provider.Invalidations} - an invalidations object + */ + getInvalidations(): H.map.provider.Invalidations; + + /** + * To signal to this provider that a map object has been changed. The method updates the Invalidations of this provider and the given map object and triggers dispatchUpdate() + * @param mapObject {!H.map.Object} - The map object to be invalidated + * @param changes {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(mapObject: H.map.Object, changes: H.math.BitMask): void; + + min: number; + max: number; + } + + export module Provider { + /** + * Options which are used within cluster calculations. + * @property eps {number=} - epsilon parameter for cluster calculation. For the FASTGRID strategy it must not exceed 256 and must take values that are power of 2. For the GRID and DYNAMICGRID strategies it can take values from 10 to 127. Default is 32. + * @property minWeight {number=} - the minimum points weight sum to form a cluster, default is 2 + * @property projection {H.geo.IProjection=} - projection to use for clustering, default is H.geo.mercator + * @property strategy {H.clustering.Provider.Strategy=} - clustering stretegy, defaults to H.clustering.Provider.Strategy.FASTGRID + */ + export interface ClusteringOptions { + eps?: number; + minWeight?: number; + projection?: H.geo.IProjection; + strategy?: H.clustering.Provider.Strategy; + } + + /** + * Options which are used to initialize the clustering Provider + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property clusteringOptions {H.clustering.Provider.ClusteringOptions=} - options for clustering algorithm + * @property theme {H.clustering.ITheme=} - cluster and noise point graphical representation + */ + export interface Options { + min?: number; + max?: number; + clusteringOptions?: H.clustering.Provider.ClusteringOptions; + theme?: H.clustering.ITheme; + } + + /** + * Enumeration represents possible clustering strategies. FASTGRID clustering is the efficient way to cluster large sets of data points. GRID clustering is slower but has greater precision due to the bigger range of epsilon values, this strategy suitable for clustering smaller data sets (up to 1000 data points) on desktop devices. DYNAMICGRID clustering uses the same algorithm of clustering as the GRID, but clusters on the viewport basis is meant to be used with data sets that are subject to the frequent update operations. + */ + export enum Strategy { + FASTGRID, + GRID, + DYNAMICGRID, + } + } + } + + /***** data *****/ + export module data { + /** + * An abstract reader class defines interface for data readers and has general functionality related to fetching data and reader events. + */ + export class AbstractReader extends H.util.EventTarget { + /** + * Constructor + * @param opt_url {string=} + */ + constructor(opt_url?: string); + + /** + * Method returns H.map.layer.ObjectLayer that contains parsed data, and can be added directly to the map. It returns new instance of the class with every invocation. If data hasn't been parsed it will return H.map.layer.ObjectLayer that contains partial information, and reader will add new parsed objects to the layer's provider later on. + * @returns {H.map.layer.ObjectLayer} + */ + getLayer(): H.map.layer.ObjectLayer; + + /** + * Method returns collection of currently parsed, and converted to H.map.Object data objects. Method returns only currently parsed objects if parsing is ongoing. + * @returns {Array} + */ + getParsedObjects(): Array; + + /** + * Returns URL of the current file, which is either in process of fetching/parsing or file that has been already parsed. + * @returns {(string | undefined)} - url + */ + getUrl(): string | void; + + /** + * Method sets reader's URL. Method resets current Reader's state to its initial values (clears data about last parsed objects, etc.), and throws InvalidState exception if Reader's state is not READY or ERROR. + * @param url {string} - The new URL + * @returns {H.data.AbstractReader} + */ + setUrl(url: string): H.data.AbstractReader; + + /** + * Returns the reader's processing state for possible states see H.data.AbstractReader.State + * @returns {H.data.AbstractReader.State} + */ + getState(): H.data.AbstractReader.State; + + /** + * Method launches parsing of the data file at the current url (see H.data.AbstractReader#setUrl or H.data.AbstractReader). Method uses XHR as a transport therefore same origin policy applies, or server should respond with proper CORS headers. + */ + parse(): void; + } + + export module AbstractReader { + /** + * The event class for state events that are dispatched by AbstractReader + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param target {(H.data.AbstractReader | H.map.Object)} - The target that's passed to event listeners + * @param type {string} - The type of the event + * @param state {H.data.AbstractReader.State} - The state of the target firing an event + * @param message {string} - The message associated with an event + */ + constructor(target: (H.data.AbstractReader | H.map.Object), type: string, state: H.data.AbstractReader.State, message: string); + } + + /** + * The state types of an Reader. Possible states are: + */ + export enum State { + ERROR, + LOADING, + VISIT, + READY, + } + } + } + + /***** geo *****/ + export module geo { + /** + * A Geographic coordinate that specifies the height of a point in meters. A value of undefined is treated as 0. + */ + export type Altitude = number; + + /** + * Contexts for altitudes to specify the contextual origin of an altitude's value + */ + export enum AltitudeContext { + /** Ground level */ + undefined, + /** Ground level */ + GL, + /** Obstruction level */ + OL, + /** Mean sea level */ + SL, + /** Sea bed level */ + SB, + /** WGS84 ellipsoid */ + WE, + /** WGS84 geoid */ + WG, + } + + /** + * An interface to represent a geographic point. Every point in geo space is represented by three coordinates latitude, longitude and optional altitude. + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property alt {H.geo.Altitude=} - The altitude coordinate. + * @property ctx {H.geo.AltitudeContext=} - The altitude context. + */ + export interface IPoint { + lat: H.geo.Latitude; + lng: Longitude; + alt?: H.geo.Altitude; + ctx?: H.geo.AltitudeContext; + } + + export interface IProjection { + latLngToPoint(lat: number, lng: number, opt_out?: H.math.Point): H.math.Point; + xyToGeo(x: number, y: number, opt_out?: H.geo.Point): H.geo.Point; + pointToGeo(point: H.math.IPoint, opt_out?: H.geo.Point): H.geo.Point; + geoToPoint(geoPoint: H.geo.IPoint, opt_out?: H.math.Point): H.math.Point; + } + + /** + * A geographic coordinate that specifies the north-south position of a point on the Earth's surface in the range from -90 to + 90 degrees, inclusive. + */ + export type Latitude = number; + + /** + * A Geographic coordinate that specifies the east-west position of a point on the Earth's surface in the range from -180 to 180 degrees, inclusive. + */ + export type Longitude = number; + + /** + * Class represents a geographical point, which is defined by the latitude, longitude and optional altitude. + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property alt {H.geo.Altitude} - The altitude coordinate. + * @property ctx {H.geo.AltitudeContext} - The altitude context. + */ + export class Point implements IPoint { + /** + * Constructor + * @property lat {H.geo.Latitude} - The latitude coordinate. + * @property lng {H.geo.Longitude} - The longitude coordinate. + * @property opt_alt {H.geo.Altitude=} - The altitude coordinate. + * @property opt_ctx {H.geo.AltitudeContext=} - The altitude context. + */ + constructor(lat: H.geo.Latitude, lng: Longitude, opt_alt?: H.geo.Altitude, opt_ctx?: H.geo.AltitudeContext); + + /** + * To compare this point with a supplied other point for equality. Two points are considered equal if they have the same lat and lng as well as equivalent values for alt and ctx. + * @param other {H.geo.IPoint} + * @returns {boolean} - Whether the two points are equal. + */ + equals(other: IPoint): boolean; + + /** + * To calculate the distance between this point and the supplied other point. The method uses the Haversine formula. The altitude is not considered. + * @param other {H.geo.IPoint} + * @returns {number} - The distance between the given location and the location supplied by the caller in meters. + */ + distance(other: IPoint): number; + + /** + * This method calculates the geographic point of a destination point using the distance and bearing specified by the caller. The altitude is ignored, instead the WGS84 Mean Radius is taken. + * @param bearing {number} - The bearing to use in the calculation in degrees. + * @param distance {number} - The distance to the destination in meters. + * @param opt_overGreatCircle {boolean=} - If true the computation uses the 'Great Circle' otherwise 'Rhumb Line'. + * @returns {H.geo.Point} - The calculated point + */ + walk(bearing: number, distance: number, opt_overGreatCircle?: boolean): Point; + + /** + * This method validates the given IPoint. It checks, if lat, lng, alt and ctx have valid types. Additionally the value of the lat property is clamped into a range of -90 ... +90 and the value of the lng property is modulo into a range of -180 ... +180 plus validates the values of the alt and ctx properties + * @param point {H.geo.IPoint} - The point to validate + * @param opt_caller {Function=} - The caller to use for InvalidArgumentError. If omitted no error is thrown + * @param opt_argNr {number=} - The argument number to use for InvalidArgumentError. + * @returns {boolean} - if the given point could validate + */ + static validate(point: IPoint, opt_caller?: Function, opt_argNr?: number): boolean; + + /** + * This method creates a Point instance from a given IPoint object. + * @param iPoint {H.geo.IPoint} - The IPoint object to use + * @returns {H.geo.Point} - the created Point instance + */ + static fromIPoint(iPoint: IPoint): Point; + + lat: H.geo.Latitude; + lng: H.geo.Longitude; + alt: H.geo.Altitude; + ctx: H.geo.AltitudeContext; + } + + /** + * This class represents a rectangular geographic area. The area is defined by four geographical coordinates two (left, right) longitudes and two (top, bottom) latitudes. + */ + export class Rect { + /** + * Constructor + * @param top {H.geo.Latitude} - the northern-most latitude + * @param left {H.geo.Longitude} - the left-most longitude + * @param bottom {H.geo.Latitude} - the southern-most latitude + * @param right {H.geo.Longitude} - the right-most latitude + */ + constructor(top: H.geo.Latitude, left: H.geo.Longitude, bottom: H.geo.Latitude, right: H.geo.Longitude); + + /** + * To compare this rectangle with a supplied other rectangle for equality. + * @param other {H.geo.Rect} + * @returns {boolean} - Whether the two rectangles are equal. + */ + equals(other: H.geo.Rect): boolean; + + /** + * Toclone this rectangle. + * @returns {H.geo.Rect} + */ + clone(): H.geo.Rect; + + /** + * This method returns the top-left corner of the rectangular area. + * @returns {H.geo.Point} - the top-left corner of the area + */ + getTopLeft(): H.geo.Point; + + /** + * This method returns the bottom-right corner of the rectangular area. + * @returns {H.geo.Point} - the bottom-right corner of the area + */ + getBottomRight(): H.geo.Point; + + /** + * This method returns the north-most latitude of this rectangular area + * @returns {H.geo.Latitude} - the north-most latitude of the area + */ + getTop(): H.geo.Latitude; + + /** + * This method returns the south-most latitude of this rectangular area + * @returns {H.geo.Latitude} - the south-most latitude of the area + */ + getBottom(): H.geo.Latitude; + + /** + * This method returns the left-most longitude of this rectangular area + * @returns {H.geo.Longitude} - the left-most longitude of the area + */ + getLeft(): H.geo.Longitude; + + /** + * This method returns the right-most longitude of this rectangular area + * @returns {H.geo.Longitude} - the right-most longitude of the area + */ + getRight(): H.geo.Longitude; + + /** + * This method returns the center point of this rectangular area + * @returns {H.geo.Point} - the center point of the area + */ + getCenter(): H.geo.Point; + + /** + * Returns this width of this rectangular area in decimal degrees. + * @returns {number} - the width of this area + */ + getWidth(): number; + + /** + * Returns this height of this rectangular area in decimal degrees. + * @returns {number} - the height of this area + */ + getHeight(): number; + + /** + * Returns a boolean value indicating whether this rectangular area spans across the date border. + * @returns {boolean} - true if the area spans across the date border, otherwise false + */ + isCDB(): boolean; + + /** + * The method checks if the area enclosed by the given bounding box is 0. + * @returns {boolean} - true if the dimensions of the area a 0, otherwise false + */ + isEmpty(): boolean; + + /** + * This method checks if the latitude and longitude supplied by the caller lie within the area of this rectangular area. + * @param lat {H.geo.Latitude} - the latitude + * @param lng {H.geo.Longitude} - the longitude + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the latitude and longitude are contained in this area, otherwise false + */ + containsLatLng(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_skipValidation?: boolean): boolean; + + /** + * This method checks if the point supplied by the caller lies within the area of this rectangular area. + * @param geoPoint {H.geo.IPoint} - the point + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the point is contained in this area, otherwise false + */ + containsPoint(geoPoint: H.geo.IPoint, opt_skipValidation?: boolean): boolean; + + /** + * This method checks if the rectangular area supplied by the caller is completely contained within the area of this rectangular area. + * @param geoRect {H.geo.Rect} - the rectangular area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - true if the rectangular area is contained in this area, otherwise false + */ + containsRect(geoRect: H.geo.Rect, opt_skipValidation?: boolean): boolean; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the latitude and longitude supplied by the caller. + * @param lat {H.geo.Latitude} - the latitude + * @param lng {H.geo.Longitude} - the longitude + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeLatLng(lat: H.geo.Latitude, lng: H.geo.Longitude, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the point supplied by the caller. + * @param geoPoint {H.geo.IPoint} - the point to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergePoint(geoPoint: H.geo.IPoint, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the rectangular area supplied by the caller. + * @param geoRect {H.geo.Rect} - the point to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeRect(geoRect: H.geo.Rect, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method returns the smallest bounding box that covers this rectangular area and the rectangular area supplied by the caller. + * @param top {H.geo.Latitude} - The top latitude of the rectangle to merge + * @param left {H.geo.Longitude} - The left longitude of the rectangle to merge + * @param bottom {H.geo.Latitude} - The bottom latitude of the rectangle to merge + * @param right {H.geo.Longitude} - The right longitude of the rectangle to merge + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - either the rectangular area passed as out parameter or a new rectangular area + */ + mergeTopLeftBottomRight(top: H.geo.Latitude, left: H.geo.Longitude, bottom: H.geo.Latitude, right: H.geo.Longitude, opt_skipValidation?: boolean, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method checks if the intersection of two bounding boxes is non-empty. + * @param geoRect {H.geo.Rect} - a rectangular area to be tested for intersection with this rectangular area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {boolean} - a boolean value indicating whether the two areas intersect + */ + intersects(geoRect: H.geo.Rect, opt_skipValidation?: boolean): boolean; + + /** + * This method merges two rects by their values. The result of the merge is a bounding rect which covers all provided rect bounds. + * @param topA {H.geo.Latitude} - the northern-most latitude + * @param leftA {H.geo.Longitude} - the left-most longitude of operand A + * @param bottomA {H.geo.Latitude} - the southern-most latitude of operand A + * @param rightA {H.geo.Longitude} - the right-most latitude of operand A + * @param topB {H.geo.Latitude} - the northern-most latitude of operand B + * @param leftB {H.geo.Longitude} - the left-most longitude of operand B + * @param bottomB {H.geo.Latitude} - the southern-most latitude of operand B + * @param rightB {H.geo.Longitude} - the right-most latitude of operand B + * @param opt_out {H.geo.Rect=} - an optional rect to store the results + * @returns {H.geo.Rect} - either the opt_out rect or a new rect + */ + static merge(topA: H.geo.Latitude, leftA: H.geo.Longitude, bottomA: H.geo.Latitude, rightA: H.geo.Longitude, topB: H.geo.Latitude, leftB: H.geo.Longitude, bottomB: H.geo.Latitude, rightB: H.geo.Longitude, opt_out?: H.geo.Rect): H.geo.Rect; + + /** + * This method creates a rectangular area from a top-left and bottom-right point pair. + * @param topLeft {H.geo.IPoint} - the top-left corner of the area + * @param bottomRight {H.geo.IPoint} - the bottom-right corner of the area + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {H.geo.Rect} - returns the rectangular area defined by the top-left and bottom-right corners + */ + static fromPoints(topLeft: H.geo.IPoint, bottomRight: H.geo.IPoint, opt_skipValidation?: boolean): H.geo.Rect; + + /** + * This method creates the minimum rectangular area covering all of the points in the argument array. + * @param pointArray {Array} - the array of points to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {H.geo.Rect} - returns the minimum rectangular area covering the points or null if no point is covered + */ + static coverPoints(pointArray: Array, opt_skipValidation?: boolean): H.geo.Rect; + + /** + * This method creates the minimum rectangular area covering all of the coordinates in the argument array. + * @param latLngAltArray {Array} - the array of coordinates to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {(H.geo.Rect | undefined)} - returns the minimum rectangular area covering the coordinates + */ + static coverLatLngAlts(latLngAltArray: Array, opt_skipValidation?: boolean): H.geo.Rect | void; + + /** + * This method creates the minimum rectangular area covering all of the rectangular areas in the argument array. + * @param rectArray {Array} - the array of points to cover + * @param opt_skipValidation {boolean=} - a boolean flag indicating whether to check validity of the arguments + * @returns {(H.geo.Rect | undefined)} - returns the minimum rectangular area covering the rectangular areas + */ + static coverRects(rectArray: Array, opt_skipValidation?: boolean): H.geo.Rect | void; + + /** + * This method clones the given bounding rect and resizes the clone if necessary until the location supplied by the caller is at its center. + * @param center {H.geo.IPoint} - a point which is to be the center of the resized rectangular area + * @param opt_out {H.geo.Rect=} - an optional rectangular area to store the result + * @returns {H.geo.Rect} - the resized rectangular area + */ + resizeToCenter(center: H.geo.IPoint, opt_out?: H.geo.Rect): H.geo.Rect; + } + } + + /***** lang *****/ + + /***** map *****/ + export module map { + /** + * This class represents marker, which offers a means of identifying a location on the map with an icon. + */ + export class AbstractMarker extends H.map.Object { + /** + * Constructor + * @param position {H.geo.IPoint} - The location of this marker + * @param opt_options {H.map.AbstractMarker.Options=} - The values to initialize this marker + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.AbstractMarker.Options); + + /** + * This method returns this marker's current position. + * @returns {H.geo.Point} - current marker geo position + */ + getPosition(): H.geo.Point; + + /** + * This method sets the marker's current position. + * @param position {H.geo.IPoint} + * @returns {H.map.AbstractMarker} - the marker itself + */ + setPosition(position: H.geo.IPoint): H.map.AbstractMarker; + + /** + * Returns this marker's current icon. + * @returns {!(H.map.Icon | H.map.DomIcon)} + */ + getIcon(): (H.map.Icon | H.map.DomIcon); + + /** + * Sets the marker's current icon. + * @param icon {!(H.map.Icon | H.map.DomIcon)} - The new marker icon + * @returns {H.map.AbstractMarker} - the marker itself + */ + setIcon(icon: (H.map.Icon | H.map.DomIcon)): H.map.AbstractMarker; + } + + export module AbstractMarker { + /** + * Options used to initialize a AbstractMarker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {(H.map.Icon | H.map.DomIcon)=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.Icon | H.map.DomIcon; + data?: any; + } + } + + /** + * This class represents style attributes for arrows to be rendered along a polyline. A ArrowStyle instance is always treated as immutable to avoid inconstiencies and must not modified. + */ + export class ArrowStyle { + /** + * Constructor + * @param opt_options {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} + */ + constructor(opt_options?: (H.map.ArrowStyle | H.map.ArrowStyle.Options)); + + /** + * This method checks value-equality with another arrow style. + * @param other {(H.map.ArrowStyle | H.map.ArrowStyle.Options)} - the arrow style to compare with + * @returns {boolean} - true if the arrow styles are value-equal, otherwise false + */ + equals(other: (H.map.ArrowStyle | H.map.ArrowStyle.Options)): boolean; + } + + export module ArrowStyle { + /** + * An object type to specify the style of arrows to render along a polyline + * @property fillColor {string=} - The CSS color value used to fill the arrow shapes. If omitted or the value evaluates to false it defaults to "rgba(255, 255, 255, 0.75)" + * @property width {number=} - The width of the arrow shape. The value is taken as a factor of the width of the line, where the arrow description is applied. If omitted or the value is <= 0 it defaults to 1.2 + * @property length {number=} - The length of the arrow shapes. The value is taken as a factor of the width of the line at the end of which the arrow is drawn. If omitted or the value is <= 0 it defaults to 1.6 + * @property frequency {number=} - The frequency of arrow shapes. The value is taken as factor of the length of the arrow. A value of 1 results in gapless arrows. If omitted or the value is false it defaults to 5 + */ + export interface Options { + fillColor?: string; + width?: number; + length?: number; + frequency?: number; + } + } + + /** + * The class represents data model of the map. It holds list of layers that are rendered by map's RenderEngine. The class listens to 'update' events from layers and dispatches them to the RenderEngine. + */ + export class DataModel extends H.util.OList { + /** + * Constructor + * @param opt_layers {Array=} - array of layers to be added to the data model + */ + constructor(opt_layers?: Array); + } + + /** + * A visual representation of the H.map.DomMarker. + */ + export class DomIcon { + /** + * Constructor + * @param element {!(Element | string)} - The element or markup to use for this icon + * @param opt_options {H.map.DomIcon.Options=} + */ + constructor(element: (Element | string), opt_options?: H.map.DomIcon.Options); + } + + export module DomIcon { + /** + * Options used to initialize a DomIcon + * @property onAttach {function(Element, H.map.DomIcon, H.map.DomMarker)=} - A callback which is invoked before a clone of the icon's element is appended and displayed on the map. This callback can be used to setup the clone. + * @property onDetach {function(Element, H.map.DomIcon, H.map.DomMarker)=} - A callback which is invoked after a clone of the icon's element is removed from the map. This callback can be used to clean up the clone. + */ + export interface Options { + onAttach?: (el: Element, icon: H.map.DomIcon, marker: H.map.DomMarker) => void; + onDetach?: (el: Element, icon: H.map.DomIcon, marker: H.map.DomMarker) => void; + } + } + + /** + * A marker with a visual representation in the form of a full styleable and scripteable DOM element. DomMarker are predestinated if small amounts of markers with dynamic styled and/or scripted icons should be displayed om the map (e.g. animated interactive SVG). + */ + export class DomMarker extends H.map.AbstractMarker { + /** + * Constructor + * @param position {H.geo.IPoint} + * @param opt_options {H.map.DomMarker.Options=} + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.DomMarker.Options); + } + + export module DomMarker { + /** + * Options used to initialize a DomMarker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {H.map.DomIcon=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.DomIcon; + data?: any; + } + } + + /** + * This class represents a map object which can contain other map objects. It's visibility, zIndex and object-order influences the contained map objects + */ + export class Group extends H.map.Object { + /** + * Constructor + * @param opt_options {H.map.Group.Options=} - an optional object containing initialization values + */ + constructor(opt_options?: H.map.Group.Options); + + /** + * + * @param callback {function(!H.map.Object, number, !H.map.Group)} + * @param opt_recursive {boolean=} - Indicates whether sub groups should be traversed recursively + * @param opt_context {*=} - The context to use as "this" within the callback + */ + forEach(callback: (object: H.map.Object, n: number, group: H.map.Group) => void, opt_recursive?: boolean, opt_context?: any): void; + + /** + * To get a list of all objects of this group. On groups with many chilren this method can cause a higher memory and CPU consumption. Alternatively you case use H.map.Group#forEach + * @param opt_recursive {boolean=} - Indicates whether objects in sub-groups are also collected . + * @returns {!Array} + */ + getObjects(opt_recursive?: boolean): Array; + + /** + * Method returns the bounding rectangle for the group. The rectangle is the smallest rectangle that covers all objects. If group doesn't contains objects method returns null. + * @returns {H.geo.Rect} - geo ractangle that covers all objects in the group + */ + getBounds(): H.geo.Rect; + + /** + * To add an object to this group. + * @param object {!H.map.Object} + * @returns {!H.map.Object} - a reference to the appended object + */ + addObject(object: H.map.Object): H.map.Object; + + /** + * Appends a list of objects to this group + * @param objects {Array} + */ + addObjects(objects: Array): void; + + /** + * Removes an object from this group. + * @param object {!H.map.Object} - The object to remove + * @returns {!H.map.Object} - a reference to the removed object + */ + removeObject(object: H.map.Object): H.map.Object; + + /** + * Removes objects from this group. + * @param objects {!Array} - The list of objects to remove + */ + removeObjects(objects: Array): void; + + /** + * Method removes all objects from the group. + */ + removeAll(): void; + } + + export module Group { + /** + * Options used to initialize a group + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + * @property objects {Array=} - A list of map objects to add initially to this group. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + objects?: Array; + } + } + + /** + * This class represents an area that objects, like a marker, occupies in the screen space, meaning that object can be probed and returned by H.Map@getObjectsAt method. + */ + export class HitArea { + /** + * Constructor + * @param shapeType {H.map.HitArea.ShapeType} - The shape type of the HitArea + * @param opt_values {Array=} - The type-dependent values to define the shape of the hit area. The format for the different types are: + */ + constructor(shapeType: H.map.HitArea.ShapeType, opt_values?: Array); + } + + export module HitArea { + /** + * Enumeration represents possible shape types that HitArea can have. + */ + export enum ShapeType { + NONE, + RECT, + CIRCLE, + POLYGON, + } + } + + /** + * Control interface defines method which are used for direct view or camera manipulation + */ + export interface IControl { + + /** + * This method starts control action for camera. This action allows to control camera animation and movement according to provided values in the H.map.IControl#control function + * @param opt_kinetics {H.util.kinetics.IKinetics=} - kinetics settings + * @param opt_atX {number=} - control starts at x screen coordinate + * @param opt_atY {number=} - control starts at y screen coordinate + */ + startControl(opt_kinetics?: H.util.kinetics.IKinetics, opt_atX?: number, opt_atY?: number): void; + + /** + * This method triggers single control action on engine. This will trigger an animation which will start modification of the view's or camera's properties according to values begin set. Modification will occur at every frame. The speed values are measure by 'levels per frame' were 1 level cooresponds to a distance to next zoom level. + * @param moveX {number} - moves the view/cam in right/left direction + * @param moveY {number} - moves the view/cam in bottom/top direction + * @param moveZ {number} - moves the view/cam in depth direction (changes zoom level) + * @param angleX {number} - rotates cam over x-axis + * @param angleY {number} - rotates cam over y-axis + * @param angleZ {number} - rotates cam over z-axis + * @param zoom {number} - changes current zoom level (for view works as moveZ) + * @param opt_timestamp {number=} + */ + control(moveX: number, moveY: number, moveZ: number, angleX: number, angleY: number, angleZ: number, zoom: number, opt_timestamp?: number): void; + + /** + * This method ends current control, which will stop ongoing animation triggered by the startControl method. This method can prevent kinetics as well as it can adjust the final view if the adjust function is being passed. + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics animation + * @param opt_adjustView {function(H.map.ViewModel.CameraData)=} - user defined function which can adjust the final view this function takes last requestedData from the view model and should return a modified H.map.ViewModel.CameraData which will be set as the final view + */ + endControl(opt_preventKinetics?: boolean, opt_adjustView?: (data: H.map.ViewModel.CameraData) => void): void; + } + + /** + * An interface to specify a copyright note + * @property label {string} - A short textual representation of the copyright note, e.g. "DigitalGlobe 2009" + * @property alt {string} - A detailed textual representation of the copyright note, e.g. "copyright 2009 DigitalGlobe, Inc." + */ + export interface ICopyright { + label: string; + alt: string; + } + + /** + * Interface describes interaction with the view port. Interaction will reflect view change depending on the interaction coordinates passed and the modifiers which specify the type of interaction. + */ + export interface IInteraction { + /** + * This method starts the interaction with the view port. Should be called every time when new interaction is started i.e mouse grab, or touch start. + * @param modifiers {number} - a bitmask which specifies what operations should performed during every interaction + * @param opt_kinetics {H.util.kinetics.IKinetics=} - specifies kinetic move at the end of interaction + */ + startInteraction(modifiers: H.math.BitMask, opt_kinetics?: H.util.kinetics.IKinetics): void; + + /** + * This method resolves direct screen (view port) interaction. This function will modify the current view according to values passed in. + * @param x {number} - viewport x coordinate + * @param y {number} - viewport y coordinate + * @param opt_bx {number=} - x coordinate for second pointer/touch if present + * @param opt_by {number=} - y coordinate for secong pointer/touch if present + * @param opt_timestamp {number=} - known timestamp which should be passed + */ + interaction(x: number, y: number, opt_bx?: number, opt_by?: number, opt_timestamp?: number): void; + + /** + * This method ends interaction and applies kinetic movement if defined by using startInteraction method + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics behaviour at the end of interaction + */ + endInteraction(opt_preventKinetics?: boolean): void; + } + + /** + * A visual representation of the H.map.Marker. + */ + export class Icon { + /** + * Constructor + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @param opt_options {H.map.Icon.Options=} + */ + constructor(bitmap: (string | HTMLImageElement | HTMLCanvasElement), opt_options?: H.map.Icon.Options); + + /** + * Returns the icon's bitmap loading state + * @returns {H.map.Icon.prototype.State} + */ + getState(): H.map.Icon.State; + + /** + * Returns the bitmap of this icon or null if the bitmap is not ready yet (see H.map.Icon#getState) + * @returns {?(HTMLImageElement | HTMLCanvasElement)} + */ + getBitmap(): (HTMLImageElement | HTMLCanvasElement); + + /** + * Returns the size of this icon or null if a size wasn't specified in the constructor's options and the state of this icon is not H.map.Icon.prototype.State.READY + * @returns {?H.math.Size} + */ + getSize(): H.math.Size; + + /** + * Returns the anchor point of this icon or null if an anchor wasn't specified in the constructor's options and the state of this icon is not H.map.Icon.prototype.State.READY. + * @returns {?H.math.Point} + */ + getAnchor(): H.math.Point; + + /** + * Returns the hit area of the icon. + * @returns {?H.map.HitArea} - icon's anchor point + */ + getHitArea(): H.map.HitArea; + + /** + * This method allows to listen for specific event triggered by the object. Keep in mind, that you must removeEventListener manually or dispose an object when you no longer need it. Otherwise memory leak is possible. + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + addEventListener(type: string, handler: Function, opt_capture?: boolean, opt_scope?: Object): void; + + /** + * This method will removed previously added listener from the event target + * @param type {string} - name of event + * @param handler {Function} - previously added event handler + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + removeEventListener(type: string, handler: Function, opt_capture?: boolean, opt_scope?: Object): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Icon { + /** + * The state types of an Icon + */ + export enum State { + ERROR, + LOADING, + READY, + } + + /** + * Options used to initialize a Icon + * @property size {H.math.ISize=} - The icon's size in pixel, default is the bitmap's natural size + * @property anchor {H.math.IPoint=} - The anchorage point in pixel, default is bottom-center + * @property hitArea {H.map.HitArea=} - The area to use for hit detection, default is the whole rectangular area + * @property asCanvas {H.map.HitArea=} - Indicates whether a non canvas bitmap is converted into a canvas, default is true. The conversion improves the rendering performance but it could also cause a higher memory consumption. + * @property crossOrigin {boolean} - Specifies whether to use anonynous Cross-Origin Resource Sharing (CORS) when fetching an image to prevent resulting canvas from tainting, default is false. The option is ignored by IE9-10. + */ + export interface Options { + size?: H.math.ISize; + anchor?: H.math.IPoint; + hitArea?: H.map.HitArea; + asCanvas?: H.map.HitArea; + crossOrigin: boolean; + } + } + + /** + * This class encapsulates the brand, copyright and terms of use elements on the map. + */ + export class Imprint { + /** + * Constructor + * @param map {H.Map} - The map where the imprint is attached to + * @param opt_options {H.map.Imprint.Options=} - The options to style the imprint + */ + constructor(map: H.Map, opt_options?: H.map.Imprint.Options); + + /** + * To set the imprint options. If no opt_options argument is defined then all values are reset to their defaults. + * @param opt_options {H.map.Imprint.Options=} - The options to style the imprint + */ + setOptions(opt_options?: H.map.Imprint.Options): void; + + /** + * This method retrieves the copyright string for the current view of the map. + * @returns {string} - The copyright string for the current map view + */ + getCopyrights(): string; + + /** + * To get the CSS style declaration of the imprint DOM element + * @returns {CSSStyleDeclaration} + */ + getStyle(): CSSStyleDeclaration; + + /** + * Method adds a callback which will be triggered when the object is disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRatio {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {function(HTMLCanvasElement=)} - Callback function to call once result of the capturing is ready + * @param opt_errback {function(string)=} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRatio: number, callback?: (canvas: HTMLCanvasElement) => void, opt_errback?: (s: string) => void): void; + } + + export module Imprint { + /** + * Options to style an imprint + * @property invert {boolean=} - Indicates whether the logo is inverted. If omitted the current value remains, default is false. + * @property font {string=} - The font of the text. If omitted the current value remains, default is "11px Arial,sans-serif". + * @property href {string=} - The URL of the "Terms of use" link. If omitted the current value remains, default is "http://here.com/terms". + */ + export interface Options { + invert?: boolean; + font?: string; + href?: string; + } + } + + /** + * A marker with a visual representation in the form of a bitmap icon. Marker are predestinated if large amounts of markers with static icons should be displayed om the map. + */ + export class Marker extends H.map.AbstractMarker { + /** + * Constructor + * @param position {H.geo.IPoint} - The location of this marker + * @param opt_options {H.map.Marker.Options=} - The values to initialize this marker + */ + constructor(position: H.geo.IPoint, opt_options?: H.map.Marker.Options); + } + + export module Marker { + /** + * Options used to initialize a Marker + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property icon {H.map.Icon=} - The icon to use for the visual representation, if omitted a default icon is used. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + icon?: H.map.Icon; + data?: any; + } + } + + /** + * This class represents the abstract base class for map objects such as polylines, polygons, markers, groups etc. + */ + export class Object extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.Object.Options=} - The values to initialize this object + */ + constructor(opt_options?: H.map.Object.Options); + + /** + * Returns the ID of this object. + * @returns {*} + */ + getId(): any; + + /** + * Sets the visibility of this object. + * @param opt_visibility {boolean=} - Indicates whether this map object should be visible. + * @returns {H.map.Object} - returns this object + */ + setVisibility(opt_visibility?: boolean): H.map.Object; + + /** + * Returns the visibility of this object. + * @param opt_effective {boolean=} - Indicates that the effective visibility is requested. In this case the visibility of all possible ancestor groups is also taken into account + * @returns {boolean} + */ + getVisibility(opt_effective?: boolean): boolean; + + /** + * Returns the z-index of this object. + * @returns {(number | undefined)} + */ + getZIndex(): number | void; + + /** + * To set the-index of this object. + * @param zIndex {(number | undefined)} + * @returns {H.map.Object} - returns this object + */ + setZIndex(zIndex?: number): H.map.Object; + + /** + * Compares two objects regarding their z-order, useful to sort a list of objects via Array's sort() method + * @param first {H.map.Object} - The first object to compare + * @param second {H.map.Object} - The second object to compare + * @returns {number} - If less then 0 the first object has a lower z-order. If equal 0 booth objects have the same z-order. If greater then 0 the first object has a higher z-order. + */ + static compareZOrder(first: H.map.Object, second: H.map.Object): number; + + /** + * Returns the parent group which contains this object or null if the object is not contained by any group. + * @returns {?H.map.Group} + */ + getParentGroup(): H.map.Group; + + /** + * The root object in which this object is attached or the object itself. + * @returns {!H.map.Object} + */ + getRootGroup(): H.map.Object; + + /** + * Checks whether the given object is an inclusive descendant of this object + * @param object {*} - The object that's being compared against. + * @returns {boolean} + */ + contains(object: any): boolean; + + /** + * The current provider of this object + * @returns {?H.map.provider.ObjectProvider} - the current provider + */ + getProvider(): H.map.provider.ObjectProvider; + + /** + * Returns the invalidations of this object + * @returns {H.map.provider.Invalidations} - an invalidation object + */ + getInvalidations(): H.map.provider.Invalidations; + + /** + * This method invalidates this map object. + * @param flags {H.math.BitMask} - The flags indicating the types of occurred changes + * @returns {boolean} - indicates whether a validtion was executed (only if the object has a provider) + */ + invalidate(flags: H.math.BitMask): boolean; + + /** + * This method returns previously stored arbitrary data from this object. + * @returns {*} - the previously stored data or undefined if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this map object + * @param data {*} - the data to be stored + * @returns {H.map.Object} - returns this map object instance + */ + setData(data: any): H.map.Object; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Object { + /** + * Options used to initialize a map object + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + } + + /** + * The major types of map objects + */ + export enum Type { + /** spatial object */ + ANY, + /** spatial object */ + OVERLAY, + /** spatial object */ + SPATIAL, + /** Marker object */ + MARKER, + /** DomMarker object */ + DOM_MARKER, + /** DomMarker object */ + GROUP, + } + } + + /** + * This class represents an overlay, which offers a bitmap that covers a geographical reactangular area on the map. + */ + export class Overlay extends H.map.Object { + /** + * Constructor + * @param bounds {H.geo.Rect} - The geographical reactangular area of this overlay + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @param opt_options {H.map.Overlay.Options=} - Optional values values to initialize this overlay + */ + constructor(bounds: H.geo.Rect, bitmap: (string | HTMLImageElement | HTMLCanvasElement), opt_options?: H.map.Overlay.Options); + + /** + * This method returns this overlay's current bounds. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + + /** + * This method sets the overlay's current bounds. + * @param bounds {H.geo.Rect} + * @returns {H.map.Overlay} - the overlay itself + */ + setBounds(bounds: H.geo.Rect): H.map.Overlay; + + /** + * Returns this overlay's current bitmap. + * @returns {?(HTMLImageElement | HTMLCanvasElement)} - the bitmap of this Overlay or null if it isn't ready yet + */ + getBitmap(): (HTMLImageElement | HTMLCanvasElement); + + /** + * Sets the overlay's current bitmap. + * @param bitmap {!(string | HTMLImageElement | HTMLCanvasElement)} - Either an image URL, a SVG markup, an image or a canvas. + * @returns {H.map.Overlay} - the overlay itself + */ + setBitmap(bitmap: (string | HTMLImageElement | HTMLCanvasElement)): H.map.Overlay; + + /** + * Returns this overlay's current opacity. + * @returns {number} + */ + getOpacity(): number; + + /** + * Sets the overlay's current opacity. + * @param opacity {number} - The opacity in range from 0 (transparent) to 1 (opaque). + * @returns {H.map.Overlay} - the overlay itself + */ + setOpacity(opacity: number): H.map.Overlay; + } + + export module Overlay { + /** + * Options used to initialize an Overlay + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property opacity {number=} - The opacity of the object in range from 0 (transparent) to 1 (opaque), default is 1. + * @property visibility {boolean=} - Indicates whether the map object is visible at all, default is true. + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + min?: number; + max?: number; + opacity?: number; + visibility?: boolean; + zIndex?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * This class represents a spatial map object which provides its projected geometry. + */ + export class Spatial extends H.map.Object { + /** + * Constructor + * @param isClosed {boolean} - Indicates whether this spatial object represents a closed shape + * @param opt_options {H.map.Spatial.Options=} - The options to apply + */ + constructor(isClosed: boolean, opt_options?: H.map.Spatial.Options); + + /** + * To get the drawing style of this object. The returned style is treated as immutable and must not be modified afterwards to prevent inconsistancies! + * @returns {H.map.SpatialStyle} + */ + getStyle(): H.map.SpatialStyle; + + /** + * To set the drawing style of this object. If the passed opt_style argument is an instance of H.map.SpatialStyle it is treated as immutable and must not be modified afterwards to prevent inconsistancies! . + * @param opt_style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - The style to set. If it evaluates to a falsy the H.map.SpatialStyle.DEFAULT_STYLE is used. + * @returns {H.map.Spatial} - the Spatial instance itself + */ + setStyle(opt_style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): H.map.Spatial; + + /** + * To get the arrow style of this spatial object or undefined if no style is defined. A returned arrow style is treated as immutable and must not be modified afterwards to prevent inconsistancies! + * @returns {(H.map.ArrowStyle | undefined)} + */ + getArrows(): H.map.ArrowStyle | void; + + /** + * To set the arrow style of this object. + * @param opt_arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - the arrow style to be applied + * @returns {H.map.Spatial} - the Spatial instance itself + */ + setArrows(opt_arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options)): H.map.Spatial; + + /** + * Indicates whether this spatial object represents a closed shape + * @returns {boolean} + */ + isClosed(): boolean; + } + + export module Spatial { + /** + * Data to used as rendering hint for a label + * @property x {number} - The X coordinate of the first line's starting point + * @property y {number} - The Y coordinate of the first line's base line + * @property angle {number} - The clockwise rotation angle in radians + * @property font {string} - The CSS font-family + * @property size {number} - The CSS font-size + * @property color {string} - The CSS color + * @property text {string} - The text content, new line characters (\u000A) are interpreted as line breaks + */ + export interface Label { + x: number; + y: number; + angle: number; + font: string; + size: number; + color: string; + text: string; + } + + /** + * Options which are used to initialize spatial object object + * @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the spatial object + * @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the spatial. + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData. + */ + export interface Options { + style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options); + arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options); + visibility?: boolean; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * The SpatialStyle class represents a style with which spatial objects like polylines and polygons are drawn. A SpatialStyle instance is always treated as immutable to avoid inconstiencies and must not modified. + * @property strokeColor {string} - The color of the stroke in CSS syntax, default is 'rgba(0, 85, 170, 0.6)'. + * @property fillColor {string} - The filling color in CSS syntax, default is 'rgba(0, 85, 170, 0.4)'. + * @property lineWidth {number} - The width of the line in pixels, default is 2. + * @property lineCap {H.map.SpatialStyle.LineCap} - The style of the end caps for a line, default is 'round'. + * @property lineJoin {H.map.SpatialStyle.LineJoin} - The type of corner created, when two lines meet, default is 'miter'. + * @property miterLimit {number} - The miter length is the distance between the inner corner and the outer corner where two lines meet. The default is 10. + * @property lineDash {Array} - The line dash pattern as an even numbered list of distances to alternately produce a line and a space. The default is [ ]. + * @property lineDashOffset {number} - The phase offset of the line dash pattern The default is 0. + * @property MAX_LINE_WIDTH {number} - This constant represents the maximum line width which can be used for rendering. + * @property DEFAULT_STYLE {H.map.SpatialStyle} - This static member defines the default style for spatial objects on the map. It's value is { strokeColor: '#05A', fillColor: 'rgba(0, 85, 170, 0.4)' lineWidth: 1, lineCap: 'round', lineJoin: 'miter', miterLimit: 10, lineDash: [ ], lineDashOffset: 0 } + */ + export class SpatialStyle { + /** + * Constructor + * @param opt_options {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - The optional style attributes + */ + constructor(opt_options?: (H.map.SpatialStyle | H.map.SpatialStyle.Options)); + + /** + * This method checks value-equality with another style. + * @param other {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - the style to compare with + * @returns {boolean} - true if the styles are value-equal, otherwise false + */ + equals(other: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): boolean; + + /** + * Returns a copy of spatial style object and replaces the passed style attributes into it. + * @param opt_attributes {H.map.SpatialStyle.Options=} - The style attributes to set on the copied style instance + * @returns {H.map.SpatialStyle} + */ + getCopy(opt_attributes?: H.map.SpatialStyle.Options): H.map.SpatialStyle; + + strokeColor: string; + fillColor: string; + lineWidth: number; + lineCap: H.map.SpatialStyle.LineCap; + lineJoin: H.map.SpatialStyle.LineJoin; + miterLimit: number; + lineDash: Array; + lineDashOffset: number; + MAX_LINE_WIDTH: number; + DEFAULT_STYLE: H.map.SpatialStyle; + } + + export module SpatialStyle { + /** + * The style of the end caps for a line, one of 'butt', 'round' or 'square'. + */ + export type LineCap = 'butt' | 'round' | 'square'; + + /** + * The type of corner created, when two lines meet, one of 'round', 'bevel' or 'miter'. + */ + export type LineJoin = 'round' | 'bevel' | 'miter'; + + /** + * Options used to initialize a style. If a property is not set, the default value from H.map.SpatialStyle is taken. + * @property strokeColor {string=} - The color of the stroke in CSS syntax. + * @property fillColor {string=} - The color of the stroke in CSS syntax. + * @property lineWidth {number=} - The width of the line in pixels, default is 2. The maximum supported line width is 100. + * @property lineCap {H.map.SpatialStyle.LineCap=} - The style of the end caps for a line. + * @property lineJoin {H.map.SpatialStyle.LineJoin=} - The type of corner created, when two lines meet. + * @property miterLimit {number=} - The miter limit in pixel, default is 10. The maximum supported miter limit is 100 + * @property lineDash {Array} - The line dash pattern as an even numbered list of distances to alternately produce a line and a space. If the browser doesn't support this feature this style property is ignored. + * @property lineDashOffset {number=} - The phase offset of the line dash pattern + */ + export interface Options { + strokeColor?: string; + fillColor?: string; + lineWidth?: number; + lineCap?: H.map.SpatialStyle.LineCap; + lineJoin?: H.map.SpatialStyle.LineJoin; + miterLimit?: number; + lineDash: Array; + lineDashOffset?: number; + } + } + + /** + * This class represents a view of the map. It consists of a virtual camera and a look-at point both of which have a position in geo-space and orientation angles. The view model allows to change the values of these objects in order to move or rotate the map or zoom in and out. + */ + export class ViewModel extends H.util.EventTarget implements H.map.IControl { + /** + * This method returns the camera data, which is currently rendered. + * @returns {H.map.ViewModel.CameraData} - the current rendered camera data + */ + getCameraData(): H.map.ViewModel.CameraData; + + /** + * This method sets new camera data to be processed by the renderer. + * @param data {H.map.ViewModel.CameraData} - the values to be modified + * @returns {H.map.ViewModel} - this view model object + */ + setCameraData(data: H.map.ViewModel.CameraData): H.map.ViewModel; + + /** + * This method sets a new zoom level to be processed by the renderer + * @param zoom {number} - the new zoom level + * @param animate {boolean} + */ + setZoom(zoom: number, animate: boolean): void; + + /** + * This method returns the zoom level that is currently rendered. + * @returns {number} - current zoom level (scale) + */ + getZoom(): number; + + /** + * This method returns the currently requested data. + * @returns {H.map.ViewModel.CameraData} - last requested cam/view data + */ + getRequestedCameraData(): H.map.ViewModel.CameraData; + + /** + * A method to signal the begin of a control operation. + * @param opt_kinetics {H.util.kinetics.IKinetics=} - kinetics settings + * @param opt_atX {number=} - x screen coordinate at which control has started + * @param opt_atY {number=} - y screen coordinate at which control has started + */ + startControl(opt_kinetics?: H.util.kinetics.IKinetics, opt_atX?: number, opt_atY?: number): void; + + /** + * A method to set the values for a continuously modification of the ViewModel on different axes. If the current render engine doesn't support certain modifications then they are ignored. + * @param moveX {number} - The movement on x-axis as levels per millisecond where a level correlates to the distance between camera and look-at point. + * @param moveY {number} - The movement on y-axis as levels per millisecond where a level correlates to the distance between camera and look-at point + * @param moveZ {number} - The movement on z-axis as levels per millisecond. + * @param angleX {number} - The rotation of on screen's x axis as degrees per millisecond. + * @param angleY {number} - The rotation of on screen's y axis as degrees per millisecond. + * @param angleZ {number} - The rotation of on screen's z axis as degrees per millisecond. + * @param opt_zoom {number=} - The modification of the zoom level as levels per millisecond + */ + control(moveX: number, moveY: number, moveZ: number, angleX: number, angleY: number, angleZ: number, opt_zoom?: number): void; + + /** + * A method to signal the end of a control operation. + * @param opt_preventKinetics {boolean=} - A flag to indicate whether a kinetic effect is performed + * @param opt_adjustView {function(H.map.ViewModel.CameraData)=} - An callback to adjust the final ViewModel by modifying the passed camera data. + */ + endControl(opt_preventKinetics?: boolean, opt_adjustView?: (data: H.map.ViewModel.CameraData) => void): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module ViewModel { + /** + * Defines camera's properties. + * @property zoom {number=} - zoom level to be used by rendering engine + * @property position {H.geo.IPoint} - the position of the virtual camera in geo-space + * @property pitch {number=} - the rotation of the virtual camera along its local x-axis + * @property yaw {number=} - the rotation of the virtual camera along its local y-axis + * @property roll {number=} - the rotation of the virtual camera along its local z-axis + * @property fov {number=} - + */ + export interface CameraData { + zoom?: number; + position: H.geo.IPoint; + pitch?: number; + yaw?: number; + roll?: number; + fov?: number; + } + + /** + * Defines currently requested view data, which will be rendered by the map. + * @property camera {H.map.ViewModel.CameraData=} - The requested camera properties + * @property zoom {number=} - The requested zoom level + * @property animate {boolean=} - indicates if the requested transition should be animated + */ + export interface RequestedData { + camera?: H.map.ViewModel.CameraData; + zoom?: number; + animate?: boolean; + } + + /** + * Update event is fired whenever view model data is changed. It contains property which hold currently requested data + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class UpdateEvent extends H.util.Event { + /** + * Constructor + * @param requested {H.map.ViewModel.RequestedData} + */ + constructor(requested: H.map.ViewModel.RequestedData); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + } + + /** + * ViewPort object holds information about the HTML element where the map is rendered. It contains information regarding the element (view port) size and triggers events when the element size is changed. + * @property element {Element} - This property holds the HTML element, which defines the viewport. + * @property width {number} - This property holds this viewport's current width + * @property height {number} - This property holds this viewport's current height + * @property margin {number} - This property holds this viewport's current margin value + * @property padding {H.map.ViewPort.Padding} - This property holds this viewport's current padding + * @property center {H.math.Point} - This property holds this viewport's current center point + */ + export class ViewPort extends H.util.EventTarget implements H.map.IInteraction { + /** + * Constructor + * @param element {Element} - html element were map will be rendered + * @param opt_options {H.map.ViewPort.Options=} - optional configuration parameters + */ + constructor(element: Element, opt_options?: H.map.ViewPort.Options); + + /** + * This method sets the margin on the viewPort + * @param margin {number} - margin which is used to fetch map data + */ + setMargin(margin: number): void; + + /** + * This method sets the padding on the viewport. Padding will result in shifted map center which will be the visual center of the padded area. + * @param top {number} - padding from the top + * @param right {number} - padding from the right + * @param bottom {number} - padding from the bottom + * @param left {number} - padding from the left + */ + setPadding(top: number, right: number, bottom: number, left: number): void; + + /** + * This method updates size of the viewport according to container size. It must be called whenever the HTML element changed size in order to update the map's viewport values. + */ + resize(): void; + + /** + * This method starts the interaction with the view port. Should be called every time when new interaction is started i.e mouse grab, or touch start. + * @param modifiers {number} - a bitmask which specifies what operations should performed during every interaction + * @param opt_kinetics {H.util.kinetics.IKinetics=} - specifies kinetic move at the end of interaction + */ + startInteraction(modifiers: H.math.BitMask, opt_kinetics?: H.util.kinetics.IKinetics): void; + + /** + * This method resolves direct screen (view port) interaction. This function will modify the current view according to values passed in. + * @param x {number} - viewport x coordinate + * @param y {number} - viewport y coordinate + * @param opt_bx {number=} - x coordinate for second pointer/touch if present + * @param opt_by {number=} - y coordinate for secong pointer/touch if present + * @param opt_timestamp {number=} - known timestamp which should be passed + */ + interaction(x: number, y: number, opt_bx?: number, opt_by?: number, opt_timestamp?: number): void; + + /** + * This method ends interaction and applies kinetic movement if defined by using startInteraction method + * @param opt_preventKinetics {boolean=} - if set to true will prevent kinetics behaviour at the end of interaction + */ + endInteraction(opt_preventKinetics?: boolean): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + element: Element; + width: number; + height: number; + margin: number; + padding: H.map.ViewPort.Padding; + center: H.math.Point; + } + + export module ViewPort { + /** + * Options which may be used to initialize new ViewPort instance + * @property margin {number=} - The size in pixel of the supplemental area to render for each side of the map + * @property padding {H.map.ViewPort.Padding=} - The padding in pixels for each side of the map + * @property fixedCenter {boolean=} - Indicates whether the center of the map should remain unchanged if the viewport's size or or padding has been changed, default is true + */ + export interface Options { + margin?: number; + padding?: H.map.ViewPort.Padding; + fixedCenter?: boolean; + } + + /** + * Represents viewport padding definition. + * @property top {number} - the padding on the top edge (in pixels) + * @property right {number} - the padding on the right edge (in pixels) + * @property bottom {number} - the padding on the bottom edge (in pixels) + * @property left {number} - the padding on the left edge (in pixels) + */ + export interface Padding { + top: number; + right: number; + bottom: number; + left: number; + } + } + + export module layer { + /** + * BaseTileLayer encapsulates funcitonailty that is common to all layers that deliver tiles, such as H.map.layer.TileLayer. The functionality includes geo bounding box to grid calculation, tile request management. + */ + export class BaseTileLayer extends H.map.layer.Layer { + /** + * Constructor + * @param provider {H.map.provider.TileProvider} - data source for the TileLayer + * @param opt_options {H.map.layer.ITileLayer.Options=} - additional options + */ + constructor(provider: H.map.provider.TileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method returns the provider which feeds this layer with data. + * @returns {H.map.provider.TileProvider} - this layer's provider + */ + getProvider(): H.map.provider.TileProvider; + + /** + * This method transforms a geo-rectangle to geometrical projected rectangle at the current projection zoom level or at provided zoom level + * @param geoRect {H.geo.Rect} - geo bounds to be projected + * @param opt_zoom {number=} - overrides current projection zoom level + * @returns {H.math.Rect} - projected 2d space rect cooresponding to provided geo bounds + */ + geoRectToRect(geoRect: H.geo.Rect, opt_zoom?: number): H.math.Rect; + + /** + * This method returns tile grid for a bounding rectangle + * @param rectBounds {H.math.Rect} - projected rect bounds which coorespond to geo bounding box + * @param zoom {number} - current zoom level + * @returns {H.math.Rect} - rectangle which represents the tile grid bounds + */ + getTileBounds(rectBounds: H.math.Rect, zoom: number): H.math.Rect; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + + /** + * This method requests tiles from the data source (provider). It can return a set of tiles which are currently loaded. All tiles which are not yet loaded will be included in response as soon as they will be available during subsequent calls. + * @param tileBounds {H.math.Rect} - bounds in tile grid + * @param isCDB {boolean} + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - returns an array if tile which are already loaded + */ + getProviderTiles(tileBounds: H.math.Rect, isCDB: boolean, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + } + + /** + * This interface describes a layer which provides marker objects to the renderer. + */ + export interface IMarkerLayer { + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + export module IMarkerLayer { + /** + * This type represents a response object returned by the H.map.layer.IMarkerLayer#requestMarkers function. + * @property total {number} - The total number of markers, inclusive markers with not ready icons + * @property markers {Array} - The marker objects for the bounding rectangle (only ready) + */ + export interface Response { + total: number; + markers: Array; + } + + /** + * This type represents a response object returned by the H.map.layer.IMarkerLayer#requestMarkers function. + * @property number {number} - of returned tiles + * @property requested {number} - number of requested tiles + * @property objects {Array} - the marker objects within requested tiled area + */ + export interface TiledResponse { + number: number; + requested: number; + objects: Array; + } + } + + /** + * This interface describes a layer which provides data partitioned in quad-tree tiles in an x, y, z fashion (where z describes the level within the tree and x and y describe the absolute column and row indeces whithin the level). + */ + export interface ITileLayer { + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + } + + export module ITileLayer { + /** + * Options which are used to initialize a TileLayer object. + * @property projection {H.geo.IProjection=} - an optional projection to be used for this layer, default is H.geo.mercator + * @property opacity {number=} - tile layer opacity, default is 1 + */ + export interface Options { + projection?: H.geo.IProjection; + opacity?: number; + } + + /** + * A response object for a tile request. Contains total number of elements requested and an array of currently available Tiles + * @property total {number} - the total number of requested tiles + * @property tiles {Array} - the tiles which this provider can currently return synchronously + */ + export interface Response { + total: number; + tiles: Array; + } + } + + /** + * The Layer class represents an object that is evaluated by the renderer in the order in which it is added to the layers collection. It provides the basic infrastructure for dispatching update events to the renderer in case new data is available. + */ + export class Layer extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.layer.Layer.Options=} - optional configuration object + */ + constructor(opt_options?: H.map.layer.Layer.Options); + + /** + * This method checks if a zoom level can be served by this layer. + * @param zoomLevel {number} - the zoom level to check + * @returns {boolean} - true if this layer can provide data for the zoom level, otherwise false + */ + isValid(zoomLevel: number): boolean; + + /** + * This method sets the minimum zoom level for which this layer will provide tiles. + * @param min {number} - The new minimum zoom level of this layer + * @returns {H.map.layer.Layer} - Returns this instance of the layer + */ + setMin(min: number): H.map.layer.Layer; + + /** + * This method sets the maximum zoom level for which this layer will provide tiles. + * @param max {number} - The new maximum zoom level of this layer + * @returns {H.map.layer.Layer} - Returns this instance of the layer + */ + setMax(max: number): H.map.layer.Layer; + + /** + * This method returns the copyright of the current data provider. + * @param bounds {H.geo.Rect} - the bounding area for which to retrieve the copyright information + * @param level {number} - the zoom level for which to retrieve the copyright information + * @returns {Array} - a list of copyright information objects for the provided area and zoom level + */ + getCopyrights(bounds: H.geo.Rect, level: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module Layer { + /** + * Options which can be used when creating new layer object. + * @property min {number=} - The minimum zoom level for which the layer can provide data, default is 0 + * @property max {number=} - The maximum zoom level for which the layer can provide data, default is 22 + * @property dark {boolean=} - Indicates whether the content of this layer is mainly dark, default is false See also H.Map.Options#autoColor + * @property projection {H.geo.IProjection=} - The projection to be used for this layer, default is H.geo.mercator + * @property minWorldSize {number=} - The minimal world size at zoom level 0, default is 256 + */ + export interface Options { + min?: number; + max?: number; + dark?: boolean; + projection?: H.geo.IProjection; + minWorldSize?: number; + } + } + + /** + * ObjectTileLayer represents map objects which are requested on a tile basis + */ + export class MarkerTileLayer extends H.map.layer.BaseTileLayer implements H.map.layer.IMarkerLayer { + /** + * Constructor + * @param provider {H.map.provider.MarkerTileProvider} + * @param opt_options {H.map.layer.ITileLayer.Options=} + */ + constructor(provider: H.map.provider.MarkerTileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + /** + * This class represents a layer which renders map objects. Spatial objects like polygons and polylines a rendered to tiles before being passed to the enigne. Point objects like markers are provided as objects given an rectangular area. + */ + export class ObjectLayer extends H.map.layer.Layer implements H.map.layer.ITileLayer { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - the ObjectProvider which provides the map objects to this object layer. + * @param opt_options {H.map.layer.ObjectLayer.Options=} - The options for this layer + */ + constructor(provider: H.map.provider.ObjectProvider, opt_options?: H.map.layer.ObjectLayer.Options); + + /** + * This method returns current ObjectLayer's data provider + * @returns {H.map.provider.ObjectProvider} + */ + getProvider(): H.map.provider.ObjectProvider; + + /** + * To request overlay objects for the passsed bounding rectangle. It returns all overlay objects which are contained within this bounding rectangle. + * @param bounds {H.geo.Rect} - The bounding rectangle for which overlays are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ObjectLayer.OverlaysResponse} + */ + requestOverlays(bounds: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ObjectLayer.OverlaysResponse; + + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + /** + * This method requests a single tile according to tile coordinates. It returns either a Tile object if it is already loaded or undefined and starts loading the tile + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - The zoom level for which the tile is requested + * @param cacheOnly {boolean} - indicates whether only cached tiles are to be considered + * @returns {(H.map.provider.Tile | undefined)} - tile object corresponding to requested coordinates + */ + requestTile(x: number, y: number, z: number, cacheOnly: boolean): H.map.provider.Tile | void; + + /** + * This method cancels a previously requested tile. + * @param x {number} - tile row position + * @param y {number} - tile column position + * @param z {number} - zoom level + */ + cancelTile(x: number, y: number, z: number): void; + + /** + * This method requests marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + + /** + * This method requests dom marker objects for provided bounding rectangle. + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which marker are to be returned + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {(H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse)} - a response object containing the number of markers and the markers themselves + */ + requestDomMarkers(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): (H.map.layer.IMarkerLayer.Response | H.map.layer.IMarkerLayer.TiledResponse); + } + + export module ObjectLayer { + /** + * Configuration object which can be use to initialize the ObjectLayer. + * @property tileSize {number=} - the size of the tiles rendered by this layer for polylines and polygons (must be power of 2, default is 256) + * @property tileCacheSize {number=} - the number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property dataCacheSize {number=} - the number of tiles to cache which have render data only, default is 512 + * @property pixelRatio {number=} - The pixelRatio to use for over-sampling in cases of high-resolution displays + */ + export interface Options { + tileSize?: number; + tileCacheSize?: number; + dataCacheSize?: number; + pixelRatio?: number; + } + + /** + * A response object returned by the H.map.layer.ObjectLayer#requestOverlays function. + * @property total {number} - The total number of overlays within the requested bounds, inclusive overlays which are not ready loaded yet + * @property overlays {Array} - A list all overlays which are ready to render + */ + export interface OverlaysResponse { + total: number; + overlays: Array; + } + } + + /** + * Tile Layer, represents data shown on map on a tile basis. Can be used to show map tile images or other type of data which is partitioned into tiles. + * @event update {H.util.Event} + */ + export class TileLayer extends H.map.layer.BaseTileLayer implements H.map.layer.ITileLayer { + /** + * Constructor + * @param provider {H.map.provider.TileProvider} - data source for the TileLayer + * @param opt_options {H.map.layer.ITileLayer.Options=} - additional options + */ + constructor(provider: H.map.provider.TileProvider, opt_options?: H.map.layer.ITileLayer.Options); + + /** + * This method requests tiles for the current bounding rectangle at the given zoom level (z-value). + * @param boundingRect {H.geo.Rect} - the bounding rectangle for which tiles are to be returned + * @param zoomLevel {number} - The zoom level for which the tiles are requested + * @param cacheOnly {boolean} - Indicates whether only cached tiles are to be considered + * @param prioCenter {H.math.Point} - The priority center as an offset in screen pixel relative to the center + * @returns {H.map.layer.ITileLayer.Response} - a response object containing the total number of tiles requested and the tile objects that could be immediately returned + */ + requestTiles(boundingRect: H.geo.Rect, zoomLevel: number, cacheOnly: boolean, prioCenter: H.math.Point): H.map.layer.ITileLayer.Response; + + update: H.util.Event; + } + } + + export module provider { + /** + * An ImageTileProvider uses network service to provide bitmap images as tiles. + * @property tileSize {number} - Size of a tile image supported by the provider + */ + export class ImageTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param options {H.map.provider.ImageTileProvider.Options} - configuration for tile provider + */ + constructor(options: H.map.provider.ImageTileProvider.Options); + + tileSize: number; + } + + export module ImageTileProvider { + /** + * Options to initialize an ImageTileProvider instance + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number) : ?Array)=} - A function to replace the default implementation of H.map.provider.Provider#getCopyrights + * @property tileSize {number=} - The size of a tile as edge length in pixels. It must be 2^n where n is in range [0 ... 30], default is 256 + * @property getURL {function(number, number, number)} - The function to create an URL for the specified tile. If it returns a falsy the tile is not requested. + * @property crossOrigin {(string | boolean=)} - The CORS settings to use for the crossOrigin attribute for the image, if omitted or if the value evaluates to false no CORS settings are used. + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?: ((rect: H.geo.Rect, n: number) => Array); + tileSize?: number; + getURL: (n1: number, n2: number, n3: number) => string; + crossOrigin?: (string | boolean); + } + } + + /** + * This class represents invalidation states of a renderable object. A renderer can optimize its rendering strategies based on the information in this object. + * @property MARK_INITIAL {H.map.provider.Invalidations.Mark} - This constant represents the initial invalidation mark an invalidations object has. + */ + export class Invalidations { + + /** + * To update invalidation marks accordingly to the given the invalidation types. + * @param mark {H.map.provider.Invalidations.Mark} - The invalidation mark to set + * @param types {H.math.BitMask} - The descrete invalidation types to update + */ + update(mark: H.map.provider.Invalidations.Mark, types: H.math.BitMask): void; + + /** + * This method returns the current invalidation mark of this invalidations object. + * @returns {H.map.provider.Invalidations.Mark} - the current invalidation mark + */ + getMark(): H.map.provider.Invalidations.Mark; + + /** + * Checks whether any change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isAny(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a visual change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isVisual(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a spatial change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isSpatial(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether an add-operation occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isAdd(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a remove operation occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isRemove(since: H.map.provider.Invalidations.Mark): boolean; + + /** + * Checks whether a z-order change occurred after the specified since mark + * @param since {H.map.provider.Invalidations.Mark} - The invalidation mark to check against + * @returns {boolean} + */ + isZOrder(since: H.map.provider.Invalidations.Mark): boolean; + + static MARK_INITIAL: H.map.provider.Invalidations.Mark; + } + + export module Invalidations { + /** + * This enumeration encapsulates bit flags for different invalidations of map objects. + */ + export enum Flag { + NONE, + VISUAL, + SPATIAL, + ADD, + REMOVE, + Z_ORDER, + } + + /** + * The invalidation mark represents a counter which is increased whenever an invalidation takes place. + */ + export interface Mark { } + } + + /** + * A MarkerTileProvider uses network service to provide markers on tile basis. + * @property requestTile {} - Request data on a tile basis + * @property cancelTile {} - Cancels tile from being requested using x, y, z coordinates (column, row, zoom) + * @property cancelTileByKey {} - Cancels tile from being requested using a tile-key + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class MarkerTileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param options {H.map.provider.MarkerTileProvider.Options} - configuration for tile provider + */ + constructor(options: H.map.provider.MarkerTileProvider.Options); + + /** + * To signal to this provider that a map object has been changed. The method marks tile, that contains that object as invalid and triggers dispatchUpdate() + * @param marker {!H.map.AbstractMarker} - The map object to be invalidated + * @param flags {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(marker: H.map.AbstractMarker, flags: H.math.BitMask): void; + + /** + * Checks whether this provider is currently providing H.map.DomMarker map objects. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + } + + export module MarkerTileProvider { + /** + * Options which are used to initialize the MarkerTileProvider object. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property requestData {function(number, number, number, function(Array), Function) : H.util.ICancelable} - function that fetches marker data and creates array of H.map.AbstractMarker that is passed success callback, if function fails to fetch data onError callback must be called + * @property providesDomMarkers {boolean=} - indicates if markers provided are of type H.map.DomMarker or H.map.Marker, default is H.map.Marker + */ + export interface Options { + min?: number; + max?: number; + requestData: (n1: number, n2: number, n3: number, markerCallback: (markers: Array) => void, f: Function) => H.util.ICancelable; + providesDomMarkers?: boolean; + } + } + + /** + * An abstract class to manage and provide map objects (Marker, Polyline, Polygon) + */ + export class ObjectProvider extends H.map.provider.Provider { + /** + * Constructor + * @param opt_options {H.map.provider.Provider.Options=} + */ + constructor(opt_options?: H.map.provider.Provider.Options); + + /** + * Returns the accumulate invalidations of this provider's objects that have occurred. + * @param opt_type {H.map.Object.Type=} - The type of objects to consider for the invalidations. If undefined, all types are taken into account. + * @returns {H.map.provider.Invalidations} + */ + getInvalidations(opt_type?: H.map.Object.Type): H.map.provider.Invalidations; + + /** + * To signal to this provider that a map object has been changed. The method updates the Invalidations of this provider and the given map object and triggers dispatchUpdate() + * @param mapObject {!H.map.Object} - The map object to be invalidated + * @param changes {H.math.BitMask} - The flags indicating the types of occurred changes + */ + invalidateObject(mapObject: H.map.Object, changes: H.math.BitMask): void; + + /** + * Checks whether this provider is currently providing overlay map objects. A concrete implementation of ObjectProvider must override it if it currently provides overlays. + * @returns {boolean} + */ + providesOverlays(): boolean; + + /** + * Returns all Overlay objects which intersect with the provided area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestOverlays(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing spatial map objects. A concrete implementation of ObjectProvider must override it if it currently provides Spatials. + * @returns {boolean} + */ + providesSpatials(): boolean; + + /** + * Returns all polyline, polygon, circle and rect objects which intersect with the provided area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatials(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Returns the spatial objects which intersect the given tile + * @param tile {H.map.provider.SpatialTile} - The tile for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestSpatialsByTile(tile: H.map.provider.Tile, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing Marker map objects. A concrete implementation of ObjectProvider must override it if it currently provides Markers. + * @returns {boolean} + */ + providesMarkers(): boolean; + + /** + * Returns all Marker map objects which intersect with the provided rectangular area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestMarkers(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + + /** + * Checks whether this provider is currently providing DomMarker map objects. A concrete implementation of ObjectProvider must override it if it currently provides Markers. + * @returns {boolean} + */ + providesDomMarkers(): boolean; + + /** + * Returns all DomMarker map objects which intersect with the provided rectangular area. + * @param geoRect {H.geo.Rect} - A rectangular area in geo space to intersect with + * @param zoomLevel {number} - The zoom level for which the objects are requested + * @param visiblesOnly {boolean} - Indicates whether only invisible objects are to be considered + * @param cacheOnly {boolean} - Indicates whether only cached objects are to be considered + * @returns {Array} - a list of intersecting objects + */ + requestDomMarkers(geoRect: H.geo.Rect, zoomLevel: number, visiblesOnly: boolean, cacheOnly: boolean): Array; + } + + /** + * A Provider defines an object which works as a database for the map. Providers can exists in different forms they can implement client side object storage or they can request data from the remote service. + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class Provider extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.map.provider.Provider.Options=} + */ + constructor(opt_options?: H.map.provider.Provider.Options); + + /** + * This method returns the copyrights of the provided content for a certain geographical area at a specified zoom level. + * @param bounds {H.geo.Rect} - The bounding area for which to retrieve the copyright information + * @param level {number} - The zoom level for which to retrieve the copyright information + * @returns {?Array} - a list of copyright information objects for the provided area and zoom level + */ + getCopyrights(bounds: H.geo.Rect, level: number): Array; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + uri: string; + min: number; + max: number; + uid: string; + } + + export module Provider { + /** + * Options to initialize a Provider instance + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number) : ?Array)=} - A function to replace the default implementation of H.map.provider.Provider#getCopyrights + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?: (rect: H.geo.Rect, n: number) => Array; + } + } + + /** + * RemoteTileProvider is an abstract class which should be used by classes implementing data provision on a tile basis. Every child class needs to implement 'requestInternal' (to request remote tile) and 'getCache' (to provide configured cache object were tiled data is being cached) + */ + export class RemoteTileProvider extends H.map.provider.TileProvider { + /** + * Constructor + * @param options {H.map.provider.TileProvider.Options} - The options to instantiate this TileProvider + */ + constructor(options: H.map.provider.TileProvider.Options); + + /** + * This method returns cache which should be used to store tiles + * @returns {H.util.ICache} - cache + */ + getCache(): H.util.ICache; + + /** + * This method request tile from remote service + * @param x {number} - The row number of the tile + * @param y {number} - The column number of the tile + * @param z {number} - The zoom level for which the tile is requested + * @param onResponse {function((Array | HTMLImageElement | HTMLCanvasElement | ArrayBuffer | null), *=)} - function which is called after response arrives + * @param onError {function(string=)} - function which is called in case of communication error + * @param opt_priority {H.net.Request.Priority=} - optional request priority level + * @returns {H.util.ICancelable} + */ + requestInternal( + x: number, + y: number, + z: number, + + onResponse?: ( + object: Array | HTMLImageElement | HTMLCanvasElement | ArrayBuffer, + response: any + ) => void, + + onError?: (s: string) => void, + opt_priority?: H.net.Request.Priority + ): H.util.ICancelable; + + /** + * This method instructs the provider to reload data from it's source. + * @param hard {boolean} - a boolean flag indicating whether to invalidate in hard mode (true) or in soft mode (false); + */ + reload(hard: boolean): void; + } + + /** + * Generic Tile object which represents a part of the world fiting into the Tile area represented by the Tiel coordinates (x - row, y - column) and the zoom level (z). Number of tiles at particular zoom level (which means number of areas into world is being splitted) is defined as following: numberOfRows = numberOfColumns = 2^zoomlevel + * @property key {string} - Unique tile key generated by provider + * @property data {*} - Tile data (an image for example) + * @property valid {boolean} - This property holds a boolean flag indicating whether this tile is still valid (true) or whether it should be re-fetched (false) + * @property x {number} - Tile column + * @property y {number} - Tile row + * @property z {number} - Tile zoom level + */ + export class Tile { + /** + * Constructor + * @param x {number} - x tile coordinate (row) + * @param y {number} - y tile coordinate (column) + * @param z {number} - tile zoom level + * @param data {*} - generic data object which cooresponds to the given coordinates + */ + constructor(x: number, y: number, z: number, data?: any); key: string; + + data: any; + valid: boolean; + x: number; + y: number; + z: number; + } + + /** + * TileProvider is an abstract class to provide data on a tile basis + * @property requestTile {} - Request data on a tile basis + * @property cancelTile {} - Cancels tile from being requested using x, y, z coordinates (column, row, zoom) + * @property cancelTileByKey {} - Cancels tile from being requested using a tile-key + * @property uri {string} - This provider's unique resource identifier, if not provided at construction time it defaults to provider's uid + * @property min {number} - Minimum zoom level at which provider can serve data, set at construction time + * @property max {number} - Maximum zoom level at which provider can server data, set at construction time + * @property uid {string} - Provider instance unique identifier, generated at construction time + */ + export class TileProvider extends H.map.provider.Provider { + /** + * Constructor + * @param options {H.map.provider.TileProvider.Options} - The options to instantiate this TileProvider + */ + constructor(options: H.map.provider.TileProvider.Options); + + /** + * This method creates a tile object with given parameters + * @param x {number} - x tile coordinate (row) + * @param y {number} - y tile coordinate (column) + * @param z {number} - tile coordinate (zoom) + * @param data {(HTMLImageElement | HTMLCanvasElement)} - data for the tile + * @param opt_options {Object=} - free form options object. These options are meant to be used in tile specific rendering cases + * @returns {H.map.provider.Tile} + */ + createTileInternal(x: number, y: number, z: number, data: (HTMLImageElement | HTMLCanvasElement), opt_options?: { [key: string]: any }): H.map.provider.Tile; + + /** + * This method creates a tile key consisting of the provider's uri, and the tile's x, y and z coordinates, seperated by underscores e.g.: "4711_7_42_23" + * @param x {number} - The x tile coordinate (row) + * @param y {number} - The y tile coordinate (column) + * @param z {number} - The z tile coordinate (zoom level) + * @returns {string} - string + */ + getTileKey(x: number, y: number, z: number): string; + + requestTile: any; + cancelTile: any; + cancelTileByKey: any; + uri: string; + min: number; + max: number; + uid: string; + } + + export module TileProvider { + /** + * @property uri {string=} - The provider's unique resource identifier which must not contain an underscore "_". If omitted an auto-generated unique Session ID is used. If a cross sessions consistent IDs is needed (e.g. for storing provider data) this property must be specified. + * @property min {number=} - The minimal supported zoom level, default is 0 + * @property max {number=} - The maximal supported zoom level, default is 22 + * @property getCopyrights {(function(H.geo.Rect, number): Array)=} - A function to replace the default implememtation of H.map.provider.Provider#getCopyrights + * @property tileSize {number=} - The size of a tile as edge length in pixels. It must be 2^n where n is in range [0 ... 30], default is 256 + */ + export interface Options { + uri?: string; + min?: number; + max?: number; + getCopyrights?(rect: H.geo.Rect, number: number): Array; + tileSize?: number; + } + } + } + } + + /***** mapevents *****/ + export module mapevents { + /** + * Behavior class uses map events and adds behavior functionality to the map. This allows map panning and zooming via using mouse wheel + * @property DRAGGING {number} - Map responds to user dragging via mouse or touch + * @property WHEELZOOM {number} - Map zooms in or out in respond to mouse wheel events + * @property DBLTAPZOOM {number} - Map zooms in or out in response to double click or double tap. For double tap if more that one touches are on the screen map will zoom out. + */ + export class Behavior extends H.util.Disposable { + /** + * Constructor + * @param mapEvents {H.mapevents.MapEvents} - previously initialized map events instance + * @param options {H.mapevents.Behavior.Options} - additional options (i.e kinetics) + */ + constructor(mapEvents: H.mapevents.MapEvents, options?: H.mapevents.Behavior.Options); + + /** + * This method destroys all map interaction handling. Should be used when the behavior functionality is disposed. Behavior object will also be disposed (this function will be called) when attached H.mapevents.MapEvents object is dispose. + */ + dispose(): void; + + /** + * This method disables the behavior functionality for the map + * @param opt_behavior {number=} - The bitmask of behaviors to disable. If no arguments are passed, all behaviors will be disabled. + */ + disable(opt_behavior?: H.math.BitMask): void; + + /** + * This method re-enables the behavior functionality for the map. + * @param opt_behavior {number=} - The bitmask of behaviors to enable. If no arguments are passed, all behaviors will be enabled. + */ + enable(opt_behavior?: H.math.BitMask): void; + + /** + * This method checks if certain functionality is enabled + * @param behavior {number} - value like H.mapevents.Behavior.DRAGGING which the check is being performed + * @returns {boolean} + */ + isEnabled(behavior: number): boolean; + + static DRAGGING: number; + static WHEELZOOM: number; + static DBLTAPZOOM: number; + } + + export module Behavior { + /** + * Options which are used to initialize the Behavior class. + * @property kinetics {H.util.kinetics.IKinetics=} - The parameters for the kinetic movement. + * @property enable {number=} - The bitmask of behaviors to enable like H.mapevents.Behavior.DRAGGING. All are enabled by default. + */ + export interface Options { + kinetics?: H.util.kinetics.IKinetics; + enable?: H.math.BitMask; + } + } + + /** + * ContextMenuEvent should be fired, when a user right-clicks or longpresses on a map object. + * @property viewportX {Array} - Contains ContextItems, that will be used to create context menu entries. Should be filled by listeners of the "contextmenu" event + * @property viewportY {number} - Map viewport y position + * @property target {(H.map.Object | H.Map)} - Target for the event + * @property originalEvent {Event} - Original event + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class ContextMenuEvent extends H.util.Event { + /** + * Constructor + * @param viewportX {number} - The x coordinate on the viewport + * @param viewportY {number} - The y coordinate on the viewport + * @param target {(H.Map | H.map.Object)} - The event's target element + * @param originalEvent {Event} - target of the event + */ + constructor(viewportX: number, viewportY: number, target: (H.Map | H.map.Object), originalEvent: Event); + + viewportX: Array; + viewportY: number; + originalEvent: Event; + } + + /** + * Custom map event. Contains list of pointers on the map, list of changed pointers and original event. Inherits from H.util.Event. + * @property pointers {Array} - Pointers which are currently on the screen + * @property changedPointers {Array} - Pointers which has changed in course of event + * @property targetPointers {Array} - Pointers which are on same target as the current pointer + * @property currentPointer {H.mapevents.Pointer} - Current pointer + * @property originalEvent {Event} - Original event fired by the browser + * @property target {(H.map.Object | H.Map)} - Object which triggered event. Can be the map object (i.e marker or polyline) or the map itself + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param type {string} - type of event + * @param pointers {Array} - pointers which are currently on the screen + * @param changedPointers {Array} - pointers which changed during event + * @param targetPointers {Array} - pointers on the event target + * @param currentPointer {H.mapevents.Pointer} - pointer which triggered the event + * @param target {(H.Map | H.map.Object)} - target map object which triggered event + * @param originalEvent {Event} - original dom event + */ + constructor(type: string, pointers: Array, changedPointers: Array, targetPointers: Array, currentPointer: H.mapevents.Pointer, target: (H.Map | H.map.Object), originalEvent: Event); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + pointers: Array; + changedPointers: Array; + targetPointers: Array; + currentPointer: H.mapevents.Pointer; + originalEvent: Event; + target: (H.map.Object | H.Map); + currentTarget: (H.map.Object | H.Map); + type: string; + defaultPrevented: boolean; + } + + /** + * MapEvents enable the events functionality on the map and on the map objects. By using this extension it is possible to listen to events on map objects like markers, polylines, polygons, circles and on the map object itself. Events are triggered depending on user interaction. Please check the Events Summary section for the list of events fired by this class and by the map objects. + */ + export class MapEvents extends H.util.Disposable { + /** + * Constructor + * @param map {H.Map} - map instance which is used for firing events + */ + constructor(map: H.Map); + + /** + * This method destroys the MapEvents by removing all handlers from the map object. After calling this function mapEvents and map objects will not trigger any events. This object will be disposed automatically if the corresponding map object is disposed. + */ + dispose(): void; + + /** + * This method returns map into which events are attached + * @returns {H.Map} + */ + getAttachedMap(): H.Map; + } + + /** + * Class representing pointer on the map surface. A pointer in platform specific definition would mean either mouse, touch, pen or any pointing device which can trigger browser events. + * @property viewportX {number} - X coordinate on the map's viewport + * @property viewportY {number} - Y coordinate on the map's viewport + * @property target {(H.map.Object | H.Map)} - Map object directly under the pointer. Can be null if if pointer is out of the map viewport + * @property id {number} - Pointer unique identifier. + * @property type {string} - Pointer type can be: 'mouse', 'touch' or 'pen' + * @property dragTarget {(H.map.Object | H.Map)} - Object which is currently dragged by the pointer + * @property button {H.mapevents.Pointer.Button} - Indicates which pointer device button has changed. + */ + export class Pointer { + /** + * Constructor + * @param viewportX {number} - pointer position on x-axis + * @param viewportY {number} - pointer position on y-axis + * @param id {number} - unique pointer identifier among currently available pointers + * @param type {string} - type of pointer can be i.e 'mouse', 'touch'. 'pen' + * @param opt_button {H.mapevents.Pointer.Button=} - Indicates which pointer device button has changed. + * @param opt_buttons {number=} - Indicates which pointer device buttons are being pressed, expressed as a bitmask. Uses the same values, as "buttons" in Pointer Events spec. + */ + constructor(viewportX: number, viewportY: number, id: number, type: string, opt_button?: H.mapevents.Pointer.Button, opt_buttons?: H.math.BitMask); + static viewportX: number; + static viewportY: number; + static target: (H.map.Object | H.Map); + static id: number; + static type: string; + static dragTarget: (H.map.Object | H.Map); + static button: H.mapevents.Pointer.Button; + } + + export module Pointer { + /** + * Types of a button + */ + export enum Button { + /** No button */ + NONE, + /** Left mouse button or touch contact or pen contact */ + LEFT, + /** Middle mouse button */ + MIDDLE, + /** Right mouse button or Pen barrel button */ + RIGHT, + } + + /** + * Indicates which pointer device buttons are being pressed, expressed as a bitmask. Bit values are: + * + * - 0: No button pressed + * - 1: Left mouse button pressed, or Touch contact or Pen contact + * - 2: Right mouse button pressed, or Pen contact with barrel button pressed + * - 4: Middle mouse button pressed + */ + // TODO not sure this is the right interpretation of the docs + export type Buttons = H.math.BitMask; + } + + /** + * WheelEvent is fired when the mouse wheel is used over the map. It contains information about cursor position and the map object which resides directly under the cursor. + * @property delta {number} - Wheel move delta + * @property viewportX {number} - Map viewport x position + * @property viewportY {number} - Map viewport y position + * @property target {(H.map.Object | H.Map)} - Target for the event + * @property originalEvent {Event} - Original mouse wheel event + * @property currentTarget {(H.map.Object | H.Map)} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class WheelEvent extends H.util.Event { + /** + * Constructor + * @param deltaY {number} - The wheel move delta on y-axis + * @param viewportX {number} - The x coordinate on the viewport + * @param viewportY {number} - The y coordinate on the viewport + * @param target {(H.Map | H.map.Object)} - The event's target element + * @param originalEvent {Event} - target of the event + */ + constructor(deltaY: number, viewportX: number, viewportY: number, target: (H.Map | H.map.Object), originalEvent: Event); + + delta: number; + viewportX: number; + viewportY: number; + originalEvent: Event; + } + } + + /***** math *****/ + export module math { + /** + * A signed 32 bit integer (JS restriction) where bit operator can be applied to. The range is [-2,147,483,648 ... 2,147,483,647] or [-2^31 ... 2^31 − 1] + */ + export type BitMask = number; + + /** + * An interface for a 2-dimensional point consisting a x and y coordinate. + * @property x {number} - The point's coordinate on X-axis. + * @property y {number} - The point's coordinate on Y-axis. + */ + export interface IPoint { + x: number; + y: number; + } + + /** + * An interface for a 2-dimensional size consisting a with and a height. + * @property w {number} - The size's width. + * @property h {number} - The size's height. + */ + export interface ISize { + w: number; + h: number; + } + + /** + * Class represents a 2-dimensional point, defined by x and y coordinates. + * @property x {number} - The point's coordinate on X-axis. + * @property y {number} - The point's coordinate on Y-axis. + */ + export class Point implements IPoint { + /** + * Constructor + * @param x {number} - The point's coordinate on X-axis. + * @param y {number} - The point's coordinate on Y-axis. + */ + constructor(x: number, y: number); + + /** + * Sets the x and y coordinate of this point + * @param x {number} - The point's coordinate on X-axis. + * @param y {number} - The point's coordinate on Y-axis. + */ + set(x: number, y: number): void; + + /** + * This method creates a copy of the current point. + * @param opt_out {H.math.Point=} - An optional point to store the copied values + * @returns {H.math.Point} - The clone of the point + */ + clone(opt_out?: Point): Point; + + /** + * This method adds given point coordinates to the current one. + * @param other {H.math.IPoint} - The point to add + * @returns {H.math.Point} - the point itself after adding + */ + add(other: IPoint): Point; + + /** + * This method subtracts given point coordinates from the current point. + * @param other {H.math.IPoint} - The point to subtract + * @returns {H.math.Point} - the point itself after subtracting + */ + sub(other: IPoint): Point; + + /** + * This method scales the current point coordinates by the given factor(s). + * @param factor {number} - multiplication factor + * @param opt_factorY {number=} - If omitted, the factor argument is used + * @returns {H.math.Point} - the point itself after scaling + */ + scale(factor: number, opt_factorY?: number): Point; + + /** + * This method rounds the x and y coordinates of the point. + * @returns {H.math.Point} - the point itself after rounding + */ + round(): Point; + + /** + * Rounds the x and y coordinates to the next smaller integer values. + * @returns {H.math.Point} - the point itself after flooring + */ + floor(): Point; + + /** + * Rounds the x and y coordinates to the next greater integer values. + * @returns {H.math.Point} - the point itself after ceiling + */ + ceil(): Point; + + /** + * This method compares current point coordinates with the supplied point coordinates. + * @param other {H.math.IPoint} - The point to compare to. + * @returns {boolean} - True if the points are equal + */ + equals(other: IPoint): boolean; + + /** + * Calculates the closest point on a given line + * @param start {H.math.IPoint} - The start point of the line + * @param end {H.math.IPoint} - The end point of the line + * @returns {H.math.IPoint} - the closest point + */ + getNearest(start: IPoint, end: IPoint): IPoint; + + /** + * This method calculates the distance to a point supplied by the caller. + * @param other {H.math.IPoint} + * @returns {number} + */ + distance(other: IPoint): number; + + /** + * This method creates a Point instance from a given IPoint object. + * @param iPoint {H.math.IPoint} - The IPoint object to use + * @returns {H.math.Point} - the created Point instance + */ + static fromIPoint(iPoint: IPoint): Point; + + x: number; + y: number; + } + + /** + * Class defines a rectangle in 2-dimensional geometric space. It is used to represent the area in projected space. + */ + export class Rect { + /** + * Constructor + * @param left {number} - The rectangle's left edge x value + * @param top {number} - The rectangle's top edge y value + * @param right {number} - The rectangle's right edge x value + * @param bottom {number} - The rectangle's bottom edge y value + */ + constructor(left: number, top: number, right: number, bottom: number); + + /** + * To set all values of the rectangle's edges + * @param left {number} - The rectangle's left edge x value + * @param top {number} - The rectangle's top edge y value + * @param right {number} - The rectangle's right edge x value + * @param bottom {number} - The rectangle's bottom edge y value + */ + set(left: number, top: number, right: number, bottom: number): void; + + /** + * To get the rectangle's top-left vertex + * @returns {H.math.Point} + */ + getTopLeft(): H.math.Point; + + /** + * To get the rectangle's bottom-right vertex + * @returns {H.math.Point} + */ + getBottomRight(): H.math.Point; + + /** + * Method checks if provided coordinates lie within rectangle. + * @param x {number} - x-coordinate to check + * @param y {number} - y-coordinate to check + * @returns {boolean} - returns true if coordinates lie within rectangle, if parameters are isNaN returns false + */ + containsXY(x: number, y: number): boolean; + + /** + * To create a rectangle from a top-left and bottom-right point pair. + * @param topLeft {H.math.IPoint} - the top-left vertex of the rectanle + * @param bottomRight {H.math.IPoint} - the bottom-right vertex of the rectanle + * @returns {H.math.Rect} - returns the rectangular area defined by the top-left and bottom-right vertices + */ + static fromPoints(topLeft: H.math.IPoint, bottomRight: H.math.IPoint): H.math.Rect; + + /** + * To clone a rectangle + * @returns {H.math.Rect} + */ + clone(): H.math.Rect; + } + + /** + * Class for representing sizes consisting of a width and height. + * @property w {number} - The size's width value + * @property h {number} - The size's height value + */ + export class Size { + /** + * Constructor + * @param width {number} - Width. + * @param height {number} - Height. + */ + constructor(width: number, height: number); + w: number; + h: number; + } + } + + /***** net *****/ + export module net { + export module Request { + export enum State { + DONE = 2, + OPENED = 1, + UNSENT = 0, + } + + // TODO no idea how this interface is set up, investigate + export interface Priority { } + } + } + + /***** places *****/ + + /***** service *****/ + export module service { + /** + * Abstract rest service class + */ + export class AbstractRestService implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.AbstractRestService.Options=} + */ + constructor(opt_options?: H.service.AbstractRestService.Options); + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module AbstractRestService { + export interface Options { + + } + } + + /** + * This class encapsulates Enterprise Routing REST API as a service stub. An instance of this class can be retrieved by calling the factory method on a platform instance. H.service.Platform#getEnterpriseRoutingService. + */ + export class EnterpriseRoutingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.EnterpriseRoutingService.Options=} + */ + constructor(opt_options?: H.service.EnterpriseRoutingService.Options); + + /** + * This method sends a "calculateroute" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param calculateRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateRoute(calculateRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "getroute" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param getRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + getRoute(getRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "getlinkinfo" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param getLinkInfoParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + getLinkInfo(getLinkInfoParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + + /** + * This method sends a "calculateisoline" request to Enterprise Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occurred. + * @param calculateIsolineParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Enterprise Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateIsoline(calculateIsolineParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + } + + export module EnterpriseRoutingService { + /** + * @property subDomain {string=} - The sub-domain of the routing service relative to the platform's base URL (default is 'route') + * @property path {string=} - The path of the map tile service, default is "routing/7.2" + * @property baseUrl {H.service.Url=} - The base URL of the service, defaults to the the platform's base URL if instance was created using H.service.Platform#getEnterpriseRoutingService method. + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This class encapsulates the Geocoding REST API in a service stub with calls to its various resources implemented. + */ + export class GeocodingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.GeocodingService.Options=} + */ + constructor(opt_options?: H.service.GeocodingService.Options); + + /** + * This method sends a reverse geocoding request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param geoodingParams {H.service.ServiceParameters} - the service parameters to be sent with the geocoding request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + geocode(geoodingParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + + /** + * This method sends a reverse geocoding request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param reverseGeocodingParams {H.service.ServiceParameters} - the service parameters to be sent with the reverse geocoding request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + reverseGeocode(reverseGeocodingParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + + /** + * This method sends a landmark search request to Geocoder REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param searchParams {H.service.ServiceParameters} - the service parameters to be sent with the reverse geocoding request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Geocoder REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + * @returns {H.service.JsonpRequestHandle} + */ + search(searchParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): H.service.JsonpRequestHandle; + } + + export module GeocodingService { + /** + * @property subDomain {string=} - the sub-domain of the geo-coding service relative to the platform's base URL, default is 'geocoder' + * @property path {string=} - the path of the Geocoding service, default is '6.2' + */ + export interface Options { + subDomain?: string; + path?: string; + } + } + + /** + * An interface represents an object, that can be configured credentials, settings etc. by H.service.Platform + */ + export interface IConfigurable { + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + /** + * @property id {number} - the ID associated internally with this request + * @property cancel {function()} - this function cancels the request and invokes the errback function + */ + export interface JsonpRequestHandle { + id: number; + cancel: () => void; + } + + /** + * This class encapsulates a map tile end point of the HERE Map Tile API. + */ + export class MapTileService extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.MapTileService.Options=} + */ + constructor(opt_options?: H.service.MapTileService.Options); + + /** + * This method returns the map tile type provided by this service. + * @returns {string} - the map tile type + */ + getType(): string; + + /** + * This method returns the map tile service's newest version hash. + * @returns {string} - meta information for this map tile service + */ + getVersion(): string; + + /** + * This method returns the map tile service's meta information. The method will return an object once the map tile service's data has been fetched. + * @returns {(H.service.MapTileService.Info | undefined)} - meta information for this map tile service + */ + getInfo(): H.service.MapTileService.Info | void; + + /** + * This method creates a tile provider which uses the specified map tiles. This provider can be used as a data source for an ImageTileLayer. + * @param tileType {string} - the tile type + * @param scheme {string} - the tile scheme + * @param tileSize {number} - the tile size + * @param format {string} - the tile image format + * @param opt_additionalParameters {H.service.ServiceParameters=} - a hash of additional parameters to be + * @param opt_options {H.service.TileProviderOptions=} - additional set of options for the provider + * @returns {H.map.provider.ImageTileProvider} - the image tile provider + */ + createTileProvider(tileType: string, scheme: string, tileSize: number, format: string, opt_additionalParameters?: H.service.ServiceParameters, opt_options?: H.service.TileProviderOptions): H.map.provider.ImageTileProvider; + + /** + * This method creates a tile layer. This layer can be used as a layer on a map's data model. + * @param tileType {string} - the tile type + * @param scheme {string} - the tile scheme + * @param tileSize {number} - the tile size + * @param format {string} - the tile image format + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the map tile service + * @param opt_opacity {number=} - The opacity of this layer + * @param opt_dark {boolean=} - Indicates whether the content of this layer is mainly dark, default is false See also H.Map.Options#autoColor + * @param opt_options {H.service.TileProviderOptions=} - additional set of options for the provider + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(tileType: string, scheme: string, tileSize: number, format: string, opt_additionalParameters?: H.service.ServiceParameters, opt_opacity?: number, opt_dark?: boolean, opt_options?: H.service.TileProviderOptions): H.map.layer.TileLayer; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module MapTileService { + /** + * @property maps {Object} - + * @property schemes {Object} - + * @property tiletypes {Object} - + * @property formats {Object} - + * @property resolutions {Object} - + * @property languages {Object} - + */ + export interface Info { + maps: { [key: string]: any }; + schemes: { [key: string]: any }; + tiletypes: { [key: string]: any }; + formats: { [key: string]: any }; + resolutions: { [key: string]: any }; + languages: { [key: string]: any }; + } + + /** + * @property type {string=} - the type of the map tile service to communicate with, e.g. 'base' (default), 'aerial', etc. (refer to the Map Tile REST API documentation for available types) + * @property version {string=} - the map version hash to use for retrieving tiles, default is newest and will be automatically updated + * @property subDomain {string=} - the sub-domain of the map tile service relative to the platform's base URL, default is 'maps' + * @property path {string=} - the path of the map tile service, default is 'maptile/2.1' + */ + export interface Options { + type?: string; + version?: string; + subDomain?: string; + path?: string; + } + } + + /** + * A map type is an object holding tile layers corresponding to a map type (e.g. 'normal', 'satellite' or 'terrain'). A map type contains at least a map property which defines the basic map layer for a given map type. In addition it can hold other map layers with the given style, e.g. base, xbase, traffic etc. + * @property map {H.map.layer.TileLayer} - the basic map tiles with all features and labels + * @property mapnight {H.map.layer.TileLayer} - the basic map tiles with all features and labels (night mode) + * @property xbase {H.map.layer.TileLayer=} - map tiles without features and labels + * @property xbasenight {H.map.layer.TileLayer=} - map tiles without features and labels (night mode) + * @property base {H.map.layer.TileLayer=} - map tiles without labels + * @property basenight {H.map.layer.TileLayer=} - map tiles without labels (night mode) + * @property traffic {H.map.layer.TileLayer=} - map tiles with traffic flow highlighting + * @property trafficnight {H.map.layer.TileLayer=} - map tiles with traffic flow highlighting (night mode) + * @property transit {H.map.layer.TileLayer=} - map tiles with public transit lines highlighted + * @property panorama {H.map.layer.TileLayer=} - map tiles highlighting areas with HERE StreetLevel coverage + * @property panoramanight {H.map.layer.TileLayer=} - map tiles highlighting areas with HERE StreetLevel coverage (night mode) + * @property labels {H.map.layer.TileLayer=} - transparent map tiles with labels only + */ + export interface MapType { + map: H.map.layer.TileLayer; + mapnight: H.map.layer.TileLayer; + xbase?: H.map.layer.TileLayer; + xbasenight?: H.map.layer.TileLayer; + base?: H.map.layer.TileLayer; + basenight?: H.map.layer.TileLayer; + traffic?: H.map.layer.TileLayer; + trafficnight?: H.map.layer.TileLayer; + transit?: H.map.layer.TileLayer; + panorama?: H.map.layer.TileLayer; + panoramanight?: H.map.layer.TileLayer; + labels?: H.map.layer.TileLayer; + } + + /** + * Places service implements a low level places RestApi access. Please refer to Restful API documentation for providing parameters and handling response objects. + */ + export class PlacesService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.PlacesService.Options=} + */ + constructor(opt_options?: H.service.PlacesService.Options); + + /** + * This is generic method to query places RestAPI. + * @param entryPoint {string} - can be one of available entry points H.service.PlacesService.EntryPoint i.e value of H.service.PlacesService.EntryPoint.SEARCH + * @param entryPointParams {Object} - parameter map key value pairs will be transformed into the url key=value parametes. For entry point parameters description please refer to places restful api documentation documentation for available parameters for chose entry point + * @param onResult {Function} - callback which is called when result is returned + * @param onError {Function} - callback which is called when error occured (i.e request timeout) + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + request(entryPoint: string, entryPointParams: Object, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'search' entry point. Please refer to documentation for parameter specification and response handling. + * @param searchParams {H.service.ServiceParameters} - places api search entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + search(searchParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'suggestions' entry point. Please refer to documentation for parameter specification and response handling. + * @param suggestParams {H.service.ServiceParameters} - places api suggest entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + suggest(suggestParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'explore' entry point. Please refer to documentation for parameter specification and response handling. + * @param exploreParams {H.service.ServiceParameters} - places api explore entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + explore(exploreParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'around' entry point. Please refer to documentation for parameter specification and response handling. + * @param aroundParams {H.service.ServiceParameters} - places api around entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + around(aroundParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'here' entry point. Please refer to documentation for parameter specification and response handling. + * @param hereParams {H.service.ServiceParameters} - places api here entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + here(hereParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * Function triggers places api 'categories' entry point. Please refer to documentation for parameter specification and response handling. + * @param categoriesParams {H.service.ServiceParameters} - places api here entry point parameters please refer to places api documentation + * @param onResult {Function} + * @param onError {Function} + * @returns {H.service.JsonpRequestHandle} - jsonp request handle + */ + categories(categoriesParams: H.service.ServiceParameters, onResult: Function, onError: Function): H.service.JsonpRequestHandle; + + /** + * This method should be used to follow hyperlinks available in results returned by dicovery queries. + * @param hyperlink {string} + * @param onResult {Function} + * @param onError {Function} + * @param opt_additionalParameters {Object=} - additional parameters to send with request + * @returns {H.service.JsonpRequestHandle} - jsonp resquest handle + */ + follow(hyperlink: string, onResult: Function, onError: Function, opt_additionalParameters?: Object): H.service.JsonpRequestHandle; + } + + export module PlacesService { + /** + * List of available entry points + */ + export enum EntryPoint { + SEARCH, + SUGGEST, + EXPLORE, + AROUND, + HERE, + CATEGORIES, + } + + /** + * @property subDomain {string=} - the sub-domain of the places service relative to the platform's base URL, default is 'places' + * @property path {string=} - the path of the places service, default is 'places/v1' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * The Platform class represents central class from which all other service stubs are created. It also contains the shared settings to be passed to the individual service stubs, for example the root URL of the platform, application credentials, etc. + */ + export class Platform { + /** + * Constructor + * @param options {H.service.Platform.Options} + */ + constructor(options: H.service.Platform.Options); + + /** + * Method attempts to configure object that implements H.service.IConfigurable + * @param configurable {H.service.IConfigurable} + * @returns {H.service.IConfigurable} + */ + configure(configurable: H.service.IConfigurable): H.service.IConfigurable; + + /** + * This method enables or disables HTTPS communication with the platform + * @param useHTTPS {boolean} - a boolean value indicating whether to communicate with the platform via HTTPS + */ + setUseHTTPS(useHTTPS: boolean): void; + + /** + * This method configures whether to use the "customer integration testing" instance of the platform. + * @param useCIT {boolean} - a boolean value indicating whether the CIT platform instance is to be used + */ + setUseCIT(useCIT: boolean): void; + + /** + * This method modifies the base URL to be used when creating service stubs. + * @param baseUrl {H.service.Url} - the new base URL to use + */ + setBaseUrl(baseUrl: H.service.Url): void; + + /** + * This method returns the currently used base URL. + * @returns {H.service.Url} + */ + getBaseUrl(): H.service.Url; + + /** + * This method returns an instance of H.service.TrafficIncidentsService to query the Traffic API Traffic Incident Data + * @returns {H.service.TrafficIncidentsService} - a new places service instance + */ + getTrafficIncidentsService(): H.service.TrafficIncidentsService; + + /** + * This method returns an instance of H.service.MapTileService to query the Map Tile API. + * @param opt_options {H.service.MapTileService.Options=} + * @returns {H.service.MapTileService} + */ + getMapTileService(opt_options?: H.service.MapTileService.Options): H.service.MapTileService; + + /** + * This method returns an instance of H.service.venues.Service to query the Venue Maps API + * @param opt_params {H.service.venues.Service.Options=} - additional service parameters + * @returns {H.service.venues.Service} + */ + getVenueService(opt_params?: H.service.venues.Service.Options): H.service.venues.Service; + + /** + * This method returns an instance of H.service.metaInfo.Service to query the Map Tile API Metainfo Tiles + * @param opt_params {H.service.metaInfo.Service.Options=} - additional service parameters + * @returns {H.service.metaInfo.Service} + */ + getMetaInfoService(opt_params?: H.service.metaInfo.Service.Options): H.service.metaInfo.Service; + + /** + * This method creates a pre-configured set of HERE tile layers for convenient use with the map. + * @param opt_tileSize {(H.service.Platform.DefaultLayersOptions | number)=} - When a number – optional tile size to be queried from the HERE Map Tile API, default is 256. If the parameter is an object, then it represents options and all remaining below parameters should be omitted. + * @param opt_ppi {number=} - optional 'ppi' parameter to use when querying tiles, default is not specified + * @param opt_lang {string=} - optional primary language parameter, default is not specified + * @param opt_secondaryLang {string=} - optional secondary language parameter, default is not specified + * @param opt_style {string=} - optional 'style' parameter to use when querying map tiles, default is not specified + * @param opt_pois {(string | boolean)=} - indicates if pois are displayed on the map. Pass true to indicate that all pois should be visible. Alternatively you can specify mask for the POI Categories as described at the Map Tile API documentation POI Categories chapter. + * @returns {Object} - a set of tile layers ready to use + */ + createDefaultLayers(opt_tileSize?: (H.service.Platform.DefaultLayersOptions | number), opt_ppi?: number, opt_lang?: string, opt_secondaryLang?: string, opt_style?: string, opt_pois?: (string | boolean)): H.service.Platform.MapTypes; + + /** + * This method returns an instance of H.service.RoutingService to query the Routing API. + * @param opt_options {H.service.RoutingService.Options=} + * @returns {H.service.RoutingService} + */ + getRoutingService(opt_options?: H.service.RoutingService.Options): H.service.RoutingService; + + /** + * This method returns an instance of H.service.GeocodingService to query the Geocoder API + * @param opt_options {H.service.GeocodingService.Options=} - an optional set of options for the new geocoding service to connect to + * @returns {H.service.GeocodingService} - a new geocoding service instance + */ + getGeocodingService(opt_options?: H.service.GeocodingService.Options): H.service.GeocodingService; + + /** + * This method returns an instance of H.service.PlacesService to query the Places API. + * @returns {H.service.PlacesService} - a new places service instance + */ + getPlacesService(): H.service.PlacesService; + + /** + * This method returns an instance of H.service.EnterpriseRoutingService to query the Enterprise Routing API. + * @param opt_options {H.service.EnterpriseRoutingService.Options=} + * @returns {H.service.EnterpriseRoutingService} + */ + getEnterpriseRoutingService(opt_options?: H.service.EnterpriseRoutingService.Options): H.service.EnterpriseRoutingService; + } + + export module Platform { + /** + * Options used to create default layers + * @property tileSize {number=} - tile size to be queried from the HERE Map Tile API, default is 256 + * @property ppi {number=} - 'ppi' parameter to use when querying tiles, default is not specified + * @property lg {string=} - optional primary language parameter, default is not specified + * @property lg2 {string=} - optional secondary language parameter, default is not specified + * @property style {string=} - optional 'style' parameter to use when querying map tiles, default is not specified + * @property pois {boolean=} - indicates if pois are displayed on the map + * @property crossOrigin {(string | boolean=)} - indicates if CORS headers should be used for default layers, if false is specified, CORS headers are not set, defaults to 'anonymous'. Be aware that storing of content is not possible if crossOrigin is not set to true (see H.Map#storeContent). + */ + export interface DefaultLayersOptions { + tileSize?: number; + ppi?: number; + lg?: string; + lg2?: string; + style?: string; + pois?: boolean; + crossOrigin?: (string | boolean); + } + + /** + * @property app_id {string} - The application ID to identify the client against the platform (mandatory to provide) + * @property app_code {string} - The application code to identify the client against the platform (mandatory to provide) + * @property baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com + * @property useCIT {boolean=} - Indicates whether the Customer Integration Testing should be used, default is false + * @property useHTTPS {boolean=} - Indicates whether secure communication should be used, default is false + */ + export interface Options { + app_id: string; + app_code: string; + baseUrl?: H.service.Url; + useCIT?: boolean; + useHTTPS?: boolean; + } + + /** + * pre-configured set of HERE tile layers for convenient use with the map. + */ + export interface MapTypes { + normal?: H.service.MapType; + satellite?: H.service.MapType; + terrain?: H.service.MapType; + [key: string]: H.service.MapType; + } + } + + /** + * This class encapsulates the Routing REST API as a service stub. An instance of this class can be retrieved by calling the factory method on a platform instance. H.service.Platform#getRoutingService. + */ + export class RoutingService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.RoutingService.Options=} + */ + constructor(opt_options?: H.service.RoutingService.Options); + + /** + * This method sends a "calculateroute" request to Routing REST API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object - or the onError callback if a communication error occured. + * @param calculateRouteParams {H.service.ServiceParameters} - the service parameters to be sent with the routing request. + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Routing REST API provides a response to the request. + * @param onError {function(Error)} - this function will be called if a communication error occurs during the JSON-P request + */ + calculateRoute(calculateRouteParams: H.service.ServiceParameters, onResult: (result: H.service.ServiceResult) => void, onError: (error: Error) => void): void; + } + + export module RoutingService { + /** + * @property subDomain {string=} - the sub-domain of the routing service relative to the platform's base URL, default is 'route' + * @property path {string=} - the path of the map tile service, default is 'routing/7.2' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This type encapsulates URL parameters to be sent to a HERE platform service. + */ + export interface ServiceParameters { + [key: string]: string; + } + + /** + * This type encapsulates a response object provider by a HERE platform service. + */ + export interface ServiceResult { + [key: string]: string; + } + + /** + * Options which are used to initialize the tile provider. + * @property crossOrigin {boolean=} - The string to be set for the crossOrigin attribute for loaded images + */ + export interface TileProviderOptions { + crossOrigin?: boolean; + } + + /** + * TrafficIncindentsService provides functionality to the low level traffic incidents api Traffic API documentation where it is possible to retrieve traffic incident information on a tile basis + */ + export class TrafficIncidentsService extends H.service.AbstractRestService { + /** + * Constructor + * @param opt_options {H.service.TrafficIncidentsService.Options=} + */ + constructor(opt_options?: H.service.TrafficIncidentsService.Options); + + /** + * This method requests traffic incidents based on the service parameters provided. + * @param serviceParams {H.service.ServiceParameters} + * @param onResponse {function(H.service.ServiceResult)} + * @param onError {function()} + * @returns {H.service.JsonpRequestHandle} + */ + requestIncidents(serviceParams: H.service.ServiceParameters, onResponse: (result: H.service.ServiceResult) => void, onError: () => void): H.service.JsonpRequestHandle; + + /** + * This method requests traffic incident information by tile coordinates + * @param x {number} - tile column number + * @param y {number} - tile row number + * @param z {number} - zoom level + * @param onResponse {function(H.service.ServiceResult)} - callback to handle service resposne + * @param onError {function()} - callback to habdle communication error + * @param opt_serviceParams {H.service.ServiceParameters=} - optional service parameters to be added to the request + * @returns {H.service.JsonpRequestHandle} + */ + requestIncidentsByTile(x: number, y: number, z: number, onResponse: (result: H.service.ServiceResult) => void, onError: () => void, opt_serviceParams?: H.service.ServiceParameters): H.service.JsonpRequestHandle; + } + + export module TrafficIncidentsService { + /** + * @property subDomain {string=} - the sub-domain of the traffic incidents service relative to the platform's base URL, default is 'traffic' + * @property path {string=} - the path of the traffic incidents service, default is 'traffic/6.1' + * @property baseUrl {H.service.Url=} - an optional base URL if it differs from the platform's default base URL + */ + export interface Options { + subDomain?: string; + path?: string; + baseUrl?: H.service.Url; + } + } + + /** + * This class represents a URL giving access to the individual parts that make up a URL,such as the scheme, host/domain, path, etc. Use the static parse method to populate a new URL object from a URL string. Be aware that URLs with user and password like "ftp://user:password@foo.bar/" are not supported! + */ + export class Url { + /** + * Constructor + * @param scheme {string} - the URL scheme (e.g. "http" or "https" or "mailto") + * @param host {string} - the host (or domain) part of the URL + * @param opt_path {string=} - the path following the host pointing to a resource + * @param opt_params {Object=} - the query string parameters of this URL + * @param opt_port {number=} - The port of the host on which the host listens. If a string is passed it must be convertible to an integer. + * @param opt_anchor {string=} - an optional anchor part of the URL (usually preceded by '#'); + */ + constructor(scheme: string, host: string, opt_path?: string, opt_params?: Object, opt_port?: number, opt_anchor?: string); + + /** + * This function parses a URL string and returns a H.service.Url object. The URL string must contain at least a scheme and a host. + * @param url {string} - The URL string to parse. + * @param opt_baseURL {string=} - The base URL to use to resolve relative URLs. If ommited the base URL of the document which loaded the API is taken. + * @returns {H.service.Url} - the parsed URL object + */ + static parse(url: string, opt_baseURL?: string): H.service.Url; + + /** + * Clones this URL object. Optionally, mutations can be passed to this function to modify properties of the cloned object. Note that URL parameters are not replaced but merged with the parameters of this instance. + * @returns {H.service.Url} - the clone of the URL object + */ + clone(): H.service.Url; + + /** + * This function sets the scheme of this URL object. + * @param scheme {string} - the new scheme + * @returns {H.service.Url} - this URL object + */ + setScheme(scheme: string): H.service.Url; + + /** + * This function returns the scheme of this Url object. + * @returns {string} - the scheme (for example 'http') + */ + getScheme(): string; + + /** + * This function sets the host of this URL object. + * @param host {string} - the new host + * @returns {H.service.Url} - this URL object + */ + setHost(host: string): H.service.Url; + + /** + * This function returns the host name of this Url object. + * @returns {string} - the host (for example 'api.here.com') + */ + getHost(): string; + + /** + * This function sets the path of this URL object. + * @param path {(string | undefined)} - the new path or a boolean to clear the path + * @returns {H.service.Url} - this URL object + */ + setPath(path: string | boolean): H.service.Url; + + /** + * This function returns the path part of this Url object. + * @returns {(string | undefined)} - the path (for example 'myresources/resource.html') + */ + getPath(): string | void; + + /** + * This function sets the specified parameters for this URL object. Keys in this object, which are associated with undefined values will be treated as query string parameters with no value. + * @param params {(Object | undefined)} - a hash of query string parameters specifying the parameters to be set.or a boolean to clear the parameters. + * @returns {H.service.Url} - this URL object + */ + setQuery(params?: Object | boolean): H.service.Url; + + /** + * This function returns a boolean value indicating whether there are any query string parameter associated with this URL. + * @returns {boolean} - true if there are parameters, false if none are present + */ + hasQuery(): boolean; + + /** + * This function returns the query object of this Url object. + * @returns {Object} - the query object + */ + getQuery(): Object; + + /** + * This function sets the anchor of this URL object. + * @param anchor {(string | boolean | undefined)} - the new anchor or undefined to clear the anchor + * @returns {H.service.Url} - this URL object + */ + setAnchor(anchor?: string | boolean): H.service.Url; + + /** + * This function returns the anchor of this Url object. + * @returns {(string | undefined)} - the anchor + */ + getAnchor(): string | void; + + /** + * This function merges the provided parameters into this URL's existing parameters. Key-value pairs which are defined in the argument and this URL's parameters will be overwritten. Key-value pairs which are defined in the argument and are not defined in this URL's parameters will be added. Prototype properties and function properties will not be merged. + * @param other {Object} - the parmeters to be merged into this URL's query string parameters + * @returns {H.service.Url} - this URL object + */ + mergeQuery(other: Object): H.service.Url; + + /** + * This function adds a sub-domain to the host of this URL object. + * @param subDomain {string} - the sub domain (non-empty string) to be added + * @returns {H.service.Url} - this URL object + */ + addSubDomain(subDomain: string): H.service.Url; + + /** + * This function adds a sub-path to this URL's path + * @param subPath {string} - the path to be added + * @returns {H.service.Url} - this URL object + */ + addSubPath(subPath: string): H.service.Url; + + /** + * This function formats this URL object to a full URL string. + * @returns {string} - the URL's string representation + */ + toString(): string; + } + + export module metaInfo { + /** + * This class encapsulates a Metainfo Tile end point of the HERE Map Tile API. + */ + export class Service extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.metaInfo.Service.Options=} - additional service parameters + */ + constructor(opt_options?: H.service.metaInfo.Service.Options); + + /** + * This method returns the meta info tile service's newest version hash. + * @returns {string} - meta information for this map tile service + */ + getVersion(): string; + + /** + * This method returns the meta info tile service's meta information. The method will return an object once the map tile service's data has been fetched. + * @returns {(H.service.metaInfo.Service.Info | undefined)} - meta information for this meta info tile service + */ + getInfo(): H.service.metaInfo.Service.Info | void; + + /** + * This method creates a tile provider which uses the meta info tile backend. This provider can be used as a data source for an TileLayer. + * @param tileSize {number} - The tile size + * @param pixelRatio {number} - The tile's pixel ratio, should be aligned with base map tile + * @param opt_categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the meta info service + * @param opt_tileType {string=} - the tile type (default is 'maptile') + * @param opt_scheme {string=} - the scheme for which the meta info tiles a requested (default is 'normal.day') + * @returns {H.map.provider.TileProvider} - the tile provider + */ + createTileProvider(tileSize: number, pixelRatio: number, opt_categoryFilter?: Array, opt_additionalParameters?: H.service.ServiceParameters, opt_tileType?: string, opt_scheme?: string): H.map.provider.TileProvider; + + /** + * This method creates a tile layer. This layer can be used as a layer on a map's data model. + * @param tileSize {number} - The tile size + * @param pixelRatio {number} - The tile's pixel ratio, should be aligned with base map tile + * @param opt_categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + * @param opt_additionalParameters {H.service.ServiceParameters=} - Additional parameters for the meta info service + * @param opt_tileType {string=} - the tile type (default is 'maptile') + * @param opt_scheme {string=} - the scheme for which the meta info tiles a requested (default is 'normal.day') + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(tileSize: number, pixelRatio: number, opt_categoryFilter?: Array, opt_additionalParameters?: H.service.ServiceParameters, opt_tileType?: string, opt_scheme?: string): H.map.layer.TileLayer; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module Service { + /** + * @property maps {Object} - + * @property schemes {Object} - + * @property tiletypes {Object} - + * @property formats {Object} - + * @property resolutions {Object} - + * @property languages {Object} - + */ + export interface Info { + maps: { [key: string]: any }; + schemes: { [key: string]: any }; + tiletypes: { [key: string]: any }; + formats: { [key: string]: any }; + resolutions: { [key: string]: any }; + languages: { [key: string]: any }; + } + + /** + * @property type {string=} - the type of the map tile service to communicate with, e.g. 'base' (default), 'aerial', etc. (refer to the Map Tile REST API documentation for available types) + * @property version {string=} - the map version hash to use for retrieving tiles, default is newest and will be automatically updated + * @property subDomain {string=} - the sub-domain of the map tile service relative to the platform's base URL, default is 'maps' + */ + export interface Options { + type?: string; + version?: string; + subDomain?: string; + } + } + + /** + * This class utilizes Metainfo Tiles functionality provided by the Map Tile API to load meta information about map objects (buildings, labels, public transport etc.). + */ + export class TileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {(H.service.metaInfo.Service | H.service.MapTileService)} - the tile service which holds information from about the source of the tiles + * @param opt_params {H.service.ServiceParameters=} - an additional set of URL parameters + * @param opt_options {H.service.metaInfo.TileProvider.Options=} - additional parameters + */ + constructor(service: (H.service.metaInfo.Service | H.service.MapTileService), opt_params?: H.service.ServiceParameters, opt_options?: H.service.metaInfo.TileProvider.Options); + } + + export module TileProvider { + /** + * Configuration object which can be used to initialize the TileProvider. + * @property tileType {string=} - The tile type for which to request meta info + * @property scheme {string=} - The map scheme for which to request meta info + * @property tileCacheSize {number=} - The number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property tileSize {number=} - The size of the tiles rendered by this provider (must be power of 2, default is 256) + * @property pixelRatio {number=} - The pixel ratio to use for over-sampling in cases of high-resolution displays + * @property categoryFilter {Array=} - A list of meta-info category names which should be suppressed. See Metainfo Tile for valid category names. + */ + export interface Options { + tileType?: string; + scheme?: string; + tileCacheSize?: number; + tileSize?: number; + pixelRatio?: number; + categoryFilter?: Array; + } + } + } + + export module venues { + /** + * The class represents the building in the venue hiearachy (see H.service.venues.Venue) and holds floors that belong to the building. + */ + export class Building extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue building + * @param uid {string} - The unique identifier of this building + * @param minLevel {number} - The minimum floor level of this building + * @param maxLevel {number} - The maximum floor level of this building + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string, minLevel: number, maxLevel: number); + + /** + * Method returns the parent object - venue (see H.service.venues.Venue) to which the building belongs to. + * @returns {H.service.venues.Venue} + */ + getVenue(): H.service.venues.Venue; + + /** + * Method returns the minimum floor level of this building. + * @returns {number} + */ + getMinLevel(): number; + + /** + * Method returns the maximum floor level of this building + * @returns {number} + */ + getMaxLevel(): number; + + /** + * Method returns the floor (see H.service.venues.Floor) if one was already loaded. This method doesn't make attempt to fetch the floor data. + * @param level {number} - floor level within minimum and maximum level boundaries for the building + * @returns {(H.service.venues.Floor | undefined)} - The floor object or undefined if floor was not loaded + */ + getFloor(level: number): H.service.venues.Floor | void; + } + + /** + * The class represents the floor object in the venue hierarchy (see H.service.venues.Venue). The class holds information about floor geometry and spaces (see H.service.venues.Space) that belong to this floor. + */ + export class Floor extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue floor + * @param data {*} - The meta data of this floor + * @param level {number} - The level of this floor + */ + constructor(provider: H.map.provider.ObjectProvider, data: any, level: number); + + /** + * Method returns the level of the floor in the building. + * @returns {number} + */ + getLevel(): number; + + /** + * Method returns map geometry that represents floor boundaries. + * @returns {(H.service.venues.Space | undefined)} + */ + getFloorSpace(): H.service.venues.Space | void; + + /** + * Method returns the H.map.Group of all spaces that belong to the floor. + * @returns {H.map.Group} + */ + getSpaces(): H.map.Group; + + /** + * Method returns parent object - building (see H.service.venues.Building) of the floor. + * @returns {H.service.venues.Building} + */ + getBuilding(): H.service.venues.Building; + + /** + * Method returns raw data associated with the floor. For more details on data format see http://developer.here.com/rest-apis/documentation/venue-maps/topics/resource-type-venue-interaction-tile-floor.html + * @returns {*} - the raw floor data object + */ + getData(): any; + + /** + * Method returns the space object with the given ID, that belongs to the floor. + * @param id {string} - The ID of the space. + * @returns {(H.service.venues.Space | undefined)} - The requested space or undefined if space not found. + */ + getSpace(id: string): H.service.venues.Space | void; + } + + /** + * This class encapsulates methods to call Venue Maps API endpoints. + */ + export class Service extends H.util.EventTarget implements H.service.IConfigurable { + /** + * Constructor + * @param opt_options {H.service.venues.Service.Options=} - additional service parameters + */ + constructor(opt_options?: H.service.venues.Service.Options); + + /** + * This method sends a discovery request to the Venue Maps API and calls the onResult callback function once the service response was received - providing a H.service.ServiceResult object, or the onError callback if a communication error occured. + * @param serviceParams {H.service.ServiceParameters} - the service parameters to be sent with the discovery request + * @param onResult {function(H.service.ServiceResult)} - this function will be called once the Venue Maps API provides a response to the request + * @param onError {function(string)} - this function will be called if a communication error occurs during request and error type is passed as an argument + */ + discover(serviceParams: H.service.ServiceParameters, onResult: (res: H.service.ServiceResult) => void, onError: (s: string) => void): void; + + /** + * This method creates a tile layer which can be added to the map in order to see the venues. It uses Interaction Tile endpoint of the Venue Maps API, more at http://developer.here.com/rest-apis/documentation/venue-maps/topics/quick-start-get-interaction-tile.html. + * @param opt_options {H.service.venues.TileProvider.Options=} - Tile provider options + * @returns {H.map.layer.TileLayer} - the tile layer + */ + createTileLayer(opt_options?: H.service.venues.TileProvider.Options): H.map.layer.TileLayer; + + /** + * Method returns current state of the service. + * @returns {H.service.venues.Service.State} - State of the service + */ + getState(): H.service.venues.Service.State; + + /** + * This methods receive configuration parameters from the platform, that can be used by the object implementing the interface. + * @param appId {string} - The application ID to identify the client against the platform (mandatory to provide) + * @param appCode {string} - The application code to identify the client against the platform (mandatory to provide) + * @param useHTTPS {boolean} - Indicates whether secure communication should be used, default is false + * @param useCIT {boolean} - Indicates whether the Customer Integration Testing should be used, default is false + * @param opt_baseUrl {H.service.Url=} - The base URL of the platform, default is http://api.here.com. Note that if useHTTPS flag is passed it will override the URL scheme specified in the opt_baseUrl to use HTTPS. + * @returns {H.service.IConfigurable} + */ + configure(appId: string, appCode: string, useHTTPS: boolean, useCIT: boolean, opt_baseUrl?: H.service.Url): H.service.IConfigurable; + } + + export module Service { + /** + * @property subDomain {string=} - the sub-domain of the Venue Maps service relative to the platform's base URL, default is 'venue.maps' + * @property path {string=} - the path to append after host name when making requests to the Venue Maps API, default is empty + */ + export interface Options { + subDomain?: string; + path?: string; + } + + /** + * The state types of the H.service.venues.Service. Possible states are: + */ + export enum State { + ERROR, + INIT, + READY, + } + } + + /** + * Represents a spatial object for this space. Each space object contains data associated with that space and can be retrieved by using H.service.venues.Space#getData method. + */ + export class Space { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The provider of this object. + * @param uid {string} - The unique identifier of this space + * @param data {*} - The meta data of this space + * @param opt_isFloorSpace {boolean=} - Indicates whether this space represents a floor itself, defaults to false + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string, data?: any, opt_isFloorSpace?: boolean); + + /** + * The method indicates whether the spatial object represents the whole floor space or a space within a floor boundaries, that belongs to the floor. + * @returns {boolean} - True if this spatial object represents the floor space. + */ + isFloorSpace(): boolean; + + /** + * This method sets custom style to use for rendering the labels. Should be called before the first render of the space, otherwise has no any effect. Note that due to the design consistency currently it is not allowed to change the font family and the size of the labels. + * @param labelStyle {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - Custom label style + */ + initLabelStyle(labelStyle: (H.map.SpatialStyle | H.map.SpatialStyle.Options)): void; + + /** + * Method returns parent object - floor (see H.service.venues.Floor) of the space. + * @returns {H.service.venues.Floor} + */ + getFloor(): H.service.venues.Floor; + + /** + * Method returns raw data associated with the space. For more details on data format see http://developer.here.com/rest-apis/documentation/venue-maps/topics/resource-type-venue-interaction-tile-space.html + * @returns {Object} - raw space data object + */ + getData(): Object; + } + + /** + * This class represents a Venue Maps tile provider which requests venues tiles from a platform venue tile service. + */ + export class TileProvider extends H.map.provider.RemoteTileProvider { + /** + * Constructor + * @param service {H.service.venues.Service} + * @param opt_options {H.service.venues.TileProvider.Options=} + */ + constructor(service: H.service.venues.Service, opt_options?: H.service.venues.TileProvider.Options); + + /** + * Method specifies which floor level of the venues must be fetched by provider. Floor level is global to all venues and defaults to 0. + * @param level {number} + */ + setCurrentLevel(level: number): void; + + /** + * Method returns the floor level that provider uses for tile fetching. + * @returns {number} - current provider's floor level + */ + getCurrentLevel(): number; + } + + export module TileProvider { + /** + * Configuration object which can be used to initialize the TileProvider. + * @property tileCacheSize {number=} - The number of fully rendered spatial tiles that are cached for immediate reuse, default is 32 + * @property pixelRatio {number=} - The pixel ratio to use for over-sampling in cases of high-resolution displays + * @property onSpaceCreated {function(H.service.venues.Space)=} - A callback function that is called on every created space (see H.service.venues.Space) object. The function can be used for space object styling. + */ + export interface Options { + tileCacheSize?: number; + pixelRatio?: number; + onSpaceCreated?: (space: H.service.venues.Space) => void; + } + } + + /** + * The class represents the venue, it is a root for the venue object heirarchy. The venue inherits from H.map.Group and holds building objects (see H.service.venues.Building). Building objects hold floor objects (see H.service.venues.Floor) and inherit from H.map.Group as well. Leaf objects are spaces (see H.service.venues.Space) that are spatial map objects and reside inside floor containers. + */ + export class Venue extends H.map.Group { + /** + * Constructor + * @param provider {H.map.provider.ObjectProvider} - The object provider of this venue + * @param uid {string} - The unique identifier of this venue + */ + constructor(provider: H.map.provider.ObjectProvider, uid: string); + + /** + * Method returns the building object, that belongs to the venue, with the given ID . The method doesn't attempt to fetch building data. + * @param id {string} - the ID of the building + * @returns {(H.service.venues.Building | undefined)} - The requested building or undefined if building wasn't loaded + */ + getBuilding(id: string): H.service.venues.Building | void; + + /** + * Method returns map of all loaded buildings associated with the venue. + * @returns {Object<*, H.service.venues.Building>} + */ + getBuildings(): any; + } + } + } + + /***** ui *****/ + export module ui { + /** + * This class represents the base class for UI controls on the map. + */ + export class Control extends H.ui.base.Container { + /** + * This abstract method can be overridden by deriving classes to be invoked when the UI object's unit system changes. + * @param unitSystem {H.ui.UnitSystem} - the unit system the UI currently uses + */ + onUnitSystemChange(unitSystem: H.ui.UnitSystem): void; + + /** + * This abstract method can be overridden by deriving classes to be invoked when the underlying map engine changes. + * @param engineType {H.Map.EngineType} - the engine type the map currently uses + */ + onMapEngineTypeChange(engineType: H.Map.EngineType): void; + + /** + * This method returns the map to which this control is attached. + * @returns {?H.Map} - return the map + */ + getMap(): H.Map; + + /** + * This method returns the localization object which corresponds to the UI's current locale. + * @returns {H.ui.i18n.Localization} + */ + getLocalization(): H.ui.i18n.Localization; + + /** + * This method returns this control's layout alignment. + * @returns {H.ui.LayoutAlignment} - the control's current layout alignment + */ + getAlignment(): H.ui.LayoutAlignment; + + /** + * This method sets the control's layout alignments. + * @param alignment {H.ui.LayoutAlignment} - The new alignment of the control + * @returns {H.ui.Control} - returns this control instance + */ + setAlignment(alignment: H.ui.LayoutAlignment): H.ui.Control; + } + + /** + * This class represents a distance measurement control which helps calculating distances between geographical locations indicated by the user clicks. + */ + export class DistanceMeasurement extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.DistanceMeasurement.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.DistanceMeasurement.Options); + } + + export module DistanceMeasurement { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.RIGHT_BOTTOM + * @property startIcon {H.map.Icon=} - the icon to use for the first measurement point + * @property stopoverIcon {H.map.Icon=} - the icon to use for the intermediate measurement points + * @property endIcon {H.map.Icon=} - the icon to use for the last measurement point + * @property splitIcon {H.map.Icon=} - the icon to use for indicating position under pointer over the line where new point will be created once user clicks + * @property lineStyle {(H.map.SpatialStyle | H.map.SpatialStyle.Options)} - the style to use for connecting lines of the measurement points + * @property distanceFormatter {function(number)=} - Optional function used for formatting a distance. By default distance measurement tool will do the formatting according to the specified measurement unit (see H.ui.UI.Options#unitSystem) + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + startIcon?: H.map.Icon; + stopoverIcon?: H.map.Icon; + endIcon?: H.map.Icon; + splitIcon?: H.map.Icon; + lineStyle: H.map.SpatialStyle | H.map.SpatialStyle.Options; + distanceFormatter?(n: number): void; + } + } + + /** + * This class represents an information bubble bound to a geo-position on the map. + */ + export class InfoBubble extends base.Element { + /** + * Constructor + * @param position {H.geo.IPoint} - the geo-position to which this info bubble corresponds + * @param opt_options {H.ui.InfoBubble.Options=} - optional parameters to be passed to the info bubble + */ + constructor(position: H.geo.IPoint, opt_options?: InfoBubble.Options); + + /** + * This method sets the geo-position of this info bubble + * @param position {(H.geo.IPoint | H.geo.Point)} - the new geo-position of this bubble + */ + setPosition(position: H.geo.IPoint | H.geo.Point): void; + + /** + * This method returns this info bubble's current state. + * @returns {H.ui.InfoBubble.State} - this bubble's current state + */ + getState(): InfoBubble.State; + + /** + * This method sets the info bubble's state. + * @param state {H.ui.InfoBubble.State} - the new state + */ + setState(state: InfoBubble.State): void; + + /** + * This method closes the info bubble (setting its state to CLOSED) + */ + close(): void; + + /** + * This method opens the info bubble (setting its state to OPEN) + */ + open(): void; + + /** + * This method returns the bubble's content element. + * + * Note: Before adding an info bubble to a UI object the content element is null. + * @returns {?HTMLElement} - the content element of this info bubble + */ + getContentElement(): HTMLElement; + + /** + * This methods sets the content of the info bubble. This can either be a string (applied as innerHTML) to the content element of this info bubble or a HTML node which is appended to the content element. + * @param content {(string | Node)} - the content for this bubble + */ + setContent(content: string | Node): void; + } + + export module InfoBubble { + /** + * This enumeration holds the state an info bubble can have. + */ + export enum State { + /** This value represents the state where an info bubble is open and visible (value: 'open'). */ + OPEN, + /** This value represents the state where an info bubble is closed and invisible (value: 'closed') */ + CLOSED, + } + + export interface Options { + /** + * a callback to be invoked when the info bubble's state changes + * @param event {H.util.Event} + */ + onStateChange?(event: H.util.Event): void; + + /** + * content to be added to the info bubble + */ + content: string | Node; + } + } + + /** + * This enumeration holds the possible layout alignments for the UI elements. + */ + export enum LayoutAlignment { + TOP_LEFT, + TOP_CENTER, + TOP_RIGHT, + LEFT_TOP, + LEFT_MIDDLE, + LEFT_BOTTOM, + RIGHT_TOP, + RIGHT_MIDDLE, + RIGHT_BOTTOM, + BOTTOM_LEFT, + BOTTOM_CENTER, + BOTTOM_RIGHT, + } + + /** + * This class represents a menu control allowing to control which map type the map shows, etc. + */ + export class MapSettingsControl extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.MapSettingsControl.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.MapSettingsControl.Options); + + /** + * Sets the traffic incidents layer to be shown when activating the respective button on the map settings control. + * @param incidentsLayer {H.map.layer.Layer} - the incidents layer + */ + setIncidentsLayer(incidentsLayer: H.map.layer.Layer): void; + } + + export module MapSettingsControl { + /** + * The map type entry is an object containing a display name and a map type object to which it refers. + * @property name {string} - label which describes the map type + * @property mapType {H.service.MapType} - reference to map type + */ + export interface MapTypeEntry { + name: string; + mapType: H.service.MapType; + } + + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + * @property entries {Array=} - the map type entries to be shown in this map settings control + * @property incidents {H.map.layer.Layer} - the traffic incidents layer to be activated by the map settings control + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + entries?: Array; + incidents: H.map.layer.Layer; + } + } + + /** + * This class represents the UI controls for panorama + */ + export class Pano extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.Pano.Options=} - optional parameters to be passed to the map. + */ + constructor(opt_options?: H.ui.Pano.Options); + } + + export module Pano { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.RIGHT_BOTTOM + * @property mapTypes {H.service.MapTypes} - The map types to use + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + mapTypes: H.service.MapType; + } + } + + /** + * This class represents a UI element showing the current zoom scale. + */ + export class ScaleBar { + /** + * Constructor + * @param opt_options {H.ui.ScaleBar.Options=} - optional parameters to be passed to this scale bar. + */ + constructor(opt_options?: H.ui.ScaleBar.Options); + } + + export module ScaleBar { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + } + } + + /** + * This class encapsulates map UI functionality. + */ + export class UI implements H.util.ICapturable { + /** + * Constructor + * @param map {H.Map} + * @param opt_options {H.ui.UI.Options=} + */ + constructor(map: H.Map, opt_options?: UI.Options); + + /** + * This method returns this ui's root element. + * @returns {ELement} - the root element + */ + getElement(): Element; + + /** + * Returns the map instance to which this UI was added. + * @returns {H.Map} + */ + getMap(): H.Map; + + /** + * This method returns this UI object's current unit system. + * @returns {H.ui.UnitSystem} - the current unit system + */ + getUnitSystem(): UnitSystem; + + /** + * This method sets this UI object's unit system for displaying distances. + * @param unitSystem {H.ui.UnitSystem} - the unit system to use + */ + setUnitSystem(unitSystem: UnitSystem): void; + + /** + * Toggles this UI's unit system between {@link H.ui.UnitSystem.METRIC} and {@link H.ui.UnitSystem.IMPERIAL}. + */ + toggleUnitSystem(): void; + + /** + * This method adds an info bubble to the UI. + * @param bubble {H.ui.InfoBubble} - the info bubble to be added + */ + addBubble(bubble: InfoBubble): void; + + /** + * This method removes a previously added info bubble from the UI. + * @param bubble {H.ui.InfoBubble} - the info bubble to be removed + */ + removeBubble(bubble: InfoBubble): void; + + /** + * This method returns a list of info bubble objects which are currently attached to this UI. + * @returns {Array} - the list of info bubbles + */ + getBubbles(): Array; + + /** + * This method appends a control to the UI. + * @param name {string} - the name under which to register this control + * @param control {H.ui.Control} - the control to add to this UI + */ + addControl(name: string, control: Control): void; + + /** + * Removes a previously registered control from the UI object. + * @param name {string} - the name under which this control was previously registered + * @returns {H.ui.Control} - the removed control + */ + removeControl(name: string): Control; + + /** + * This method returns a UI control which was previously registered with the provided name. + * @param name {string} - the name under which the control was registered. + * @returns {H.ui.Control} - the control or undefined if the control does not exist. + */ + getControl(name: string): Control; + + /** + * This function creates the default UI including the zoom control, + * map settings control and scalebar and panorama discovery control. + * The default controls will be assigned the following values: + * + * Zoom control: + * id: 'zoom' + * alignment: 'right-middle' + * Map settings control: + * id: 'mapsettings' + * alignment: 'bottom-right' + * Scalebar: + * id: 'scalebar' + * alignment: 'bottom-right' + * Pano: + * id: 'panorama' + * alignment: 'top-right' + * + * @param map {H.Map} - The map instance to which to append the UI + * @param mapTypes {Object} - The map types to use + * @param opt_locale {(H.ui.i18n.Localization | string)=} - the language to use (or a full localization object). + * @returns {H.ui.UI} - the UI instance configured with the default controls + */ + static createDefault(map: H.Map, mapTypes: H.service.Platform.MapTypes, opt_locale?: H.ui.i18n.Localization | string): UI; + + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRation {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {ICapturable~captureCallback} - Callback function to call once result of the capturing is ready + * @param opt_errback {ICapturable~errorCallback} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRation: number, callback: (canvas?: HTMLCanvasElement) => void, opt_errback?: (error: string) => void): void; + + /** + * @callback ICapturable~captureCallback + * @param canvas {HTMLCanvasElement=} + */ + + /** + * @callback ICapturable~errorCallback + * @param error {string} + */ + } + + export module UI { + /** + * Optional parameters to be passed to the UI constructor. + * @property unitSystem {H.ui.UnitSystem=} - An optional unit system to be used by the UI, default is H.ui.UnitSystem.METRIC + * @property zoom {(H.ui.ZoomControl.Options | boolean)=} - + * @property zoomrectangle {(H.ui.ZoomRectangle.Options | boolean)=} - + * @property mapsettings {(H.ui.MapSettingsControl.Options | boolean)=} - + * @property scalebar {(H.ui.ScaleBar.Options | boolean)=} - + * @property panorama {(H.ui.Pano.Options | boolean)=} - + * @property distancemeasurement {(H.ui.DistanceMeasurement.Options | boolean)=} - + * @property locale {(H.ui.i18n.Localization | string)=} - defines language in which UI can be rendered. It can be predefined H.ui.i18n.Localization object with custom translation map, or a string one of following 'en-US', 'de-DE', 'es-ES', 'fi-FI', 'fr-FR', 'it-IT', 'nl-NL', 'pl-PL', 'pt-BR', 'pt-PT', 'ru-RU', 'tr-TR', 'zh-CN'. If not defined ui will use 'en-US' by default + */ + export interface Options { + unitSystem?: H.ui.UnitSystem; + zoom?: (H.ui.ZoomControl.Options | boolean); + zoomrectangle?: (H.ui.ZoomRectangle.Options | boolean); + mapsettings?: (H.ui.MapSettingsControl.Options | boolean); + scalebar?: (H.ui.ScaleBar.Options | boolean); + panorama?: (H.ui.Pano.Options | boolean); + distancemeasurement?: (H.ui.DistanceMeasurement.Options | boolean); + locale?: (H.ui.i18n.Localization | string); + } + } + + /** + * This enumeration holds the possible unit systems for the UI to display distances. + */ + export enum UnitSystem { + /** This value represents the imperial unit system using miles and feet (value: 'imperial'). */ + IMPERIAL, + /** This value represents the metric unit system using meters and kilometers, etc (value: 'metric'). */ + METRIC, + } + + /** + * This class represents the UI controls for zooming in an out of the map. + */ + export class ZoomControl extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.ZoomControl.Options=} - optional parameters to be passed to the map. + */ + constructor(opt_options?: H.ui.ZoomControl.Options); + + /** + * This method returns the zoom speed (in levels per millisecond) which is applied when the button is pressed constantly. + * @returns {number} - the current zoom speed + */ + getZoomSpeed(): number; + } + + export module ZoomControl { + /** + * @property zoomSpeed {number=} - the speed if zooming in and out in levels per millisecond, defaults to 0.05 + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, defaults to H.ui.LayoutAlignment.RIGHT_MIDDLE + * @property slider {boolean=} - flag whether to show the slider (true) or not, defaults to false + * @property sliderSnaps {boolean=} - flag whether slider should snap to the integer values or not, defaults to false. This option has effect only if slider is enabled. + */ + export interface Options { + zoomSpeed?: number; + alignment?: H.ui.LayoutAlignment; + slider?: boolean; + sliderSnaps?: boolean; + } + } + + /** + * This class represents a zoom rectangle control element that allows zooming to the selected area on the screen. + */ + export class ZoomRectangle extends H.ui.Control { + /** + * Constructor + * @param opt_options {H.ui.ZoomRectangle.Options=} - optional parameters to be passed to this control + */ + constructor(opt_options?: H.ui.ZoomRectangle.Options); + } + + export module ZoomRectangle { + /** + * @property alignment {H.ui.LayoutAlignment=} - the layout alignment which should be applied to this control, default is H.ui.LayoutAlignment.BOTTOM_RIGHT + * @property adjustZoom {function(number, H.Map) : number=} - optional function that defines how zoom level should be changed, by default zoom level is picked to fit the bounding rectangle into the view port. + */ + export interface Options { + alignment?: H.ui.LayoutAlignment; + adjustZoom?(n: number, m: H.Map): number; + } + } + + type ES6Element = Element; + + /** + * This namespace contains basic UI elements from which the UI controls are built. + */ + export module base { + export class Container extends H.util.EventTarget { + /** + * Constructor + * @param opt_elementType {string=} - the type of HTML element this UI element renders as, default is 'div' + * @param opt_className {string=} - an optional class name to be used on this element + * @param opt_children {Array=} - optional child elements to be added to this container + */ + constructor(opt_elementType?: string, opt_className?: string, opt_children?: Array); + + /** + * Adds a child element to be rendered within the container element. + * @param child {H.ui.base.Element} - the child element to be added + * @returns {H.ui.base.Container} - this container instance + */ + addChild(child: Element): Container; + + /** + * Returns the child collection of this container. + * @returns {Array} - Returns the child collection of this container. + */ + getChildren(): Array; + + /** + * Removes a child element from this container's child collection. + * @param child {H.ui.base.Element} - the child element to be removed + */ + removeChild(child: Element): void; + + /** + * This method is the concrete implementation of the UI element. This method receives the pre-rendered HTML element which may be modified by deriving classes. + * @param element {Element} - this UI element's HTML representation + * @param doc {Document} - the HTML document into which the element is currently being rendered + */ + renderInternal(element: ES6Element, doc: Document): void; + + /** + * This method returns this UI element's disabled state as a boolean value. + * @returns {boolean} - true if the element is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method set's the disabled state of this UI element. + * @param disabled {boolean} - true to disable the element, false to enable it + * @param opt_force {boolean=} - an optional boolean flag indicating that the value should be set and propagated even if it is the same as the current state + * @returns {H.ui.base.Element} - this element instance + */ + setDisabled(disabled: boolean, opt_force?: boolean): ES6Element; + + /** + * This method returns a previously stored arbitrary data from this element. + * @returns {*} - the previously stored data object or null if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this UI element. + * @param data {*} - the data to be stored + */ + setData(data: any): void; + + /** + * This method returns the HTML element this UI element renders. + * + * Note: Before the UI element was rendered the method returns null. + * @returns {?HTMLElement} - the element + */ + getElement(): HTMLElement; + + /** + * Sets the visibility of this element. + * @param visibility {boolean} - visibility + */ + setVisibility(visibility: boolean): void; + + /** + * Returns the visibility of this element. + * @returns {boolean} - visibility + */ + getVisibility(): boolean; + + /** + * This method adds a CSS class to this UI element (if it is not already present). + * @param className {string} - the CSS class name to add + * @returns {H.ui.base.Element} - this UI element instance + */ + addClass(className: string): Element; + + /** + * This method removes a CSS class from this UI element (if it is present). + * @param className {string} - the CSS class name to remove + * @returns {H.ui.base.Element} - this UI element instance + */ + removeClass(className: string): Element; + } + + export class Element extends H.util.EventTarget { + /** + * Constructor + * @param opt_elementType {string=} - the type of HTML element this UI element renders as, default is 'div' + * @param opt_className {string=} - an optional class name to be used on this element + */ + constructor(opt_elementType?: string, opt_className?: string); + + /** + * This method is the concrete implementation of the UI element. This method receives the pre-rendered HTML element which may be modified by deriving classes. + * @param element {Element} - this UI element's HTML representation + * @param doc {Document} - the HTML document into which the element is currently being rendered + */ + renderInternal(element: ES6Element, doc: Document): void; + + /** + * This method returns this UI element's disabled state as a boolean value. + * @returns {boolean} - true if the element is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method set's the disabled state of this UI element. + * @param disabled {boolean} - true to disable the element, false to enable it + * @param opt_force {boolean=} - an optional boolean flag indicating that the value should be set and propagated even if it is the same as the current state + * @returns {H.ui.base.Element} - this element instance + */ + setDisabled(disabled: boolean, opt_force?: boolean): ES6Element; + + /** + * This method returns a previously stored arbitrary data from this element. + * @returns {*} - the previously stored data object or null if not data was stored. + */ + getData(): any; + + /** + * This method stores arbitrary data with this UI element. + * @param data {*} - the data to be stored + */ + setData(data: any): void; + + /** + * This method returns the HTML element this UI element renders. + * + * Note: Before the UI element was rendered the method returns null. + * @returns {?HTMLElement} - the element + */ + getElement(): HTMLElement; + + /** + * Sets the visibility of this element. + * @param visibility {boolean} - visibility + */ + setVisibility(visibility: boolean): void; + + /** + * Returns the visibility of this element. + * @returns {boolean} - visibility + */ + getVisibility(): boolean; + + /** + * This method adds a CSS class to this UI element (if it is not already present). + * @param className {string} - the CSS class name to add + * @returns {H.ui.base.Element} - this UI element instance + */ + addClass(className: string): Element; + + /** + * This method removes a CSS class from this UI element (if it is present). + * @param className {string} - the CSS class name to remove + * @returns {H.ui.base.Element} - this UI element instance + */ + removeClass(className: string): Element; + } + } + + /** + * Namespace contains functionality related to internationalization. + */ + export module i18n { + /** + * Default available locales. UI provides default translations for this set of locale codes. + */ + export const defaultLocales: Array; + + /** + * This class is used for internationalization of UI components. + */ + export class Localization { + constructor(locale: string, opt_translationMap?: any); + + /** + * This method returns current locale code i.e 'en-US' + * @returns {string} - locale code + */ + getLocale(): string; + + /** + * This method returns translation keys for current locale. Keys from this set can be used to get translations via translate method. + * @returns {Array} + */ + getKeys(): Array; + + /** + * This method returns a boolean value indicating whether this localization object has a translation for the specified translation key. + * @param key {string} - a translation key + * @returns {boolean} - true if the key exists, otherwise false + */ + hasKey(key: string): boolean; + + /** + * This method returns translation for provided key. It throws exception if translation is not available + * @param key {string} - a translation key + * @returns {string} - a localized string corresponding to provided key + */ + translate(key: string): string; + } + } + } + + /***** util *****/ + export module util { + /** + * The cache represents a in-memory LRU-cache with a fixed size. It stores any data that is added until the cache's content exceeds a maximum size. Once the size of all content elements exceeds the maximum size the cache will drop the least recently retrieved elements until the size of the cache is within the bounds of its maximum size. Data elements are always associated with an identifier that allow to retrieve them at a later stage and their content size. + */ + export class Cache implements H.util.ICache { + /** + * Constructor + * @param maxSize {number} - the maximum size of the cache + * @param opt_onDrop {function(string, ?, number)=} - A callback to be invoked when a data element is dropped from the cache + * @param opt_filter {(function(string, ?, number) : boolean)=} - A function to filter data elements that are not to be cached + */ + constructor(maxSize: number, opt_onDrop?: (s: string, i: any, n: number) => void, opt_filter?: (s: string, i: any, n: number) => boolean); + + /** + * This method sets this cache's maximum size to a new size. If the cache's contents exceed the new size, least recently used data elements will be dropped. + * @param maxSize {number} - the new maximum size of this cache. + * @returns {H.util.Cache} - this cache + */ + setMaxSize(maxSize: number): H.util.Cache; + + /** + * This method returns the maximum size of this cache. + * @returns {number} - the maximum size of the cache + */ + getMaxSize(): number; + + /** + * This method returns the current size of this cache. + * @returns {number} - the current size of the cache + */ + getCurrentSize(): number; + + /** + * This method adds an element to the cache. + * @param id {*} - The identifier of this data element, the value is converted to a string. + * @param data {*} - the actual data to be stored + * @param size {number} - the size of the data element + * @returns {boolean} - a boolean value indicating whether the data was added + */ + add(id: any, data: any, size: number): boolean; + + /** + * This method retrieves an element from the cache. + * @param id {string} - the ID of the data element to be retrieved. + * @param opt_noUpdate {boolean=} - and optional flag to indicate that the retrieved object should not be marked as 'most recently used'. + * @returns {*} - returns the data associated with the ID or undefined if the data element is not currently in the cache. + */ + get(id: string, opt_noUpdate?: boolean): any; + + /** + * This method explicitly drops an element from the cache. + * @param id {*} - the id of the item to drop + */ + drop(id: any): void; + + /** + * This method will execute the provided callback function on each of the cache's entries. If the optional match predicate is passed to this method the callback will only be executed on those entries for which the predicated returns true. + * @param callback {function(string, ?, number)} - the callback to be invoked for each entry + * @param opt_ctx {Object=} - an optional context object to be used as this within the callback + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional match predicate to customize on which entries the callback will be called + */ + forEach(callback: (s: string, i: any, n: number) => void, opt_ctx?: any, opt_matcher?: (s: string, i: any, n: number) => boolean): void; + + /** + * This method removes all data elements from the cache. If the optional match predicate is passed to this method only those data elements will be removed for which the predicate return true. + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional function that receives an entries id, data and size and may return true or false to either remove it or leave the entry in the cache respectively + */ + removeAll(opt_matcher?: (s: string, i: any, n: number) => boolean): void; + + /** + * This method registers a callback that should be called each time an entry is dropped from the cache. + * @param callback {(function(string, ?, number))} - the callback to be invoked for each entry + */ + registerOnDrop(callback: (s: string, i: any, n: number) => void): void; + } + + /** + * This event indicates a change. It contains the old and the new value. + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class ChangeEvent extends H.util.Event { + /** + * Constructor + * @param type {string} - The type of the event + * @param newValue {*} - The new value of the property + * @param oldValue {*} - The previous value of the property + */ + constructor(type: string, newValue: any, oldValue: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + + /** + * This class represents a contextual information/action. + * @property SEPARATOR {H.util.ContextItem} - Separator for the context items + */ + export class ContextItem extends H.util.EventTarget { + /** + * Constructor + * @param opt_options {H.util.ContextItem.Options=} - The values to initialize this context item + */ + constructor(opt_options?: H.util.ContextItem.Options); + + /** + * This method returns label of the context item + * @returns {string} - the label of the context item + */ + getLabel(): string; + + /** + * This method changes context item label to the specified one + * @param label {string} - New label for the context item + * @returns {H.util.ContextItem} - this context item instance + */ + setLabel(label: string): H.util.ContextItem; + + /** + * This method returns disabled state of the context item. + * @returns {boolean} - true if the item is disabled, false otherwise + */ + isDisabled(): boolean; + + /** + * This method enables/disables the context item + * @param disabled {boolean} - true to disable and false to enabled it + * @returns {H.util.ContextItem} - this context item instance + */ + setDisabled(disabled: boolean): H.util.ContextItem; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + + static SEPARATOR: H.util.ContextItem; + } + + export module ContextItem { + /** + * This type defines options which can be used to initialize the context item. + * @property label {string=} - the label of the context item + * @property disabled {boolean=} - flag indicatting whether context item is disabled or no, by default false + * @property callback {function(H.util.Event)=} - Optional callback function to call once context item is selected + */ + export interface Options { + label?: string; + disabled?: boolean; + callback?: (event: H.util.Event) => void; + } + } + + /** + * Object which can be safely disposed. + */ + export class Disposable { + /** + * Constructor + */ + constructor(); + + /** + * Method adds a callback which will be triggered when the object is disposed + * @param callback {Function} + * @param opt_scope {Object=} + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + /** + * Base Event class which is used for all events dispatched by any EventTarget within the api. + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event { + /** + * Constructor + * @param type {string} - Event Type. + * @param opt_target {Object=} - Reference to the object that is the target of this event. It has to implement the {@link EventTargetInstance} interface. + */ + constructor(type: string, opt_target?: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + + /** + * EventTarget enabled listening and dispatching events on all instances and derived classes. + */ + export class EventTarget { + /** + * Constructor + */ + constructor(); + + /** + * This method allows to listen for specific event triggered by the object. Keep in mind, that you must removeEventListener manually or dispose an object when you no longer need it. Otherwise memory leak is possible. + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + addEventListener(type: string, handler: EventListenerOrEventListenerObject, opt_capture?: boolean, opt_scope?: any): void; + + /** + * This method will removed previously added listener from the event target + * @param type {string} - name of event + * @param handler {Function} - event handler function + * @param opt_capture {boolean=} - if set to true will listen in the capture phase (bubble otherwise) + * @param opt_scope {Object=} - scope for the handler function + */ + removeEventListener(type: string, handler: EventListenerOrEventListenerObject, opt_capture?: boolean, opt_scope?: any): void; + + /** + * This method will dispatch event on the event target object + * @param evt {H.util.Event | string} - event object or event name + */ + dispatchEvent(evt: H.util.Event | string): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: () => void, opt_scope?: any): void; + } + + /** + * An interface definition for the generic cache. Any data elements can be stored in the cache. They are always associated with an identifier to retrieve them at a later stage and their content size. + */ + export interface ICache { + /** + * This method adds an element to the cache. + * @param id {*} - The identifier of this data element, the value is converted to a string. + * @param data {*} - the actual data to be stored + * @param size {number} - the size of the data element + * @returns {boolean} - a boolean value indicating whether the data was added + */ + add(id: any, data: any, size: number): boolean; + + /** + * This method retrieves an element from the cache. + * @param id {string} - the ID of the data element to be retrieved. + * @param opt_noUpdate {boolean=} - and optional flag to indicate that the retrieved object should not be marked as 'most recently used'. + * @returns {*} - returns the data associated with the ID or undefined if the data element is not currently in the cache. + */ + get(id: string, opt_noUpdate?: boolean): any; + + /** + * This method explicitly drops an element from the cache. + * @param id {*} - the id of the item to drop + */ + drop(id: any): void; + + /** + * This method will execute the provided callback function on each of the cache's entries. If the optional match predicate is passed to this method the callback will only be executed on those entries for which the predicated returns true. + * @param callback {function(string, ?, number)} - the callback to be invoked for each entry + * @param opt_ctx {Object=} - an optional context object to be used as this within the callback + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional match predicate to customize on which entries the callback will be called + */ + forEach(callback: (s: string, t: any, n: number) => void, opt_ctx?: Object, opt_matcher?: ((s: string, t: any, n: number) => boolean)): void; + + /** + * This method removes all data elements from the cache. If the optional match predicate is passed to this method only those data elements will be removed for which the predicate return true. + * @param opt_matcher {(function(string, ?, number) : boolean)=} - an optional function that receives an entries id, data and size and may return true or false to either remove it or leave the entry in the cache respectively + */ + removeAll(opt_matcher?: ((s: string, t: any, n: number) => boolean)): void; + + /** + * This method registers a callback that should be called each time an entry is dropped from the cache. + * @param callback {(function(string, ?, number))} - the callback to be invoked for each entry + */ + registerOnDrop(callback: ((s: string, t: any, n: number) => void)): void; + } + + /** + * An interface to cancelable requests and actions. + */ + export interface ICancelable { + /** + * This method is used to cancel current action + */ + cancel(): void; + } + + export interface ICapturable { + /** + * This method is used to capture the element view + * @param canvas {HTMLCanvasElement} - HTML Canvas element to draw the view of the capturable element + * @param pixelRation {number} - The pixelRatio to use for over-sampling in cases of high-resolution displays, default is 1 + * @param callback {ICapturable~captureCallback} - Callback function to call once result of the capturing is ready + * @param opt_errback {ICapturable~errorCallback} - Callback function to call if error occurred during capturing + */ + capture(canvas: HTMLCanvasElement, pixelRation: number, callback: (canvas?: HTMLCanvasElement) => void, opt_errback?: (error: string) => void): void; + + /** + * @callback ICapturable~captureCallback + * @param canvas {HTMLCanvasElement=} + */ + + /** + * @callback ICapturable~errorCallback + * @param error {string} + */ + } + + /** + * This class represents an list of ordered entries which dispatches events when the list is modified. + * @event add {H.util.OList.Event} - Fired when an entry was added to the list. + * @event remove {H.util.OList.Event} - Fired when an entry was removed from the list. + * @event set {H.util.OList.Event} - Fired when an entry was set in the list. + * @event move {H.util.OList.Event} - Fired when an entry was moved within the list. + */ + export class OList extends H.util.EventTarget { + + /** + * This method inserts an entry to the list. Optionally it can place new entry at provided index. + * @param entry {?} - The entry to insert + * @param opt_idx {number=} - The index where the new entry should be inserted; if omitted or greater then the current size of the list, the entry is added at the end of the list; a negative index is treated as being relative from the end of the list + */ + add(entry: any, opt_idx?: number): void; + + /** + * This method removes an entry by a given index from the list. + * @param idx {number} - The index of the entry which should be removed; a negative index is treated as being relative from the end of the list + * @returns {?} - The removed entry + */ + removeAt(idx: number): any; + + /** + * This method removes the the first entry which is identical with the given entry. + * @param entry {?} - The entry to remove + * @returns {boolean} - signals if the entry could be found in the list and is removed + */ + remove(entry: any): boolean; + + /** + * This method replaces an entry at the given index with the given entry. + * @param idx {number} - The index of the entry which should be replaced; a negative index is treated as being relative from the end of the list + * @param entry {?} - The entry which replaces the existing one + * @returns {?} - The replaced entry + */ + set(idx: number, entry: any): any; + + /** + * This method retrieves the index of the first object in this list that is identical with the object supplied by the caller. + * @param entry {?} - The entry for which to return the index. + * @returns {number} - The index of the first matching entry in this list or -1 if the entry provided by the caller is not found in the list + */ + indexOf(entry: any): number; + + /** + * To get the entry at the specified index. + * @param idx {number} - The index of the entry to get a negative index is treated as being relative from the end of the list + * @returns {?} - The element at the given index + */ + get(idx: number): any; + + /** + * This method returns the length of the list. + * @returns {number} + */ + getLength(): number; + + /** + * This method returns all list's entries as an array. + * @returns {Array<*>} - The list as an array + */ + asArray(): Array; + + /** + * This method removes all entries from the list. + */ + flush(): void; + + /** + * This method will dispatch event on the event target object + * @param evt {(H.util.Event | string)} - event object or event name + */ + dispatchEvent(evt: (H.util.Event | string)): void; + + /** + * Removes listeners from this object. Classes that extend EventTarget may need to override this method in order to remove references to DOM Elements and additional listeners. + */ + dispose(): void; + + /** + * This method adds callback which is triggered when the object is being disposed + * @param callback {Function} - The callback function. + * @param opt_scope {Object=} - An optional scope to call the callback in. + */ + addOnDisposeCallback(callback: Function, opt_scope?: Object): void; + } + + export module OList { + /** + * The event class for events that are dispatched by OList + * @property target {*} - Object which triggered the event + * @property currentTarget {*} - Object which has listener attached + * @property type {string} - Name of the dispatched event + * @property defaultPrevented {boolean} - Indicates if preventDefault was called on the current event + */ + export class Event extends H.util.Event { + /** + * Constructor + * @param list {H.util.OList} - The OList instance which is emitting the event + * @param type {H.util.OList.prototype.EventType} - The type of the event + * @param idx {number} - The affected index within this list + * @param added {?*} - The value of the entry which was added or set + * @param removed {?*} - The value of the entry which was removed or replaced + * @param moved {?*} - The value of the entry which was moved + */ + constructor(list: H.util.OList, type: string, idx: number, added: any, removed: any, moved: any); + + /** + * Sets defaultPrevented to true. Which can be used to prevent some default behavior. + */ + preventDefault(): void; + + /** + * Stops propagation for current event. + */ + stopPropagation(): void; + + target: any; + currentTarget: any; + type: string; + defaultPrevented: boolean; + } + } + + /** + * A generic class to represent a handle for any kind of asynchronous processed requests + */ + export class Request { + /** + * Constructor + * @param opt_onprogress {function(H.util.Request)=} - A callback to invoke every time when the request's progress state changes + * @param opt_total {number=} - The total number of processing steps to complete this request, default is 1 + */ + constructor(opt_onprogress?: (req: H.util.Request) => void, opt_total?: number); + + /** + * Returns the state of this request + * @returns {H.util.Request.State} + */ + getState(): H.util.Request.State; + + /** + * Returns the number of processing steps to complete this request + * @returns {number} + */ + getTotal(): number; + + /** + * Returns the number of steps which are already processed by this request + * @returns {number} + */ + getProcessed(): number; + + /** + * Returns the number of processingsteps which have been failed + * @returns {number} + */ + getFailed(): number; + } + + export module Request { + /** + * The supported states of an request + */ + export enum State { + PENDING, + PROCESSING, + COMPLETE, + CANCELLED, + ERROR, + } + } + + export module animation { + /** + * This mamespace contains easing functions used for Animation class. + */ + export class ease { + /** + * This function defines linear ease. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static LINEAR(val: number): number; + + /** + * This function defines quadratic ease in. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_IN_QUAD(val: number): number; + + /** + * This function defines quadratic ease out. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_OUT_QUAD(val: number): number; + + /** + * This function defines ease in and out with slope. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_IN_OUT_QUINT(val: number): number; + + /** + * This function defines ease out with circ function. + * @param val {number} - A value in range [0..1] to translate + * @returns {number} - the translated value + */ + static EASE_OUT_CIRC(val: number): number; + } + } + + export module kinetics { + /** + * This interface defines kinetic move parameters used by map for kinetic drag. + * @property power {number} - Power multiplier. Multiplier is used to increase the speed of the kinetic move. By default map uses 1. + * @property duration {number} - Defines duration of the kinetic move. + */ + export interface IKinetics { + /** + * Easing function modifies animation progress. In example it can modify the animation in a way it starts rapidly and then slows down at the end. + * @param p {number} - current progress + * @returns {number} - modified progress + */ + ease(p: number): number; + + power: number; + duration: number; + } + } + } +} From ba79abdc6a48349ee38c6ad854d2b22be8712f5d Mon Sep 17 00:00:00 2001 From: Rodrigo Fernandes Date: Tue, 30 Aug 2016 13:57:58 +0100 Subject: [PATCH 44/68] Add diff2html typings and tests (#10681) --- diff2html/diff2html-tests.ts | 26 ++++++++++++++ diff2html/diff2html.d.ts | 66 ++++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 diff2html/diff2html-tests.ts create mode 100644 diff2html/diff2html.d.ts diff --git a/diff2html/diff2html-tests.ts b/diff2html/diff2html-tests.ts new file mode 100644 index 0000000000..35448baa90 --- /dev/null +++ b/diff2html/diff2html-tests.ts @@ -0,0 +1,26 @@ +/// + +import Diff2Html = require('diff2html'); + +let d2h = Diff2Html.Diff2Html; + +class Diff2HtmlOptionsImpl implements Diff2Html.Options { + constructor (public inputFormat: string) { + } +} + +let strInput = + 'diff --git a/sample b/sample\n' + + 'index 0000001..0ddf2ba\n' + + '--- a/sample\n' + + '+++ b/sample\n' + + '@@ -1 +1 @@\n' + + '-test\n' + + '+test1r\n'; + +let strConfiguration = new Diff2HtmlOptionsImpl('diff'); +let diffInput = d2h.getJsonFromDiff(strInput, strConfiguration); + +let diffConfiguration = new Diff2HtmlOptionsImpl('json'); +let htmlString = d2h.getPrettyHtml(diffInput, diffConfiguration); +console.log(htmlString); diff --git a/diff2html/diff2html.d.ts b/diff2html/diff2html.d.ts new file mode 100644 index 0000000000..398cb1aba1 --- /dev/null +++ b/diff2html/diff2html.d.ts @@ -0,0 +1,66 @@ +// Type definitions for diff2html +// Project: https://github.com/rtfpessoa/diff2html +// Definitions by: rtfpessoa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Diff2Html { + + export interface Options { + inputFormat?: string; + outputFormat?: string; + showFiles?: boolean; + matching?: string; + synchronisedScroll?: boolean; + matchWordsThreshold?: number; + matchingMaxComparisons?: number; + } + + export interface Line { + content: string; + type: string; + oldNumber: number; + newNumber: number; + } + + export interface Block { + oldStartLine: number; + oldStartLine2?: number; + newStartLine: number; + header: string; + lines: Line[]; + } + + export interface Result { + addedLines: number; + deletedLines: number; + isCombined: boolean; + isGitDiff: boolean; + oldName: string; + newName: string; + language: string; + blocks: Block[]; + oldMode?: string; + newMode?: string; + deletedFileMode?: string; + newFileMode?: string; + isDeleted?: boolean; + isNew?: boolean; + isCopy?: boolean; + isRename?: boolean; + unchangedPercentage?: number; + changedPercentage?: number; + checksumBefore?: string; + checksumAfter?: string; + mode?: string; + } + + export interface Diff2Html { + getJsonFromDiff(input: string, configuration?: Options): Result; + getPrettyHtml(input: any, configuration?: Options): string; + } +} + +declare module "diff2html" { + var d2h: { "Diff2Html": Diff2Html.Diff2Html }; + export = d2h; +} From ecacd0de3800f4f31a743944bf66faba9a315753 Mon Sep 17 00:00:00 2001 From: Aman Mahajan Date: Tue, 30 Aug 2016 06:00:06 -0700 Subject: [PATCH 45/68] Adding type definitions for gulp-angular-templatecache (#10860) --- .../gulp-angular-templatecache-tests.ts | 36 ++++++++++ .../gulp-angular-templatecache.d.ts | 69 +++++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 gulp-angular-templatecache/gulp-angular-templatecache-tests.ts create mode 100644 gulp-angular-templatecache/gulp-angular-templatecache.d.ts diff --git a/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts new file mode 100644 index 0000000000..fd7a053ce6 --- /dev/null +++ b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts @@ -0,0 +1,36 @@ +/// +/// + +import * as gulp from 'gulp'; +import * as templateCache from 'gulp-angular-templatecache'; + +gulp.task('templatecache:no-arguments', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache()) + .pipe(gulp.dest('public')); +}); + +gulp.task('templatecache:with-filename', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache('templates.js')) + .pipe(gulp.dest('public')); +}); + +gulp.task('templatecache:with-options', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache({ + filename: 'templates.js', + standalone: true, + module: 'app.templates' + })) + .pipe(gulp.dest('public')); +}); + +gulp.task('templatecache:with-filename-and-options', function () { + return gulp.src('templates/**/*.html') + .pipe(templateCache('templates.js', { + standalone: true, + module: 'app.templates' + })) + .pipe(gulp.dest('public')); +}); \ No newline at end of file diff --git a/gulp-angular-templatecache/gulp-angular-templatecache.d.ts b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts new file mode 100644 index 0000000000..34e52acc36 --- /dev/null +++ b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts @@ -0,0 +1,69 @@ +// Type definitions for gulp-angular-templatecache v2.0.0 +// Project: https://github.com/miickel/gulp-angular-templatecache +// Definitions by: Aman Mahajan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "gulp-angular-templatecache" { + function templatecache(): NodeJS.ReadWriteStream; + function templatecache(filename: string): NodeJS.ReadWriteStream; + function templatecache(options: templatecache.Options): NodeJS.ReadWriteStream; + function templatecache(filename: string, options: templatecache.Options): NodeJS.ReadWriteStream; + + namespace templatecache { + interface Options { + /** + * Name to use when concatenating. + */ + filename?: string; + + /** + * Prefix for template URLs. + */ + root?: string; + + /** + * Name of AngularJS module. + */ + module?: string; + + /** + * Create a new AngularJS module, instead of using an existing. + */ + standalone?: boolean; + + /** + * Override file base path. + */ + base?: string | Function; + + /** + * Wrap the templateCache in a module system. Currently supported systems: RequireJS, Browserify, ES6 and IIFE (Immediately-Invoked Function Expression). + */ + moduleSystem?: string; + + /** + * Transform the generated URL before it's put into $templateCache. + */ + transformUrl?: Function; + + /** + * Override template header. + */ + templateHeader?: string; + + /** + * Override template body. + */ + templateBody?: string; + + /** + * Override template footer. + */ + templateFooter?: string; + } + } + + export = templatecache; +} \ No newline at end of file From b0a3b266bc1851b2cd45df16509d73be5c7b6392 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elis=C3=A9e=20Maurer?= Date: Tue, 30 Aug 2016 15:00:16 +0200 Subject: [PATCH 46/68] slate-irc: Add a few more event types (#10861) * slate-irc; Add a few more event types * slate-irc: Add missing client field in ModeEvent --- slate-irc/slate-irc.d.ts | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/slate-irc/slate-irc.d.ts b/slate-irc/slate-irc.d.ts index 5f9d947bca..4bd6957a93 100644 --- a/slate-irc/slate-irc.d.ts +++ b/slate-irc/slate-irc.d.ts @@ -23,9 +23,16 @@ declare module "slate-irc" { motd: string[]; } + interface TopicEvent { + nick: string; + hostmask: string; + channel: string; + topic: string; + } + interface MessageEvent { from: string; - hostmask: any; + hostmask: string; to: string; message: string; } @@ -48,6 +55,18 @@ declare module "slate-irc" { new: string; } + interface ModeEvent { + nick: string; + target: string; + mode: string; + client: string; + } + + interface AwayEvent { + nick: string; + message: string; + } + interface QuitEvent { nick: string; hostmask: string; @@ -87,9 +106,12 @@ declare module "slate-irc" { on(event: "message", callback: (event: MessageEvent) => void): void; on(event: "notice", callback: (event: MessageEvent) => void): void; on(event: "motd", callback: (event: MOTDEvent) => void): void; + on(event: "topic", callback: (event: TopicEvent) => void): void; on(event: "join", callback: (event: JoinEvent) => void): void; on(event: "part", callback: (event: PartEvent) => void): void; on(event: "nick", callback: (event: NickEvent) => void): void; + on(event: "mode", callback: (event: ModeEvent) => void): void; + on(event: "away", callback: (event: AwayEvent) => void): void; on(event: "quit", callback: (event: QuitEvent) => void): void; } } From 53539f31f67e79a4ff3e23d5e9761029fabccccd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Tue, 30 Aug 2016 07:00:29 -0600 Subject: [PATCH 47/68] Added saveTransaction and transaction definitions to Connection (#10850) --- tedious/tedious-tests.ts | 9 +++++++-- tedious/tedious.d.ts | 26 +++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/tedious/tedious-tests.ts b/tedious/tedious-tests.ts index bbfdb7629c..d039ab6a2b 100644 --- a/tedious/tedious-tests.ts +++ b/tedious/tedious-tests.ts @@ -13,7 +13,7 @@ var config: tedious.ConnectionConfig = { database: "somedb", instanceName: "someinstance", } -} +}; var connection = new tedious.Connection(config); connection.on("connect", (): void => { @@ -23,7 +23,12 @@ connection.on("connect", (): void => { connection.beginTransaction((error: Error): void => {}, "some name"); connection.rollbackTransaction((error: Error): void => {}); connection.commitTransaction((error: Error): void => {}); - +connection.saveTransaction((error: Error): void => {}); +connection.transaction((error: Error, done: (error?: Error) => void): void => { + done(); + done(error); +}, "some name", tedious.ISOLATION_LEVEL.NO_CHANGE); +connection.transaction((error: Error, done: (error?: Error) => void): void => {}); var request = new tedious.Request("SELECT * FROM foo", (error: Error, rowCount: number): void => { }); diff --git a/tedious/tedious.d.ts b/tedious/tedious.d.ts index 0be051c91f..e790c24b51 100644 --- a/tedious/tedious.d.ts +++ b/tedious/tedious.d.ts @@ -443,7 +443,7 @@ declare module 'tedious' { * a connection, another request should not be initiated until this callback is called. * @param callback The callback is called when the request to start the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. * @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. Required when isolationLevel is present. - * @param isolationLevel The isolation level that the transaction is to be run with. + * @param isolationLevel The isolation level that the transaction is to be run with. */ beginTransaction(callback: (error?: Error) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void; @@ -456,12 +456,32 @@ declare module 'tedious' { commitTransaction(callback: (error: Error) => void): void; /** - * Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. - * @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * Rollback a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. + * @param callback The callback is called when the request to rollback the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. */ rollbackTransaction(callback: (error: Error) => void): void; + /** + * Set a savepoint within a transaction. There should be an active transaction. That is, beginTransaction should have been previously called. + * @param callback The callback is called when the request to set a savepoint within the transaction has completed, either successfully or with an error. If an error occured then err will describe the error. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + */ + saveTransaction(callback: (error: Error) => void): void; + + /** + * Run the given callback after starting a transaction, and commit or rollback the transaction afterwards. + * This is a helper that employs beginTransaction, commitTransaction, rollbackTransaction and saveTransaction to greatly simplify the use of database transactions and automatically handle transaction nesting. + * @param callback The callback is called when the request to start a transaction (or create a savepoint, in the case of a nested transaction) has completed, either successfully or with an error. + * If an error occured, then err will describe the error. If no error occured, the callback should perform its work and eventually call done with an error or null + * (to trigger a transaction rollback or a transaction commit) and an additional completion callback that will be called when the request to rollback or commit the current transaction + * has completed, either successfully or with an error. Additional arguments given to done will be passed through to this callback. + * As only one request at a time may be executed on a connection, another request should not be initiated until this callback is called. + * @param name A string representing a name to associate with the transaction. Optional, and defaults to an empty string. In case of a nested transaction, naming the transaction name has no effect. + * @param isolationLevel The isolation level that the transaction is to be run with. + */ + transaction(callback: (error: Error, done: (error?: Error) => void) => void, name?: string, isolationLevel?: ISOLATION_LEVEL): void; + /** * Prepare the SQL represented by the request. The request can then be used in subsequent calls to execute and unprepare * @param request A Request object representing the request. Parameters only require a name and type. Parameter values are ignored. From f5d2481f7eac0951596e8ecefe41229e1eb10c51 Mon Sep 17 00:00:00 2001 From: Matanel Sindilevich Date: Tue, 30 Aug 2016 16:06:02 +0300 Subject: [PATCH 48/68] Morris.js typings miss the module declaration (https://github.com/DefinitelyTyped/DefinitelyTyped/issues/10865). (#10867) --- morris.js/morris.js.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/morris.js/morris.js.d.ts b/morris.js/morris.js.d.ts index 79598ee5c3..cf0af054b6 100644 --- a/morris.js/morris.js.d.ts +++ b/morris.js/morris.js.d.ts @@ -1,6 +1,6 @@ // Type definitions for morris.js 0.5.1 // Project: http://morrisjs.github.io/morris.js/ -// Definitions by: Matthieu Mourisson +// Definitions by: Matthieu Mourisson , Matanel Sindilevich // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace morris { @@ -143,4 +143,8 @@ declare namespace morris { } } -declare var Morris: morris.MorrisStatic; +declare module "morris" { + export = Morris; +} + +declare var Morris: morris.MorrisStatic; \ No newline at end of file From 75cf3ac5ede1eb563d22ce3b54fb9de4171e7a34 Mon Sep 17 00:00:00 2001 From: poseidonCore Date: Tue, 30 Aug 2016 23:10:55 +1000 Subject: [PATCH 49/68] Worker.send and ChildProcess.send should return Booleans (#10866) https://nodejs.org/dist/latest-v6.x/docs/api/all.html#child_process_child_send_message_sendhandle_options_callback https://nodejs.org/dist/latest-v6.x/docs/api/all.html#cluster_worker_send_message_sendhandle_callback --- node/node.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 731b136585..c7df8463b3 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -749,7 +749,7 @@ declare module "cluster" { id: string; process: child.ChildProcess; suicide: boolean; - send(message: any, sendHandle?: any): void; + send(message: any, sendHandle?: any): boolean; kill(signal?: string): void; destroy(signal?: string): void; disconnect(): void; @@ -1071,7 +1071,7 @@ declare module "child_process" { stdio: [stream.Writable, stream.Readable, stream.Readable]; pid: number; kill(signal?: string): void; - send(message: any, sendHandle?: any): void; + send(message: any, sendHandle?: any): boolean; connected: boolean; disconnect(): void; unref(): void; @@ -2628,4 +2628,4 @@ declare module "constants" { declare module "process" { export = process; -} \ No newline at end of file +} From eaeea6e83fc58f97a789813de62e8a387dd5fe97 Mon Sep 17 00:00:00 2001 From: Thodoris Greasidis Date: Tue, 30 Aug 2016 16:44:10 +0300 Subject: [PATCH 50/68] fix(localforage): use `export =` since it's a UMD module --- localForage/localForage.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/localForage/localForage.d.ts b/localForage/localForage.d.ts index 803bde9e57..c727d93b3a 100644 --- a/localForage/localForage.d.ts +++ b/localForage/localForage.d.ts @@ -96,6 +96,6 @@ interface LocalForage { } declare module "localforage" { - export var localforage: LocalForage; - export default localforage; + var localforage: LocalForage; + export = localforage; } From 44c49ae9c03e370b9cbe18e4d223e83945a2185c Mon Sep 17 00:00:00 2001 From: Honza Kalfus Date: Tue, 30 Aug 2016 16:15:35 +0200 Subject: [PATCH 51/68] Added react-native requireNativeComponent function (#10712) * Added react-native requireNativeComponent function * Replaced "any" in requireNativeComponent and ComponentInterface with generics --- react-native/react-native.d.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index cc71452ae4..732e4aacde 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -5977,6 +5977,20 @@ declare namespace __React { export var NativeModules: any export var NativeAppEventEmitter: NativeAppEventEmitterStatic + + //////////// Plugins ////////////// + export interface ComponentInterface

{ + name?: string; + displayName?: string; + propTypes: P + } + + export function requireNativeComponent

( + viewName: string, + componentInterface?: ComponentInterface

, + extraConfig?: {nativeOnly: Object} + ): React.ComponentClass

; + // // /TODO: BGR: These are leftovers of the initial port that must be revisited // From 67827a1e39dc91bf66a79b04f36e9eb85e075e10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Tue, 30 Aug 2016 08:19:56 -0600 Subject: [PATCH 52/68] Added entries, includes, keys and values to Buffer (#10809) --- node/node-tests.ts | 41 +++++++++++++++++++++++++++++++++++++++++ node/node.d.ts | 8 ++++---- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index bd19697f31..a35696fea6 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -259,6 +259,47 @@ function bufferTests() { index = buffer.lastIndexOf(buffer); } + { + let buffer = new Buffer('123'); + let val: [number, number]; + + for (let entry of buffer.entries()) { + val = entry; + } + } + + { + let buffer = new Buffer('123'); + let includes: boolean; + includes = buffer.includes("23"); + includes = buffer.includes("23", 1); + includes = buffer.includes("23", 1, "utf8"); + includes = buffer.includes(23); + includes = buffer.includes(23, 1); + includes = buffer.includes(23, 1, "utf8"); + includes = buffer.includes(buffer); + includes = buffer.includes(buffer, 1); + includes = buffer.includes(buffer, 1, "utf8"); + } + + { + let buffer = new Buffer('123'); + let val: number; + + for (let key of buffer.keys()) { + val = key; + } + } + + { + let buffer = new Buffer('123'); + let val: number; + + for (let value of buffer.values()) { + val = value; + } + } + // Imported Buffer from buffer module works properly { let b = new ImportedBuffer('123'); diff --git a/node/node.d.ts b/node/node.d.ts index c7df8463b3..6959b38f15 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -505,10 +505,10 @@ interface NodeBuffer extends Uint8Array { fill(value: any, offset?: number, end?: number): this; indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; - // TODO: entries - // TODO: includes - // TODO: keys - // TODO: values + entries(): IterableIterator<[number, number]>; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + keys(): IterableIterator; + values(): IterableIterator; } /************************************************ From 8fb286186bd170e3abc1b1601a7e84eda00490fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Bitard?= Date: Tue, 30 Aug 2016 16:20:27 +0200 Subject: [PATCH 53/68] update react-mdl 1.5.3 -> 1.7.0 (#10881) --- react-mdl/react-mdl-tests.tsx | 31 ++++++++++++++++++++++++++++++- react-mdl/react-mdl.d.ts | 19 +++++++++++++++---- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/react-mdl/react-mdl-tests.tsx b/react-mdl/react-mdl-tests.tsx index 1e7fd19b0c..fe775eb4a4 100644 --- a/react-mdl/react-mdl-tests.tsx +++ b/react-mdl/react-mdl-tests.tsx @@ -2,7 +2,8 @@ /// import * as React from 'react'; -import {Badge, +import {Chip, ChipContact, + Badge, FABButton, Button, IconButton, Card, CardActions, CardTitle, CardText, CardMenu, CardMedia, Checkbox, @@ -50,6 +51,34 @@ React.createClass({ } }); +// Chip tests +React.createClass({ + render: function() { + return ( +

+ Basic chip + + { alert('Close icon clicked!'); }}>Deletable Chip + + { alert('Clicked!'); }}>Button Chip + {/* Contact Chip */} + + A + Contact chip + + + {/* User Contact Chip */} + { alert('Close icon clicked!'); }}> + + Deletable user contact chip + +
+ ); + } +}); + // Button tests React.createClass({ render: function() { diff --git a/react-mdl/react-mdl.d.ts b/react-mdl/react-mdl.d.ts index 56d688c7f4..c3786bd662 100644 --- a/react-mdl/react-mdl.d.ts +++ b/react-mdl/react-mdl.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-mdl 1.5.3 +// Type definitions for react-mdl 1.7.0 // Project: https://github.com/tleunen/react-mdl // Definitions by: Brad Zacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -275,8 +275,17 @@ declare namespace __ReactMDL { overlap ?: boolean; } class Badge extends __MDLComponent {} - - + + + interface ChipProps extends __MDLOtherProps { + onClick ?:React.MouseEventHandler; + onClose ?:React.MouseEventHandler; + } + + class Chip extends __MDLComponent {} + + class ChipContact extends __MDLComponent<__MDLOtherProps> {} + interface ButtonProps extends __MDLOtherProps, RippleComponent, CustomRenderedComponent { accent ?: boolean; colored ?: boolean; @@ -401,9 +410,11 @@ declare namespace __ReactMDL { transparent ?: boolean; waterfall ?: boolean; hideTop ?: boolean; + hideSpacer ?: boolean; } interface HeaderRowProps extends __MDLOtherProps { title ?: string; + hideSpacer ?: boolean; } interface HeaderTabsProps extends __MDLOtherProps, RippleComponent { activeTab ?: number; @@ -603,4 +614,4 @@ declare namespace __ReactMDL { declare module 'react-mdl' { export = __ReactMDL; -} \ No newline at end of file +} From f103abe02a769cbd83388076bd0bf96aa671c523 Mon Sep 17 00:00:00 2001 From: Chris Bobo Date: Tue, 30 Aug 2016 07:23:38 -0700 Subject: [PATCH 54/68] Add node-dogstatsd definitions and tests (#10795) * Add node-dogstatsd definitions and tests * Correct project url --- node-dogstatsd/node-dogstatsd-tests.ts | 48 ++++++++++++++++++++++++++ node-dogstatsd/node-dogstatsd.d.ts | 29 ++++++++++++++++ 2 files changed, 77 insertions(+) create mode 100644 node-dogstatsd/node-dogstatsd-tests.ts create mode 100644 node-dogstatsd/node-dogstatsd.d.ts diff --git a/node-dogstatsd/node-dogstatsd-tests.ts b/node-dogstatsd/node-dogstatsd-tests.ts new file mode 100644 index 0000000000..9a32229bd6 --- /dev/null +++ b/node-dogstatsd/node-dogstatsd-tests.ts @@ -0,0 +1,48 @@ +/// + +import * as datadog from 'node-dogstatsd'; + +function test_statsd_client() { + // can create client with defaults + let client = new datadog.StatsD('localhost'); + let options: datadog.StatsDOptions = { global_tags: ['environment:definitely_typed']}; + + // can create client with all params + client = new datadog.StatsD('localhost', 8125, null, options); + + let key: string = 'key'; + let timeValue: number = 99; + let sampleRate: number = 0.85; + let incrementBy: number = 7; + let decrementBy: number = 5; + let gaugeValue: number = 199; + let tags: string[] = ['tag1', 'tag2']; + + client.timing(key, timeValue); + client.timing(key, timeValue, sampleRate); + client.timing(key, timeValue, sampleRate, tags); + + client.increment(key); + client.increment(key, sampleRate); + client.increment(key, sampleRate, tags); + + client.incrementBy(key, incrementBy); + client.incrementBy(key, incrementBy, tags); + + client.decrement(key); + client.decrement(key, sampleRate); + client.decrement(key, sampleRate, tags); + + client.decrementBy(key, decrementBy); + client.decrementBy(key, decrementBy, tags); + + client.gauge(key, gaugeValue); + client.gauge(key, gaugeValue, sampleRate); + client.gauge(key, gaugeValue, sampleRate, tags); + + client.histogram(key, timeValue); + client.histogram(key, timeValue, sampleRate); + client.histogram(key, timeValue, sampleRate, tags); + + client.close(); +} diff --git a/node-dogstatsd/node-dogstatsd.d.ts b/node-dogstatsd/node-dogstatsd.d.ts new file mode 100644 index 0000000000..36f8145202 --- /dev/null +++ b/node-dogstatsd/node-dogstatsd.d.ts @@ -0,0 +1,29 @@ +// Type definitions for Datadog's nodejs metrics client node-dogstatsd +// Project: https://github.com/joybro/node-dogstatsd +// Definitions by: Chris Bobo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "node-dogstatsd" { + + export interface StatsDOptions { + global_tags?: string[]; + } + + export class StatsD { + constructor(host: string, port?: number, socket?: string, options?: StatsDOptions); + + timing(stat: string, time: number, sample_rate?: number, tags?: string[]): void; + + increment(stat: string, sample_rate?: number, tags?: string[]): void; + incrementBy(stat: string, value: number, tags?: string[]): void; + + decrement(stat: string, sample_rate?: number, tags?: string[]): void; + decrementBy(stat: string, value: number, tags?: string[]): void; + + gauge(stat: string, value: number, sample_rate?: number, tags?: string[]): void; + + histogram(stat: string, time: number, sample_rate?: number, tags?: string[]): void; + + close(): void; + } +} From 4862bdef247e94348b0146c9d21a783dca00e6a5 Mon Sep 17 00:00:00 2001 From: Grant Hutchins Date: Tue, 30 Aug 2016 09:28:56 -0500 Subject: [PATCH 55/68] google.maps: Allow LatLngLiteral for MarkerOptions.position (#10882) LatLngLiteral is an acceptable type for MarkerOptions.position See https://developers.google.com/maps/documentation/javascript/3.exp/reference#MarkerOptions and https://developers.google.com/maps/documentation/javascript/3.exp/reference#LatLng --- googlemaps/google.maps.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 0c551fd712..97d29bbf04 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -427,7 +427,7 @@ declare namespace google.maps { /** * Marker position. Required. */ - position: LatLng; + position: LatLng|LatLngLiteral; /** Image map region definition used for drag/click. */ shape?: MarkerShape; /** Rollover text. */ From 46ca501630b8a03168e058f71dd71b8ca007b35a Mon Sep 17 00:00:00 2001 From: Zipeng WU Date: Tue, 30 Aug 2016 16:29:12 +0200 Subject: [PATCH 56/68] Add type definition for Focus (#10884) --- nvd3/nvd3.d.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/nvd3/nvd3.d.ts b/nvd3/nvd3.d.ts index ba70780c38..769d900399 100644 --- a/nvd3/nvd3.d.ts +++ b/nvd3/nvd3.d.ts @@ -126,6 +126,41 @@ declare namespace nv { width(value: number): this; } + interface Focus extends Nvd3Element { + color(value: string[]): this; + color(func: (d: any, i: number) => string): this; + width(): number; + width(value: number): this; + height(): number; + height(value: number): this; + margin(): Margin; + margin(value: Margin): this; + x(): (d: any) => any; + x(func: (d: any) => any): this; + y(): (d: any) => number; + y(func: (d: any) => number): this; + showXAxis(): boolean; + showXAxis(value: boolean): this; + showYAxis(): boolean; + showYAxis(value: boolean): this; + brushExtent(): [number, number] | [[number, number], [number, number]]; + brushExtent(value: [number, number] | [[number, number], [number, number]]) : this; + duration(): number; + duration(value: number): this; + xTickFormat(): (d: any) => string; + xTickFormat(format: (t: any) => string): this; + xTickFormat(format: string): this; + xTickFormat(format: (d: any, i: any) => string): this; + yTickFormat(): (d: any) => string; + yTickFormat(format: (t: any) => string): this; + yTickFormat(format: string): this; + yTickFormat(format: (d: any, i: any) => string): this; + interpolate(): string; + interpolate(value: string): this; + rightAlignYAxis(): boolean; + rightAlignYAxis(value: boolean): this; + } + interface Nvd3Axis extends d3.svg.Axis { axisLabel(): string; axisLabel(value: string): this; @@ -1805,6 +1840,7 @@ id(value: number|string): this; yAxis: Nvd3Axis; legend: Legend; tooltip: Tooltip; + focus: Focus; clearHighlights(): this; /*If true, masks lines within the X and Y scales using a clip-path*/ @@ -3238,6 +3274,7 @@ id(value: number|string): this; yAxis: Nvd3Axis; y2Axis: Nvd3Axis; tooltip: Tooltip; + focus: Focus; controlLabels(): any; /*Object that defines the labels for control items in the graph. For instance, in the stackedAreaChart, there are controls for making it stacked, expanded, or stream. For stacked bar charts, there is stacked and grouped.*/ From 3c2537787bfe9f38e1d1fb5acb205fedfc810de2 Mon Sep 17 00:00:00 2001 From: Ian Ker-Seymer Date: Tue, 30 Aug 2016 10:36:06 -0400 Subject: [PATCH 57/68] Add email_verified property to Auth0UserProfile (#10835) --- auth0-js/auth0-js.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/auth0-js/auth0-js.d.ts b/auth0-js/auth0-js.d.ts index 515d52af7e..250c7a850e 100644 --- a/auth0-js/auth0-js.d.ts +++ b/auth0-js/auth0-js.d.ts @@ -42,6 +42,7 @@ interface Auth0ClientOptions { /** Represents a normalized UserProfile. */ interface Auth0UserProfile { email: string; + email_verified: boolean; family_name: string; gender: string; given_name: string; From e22e65e6f6a391a91be442e277f49f61fc5126be Mon Sep 17 00:00:00 2001 From: Nicholas Iannone Date: Tue, 30 Aug 2016 09:39:05 -0500 Subject: [PATCH 58/68] Tweaked module exporting for Twilio API. (#10885) * Changed exporting syntax. * Fixed import. * Fixed export. * Fixed import statement. --- twilio/twilio-tests.ts | 2 +- twilio/twilio.d.ts | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index 0c9013ede7..30e9892078 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -1,4 +1,4 @@ -import { twilio } from './twilio'; +import * as twilio from './twilio'; // Examples taken from https://twilio.github.io/twilio-node/ (v2.1.0) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 93630f0da2..8ef14760b8 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -12,11 +12,11 @@ import * as Http from 'http'; import q = require('q'); -export interface twilio { +declare interface twilio { (sid?: string, tkn?: string, options?: twilio.ClientOptions): twilio.RestClient; } -export module twilio { +declare module twilio { // Composite Classes: //============================== @@ -871,5 +871,6 @@ export module twilio { originationUrls: OriginationURLResource; } export interface TrunkResource extends ListMappedResource {} +} -} \ No newline at end of file +export = twilio; From d01120d564974dbcecb761deea9ef56c3d1f21f3 Mon Sep 17 00:00:00 2001 From: Nathan Ainslie Date: Tue, 30 Aug 2016 10:54:22 -0400 Subject: [PATCH 59/68] Updates for lodash (#10889) add support for chained .reduce, relates to #10074 --- lodash/lodash-tests.ts | 54 +++++++++++++++++++++++------------------- lodash/lodash.d.ts | 15 ++++++++++++ 2 files changed, 45 insertions(+), 24 deletions(-) diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index 749d9ce972..42fce74b8b 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -4679,32 +4679,38 @@ result = <{a: number}[][]>_({0: {a: 1}, 1: {a: 2}}).partition<{a: number}>('a', // result = _(dictionary).chain().map(['d', 0, 'b']); // } // } +namespace TestReduce { + interface ABC { + [index: string]: number; + a: number; + b: number; + c: number; + } -interface ABC { - [index: string]: number; - a: number; - b: number; - c: number; + result = _.reduce([1, 2, 3], function (sum: number, num: number) { + return sum + num; + }); + + // chained + result = _.chain([1, 2 ,3]).reduce(function (sum: number, num: number) { + return sum + num; + }).value(); + + result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { + r[key] = num * 3; + return r; + }, {}); + + result = _([1, 2, 3]).reduce(function (sum: number, num: number) { + return sum + num; + }); + result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce(function (r: ABC, num: number, key: string) { + r[key] = num * 3; + return r; + }, {}); + + result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); } - -result = _.reduce([1, 2, 3], function (sum: number, num: number) { - return sum + num; -}); -result = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function (r: ABC, num: number, key: string) { - r[key] = num * 3; - return r; -}, {}); - -result = _([1, 2, 3]).reduce(function (sum: number, num: number) { - return sum + num; -}); -result = _({ 'a': 1, 'b': 2, 'c': 3 }).reduce(function (r: ABC, num: number, key: string) { - r[key] = num * 3; - return r; -}, {}); - -result = _.reduceRight([[0, 1], [2, 3], [4, 5]], function (a: number[], b: number[]) { return a.concat(b); }, []); - // _.reject namespace TestReject { let array: TResult[]; diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index ea1a35a851..eb24793955 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -8584,6 +8584,21 @@ declare module _ { callback: MemoIterator): LoDashExplicitObjectWrapper; } + interface LoDashExplicitArrayWrapper { + /**LoDashExplicitWrapper + * @see _.reduce + */ + reduce( + callback: MemoIterator, + accumulator: TResult): LoDashExplicitWrapper; + + /** + * @see _.reduce + */ + reduce( + callback: MemoIterator): LoDashExplicitWrapper; + } + //_.reduceRight interface LoDashStatic { /** From d5424c1dc4f80a274c0dd12d95088ba530c66909 Mon Sep 17 00:00:00 2001 From: "Remo H. Jansen" Date: Tue, 30 Aug 2016 15:59:20 +0100 Subject: [PATCH 60/68] Update/Add Inversify type definitions (#10868) * Update inversify-binding-decorators.d.ts * Update inversify-binding-decorators-tests.ts * Update inversify-logger-middleware.d.ts * Update inversify-logger-middleware-tests.ts * Update inversify.d.ts * Update inversify-tests.ts * Update inversify.d.ts * Update inversify-global-tests.ts * Update inversify-express-utils.d.ts * Update inversify-express-utils-tests.ts * Create inversify-restify-utils.d.ts * Create inversify-restify-utils-tests.ts * Update inversify-inject-decorators.d.ts * Update inversify-binding-decorators.d.ts * Create inversify-devtools.d.ts * Create inversify-devtools-test.ts * Update inversify-restify-utils.d.ts * Update inversify-devtools-test.ts * Update inversify-restify-utils.d.ts * Update inversify-devtools.d.ts * Update inversify-restify-utils.d.ts * Update inversify-inject-decorators.d.ts * Update inversify-inject-decorators.d.ts * Update inversify-inject-decorators.d.ts * Update inversify-inject-decorators.d.ts * Update inversify.d.ts * Update inversify-tests.ts * Update inversify-global-tests.ts --- .../inversify-binding-decorators-tests.ts | 70 +++++---- .../inversify-binding-decorators.d.ts | 62 ++++---- inversify-devtools/inversify-devtools-test.ts | 8 + inversify-devtools/inversify-devtools.d.ts | 15 ++ .../inversify-express-utils-tests.ts | 12 +- .../inversify-express-utils.d.ts | 70 +++++---- .../inversify-inject-decorators.d.ts | 17 +- .../inversify-logger-middleware-tests.ts | 16 +- .../inversify-logger-middleware.d.ts | 95 +++++++----- .../inversify-restify-utils-tests.ts | 91 +++++++++++ .../inversify-restify-utils.d.ts | 59 +++++++ inversify/inversify-global-tests.ts | 145 ++++++------------ inversify/inversify-tests.ts | 143 +++++------------ inversify/inversify.d.ts | 28 ++-- 14 files changed, 454 insertions(+), 377 deletions(-) create mode 100644 inversify-devtools/inversify-devtools-test.ts create mode 100644 inversify-devtools/inversify-devtools.d.ts create mode 100644 inversify-restify-utils/inversify-restify-utils-tests.ts create mode 100644 inversify-restify-utils/inversify-restify-utils.d.ts diff --git a/inversify-binding-decorators/inversify-binding-decorators-tests.ts b/inversify-binding-decorators/inversify-binding-decorators-tests.ts index 9b0dff520e..8ca0acc551 100644 --- a/inversify-binding-decorators/inversify-binding-decorators-tests.ts +++ b/inversify-binding-decorators/inversify-binding-decorators-tests.ts @@ -4,51 +4,52 @@ import { inject, Kernel } from "inversify"; import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators"; module decorator { + let kernel = new Kernel(); let provide = makeProvideDecorator(kernel); - interface INinja { + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon { throw(): string; } let TYPE = { - IKatana: "IKatana", - INinja: "INinja", - IShuriken: "IShuriken" + ThrowableWeapon: "ThrowableWeapon", + Warrior: "Warrior", + Weapon: "Weapon" }; - @provide(TYPE.IKatana) - class Katana implements IKatana { + @provide(TYPE.Weapon) + class Katana implements Weapon { public hit() { return "cut!"; } } - @provide(TYPE.IShuriken) - class Shuriken implements IShuriken { + @provide(TYPE.ThrowableWeapon) + class Shuriken implements ThrowableWeapon { public throw() { return "hit!"; } } - @provide(TYPE.INinja) - class Ninja implements INinja { + @provide(TYPE.Warrior) + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; public constructor( - @inject("IKatana") katana: IKatana, - @inject("IShuriken") shuriken: IShuriken + @inject(TYPE.Weapon) katana: Weapon, + @inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon ) { this._katana = katana; this._shuriken = shuriken; @@ -59,12 +60,13 @@ module decorator { } - let ninja = kernel.get(TYPE.INinja); + let ninja = kernel.get(TYPE.Warrior); console.log(ninja); } module fluent_decorator { + let kernel = new Kernel(); let provide = makeFluentProvideDecorator(kernel); @@ -76,27 +78,27 @@ module fluent_decorator { return provide(identifier).done(); }; - interface INinja { + interface Warrior { fight(): string; sneak(): string; } - interface IKatana { + interface Weapon { hit(): string; } - interface IShuriken { + interface ThrowableWeapon { throw(): string; } let TYPE = { - IKatana: "IKatana", - INinja: "INinja", - IShuriken: "IShuriken" + ThrowableWeapon: "ThrowableWeapon", + Warrior: "Warrior", + Weapon: "Weapon" }; - @provideSingleton(TYPE.IKatana) - class Katana implements IKatana { + @provideSingleton(TYPE.Weapon) + class Katana implements Weapon { private _mark: any; public constructor() { this._mark = Math.random(); @@ -106,8 +108,8 @@ module fluent_decorator { } } - @provideTransient(TYPE.IShuriken) - class Shuriken implements IShuriken { + @provideTransient(TYPE.ThrowableWeapon) + class Shuriken implements ThrowableWeapon { private _mark: any; public constructor() { this._mark = Math.random(); @@ -117,15 +119,15 @@ module fluent_decorator { } } - @provideTransient(TYPE.INinja) - class Ninja implements INinja { + @provideTransient(TYPE.Warrior) + class Ninja implements Warrior { - private _katana: IKatana; - private _shuriken: IShuriken; + private _katana: Weapon; + private _shuriken: ThrowableWeapon; public constructor( - @inject("IKatana") katana: IKatana, - @inject("IShuriken") shuriken: IShuriken + @inject(TYPE.Weapon) katana: Weapon, + @inject(TYPE.ThrowableWeapon) shuriken: ThrowableWeapon ) { this._katana = katana; this._shuriken = shuriken; @@ -136,7 +138,7 @@ module fluent_decorator { } - let ninja = kernel.get(TYPE.INinja); + let ninja = kernel.get(TYPE.Warrior); console.log(ninja); } diff --git a/inversify-binding-decorators/inversify-binding-decorators.d.ts b/inversify-binding-decorators/inversify-binding-decorators.d.ts index 623b6c32c7..d5f92132a3 100644 --- a/inversify-binding-decorators/inversify-binding-decorators.d.ts +++ b/inversify-binding-decorators/inversify-binding-decorators.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-beta.5 +// Type definitions for inversify-binding-decorators 1.0.0 // Project: https://github.com/inversify/inversify-binding-decorators // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,46 +7,50 @@ declare namespace inversifyBindingDecorators { - interface IProvideInSyntax extends IProvideDoneSyntax { - inSingletonScope(): IProvideWhenOnSyntax; - } + namespace interfaces { - interface IProvideDoneSyntax { - done(): (target: any) => any; - } + export interface ProvideInSyntax extends ProvideDoneSyntax { + inSingletonScope(): ProvideWhenOnSyntax; + } - interface IProvideOnSyntax extends IProvideDoneSyntax { - onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): IProvideWhenSyntax; - } + export interface ProvideDoneSyntax { + done(): (target: any) => any; + } - interface IProvideInWhenOnSyntax extends IProvideInSyntax, IProvideWhenSyntax, IProvideOnSyntax {} + export interface ProvideOnSyntax extends ProvideDoneSyntax { + onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): ProvideWhenSyntax; + } - interface IProvideWhenOnSyntax extends IProvideWhenSyntax, IProvideOnSyntax {} + export interface ProvideInWhenOnSyntax extends ProvideInSyntax, ProvideWhenSyntax, ProvideOnSyntax {} + + export interface ProvideWhenOnSyntax extends ProvideWhenSyntax, ProvideOnSyntax {} + + export interface ProvideWhenSyntax extends ProvideDoneSyntax { + when(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + whenTargetNamed(name: string): ProvideOnSyntax; + whenTargetTagged(tag: string, value: any): ProvideOnSyntax; + whenInjectedInto(parent: (Function|string)): ProvideOnSyntax; + whenParentNamed(name: string): ProvideOnSyntax; + whenParentTagged(tag: string, value: any): ProvideOnSyntax; + whenAnyAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; + whenNoAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; + whenAnyAncestorNamed(name: string): ProvideOnSyntax; + whenAnyAncestorTagged(tag: string, value: any): ProvideOnSyntax; + whenNoAncestorNamed(name: string): ProvideOnSyntax; + whenNoAncestorTagged(tag: string, value: any): ProvideOnSyntax; + whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; + } - interface IProvideWhenSyntax extends IProvideDoneSyntax { - when(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; - whenTargetNamed(name: string): IProvideOnSyntax; - whenTargetTagged(tag: string, value: any): IProvideOnSyntax; - whenInjectedInto(parent: (Function|string)): IProvideOnSyntax; - whenParentNamed(name: string): IProvideOnSyntax; - whenParentTagged(tag: string, value: any): IProvideOnSyntax; - whenAnyAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; - whenNoAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; - whenAnyAncestorNamed(name: string): IProvideOnSyntax; - whenAnyAncestorTagged(tag: string, value: any): IProvideOnSyntax; - whenNoAncestorNamed(name: string): IProvideOnSyntax; - whenNoAncestorTagged(tag: string, value: any): IProvideOnSyntax; - whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; - whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; } export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void; export function makeProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => (target: any) => any; + (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (target: any) => any; export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => IProvideInWhenOnSyntax; + (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => interfaces.ProvideInWhenOnSyntax; } diff --git a/inversify-devtools/inversify-devtools-test.ts b/inversify-devtools/inversify-devtools-test.ts new file mode 100644 index 0000000000..3b99d7df93 --- /dev/null +++ b/inversify-devtools/inversify-devtools-test.ts @@ -0,0 +1,8 @@ +/// + +import render from "inversify-devtools"; +import { Kernel } from "inversify"; + +let connectKernel = render("root"); +let kernel = new Kernel(); +connectKernel(kernel); diff --git a/inversify-devtools/inversify-devtools.d.ts b/inversify-devtools/inversify-devtools.d.ts new file mode 100644 index 0000000000..841ae228c5 --- /dev/null +++ b/inversify-devtools/inversify-devtools.d.ts @@ -0,0 +1,15 @@ +// Type definitions for inversify-devtools 1.0.0 +// Project: https://github.com/inversify/inversify-devtools +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +interface ConnectKernel extends Function { + (kernel: inversify.interfaces.Kernel): void; +} + +declare module "inversify-devtools" { + let render: (container: string) => ConnectKernel; + export default render; +} diff --git a/inversify-express-utils/inversify-express-utils-tests.ts b/inversify-express-utils/inversify-express-utils-tests.ts index 1d421e397a..b082546448 100644 --- a/inversify-express-utils/inversify-express-utils-tests.ts +++ b/inversify-express-utils/inversify-express-utils-tests.ts @@ -1,21 +1,23 @@ /// -import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method } from "inversify-express-utils"; +import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method, TYPE } from "inversify-express-utils"; import * as express from "express"; import { Kernel } from "inversify"; +let kernel = new Kernel(); + module server { - let kernel = new Kernel(); + let server = new InversifyExpressServer(kernel); server - .setConfig((app) => { + .setConfig((app: express.Application) => { app.use((req: express.Request, res: express.Response, next: express.NextFunction) => { console.log("hello world"); next(); }); }) - .setErrorConfig((app) => { + .setErrorConfig((app: express.Application) => { app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { console.error(err.stack); res.status(500).send("Something broke!"); @@ -55,6 +57,8 @@ module decorators { public testMethod() { return "METHOD:FOO"; } } + kernel.bind(TYPE.Controller).to(TestController); + function m1(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } function m2(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } function m3(req: express.Request, res: express.Response, next: express.NextFunction) { next(); } diff --git a/inversify-express-utils/inversify-express-utils.d.ts b/inversify-express-utils/inversify-express-utils.d.ts index aa9a20d23c..f90b0cac88 100644 --- a/inversify-express-utils/inversify-express-utils.d.ts +++ b/inversify-express-utils/inversify-express-utils.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-alpha.4 +// Type definitions for inversify-express-utils 1.0.0 // Project: https://github.com/inversify/inversify-express-utils // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -11,40 +11,50 @@ declare module "inversify-express-utils" { import * as express from "express"; import * as inversify from "inversify"; - interface IInversifyExpressServerConstructor { - new(kernel: inversify.interfaces.Kernel): IInversifyExpressServer; + export namespace interfaces { + + export interface InversifyExpressServerConstructor { + new(kernel: inversify.interfaces.Kernel): InversifyExpressServer; + } + + export interface InversifyExpressServer { + setConfig(fn: ConfigFunction): InversifyExpressServer; + setErrorConfig(fn: ConfigFunction): InversifyExpressServer; + build(): express.Application; + } + + export interface ConfigFunction { + (app: express.Application): void; + } + + export interface HandlerDecoratorFactory { + (path: string, ...middleware: express.RequestHandler[]): HandlerDecorator; + } + + export interface HandlerDecorator { + (target: any, key: string, value: any): void; + } + } - interface IInversifyExpressServer { - setConfig(fn: IConfigFunction): IInversifyExpressServer; - setErrorConfig(fn: IConfigFunction): IInversifyExpressServer; - build(): express.Application; + export interface Controller {} + + interface ServiceIdentifiers { + Controller: Symbol; } - interface IConfigFunction { - (app: express.Application): void; - } - - interface IHandlerDecoratorFactory { - (path: string, ...middleware: express.RequestHandler[]): IHandlerDecorator; - } - - interface IHandlerDecorator { - (target: any, key: string, value: any): void; - } - - export interface IController {} - - export var InversifyExpressServer: IInversifyExpressServerConstructor; + export var InversifyExpressServer: interfaces.InversifyExpressServerConstructor; export var Controller: (path: string, ...middleware: express.RequestHandler[]) => (target: any) => void; - export var All: IHandlerDecoratorFactory; - export var Get: IHandlerDecoratorFactory; - export var Post: IHandlerDecoratorFactory; - export var Put: IHandlerDecoratorFactory; - export var Patch: IHandlerDecoratorFactory; - export var Head: IHandlerDecoratorFactory; - export var Delete: IHandlerDecoratorFactory; - export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => IHandlerDecorator; + export var All: interfaces.HandlerDecoratorFactory; + export var Get: interfaces.HandlerDecoratorFactory; + export var Post: interfaces.HandlerDecoratorFactory; + export var Put: interfaces.HandlerDecoratorFactory; + export var Patch: interfaces.HandlerDecoratorFactory; + export var Head: interfaces.HandlerDecoratorFactory; + export var Delete: interfaces.HandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: express.RequestHandler[]) => interfaces.HandlerDecorator; + export var TYPE: ServiceIdentifiers; + } diff --git a/inversify-inject-decorators/inversify-inject-decorators.d.ts b/inversify-inject-decorators/inversify-inject-decorators.d.ts index 032ed40cdd..34244c6d5e 100644 --- a/inversify-inject-decorators/inversify-inject-decorators.d.ts +++ b/inversify-inject-decorators/inversify-inject-decorators.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify-inject-decorators 1.0.0-beta.1 +// Type definitions for inversify-inject-decorators 1.0.0 // Project: https://github.com/inversify/inversify-inject-decorators // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,26 +7,25 @@ declare namespace inversifyInjectDecorators { - interface InjectDecorators { + export interface InjectDecorators { - lazyInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + lazyInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (proto: any, key: string) => void; - lazyInjectNamed: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), named: string) => + lazyInjectNamed: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, named: string) => (proto: any, key: string) => void; - lazyInjectTagged: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), key: string, value: any) => + lazyInjectTagged: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, key: string, value: any) => (proto: any, propertyName: string) => void; - lazyMultiInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + lazyMultiInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (proto: any, key: string) => void; } - export function getDecorators(kernel: inversify.interfaces.Kernel): InjectDecorators; - } declare module "inversify-inject-decorators" { - export default inversifyInjectDecorators.getDecorators; + let getDecorators: (kernel: inversify.interfaces.Kernel) => inversifyInjectDecorators.InjectDecorators; + export default getDecorators; } diff --git a/inversify-logger-middleware/inversify-logger-middleware-tests.ts b/inversify-logger-middleware/inversify-logger-middleware-tests.ts index c9c7d5c8a8..3b2119911a 100644 --- a/inversify-logger-middleware/inversify-logger-middleware-tests.ts +++ b/inversify-logger-middleware/inversify-logger-middleware-tests.ts @@ -4,23 +4,23 @@ declare var kernel: inversify.interfaces.Kernel; import { makeLoggerMiddleware, textSerializer } from "inversify-logger-middleware"; -interface ILoggerOutput { +interface LoggerOutput { entry: T; } -let makeStringRenderer = function (loggerOutput: ILoggerOutput) { - return function (entry: inversifyLoggerMiddleware.ILogEntry) { +let makeStringRenderer = function (loggerOutput: LoggerOutput) { + return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) { loggerOutput.entry = textSerializer(entry); }; }; -let makeObjRenderer = function (loggerOutput: ILoggerOutput) { - return function (entry: inversifyLoggerMiddleware.ILogEntry) { +let makeObjRenderer = function (loggerOutput: LoggerOutput) { + return function (entry: inversifyLoggerMiddleware.interfaces.LogEntry) { loggerOutput.entry = entry; }; }; -let options: inversifyLoggerMiddleware.ILoggerSettings = { +let options: inversifyLoggerMiddleware.interfaces.LoggerSettings = { request: { bindings: { activated: true, @@ -48,12 +48,12 @@ let options: inversifyLoggerMiddleware.ILoggerSettings = { let logger = makeLoggerMiddleware(); kernel.applyMiddleware(logger); -let loggerOutput1: ILoggerOutput = { entry: null }; +let loggerOutput1: LoggerOutput = { entry: null }; let stringRenderer1 = makeStringRenderer(loggerOutput1); let logger1 = makeLoggerMiddleware(options, stringRenderer1); kernel.applyMiddleware(logger1); -let loggerOutput2: ILoggerOutput = { entry: null }; +let loggerOutput2: LoggerOutput = { entry: null }; let objRenderer2 = makeObjRenderer(loggerOutput2); let logger2 = makeLoggerMiddleware(options, objRenderer2); kernel.applyMiddleware(logger2); diff --git a/inversify-logger-middleware/inversify-logger-middleware.d.ts b/inversify-logger-middleware/inversify-logger-middleware.d.ts index 3aa4ccca18..cd0037f432 100644 --- a/inversify-logger-middleware/inversify-logger-middleware.d.ts +++ b/inversify-logger-middleware/inversify-logger-middleware.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 1.0.0-beta.6 +// Type definitions for inversify-logger-middleware 1.0.0 // Project: https://github.com/inversify/inversify-logger-middleware // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -7,50 +7,61 @@ declare namespace inversifyLoggerMiddleware { - export interface ILoggerSettings { - request?: IRequestLoggerSettings; - time?: boolean; + export namespace interfaces { + + export interface LoggerSettings { + request?: RequestLoggerSettings; + time?: boolean; + } + + export interface RequestLoggerSettings { + serviceIdentifier?: boolean; + bindings?: BindingLoggerSettings; + target?: TargetLoggerSettings; + } + + export interface BindingLoggerSettings { + activated?: boolean; + serviceIdentifier?: boolean; + implementationType?: boolean; + factory?: boolean; + provider?: boolean; + constraint?: boolean; + onActivation?: boolean; + cache?: boolean; + dynamicValue?: boolean; + scope?: boolean; + type?: boolean; + } + + export interface TargetLoggerSettings { + serviceIdentifier?: boolean; + name?: boolean; + metadata?: boolean; + } + + export interface LogEntry { + error: boolean; + exception: any; + guid: string; + multiInject: boolean; + results: any[]; + rootRequest: inversify.interfaces.Request; + serviceIdentifier: any; + target: any; + time: string; + } + } - export interface IRequestLoggerSettings { - serviceIdentifier?: boolean; - bindings?: IBindingLoggerSettings; - target?: ITargetLoggerSettings; - } + export function makeLoggerMiddleware( + settings?: interfaces.LoggerSettings, + renderer?: (out: interfaces.LogEntry) => void + ): inversify.interfaces.Middleware; - export interface IBindingLoggerSettings { - activated?: boolean; - serviceIdentifier?: boolean; - implementationType?: boolean; - factory?: boolean; - provider?: boolean; - constraint?: boolean; - onActivation?: boolean; - cache?: boolean; - dynamicValue?: boolean; - scope?: boolean; - type?: boolean; - } - - export interface ITargetLoggerSettings { - serviceIdentifier?: boolean; - name?: boolean; - metadata?: boolean; - } - - export interface ILogEntry { - error: boolean; - exception: any; - multiInject: boolean; - results: any[]; - rootRequest: inversify.interfaces.Request; - serviceIdentifier: any; - target: any; - time: string; - } - - export function makeLoggerMiddleware(settings?: ILoggerSettings, renderer?: (out: ILogEntry) => void): inversify.interfaces.Middleware; - export function textSerializer(entry: ILogEntry): string; + export function textSerializer(entry: interfaces.LogEntry): string; + export function bindingTypeFormatter(type: number): string; + export function scopeFormatter(scope: number): string; } diff --git a/inversify-restify-utils/inversify-restify-utils-tests.ts b/inversify-restify-utils/inversify-restify-utils-tests.ts new file mode 100644 index 0000000000..5ff3ddc633 --- /dev/null +++ b/inversify-restify-utils/inversify-restify-utils-tests.ts @@ -0,0 +1,91 @@ +/// + +import { + InversifyRestifyServer, Controller, Get, Options, + Delete, Head, Put, Patch, Post, Method, TYPE +} from "inversify-restify-utils"; + +import * as restify from "restify"; +import { Kernel } from "inversify"; + +let kernel = new Kernel(); + +module server { + + let server = new InversifyRestifyServer(kernel); + + server + .setConfig((app: restify.Server) => { + app.use((req: restify.Request, res: restify.Response, next: restify.Next) => { + console.log("hello world"); + next(); + }); + }) + .build() + .listen(3000, "localhost"); +} + +module decorators { + + @Controller("/") + class TestController { + + @Get("/") + public testGet() { return "GET"; } + + @Options("/") + public testAll() { return "OPTIONS"; } + + @Delete("/") + public testDelete() { return "DELETE"; } + + @Head("/") + public testHead() { return "HEAD"; } + + @Put("/") + public testPut() { return "PUT"; } + + @Patch("/") + public testPatch() { return "PATCH"; } + + @Post("/") + public testPost() { return "POST"; } + + @Method("opts", "/") + public testMethod() { return "METHOD:OPTS"; } + } + + kernel.bind(TYPE.Controller).to(TestController); + + function m1(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + function m2(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + function m3(req: restify.Request, res: restify.Response, next: restify.Next) { next(); } + + @Controller("/", m1, m2, m3) + class TestMiddlewareController { + + @Get("/", m1, m2, m3) + public testGet() { return "GET"; } + + @Options("/", m1, m2, m3) + public testAll() { return "OPTIONS"; } + + @Delete("/", m1, m2, m3) + public testDelete() { return "DELETE"; } + + @Head("/", m1, m2, m3) + public testHead() { return "HEAD"; } + + @Put("/", m1, m2, m3) + public testPut() { return "PUT"; } + + @Patch("/", m1, m2, m3) + public testPatch() { return "PATCH"; } + + @Post("/", m1, m2, m3) + public testPost() { return "POST"; } + + @Method("opts", "/", m1, m2, m3) + public testMethod() { return "METHOD:OPTS"; } + } +} diff --git a/inversify-restify-utils/inversify-restify-utils.d.ts b/inversify-restify-utils/inversify-restify-utils.d.ts new file mode 100644 index 0000000000..4f2aab5510 --- /dev/null +++ b/inversify-restify-utils/inversify-restify-utils.d.ts @@ -0,0 +1,59 @@ +// Type definitions for inversify-restify-utils 1.0.0 +// Project: https://github.com/inversify/inversify-restify-utils +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// +/// + +declare module "inversify-restify-utils" { + + import * as restify from "restify"; + import * as inversify from "inversify"; + + export namespace interfaces { + + export interface InversifyRestifyServerConstructor { + new(kernel: inversify.interfaces.Kernel): InversifyRestifyServer; + } + + export interface InversifyRestifyServer { + setConfig(fn: ConfigFunction): InversifyRestifyServer; + build(): restify.Server; + } + + export interface ConfigFunction { + (app: restify.Server): void; + } + + export interface HandlerDecoratorFactory { + (path: string, ...middleware: restify.RequestHandler[]): HandlerDecorator; + } + + export interface HandlerDecorator { + (target: any, key: string, value: any): void; + } + + } + + export interface Controller {} + + interface ServiceIdentifiers { + Controller: Symbol; + } + + export var InversifyRestifyServer: interfaces.InversifyRestifyServerConstructor; + + export var Controller: (path: string, ...middleware: restify.RequestHandler[]) => (target: any) => void; + + export var Options: interfaces.HandlerDecoratorFactory; + export var Get: interfaces.HandlerDecoratorFactory; + export var Post: interfaces.HandlerDecoratorFactory; + export var Put: interfaces.HandlerDecoratorFactory; + export var Patch: interfaces.HandlerDecoratorFactory; + export var Head: interfaces.HandlerDecoratorFactory; + export var Delete: interfaces.HandlerDecoratorFactory; + export var Method: (method: string, path: string, ...middleware: restify.RequestHandler[]) => interfaces.HandlerDecorator; + export var TYPE: ServiceIdentifiers; + +} diff --git a/inversify/inversify-global-tests.ts b/inversify/inversify-global-tests.ts index e2ead555d4..53b1a522bf 100644 --- a/inversify/inversify-global-tests.ts +++ b/inversify/inversify-global-tests.ts @@ -1,6 +1,8 @@ /// /// +import * as Proxy from "harmony-proxy"; + let injectable = inversify.injectable; let inject = inversify.inject; let tagged = inversify.tagged; @@ -13,10 +15,7 @@ let traverseAncerstors = inversify.traverseAncerstors; let taggedConstraint = inversify.taggedConstraint; let namedConstraint = inversify.namedConstraint; let typeConstraint = inversify.typeConstraint; -let makePropertyMultiInjectDecorator = inversify.makePropertyMultiInjectDecorator; -let makePropertyInjectTaggedDecorator = inversify.makePropertyInjectTaggedDecorator; -let makePropertyInjectNamedDecorator = inversify.makePropertyInjectNamedDecorator; -let makePropertyInjectDecorator = inversify.makePropertyInjectDecorator; +let unmanaged = inversify.unmanaged; module external_module_test { @@ -112,7 +111,7 @@ module external_module_test { // binding types kernel.bind("Weapon").to(Katana); kernel.bind("Weapon").toConstantValue(new Katana()); - kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); + kernel.bind("Weapon").toDynamicValue((context: inversify.interfaces.Context) => { return new Katana(); }); kernel.bind>("Weapon").toConstructor(Katana); @@ -145,6 +144,7 @@ module external_module_test { return new Proxy(katanaToBeInjected, handler); }); + @injectable() class Samurai implements Warrior { public katana: Weapon; @@ -161,8 +161,9 @@ module external_module_test { } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("Weapon").to(Katana).whenTargetTagged("canThrow", false); kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.getAllTagged("Weapon", "canThrow", false); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); @@ -200,6 +201,7 @@ module external_module_test { kernel.bind("Warrior").to(Samurai3); kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); + kernel.getAllNamed("Weapon", "weak"); @injectable() class Samurai4 implements Samurai { @@ -245,18 +247,18 @@ module external_module_test { // Constraint helpers kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); - kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("Ninja"); kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); @@ -341,103 +343,42 @@ module external_module_test { } -module property_injection { +module snapshot { let kernel = new Kernel(); - let TYPES = { Weapon: "Weapon" }; - - interface Weapon { - durability: number; - use(): void; - } - - @injectable() - class Sword implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - @injectable() - class WarHammer implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); - - class Warrior1 { - @propertyMultiInject(TYPES.Weapon) - public weapons: Weapon[]; - } - - let propertyInject = makePropertyInjectDecorator(kernel); - - interface Service { - count: number; - increment(): void; - } - - @injectable() - class SomeService implements Service { - public count: number; - public constructor() { - this.count = 0; - } - public increment() { - this.count = this.count + 1; - } - } - - class SomeWebComponent { - @propertyInject("Service") - private _service: Service; - public doSomething() { - let count = this._service.count; - this._service.increment(); - return count; - } - } - - let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); - - class Warrior2 { - - @propertyInjectNammed(TYPES.Weapon, "not-throwwable") - @named("not-throwwable") - public primaryWeapon: Weapon; - - @propertyInjectNammed(TYPES.Weapon, "throwwable") - @named("throwwable") - public secondaryWeapon: Weapon; - - } - - let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); - - class Warrior3 { - - @propertyInjectTagged(TYPES.Weapon, "throwwable", false) - @tagged("throwwable", false) - public primaryWeapon: Weapon; - - @propertyInjectTagged(TYPES.Weapon, "throwwable", true) - @tagged("throwwable", true) - public secondaryWeapon: Weapon; - - } - kernel.snapshot(); kernel.restore(); + @injectable() + class Test { } + + kernel.bind(Test).toSelf(); + kernel.bind(Test).toSelf().inSingletonScope(); +} + +module unmanaged_injection { + + let kernel = new Kernel(); + + const BaseId = "Base"; + + @injectable() + class Base { + public prop: string; + public constructor(@unmanaged() arg: string) { // injected by user + this.prop = arg; + } + } + + @injectable() + class Derived extends Base { + public constructor() { + super("unmanaged-injected-value"); // user injection + } + } + + kernel.bind(BaseId).to(Derived); + console.log(kernel.get(BaseId) instanceof Base); // true + } diff --git a/inversify/inversify-tests.ts b/inversify/inversify-tests.ts index 9b5de8fa0e..6b0d4a5f12 100644 --- a/inversify/inversify-tests.ts +++ b/inversify/inversify-tests.ts @@ -6,11 +6,7 @@ import { injectable, tagged, named, targetName, inject, multiInject, traverseAncerstors, taggedConstraint, namedConstraint, typeConstraint, - makePropertyMultiInjectDecorator, - makePropertyInjectTaggedDecorator, - makePropertyInjectNamedDecorator, - makePropertyInjectDecorator, - KernelModule, interfaces + KernelModule, interfaces, unmanaged } from "inversify"; import * as Proxy from "harmony-proxy"; @@ -109,7 +105,7 @@ module external_module_test { // binding types kernel.bind("Weapon").to(Katana); kernel.bind("Weapon").toConstantValue(new Katana()); - kernel.bind("Weapon").toDynamicValue(() => { return new Katana(); }); + kernel.bind("Weapon").toDynamicValue((context: interfaces.Context) => { return new Katana(); }); kernel.bind>("Weapon").toConstructor(Katana); @@ -159,8 +155,9 @@ module external_module_test { } kernel.bind("Samurai").to(Samurai); - kernel.bind("IWeapon").to(Katana).whenTargetTagged("canThrow", false); + kernel.bind("Weapon").to(Katana).whenTargetTagged("canThrow", false); kernel.bind("ThrowableWeapon").to(Shuriken).whenTargetTagged("canThrow", true); + kernel.getAllTagged("Weapon", "canThrow", false); let throwable = tagged("canThrow", true); let notThrowable = tagged("canThrow", false); @@ -198,6 +195,7 @@ module external_module_test { kernel.bind("Warrior").to(Samurai3); kernel.bind("Weapon").to(Katana).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("weak"); + kernel.getAllNamed("Weapon", "weak"); @injectable() class Samurai4 implements Samurai { @@ -243,18 +241,18 @@ module external_module_test { // Constraint helpers kernel.bind("Weapon").to(Shuriken).whenInjectedInto(Ninja); - kernel.bind("Weapon").to(Shuriken).whenInjectedInto("INinja"); + kernel.bind("Weapon").to(Shuriken).whenInjectedInto("Ninja"); kernel.bind("Weapon").to(Shuriken).whenParentNamed("chinese"); kernel.bind("Weapon").to(Shuriken).whenParentTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenTargetNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenTargetTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenAnyAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenAnyAncestorMatches(whenParentNamedCanThrowConstraint); kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs(Ninja); - kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("INinja"); + kernel.bind("Weapon").to(Shuriken).whenNoAncestorIs("Ninja"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorNamed("strong"); kernel.bind("Weapon").to(Shuriken).whenNoAncestorTagged("canThrow", true); kernel.bind("Weapon").to(Shuriken).whenNoAncestorMatches(whenParentNamedCanThrowConstraint); @@ -339,103 +337,42 @@ module external_module_test { } -module property_injection { +module snapshot { let kernel = new Kernel(); - let TYPES = { Weapon: "Weapon" }; - - interface Weapon { - durability: number; - use(): void; - } - - @injectable() - class Sword implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - @injectable() - class WarHammer implements Weapon { - public durability: number; - public constructor() { - this.durability = 100; - } - public use() { - this.durability = this.durability - 10; - } - } - - let propertyMultiInject = makePropertyMultiInjectDecorator(kernel); - - class Warrior1 { - @propertyMultiInject(TYPES.Weapon) - public weapons: Weapon[]; - } - - let propertyInject = makePropertyInjectDecorator(kernel); - - interface Service { - count: number; - increment(): void; - } - - @injectable() - class SomeService implements Service { - public count: number; - public constructor() { - this.count = 0; - } - public increment() { - this.count = this.count + 1; - } - } - - class SomeWebComponent { - @propertyInject("Service") - private _service: Service; - public doSomething() { - let count = this._service.count; - this._service.increment(); - return count; - } - } - - let propertyInjectNammed = makePropertyInjectNamedDecorator(kernel); - - class Warrior2 { - - @propertyInjectNammed(TYPES.Weapon, "not-throwwable") - @named("not-throwwable") - public primaryWeapon: Weapon; - - @propertyInjectNammed(TYPES.Weapon, "throwwable") - @named("throwwable") - public secondaryWeapon: Weapon; - - } - - let propertyInjectTagged = makePropertyInjectTaggedDecorator(kernel); - - class Warrior3 { - - @propertyInjectTagged(TYPES.Weapon, "throwwable", false) - @tagged("throwwable", false) - public primaryWeapon: Weapon; - - @propertyInjectTagged(TYPES.Weapon, "throwwable", true) - @tagged("throwwable", true) - public secondaryWeapon: Weapon; - - } - kernel.snapshot(); kernel.restore(); + @injectable() + class Test { } + + kernel.bind(Test).toSelf(); + kernel.bind(Test).toSelf().inSingletonScope(); +} + +module unmanaged_injection { + + let kernel = new Kernel(); + + const BaseId = "Base"; + + @injectable() + class Base { + public prop: string; + public constructor(@unmanaged() arg: string) { // injected by user + this.prop = arg; + } + } + + @injectable() + class Derived extends Base { + public constructor() { + super("unmanaged-injected-value"); // user injection + } + } + + kernel.bind(BaseId).to(Derived); + console.log(kernel.get(BaseId) instanceof Base); // true + } diff --git a/inversify/inversify.d.ts b/inversify/inversify.d.ts index 0c77d9d82f..2f07d203e1 100644 --- a/inversify/inversify.d.ts +++ b/inversify/inversify.d.ts @@ -1,4 +1,4 @@ -// Type definitions for inversify 2.0.0-beta.9 +// Type definitions for inversify 2.0.0-rc.12 // Project: https://github.com/inversify/InversifyJS // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped @@ -45,7 +45,7 @@ declare namespace inversify { constraint: (request: Request) => boolean; onActivation: (context: Context, injectable: T) => T; cache: T; - dynamicValue: () => T; + dynamicValue: (context: Context) => T; scope: number; // BindingScope type: number; // BindingType } @@ -135,6 +135,7 @@ declare namespace inversify { export interface Target { guid: string; serviceIdentifier: ServiceIdentifier; + type: number; // TargetType name: QueryableString; metadata: Array; hasTag(key: string): boolean; @@ -152,6 +153,7 @@ declare namespace inversify { export interface Kernel { guid: string; + parent: Kernel; bind(serviceIdentifier: ServiceIdentifier): BindingToSyntax; unbind(serviceIdentifier: ServiceIdentifier): void; unbindAll(): void; @@ -160,6 +162,8 @@ declare namespace inversify { getNamed(serviceIdentifier: ServiceIdentifier, named: string): T; getTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T; getAll(serviceIdentifier: ServiceIdentifier): T[]; + getAllNamed(serviceIdentifier: ServiceIdentifier, named: string): T[]; + getAllTagged(serviceIdentifier: ServiceIdentifier, key: string, value: any): T[]; load(...modules: KernelModule[]): void; unload(...modules: KernelModule[]): void; applyMiddleware(...middleware: Middleware[]): void; @@ -197,10 +201,12 @@ declare namespace inversify { export interface KeyValuePair { serviceIdentifier: ServiceIdentifier; value: Array; + guid: string; } export interface BindingInSyntax { inSingletonScope(): BindingWhenOnSyntax; + inTransientScope(): BindingWhenOnSyntax; } export interface BindingInWhenOnSyntax extends BindingInSyntax, BindingWhenOnSyntax {} @@ -211,8 +217,9 @@ declare namespace inversify { export interface BindingToSyntax { to(constructor: { new(...args: any[]): T; }): BindingInWhenOnSyntax; + toSelf(): BindingInWhenOnSyntax; toConstantValue(value: T): BindingWhenOnSyntax; - toDynamicValue(func: () => T): BindingWhenOnSyntax; + toDynamicValue(func: (context: Context) => T): BindingWhenOnSyntax; toConstructor(constructor: Newable): BindingWhenOnSyntax; toFactory(factory: FactoryCreator): BindingWhenOnSyntax; toFunction(func: T): BindingWhenOnSyntax; @@ -248,30 +255,19 @@ declare namespace inversify { export function tagged(metadataKey: string, metadataValue: any): (target: any, targetKey: string, index?: number) => any; export function named(name: string): (target: any, targetKey: string, index?: number) => any; export function targetName(name: string): (target: any, targetKey: string, index: number) => any; + export function unmanaged(): (target: any, targetKey: string, index: number) => any; export function inject(serviceIdentifier: interfaces.ServiceIdentifier): (target: any, targetKey: string, index?: number) => any; + export function guid(): string; export function multiInject( serviceIdentifier: interfaces.ServiceIdentifier ): (target: any, targetKey: string, index?: number) => any; - export function makePropertyInjectDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - - export function makePropertyInjectNamedDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable), named: string) => (proto: any, key: string) => void; - - export function makePropertyInjectTaggedDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable), key: string, value: any) => (proto: any, propertyName: string) => void; - - export function makePropertyMultiInjectDecorator(kernel: interfaces.Kernel): - (serviceIdentifier: (string|Symbol|interfaces.Newable)) => (proto: any, key: string) => void; - // constraint helpers export var traverseAncerstors: (request: interfaces.Request, constraint: (request: interfaces.Request) => boolean) => boolean; export var taggedConstraint: (tag: string) => (value: any) => (request: interfaces.Request) => boolean; export var namedConstraint: (value: any) => (request: interfaces.Request) => boolean; export var typeConstraint: (type: (Function|string)) => (request: interfaces.Request) => boolean; - } declare module "inversify" { From 8e1b4362a0ba1de07a6aa4dbf146eae0e29959ad Mon Sep 17 00:00:00 2001 From: Tyler Waters Date: Tue, 30 Aug 2016 08:00:42 -0700 Subject: [PATCH 61/68] Adds typings for esprima-walk package (#10898) --- esprima-walk/esprima-walk-tests.ts | 25 +++++++++++++++++++ esprima-walk/esprima-walk.d.ts | 40 ++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 esprima-walk/esprima-walk-tests.ts create mode 100644 esprima-walk/esprima-walk.d.ts diff --git a/esprima-walk/esprima-walk-tests.ts b/esprima-walk/esprima-walk-tests.ts new file mode 100644 index 0000000000..4588ebb615 --- /dev/null +++ b/esprima-walk/esprima-walk-tests.ts @@ -0,0 +1,25 @@ +/// +/// + +import * as walk from 'esprima-walk' + +var program: ESTree.Program +var string: string +var node: ESTree.Node + +walk(program, _node => { + string = node.type + node = _node +}) + +walk.walk(program, _node => { + string = node.type + node = _node +}) + +walk.walkAddParent(program, _node => { + node = _node + node = _node.parent + string = node.type +}) + diff --git a/esprima-walk/esprima-walk.d.ts b/esprima-walk/esprima-walk.d.ts new file mode 100644 index 0000000000..d18cf96bb1 --- /dev/null +++ b/esprima-walk/esprima-walk.d.ts @@ -0,0 +1,40 @@ +// Type definitions for esprima-walk v0.1.0 +// Project: https://github.com/jrajav/esprima-walk +// Definitions by: tswaters +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "esprima-walk" { + + interface NodeWithParent extends ESTree.Node { + parent?: ESTree.Node + } + + /** + * Walk the provided AST; fn is called once for each node with a `type` + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node with type + */ + function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void + + namespace walk { + /** + * Walk the provided AST; fn is called once for each node with a `type` + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node + */ + export function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void + + /** + * Walk the provided AST; fn is called once for each node with a `type`. + * Adds a parent property prior to invoking fn when applicable + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node + */ + export function walkAddParent (ast: ESTree.Program, fn:(node: NodeWithParent)=>void) :void + } + + export = walk +} + From 103d66654792617c545a55cb038cbb14bf4d864b Mon Sep 17 00:00:00 2001 From: grippstick Date: Tue, 30 Aug 2016 10:00:57 -0500 Subject: [PATCH 62/68] include enum values used in the contactfindoptions (#10773) There is no true way to do a string literal enumeration in type script, but the proposed changes above provide type safety and intellisense. --- cordova/plugins/Contacts.d.ts | 84 ++++++++++++++++++++++++++++++----- 1 file changed, 74 insertions(+), 10 deletions(-) diff --git a/cordova/plugins/Contacts.d.ts b/cordova/plugins/Contacts.d.ts index d940fccd77..90b21ae2bb 100644 --- a/cordova/plugins/Contacts.d.ts +++ b/cordova/plugins/Contacts.d.ts @@ -42,6 +42,40 @@ interface Contacts { */ pickContact(onSuccess: (contact: Contact) => void, onError: (error: ContactError) => void): void + + /** + * This allows us to use an enumeration when setting the desired fields for the ContactFindOptions. + * The values will correspond to the type of string literals in ContactFieldType. + */ + fieldType: { + addresses: "addresses", + birthday: "birthday", + categories: "categories", + country: "country", + department: "department", + displayName: "displayName", + emails: "emails", + familyName: "familyName", + formatted: "formatted", + givenName: "givenName", + honorificPrefix: "honorificPrefix", + honorificSuffix: "honorificSuffix", + id: "id", + ims: "ims", + locality: "locality", + middleName: "middleName", + name: "name", + nickname: "nickname", + note: "note", + organizations: "organizations", + phoneNumbers: "phoneNumbers", + photos: "photos", + postalCode: "postalCode", + region: "region", + streetAddress: "streetAddress", + title: "title", + urls: "urls" + } } interface ContactProperties { @@ -105,7 +139,7 @@ interface Contact extends ContactProperties { declare var Contact: { /** Constructor of Contact object */ - new(id?: string, + new (id?: string, displayName?: string, name?: ContactName, nickname?: string, @@ -130,7 +164,7 @@ interface ContactError { } declare var ContactError: { - new(code: number): ContactError; + new (code: number): ContactError; UNKNOWN_ERROR: number; INVALID_ARGUMENT_ERROR: number; TIMEOUT_ERROR: number; @@ -158,7 +192,7 @@ interface ContactName { declare var ContactName: { /** Constructor for ContactName object */ - new(formatted?: string, + new (formatted?: string, familyName?: string, givenName?: string, middleName?: string, @@ -189,7 +223,7 @@ interface ContactField { declare var ContactField: { /** Constructor for ContactField object */ - new(type?: string, + new (type?: string, value?: string, pref?: boolean): ContactField }; @@ -219,7 +253,7 @@ interface ContactAddress { declare var ContactAddress: { /** Constructor of ContactAddress object */ - new(pref?: boolean, + new (pref?: boolean, type?: string, formatted?: string, streetAddress?: string, @@ -248,7 +282,7 @@ interface ContactOrganization { declare var ContactOrganization: { /** Constructor for ContactOrganization object */ - new(pref?: boolean, + new (pref?: boolean, type?: string, name?: string, department?: string, @@ -262,12 +296,42 @@ interface ContactFindOptions { /** Determines if the find operation returns multiple navigator.contacts. */ multiple?: boolean; /* Contact fields to be returned back. If specified, the resulting Contact object only features values for these fields. */ - desiredFields?: string[]; + desiredFields?: ContactFieldType[]; } +/** these are the string values that are valid for the desired fields in ContactFindOptions */ +declare type ContactFieldType = + "addresses" + | "birthday" + | "categories" + | "country" + | "department" + | "displayName" + | "emails" + | "familyName" + | "formatted" + | "givenName" + | "honorificPrefix" + | "honorificSuffix" + | "id" + | "ims" + | "locality" + | "middleName" + | "name" + | "nickname" + | "note" + | "organizations" + | "phoneNumbers" + | "photos" + | "postalCode" + | "region" + | "streetAddress" + | "title" + | "urls"; + declare var ContactFindOptions: { /** Constructor for ContactFindOptions object */ - new(filter?: string, + new (filter?: string, multiple?: boolean, - desiredFields?: string[]): ContactFindOptions -}; \ No newline at end of file + desiredFields?: ContactFieldType[]): ContactFindOptions +}; From b83a05d33569361f3ebe1ea3dfdb5bfd5499749d Mon Sep 17 00:00:00 2001 From: Jan Bevers Date: Tue, 30 Aug 2016 17:07:55 +0200 Subject: [PATCH 63/68] Added missing method getCurrentLocation to react-router/history --- react-router/history-tests.ts | 12 +++++++++++- react-router/history.d.ts | 1 + 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/react-router/history-tests.ts b/react-router/history-tests.ts index 92b3794e18..6c3096e48a 100644 --- a/react-router/history-tests.ts +++ b/react-router/history-tests.ts @@ -129,4 +129,14 @@ let input = { value: "" }; history.createPath('/the/path') // /base/the/path history.push('/the/path') // push /base/the/path -} \ No newline at end of file +} + +{ + let history = createHistory() + + const { pathname, query, search, state} = history.getCurrentLocation() + console.log(pathname) + console.log(query) + console.log(search) + console.log(state) +} diff --git a/react-router/history.d.ts b/react-router/history.d.ts index 5f94ea3657..a691b8784b 100644 --- a/react-router/history.d.ts +++ b/react-router/history.d.ts @@ -29,6 +29,7 @@ declare namespace HistoryModule { createPath(path: LocationDescriptor): Path createHref(path: LocationDescriptor): Href createLocation(path?: LocationDescriptor, action?: Action, key?: LocationKey): Location + getCurrentLocation: () => Location /** @deprecated use a location descriptor instead */ createLocation(path?: Path, state?: LocationState, action?: Action, key?: LocationKey): Location From fa2d30ed14172c5594ee6728dc51b1ca253c7eb8 Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 30 Aug 2016 16:17:53 -0500 Subject: [PATCH 64/68] Add opentok typings with tests. --- opentok/opentok-tests.ts | 63 +++++++++++++++++++++++++++++++ opentok/opentok.d.ts | 80 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 opentok/opentok-tests.ts create mode 100644 opentok/opentok.d.ts diff --git a/opentok/opentok-tests.ts b/opentok/opentok-tests.ts new file mode 100644 index 0000000000..c6cdfbca66 --- /dev/null +++ b/opentok/opentok-tests.ts @@ -0,0 +1,63 @@ +import * as OpenTok from 'opentok'; + +const client = new OpenTok('API_KEY', 'API_SECRET'); + +const sessionOptions: OpenTok.SessionOptions = { + mediaMode: 'routed', + archiveMode: 'manual', + location: '12.34.56.78', +}; + +client.createSession(sessionOptions, (err: Error, session: OpenTok.Session) => { + if (err) return console.log(err); + console.log(session.sessionId); +}); + +const tokenOptions: OpenTok.TokenOptions = { + role: 'subscriber', + data: 'name=Seth', + expireTime: 123456, +}; + +const token = client.generateToken('SESSION_ID', tokenOptions); + +const archiveOptions: OpenTok.ArchiveOptions = { + name: 'name', + hasAudio: true, + hasVideo: true, + outputMode: 'individual', +}; + +client.startArchive('SESSION_ID', archiveOptions, (err: Error, archive: OpenTok.Archive) => { + if (err) return console.log(err); + console.log(archive.id); +}); + +client.stopArchive('ARCHIVE_ID', (err: Error, archive: OpenTok.Archive) => { + if (err) return console.log(err); + console.log('Stopped archive:' + archive.id); +}); + +client.getArchive('ARCHIVE_ID', (err: Error, archive: OpenTok.Archive) => { + if (err) return console.log(err); + console.log(archive); +}); + +client.deleteArchive('ARCHIVE_ID', (err: Error) => { + if (err) return console.log(err); + console.log('success'); +}); + +const listArchivesOptions: OpenTok.ListArchivesOptions = { + count: 10, + offset: 5, +} + +client.listArchives(listArchivesOptions, (err: Error, archives: OpenTok.Archive[], totalCount: number) => { + if (err) return console.log(err); + + console.log(totalCount + ' archives'); + for (var i = 0; i < archives.length; i++) { + console.log(archives[i].id); + } +}); diff --git a/opentok/opentok.d.ts b/opentok/opentok.d.ts new file mode 100644 index 0000000000..d41e50b3e5 --- /dev/null +++ b/opentok/opentok.d.ts @@ -0,0 +1,80 @@ +// Type definitions for opentok v2.3.2 +// Project: https://github.com/opentok/opentok-node +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'opentok' { + + namespace OpenTok { + + export type OutputMode = 'composed' | 'individual'; + + export type ArchiveStatus = 'available' | 'expired' | 'failed' | 'paused' | 'started' | 'stopped' | 'uploaded'; + + export interface Archive { + createdAt: number; + duration: string; + id: string; + name: string; + partnerId: string; + reason: string; + sessionId: string; + size: number; + status: ArchiveStatus; + hasAudio: boolean; + hasVideo: boolean; + outputMode: OutputMode; + url: string; + } + + export interface ArchiveOptions { + name?: string; + hasAudio?: boolean; + hasVideo?: boolean; + outputMode?: OutputMode; + } + + export type MediaMode = 'relayed' | 'routed'; + + export type ArchiveMode = 'manual' | 'always'; + + export interface SessionOptions { + mediaMode?: MediaMode; + archiveMode?: ArchiveMode; + location?: string; + } + + export interface Session { + sessionId: string; + } + + export type Token = string; + + export type Role = 'subscriber' | 'publisher' | 'moderator'; + + export interface TokenOptions { + role?: Role; + data?: string; + expireTime?: number; + } + + export interface ListArchivesOptions { + count?: number; + offset?: number; + } + } + + class OpenTok { + constructor(apiKey: string, apiSecret: string); + + public createSession(options: OpenTok.SessionOptions, callback: (err: Error, session: OpenTok.Session) => void): void; + public generateToken(sessionId: string, options: OpenTok.TokenOptions): OpenTok.Token; + public startArchive(sessionId: string, options: OpenTok.ArchiveOptions, callback: (err: Error, archive: OpenTok.Archive) => void): void; + public stopArchive(archiveId: string, callback: (err: Error, archive: OpenTok.Archive) => void): void; + public getArchive(archiveId: string, callback: (err: Error, archive: OpenTok.Archive) => void): void; + public deleteArchive(archiveId: string, callback: (err: Error) => void): void; + public listArchives(options: OpenTok.ListArchivesOptions, callback: (err: Error, archives: OpenTok.Archive[], totalCount: number) => void): void; + } + + export = OpenTok; +} From 6b369e37586e78f4439c79adc750f1eb6ce5e79a Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 30 Aug 2016 17:07:22 -0500 Subject: [PATCH 65/68] Add fill-pdf with tests. --- fill-pdf/fill-pdf-tests.ts | 15 +++++++++++++++ fill-pdf/fill-pdf.d.ts | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 fill-pdf/fill-pdf-tests.ts create mode 100644 fill-pdf/fill-pdf.d.ts diff --git a/fill-pdf/fill-pdf-tests.ts b/fill-pdf/fill-pdf-tests.ts new file mode 100644 index 0000000000..44b4f23531 --- /dev/null +++ b/fill-pdf/fill-pdf-tests.ts @@ -0,0 +1,15 @@ +import * as fillPdf from 'fill-pdf'; + +var formData: fillPdf.FormData = { FieldName: 'Text to put into form field' }; +var pdfTemplatePath = 'templates.pdf'; +var extendArgs: string[] = []; + +fillPdf.generatePdf(formData, pdfTemplatePath, extendArgs, (err: Error, output: Buffer) => { + if ( !err ) { + console.log('Success!'); + // output is a buffer + } +}); + +var result = fillPdf.generateFdf(formData); +// result is a buffer diff --git a/fill-pdf/fill-pdf.d.ts b/fill-pdf/fill-pdf.d.ts new file mode 100644 index 0000000000..d35057f934 --- /dev/null +++ b/fill-pdf/fill-pdf.d.ts @@ -0,0 +1,16 @@ +// Type definitions for fill-pdf v0.5.0 +// Project: https://github.com/dommmel/fill-pdf +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'fill-pdf' { + + export interface FormData { + [name: string]: string; + } + + export function generatePdf(data: FormData, templatePath: string, extendArgs: string[], callback?: (err: Error, output: Buffer) => void): void; + export function generateFdf(data: FormData): Buffer; +} From 5f2539f4a0b10cc4bb894bff6107491f0e5a4a4b Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 30 Aug 2016 17:15:40 -0500 Subject: [PATCH 66/68] Add html-pdf typings and tests. --- html-pdf/html-pdf-tests.ts | 10 +++++ html-pdf/html-pdf.d.ts | 80 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 html-pdf/html-pdf-tests.ts create mode 100644 html-pdf/html-pdf.d.ts diff --git a/html-pdf/html-pdf-tests.ts b/html-pdf/html-pdf-tests.ts new file mode 100644 index 0000000000..f6a5ad6e1b --- /dev/null +++ b/html-pdf/html-pdf-tests.ts @@ -0,0 +1,10 @@ +import * as fs from 'fs'; +import * as pdf from 'html-pdf'; + +var html = fs.readFileSync('./test/businesscard.html', 'utf8'); +var options: pdf.CreateOptions = { format: 'Letter' }; + +pdf.create(html, options).toFile('./businesscard.pdf', (err: Error, res: pdf.FileInfo) => { + if (err) return console.log(err); + console.log(res); // { filename: '/app/businesscard.pdf' } +}); diff --git a/html-pdf/html-pdf.d.ts b/html-pdf/html-pdf.d.ts new file mode 100644 index 0000000000..07c4be9f71 --- /dev/null +++ b/html-pdf/html-pdf.d.ts @@ -0,0 +1,80 @@ +// Type definitions for html-pdf v2.1.0 +// Project: https://github.com/marcbachmann/node-html-pdf +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'html-pdf' { + + import * as fs from 'fs'; + + export interface CreateOptions { + + // Export options + directory?: string; + + // Papersize Options: http://phantomjs.org/api/webpage/property/paper-size.html + height?: string; + width?: string; + format?: 'A3' | 'A4' | 'A5' | 'Legal' | 'Letter' | 'Tabloid'; + orientation?: 'portrait' | 'landscape'; + + // Page options + border?: string | { + top?: string; + right?: string; + bottom?: string; + left?: string; + }; + + header?: { + height?: string; + contents?: string; + }; + footer?: { + height?: string; + contents?: { + first?: string; + [page: number]: string; + default?: string; + last?: string; + }; + }; + + // Rendering options + base?: string; + + // Zooming option, can be used to scale images if `options.type` is not pdf + zoomFactor?: string; + + // File options + type?: 'png' | 'jpeg' | 'pdf'; + quality?: string; + + // Script options + phantomPath?: string; + phantomArgs?: string[]; + script?: string; + timeout?: number; + + // HTTP Headers that are used for requests + httpHeaders?: { + [header: string]: string; + }; + + } + + export interface FileInfo { + filename: string; + } + + export interface CreateResult { + toBuffer(callback: (err: Error, buffer: Buffer) => void): void; + toFile(callback: (err: Error, res: FileInfo) => void): void; + toFile(filename?: string, callback?: (err: Error, res: FileInfo) => void): void; + toStream(callback: (err: Error, stream: fs.ReadStream) => void): void; + } + + export function create(html: string, options?: CreateOptions): CreateResult; +} From a6474285c37274633f9ec548962e7de29f0489a5 Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 30 Aug 2016 17:21:52 -0500 Subject: [PATCH 67/68] Add phone-formatter typings and tests. --- phone-formatter/phone-formatter-tests.ts | 7 +++++++ phone-formatter/phone-formatter.d.ts | 14 ++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 phone-formatter/phone-formatter-tests.ts create mode 100644 phone-formatter/phone-formatter.d.ts diff --git a/phone-formatter/phone-formatter-tests.ts b/phone-formatter/phone-formatter-tests.ts new file mode 100644 index 0000000000..1912fbf23a --- /dev/null +++ b/phone-formatter/phone-formatter-tests.ts @@ -0,0 +1,7 @@ +import * as phoneFormatter from 'phone-formatter'; + +phoneFormatter.normalize('212.555.1212'); +phoneFormatter.normalize('+1 (212) 555-1212'); + +phoneFormatter.format('(212) 555-1212', 'NNN.NNN.NNNN'); +phoneFormatter.format('(212) 555-1212', 'NNN.NNN.NNNN', {normalize: false}); diff --git a/phone-formatter/phone-formatter.d.ts b/phone-formatter/phone-formatter.d.ts new file mode 100644 index 0000000000..2626616657 --- /dev/null +++ b/phone-formatter/phone-formatter.d.ts @@ -0,0 +1,14 @@ +// Type definitions for phone-formatter v0.0.2 +// Project: https://github.com/stevekinney/node-phone-formatter +// Definitions by: Seth Westphal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'phone-formatter' { + + export interface FormatOptions { + normalize: boolean; + } + + export function normalize(digits: string): string; + export function format(digits: string, format: string, options?: FormatOptions): string; +} From 208abb5b313e1f0701918761a6b2e3d8131c68b6 Mon Sep 17 00:00:00 2001 From: Seth Westphal Date: Tue, 30 Aug 2016 17:28:00 -0500 Subject: [PATCH 68/68] Fix imports for typing tests. --- fill-pdf/fill-pdf-tests.ts | 2 ++ html-pdf/html-pdf-tests.ts | 3 +++ opentok/opentok-tests.ts | 2 ++ phone-formatter/phone-formatter-tests.ts | 2 ++ 4 files changed, 9 insertions(+) diff --git a/fill-pdf/fill-pdf-tests.ts b/fill-pdf/fill-pdf-tests.ts index 44b4f23531..e5b34cd943 100644 --- a/fill-pdf/fill-pdf-tests.ts +++ b/fill-pdf/fill-pdf-tests.ts @@ -1,3 +1,5 @@ +/// + import * as fillPdf from 'fill-pdf'; var formData: fillPdf.FormData = { FieldName: 'Text to put into form field' }; diff --git a/html-pdf/html-pdf-tests.ts b/html-pdf/html-pdf-tests.ts index f6a5ad6e1b..6a214ef231 100644 --- a/html-pdf/html-pdf-tests.ts +++ b/html-pdf/html-pdf-tests.ts @@ -1,3 +1,6 @@ +/// +/// + import * as fs from 'fs'; import * as pdf from 'html-pdf'; diff --git a/opentok/opentok-tests.ts b/opentok/opentok-tests.ts index c6cdfbca66..dcbb1f8aa0 100644 --- a/opentok/opentok-tests.ts +++ b/opentok/opentok-tests.ts @@ -1,3 +1,5 @@ +/// + import * as OpenTok from 'opentok'; const client = new OpenTok('API_KEY', 'API_SECRET'); diff --git a/phone-formatter/phone-formatter-tests.ts b/phone-formatter/phone-formatter-tests.ts index 1912fbf23a..89b84c04a0 100644 --- a/phone-formatter/phone-formatter-tests.ts +++ b/phone-formatter/phone-formatter-tests.ts @@ -1,3 +1,5 @@ +/// + import * as phoneFormatter from 'phone-formatter'; phoneFormatter.normalize('212.555.1212');