From 53cb2ca2928aaa65c25734b8a974c9c336bfdfa6 Mon Sep 17 00:00:00 2001 From: Luke Venn Date: Thu, 21 Apr 2016 10:39:10 +0100 Subject: [PATCH 0001/1255] Added RegExp typing to 'path' argument descriptions --- nock/nock.d.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/nock/nock.d.ts b/nock/nock.d.ts index 208aac9b31..3319456a5e 100644 --- a/nock/nock.d.ts +++ b/nock/nock.d.ts @@ -22,28 +22,45 @@ declare module "nock" { export interface Scope { get(path: string, data?: string): Scope; + get(path: RegExp, data?: string): Scope; post(path: string, data?: string): Scope; post(path: string, data?: Object): Scope; post(path: string, regex?: RegExp): Scope; + post(path: RegExp, data?: string): Scope; + post(path: RegExp, data?: Object): Scope; + post(path: RegExp, regex?: RegExp): Scope; patch(path: string, data?: string): Scope; patch(path: string, data?: Object): Scope; patch(path: string, regex?: RegExp): Scope; + patch(path: RegExp, data?: string): Scope; + patch(path: RegExp, data?: Object): Scope; + patch(path: RegExp, regex?: RegExp): Scope; put(path: string, data?: string): Scope; put(path: string, data?: Object): Scope; put(path: string, regex?: RegExp): Scope; + put(path: RegExp, data?: string): Scope; + put(path: RegExp, data?: Object): Scope; + put(path: RegExp, regex?: RegExp): Scope; head(path: string): Scope; + head(path: RegExp): Scope; delete(path: string, data?: string): Scope; delete(path: string, data?: Object): Scope; delete(path: string, regex?: RegExp): Scope; + delete(path: RegExp, data?: string): Scope; + delete(path: RegExp, data?: Object): Scope; + delete(path: RegExp, regex?: RegExp): Scope; merge(path: string, data?: string): Scope; merge(path: string, data?: Object): Scope; merge(path: string, regex?: RegExp): Scope; + merge(path: RegExp, data?: string): Scope; + merge(path: RegExp, data?: Object): Scope; + merge(path: RegExp, regex?: RegExp): Scope; query(params: any): Scope; query(acceptAnyParams: boolean): Scope; @@ -51,6 +68,9 @@ declare module "nock" { intercept(path: string, verb: string, body?: string, options?: any): Scope; intercept(path: string, verb: string, body?: Object, options?: any): Scope; intercept(path: string, verb: string, body?: RegExp, options?: any): Scope; + intercept(path: RegExp, verb: string, body?: string, options?: any): Scope; + intercept(path: RegExp, verb: string, body?: Object, options?: any): Scope; + intercept(path: RegExp, verb: string, body?: RegExp, options?: any): Scope; reply(responseCode: number, body?: string, headers?: Object): Scope; reply(responseCode: number, body?: Object, headers?: Object): Scope; From 634752a79ec35f607ecfd66b09bbf44470f174f1 Mon Sep 17 00:00:00 2001 From: microshine Date: Fri, 6 May 2016 02:00:31 +0300 Subject: [PATCH 0002/1255] xadesjs beta --- xadesjs/promise.d.ts | 14 + xadesjs/xadesjs.d.ts | 1075 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 1089 insertions(+) create mode 100644 xadesjs/promise.d.ts create mode 100644 xadesjs/xadesjs.d.ts diff --git a/xadesjs/promise.d.ts b/xadesjs/promise.d.ts new file mode 100644 index 0000000000..96b926633b --- /dev/null +++ b/xadesjs/promise.d.ts @@ -0,0 +1,14 @@ +interface PromiseFunc { + (resolve: (...args: any[]) => void, reject: (...args: any[]) => void): void; +} + +declare class Promise { + constructor(func: PromiseFunc); + + then(resolve: (...args: any[]) => any): Promise; + then(resolve: (...args: any[]) => any, reject: (...args: any[]) => any): Promise; + catch(reject: (...args: any[]) => any): void; + + static resolve(...args: any[]): Promise; + static reject(...args: any[]): Promise; +} \ No newline at end of file diff --git a/xadesjs/xadesjs.d.ts b/xadesjs/xadesjs.d.ts new file mode 100644 index 0000000000..4eb7b6a1c5 --- /dev/null +++ b/xadesjs/xadesjs.d.ts @@ -0,0 +1,1075 @@ +/// + +declare namespace xadesjs { + + const APPLICATION_XML: string; + + class XmlError extends Error { + stack: any; + constructor(code: XE, ...args: any[]); + } + + enum XE { + NONE = 0, + NULL_REFERENCE = 1, + METHOD_NOT_IMPLEMENTED = 2, + METHOD_NOT_SUPPORTED = 3, + PARAM_REQUIRED = 4, + CONVERTER_UNSUPPORTED = 5, + ELEMENT_MALFORMED = 6, + CRYPTOGRAPHIC = 7, + CRYPTOGRAPHIC_NO_MODULE = 8, + CRYPTOGRAPHIC_UNKNOWN_TRANSFORM = 9, + ALGORITHM_NOT_SUPPORTED = 10, + ALGORITHM_WRONG_NAME = 11, + XML_EXCEPTION = 12, + } + + interface CryptoEx extends Crypto { + name: string; + } + + class Application { + /** + * Sets crypto engine for the current Application + * @param {string} name + * @param {Crypto} crypto + * @returns void + */ + static setEngine(name: string, crypto: Crypto): void; + /** + * Gets the crypto module from the Application + */ + static crypto: CryptoEx; + static isNodePlugin(): boolean; + } + + enum XmlNodeType { + None = 0, + Element = 1, + Attribute = 2, + Text = 3, + CDATA = 4, + EntityReference = 5, + Entity = 6, + ProcessingInstruction = 7, + Comment = 8, + Document = 9, + DocumentType = 10, + DocumentFragment = 11, + Notation = 12, + Whitespace = 13, + SignificantWhitespace = 14, + EndElement = 15, + EndEntity = 16, + XmlDeclaration = 17, + } + + interface IXmlSerializable { + Prefix: string; + /** + * Writes object to XML node + * @returns Node + */ + GetXml(): Node; + /** + * Reads XML from string + * @param {Node} node + * @returns void + */ + LoadXml(node: Node): void; + } + + abstract class XmlObject implements IXmlSerializable { + protected m_prefix: string; + Prefix: string; + protected GetPrefix(): string; + GetXml(): Node; + GetXml(document: Document): Node; + LoadXml(node: Node): void; + toString(): string; + protected getAttribute(xel: Element, attribute: string): string; + } + + const DEFAULT_ROOT_NAME: string; + function IsEqualsEmptyStrings(s1: string, s2: string): boolean; + /** + * Creates new instance of XmlDocument with given name of root element + * @param {string} root Name of root element + * @param {string} namespaceUri + * @param {string} prefix + * @returns Document + */ + function CreateDocument(root?: string, namespaceUri?: string, prefix?: string): Document; + /** + * Returns signle Node from given Node + * @param {Node} node + * @param {string} path + * @returns Node + */ + function SelectSingleNode(node: Node, path: string): Node; + + function findAttr(node: Node, localName: string, nameSpace?: string): Attr; + function findFirst(doc: Node, xpath: string): Node; + function findChilds(node: Node, localName: string, nameSpace?: string): Node[]; + interface IAssocArray { + [index: string]: string; + } + function encodeSpecialCharactersInAttribute(attributeValue: string): string; + function encodeSpecialCharactersInText(text: string): string; + function SelectNamespaces(node: Element): Node[]; + + class Convert { + static ToBase64UrlString(text: string): string; + static FromBase64UrlString(base64UrlText: string): string; + static ToBase64String(text: string): string; + static FromBase64String(base64Text: string): string; + static Base64UrlToBase64(base64url: string): string; + static Base64ToBase64Url(base64: string): string; + static ToBufferUtf8String(text: string): Uint8Array; + static FromBufferUtf8String(buffer: Uint8Array): string; + static ToBufferString(text: string): Uint8Array; + static FromBufferString(buffer: ArrayBuffer): string; + static FromBufferString(buffer: Uint8Array): string; + } + + interface IAlgorithm { + algorithm: Algorithm; + xmlNamespace: string; + getAlgorithmName(): string; + } + interface IHashAlgorithm extends IAlgorithm { + getHash(xml: string): Promise; + } + interface IHashAlgorithmConstructable { + new (): IHashAlgorithm; + } + abstract class XmlAlgorithm implements IAlgorithm { + algorithm: Algorithm; + xmlNamespace: string; + getAlgorithmName(): string; + } + abstract class HashAlgorithm extends XmlAlgorithm implements IHashAlgorithm { + getHash(xml: string): Promise; + } + interface ISignatureAlgorithm extends IAlgorithm { + getSignature(signedInfo: string, signingKey: CryptoKey, algorithm: Algorithm): Promise; + verifySignature(signedInfo: string, key: CryptoKey, signatureValue: string, algorithm?: Algorithm): Promise; + } + interface ISignatureAlgorithmConstructable { + new (): ISignatureAlgorithm; + } + abstract class SignatureAlgorithm extends XmlAlgorithm implements ISignatureAlgorithm { + /** + * Sign the given string using the given key + */ + getSignature(signedInfo: string, signingKey: CryptoKey, algorithm: Algorithm): Promise; + /** + * Verify the given signature of the given string using key + */ + verifySignature(signedInfo: string, key: CryptoKey, signatureValue: string, algorithm?: Algorithm): Promise; + } + + const SHA1: string; + const SHA224: string; + const SHA256: string; + const SHA384: string; + const SHA512: string; + const SHA1_NAMESPACE: string; + const SHA224_NAMESPACE: string; + const SHA256_NAMESPACE: string; + const SHA384_NAMESPACE: string; + const SHA512_NAMESPACE: string; + class Sha1 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + class Sha224 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + class Sha256 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + class Sha384 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + class Sha512 extends HashAlgorithm { + algorithm: { + name: string; + }; + xmlNamespace: string; + } + + // RSA PKCS1 + + const RSA_PKCS1: string; + const RSA_PKCS1_SHA1_NAMESPACE: string; + const RSA_PKCS1_SHA224_NAMESPACE: string; + const RSA_PKCS1_SHA256_NAMESPACE: string; + const RSA_PKCS1_SHA384_NAMESPACE: string; + const RSA_PKCS1_SHA512_NAMESPACE: string; + + class RsaPkcs1Sha1 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPkcs1Sha224 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPkcs1Sha256 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPkcs1Sha384 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPkcs1Sha512 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + + // RSA PSS + + const RSA_PSS: string; + const RSA_PSS_WITH_PARAMS_NAMESPACE: string; + const RSA_PSS_WITH_PARAMS_MGF1_NAMESPACE: string; + + class RsaPssSha1 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPssSha224 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPssSha256 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPssSha384 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class RsaPssSha512 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class PssAlgorithmParams extends XmlObject { + private m_digest_method; + private m_salt_length; + private m_mgf; + private element; + dsPrefix: string; + DigestMethod: string; + SaltLength: number; + MGF: string; + GetXml(): Element; + LoadXml(value: Element): void; + } + + // HMAC + + const HMAC_ALGORITHM: string; + const HMAC_SHA1_NAMESPACE: string; + const HMAC_SHA256_NAMESPACE: string; + const HMAC_SHA384_NAMESPACE: string; + const HMAC_SHA512_NAMESPACE: string; + + class HmacSha1 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class HmacSha256 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class HmacSha384 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class HmacSha512 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + + // ECDSA + + const ECDSA_SIGN_ALGORITHM: string; + const ECDSA_SHA1_NAMESPACE: string; + const ECDSA_SHA224_NAMESPACE: string; + const ECDSA_SHA256_NAMESPACE: string; + const ECDSA_SHA384_NAMESPACE: string; + const ECDSA_SHA512_NAMESPACE: string; + class EcdsaSha1 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class EcdsaSha224 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class EcdsaSha256 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class EcdsaSha384 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + class EcdsaSha512 extends SignatureAlgorithm { + algorithm: any; + xmlNamespace: string; + } + + /** + * Represents an element. + */ + class X509Certificate { + protected raw: Uint8Array; + protected cert_simpl: any; + protected publicKey: CryptoKey; + constructor(rawData?: Uint8Array); + /** + * Loads X509Certificate from DER data + * @param {Uint8Array} rawData + */ + protected LoadFromRawData(rawData: Uint8Array): void; + /** + * Gets the public key from the X509Certificate + */ + PublicKey: CryptoKey; + /** + * Returns DER raw of X509Certificate + */ + GetRawCertData(): Uint8Array; + /** + * Returns public key from X509Certificate + * @param {Algorithm} algorithm + * @returns Promise + */ + exportKey(algorithm: Algorithm): Promise; + } + + enum X509IncludeOption { + None = 0, + EndCertOnly = 1, + ExcludeRoot = 2, + WholeChain = 3, + } + interface X509IssuerSerial { + issuerName: string; + serialNumber: string; + } + /** + * Represents an subelement of an XMLDSIG or XML Encryption element. + */ + class KeyInfoX509Data extends XmlObject implements KeyInfoClause { + + constructor(); + constructor(rgbCert: Uint8Array); + constructor(cert: X509Certificate); + /** + * Gets public key of the X509Data + */ + Key: CryptoKey; + importKey(key: CryptoKey): Promise; + /** + * Exports key from X509Data object + * @param {Algorithm} alg + * @returns Promise + */ + exportKey(alg: Algorithm): Promise; + /** + * Gets a list of the X.509v3 certificates contained in the KeyInfoX509Data object. + */ + Certificates: X509Certificate[]; + /** + * Gets or sets the Certificate Revocation List (CRL) contained within the KeyInfoX509Data object. + */ + CRL: Uint8Array; + /** + * Gets a list of X509IssuerSerial structures that represent an issuer name and serial number pair. + */ + IssuerSerials: X509IssuerSerial[]; + /** + * Gets a list of the subject key identifiers (SKIs) contained in the KeyInfoX509Data object. + */ + SubjectKeyIds: Uint8Array[]; + /** + * Gets a list of the subject names of the entities contained in the KeyInfoX509Data object. + */ + SubjectNames: string[]; + /** + * Adds the specified X.509v3 certificate to the KeyInfoX509Data. + * @param {X509Certificate} certificate + * @returns void + */ + AddCertificate(certificate: X509Certificate): void; + /** + * Adds the specified issuer name and serial number pair to the KeyInfoX509Data object. + * @param {string} issuerName + * @param {string} serialNumber + * @returns void + */ + AddIssuerSerial(issuerName: string, serialNumber: string): void; + /** + * Adds the specified subject key identifier (SKI) to the KeyInfoX509Data object. + * @param {string | Uint8Array} subjectKeyId + * @returns void + */ + AddSubjectKeyId(subjectKeyId: string): void; + AddSubjectKeyId(subjectKeyId: Uint8Array): void; + /** + * Adds the subject name of the entity that was issued an X.509v3 certificate to the KeyInfoX509Data object. + * @param {string} subjectName + * @returns void + */ + AddSubjectName(subjectName: string): void; + /** + * Returns an XML representation of the KeyInfoX509Data object. + * @returns Element + */ + GetXml(): Element; + /** + * Parses the input XmlElement object and configures the internal state of the KeyInfoX509Data object to match. + * @param {Element} element + * @returns void + */ + LoadXml(element: Element): void; + } + + interface IJwkRsa { + alg: string; + kty: string; + e: string; + n: string; + ext: boolean; + } + /** + * Represents the element of an XML signature. + */ + class RsaKeyValue extends XmlObject implements KeyInfoClause { + /** + * Gets or sets the instance of RSA that holds the public key. + */ + Key: CryptoKey; + /** + * Gets the algorithm of the public key + */ + Algorithm: ISignatureAlgorithm; + /** + * Gets the Modulus of the public key + */ + Modulus: Uint8Array; + /** + * Gets the Exponent of the public key + */ + Exponent: Uint8Array; + constructor(); + /** + * Imports key to the RSAKeyValue object + * @param {CryptoKey} key + * @returns Promise + */ + importKey(key: CryptoKey): Promise; + /** + * Exports key from the RSAKeyValue object + * @param {Algorithm} alg + * @returns Promise + */ + exportKey(alg: Algorithm): Promise; + /** + * Returns the XML representation of the RSA key clause. + * @returns Element + */ + GetXml(): Element; + /** + * Loads an RSA key clause from an XML element. + * @param {Element} element + * @returns void + */ + LoadXml(element: Element): void; + } + + type NamedCurve = "P-256" | "P-384" | "P-521"; + + interface IJwkEcdsa { + crv: NamedCurve; + kty: "EC"; + x: string; + y: string; + ext: boolean; + } + + /** + * Represents the element of an XML signature. + */ + class EcdsaKeyValue extends XmlObject implements KeyInfoClause { + /** + * Gets or sets the instance of ECDSA that holds the public key. + */ + Key: CryptoKey; + /** + * Gets the algorithm of the public key + */ + Algorithm: ISignatureAlgorithm; + /** + * Gets the X point value of then public key + */ + X: Uint8Array; + /** + * Gets the Y point value of then public key + */ + Y: Uint8Array; + /** + * Gets the NamedCurve value of then public key + */ + NamedCurve: NamedCurve; + constructor(); + /** + * Imports key to the ECKeyValue object + * @param {CryptoKey} key + * @returns Promise + */ + importKey(key: CryptoKey): Promise; + /** + * Exports key from the ECKeyValue object + * @param {Algorithm} alg + * @returns Promise + */ + exportKey(alg: Algorithm): Promise; + /** + * Returns the XML representation of the ECDSA key clause. + * @returns Element + */ + GetXml(): Element; + /** + * Loads an ECDSA key clause from an XML element. + * @param {Element} element + * @returns void + */ + LoadXml(element: Element): void; + } + + type XmlNamespace = { + prefix: string; + namespace: string; + }; + + enum XmlCanonicalizerState { + BeforeDocElement = 0, + InsideDocElement = 1, + AfterDocElement = 2, + } + + class XmlCanonicalizer { + constructor(withComments: boolean, excC14N: boolean, propagatedNamespaces?: XmlNamespace[]); + InclusiveNamespacesPrefixList: string; + Canonicalize(node: Node): string; + } + + interface Transform extends IXmlSerializable { + Algorithm: string; + LoadInnerXml(node: Node): void; + GetInnerXml(): Node; + GetOutput(): string; + } + + interface ICanonicalizationAlgorithmConstructable { + new (): Transform; + } + /** + * Represents the abstract base class from which all elements + * that can be used in an XML digital signature derive. + */ + abstract class Transform extends XmlObject implements Transform { + protected innerXml: Node; + LoadXml(value: Node): void; + /** + * Returns the XML representation of the current Transform object. + * @returns Element + */ + GetXml(): Element; + } + + /** + * Represents the enveloped signature transform for an XML digital signature as defined by the W3C. + */ + class XmlDsigEnvelopedSignatureTransform extends Transform { + Algorithm: string; + /** + * Returns the output of the current XmlDsigEnvelopedSignatureTransform object. + * @returns string + */ + GetOutput(): string; + } + + /** + * Represents the C14N XML canonicalization transform for a digital signature + * as defined by the World Wide Web Consortium (W3C), without comments. + */ + class XmlDsigC14NTransform extends Transform { + protected xmlCanonicalizer: XmlCanonicalizer; + Algorithm: string; + /** + * Returns the output of the current XmlDsigC14NTransform object. + * @returns string + */ + GetOutput(): string; + } + /** + * Represents the C14N XML canonicalization transform for a digital signature + * as defined by the World Wide Web Consortium (W3C), with comments. + */ + class XmlDsigC14NWithCommentsTransform extends XmlDsigC14NTransform { + Algorithm: string; + protected xmlCanonicalizer: XmlCanonicalizer; + } + + /** + * Represents the exclusive C14N XML canonicalization transform for a digital signature + * as defined by the World Wide Web Consortium (W3C), without comments. + */ + class XmlDsigExcC14NTransform extends Transform { + protected xmlCanonicalizer: XmlCanonicalizer; + Algorithm: string; + /** + * Gets or sets a string that contains namespace prefixes to canonicalize + * using the standard canonicalization algorithm. + */ + InclusiveNamespacesPrefixList: string; + /** + * Returns the output of the current XmlDsigExcC14NTransform object + */ + GetOutput(): string; + } + /** + * Represents the exclusive C14N XML canonicalization transform for a digital signature + * as defined by the World Wide Web Consortium (W3C), with comments. + */ + class XmlDsigExcC14NWithCommentsTransform extends XmlDsigExcC14NTransform { + Algorithm: string; + protected xmlCanonicalizer: XmlCanonicalizer; + } + + class CryptoConfig { + static CreateFromName(name: string): Transform; + static CreateSignatureAlgorithm(namespace: string): SignatureAlgorithm; + static CreateHashAlgorithm(namespace: string): HashAlgorithm; + } + + /** + * Represents the object element of an XML signature that holds data to be signed. + */ + class DataObject extends XmlObject { + constructor(); + constructor(id?: string, mimeType?: string, encoding?: string, data?: Element); + /** + * Gets or sets the data value of the current DataObject object. + */ + Data: NodeList; + /** + * Gets or sets the encoding of the current DataObject object. + */ + Encoding: string; + /** + * Gets or sets the identification of the current DataObject object. + */ + Id: string; + /** + * Gets or sets the MIME type of the current DataObject object. + */ + MimeType: string; + /** + * Returns the XML representation of the DataObject object. + * @returns Element + */ + GetXml(): Element; + /** + * Loads a DataObject state from an XML element. + * @param {Element} value + * @returns void + */ + LoadXml(value: Element): void; + } + + /** + * Represents the element of an XML signature. + */ + class Reference extends XmlObject { + + constructor(p?: string); + /** + * Gets or sets the digest method Uniform Resource Identifier (URI) of the current + */ + DigestMethod: string; + /** + * Gets or sets the digest value of the current Reference. + */ + DigestValue: ArrayBuffer; + /** + * Gets or sets the ID of the current Reference. + */ + Id: string; + /** + * Gets the transform chain of the current Reference. + */ + TransformChain: Transform[]; + /** + * Gets or sets the type of the object being signed. + */ + Type: string; + /** + * Gets or sets the Uri of the current Reference. + */ + Uri: string; + /** + * Adds a Transform object to the list of transforms to be performed + * on the data before passing it to the digest algorithm. + * @param {Transform} transform The transform to be added to the list of transforms. + * @returns void + */ + AddTransform(transform: Transform): void; + /** + * Returns the XML representation of the Reference. + * @returns Element + */ + GetXml(): Element; + /** + * Loads a Reference state from an XML element. + * @param {Element} value + */ + LoadXml(value: Element): void; + } + + /** + * Represents an XML digital signature or XML encryption element. + */ + class KeyInfo extends XmlObject { + constructor(); + /** + * Gets the number of KeyInfoClause objects contained in the KeyInfo object. + */ + length: number; + /** + * Gets or sets the key information identity. + */ + Id: string; + /** + * Returns an enumerator of the KeyInfoClause objects in the KeyInfo object. + * @param {any} requestedObjectType? + */ + GetEnumerator(): Array; + GetEnumerator(requestedObjectType: any): Array; + /** + * Returns an enumerator of the KeyInfoClause objects in the KeyInfo object. + * @param {KeyInfoClause} clause The KeyInfoClause to add to the KeyInfo object. + * @returns void + */ + AddClause(clause: KeyInfoClause): void; + /** + * Returns the XML representation of the KeyInfo object. + * @returns Node + */ + GetXml(): Node; + /** + * Loads a KeyInfo state from an XML element. + * @param {Element} value + * @returns void + */ + LoadXml(value: Element): void; + } + interface KeyInfoClause extends IXmlSerializable { + Key: CryptoKey; + importKey(key: CryptoKey): Promise; + exportKey(alg: Algorithm): Promise; + } + + /** + * Represents the element of an XML signature. + */ + class Signature extends XmlObject { + + constructor(); + /** + * Gets or sets the ID of the current Signature. + */ + Id: string; + /** + * Gets or sets the KeyInfo of the current Signature. + */ + KeyInfo: KeyInfo; + /** + * Gets or sets a list of objects to be signed. + */ + ObjectList: Array; + /** + * Gets or sets the value of the digital signature. + */ + SignatureValue: Uint8Array; + /** + * Gets or sets the SignedInfo of the current Signature. + */ + SignedInfo: SignedInfo; + /** + * Adds a DataObject to the list of objects to be signed. + * @param {DataObject} dataObject The DataObject to be added to the list of objects to be signed. + * @returns void + */ + AddObject(dataObject: DataObject): void; + /** + * Returns the XML representation of the Signature. + * @returns Element + */ + GetXml(): Element; + /** + * Loads a Signature state from an XML element. + * @param {Element} value + * @returns void + */ + LoadXml(value: Element): void; + } + const XmlSignature: { + ElementNames: { + CanonicalizationMethod: string; + DigestMethod: string; + DigestValue: string; + DSAKeyValue: string; + EncryptedKey: string; + HMACOutputLength: string; + RSAPSSParams: string; + MaskGenerationFunction: string; + SaltLength: string; + KeyInfo: string; + KeyName: string; + KeyValue: string; + Modulus: string; + Exponent: string; + Manifest: string; + Object: string; + Reference: string; + RetrievalMethod: string; + RSAKeyValue: string; + ECKeyValue: string; + NamedCurve: string; + PublicKey: string; + Signature: string; + SignatureMethod: string; + SignatureValue: string; + SignedInfo: string; + Transform: string; + Transforms: string; + X509Data: string; + X509IssuerSerial: string; + X509IssuerName: string; + X509SerialNumber: string; + X509SKI: string; + X509SubjectName: string; + X509Certificate: string; + X509CRL: string; + }; + AttributeNames: { + Algorithm: string; + Encoding: string; + Id: string; + MimeType: string; + Type: string; + URI: string; + }; + AlgorithmNamespaces: { + XmlDsigBase64Transform: string; + XmlDsigC14NTransform: string; + XmlDsigC14NWithCommentsTransform: string; + XmlDsigEnvelopedSignatureTransform: string; + XmlDsigXPathTransform: string; + XmlDsigXsltTransform: string; + XmlDsigExcC14NTransform: string; + XmlDsigExcC14NWithCommentsTransform: string; + XmlDecryptionTransform: string; + XmlLicenseTransform: string; + }; + Uri: { + Manifest: string; + }; + NamespaceURI: string; + NamespaceURIMore: string; + NamespaceURIPss: string; + Prefix: string; + GetChildElement: (xel: Node, element: string, ns: string) => Element; + GetAttributeFromElement: (xel: Element, attribute: string, element: string) => string; + GetChildElements: (xel: Element, element: string) => Element[]; + }; + + /** + * The SignedInfo class represents the element + * of an XML signature defined by the XML digital signature specification + */ + class SignedInfo extends XmlObject { + + constructor(signedXml?: SignedXml); + /** + * Gets or sets the canonicalization algorithm that is used before signing + * for the current SignedInfo object. + */ + CanonicalizationMethod: string; + /** + * Gets a Transform object used for canonicalization. + * @returns Transform + */ + CanonicalizationMethodObject: Transform; + /** + * Gets the number of references in the current SignedInfo object. + */ + Count: number; + /** + * Gets or sets the ID of the current SignedInfo object. + */ + Id: string; + /** + * Gets a value that indicates whether the collection is read-only. + * @returns boolean + */ + IsReadOnly: boolean; + /** + * Gets a value that indicates whether the collection is synchronized. + * @returns boolean + */ + IsSynchronized: boolean; + /** + * Gets a list of the Reference objects of the current SignedInfo object. + */ + References: Reference[]; + /** + * Gets or sets the length of the signature for the current SignedInfo object. + */ + SignatureLength: string; + /** + * Gets or sets the name of the algorithm used for signature generation + * and validation for the current SignedInfo object. + */ + SignatureMethod: string; + SignatureParams: XmlObject; + /** + * Gets an object to use for synchronization. + */ + SyncRoot: any; + /** + * Adds a Reference object to the list of references to digest and sign. + * @param {Reference} reference The reference to add to the list of references. + * @returns void + */ + AddReference(reference: Reference): void; + /** + * Copies the elements of this instance into an Array object, starting at a specified index in the array. + * @param {any[]} array + * @param {number} index + * @returns void + */ + CopyTo(array: any[], index: number): void; + /** + * Returns the XML representation of the SignedInfo object. + * @returns Node + */ + GetXml(): Node; + /** + * Loads a SignedInfo state from an XML element. + * @param {Element} value + * @returns void + */ + LoadXml(value: Element): void; + } + + /** + * Provides a wrapper on a core XML signature object to facilitate creating XML signatures. + */ + class SignedXml extends XmlObject { + /** + * Gets or sets the KeyInfo object of the current SignedXml object. + */ + KeyInfo: KeyInfo; + /** + * Gets the Signature object of the current SignedXml object. + */ + Signature: Signature; + /** + * Gets or sets the prefix for the current SignedXml object. + */ + Prefix: string; + /** + * Gets the length of the signature for the current SignedXml object. + */ + SignatureLength: number; + SignatureMethod: string; + /** + * Gets the signature value of the current SignedXml object. + */ + SignatureValue: ArrayBuffer; + /** + * Gets the CanonicalizationMethod of the current SignedXml object. + */ + CanonicalizationMethod: string; + /** + * Gets the SignedInfo object of the current SignedXml object. + */ + SignedInfo: SignedInfo; + /** + * Gets or sets the asymmetric algorithm key used for signing a SignedXml object. + */ + SigningKey: CryptoKey; + /** + * Gets or sets the name of the installed key to be used for signing the SignedXml object. + */ + SigningKeyName: string; + /** + * @param {string} idMode. Value of "wssecurity" will create/validate id's with the ws-security namespace + */ + constructor(); + constructor(node: Document); + constructor(node: Element); + /** + * Adds a Reference object to the SignedXml object that describes a digest method, + * digest value, and transform to use for creating an XML digital signature. + * @param {Reference} reference The Reference object that describes a digest method, digest value, + * and transform to use for creating an XML digital signature. + * @returns void + */ + AddReference(reference: Reference): void; + /** + * Computes an XML digital signature using the specified algorithm. + * @param {Algorithm} algorithm Specified WebCrypto Algoriithm + * @returns Promise + */ + ComputeSignature(algorithm: Algorithm): Promise; + /** + * Determines whether the SignedXml.Signature property verifies using the public key in the signature. + * @returns Promise + */ + CheckSignature(): Promise; + CheckSignature(key: CryptoKey): Promise; + CheckSignature(cert: X509Certificate): Promise; + /** + * Loads a SignedXml state from an XML element. + * @param {Element} value The XML element to load the SignedXml state from. + * @returns void + */ + LoadXml(value: Element): void; + /** + * Returns the XML representation of a SignedXml object. + * @returns Element + */ + GetXml(): Element; + } +} From df611346ddf7a2a600e23fcd1e9fd3814769981a Mon Sep 17 00:00:00 2001 From: microshine Date: Mon, 9 May 2016 12:28:15 +0300 Subject: [PATCH 0003/1255] Add test & set version --- xadesjs/xadesjs-tests.ts | 47 ++++++++++++++++++++++++++++++++++++++++ xadesjs/xadesjs.d.ts | 10 +++++++++ 2 files changed, 57 insertions(+) create mode 100644 xadesjs/xadesjs-tests.ts diff --git a/xadesjs/xadesjs-tests.ts b/xadesjs/xadesjs-tests.ts new file mode 100644 index 0000000000..e83cb0cf6a --- /dev/null +++ b/xadesjs/xadesjs-tests.ts @@ -0,0 +1,47 @@ +/// + +let xmlString = ""; +let xmlDoc = new DOMParser().parseFromString(xmlString, "application/xml"); +let signedXml = new xadesjs.SignedXml(xmlDoc); + +let alg = { + name: "ECDSA", + namedCurve: "P-256" +}; +xadesjs.Application.crypto.subtle.generateKey( + alg, + false, + ["sign", "verify"] +) + .then((keys: CryptoKeyPair) => { + signedXml.SigningKey = keys.privateKey; + + // Add the key to the SignedXml document. + // Create a reference to be signed. + let reference = new xadesjs.Reference(); + reference.Uri = ""; + // Add an enveloped transformation to the reference. + reference.AddTransform(new xadesjs.XmlDsigEnvelopedSignatureTransform()); + // Add the reference to the SignedXml object. + signedXml.AddReference(reference); + // Set prefix for Signature namespace + signedXml.Prefix = "ds"; + + // Compute the signature. + return signedXml.ComputeSignature({ name: "ECDSA", hash: { name: "SHA-256" } } as any); + }) + .then(function () { + // Append signature + let xmlDigitalSignature = signedXml.GetXml(); + xmlDoc.documentElement.appendChild(xmlDigitalSignature); + + // Serialize XML document + let signedDocument = new XMLSerializer().serializeToString(xmlDoc); + return Promise.resolve(signedDocument); + }) + .then((doc: string) => { + console.log("Signed document:", doc); + }) + .catch((e) => { + console.error("Error", e); + }) \ No newline at end of file diff --git a/xadesjs/xadesjs.d.ts b/xadesjs/xadesjs.d.ts index 4eb7b6a1c5..9f89cab9f1 100644 --- a/xadesjs/xadesjs.d.ts +++ b/xadesjs/xadesjs.d.ts @@ -1,5 +1,15 @@ +// Type definitions for graphene-pk11 v2.0.0 +// Project: https://github.com/PeculiarVentures/graphene +// Definitions by: Stepan Miroshin +// Definitions: https://github.com/borisyankov/DefinitelyTyped + /// +/** + * A pure Javascript implementation of XMLDSIG and XAdES based on Web Crypto https://xadesjs.com + * v1.0.0 + */ + declare namespace xadesjs { const APPLICATION_XML: string; From 7be1ff7f9e8a36bb368d580e018d4dafe47d0fa0 Mon Sep 17 00:00:00 2001 From: microshine Date: Mon, 9 May 2016 12:29:26 +0300 Subject: [PATCH 0004/1255] Fix def errors --- xadesjs/xadesjs.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xadesjs/xadesjs.d.ts b/xadesjs/xadesjs.d.ts index 9f89cab9f1..fc7d1b4bd6 100644 --- a/xadesjs/xadesjs.d.ts +++ b/xadesjs/xadesjs.d.ts @@ -1,5 +1,5 @@ -// Type definitions for graphene-pk11 v2.0.0 -// Project: https://github.com/PeculiarVentures/graphene +// Type definitions for xadesjs v1.0.0 +// Project: https://github.com/PeculiarVentures/xadesjs // Definitions by: Stepan Miroshin // Definitions: https://github.com/borisyankov/DefinitelyTyped From 420c0d7ab551c4a938a32fabb11636d569c8a3d9 Mon Sep 17 00:00:00 2001 From: microshine Date: Mon, 9 May 2016 14:51:31 +0300 Subject: [PATCH 0005/1255] Change Promise to PromiseType --- xadesjs/promise.d.ts | 14 ----------- xadesjs/xadesjs.d.ts | 58 ++++++++++++++++++++++---------------------- 2 files changed, 29 insertions(+), 43 deletions(-) delete mode 100644 xadesjs/promise.d.ts diff --git a/xadesjs/promise.d.ts b/xadesjs/promise.d.ts deleted file mode 100644 index 96b926633b..0000000000 --- a/xadesjs/promise.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -interface PromiseFunc { - (resolve: (...args: any[]) => void, reject: (...args: any[]) => void): void; -} - -declare class Promise { - constructor(func: PromiseFunc); - - then(resolve: (...args: any[]) => any): Promise; - then(resolve: (...args: any[]) => any, reject: (...args: any[]) => any): Promise; - catch(reject: (...args: any[]) => any): void; - - static resolve(...args: any[]): Promise; - static reject(...args: any[]): Promise; -} \ No newline at end of file diff --git a/xadesjs/xadesjs.d.ts b/xadesjs/xadesjs.d.ts index fc7d1b4bd6..cad137db05 100644 --- a/xadesjs/xadesjs.d.ts +++ b/xadesjs/xadesjs.d.ts @@ -3,8 +3,6 @@ // Definitions by: Stepan Miroshin // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// - /** * A pure Javascript implementation of XMLDSIG and XAdES based on Web Crypto https://xadesjs.com * v1.0.0 @@ -12,6 +10,8 @@ declare namespace xadesjs { + type PromiseType = any; + const APPLICATION_XML: string; class XmlError extends Error { @@ -149,7 +149,7 @@ declare namespace xadesjs { getAlgorithmName(): string; } interface IHashAlgorithm extends IAlgorithm { - getHash(xml: string): Promise; + getHash(xml: string): PromiseType; } interface IHashAlgorithmConstructable { new (): IHashAlgorithm; @@ -160,11 +160,11 @@ declare namespace xadesjs { getAlgorithmName(): string; } abstract class HashAlgorithm extends XmlAlgorithm implements IHashAlgorithm { - getHash(xml: string): Promise; + getHash(xml: string): PromiseType; } interface ISignatureAlgorithm extends IAlgorithm { - getSignature(signedInfo: string, signingKey: CryptoKey, algorithm: Algorithm): Promise; - verifySignature(signedInfo: string, key: CryptoKey, signatureValue: string, algorithm?: Algorithm): Promise; + getSignature(signedInfo: string, signingKey: CryptoKey, algorithm: Algorithm): PromiseType; + verifySignature(signedInfo: string, key: CryptoKey, signatureValue: string, algorithm?: Algorithm): PromiseType; } interface ISignatureAlgorithmConstructable { new (): ISignatureAlgorithm; @@ -173,11 +173,11 @@ declare namespace xadesjs { /** * Sign the given string using the given key */ - getSignature(signedInfo: string, signingKey: CryptoKey, algorithm: Algorithm): Promise; + getSignature(signedInfo: string, signingKey: CryptoKey, algorithm: Algorithm): PromiseType; /** * Verify the given signature of the given string using key */ - verifySignature(signedInfo: string, key: CryptoKey, signatureValue: string, algorithm?: Algorithm): Promise; + verifySignature(signedInfo: string, key: CryptoKey, signatureValue: string, algorithm?: Algorithm): PromiseType; } const SHA1: string; @@ -368,9 +368,9 @@ declare namespace xadesjs { /** * Returns public key from X509Certificate * @param {Algorithm} algorithm - * @returns Promise + * @returns PromiseType */ - exportKey(algorithm: Algorithm): Promise; + exportKey(algorithm: Algorithm): PromiseType; } enum X509IncludeOption { @@ -395,13 +395,13 @@ declare namespace xadesjs { * Gets public key of the X509Data */ Key: CryptoKey; - importKey(key: CryptoKey): Promise; + importKey(key: CryptoKey): PromiseType; /** * Exports key from X509Data object * @param {Algorithm} alg - * @returns Promise + * @returns PromiseType */ - exportKey(alg: Algorithm): Promise; + exportKey(alg: Algorithm): PromiseType; /** * Gets a list of the X.509v3 certificates contained in the KeyInfoX509Data object. */ @@ -492,15 +492,15 @@ declare namespace xadesjs { /** * Imports key to the RSAKeyValue object * @param {CryptoKey} key - * @returns Promise + * @returns PromiseType */ - importKey(key: CryptoKey): Promise; + importKey(key: CryptoKey): PromiseType; /** * Exports key from the RSAKeyValue object * @param {Algorithm} alg - * @returns Promise + * @returns PromiseType */ - exportKey(alg: Algorithm): Promise; + exportKey(alg: Algorithm): PromiseType; /** * Returns the XML representation of the RSA key clause. * @returns Element @@ -552,15 +552,15 @@ declare namespace xadesjs { /** * Imports key to the ECKeyValue object * @param {CryptoKey} key - * @returns Promise + * @returns PromiseType */ - importKey(key: CryptoKey): Promise; + importKey(key: CryptoKey): PromiseType; /** * Exports key from the ECKeyValue object * @param {Algorithm} alg - * @returns Promise + * @returns PromiseType */ - exportKey(alg: Algorithm): Promise; + exportKey(alg: Algorithm): PromiseType; /** * Returns the XML representation of the ECDSA key clause. * @returns Element @@ -804,8 +804,8 @@ declare namespace xadesjs { } interface KeyInfoClause extends IXmlSerializable { Key: CryptoKey; - importKey(key: CryptoKey): Promise; - exportKey(alg: Algorithm): Promise; + importKey(key: CryptoKey): PromiseType; + exportKey(alg: Algorithm): PromiseType; } /** @@ -1060,16 +1060,16 @@ declare namespace xadesjs { /** * Computes an XML digital signature using the specified algorithm. * @param {Algorithm} algorithm Specified WebCrypto Algoriithm - * @returns Promise + * @returns PromiseType */ - ComputeSignature(algorithm: Algorithm): Promise; + ComputeSignature(algorithm: Algorithm): PromiseType; /** * Determines whether the SignedXml.Signature property verifies using the public key in the signature. - * @returns Promise + * @returns PromiseType */ - CheckSignature(): Promise; - CheckSignature(key: CryptoKey): Promise; - CheckSignature(cert: X509Certificate): Promise; + CheckSignature(): PromiseType; + CheckSignature(key: CryptoKey): PromiseType; + CheckSignature(cert: X509Certificate): PromiseType; /** * Loads a SignedXml state from an XML element. * @param {Element} value The XML element to load the SignedXml state from. From 2847bd521629b85a94dca5d74a8c74ea49952a3f Mon Sep 17 00:00:00 2001 From: microshine Date: Mon, 9 May 2016 15:29:18 +0300 Subject: [PATCH 0006/1255] Fix test error --- xadesjs/xadesjs-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/xadesjs/xadesjs-tests.ts b/xadesjs/xadesjs-tests.ts index e83cb0cf6a..e36f903945 100644 --- a/xadesjs/xadesjs-tests.ts +++ b/xadesjs/xadesjs-tests.ts @@ -42,6 +42,6 @@ xadesjs.Application.crypto.subtle.generateKey( .then((doc: string) => { console.log("Signed document:", doc); }) - .catch((e) => { + .catch((e: any) => { console.error("Error", e); - }) \ No newline at end of file + }); \ No newline at end of file From 4e00b9e8dc11eef0b7ef4bd2f1bbfb91f3e2cc2f Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 12 May 2016 22:24:49 +0100 Subject: [PATCH 0007/1255] Update to version 2.20.4 Update methods from node-validator (https://github.com/chriso/validator.js) and update express-validator methods to adhere to the latest api. --- express-validator/express-validator-tests.ts | 14 +- express-validator/express-validator.d.ts | 136 ++++++++++++------- 2 files changed, 99 insertions(+), 51 deletions(-) diff --git a/express-validator/express-validator-tests.ts b/express-validator/express-validator-tests.ts index 74bd277e46..ebd61d6cfc 100644 --- a/express-validator/express-validator-tests.ts +++ b/express-validator/express-validator-tests.ts @@ -15,19 +15,23 @@ app.post('/:urlparam', function(req: express.Request, res: express.Response) { // Similarly checkParams only checks in req.params (URL params) and // checkQuery only checks req.query (GET params). req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt(); - req.checkParams('urlparam', 'Invalid urlparam').isAlpha(); + req.checkParams('urlparam', 'Invalid urlparam').isAlpha().matches(/test?/i).matches('test?', 'i'); req.checkQuery('getparam', 'Invalid getparam').isInt(); - req.checkHeader('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); - req.checkFiles('testFiles', 'Invalid testFiles').isUrl(); - + req.checkHeaders('testHeader', 'Invalid testHeader').isLowercase().isUppercase(); + req.checkFiles('testFiles', 'Invalid testFiles').isURL(); // OR assert can be used to check on all 3 types of params. // req.assert('postparam', 'Invalid postparam').notEmpty().isInt(); // req.assert('urlparam', 'Invalid urlparam').isAlpha(); // req.assert('getparam', 'Invalid getparam').isInt(); - req.sanitize('postparam').toBoolean(); req.filter('postparam').toBoolean(); + req.sanitize('postparam').blacklist('t').blacklist(['']).whitelist('hello').whitelist(['h', 'e', 'l']); + req.sanitizeBody('postvar').trim().stripLow().escape(); + req.sanitizeQuery('queryvar').toDate(); + req.sanitizeParams('urlparam').toFloat().toInt().toInt(10); + req.sanitizeHeaders('header').normalizeEmail(); + var errors = req.validationErrors(); var mappedErrors = req.validationErrors(true); diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 52792a391f..cb15aebf8f 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -1,9 +1,10 @@ -// Type definitions for express-validator 2.9.0 +// Type definitions for express-validator 2.20.4 // Project: https://github.com/ctavan/express-validator -// Definitions by: Nathan Ridley , Jonathan Häberle +// Definitions by: Nathan Ridley , Jonathan Häberle , Peter Harris // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// // Add RequestValidation Interface on to Express's Request Interface. declare namespace Express { @@ -31,25 +32,33 @@ declare namespace ExpressValidator { param: string; } - interface ValidatorFunction { (item: string, message: string): Validator; } + interface ValidatorFunction { (item: string | {}, message?: string): Validator; } + interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; }; interface SanitizerFunction { (item: string): Sanitizer; } interface Dictionary { [key: string]: T; } export interface RequestValidation { - assert: ValidatorFunction; - check: ValidatorFunction; + assert: ValidatorExtraFunction; + validate: ValidatorExtraFunction; + check: ValidatorExtraFunction; checkBody: ValidatorFunction; checkFiles: ValidatorFunction; - checkHeader: ValidatorFunction; + checkHeaders: ValidatorFunction; checkParams: ValidatorFunction; checkQuery: ValidatorFunction; - validate: ValidatorFunction; - + filter: SanitizerFunction; sanitize: SanitizerFunction; - + sanitizeBody: SanitizerFunction; + sanitizeQuery: SanitizerFunction; + sanitizeParams: SanitizerFunction; + sanitizeHeaders: SanitizerFunction; + onValidationError(errback: (msg: string) => void): void; - validationErrors(mapped?: boolean): Dictionary | any[]; + validationErrors(mapped?: boolean): Dictionary | MappedError[]; + validationErrors(mapped?: boolean): Dictionary | T[]; + asyncValidationErrors(mapped?: boolean): Promise>; + asyncValidationErrors(mapped?: boolean): Promise>; } export interface Validator { @@ -61,12 +70,13 @@ declare namespace ExpressValidator { * Alias for notRegex() */ not(): Validator; - isEmail(): Validator; + isEmail(options?:{}): Validator; /** * Accepts http, https, ftp */ - isUrl(): Validator; - + isURL(): Validator; + isFQDN(options?: MinMaxOptions): Validator; + /** * Combines isIPv4 and isIPv6 */ @@ -74,8 +84,21 @@ declare namespace ExpressValidator { isIPv4(): Validator; isIPv6(): Validator; isMACAddress(): Validator; - isAlpha(): Validator; - isAlphanumeric(): Validator; + isISBN(version?: number): Validator; + isISIN(): Validator; + isISO8601(): Validator; + isMobilePhone(locale: string): Validator; + isMongoId(): Validator; + isMultibyte(): Validator; + isAlpha(locale?: string): Validator; + isAlphanumeric(locale?: string): Validator; + isAscii(): Validator; + isBase64(): Validator; + isBoolean(): Validator; + isByteLength(options: MinMaxOptions): Validator; + isCurrency(options: {}): Validator; + isDataURI(): Validator; + isDivisibleBy(num: number): Validator; isNumeric(): Validator; isHexadecimal(): Validator; /** @@ -85,7 +108,7 @@ declare namespace ExpressValidator { /** * isNumeric accepts zero padded numbers, e.g. '001', isInt doesn't */ - isInt(): Validator; + isInt(options?: MinMaxOptions): Validator; isLowercase(): Validator; isUppercase(): Validator; isDecimal(): Validator; @@ -93,10 +116,13 @@ declare namespace ExpressValidator { * Alias for isDecimal */ isFloat(): Validator; + isFullWidth(): Validator; + isHalfWidth(): Validator; + isVariableWidth(): Validator; /** * Check if length is 0 */ - notNull(): Validator; + //notNull(): Validator; // I don't see this in the documentation or code anywhere. isNull(): Validator; /** * Not just whitespace (input.trim().length !== 0) @@ -104,12 +130,14 @@ declare namespace ExpressValidator { notEmpty(): Validator; equals(equals:any): Validator; contains(str:string): Validator; - notContains(str:string): Validator; + //notContains(str:string): Validator; // I don't see this in the documentation or code anywhere. + matches(pattern:string, modifiers?:string): Validator; + matches(pattern: RegExp): Validator; /** * Usage: regex(/[a-z]/i) or regex('[a-z]','i') */ - regex(pattern:string, modifiers:string): Validator; - notRegex(pattern:string, modifiers:string): Validator; + //regex(pattern:string, modifiers:string): Validator; // I don't see this in the documentation or code anywhere. + //notRegex(pattern:string, modifiers:string): Validator; // I don't see this in the documentation or code anywhere. /** * max is optional */ @@ -117,7 +145,7 @@ declare namespace ExpressValidator { /** * Version can be 3, 4 or 5 or empty, see http://en.wikipedia.org/wiki/Universally_unique_identifier */ - isUUID(version:number): Validator; + isUUID(version?:number): Validator; /** * Alias for isUUID(3) */ @@ -137,17 +165,20 @@ declare namespace ExpressValidator { /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isAfter(date:Date): Validator; + isAfter(date?:Date): Validator; /** * Argument is optional and defaults to today. Comparison is non-inclusive */ - isBefore(date:Date): Validator; + isBefore(date?:Date): Validator; isIn(options:string): Validator; isIn(options:string[]): Validator; notIn(options:string): Validator; notIn(options:string[]): Validator; max(val:string): Validator; min(val:string): Validator; + isJSON(): Validator; + isLength(options: MinMaxOptions): Validator; + isWhitelisted(chars: string); /** * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats */ @@ -155,7 +186,10 @@ declare namespace ExpressValidator { /** * Check an input only when the input exists */ - optional(): Validator; + isSurrogatePar(): Validator; + + optional(options?: { checkFalsy?: boolean }): Validator; + withMessage(message: string): Validator; } interface Sanitizer { @@ -165,40 +199,50 @@ declare namespace ExpressValidator { trim(...chars:string[]): Sanitizer; ltrim(...chars:string[]): Sanitizer; rtrim(...chars:string[]): Sanitizer; - ifNull(replace:any): Sanitizer; + stripLow(keep_new_lines?: boolean): Sanitizer; + //ifNull(replace:any): Sanitizer; // I don't see this in the documentation or code anywhere. toFloat(): Sanitizer; - toInt(): Sanitizer; + toInt(radix?: number): Sanitizer; /** - * True unless str = '0', 'false', or str.length == 0 - */ - toBoolean(): Sanitizer; - /** - * False unless str = '1' or 'true' - */ - toBooleanStrict(): Sanitizer; - /** - * Decode HTML entities + * True unless str = '0', 'false', or str.length == 0. In strict mode only '1' and 'true' return true. */ + toBoolean(strict?: boolean): Sanitizer; /** - * Convert the input string to a date, or null if the input is not a date. - */ - toDate(): Sanitizer; - - entityDecode(): Sanitizer; - entityEncode(): Sanitizer; + * Convert the input string to a date, or null if the input is not a date. + */ + toDate(): Sanitizer; + /** * Escape &, <, >, and " */ escape(): Sanitizer; + /** - * Remove common XSS attack vectors from user-supplied HTML + * Replaces HTML encoded entities with <, >, &, ', " and /. */ - xss(): Sanitizer; + unescape(): Sanitizer; + + blacklist(chars: string): Sanitizer; + blacklist(chars: string[]): Sanitizer; + whitelist(chars: string): Sanitizer; + whitelist(chars: string[]): Sanitizer; + + normalizeEmail(options?: { lowercase?: boolean; remove_dots?: boolean; remove_extensions?: boolean }): Sanitizer; + /** - * Remove common XSS attack vectors from images + * !!! XSS sanitization was removed from the library (see: https://github.com/chriso/validator.js#xss-sanitization) */ - xss(fromImages:boolean): Sanitizer; } - + + interface MappedError { + param: string; + msg: string; + value: string; + } + + interface MinMaxOptions { + min?: number; + max?: number; + } } From 396e37eb8b17cace44ba2bce0f2aa59a88d17fd0 Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 12 May 2016 22:38:26 +0100 Subject: [PATCH 0008/1255] Remove ambient semicolon --- express-validator/express-validator.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index cb15aebf8f..583ffbf6e8 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -33,7 +33,7 @@ declare namespace ExpressValidator { } interface ValidatorFunction { (item: string | {}, message?: string): Validator; } - interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; }; + interface ValidatorExtraFunction extends ValidatorFunction { (matchIndex: number, message?: string): Validator; } interface SanitizerFunction { (item: string): Sanitizer; } interface Dictionary { [key: string]: T; } From 10bc473fe57df9c5acb2926faf785ece99beb37f Mon Sep 17 00:00:00 2001 From: CodeAnimal Date: Thu, 12 May 2016 22:44:39 +0100 Subject: [PATCH 0009/1255] Add return type to isWhitelisted method. --- express-validator/express-validator.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/express-validator/express-validator.d.ts b/express-validator/express-validator.d.ts index 583ffbf6e8..71797efce2 100644 --- a/express-validator/express-validator.d.ts +++ b/express-validator/express-validator.d.ts @@ -178,7 +178,7 @@ declare namespace ExpressValidator { min(val:string): Validator; isJSON(): Validator; isLength(options: MinMaxOptions): Validator; - isWhitelisted(chars: string); + isWhitelisted(chars: string): Validator; /** * Will work against Visa, MasterCard, American Express, Discover, Diners Club, and JCB card numbering formats */ From c59c139444477fda75df8541cd8c7bcb5c93ec5b Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:16:47 +0200 Subject: [PATCH 0010/1255] Implemented Amplitude SDK type definition. --- amplitude/amplitude-tests.ts | 85 ++++++++++++++++++++++++++++++++++++ amplitude/amplitude.d.ts | 58 ++++++++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 amplitude/amplitude-tests.ts create mode 100644 amplitude/amplitude.d.ts diff --git a/amplitude/amplitude-tests.ts b/amplitude/amplitude-tests.ts new file mode 100644 index 0000000000..c4ffb9e811 --- /dev/null +++ b/amplitude/amplitude-tests.ts @@ -0,0 +1,85 @@ +/// + +module Amplitude.Tests { + function all() { + amplitude.init('YOUR_API_KEY_HERE', null, { + // optional configuration options + saveEvents: true, + includeUtm: true, + includeReferrer: true, + batchEvents: true, + eventUploadThreshold: 50 + }); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {}); + + amplitude.logEvent('EVENT_IDENTIFIER_HERE'); + amplitude.setUserId('USER_ID_HERE'); + amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE'); + amplitude.setUserId(null); // not string 'null' + amplitude.setVersionName('VERSION_NAME_HERE'); + + amplitude.regenerateDeviceId(); + amplitude.setDeviceId('CUSTOM_DEVICE_ID'); + + amplitude.logEvent('EVENT_IDENTIFIER_HERE', { + 'color': 'blue', + 'age': 20, + 'key': 'value' + }); + amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { }); + + let identify = new amplitude.Identify().set('gender', 'female').set('age', 20); + amplitude.identify(identify); + + identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015'); + amplitude.identify(identify); + + identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015'); + amplitude.identify(identify); + + identify = new amplitude.Identify().unset('gender').unset('age'); + amplitude.identify(identify); + + identify = new amplitude.Identify().add('karma', 1).add('friends', 1); + amplitude.identify(identify); + + identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); + + identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']); + amplitude.identify(identify); + + identify = new amplitude.Identify() + .set('karma', 10) + .add('karma', 1) + .unset('karma'); + amplitude.identify(identify); + + identify = new amplitude.Identify() + .set('colors', ['rose', 'gold']) + .append('ab-tests', 'campaign_a') + .append('existing_list', [4, 5]); + amplitude.identify(identify); + + amplitude.setUserProperties({ + gender: 'female', + age: 20 + }); + + amplitude.clearUserProperties(); + + amplitude.setOptOut(true); + amplitude.setOptOut(false); + + amplitude.setGroup('orgId', '15'); + amplitude.setGroup('sport', ['soccer', 'tennis']); + + // Still to implement: + /* + var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); + amplitude.logRevenueV2(revenue); + + amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' }); + */ + } +} diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts new file mode 100644 index 0000000000..339153634d --- /dev/null +++ b/amplitude/amplitude.d.ts @@ -0,0 +1,58 @@ +declare module amplitude { + interface Config { + batchEvents?: boolean; + cookieExpiration?: number; + cookieName?: string; + deviceId?: string; + domain?: string; + eventUploadPeriodMillis?: number; + eventUploadThreshold?: number; + includeReferrer?: boolean; + includeUtm?: boolean; + language?: string; + optOut?: boolean; + platform?: string; + saveEvents?: boolean; + savedMaxCount?: number; + sessionTimeout?: number; + uploadBatchSize?: number; + } + + export class Identify { + set(key: string, value: any): Identify; + setOnce(key: string, value: any): Identify; + add(key: string, value: number): Identify; + append(key: string, value: any): Identify; + prepend(key: string, value: any): Identify; + + unset(key: string): Identify; + } + + export function init(apiKey: string): void; + export function init(apiKey: string, userId: string): void; + export function init(apiKey: string, userId: string, options: Config): void; + export function init(apiKey: string, userId: string, options: Config, callback: () => void): void; + + export function setVersionName(version: string): void; + export function setUserId(userId: string): void; + + export function setDeviceId(id: string): void; + export function regenerateDeviceId(): void; + + export function identify(identify: Identify): void; + + export function setUserProperties(properties: Object): void; + export function clearUserProperties(): void; + + export function setOptOut(optOut: boolean): void; + + export function setGroup(groupType: string, groupName: string | string[]); + + export function logEvent(event: string): void; + export function logEvent(event: string, data: Object): void; + export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void; + + export var options: Config; +} + +//declare var amplitude: AmplitudeStatic; From 9a055b462ad6465f999facbd3b7013e564bebfc2 Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:37:31 +0200 Subject: [PATCH 0011/1255] Added required header comments to amplitude definition files. --- amplitude/amplitude-tests.ts | 2 ++ amplitude/amplitude.d.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/amplitude/amplitude-tests.ts b/amplitude/amplitude-tests.ts index c4ffb9e811..d60cf4bc7b 100644 --- a/amplitude/amplitude-tests.ts +++ b/amplitude/amplitude-tests.ts @@ -1,3 +1,5 @@ +// Tests for Amplitude SDK TypeScript definitions + /// module Amplitude.Tests { diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index 339153634d..3955ae128a 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -1,3 +1,5 @@ +// Type definitions for Amplitude SDK 2.12.1 + declare module amplitude { interface Config { batchEvents?: boolean; From ed54ec0de6b1ef627fcfd9382ae1e91c9aa97180 Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:38:02 +0200 Subject: [PATCH 0012/1255] amplitude.setGroup() return value is now void instead instead of implicit any. --- amplitude/amplitude.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index 3955ae128a..d3ad99c890 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -48,7 +48,7 @@ declare module amplitude { export function setOptOut(optOut: boolean): void; - export function setGroup(groupType: string, groupName: string | string[]); + export function setGroup(groupType: string, groupName: string | string[]): void; export function logEvent(event: string): void; export function logEvent(event: string, data: Object): void; From 6b5953e8d06043c69d3be715cef78ba278827503 Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:40:29 +0200 Subject: [PATCH 0013/1255] Added required 'Project' comment to amplitude definition file header. --- amplitude/amplitude.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index d3ad99c890..b8b208bcdd 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -1,4 +1,5 @@ // Type definitions for Amplitude SDK 2.12.1 +// Project: https://github.com/amplitude/Amplitude-Javascript declare module amplitude { interface Config { From 233b6e31fe562202a1c08a3eb23635350ab672fe Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:43:33 +0200 Subject: [PATCH 0014/1255] Added required 'Definitions by' comment to amplitude definition file header. --- amplitude/amplitude.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index b8b208bcdd..0e2c392e64 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -1,5 +1,6 @@ // Type definitions for Amplitude SDK 2.12.1 // Project: https://github.com/amplitude/Amplitude-Javascript +// Definitions by: Arvydas Sidorenko declare module amplitude { interface Config { From 759ae4713b69d6b96825c839472c0bf6c79662aa Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Sun, 22 May 2016 13:48:53 +0200 Subject: [PATCH 0015/1255] Added required 'Definitions' comment to amplitude definition file header. --- amplitude/amplitude.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/amplitude/amplitude.d.ts b/amplitude/amplitude.d.ts index 0e2c392e64..9a5df3d179 100644 --- a/amplitude/amplitude.d.ts +++ b/amplitude/amplitude.d.ts @@ -1,6 +1,7 @@ // Type definitions for Amplitude SDK 2.12.1 // Project: https://github.com/amplitude/Amplitude-Javascript // Definitions by: Arvydas Sidorenko +// Definitions: https://github.com/Asido/DefinitelyTyped declare module amplitude { interface Config { From beb9814807ffec927b1ef4eb74c735296ab33a63 Mon Sep 17 00:00:00 2001 From: Arvydas Sidorenko Date: Mon, 30 May 2016 10:11:37 +0200 Subject: [PATCH 0016/1255] Renamed amplitude to amplitude-js. --- .../amplitude-tests.ts => amplitude-js/amplitude-js-tests.ts | 4 ++-- amplitude/amplitude.d.ts => amplitude-js/amplitude-js.d.ts | 0 2 files changed, 2 insertions(+), 2 deletions(-) rename amplitude/amplitude-tests.ts => amplitude-js/amplitude-js-tests.ts (97%) rename amplitude/amplitude.d.ts => amplitude-js/amplitude-js.d.ts (100%) diff --git a/amplitude/amplitude-tests.ts b/amplitude-js/amplitude-js-tests.ts similarity index 97% rename from amplitude/amplitude-tests.ts rename to amplitude-js/amplitude-js-tests.ts index d60cf4bc7b..66285f10dd 100644 --- a/amplitude/amplitude-tests.ts +++ b/amplitude-js/amplitude-js-tests.ts @@ -1,6 +1,6 @@ // Tests for Amplitude SDK TypeScript definitions -/// +/// module Amplitude.Tests { function all() { @@ -76,7 +76,7 @@ module Amplitude.Tests { amplitude.setGroup('orgId', '15'); amplitude.setGroup('sport', ['soccer', 'tennis']); - // Still to implement: + // TODO: Implement those. /* var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); amplitude.logRevenueV2(revenue); diff --git a/amplitude/amplitude.d.ts b/amplitude-js/amplitude-js.d.ts similarity index 100% rename from amplitude/amplitude.d.ts rename to amplitude-js/amplitude-js.d.ts From 7cdeddfc0dc5188cafde9f2ff2e97f574028030e Mon Sep 17 00:00:00 2001 From: anuti Date: Mon, 13 Jun 2016 19:26:06 +0200 Subject: [PATCH 0017/1255] Create chart2.d.ts Chart JS library has been updated to version 2.0 although no one has yet created the proper definitions files. For this reason I propose my file while being aware that still needs lots of work. In addition to the usual bug there are shortcomings in the definition of many functions, as the official guide does not specify the parameter's types. in the hope that this can help someone. --- chartjs/chart2.d.ts | 392 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 392 insertions(+) create mode 100644 chartjs/chart2.d.ts diff --git a/chartjs/chart2.d.ts b/chartjs/chart2.d.ts new file mode 100644 index 0000000000..7ae02a6ebf --- /dev/null +++ b/chartjs/chart2.d.ts @@ -0,0 +1,392 @@ +/* TYPES */ +declare enum ChartType { + line, bar, radar, doughnut, polarArea, bubble +} +declare enum TimeUnit { + millisecond, second, minute, + hour, day, week, + month, quarter, year +} +interface ChartLegendItem { + text?: string; + fillStyle?: string; + hidden?: boolean; + lineCap?: string; + lineDash?: number[]; + lineDashOffset?: number; + lineJoin?: string; + lineWidth?: number; + strokeStyle?: string; +} +interface ChartTooltipItem { + xLabel?: string; + yLabel?: string; + datasetIndex?: number; + index?: number; +} +interface ChartTooltipCallback { + beforeTitle?: (item?: ChartTooltipItem[], data?: any) => void; + title?: (item?: ChartTooltipItem[], data?: any) => void; + afterTitle?: (item?: ChartTooltipItem[], data?: any) => void; + beforeBody?: (item?: ChartTooltipItem[], data?: any) => void; + beforeLabel?: (tooltipItem?: ChartTooltipItem, data?: any) => void; + label?: (tooltipItem?: ChartTooltipItem, data?: any) => void; + afterLabel?: (tooltipItem?: ChartTooltipItem, data?: any) => void; + afterBody?: (item?: ChartTooltipItem[], data?: any) => void; + beforeFooter?: (item?: ChartTooltipItem[], data?: any) => void; + footer?: (item?: ChartTooltipItem[], data?: any) => void; + afterfooter?: (item?: ChartTooltipItem[], data?: any) => void; +} +interface ChartAnimationParameter { + chartInstance?: any; + animationObject?: any; +} +interface ChartPoint { + x?: number; + y?: number; +} + +/* END */ + +/* Configuration */ +interface ChartConfiguration { + type?: string; + data?: ChartData; + options?: ChartOptions; +} + +/* END */ + +/* DATA */ +interface ChartData { + +} + +interface LinearChartData extends ChartData { + labels?: string[]; + datasets?: ChartDataSets[]; +} + +/* END */ + +/* Options */ +interface ChartOptions { + responsive?: boolean; + responsiveAnimationDuration?: number; + maintainAspectRatio?: boolean; + events?: string[]; + onClick?: (any?: any) => any; + title?: ChartTitleOptions; + legend?: ChartLegendOptions; + tooltip?: ChartTooltipOptions; + hover?: ChartHoverOptions; + animation?: ChartAnimationOptions; + elements?: ChartElementsOptions; + scales?: ChartScales; +} + +interface ChartFontOptions { + defaultFontColor?: string; + defaultFontFamily?: string; + defaultFontSize?: number; + defaultFontStyle?: string; +} + +interface ChartTitleOptions { + display?: boolean; + position?: string; + fullWdith?: boolean; + fontSize?: number; + fontFamily?: string; + fontColor?: string; + fontStyle?: string; + padding?: number; + text?: string; +} + +interface ChartLegendOptions { + display?: boolean; + position?: string; + fullWidth?: boolean; + onClick?: (event, legendItem) => void; + labels?: ChartLegendLabelOptions; +} + +interface ChartLegendLabelOptions { + boxWidth?: number; + fontSize?: number; + fontStyle?: number; + fontColor?: string; + fontFamily?: string; + padding?: number; + generateLabels?: (chart) => any; +} + +interface ChartTooltipOptions { + enabled?: boolean; + custom?: (a) => void; + mode?: string; + backgroundColor?: string; + titleFontFamily?: string; + titleFontSize?: number; + titleFontStyle?: string; + titleFontColor?: string; + titleSpacing?: number; + titleMarginBottom?: number; + bodyFontFamily?: string; + bodyFontSize?: number; + bodyFontStyle?: string; + bodyFontColor?: string; + bodySpacing?: number; + footerFontFamily?: string; + footerFontSize?: number; + footerFontStyle?: string; + footerFontColor?: string; + footerSpacing?: number; + footerMarginTop?: number; + xPadding?: number; + yPadding?: number; + caretSize?: number; + cornerRadius?: number; + multiKeyBackground?: string; + callbacks?: ChartTooltipCallback; +} + +interface ChartHoverOptions { + mode?: string; + animationDuration?: number; + onHover?: (active) => void; +} + +interface ChartAnimationObject { + currentStep?: number; + numSteps?: number; + easing?: string; + render?: (arg) => void; + onAnimationProgress?: (arg) => void; + onAnimationComplete?: (arg) => void; +} + +interface ChartAnimationOptions { + duration?: number; + easing?: string; + onProgress?: (chart) => void; + onComplete?: (chart) => void; +} + +interface ChartElementsOptions { + point?: ChartPointOptions; + line?: ChartLineOptions; + arg?: ChartArcOtpions; + rectangle?: ChartRectangleOptions; +} + +interface ChartArcOtpions { + backgroundColor?: string; + borderColor?: string; + borderWidth?: number; +} + +interface ChartLineOptions { + tension?: number; + backgroundColor?: string; + borderWidth?: number; + borderColor?: string; + borderCapStyle?: string; + borderDash?: any[]; + borderDashOffset?: number; + borderJoinStyle?: string; +} + +interface ChartPointOptions { + radius?: number; + pointStyle?: string; + backgroundColor?: string; + borderWidth?: number; + borderColor?: string; + hitRadius?: number; + hoverRadius?: number; + hoverBorderWidth?: number; +} + +interface ChartRectangleOptions { + backgroundColor?: string; + borderWidth?: number; + borderColor?: string; + borderSkipped?: string; +} +interface GridLineOptions { + display?: boolean; + color?: string; + lineWidth?: number; + drawBorder?: boolean; + drawOnChartArea?: boolean; + drawticks?: boolean; + tickMarkLength?: number; + zeroLineWidth?: number; + zeroLineColor?: string; + offsetGridLines?: boolean; +} + +interface ScaleTitleOptions { + display?: boolean; + labelString?: string; + fontColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; +} + +interface TickOptions { + autoSkip?: boolean; + callback?: (value, index, values) => string; + display?: boolean; + fontColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; + labelOffset?: number; + maxRotation?: number; + minRotation?: number; + mirror?: boolean; + padding?: number; + reverse?: boolean; + min?: any; + max?: any; +} +interface AngleLineOptions { + display?: boolean; + color?: string; + lineWidth?: number; +} + +interface PointLabelOptions { + callback?: (arg) => any; + fontColor?: string; + fontFamily?: string; + fontSize?: number; + fontStyle?: string; +} + +interface TickOptions { + backdropColor?: string; + backdropPaddingX?: number; + backdropPaddingY?: number; + maxTicksLimit?: number; + showLabelBackdrop?: boolean; +} +interface LinearTickOptions extends TickOptions { + beginAtZero?: boolean; + min?: number; + max?: number; + maxTicksLimit?: number; + stepSize?: number; + suggestedMin?: number; + suggestedMax?: number; +} + +interface LogarithmicTickOptions extends TickOptions { + min?: number; + max?: number; +} +/* END */ + +/* DATASETS */ +interface ChartDataSets { + backgroundColor?: string[]; + borderWidth?: number; + borderColor?: string[]; + borderCapStyle?: string; + borderDash?: number[]; + borderDashOffset?: number; + borderJoinStyle?: string; + data?: number[] | ChartPoint[]; + fill?: boolean; + label?: string; + lineTension?: number; + pointBorderColor?: string | string[]; + pointBackgroundColor?: string | string[]; + pointBorderWidth?: number | number[]; + pointRadius?: number | number[]; + pointHoverRadius?: number | number[]; + pointHitRadius?: number | number[]; + pointHoverBackgroundColor?: string | string[]; + pointHoverBorderColor?: string | string[]; + pointHoverBorderWidth?: number | number[]; + pointStyle?: string | string[] | HTMLImageElement | HTMLImageElement[]; + xAxisID?: string; + yAxisID?: string; +} +/* END */ + +/* SCALES */ +interface ChartScales { + type?: string; + display?: boolean; + position?: string; + beforeUpdate?: (scale?: any) => void; + beforeSetDimension?: (scale?: any) => void; + beforeDataLimits?: (scale?: any) => void; + beforeBuildTicks?: (scale?: any) => void; + beforeTickToLabelConversion?: (scale?: any) => void; + beforeCalculateTickRotation?: (scale?: any) => void; + beforeFit?: (scale?: any) => void; + afterUpdate?: (scale?: any) => void; + afterSetDimension?: (scale?: any) => void; + afterDataLimits?: (scale?: any) => void; + afterBuildTicks?: (scale?: any) => void; + afterTickToLabelConversion?: (scale?: any) => void; + afterCalculateTickRotation?: (scale?: any) => void; + afterFit?: (scale?: any) => void; + gridLines?: GridLineOptions; + scaleLabel?: ScaleTitleOptions; + ticks?: TickOptions; +} + +interface LinearScale extends ChartScales { + ticks?: LinearTickOptions; +} + + +interface LogarithmicScale extends ChartScales { + ticks?: LogarithmicTickOptions; +} + +interface TimeScale extends ChartScales { + displayFormats?: string; + isoWeekday?: boolean; + max?: string; + min?: string; + parser?: string | ((arg) => moment.MomentDateObject); + round?: string; + tooltipFormat?: string; + unit?: TimeUnit; + unitStepSize?: number; +} + +interface RadialLinearScale { + lineArc?: boolean; + angleLines?: AngleLineOptions; + pointLabels?: PointLabelOptions; + ticks?: TickOptions; +} +/* END */ + +declare var Chart: { + new (context: CanvasRenderingContext2D, options: ChartConfiguration): {}; + destroy: () => {}; + update: (duration, lazy) => {}; + render: (duration, lazy) => {}; + stop: () => {}; + resize: () => {}; + clear: () => {}; + toBase64: () => string; + generateLegend: () => {}; + getElementAtEvent: (e) => {}; + getElementsAtEvent: (e) => {}[]; + getDatasetAtEvent: (e) => {}[]; + + defaults: { + global: ChartOptions; + } +}; From 160f9f51a0662505e1671e87492097db9aedd1c3 Mon Sep 17 00:00:00 2001 From: anuti Date: Mon, 13 Jun 2016 20:36:25 +0200 Subject: [PATCH 0018/1255] Update chart2.d.ts --- chartjs/chart2.d.ts | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/chartjs/chart2.d.ts b/chartjs/chart2.d.ts index 7ae02a6ebf..f80e8d9897 100644 --- a/chartjs/chart2.d.ts +++ b/chartjs/chart2.d.ts @@ -108,7 +108,7 @@ interface ChartLegendOptions { display?: boolean; position?: string; fullWidth?: boolean; - onClick?: (event, legendItem) => void; + onClick?: (event: any, legendItem: any) => void; labels?: ChartLegendLabelOptions; } @@ -119,12 +119,12 @@ interface ChartLegendLabelOptions { fontColor?: string; fontFamily?: string; padding?: number; - generateLabels?: (chart) => any; + generateLabels?: (chart: any) => any; } interface ChartTooltipOptions { enabled?: boolean; - custom?: (a) => void; + custom?: (a: any) => void; mode?: string; backgroundColor?: string; titleFontFamily?: string; @@ -155,23 +155,23 @@ interface ChartTooltipOptions { interface ChartHoverOptions { mode?: string; animationDuration?: number; - onHover?: (active) => void; + onHover?: (active: any) => void; } interface ChartAnimationObject { currentStep?: number; numSteps?: number; easing?: string; - render?: (arg) => void; - onAnimationProgress?: (arg) => void; - onAnimationComplete?: (arg) => void; + render?: (arg: any) => void; + onAnimationProgress?: (arg: any) => void; + onAnimationComplete?: (arg: any) => void; } interface ChartAnimationOptions { duration?: number; easing?: string; - onProgress?: (chart) => void; - onComplete?: (chart) => void; + onProgress?: (chart: any) => void; + onComplete?: (chart: any) => void; } interface ChartElementsOptions { @@ -239,7 +239,7 @@ interface ScaleTitleOptions { interface TickOptions { autoSkip?: boolean; - callback?: (value, index, values) => string; + callback?: (value: any, index: any, values: any) => string; display?: boolean; fontColor?: string; fontFamily?: string; @@ -261,7 +261,7 @@ interface AngleLineOptions { } interface PointLabelOptions { - callback?: (arg) => any; + callback?: (arg: any) => any; fontColor?: string; fontFamily?: string; fontSize?: number; @@ -357,7 +357,7 @@ interface TimeScale extends ChartScales { isoWeekday?: boolean; max?: string; min?: string; - parser?: string | ((arg) => moment.MomentDateObject); + parser?: string | ((arg: any) => moment.MomentDateObject); round?: string; tooltipFormat?: string; unit?: TimeUnit; @@ -375,16 +375,16 @@ interface RadialLinearScale { declare var Chart: { new (context: CanvasRenderingContext2D, options: ChartConfiguration): {}; destroy: () => {}; - update: (duration, lazy) => {}; - render: (duration, lazy) => {}; + update: (duration: any, lazy: any) => {}; + render: (duration: any, lazy: any) => {}; stop: () => {}; resize: () => {}; clear: () => {}; toBase64: () => string; generateLegend: () => {}; - getElementAtEvent: (e) => {}; - getElementsAtEvent: (e) => {}[]; - getDatasetAtEvent: (e) => {}[]; + getElementAtEvent: (e: any) => {}; + getElementsAtEvent: (e: any) => {}[]; + getDatasetAtEvent: (e: any) => {}[]; defaults: { global: ChartOptions; From cfafb5a2f70a744102cdc9b9ce6abaa9adfe4d7a Mon Sep 17 00:00:00 2001 From: anuti Date: Mon, 13 Jun 2016 20:40:02 +0200 Subject: [PATCH 0019/1255] Update chart2.d.ts --- chartjs/chart2.d.ts | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/chartjs/chart2.d.ts b/chartjs/chart2.d.ts index f80e8d9897..b3ac83f33d 100644 --- a/chartjs/chart2.d.ts +++ b/chartjs/chart2.d.ts @@ -1,4 +1,4 @@ -/* TYPES */ +// TYPES declare enum ChartType { line, bar, radar, doughnut, polarArea, bubble } @@ -46,18 +46,18 @@ interface ChartPoint { y?: number; } -/* END */ +// END -/* Configuration */ +// Configuration interface ChartConfiguration { type?: string; data?: ChartData; options?: ChartOptions; } -/* END */ +// END -/* DATA */ +// DATA interface ChartData { } @@ -67,9 +67,9 @@ interface LinearChartData extends ChartData { datasets?: ChartDataSets[]; } -/* END */ +// END -/* Options */ +// Options interface ChartOptions { responsive?: boolean; responsiveAnimationDuration?: number; @@ -289,9 +289,9 @@ interface LogarithmicTickOptions extends TickOptions { min?: number; max?: number; } -/* END */ +// END -/* DATASETS */ +// DATASETS interface ChartDataSets { backgroundColor?: string[]; borderWidth?: number; @@ -317,9 +317,9 @@ interface ChartDataSets { xAxisID?: string; yAxisID?: string; } -/* END */ +// END -/* SCALES */ +// SCALES interface ChartScales { type?: string; display?: boolean; @@ -370,7 +370,7 @@ interface RadialLinearScale { pointLabels?: PointLabelOptions; ticks?: TickOptions; } -/* END */ +// END declare var Chart: { new (context: CanvasRenderingContext2D, options: ChartConfiguration): {}; From 40a3ecb89d7dccb88b1dd65279fca6e635724d4b Mon Sep 17 00:00:00 2001 From: anuti Date: Fri, 1 Jul 2016 11:46:00 +0200 Subject: [PATCH 0020/1255] Update chart2.d.ts --- chartjs/chart2.d.ts | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/chartjs/chart2.d.ts b/chartjs/chart2.d.ts index b3ac83f33d..7c30802074 100644 --- a/chartjs/chart2.d.ts +++ b/chartjs/chart2.d.ts @@ -1,4 +1,3 @@ -// TYPES declare enum ChartType { line, bar, radar, doughnut, polarArea, bubble } @@ -46,18 +45,12 @@ interface ChartPoint { y?: number; } -// END - -// Configuration interface ChartConfiguration { type?: string; data?: ChartData; options?: ChartOptions; } -// END - -// DATA interface ChartData { } @@ -67,9 +60,6 @@ interface LinearChartData extends ChartData { datasets?: ChartDataSets[]; } -// END - -// Options interface ChartOptions { responsive?: boolean; responsiveAnimationDuration?: number; @@ -289,9 +279,7 @@ interface LogarithmicTickOptions extends TickOptions { min?: number; max?: number; } -// END -// DATASETS interface ChartDataSets { backgroundColor?: string[]; borderWidth?: number; @@ -317,9 +305,7 @@ interface ChartDataSets { xAxisID?: string; yAxisID?: string; } -// END -// SCALES interface ChartScales { type?: string; display?: boolean; @@ -347,7 +333,6 @@ interface LinearScale extends ChartScales { ticks?: LinearTickOptions; } - interface LogarithmicScale extends ChartScales { ticks?: LogarithmicTickOptions; } @@ -370,7 +355,6 @@ interface RadialLinearScale { pointLabels?: PointLabelOptions; ticks?: TickOptions; } -// END declare var Chart: { new (context: CanvasRenderingContext2D, options: ChartConfiguration): {}; From 517371c47a937d9fb3859e9b694b9f60e17e5cba Mon Sep 17 00:00:00 2001 From: anuti Date: Fri, 1 Jul 2016 12:06:12 +0200 Subject: [PATCH 0021/1255] Update chart2.d.ts --- chartjs/chart2.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/chartjs/chart2.d.ts b/chartjs/chart2.d.ts index 7c30802074..5ea06e9ba6 100644 --- a/chartjs/chart2.d.ts +++ b/chartjs/chart2.d.ts @@ -1,3 +1,8 @@ +// Type definitions for Chart.js +// Project: https://github.com/nnnick/Chart.js +// Definitions by: Alberto Nuti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + declare enum ChartType { line, bar, radar, doughnut, polarArea, bubble } From 02c79d8200ba886ffe4590a89e4ced8e29ee51ab Mon Sep 17 00:00:00 2001 From: anuti Date: Fri, 1 Jul 2016 12:08:22 +0200 Subject: [PATCH 0022/1255] Update chart2.d.ts --- chartjs/chart2.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chartjs/chart2.d.ts b/chartjs/chart2.d.ts index 5ea06e9ba6..2d77f4c502 100644 --- a/chartjs/chart2.d.ts +++ b/chartjs/chart2.d.ts @@ -347,7 +347,7 @@ interface TimeScale extends ChartScales { isoWeekday?: boolean; max?: string; min?: string; - parser?: string | ((arg: any) => moment.MomentDateObject); + parser?: string | ((arg: any) => any); round?: string; tooltipFormat?: string; unit?: TimeUnit; From c8d5f64ef86cd7c3227bef1d412c034db8bbaf6d Mon Sep 17 00:00:00 2001 From: Gayan Ranasinghe Date: Mon, 4 Jul 2016 16:20:28 +0530 Subject: [PATCH 0023/1255] added some fields --- kendo-ui/kendo-ui.d.ts | 1425 ++++++++++++++++++++-------------------- 1 file changed, 717 insertions(+), 708 deletions(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index 934a8cd8b1..b8aea8a61a 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -3,7 +3,7 @@ // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// + declare namespace kendo { function culture(): { @@ -89,40 +89,10 @@ declare namespace kendo { }; }; - var cultures: {[culture: string] : { - name?: string; - calendar?: { - AM: string[]; - PM: string[]; - days: { - names: string[]; - namesAbbr: string[]; - namesShort: string[]; - firstDay: number; - }; - months: { - names: string[]; - namesAbbr: string[]; - }; - patterns: { - D: string; - F: string; - G: string; - M: string; - T: string; - Y: string; - d: string; - g: string; - m: string; - s: string; - t: string; - u: string; - y: string; - }; - twoDigitYearMax: number; - }; - calendars?: { - standard: { + var cultures: { + [culture: string]: { + name?: string; + calendar?: { AM: string[]; PM: string[]; days: { @@ -152,25 +122,57 @@ declare namespace kendo { }; twoDigitYearMax: number; }; - }; - numberFormat?: { - currency: { + calendars?: { + standard: { + AM: string[]; + PM: string[]; + days: { + names: string[]; + namesAbbr: string[]; + namesShort: string[]; + firstDay: number; + }; + months: { + names: string[]; + namesAbbr: string[]; + }; + patterns: { + D: string; + F: string; + G: string; + M: string; + T: string; + Y: string; + d: string; + g: string; + m: string; + s: string; + t: string; + u: string; + y: string; + }; + twoDigitYearMax: number; + }; + }; + numberFormat?: { + currency: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; decimals: number; groupSize: number[]; pattern: string[]; - symbol: string; + percent: { + decimals: number; + groupSize: number[]; + pattern: string[]; + symbol: string; + }; }; - decimals: number; - groupSize: number[]; - pattern: string[]; - percent: { - decimals: number; - groupSize: number[]; - pattern: string[]; - symbol: string; - }; - }; - }}; + } + }; function format(format: string, ...values: any[]): string; @@ -300,7 +302,7 @@ declare namespace kendo { } class ViewContainer extends Observable { - view: View; + view: View; } class Layout extends View { @@ -488,8 +490,8 @@ declare namespace kendo.data { change(e: Object): void; start(source: kendo.Observable): void; stop(source: kendo.Observable): void; - get (): any; - set (value: any): void; + get(): any; + set(value: any): void; destroy(): void; } @@ -500,7 +502,7 @@ declare namespace kendo.data { } class EventBinding extends Binding { - get (): void; + get(): void; } class TemplateBinding extends Binding { @@ -508,7 +510,8 @@ declare namespace kendo.data { render(value: Object): string; } - namespace binders { } + module binders { } + export var binders; interface Bindings { [key: string]: Binding; @@ -531,7 +534,7 @@ declare namespace kendo.data { interface BinderOptions { } - class ObservableObject extends Observable{ + class ObservableObject extends Observable { constructor(value?: any); uid: string; init(value?: any): void; @@ -571,6 +574,8 @@ declare namespace kendo.data { isAllDay?: boolean; id?: any; start?: Date; + ownerId?: number; + taskId?: number; startTimezone?: string; recurrenceId?: any; recurrenceRule?: string; @@ -583,7 +588,8 @@ declare namespace kendo.data { static fields: DataSourceSchemaModelFields; constructor(data?: SchedulerEventData); - + ownerId: number; + taskId: number; description: string; end: Date; endTimezone: string; @@ -839,7 +845,7 @@ declare namespace kendo.data { columns: PivotSchemaColumnAxis; } - interface PivotSchema extends DataSourceSchema{ + interface PivotSchema extends DataSourceSchema { axes?: any; catalogs?: any; cubes?: any; @@ -948,7 +954,7 @@ declare namespace kendo.data { } interface DataSourceSchemaWithConstructorModel extends DataSourceSchema { - model?: typeof Model; + model?: typeof Model; } interface DataSourceSchemaModel { @@ -996,7 +1002,7 @@ declare namespace kendo.data { every(callback: (item: Object, index: number, source: ObservableArray) => boolean): boolean; filter(callback: (item: Object, index: number, source: ObservableArray) => boolean): any[]; find(callback: (item: Object, index: number, source: ObservableArray) => boolean): any; - forEach(callback: (item: Object, index: number, source: ObservableArray) => void ): void; + forEach(callback: (item: Object, index: number, source: ObservableArray) => void): void; indexOf(item: any): number; join(separator: string): string; map(callback: (item: Object, index: number, source: ObservableArray) => any): any[]; @@ -1022,7 +1028,7 @@ declare namespace kendo.data { items?: kendo.data.Model[]; } - class DataSource extends Observable{ + class DataSource extends Observable { options: DataSourceOptions; static create(options?: DataSourceOptions): DataSource; @@ -1242,7 +1248,7 @@ declare namespace kendo.data { sort?: any; transport?: DataSourceTransport; type?: string; - change? (e: DataSourceChangeEvent): void; + change?(e: DataSourceChangeEvent): void; error?(e: DataSourceErrorEvent): void; sync?(e: DataSourceEvent): void; requestStart?(e: DataSourceRequestStartEvent): void; @@ -1325,7 +1331,7 @@ declare namespace kendo.ui { function plugin(widget: typeof kendo.ui.Widget, register?: typeof kendo.dataviz.ui, prefix?: String): void; function plugin(widget: any, register?: typeof kendo.dataviz.ui, prefix?: String): void; - class Draggable extends kendo.ui.Widget{ + class Draggable extends kendo.ui.Widget { element: JQuery; currentTarget: JQuery; constructor(element: Element, options?: DraggableOptions); @@ -1336,7 +1342,7 @@ declare namespace kendo.ui { sender?: Draggable; } - class DropTarget extends kendo.ui.Widget{ + class DropTarget extends kendo.ui.Widget { element: JQuery; constructor(element: Element, options?: DropTargetOptions); options: DropTargetOptions; @@ -1366,7 +1372,7 @@ declare namespace kendo.ui { draggable?: kendo.ui.Draggable; } - class DropTargetArea extends kendo.ui.Widget{ + class DropTargetArea extends kendo.ui.Widget { element: JQuery; constructor(element: Element, options?: DropTargetAreaOptions); options: DropTargetAreaOptions; @@ -1517,7 +1523,7 @@ declare namespace kendo.dataviz.map.layer { declare namespace kendo.drawing.pdf { function saveAs(group: kendo.drawing.Group, fileName: string, - proxyUrl?: string, callback?: Function): void; + proxyUrl?: string, callback?: Function): void; } declare namespace kendo.geometry { @@ -1690,7 +1696,7 @@ declare namespace kendo.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); + constructor(origin: kendo.geometry.Point | any, size: kendo.geometry.Size | any); static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; @@ -1916,7 +1922,7 @@ declare namespace kendo.drawing { } - interface FillOptions { + interface FillOptions { @@ -2215,7 +2221,7 @@ declare namespace kendo.drawing { } - interface PDFOptions { + interface PDFOptions { @@ -2319,7 +2325,7 @@ declare namespace kendo.drawing { interface RadialGradientOptions { name?: string; - center?: any|kendo.geometry.Point; + center?: any | kendo.geometry.Point; radius?: number; stops?: any; } @@ -2403,7 +2409,7 @@ declare namespace kendo.drawing { } - interface StrokeOptions { + interface StrokeOptions { @@ -2457,8 +2463,8 @@ declare namespace kendo.drawing { } interface SurfaceTooltip { - animation?: boolean|SurfaceTooltipAnimation; - appendTo?: string|JQuery; + animation?: boolean | SurfaceTooltipAnimation; + appendTo?: string | JQuery; } interface SurfaceOptions { @@ -2553,20 +2559,20 @@ declare namespace kendo.drawing { } - interface TooltipOptions { + interface TooltipOptions { autoHide?: boolean; - content?: string|Function; + content?: string | Function; position?: string; - height?: number|string; + height?: number | string; hideDelay?: number; offset?: number; shared?: boolean; showAfter?: number; showOn?: string; - width?: number|string; + width?: number | string; @@ -2636,14 +2642,14 @@ declare namespace kendo.ui { interface AutoCompleteOptions { name?: string; - animation?: boolean|AutoCompleteAnimation; - dataSource?: any|any|kendo.data.DataSource; + animation?: boolean | AutoCompleteAnimation; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string|Function; - groupTemplate?: string|Function; + fixedGroupTemplate?: string | Function; + groupTemplate?: string | Function; height?: number; highlightFirst?: boolean; ignoreCase?: boolean; @@ -2652,10 +2658,11 @@ declare namespace kendo.ui { popup?: any; separator?: string; suggest?: boolean; - headerTemplate?: string|Function; - template?: string|Function; + value?: any; + headerTemplate?: string | Function; + template?: string | Function; valuePrimitive?: boolean; - virtual?: boolean|AutoCompleteVirtual; + virtual?: boolean | AutoCompleteVirtual; change?(e: AutoCompleteChangeEvent): void; close?(e: AutoCompleteCloseEvent): void; dataBound?(e: AutoCompleteDataBoundEvent): void; @@ -2773,8 +2780,8 @@ declare namespace kendo.ui { culture?: string; dates?: any; depth?: string; - disableDates?: any|Function; - footer?: string|Function; + disableDates?: any | Function; + footer?: string | Function; format?: string; max?: Date; min?: Date; @@ -2821,7 +2828,7 @@ declare namespace kendo.ui { interface ColorPaletteOptions { name?: string; - palette?: string|any; + palette?: string | any; columns?: number; tileSize?: ColorPaletteTileSize; value?: string; @@ -2876,7 +2883,7 @@ declare namespace kendo.ui { columns?: number; tileSize?: ColorPickerTileSize; messages?: ColorPickerMessages; - palette?: string|any; + palette?: string | any; opacity?: boolean; preview?: boolean; toolIcon?: string; @@ -2976,14 +2983,14 @@ declare namespace kendo.ui { autoBind?: boolean; cascadeFrom?: string; cascadeFromField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; dataValueField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string|Function; - groupTemplate?: string|Function; + fixedGroupTemplate?: string | Function; + groupTemplate?: string | Function; height?: number; highlightFirst?: boolean; ignoreCase?: boolean; @@ -2992,12 +2999,12 @@ declare namespace kendo.ui { placeholder?: string; popup?: ComboBoxPopup; suggest?: boolean; - headerTemplate?: string|Function; - template?: string|Function; + headerTemplate?: string | Function; + template?: string | Function; text?: string; value?: string; valuePrimitive?: boolean; - virtual?: boolean|ComboBoxVirtual; + virtual?: boolean | ComboBoxVirtual; change?(e: ComboBoxChangeEvent): void; close?(e: ComboBoxCloseEvent): void; dataBound?(e: ComboBoxDataBoundEvent): void; @@ -3092,16 +3099,16 @@ declare namespace kendo.ui { interface ContextMenuOptions { name?: string; alignToAnchor?: boolean; - animation?: boolean|ContextMenuAnimation; + animation?: boolean | ContextMenuAnimation; closeOnClick?: boolean; - dataSource?: any|any; + dataSource?: any | any; direction?: string; filter?: string; hoverDelay?: number; orientation?: string; popupCollision?: string; showOn?: string; - target?: string|JQuery; + target?: string | JQuery; close?(e: ContextMenuCloseEvent): void; open?(e: ContextMenuOpenEvent): void; activate?(e: ContextMenuActivateEvent): void; @@ -3202,13 +3209,13 @@ declare namespace kendo.ui { interface DatePickerOptions { name?: string; - animation?: boolean|DatePickerAnimation; + animation?: boolean | DatePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; depth?: string; - disableDates?: any|Function; - footer?: string|Function; + disableDates?: any | Function; + footer?: string | Function; format?: string; max?: Date; min?: Date; @@ -3292,12 +3299,12 @@ declare namespace kendo.ui { interface DateTimePickerOptions { name?: string; - animation?: boolean|DateTimePickerAnimation; + animation?: boolean | DateTimePickerAnimation; ARIATemplate?: string; culture?: string; dates?: any; depth?: string; - disableDates?: any|Function; + disableDates?: any | Function; footer?: string; format?: string; interval?: number; @@ -3403,32 +3410,32 @@ declare namespace kendo.ui { interface DropDownListOptions { name?: string; - animation?: boolean|DropDownListAnimation; + animation?: boolean | DropDownListAnimation; autoBind?: boolean; cascadeFrom?: string; cascadeFromField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; dataValueField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string|Function; - groupTemplate?: string|Function; + fixedGroupTemplate?: string | Function; + groupTemplate?: string | Function; height?: number; ignoreCase?: boolean; index?: number; minLength?: number; popup?: DropDownListPopup; - optionLabel?: string|any; - optionLabelTemplate?: string|Function; - headerTemplate?: string|Function; - template?: string|Function; - valueTemplate?: string|Function; + optionLabel?: string | any; + optionLabelTemplate?: string | Function; + headerTemplate?: string | Function; + template?: string | Function; + valueTemplate?: string | Function; text?: string; value?: string; valuePrimitive?: boolean; - virtual?: boolean|DropDownListVirtual; + virtual?: boolean | DropDownListVirtual; change?(e: DropDownListChangeEvent): void; close?(e: DropDownListCloseEvent): void; dataBound?(e: DropDownListDataBoundEvent): void; @@ -3550,32 +3557,32 @@ declare namespace kendo.ui { interface EditorFileBrowserTransportCreate { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorFileBrowserTransportDestroy { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorFileBrowserTransportRead { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorFileBrowserTransport { read?: EditorFileBrowserTransportRead; uploadUrl?: string; - fileUrl?: string|Function; + fileUrl?: string | Function; destroy?: EditorFileBrowserTransportDestroy; create?: EditorFileBrowserTransportCreate; } @@ -3632,33 +3639,33 @@ declare namespace kendo.ui { interface EditorImageBrowserTransportCreate { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorImageBrowserTransportDestroy { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorImageBrowserTransportRead { contentType?: string; - data?: any|string|Function; + data?: any | string | Function; dataType?: string; type?: string; - url?: string|Function; + url?: string | Function; } interface EditorImageBrowserTransport { read?: EditorImageBrowserTransportRead; - thumbnailUrl?: string|Function; + thumbnailUrl?: string | Function; uploadUrl?: string; - imageUrl?: string|Function; + imageUrl?: string | Function; destroy?: EditorImageBrowserTransportDestroy; create?: EditorImageBrowserTransportCreate; } @@ -3747,15 +3754,15 @@ declare namespace kendo.ui { } interface EditorPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface EditorPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -3763,7 +3770,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: EditorPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -3814,7 +3821,7 @@ declare namespace kendo.ui { messages?: EditorMessages; pasteCleanup?: EditorPasteCleanup; pdf?: EditorPdf; - resizable?: boolean|EditorResizable; + resizable?: boolean | EditorResizable; serialization?: EditorSerialization; stylesheets?: any; tools?: EditorTool[]; @@ -3930,7 +3937,7 @@ declare namespace kendo.ui { interface FilterMenuOptions { name?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; extra?: boolean; field?: string; messages?: FilterMenuMessages; @@ -4034,7 +4041,7 @@ declare namespace kendo.ui { } interface GanttAssignments { - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataResourceIdField?: string; dataTaskIdField?: string; dataValueField?: string; @@ -4044,7 +4051,7 @@ declare namespace kendo.ui { field?: string; title?: string; format?: string; - width?: string|number; + width?: string | number; editable?: boolean; sortable?: boolean; } @@ -4055,7 +4062,7 @@ declare namespace kendo.ui { interface GanttEditable { confirmation?: boolean; - template?: string|Function; + template?: string | Function; } interface GanttMessagesActions { @@ -4102,15 +4109,15 @@ declare namespace kendo.ui { } interface GanttPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface GanttPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -4118,7 +4125,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: GanttPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -4128,31 +4135,31 @@ declare namespace kendo.ui { interface GanttResources { dataFormatField?: string; dataColorField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; field?: string; } interface GanttToolbarItem { name?: string; - template?: string|Function; + template?: string | Function; text?: string; } interface GanttTooltip { - template?: string|Function; + template?: string | Function; visible?: boolean; } interface GanttView { type?: string; selected?: boolean; - slotSize?: number|string; - timeHeaderTemplate?: string|Function; - dayHeaderTemplate?: string|Function; - weekHeaderTemplate?: string|Function; - monthHeaderTemplate?: string|Function; - yearHeaderTemplate?: string|Function; + slotSize?: number | string; + timeHeaderTemplate?: string | Function; + dayHeaderTemplate?: string | Function; + weekHeaderTemplate?: string | Function; + monthHeaderTemplate?: string | Function; + yearHeaderTemplate?: string | Function; resizeTooltipFormat?: string; } @@ -4162,10 +4169,10 @@ declare namespace kendo.ui { autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GanttColumn[]; - currentTimeMarker?: boolean|GanttCurrentTimeMarker; - dataSource?: any|any|kendo.data.GanttDataSource; - dependencies?: any|any|kendo.data.GanttDependencyDataSource; - editable?: boolean|GanttEditable; + currentTimeMarker?: boolean | GanttCurrentTimeMarker; + dataSource?: any | any | kendo.data.GanttDataSource; + dependencies?: any | any | kendo.data.GanttDependencyDataSource; + editable?: boolean | GanttEditable; navigatable?: boolean; workDayStart?: Date; workDayEnd?: Date; @@ -4173,20 +4180,20 @@ declare namespace kendo.ui { workWeekEnd?: number; hourSpan?: number; snap?: boolean; - height?: number|string; - listWidth?: string|number; + height?: number | string; + listWidth?: string | number; messages?: GanttMessages; pdf?: GanttPdf; resizable?: boolean; selectable?: boolean; showWorkDays?: boolean; showWorkHours?: boolean; - taskTemplate?: string|Function; + taskTemplate?: string | Function; toolbar?: GanttToolbarItem[]; tooltip?: GanttTooltip; views?: GanttView[]; resources?: GanttResources; - rowHeight?: number|string; + rowHeight?: number | string; dataBinding?(e: GanttDataBindingEvent): void; dataBound?(e: GanttDataBoundEvent): void; add?(e: GanttAddEvent): void; @@ -4380,7 +4387,7 @@ declare namespace kendo.ui { } interface GridAllowCopy { - delimeter?: string|any; + delimeter?: string | any; } interface GridColumnMenuMessages { @@ -4416,7 +4423,7 @@ declare namespace kendo.ui { } interface GridColumnFilterableCell { - dataSource?: any|kendo.data.DataSource; + dataSource?: any | kendo.data.DataSource; dataTextField?: string; delay?: number; inputWidth?: number; @@ -4431,13 +4438,13 @@ declare namespace kendo.ui { interface GridColumnFilterable { cell?: GridColumnFilterableCell; multi?: boolean; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; checkAll?: boolean; itemTemplate?: Function; operators?: any; search?: boolean; ignoreCase?: boolean; - ui?: string|Function; + ui?: string | Function; } interface GridColumnSortable { @@ -4451,35 +4458,36 @@ declare namespace kendo.ui { command?: GridColumnCommandItem[]; encoded?: boolean; field?: string; - filterable?: boolean|GridColumnFilterable; + filterable?: boolean | GridColumnFilterable; footerAttributes?: any; - footerTemplate?: string|Function; + footerTemplate?: string | Function; format?: string; groupable?: boolean; - groupHeaderTemplate?: string|Function; - groupFooterTemplate?: string|Function; + groupHeaderTemplate?: string | Function; + groupFooterTemplate?: string | Function; headerAttributes?: any; - headerTemplate?: string|Function; + headerTemplate?: string | Function; hidden?: boolean; locked?: boolean; lockable?: boolean; minScreenWidth?: number; - sortable?: boolean|GridColumnSortable; - template?: string|Function; + sortable?: boolean | GridColumnSortable; + template?: string | Function; title?: string; - width?: string|number; + width?: string | number; values?: any; menu?: boolean; + type?: any; } interface GridEditable { - confirmation?: boolean|string|Function; + confirmation?: boolean | string | Function; cancelDelete?: string; confirmDelete?: string; createAt?: string; destroy?: boolean; mode?: string; - template?: string|Function; + template?: string | Function; update?: boolean; window?: any; } @@ -4592,7 +4600,7 @@ declare namespace kendo.ui { } interface GridNoRecords { - template?: string|Function; + template?: string | Function; } interface GridPageableMessages { @@ -4615,23 +4623,23 @@ declare namespace kendo.ui { numeric?: boolean; buttonCount?: number; input?: boolean; - pageSizes?: boolean|any; + pageSizes?: boolean | any; refresh?: boolean; info?: boolean; messages?: GridPageableMessages; } interface GridPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface GridPdf { allPages?: boolean; author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -4639,7 +4647,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: GridPdfMargin; - paperSize?: string|any; + paperSize?: string | any; template?: string; repeatHeaders?: boolean; scale?: number; @@ -4660,38 +4668,38 @@ declare namespace kendo.ui { interface GridToolbarItem { name?: string; - template?: string|Function; + template?: string | Function; text?: string; } interface GridOptions { name?: string; - allowCopy?: boolean|GridAllowCopy; - altRowTemplate?: string|Function; + allowCopy?: boolean | GridAllowCopy; + altRowTemplate?: string | Function; autoBind?: boolean; columnResizeHandleWidth?: number; columns?: GridColumn[]; - columnMenu?: boolean|GridColumnMenu; - dataSource?: any|any|kendo.data.DataSource; - detailTemplate?: string|Function; - editable?: boolean|GridEditable; + columnMenu?: boolean | GridColumnMenu; + dataSource?: any | any | kendo.data.DataSource; + detailTemplate?: string | Function; + editable?: boolean | GridEditable; excel?: GridExcel; - filterable?: boolean|GridFilterable; - groupable?: boolean|GridGroupable; - height?: number|string; + filterable?: boolean | GridFilterable; + groupable?: boolean | GridGroupable; + height?: number | string; messages?: GridMessages; - mobile?: boolean|string; + mobile?: boolean | string; navigatable?: boolean; - noRecords?: boolean|GridNoRecords; - pageable?: boolean|GridPageable; + noRecords?: boolean | GridNoRecords; + pageable?: boolean | GridPageable; pdf?: GridPdf; reorderable?: boolean; resizable?: boolean; - rowTemplate?: string|Function; - scrollable?: boolean|GridScrollable; - selectable?: boolean|string; - sortable?: boolean|GridSortable; - toolbar?: string | ((...args:any[]) => string) | GridToolbarItem[]; + rowTemplate?: string | Function; + scrollable?: boolean | GridScrollable; + selectable?: boolean | string; + sortable?: boolean | GridSortable; + toolbar?: string | ((...args: any[]) => string) | GridToolbarItem[]; cancel?(e: GridCancelEvent): void; change?(e: GridChangeEvent): void; columnHide?(e: GridColumnHideEvent): void; @@ -4865,10 +4873,10 @@ declare namespace kendo.ui { interface ListViewOptions { name?: string; autoBind?: boolean; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; editTemplate?: Function; navigatable?: boolean; - selectable?: boolean|string; + selectable?: boolean | string; template?: Function; altTemplate?: Function; cancel?(e: ListViewCancelEvent): void; @@ -5007,9 +5015,9 @@ declare namespace kendo.ui { interface MenuOptions { name?: string; - animation?: boolean|MenuAnimation; + animation?: boolean | MenuAnimation; closeOnClick?: boolean; - dataSource?: any|any; + dataSource?: any | any; direction?: string; hoverDelay?: number; openOnClick?: boolean; @@ -5114,17 +5122,17 @@ declare namespace kendo.ui { interface MultiSelectOptions { name?: string; - animation?: boolean|MultiSelectAnimation; + animation?: boolean | MultiSelectAnimation; autoBind?: boolean; autoClose?: boolean; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; dataValueField?: string; delay?: number; enable?: boolean; filter?: string; - fixedGroupTemplate?: string|Function; - groupTemplate?: string|Function; + fixedGroupTemplate?: string | Function; + groupTemplate?: string | Function; height?: number; highlightFirst?: boolean; ignoreCase?: boolean; @@ -5132,13 +5140,13 @@ declare namespace kendo.ui { maxSelectedItems?: number; placeholder?: string; popup?: MultiSelectPopup; - headerTemplate?: string|Function; - itemTemplate?: string|Function; + headerTemplate?: string | Function; + itemTemplate?: string | Function; tagTemplate?: string; tagMode?: string; value?: any; valuePrimitive?: boolean; - virtual?: boolean|MultiSelectVirtual; + virtual?: boolean | MultiSelectVirtual; change?(e: MultiSelectChangeEvent): void; close?(e: MultiSelectCloseEvent): void; dataBound?(e: MultiSelectDataBoundEvent): void; @@ -5227,16 +5235,16 @@ declare namespace kendo.ui { interface NotificationOptions { name?: string; allowHideAfter?: number; - animation?: any|boolean; - appendTo?: string|JQuery; + animation?: any | boolean; + appendTo?: string | JQuery; autoHideAfter?: number; button?: boolean; - height?: number|string; + height?: number | string; hideOnClick?: boolean; position?: NotificationPosition; stacking?: string; templates?: NotificationTemplate[]; - width?: number|string; + width?: number | string; hide?(e: NotificationHideEvent): void; show?(e: NotificationShowEvent): void; } @@ -5361,13 +5369,13 @@ declare namespace kendo.ui { name?: string; autoBind?: boolean; buttonCount?: number; - dataSource?: any|kendo.data.DataSource; + dataSource?: any | kendo.data.DataSource; selectTemplate?: string; linkTemplate?: string; info?: boolean; input?: boolean; numeric?: boolean; - pageSizes?: boolean|any; + pageSizes?: boolean | any; previousNext?: boolean; refresh?: boolean; messages?: PagerMessages; @@ -5475,9 +5483,9 @@ declare namespace kendo.ui { interface PanelBarOptions { name?: string; - animation?: boolean|PanelBarAnimation; + animation?: boolean | PanelBarAnimation; contentUrls?: any; - dataSource?: any|any; + dataSource?: any | any; expandMode?: string; activate?(e: PanelBarActivateEvent): void; collapse?(e: PanelBarCollapseEvent): void; @@ -5581,10 +5589,10 @@ declare namespace kendo.ui { interface PivotConfiguratorOptions { name?: string; - dataSource?: any|kendo.data.PivotDataSource; + dataSource?: any | kendo.data.PivotDataSource; filterable?: boolean; - sortable?: boolean|PivotConfiguratorSortable; - height?: number|string; + sortable?: boolean | PivotConfiguratorSortable; + height?: number | string; messages?: PivotConfiguratorMessages; } interface PivotConfiguratorEvent { @@ -5660,15 +5668,15 @@ declare namespace kendo.ui { } interface PivotGridPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface PivotGridPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -5676,7 +5684,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: PivotGridPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -5689,20 +5697,20 @@ declare namespace kendo.ui { interface PivotGridOptions { name?: string; - dataSource?: any|kendo.data.PivotDataSource; + dataSource?: any | kendo.data.PivotDataSource; autoBind?: boolean; reorderable?: boolean; excel?: PivotGridExcel; pdf?: PivotGridPdf; filterable?: boolean; - sortable?: boolean|PivotGridSortable; + sortable?: boolean | PivotGridSortable; columnWidth?: number; - height?: number|string; - columnHeaderTemplate?: string|Function; - dataCellTemplate?: string|Function; - kpiStatusTemplate?: string|Function; - kpiTrendTemplate?: string|Function; - rowHeaderTemplate?: string|Function; + height?: number | string; + columnHeaderTemplate?: string | Function; + dataCellTemplate?: string | Function; + kpiStatusTemplate?: string | Function; + kpiTrendTemplate?: string | Function; + rowHeaderTemplate?: string | Function; messages?: PivotGridMessages; dataBinding?(e: PivotGridDataBindingEvent): void; dataBound?(e: PivotGridDataBoundEvent): void; @@ -5784,9 +5792,9 @@ declare namespace kendo.ui { interface PopupOptions { name?: string; adjustSize?: any; - animation?: boolean|PopupAnimation; - anchor?: string|JQuery; - appendTo?: string|JQuery; + animation?: boolean | PopupAnimation; + anchor?: string | JQuery; + appendTo?: string | JQuery; collision?: string; origin?: string; position?: string; @@ -5889,6 +5897,7 @@ declare namespace kendo.ui { destroy(): void; enable(enable: boolean): void; value(): any; + values(): any; value(selectionStart: number, selectionEnd: number): void; resize(): void; @@ -6017,19 +6026,19 @@ declare namespace kendo.ui { } interface SchedulerEditable { - confirmation?: boolean|string; + confirmation?: boolean | string; create?: boolean; destroy?: boolean; editRecurringMode?: string; move?: boolean; resize?: boolean; - template?: string|Function; + template?: string | Function; update?: boolean; window?: any; } interface SchedulerFooter { - command?: string|boolean; + command?: string | boolean; } interface SchedulerGroup { @@ -6166,15 +6175,15 @@ declare namespace kendo.ui { } interface SchedulerPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface SchedulerPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -6182,7 +6191,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: SchedulerPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -6191,7 +6200,7 @@ declare namespace kendo.ui { interface SchedulerResource { dataColorField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataTextField?: string; dataValueField?: string; field?: string; @@ -6216,26 +6225,26 @@ declare namespace kendo.ui { } interface SchedulerView { - allDayEventTemplate?: string|Function; + allDayEventTemplate?: string | Function; allDaySlot?: boolean; - allDaySlotTemplate?: string|Function; + allDaySlotTemplate?: string | Function; columnWidth?: number; - dateHeaderTemplate?: string|Function; - dayTemplate?: string|Function; - editable?: boolean|SchedulerViewEditable; + dateHeaderTemplate?: string | Function; + dayTemplate?: string | Function; + editable?: boolean | SchedulerViewEditable; endTime?: Date; eventHeight?: number; - eventTemplate?: string|Function; - eventTimeTemplate?: string|Function; + eventTemplate?: string | Function; + eventTimeTemplate?: string | Function; group?: SchedulerViewGroup; majorTick?: number; - majorTimeHeaderTemplate?: string|Function; + majorTimeHeaderTemplate?: string | Function; minorTickCount?: number; - minorTimeHeaderTemplate?: string|Function; + minorTimeHeaderTemplate?: string | Function; selected?: boolean; selectedDateFormat?: string; showWorkHours?: boolean; - slotTemplate?: string|Function; + slotTemplate?: string | Function; startTime?: Date; title?: string; type?: string; @@ -6253,27 +6262,27 @@ declare namespace kendo.ui { interface SchedulerOptions { name?: string; - allDayEventTemplate?: string|Function; + allDayEventTemplate?: string | Function; allDaySlot?: boolean; autoBind?: boolean; - currentTimeMarker?: boolean|SchedulerCurrentTimeMarker; - dataSource?: any|any|kendo.data.SchedulerDataSource; + currentTimeMarker?: boolean | SchedulerCurrentTimeMarker; + dataSource?: any | any | kendo.data.SchedulerDataSource; date?: Date; - dateHeaderTemplate?: string|Function; - editable?: boolean|SchedulerEditable; + dateHeaderTemplate?: string | Function; + editable?: boolean | SchedulerEditable; endTime?: Date; - eventTemplate?: string|Function; - footer?: boolean|SchedulerFooter; + eventTemplate?: string | Function; + footer?: boolean | SchedulerFooter; group?: SchedulerGroup; - height?: number|string; + height?: number | string; majorTick?: number; - majorTimeHeaderTemplate?: string|Function; + majorTimeHeaderTemplate?: string | Function; max?: Date; messages?: SchedulerMessages; min?: Date; minorTickCount?: number; - minorTimeHeaderTemplate?: string|Function; - mobile?: boolean|string; + minorTimeHeaderTemplate?: string | Function; + mobile?: boolean | string; pdf?: SchedulerPdf; resources?: SchedulerResource[]; selectable?: boolean; @@ -6283,8 +6292,8 @@ declare namespace kendo.ui { timezone?: string; toolbar?: SchedulerToolbarItem[]; views?: SchedulerView[]; - groupHeaderTemplate?: string|Function; - width?: number|string; + groupHeaderTemplate?: string | Function; + width?: number | string; workDayStart?: Date; workDayEnd?: Date; workWeekStart?: number; @@ -6480,17 +6489,17 @@ declare namespace kendo.ui { name?: string; axis?: string; autoScroll?: boolean; - container?: string|JQuery; + container?: string | JQuery; connectWith?: string; cursor?: string; cursorOffset?: SortableCursorOffset; disabled?: string; filter?: string; handler?: string; - hint?: Function|string|JQuery; + hint?: Function | string | JQuery; holdToDrag?: boolean; ignore?: string; - placeholder?: Function|string|JQuery; + placeholder?: Function | string | JQuery; start?(e: SortableStartEvent): void; move?(e: SortableMoveEvent): void; end?(e: SortableEndEvent): void; @@ -6677,10 +6686,10 @@ declare namespace kendo.ui { } interface SpreadsheetPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface SpreadsheetPdf { @@ -6696,7 +6705,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: SpreadsheetPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -6720,7 +6729,7 @@ declare namespace kendo.ui { index?: number; logic?: string; type?: string; - value?: number|string|Date; + value?: number | string | Date; values?: any; } @@ -6778,7 +6787,7 @@ declare namespace kendo.ui { link?: string; textAlign?: string; underline?: boolean; - value?: number|string|boolean|Date; + value?: number | string | boolean | Date; validation?: SpreadsheetSheetRowCellValidation; verticalAlign?: string; wrap?: boolean; @@ -6816,9 +6825,9 @@ declare namespace kendo.ui { } interface SpreadsheetToolbar { - home?: boolean|any; - insert?: boolean|any; - data?: boolean|any; + home?: boolean | any; + insert?: boolean | any; + data?: boolean | any; } interface SpreadsheetInsertSheetOptions { @@ -6845,7 +6854,7 @@ declare namespace kendo.ui { rows?: number; sheets?: SpreadsheetSheet[]; sheetsbar?: boolean; - toolbar?: boolean|SpreadsheetToolbar; + toolbar?: boolean | SpreadsheetToolbar; change?(e: SpreadsheetChangeEvent): void; render?(e: SpreadsheetRenderEvent): void; excelExport?(e: SpreadsheetExcelExportEvent): void; @@ -6871,7 +6880,7 @@ declare namespace kendo.ui { } interface SpreadsheetExcelImportEvent extends SpreadsheetEvent { - file?: Blob|File; + file?: Blob | File; progress?: JQueryPromise; } @@ -6971,18 +6980,18 @@ declare namespace kendo.ui { interface TabStripOptions { name?: string; - animation?: boolean|TabStripAnimation; + animation?: boolean | TabStripAnimation; collapsible?: boolean; contentUrls?: any; dataContentField?: string; dataContentUrlField?: string; dataImageUrlField?: string; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; dataSpriteCssClass?: string; dataTextField?: string; dataUrlField?: string; navigatable?: boolean; - scrollable?: boolean|TabStripScrollable; + scrollable?: boolean | TabStripScrollable; tabPosition?: string; value?: string; activate?(e: TabStripActivateEvent): void; @@ -7073,7 +7082,7 @@ declare namespace kendo.ui { interface TimePickerOptions { name?: string; - animation?: boolean|TimePickerAnimation; + animation?: boolean | TimePickerAnimation; culture?: string; dates?: any; format?: string; @@ -7179,13 +7188,13 @@ declare namespace kendo.ui { imageUrl?: string; menuButtons?: ToolBarItemMenuButton[]; overflow?: string; - overflowTemplate?: string|Function; + overflowTemplate?: string | Function; primary?: boolean; selected?: boolean; showIcon?: string; showText?: string; spriteCssClass?: string; - template?: string|Function; + template?: string | Function; text?: string; togglable?: boolean; toggle?: Function; @@ -7280,7 +7289,7 @@ declare namespace kendo.ui { interface TooltipOptions { name?: string; autoHide?: boolean; - animation?: boolean|TooltipAnimation; + animation?: boolean | TooltipAnimation; content?: TooltipContent; callout?: boolean; filter?: string; @@ -7505,7 +7514,7 @@ declare namespace kendo.ui { } interface TreeListColumnFilterable { - ui?: string|Function; + ui?: string | Function; } interface TreeListColumnSortable { @@ -7518,16 +7527,16 @@ declare namespace kendo.ui { encoded?: boolean; expandable?: boolean; field?: string; - filterable?: boolean|TreeListColumnFilterable; - footerTemplate?: string|Function; + filterable?: boolean | TreeListColumnFilterable; + footerTemplate?: string | Function; format?: string; headerAttributes?: any; - headerTemplate?: string|Function; + headerTemplate?: string | Function; minScreenWidth?: number; - sortable?: boolean|TreeListColumnSortable; - template?: string|Function; + sortable?: boolean | TreeListColumnSortable; + template?: string | Function; title?: string; - width?: string|number; + width?: string | number; hidden?: boolean; menu?: boolean; locked?: boolean; @@ -7537,7 +7546,7 @@ declare namespace kendo.ui { interface TreeListEditable { mode?: string; move?: boolean; - template?: string|Function; + template?: string | Function; window?: any; } @@ -7586,15 +7595,15 @@ declare namespace kendo.ui { } interface TreeListPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface TreeListPdf { author?: string; - avoidLinks?: boolean|string; + avoidLinks?: boolean | string; creator?: string; date?: Date; fileName?: string; @@ -7602,7 +7611,7 @@ declare namespace kendo.ui { keywords?: string; landscape?: boolean; margin?: TreeListPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -7625,17 +7634,17 @@ declare namespace kendo.ui { columns?: TreeListColumn[]; resizable?: boolean; reorderable?: boolean; - columnMenu?: boolean|TreeListColumnMenu; - dataSource?: any|any|kendo.data.TreeListDataSource; - editable?: boolean|TreeListEditable; + columnMenu?: boolean | TreeListColumnMenu; + dataSource?: any | any | kendo.data.TreeListDataSource; + editable?: boolean | TreeListEditable; excel?: TreeListExcel; - filterable?: boolean|TreeListFilterable; - height?: number|string; + filterable?: boolean | TreeListFilterable; + height?: number | string; messages?: TreeListMessages; pdf?: TreeListPdf; - scrollable?: boolean|any; - selectable?: boolean|string; - sortable?: boolean|TreeListSortable; + scrollable?: boolean | any; + selectable?: boolean | string; + sortable?: boolean | TreeListSortable; toolbar?: TreeListToolbarItem[]; cancel?(e: TreeListCancelEvent): void; change?(e: TreeListChangeEvent): void; @@ -7850,14 +7859,14 @@ declare namespace kendo.ui { } interface TreeViewAnimation { - collapse?: boolean|TreeViewAnimationCollapse; - expand?: boolean|TreeViewAnimationExpand; + collapse?: boolean | TreeViewAnimationCollapse; + expand?: boolean | TreeViewAnimationExpand; } interface TreeViewCheckboxes { checkChildren?: boolean; name?: string; - template?: string|Function; + template?: string | Function; } interface TreeViewMessages { @@ -7868,19 +7877,19 @@ declare namespace kendo.ui { interface TreeViewOptions { name?: string; - animation?: boolean|TreeViewAnimation; + animation?: boolean | TreeViewAnimation; autoBind?: boolean; autoScroll?: boolean; - checkboxes?: boolean|TreeViewCheckboxes; + checkboxes?: boolean | TreeViewCheckboxes; dataImageUrlField?: string; - dataSource?: any|any|kendo.data.HierarchicalDataSource; + dataSource?: any | any | kendo.data.HierarchicalDataSource; dataSpriteCssClassField?: string; - dataTextField?: string|any; + dataTextField?: string | any; dataUrlField?: string; dragAndDrop?: boolean; loadOnDemand?: boolean; messages?: TreeViewMessages; - template?: string|Function; + template?: string | Function; change?(e: TreeViewEvent): void; check?(e: TreeViewCheckEvent): void; collapse?(e: TreeViewCollapseEvent): void; @@ -8013,7 +8022,7 @@ declare namespace kendo.ui { localization?: UploadLocalization; multiple?: boolean; showFileList?: boolean; - template?: string|Function; + template?: string | Function; cancel?(e: UploadCancelEvent): void; complete?(e: UploadEvent): void; error?(e: UploadErrorEvent): void; @@ -8167,8 +8176,8 @@ declare namespace kendo.ui { } interface WindowPosition { - top?: number|string; - left?: number|string; + top?: number | string; + left?: number | string; } interface WindowRefreshOptions { @@ -8183,13 +8192,13 @@ declare namespace kendo.ui { interface WindowOptions { name?: string; actions?: any; - animation?: boolean|WindowAnimation; - appendTo?: any|string; + animation?: boolean | WindowAnimation; + appendTo?: any | string; autoFocus?: boolean; content?: WindowContent; draggable?: boolean; iframe?: boolean; - height?: number|string; + height?: number | string; maxHeight?: number; maxWidth?: number; minHeight?: number; @@ -8199,9 +8208,9 @@ declare namespace kendo.ui { position?: WindowPosition; resizable?: boolean; scrollable?: boolean; - title?: string|boolean; + title?: string | boolean; visible?: boolean; - width?: number|string; + width?: number | string; activate?(e: WindowEvent): void; close?(e: WindowCloseEvent): void; deactivate?(e: WindowEvent): void; @@ -8371,7 +8380,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartAxisDefaultsCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -8399,7 +8408,7 @@ declare namespace kendo.dataviz.ui { interface ChartAxisDefaultsLabelsRotation { align?: string; - angle?: number|string; + angle?: number | string; } interface ChartAxisDefaultsLabels { @@ -8411,7 +8420,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartAxisDefaultsLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -8549,7 +8558,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartCategoryAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -8591,7 +8600,7 @@ declare namespace kendo.dataviz.ui { interface ChartCategoryAxisItemLabelsRotation { align?: string; - angle?: number|string; + angle?: number | string; } interface ChartCategoryAxisItemLabels { @@ -8608,7 +8617,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartCategoryAxisItemLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -8680,7 +8689,7 @@ declare namespace kendo.dataviz.ui { border?: ChartCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -8726,7 +8735,7 @@ declare namespace kendo.dataviz.ui { border?: ChartCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -8804,7 +8813,7 @@ declare namespace kendo.dataviz.ui { interface ChartCategoryAxisItem { autoBaseUnitSteps?: ChartCategoryAxisItemAutoBaseUnitSteps; - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; baseUnit?: string; baseUnitStep?: any; @@ -8833,6 +8842,7 @@ declare namespace kendo.dataviz.ui { type?: string; visible?: boolean; weekStartDay?: number; + axisCrossingValues?: number[]; notes?: ChartCategoryAxisItemNotes; } @@ -8867,7 +8877,7 @@ declare namespace kendo.dataviz.ui { interface ChartLegendInactiveItemsLabels { color?: string; font?: string; - template?: string|Function; + template?: string | Function; } interface ChartLegendInactiveItems { @@ -8898,7 +8908,7 @@ declare namespace kendo.dataviz.ui { font?: string; margin?: ChartLegendLabelsMargin; padding?: ChartLegendLabelsPadding; - template?: string|Function; + template?: string | Function; } interface ChartLegendMargin { @@ -8996,10 +9006,10 @@ declare namespace kendo.dataviz.ui { } interface ChartPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface ChartPdf { @@ -9011,7 +9021,7 @@ declare namespace kendo.dataviz.ui { keywords?: string; landscape?: boolean; margin?: ChartPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -9047,10 +9057,10 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemBorder { - color?: string|Function; - dashType?: string|Function; - opacity?: number|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + opacity?: number | Function; + width?: number | Function; } interface ChartSeriesItemConnectors { @@ -9065,26 +9075,26 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemErrorBars { - value?: string|number|any|Function; + value?: string | number | any | Function; visual?: Function; - xValue?: string|number|any|Function; - yValue?: string|number|any|Function; + xValue?: string | number | any | Function; + yValue?: string | number | any | Function; endCaps?: boolean; color?: string; line?: ChartSeriesItemErrorBarsLine; } interface ChartSeriesItemExtremesBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface ChartSeriesItemExtremes { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemExtremesBorder; - size?: number|Function; - type?: string|Function; - rotation?: number|Function; + size?: number | Function; + type?: string | Function; + rotation?: number | Function; } interface ChartSeriesItemHighlightBorder { @@ -9110,15 +9120,15 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface ChartSeriesItemLabelsFromBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface ChartSeriesItemLabelsFromMargin { @@ -9136,16 +9146,16 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsFrom { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemLabelsFromBorder; - color?: string|Function; - font?: string|Function; - format?: string|Function; + color?: string | Function; + font?: string | Function; + format?: string | Function; margin?: ChartSeriesItemLabelsFromMargin; padding?: ChartSeriesItemLabelsFromPadding; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; } interface ChartSeriesItemLabelsMargin { @@ -9163,9 +9173,9 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsToBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface ChartSeriesItemLabelsToMargin { @@ -9183,31 +9193,31 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemLabelsTo { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemLabelsToBorder; - color?: string|Function; - font?: string|Function; - format?: string|Function; + color?: string | Function; + font?: string | Function; + format?: string | Function; margin?: ChartSeriesItemLabelsToMargin; padding?: ChartSeriesItemLabelsToPadding; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; } interface ChartSeriesItemLabels { align?: string; - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemLabelsBorder; - color?: string|Function; + color?: string | Function; distance?: number; - font?: string|Function; - format?: string|Function; + font?: string | Function; + format?: string | Function; margin?: ChartSeriesItemLabelsMargin; padding?: ChartSeriesItemLabelsPadding; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; visual?: Function; from?: ChartSeriesItemLabelsFrom; to?: ChartSeriesItemLabelsTo; @@ -9228,18 +9238,18 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemMarkersBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface ChartSeriesItemMarkers { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemMarkersBorder; - size?: number|Function; - type?: string|Function; - visible?: boolean|Function; + size?: number | Function; + type?: string | Function; + visible?: boolean | Function; visual?: Function; - rotation?: number|Function; + rotation?: number | Function; } interface ChartSeriesItemNegativeValues { @@ -9271,7 +9281,7 @@ declare namespace kendo.dataviz.ui { border?: ChartSeriesItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -9293,16 +9303,16 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemOutliersBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface ChartSeriesItemOutliers { - background?: string|Function; + background?: string | Function; border?: ChartSeriesItemOutliersBorder; - size?: number|Function; - type?: string|Function; - rotation?: number|Function; + size?: number | Function; + type?: string | Function; + rotation?: number | Function; } interface ChartSeriesItemOverlay { @@ -9315,18 +9325,18 @@ declare namespace kendo.dataviz.ui { } interface ChartSeriesItemTargetBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface ChartSeriesItemTargetLine { - width?: any|Function; + width?: any | Function; } interface ChartSeriesItemTarget { border?: ChartSeriesItemTargetBorder; - color?: string|Function; + color?: string | Function; line?: ChartSeriesItemTargetLine; } @@ -9349,23 +9359,23 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartSeriesItemTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } interface ChartSeriesItem { - aggregate?: string|Function; + aggregate?: string | Function; axis?: string; border?: ChartSeriesItemBorder; categoryField?: string; closeField?: string; - color?: string|Function; + color?: string | Function; colorField?: string; connectors?: ChartSeriesItemConnectors; currentField?: string; dashType?: string; data?: any; - downColor?: string|Function; + downColor?: string | Function; downColorField?: string; segmentSpacing?: number; summaryField?: string; @@ -9416,7 +9426,7 @@ declare namespace kendo.dataviz.ui { size?: number; sizeField?: string; spacing?: number; - stack?: boolean|ChartSeriesItemStack; + stack?: boolean | ChartSeriesItemStack; startAngle?: number; target?: ChartSeriesItemTarget; targetField?: string; @@ -9475,7 +9485,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsFromMargin; padding?: ChartSeriesDefaultsLabelsFromPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -9521,7 +9531,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsToMargin; padding?: ChartSeriesDefaultsLabelsToPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -9533,7 +9543,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: ChartSeriesDefaultsLabelsMargin; padding?: ChartSeriesDefaultsLabelsPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; from?: ChartSeriesDefaultsLabelsFrom; @@ -9564,7 +9574,7 @@ declare namespace kendo.dataviz.ui { border?: ChartSeriesDefaultsNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -9611,7 +9621,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartSeriesDefaultsTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -9632,7 +9642,7 @@ declare namespace kendo.dataviz.ui { scatter?: any; scatterLine?: any; spacing?: number; - stack?: boolean|ChartSeriesDefaultsStack; + stack?: boolean | ChartSeriesDefaultsStack; type?: string; tooltip?: ChartSeriesDefaultsTooltip; verticalArea?: any; @@ -9695,8 +9705,8 @@ declare namespace kendo.dataviz.ui { opacity?: number; padding?: ChartTooltipPadding; shared?: boolean; - sharedTemplate?: string|Function; - template?: string|Function; + sharedTemplate?: string | Function; + template?: string | Function; visible?: boolean; } @@ -9720,7 +9730,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartValueAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -9754,7 +9764,7 @@ declare namespace kendo.dataviz.ui { interface ChartValueAxisItemLabelsRotation { align?: string; - angle?: number|string; + angle?: number | string; } interface ChartValueAxisItemLabels { @@ -9769,7 +9779,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartValueAxisItemLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -9842,7 +9852,7 @@ declare namespace kendo.dataviz.ui { border?: ChartValueAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -9888,7 +9898,7 @@ declare namespace kendo.dataviz.ui { border?: ChartValueAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -9952,7 +9962,7 @@ declare namespace kendo.dataviz.ui { } interface ChartValueAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; color?: string; crosshair?: ChartValueAxisItemCrosshair; @@ -9997,7 +10007,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartXAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -10039,7 +10049,7 @@ declare namespace kendo.dataviz.ui { interface ChartXAxisItemLabelsRotation { align?: string; - angle?: number|string; + angle?: number | string; } interface ChartXAxisItemLabels { @@ -10056,7 +10066,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartXAxisItemLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -10128,7 +10138,7 @@ declare namespace kendo.dataviz.ui { border?: ChartXAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -10174,7 +10184,7 @@ declare namespace kendo.dataviz.ui { border?: ChartXAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -10238,7 +10248,7 @@ declare namespace kendo.dataviz.ui { } interface ChartXAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; baseUnit?: string; color?: string; @@ -10285,7 +10295,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: ChartYAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -10344,7 +10354,7 @@ declare namespace kendo.dataviz.ui { rotation?: ChartYAxisItemLabelsRotation; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; visual?: Function; } @@ -10416,7 +10426,7 @@ declare namespace kendo.dataviz.ui { border?: ChartYAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -10462,7 +10472,7 @@ declare namespace kendo.dataviz.ui { border?: ChartYAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -10526,7 +10536,7 @@ declare namespace kendo.dataviz.ui { } interface ChartYAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; baseUnit?: string; color?: string; @@ -10562,8 +10572,8 @@ declare namespace kendo.dataviz.ui { } interface ChartZoomable { - mousewheel?: boolean|ChartZoomableMousewheel; - selection?: boolean|ChartZoomableSelection; + mousewheel?: boolean | ChartZoomableMousewheel; + selection?: boolean | ChartZoomableSelection; } interface ChartExportImageOptions { @@ -10596,13 +10606,13 @@ declare namespace kendo.dataviz.ui { interface ChartOptions { name?: string; autoBind?: boolean; - axisDefaults?: ChartAxisDefaults; + axisDefaults?: any; categoryAxis?: ChartCategoryAxisItem[]; + valueAxis?: ChartValueAxisItem[]; chartArea?: ChartChartArea; - dataSource?: any|any|kendo.data.DataSource; + dataSource?: any; legend?: ChartLegend; panes?: ChartPane[]; - pannable?: boolean|ChartPannable; pdf?: ChartPdf; plotArea?: ChartPlotArea; renderAs?: string; @@ -10613,10 +10623,8 @@ declare namespace kendo.dataviz.ui { title?: ChartTitle; tooltip?: ChartTooltip; transitions?: boolean; - valueAxis?: ChartValueAxisItem[]; xAxis?: ChartXAxisItem[]; yAxis?: ChartYAxisItem[]; - zoomable?: boolean|ChartZoomable; axisLabelClick?(e: ChartAxisLabelClickEvent): void; legendItemClick?(e: ChartLegendItemClickEvent): void; legendItemHover?(e: ChartLegendItemHoverEvent): void; @@ -10627,13 +10635,14 @@ declare namespace kendo.dataviz.ui { noteClick?(e: ChartNoteClickEvent): void; noteHover?(e: ChartNoteHoverEvent): void; plotAreaClick?(e: ChartPlotAreaClickEvent): void; - plotAreaHover?(e: ChartPlotAreaHoverEvent): void; + pannable?:any; render?(e: ChartEvent): void; select?(e: ChartSelectEvent): void; selectEnd?(e: ChartSelectEndEvent): void; selectStart?(e: ChartSelectStartEvent): void; seriesClick?(e: ChartSeriesClickEvent): void; seriesHover?(e: ChartSeriesHoverEvent): void; + zoomable?:any; zoom?(e: ChartZoomEvent): void; zoomEnd?(e: ChartZoomEndEvent): void; zoomStart?(e: ChartZoomStartEvent): void; @@ -10866,7 +10875,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; visual?: Function; } @@ -10947,7 +10956,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnectionDefaults { content?: DiagramConnectionDefaultsContent; - editable?: boolean|DiagramConnectionDefaultsEditable; + editable?: boolean | DiagramConnectionDefaultsEditable; endCap?: DiagramConnectionDefaultsEndCap; fromConnector?: string; hover?: DiagramConnectionDefaultsHover; @@ -10965,7 +10974,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; visual?: Function; } @@ -11059,7 +11068,7 @@ declare namespace kendo.dataviz.ui { interface DiagramConnection { content?: DiagramConnectionContent; - editable?: boolean|DiagramConnectionEditable; + editable?: boolean | DiagramConnectionEditable; endCap?: DiagramConnectionEndCap; from?: DiagramConnectionFrom; fromConnector?: string; @@ -11078,7 +11087,7 @@ declare namespace kendo.dataviz.ui { } interface DiagramEditableDrag { - snap?: boolean|DiagramEditableDragSnap; + snap?: boolean | DiagramEditableDragSnap; } interface DiagramEditableResizeHandlesFill { @@ -11141,12 +11150,12 @@ declare namespace kendo.dataviz.ui { } interface DiagramEditable { - connectionTemplate?: string|Function; - drag?: boolean|DiagramEditableDrag; + connectionTemplate?: string | Function; + drag?: boolean | DiagramEditableDrag; remove?: boolean; - resize?: boolean|DiagramEditableResize; - rotate?: boolean|DiagramEditableRotate; - shapeTemplate?: string|Function; + resize?: boolean | DiagramEditableResize; + rotate?: boolean | DiagramEditableRotate; + shapeTemplate?: string | Function; tools?: DiagramEditableTool[]; } @@ -11182,10 +11191,10 @@ declare namespace kendo.dataviz.ui { } interface DiagramPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface DiagramPdf { @@ -11197,7 +11206,7 @@ declare namespace kendo.dataviz.ui { keywords?: string; landscape?: boolean; margin?: DiagramPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -11294,7 +11303,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; } @@ -11354,7 +11363,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeDefaultsConnector[]; connectorDefaults?: DiagramShapeDefaultsConnectorDefaults; content?: DiagramShapeDefaultsContent; - editable?: boolean|DiagramShapeDefaultsEditable; + editable?: boolean | DiagramShapeDefaultsEditable; fill?: DiagramShapeDefaultsFill; height?: number; hover?: DiagramShapeDefaultsHover; @@ -11452,7 +11461,7 @@ declare namespace kendo.dataviz.ui { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; } @@ -11510,7 +11519,7 @@ declare namespace kendo.dataviz.ui { connectors?: DiagramShapeConnector[]; connectorDefaults?: DiagramShapeConnectorDefaults; content?: DiagramShapeContent; - editable?: boolean|DiagramShapeEditable; + editable?: boolean | DiagramShapeEditable; fill?: DiagramShapeFill; height?: number; hover?: DiagramShapeHover; @@ -11547,16 +11556,16 @@ declare namespace kendo.dataviz.ui { autoBind?: boolean; connectionDefaults?: DiagramConnectionDefaults; connections?: DiagramConnection[]; - connectionsDataSource?: any|any|kendo.data.DataSource; - dataSource?: any|any|kendo.data.DataSource; - editable?: boolean|DiagramEditable; + connectionsDataSource?: any | any | kendo.data.DataSource; + dataSource?: any | any | kendo.data.DataSource; + editable?: boolean | DiagramEditable; layout?: DiagramLayout; - pannable?: boolean|DiagramPannable; + pannable?: boolean | DiagramPannable; pdf?: DiagramPdf; - selectable?: boolean|DiagramSelectable; + selectable?: boolean | DiagramSelectable; shapeDefaults?: DiagramShapeDefaults; shapes?: DiagramShape[]; - template?: string|Function; + template?: string | Function; zoom?: number; zoomMax?: number; zoomMin?: number; @@ -11764,7 +11773,7 @@ declare namespace kendo.dataviz.ui { interface LinearGaugePointerItem { border?: LinearGaugePointerItemBorder; color?: string; - margin?: number|any; + margin?: number | any; opacity?: number; shape?: string; size?: number; @@ -11800,7 +11809,7 @@ declare namespace kendo.dataviz.ui { format?: string; margin?: LinearGaugeScaleLabelsMargin; padding?: LinearGaugeScaleLabelsPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -11932,9 +11941,9 @@ declare namespace kendo.dataviz.ui { } interface MapControls { - attribution?: boolean|MapControlsAttribution; - navigator?: boolean|MapControlsNavigator; - zoom?: boolean|MapControlsZoom; + attribution?: boolean | MapControlsAttribution; + navigator?: boolean | MapControlsNavigator; + zoom?: boolean | MapControlsZoom; } interface MapLayerDefaultsBing { @@ -11968,7 +11977,7 @@ declare namespace kendo.dataviz.ui { maxSize?: number; minSize?: number; style?: MapLayerDefaultsBubbleStyle; - symbol?: string|Function; + symbol?: string | Function; } interface MapLayerDefaultsMarkerTooltipAnimationClose { @@ -12102,8 +12111,8 @@ declare namespace kendo.dataviz.ui { interface MapLayer { attribution?: string; autoBind?: boolean; - dataSource?: any|any|kendo.data.DataSource; - extent?: any|kendo.dataviz.map.Extent; + dataSource?: any | any | kendo.data.DataSource; + extent?: any | kendo.dataviz.map.Extent; key?: string; imagerySet?: string; culture?: string; @@ -12116,7 +12125,7 @@ declare namespace kendo.dataviz.ui { minSize?: number; opacity?: number; subdomains?: any; - symbol?: string|Function; + symbol?: string | Function; type?: string; style?: MapLayerStyle; urlTemplate?: string; @@ -12196,7 +12205,7 @@ declare namespace kendo.dataviz.ui { } interface MapMarker { - location?: any|kendo.dataviz.map.Location; + location?: any | kendo.dataviz.map.Location; shape?: string; title?: string; tooltip?: MapMarkerTooltip; @@ -12204,7 +12213,7 @@ declare namespace kendo.dataviz.ui { interface MapOptions { name?: string; - center?: any|kendo.dataviz.map.Location; + center?: any | kendo.dataviz.map.Location; controls?: MapControls; layerDefaults?: MapLayerDefaults; layers?: MapLayer[]; @@ -12369,8 +12378,8 @@ declare namespace kendo.dataviz.ui { errorCorrection?: string; padding?: number; renderAs?: string; - size?: number|string; - value?: number|string; + size?: number | string; + value?: number | string; } interface QRCodeEvent { sender: QRCode; @@ -12470,7 +12479,7 @@ declare namespace kendo.dataviz.ui { margin?: RadialGaugeScaleLabelsMargin; padding?: RadialGaugeScaleLabelsPadding; position?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -12575,8 +12584,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -12601,13 +12610,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; + margin?: number | any; mirror?: boolean; - padding?: number|any; + padding?: number | any; rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; culture?: string; dateFormats?: any; @@ -12680,7 +12689,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -12726,7 +12735,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -12765,7 +12774,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineCategoryAxisItemTitleBorder; color?: string; font?: string; - margin?: number|any; + margin?: number | any; position?: string; rotation?: number; text?: string; @@ -12773,7 +12782,7 @@ declare namespace kendo.dataviz.ui { } interface SparklineCategoryAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; categories?: any; color?: string; field?: string; @@ -12813,7 +12822,7 @@ declare namespace kendo.dataviz.ui { opacity?: number; border?: SparklineChartAreaBorder; height?: number; - margin?: number|any; + margin?: number | any; width?: number; } @@ -12827,14 +12836,14 @@ declare namespace kendo.dataviz.ui { background?: string; opacity?: number; border?: SparklinePlotAreaBorder; - margin?: number|any; + margin?: number | any; } interface SparklineSeriesItemBorder { - color?: string|Function; - dashType?: string|Function; - opacity?: number|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + opacity?: number | Function; + width?: number | Function; } interface SparklineSeriesItemConnectors { @@ -12857,24 +12866,24 @@ declare namespace kendo.dataviz.ui { } interface SparklineSeriesItemLabelsBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface SparklineSeriesItemLabels { align?: string; - background?: string|Function; + background?: string | Function; border?: SparklineSeriesItemLabelsBorder; - color?: string|Function; + color?: string | Function; distance?: number; - font?: string|Function; - format?: string|Function; - margin?: number|any; - padding?: number|any; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + font?: string | Function; + format?: string | Function; + margin?: number | any; + padding?: number | any; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; } interface SparklineSeriesItemLine { @@ -12885,17 +12894,17 @@ declare namespace kendo.dataviz.ui { } interface SparklineSeriesItemMarkersBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface SparklineSeriesItemMarkers { - background?: string|Function; + background?: string | Function; border?: SparklineSeriesItemMarkersBorder; - size?: number|Function; - type?: string|Function; - visible?: boolean|Function; - rotation?: number|Function; + size?: number | Function; + type?: string | Function; + visible?: boolean | Function; + rotation?: number | Function; } interface SparklineSeriesItemNotesIconBorder { @@ -12922,7 +12931,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineSeriesItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -12952,18 +12961,18 @@ declare namespace kendo.dataviz.ui { } interface SparklineSeriesItemTargetBorder { - color?: string|Function; - dashType?: string|Function; + color?: string | Function; + dashType?: string | Function; width?: number; } interface SparklineSeriesItemTargetLine { - width?: any|Function; + width?: any | Function; } interface SparklineSeriesItemTarget { line?: SparklineSeriesItemTargetLine; - color?: string|Function; + color?: string | Function; border?: SparklineSeriesItemTargetBorder; } @@ -12978,8 +12987,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -12993,11 +13002,11 @@ declare namespace kendo.dataviz.ui { field?: string; name?: string; highlight?: SparklineSeriesItemHighlight; - aggregate?: string|Function; + aggregate?: string | Function; axis?: string; border?: SparklineSeriesItemBorder; categoryField?: string; - color?: string|Function; + color?: string | Function; colorField?: string; connectors?: SparklineSeriesItemConnectors; gap?: number; @@ -13013,7 +13022,7 @@ declare namespace kendo.dataviz.ui { size?: number; startAngle?: number; spacing?: number; - stack?: boolean|SparklineSeriesItemStack; + stack?: boolean | SparklineSeriesItemStack; tooltip?: SparklineSeriesItemTooltip; width?: number; target?: SparklineSeriesItemTarget; @@ -13039,9 +13048,9 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; - padding?: number|any; - template?: string|Function; + margin?: number | any; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -13060,8 +13069,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -13076,7 +13085,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: boolean|SparklineSeriesDefaultsStack; + stack?: boolean | SparklineSeriesDefaultsStack; type?: string; tooltip?: SparklineSeriesDefaultsTooltip; } @@ -13092,8 +13101,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; shared?: boolean; sharedTemplate?: string; @@ -13110,8 +13119,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -13136,13 +13145,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; + margin?: number | any; mirror?: boolean; - padding?: number|any; + padding?: number | any; rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -13212,7 +13221,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineValueAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -13258,7 +13267,7 @@ declare namespace kendo.dataviz.ui { border?: SparklineValueAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -13297,8 +13306,8 @@ declare namespace kendo.dataviz.ui { border?: SparklineValueAxisItemTitleBorder; color?: string; font?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; position?: string; rotation?: number; text?: string; @@ -13306,7 +13315,7 @@ declare namespace kendo.dataviz.ui { } interface SparklineValueAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; color?: string; labels?: SparklineValueAxisItemLabels; line?: SparklineValueAxisItemLine; @@ -13502,8 +13511,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -13528,13 +13537,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; + margin?: number | any; mirror?: boolean; - padding?: number|any; + padding?: number | any; rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; culture?: string; dateFormats?: any; @@ -13607,7 +13616,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -13653,7 +13662,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -13705,7 +13714,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartCategoryAxisItemTitleBorder; color?: string; font?: string; - margin?: number|any; + margin?: number | any; position?: string; rotation?: number; text?: string; @@ -13713,7 +13722,7 @@ declare namespace kendo.dataviz.ui { } interface StockChartCategoryAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; categories?: any; color?: string; field?: string; @@ -13756,7 +13765,7 @@ declare namespace kendo.dataviz.ui { opacity?: number; border?: StockChartChartAreaBorder; height?: number; - margin?: number|any; + margin?: number | any; width?: number; } @@ -13797,10 +13806,10 @@ declare namespace kendo.dataviz.ui { border?: StockChartLegendBorder; item?: StockChartLegendItem; labels?: StockChartLegendLabels; - margin?: number|any; + margin?: number | any; offsetX?: number; offsetY?: number; - padding?: number|any; + padding?: number | any; position?: string; reverse?: boolean; visible?: boolean; @@ -13837,7 +13846,7 @@ declare namespace kendo.dataviz.ui { font?: string; format?: string; padding?: StockChartNavigatorCategoryAxisItemCrosshairTooltipPadding; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -13891,7 +13900,7 @@ declare namespace kendo.dataviz.ui { rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -13962,7 +13971,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartNavigatorCategoryAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14008,7 +14017,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartNavigatorCategoryAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14071,7 +14080,7 @@ declare namespace kendo.dataviz.ui { interface StockChartNavigatorCategoryAxisItem { autoBaseUnitSteps?: StockChartNavigatorCategoryAxisItemAutoBaseUnitSteps; - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; baseUnit?: string; baseUnitStep?: any; @@ -14100,7 +14109,7 @@ declare namespace kendo.dataviz.ui { interface StockChartNavigatorHint { visible?: boolean; - template?: string|Function; + template?: string | Function; format?: string; } @@ -14201,10 +14210,10 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; position?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -14222,7 +14231,7 @@ declare namespace kendo.dataviz.ui { interface StockChartNavigatorSeriesItemMarkers { background?: string; border?: StockChartNavigatorSeriesItemMarkersBorder; - rotation?: number|Function; + rotation?: number | Function; size?: number; type?: string; visible?: boolean; @@ -14248,8 +14257,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14262,7 +14271,7 @@ declare namespace kendo.dataviz.ui { categoryField?: string; name?: string; highlight?: StockChartNavigatorSeriesItemHighlight; - aggregate?: string|Function; + aggregate?: string | Function; axis?: string; border?: StockChartNavigatorSeriesItemBorder; closeField?: string; @@ -14281,7 +14290,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartNavigatorSeriesItemOverlay; spacing?: number; - stack?: boolean|StockChartNavigatorSeriesItemStack; + stack?: boolean | StockChartNavigatorSeriesItemStack; tooltip?: StockChartNavigatorSeriesItemTooltip; width?: number; } @@ -14315,7 +14324,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartPaneTitleBorder; color?: string; font?: string; - margin?: number|any; + margin?: number | any; position?: string; text?: string; visible?: boolean; @@ -14323,8 +14332,8 @@ declare namespace kendo.dataviz.ui { interface StockChartPane { name?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; background?: string; border?: StockChartPaneBorder; clip?: boolean; @@ -14333,10 +14342,10 @@ declare namespace kendo.dataviz.ui { } interface StockChartPdfMargin { - bottom?: number|string; - left?: number|string; - right?: number|string; - top?: number|string; + bottom?: number | string; + left?: number | string; + right?: number | string; + top?: number | string; } interface StockChartPdf { @@ -14348,7 +14357,7 @@ declare namespace kendo.dataviz.ui { keywords?: string; landscape?: boolean; margin?: StockChartPdfMargin; - paperSize?: string|any; + paperSize?: string | any; proxyURL?: string; proxyTarget?: string; subject?: string; @@ -14365,14 +14374,14 @@ declare namespace kendo.dataviz.ui { background?: string; opacity?: number; border?: StockChartPlotAreaBorder; - margin?: number|any; + margin?: number | any; } interface StockChartSeriesItemBorder { - color?: string|Function; - dashType?: string|Function; - opacity?: number|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + opacity?: number | Function; + width?: number | Function; } interface StockChartSeriesItemHighlightBorder { @@ -14396,22 +14405,22 @@ declare namespace kendo.dataviz.ui { } interface StockChartSeriesItemLabelsBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface StockChartSeriesItemLabels { - background?: string|Function; + background?: string | Function; border?: StockChartSeriesItemLabelsBorder; - color?: string|Function; - font?: string|Function; - format?: string|Function; - margin?: number|any; - padding?: number|any; - position?: string|Function; - template?: string|Function; - visible?: boolean|Function; + color?: string | Function; + font?: string | Function; + format?: string | Function; + margin?: number | any; + padding?: number | any; + position?: string | Function; + template?: string | Function; + visible?: boolean | Function; } interface StockChartSeriesItemLine { @@ -14422,17 +14431,17 @@ declare namespace kendo.dataviz.ui { } interface StockChartSeriesItemMarkersBorder { - color?: string|Function; - width?: number|Function; + color?: string | Function; + width?: number | Function; } interface StockChartSeriesItemMarkers { - background?: string|Function; + background?: string | Function; border?: StockChartSeriesItemMarkersBorder; - size?: number|Function; - rotation?: number|Function; - type?: string|Function; - visible?: boolean|Function; + size?: number | Function; + rotation?: number | Function; + type?: string | Function; + visible?: boolean | Function; } interface StockChartSeriesItemNotesIconBorder { @@ -14459,7 +14468,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartSeriesItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14489,18 +14498,18 @@ declare namespace kendo.dataviz.ui { } interface StockChartSeriesItemTargetBorder { - color?: string|Function; - dashType?: string|Function; - width?: number|Function; + color?: string | Function; + dashType?: string | Function; + width?: number | Function; } interface StockChartSeriesItemTargetLine { - width?: any|Function; + width?: any | Function; } interface StockChartSeriesItemTarget { line?: StockChartSeriesItemTargetLine; - color?: string|Function; + color?: string | Function; border?: StockChartSeriesItemTargetBorder; } @@ -14515,8 +14524,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14531,13 +14540,13 @@ declare namespace kendo.dataviz.ui { targetField?: string; name?: string; highlight?: StockChartSeriesItemHighlight; - aggregate?: string|Function; + aggregate?: string | Function; axis?: string; border?: StockChartSeriesItemBorder; closeField?: string; - color?: string|Function; + color?: string | Function; colorField?: string; - downColor?: string|Function; + downColor?: string | Function; downColorField?: string; gap?: number; labels?: StockChartSeriesItemLabels; @@ -14551,7 +14560,7 @@ declare namespace kendo.dataviz.ui { openField?: string; overlay?: StockChartSeriesItemOverlay; spacing?: number; - stack?: boolean|StockChartSeriesItemStack; + stack?: boolean | StockChartSeriesItemStack; tooltip?: StockChartSeriesItemTooltip; visibleInLegend?: boolean; width?: number; @@ -14578,9 +14587,9 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; - padding?: number|any; - template?: string|Function; + margin?: number | any; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14599,8 +14608,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14616,7 +14625,7 @@ declare namespace kendo.dataviz.ui { overlay?: any; pie?: any; spacing?: number; - stack?: boolean|StockChartSeriesDefaultsStack; + stack?: boolean | StockChartSeriesDefaultsStack; type?: string; tooltip?: StockChartSeriesDefaultsTooltip; } @@ -14633,8 +14642,8 @@ declare namespace kendo.dataviz.ui { border?: StockChartTitleBorder; font?: string; color?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; position?: string; text?: string; visible?: boolean; @@ -14651,8 +14660,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; shared?: boolean; sharedTemplate?: string; @@ -14669,8 +14678,8 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - padding?: number|any; - template?: string|Function; + padding?: number | any; + template?: string | Function; visible?: boolean; } @@ -14695,13 +14704,13 @@ declare namespace kendo.dataviz.ui { color?: string; font?: string; format?: string; - margin?: number|any; + margin?: number | any; mirror?: boolean; - padding?: number|any; + padding?: number | any; rotation?: number; skip?: number; step?: number; - template?: string|Function; + template?: string | Function; visible?: boolean; } @@ -14771,7 +14780,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartValueAxisItemNotesDataItemLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14817,7 +14826,7 @@ declare namespace kendo.dataviz.ui { border?: StockChartValueAxisItemNotesLabelBorder; color?: string; font?: string; - template?: string|Function; + template?: string | Function; visible?: boolean; rotation?: number; format?: string; @@ -14856,8 +14865,8 @@ declare namespace kendo.dataviz.ui { border?: StockChartValueAxisItemTitleBorder; color?: string; font?: string; - margin?: number|any; - padding?: number|any; + margin?: number | any; + padding?: number | any; position?: string; rotation?: number; text?: string; @@ -14865,7 +14874,7 @@ declare namespace kendo.dataviz.ui { } interface StockChartValueAxisItem { - axisCrossingValue?: any|Date|any; + axisCrossingValue?: any | Date | any; background?: string; color?: string; labels?: StockChartValueAxisItemLabels; @@ -15106,14 +15115,14 @@ declare namespace kendo.dataviz.ui { interface TreeMapOptions { name?: string; - dataSource?: any|any|kendo.data.HierarchicalDataSource; + dataSource?: any | any | kendo.data.HierarchicalDataSource; autoBind?: boolean; type?: string; theme?: string; valueField?: string; colorField?: string; textField?: string; - template?: string|Function; + template?: string | Function; colors?: any; itemCreated?(e: TreeMapItemCreatedEvent): void; dataBound?(e: TreeMapDataBoundEvent): void; @@ -15125,7 +15134,7 @@ declare namespace kendo.dataviz.ui { } interface TreeMapItemCreatedEvent extends TreeMapEvent { - element?: JQuery|Element; + element?: JQuery | Element; } interface TreeMapDataBoundEvent extends TreeMapEvent { @@ -15170,7 +15179,7 @@ declare namespace kendo.dataviz.map { nw: kendo.dataviz.map.Location; se: kendo.dataviz.map.Location; - constructor(nw: kendo.dataviz.map.Location|any, se: kendo.dataviz.map.Location|any); + constructor(nw: kendo.dataviz.map.Location | any, se: kendo.dataviz.map.Location | any); static create(a: kendo.dataviz.map.Location, b?: kendo.dataviz.map.Location): kendo.dataviz.map.Extent; static create(a: kendo.dataviz.map.Location, b?: any): kendo.dataviz.map.Extent; @@ -15310,7 +15319,7 @@ declare namespace kendo.dataviz.map { interface MarkerOptions { name?: string; - location?: any|kendo.dataviz.map.Location; + location?: any | kendo.dataviz.map.Location; shape?: string; title?: string; tooltip?: MarkerTooltip; @@ -15538,7 +15547,7 @@ declare namespace kendo.dataviz.diagram { fontSize?: number; fontStyle?: string; fontWeight?: string; - template?: string|Function; + template?: string | Function; text?: string; visual?: Function; } @@ -16235,7 +16244,7 @@ declare namespace kendo.dataviz.diagram { interface ShapeOptions { name?: string; id?: string; - editable?: boolean|ShapeEditable; + editable?: boolean | ShapeEditable; path?: string; stroke?: ShapeStroke; type?: string; @@ -16335,10 +16344,10 @@ declare namespace kendo { namespace drawing { function align(elements: any, rect: kendo.geometry.Rect, alignment: string): void; - function drawDOM(element: JQuery, options: any): JQueryPromise; - function exportImage(group: kendo.drawing.Group, options: any): JQueryPromise; - function exportPDF(group: kendo.drawing.Group, options: kendo.drawing.PDFOptions): JQueryPromise; - function exportSVG(group: kendo.drawing.Group, options: any): JQueryPromise; + function drawDOM(element: JQuery, options?: any): JQueryPromise; + function exportImage(group: kendo.drawing.Group, options?: any): JQueryPromise; + function exportPDF(group: kendo.drawing.Group, options?: kendo.drawing.PDFOptions): JQueryPromise; + function exportSVG(group: kendo.drawing.Group, options?: any): JQueryPromise; function fit(element: kendo.drawing.Element, rect: kendo.geometry.Rect): void; function stack(elements: any): void; function vAlign(elements: any, rect: kendo.geometry.Rect, alignment: string): void; @@ -16354,40 +16363,40 @@ declare namespace kendo { function transformOrigin(firstElement: HTMLElement, secondElement: HTMLElement): any; } - function antiForgeryTokens(): any; - function bind(element: string, viewModel: any, namespace?: any): void; - function bind(element: string, viewModel: kendo.data.ObservableObject, namespace?: any): void; - function bind(element: JQuery, viewModel: any, namespace?: any): void; - function bind(element: JQuery, viewModel: kendo.data.ObservableObject, namespace?: any): void; - function bind(element: Element, viewModel: any, namespace?: any): void; - function bind(element: Element, viewModel: kendo.data.ObservableObject, namespace?: any): void; - function observableHierarchy(array: any): void; - function culture(culture: string): void; - function destroy(element: string): void; - function destroy(element: JQuery): void; - function destroy(element: Element): void; - function htmlEncode(value: string): string; - function parseDate(value: string, formats?: string, culture?: string): Date; - function parseDate(value: string, formats?: any, culture?: string): Date; - function parseFloat(value: string, culture?: string): number; - function parseInt(value: string, culture?: string): number; - function parseColor(color: string, noerror: boolean): kendo.Color; - function proxyModelSetters(): void; - function proxyModelSetters(data: kendo.data.Model): void; - function resize(element: string, force: boolean): void; - function resize(element: JQuery, force: boolean): void; - function resize(element: Element, force: boolean): void; - function saveAs(options: any): void; - function stringify(value: any): string; - function throttle(fn: Function, timeout: number): void; - function touchScroller(element: string): void; - function touchScroller(element: JQuery): void; - function touchScroller(element: Element): void; - function toString(value: Date, format: string, culture?: string): string; - function toString(value: number, format: string, culture?: string): string; - function unbind(element: string): void; - function unbind(element: JQuery): void; - function unbind(element: Element): void; + function antiForgeryTokens(): any; + function bind(element: string, viewModel: any, namespace?: any): void; + function bind(element: string, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function bind(element: JQuery, viewModel: any, namespace?: any): void; + function bind(element: JQuery, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function bind(element: Element, viewModel: any, namespace?: any): void; + function bind(element: Element, viewModel: kendo.data.ObservableObject, namespace?: any): void; + function observableHierarchy(array: any): void; + function culture(culture: string): void; + function destroy(element: string): void; + function destroy(element: JQuery): void; + function destroy(element: Element): void; + function htmlEncode(value: string): string; + function parseDate(value: string, formats?: string, culture?: string): Date; + function parseDate(value: string, formats?: any, culture?: string): Date; + function parseFloat(value: string, culture?: string): number; + function parseInt(value: string, culture?: string): number; + function parseColor(color: string, noerror: boolean): kendo.Color; + function proxyModelSetters(): void; + function proxyModelSetters(data: kendo.data.Model): void; + function resize(element: string, force: boolean): void; + function resize(element: JQuery, force: boolean): void; + function resize(element: Element, force: boolean): void; + function saveAs(options: any): void; + function stringify(value: any): string; + function throttle(fn: Function, timeout: number): void; + function touchScroller(element: string): void; + function touchScroller(element: JQuery): void; + function touchScroller(element: Element): void; + function toString(value: Date, format: string, culture?: string): string; + function toString(value: number, format: string, culture?: string): string; + function unbind(element: string): void; + function unbind(element: JQuery): void; + function unbind(element: Element): void; namespace pdf { function defineFont(map: any): void; @@ -16639,9 +16648,9 @@ declare namespace kendo.mobile.ui { } interface ActionSheetPopup { - direction?: number|string; - height?: number|string; - width?: number|string; + direction?: number | string; + height?: number | string; + width?: number | string; } interface ActionSheetOptions { @@ -17009,18 +17018,18 @@ declare namespace kendo.mobile.ui { name?: string; appendOnRefresh?: boolean; autoBind?: boolean; - dataSource?: kendo.data.DataSource|any; + dataSource?: kendo.data.DataSource | any; endlessScroll?: boolean; fixedHeaders?: boolean; - headerTemplate?: string|Function; + headerTemplate?: string | Function; loadMore?: boolean; messages?: ListViewMessages; pullToRefresh?: boolean; pullParameters?: Function; style?: string; - template?: string|Function; + template?: string | Function; type?: string; - filterable?: boolean|ListViewFilterable; + filterable?: boolean | ListViewFilterable; virtualViewSize?: number; click?(e: ListViewClickEvent): void; dataBound?(e: ListViewEvent): void; @@ -17232,8 +17241,8 @@ declare namespace kendo.mobile.ui { } interface PopOverPopup { - height?: number|string; - width?: number|string; + height?: number | string; + width?: number | string; } interface PopOverOptions { @@ -17289,8 +17298,8 @@ declare namespace kendo.mobile.ui { name?: string; autoBind?: boolean; bounceVelocityThreshold?: number; - contentHeight?: number|string; - dataSource?: kendo.data.DataSource|any; + contentHeight?: number | string; + dataSource?: kendo.data.DataSource | any; duration?: number; emptyTemplate?: string; enablePager?: boolean; @@ -17669,7 +17678,7 @@ declare namespace kendo.ooxml { wrap?: boolean; vAlign?: string; verticalAlign?: string; - value?: Date|number|string|boolean; + value?: Date | number | string | boolean; } interface WorkbookSheetRow { @@ -17875,7 +17884,7 @@ declare namespace kendo.dataviz.geometry { origin: kendo.geometry.Point; size: kendo.geometry.Size; - constructor(origin: kendo.geometry.Point|any, size: kendo.geometry.Size|any); + constructor(origin: kendo.geometry.Point | any, size: kendo.geometry.Size | any); static fromPoints(pointA: kendo.geometry.Point, pointB: kendo.geometry.Point): kendo.geometry.Rect; static union(rectA: kendo.geometry.Rect, rectB: kendo.geometry.Rect): kendo.geometry.Rect; @@ -18101,7 +18110,7 @@ declare namespace kendo.dataviz.drawing { } - interface FillOptions { + interface FillOptions { @@ -18400,7 +18409,7 @@ declare namespace kendo.dataviz.drawing { } - interface PDFOptions { + interface PDFOptions { @@ -18504,7 +18513,7 @@ declare namespace kendo.dataviz.drawing { interface RadialGradientOptions { name?: string; - center?: any|kendo.geometry.Point; + center?: any | kendo.geometry.Point; radius?: number; stops?: any; } @@ -18588,7 +18597,7 @@ declare namespace kendo.dataviz.drawing { } - interface StrokeOptions { + interface StrokeOptions { @@ -18642,8 +18651,8 @@ declare namespace kendo.dataviz.drawing { } interface SurfaceTooltip { - animation?: boolean|SurfaceTooltipAnimation; - appendTo?: string|JQuery; + animation?: boolean | SurfaceTooltipAnimation; + appendTo?: string | JQuery; } interface SurfaceOptions { @@ -18738,20 +18747,20 @@ declare namespace kendo.dataviz.drawing { } - interface TooltipOptions { + interface TooltipOptions { autoHide?: boolean; - content?: string|Function; + content?: string | Function; position?: string; - height?: number|string; + height?: number | string; hideDelay?: number; offset?: number; shared?: boolean; showAfter?: number; showOn?: string; - width?: number|string; + width?: number | string; From fdb47e573f9c4d593094069136c1f12a0c17edd4 Mon Sep 17 00:00:00 2001 From: Gayan Ranasinghe Date: Mon, 4 Jul 2016 16:22:02 +0530 Subject: [PATCH 0024/1255] jquery reference --- kendo-ui/kendo-ui.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index b8aea8a61a..9d99d0bbfe 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -2,7 +2,7 @@ // Project: http://www.telerik.com/kendo-ui // Definitions by: Telerik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +/// declare namespace kendo { From 96817eace15d945f7202b8dc6ba00f4b7fe5f5dd Mon Sep 17 00:00:00 2001 From: Gayan Ranasinghe Date: Mon, 4 Jul 2016 16:27:55 +0530 Subject: [PATCH 0025/1255] removed implicitly has an 'any' type --- kendo-ui/kendo-ui.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/kendo-ui/kendo-ui.d.ts b/kendo-ui/kendo-ui.d.ts index 9d99d0bbfe..9974c78775 100644 --- a/kendo-ui/kendo-ui.d.ts +++ b/kendo-ui/kendo-ui.d.ts @@ -511,7 +511,6 @@ declare namespace kendo.data { } module binders { } - export var binders; interface Bindings { [key: string]: Binding; From 3dc8bd77a49ff3bb98e1a58e417877b27c76269e Mon Sep 17 00:00:00 2001 From: denis Date: Thu, 7 Jul 2016 15:24:42 +0200 Subject: [PATCH 0026/1255] Update for Chosen.JQuery version 1.6.1 Add missing options: case_sensitive_search and max_shown_results Add chosen("destroy"), SelectedData interface, triggers and JSDoc support --- chosen/chosen-tests.ts | 28 +++++++-- chosen/chosen.jquery.d.ts | 120 ++++++++++++++++++++++++++++++++------ 2 files changed, 124 insertions(+), 24 deletions(-) diff --git a/chosen/chosen-tests.ts b/chosen/chosen-tests.ts index 818b1e1261..764b57fb0e 100644 --- a/chosen/chosen-tests.ts +++ b/chosen/chosen-tests.ts @@ -1,8 +1,26 @@ /// -$(".chzn-select").chosen({ no_results_text: "No results matched" }); -$("#form_field").chosen().change(); -$("#form_field").trigger("liszt:updated"); +// Options +$(".my_select_box").chosen(); -$(".chzn-select").chosen(); -$(".chzn-select-deselect").chosen({ allow_single_deselect: true }); \ No newline at end of file +$(".my_select_box").chosen({}); + +$(".my_select_box").chosen({ + disable_search_threshold: 10, + max_selected_options: 5, + no_results_text: "Oops, nothing found!", + width: "95%" +}); + +// Destroy +$(".my_select_box").chosen("destroy"); + +// Triggered Events +$(".my_select_box").on("change", function(evt, params) { + evt.preventDefault(); + let s = params.selected; + console.log(s); +}); + +// Triggerable Events +$(".my_select_box").trigger("chosen:updated"); diff --git a/chosen/chosen.jquery.d.ts b/chosen/chosen.jquery.d.ts index 0033bfdd1d..85f233e718 100644 --- a/chosen/chosen.jquery.d.ts +++ b/chosen/chosen.jquery.d.ts @@ -1,30 +1,112 @@ -// Type definitions for Chosen.JQuery 1.4.2 +// Type definitions for Chosen.JQuery 1.6.1 // Project: http://harvesthq.github.com/chosen/ // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - /// -interface ChosenOptions { - allow_single_deselect?: boolean; - disable_search?: boolean; - disable_search_threshold?: number; - enable_split_word_search?: boolean; - inherit_select_classes?: boolean; - max_selected_options?: number; - no_results_text?: string; - placeholder_text_multiple?: string; - placeholder_text_single?: string; - search_contains?: boolean; - single_backstroke_delete?: boolean; - width?: number|string; - display_disabled_options?: boolean; - display_selected_options?: boolean; - include_group_label_in_selected?: boolean; +declare namespace Chosen { + interface Options { + /**When set to true on a single select, Chosen adds a UI element which selects the first element (if it is blank). + * @default: false + */ + allow_single_deselect?: boolean; + /**By default Chosen's search is case-insensitive. Setting this option to true makes the search case-sensitive. + * @default: false + */ + case_sensitive_search?: boolean; + /**When set to true, Chosen will not display the search field (single selects only). + * @default: false + */ + disable_search?: boolean; + /**Hide the search input on single selects if there are n or fewer options. + * @default: 0 + */ + disable_search_threshold?: number; + /**By default, searching will match on any word within an option tag. Set this option to false if you want to only match on the entire text of an option tag. + * @default: true + */ + enable_split_word_search?: boolean; + /**When set to true, Chosen will grab any classes on the original select field and add them to Chosen’s container div. + * @default: false + */ + inherit_select_classes?: boolean; + /**Limits how many options the user can select. When the limit is reached, the chosen:maxselected event is triggered. + * @default: Infinity + */ + max_selected_options?: number; + /**The text to be displayed when no matching results are found. The current search is shown at the end of the text (e.g., No results match "Bad Search"). + * @default: "No results match" + */ + no_results_text?: string; + /**The text to be displayed as a placeholder when no options are selected for a multiple select. + * @default: "Select Some Options" + */ + placeholder_text_multiple?: string; + /**The text to be displayed as a placeholder when no options are selected for a single select. + * @default: "Select an Option" + */ + placeholder_text_single?: string; + /**By default, Chosen’s search matches starting at the beginning of a word. Setting this option to true allows matches starting from anywhere within a word. This is especially useful for options that include a lot of special characters or phrases in ()s and []s. + * @default: false + */ + search_contains?: boolean; + /**By default, pressing delete/backspace on multiple selects will remove a selected choice. When false, pressing delete/backspace will highlight the last choice, and a second press deselects it. + * @default: true + */ + single_backstroke_delete?: boolean; + /**The width of the Chosen select box. By default, Chosen attempts to match the width of the select box you are replacing. If your select is hidden when Chosen is instantiated, you must specify a width or the select will show up with a width of 0. */ + width?: string; + /**By default, Chosen includes disabled options in search results with a special styling. Setting this option to false will hide disabled results and exclude them from searches. + * @default: true + */ + display_disabled_options?: boolean; + /**By default, Chosen includes selected options in search results with a special styling. Setting this option to false will hide selected results and exclude them from searches. + * Note: this is for multiple selects only. In single selects, the selected result will always be displayed. + * @default: true + */ + display_selected_options?: boolean; + /**By default, Chosen only shows the text of a selected option. Setting this option to true will show the text and group (if any) of the selected option. + * @default: false + */ + include_group_label_in_selected?: boolean; + /**Only show the first (n) matching options in the results. This can be used to increase performance for selects with very many options. + * @default: Infinity + */ + max_shown_results?: number; + } + + interface SelectedData { + selected: string; + deselected: string; + } } interface JQuery { chosen(): JQuery; - chosen(options: ChosenOptions): JQuery; + chosen(options: Chosen.Options): JQuery; + /**To destroy Chosen and revert back to the native select. */ + chosen(options: "destroy"): JQuery; + + /**Chosen triggers the standard DOM event whenever a selection is made (it also sends a selected or deselected parameter that tells you which option was changed). */ + on(events: "change", handler: (eventObject: JQueryEventObject, args: Chosen.SelectedData) => any): JQuery; + /**Triggered after Chosen has been fully instantiated. */ + on(events: "chosen:ready", handler: (eventObject: JQueryEventObject) => any): JQuery; + /**Triggered if max_selected_options is set and that total is broken. */ + on(events: "chosen:maxselected", handler: (eventObject: JQueryEventObject) => any): JQuery; + /**Triggered when Chosen’s dropdown is opened. */ + on(events: "chosen:showing_dropdown", handler: (eventObject: JQueryEventObject) => any): JQuery; + /**Triggered when Chosen’s dropdown is closed. */ + on(events: "chosen:hiding_dropdown", handler: (eventObject: JQueryEventObject) => any): JQuery; + /**Triggered when a search returns no matching results. */ + on(events: "chosen:no_results", handler: (eventObject: JQueryEventObject) => any): JQuery; + + /**This event should be triggered whenever Chosen’s underlying select element changes (such as a change in selected options). */ + trigger(eventType: "chosen:updated"): JQuery; + /**This is the equivalant of focusing a standard HTML select field. When activated, Chosen will capure keypress events as if you had clicked the field directly. */ + trigger(eventType: "chosen:activate"): JQuery; + /**This event activates Chosen and also displays the search results. */ + trigger(eventType: "chosen:open"): JQuery; + /**This event deactivates Chosen and hides the search results. */ + trigger(eventType: "chosen:close"): JQuery; } From ee2b56f2b5f9873a99b8b0ae666b4b5dd4e210dd Mon Sep 17 00:00:00 2001 From: "d.rogozhny@gmail.com" Date: Thu, 7 Jul 2016 17:17:46 +0300 Subject: [PATCH 0027/1255] Added new definition file for Draft-js v0.7.0. Added tests. Renamed old files by adding "-v0.2.2" suffix. --- draft-js/draft-js-0.2.2.d.ts | 277 +++++++ draft-js/draft-js-tests-0.2.2.tsx | 183 +++++ draft-js/draft-js-tests.tsx | 321 ++++---- draft-js/draft-js.d.ts | 1192 ++++++++++++++++++++++------- 4 files changed, 1548 insertions(+), 425 deletions(-) create mode 100644 draft-js/draft-js-0.2.2.d.ts create mode 100644 draft-js/draft-js-tests-0.2.2.tsx diff --git a/draft-js/draft-js-0.2.2.d.ts b/draft-js/draft-js-0.2.2.d.ts new file mode 100644 index 0000000000..ac5eb21f33 --- /dev/null +++ b/draft-js/draft-js-0.2.2.d.ts @@ -0,0 +1,277 @@ +// Type definitions for draft-js 0.2.2 +// Project: https://github.com/facebook/draft-js +// Definitions by: Pavel Evsegneev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "draft-js" { + namespace Draft { + interface IEditor { + new(): Editor + } + + interface EditorState { + getCurrentContent(): ContentState, + getSelection(): SelectionState, + getCurrentInlineStyle(): any, + getBlockTree(): any, + + createEmpty(decorator?: any): EditorState, + createWithContent(contentState: ContentState, decorator?: any): EditorState, + create(config: any): EditorState, + push(editorState: EditorState, contentState: ContentState, actionType: string): EditorState, + undo(editorState: EditorState): EditorState, + redo(editorState: EditorState): EditorState, + acceptSelection(editorState: EditorState, selectionState: SelectionState): EditorState, + forceSelection(editorState: EditorState, selectionState: SelectionState): EditorState, + + moveFocusToEnd(editorState: EditorState): EditorState + } + + interface CompositeDecorator { + getDecorations(): Array, + getComponentForKey(): any, + getPropsForKey(): any + } + + interface Entity { + create(type: string, mutability: string, data?: Object): EntityInstance, + add(instance: EntityInstance): string, + get(key: string): EntityInstance, + mergeData(key: string, toMerge: any): EntityInstance, + replaceData(key: string, newData: any): EntityInstance + } + + interface EntityInstance { + getData(): any, + getKey(): string, + getMutability(): string + } + + interface BlockMapBuilder { + createFromArray(blocks: Array): BlockMap + } + + interface CharacterMetadata { + create(config?: any): CharacterMetadata, + + applyStyle(record: CharacterMetadata, + style: string): CharacterMetadata, + + removeStyle(record: CharacterMetadata, + style: string): CharacterMetadata, + + applyEntity(record: CharacterMetadata, + entityKey?: string): CharacterMetadata, + + getStyle(): any, + hasStyle(style: string): boolean, + + getEntity(): string + } + + interface IContentBlock { + new(draftContentBlock: any): ContentBlock; + } + interface ContentBlock { + key: string, + type: string, + text: string, + characterList: any, + depth: number, + + getKey(): string, + getType(): string, + getText(): string, + getCharacterList(): any, + getLength(): number, + getDepth(): number, + getInlineStyleAt(offset: number): any, + getEntityAt(offset: number): string, + findStyleRanges(filterFn: Function, callback: Function): void, + findEntityRanges(filterFn: Function, callback: Function): void + + } + + interface ContentState { + createFromText(text: string): ContentState, + createFromBlockArray(blocks: Array): ContentState, + + getBlockMap(): BlockMap, + getSelectionBefore(): SelectionState, + getSelectionAfter(): SelectionState, + + getBlockForKey(key: string): ContentBlock, + getKeyBefore(key: string): string, + getKeyAfter(key: string): string, + + getBlockBefore(key: string): ContentBlock, + getBlockAfter(key: string): ContentBlock, + + getBlocksAsArray(): Array, + + getPlainText(): string, + hasText(): boolean, + + set(key: string, value: any): ContentState, + toJS(): any + } + + interface ISelectionState { + new(draftSelectionState: any): SelectionState; + createEmpty(blockKey: string): SelectionState; + } + + interface SelectionState { + getStartKey(): string, + getStartOffset(): number, + getEndKey(): string, + getEndOffset(): number, + getAnchorKey(): string, + getAnchorOffset(): number, + getFocusKey(): string, + getFocusOffset(): number, + + getIsBackward(): boolean, + getHasFocus(): boolean, + isCollapsed(): boolean, + + hasEdgeWithin(blockKey: string, start: number, end: number): boolean, + serialize(): string, + + get(key: string): any, + set(key: string, value: any): SelectionState + } + + interface BlockMap { + get(key: string): ContentBlock, + set(key: string, value: any): BlockMap, + delete(key: string): BlockMap, + find(cb: any): ContentBlock + } + + interface Modifier { + replaceText(contentState: ContentState, + rangeToReplace: SelectionState, + text: string, + inlineStyle?: any, + entityKey?: string): ContentState, + + insertText(contentState: ContentState, + targetRange: SelectionState, + text: string, + inlineStyle?: any, + entityKey?: string): ContentState, + + moveText(contentState: ContentState, + removalRange: SelectionState, + targetRange: SelectionState): ContentState, + + replaceWithFragment(contentState: ContentState, + targetRange: SelectionState, + fragment: BlockMap): ContentState, + + removeRange(contentState: ContentState, + rangeToRemove: SelectionState, + removalDirection: string): ContentState, + + splitBlock(contentState: ContentState, + selectionState: SelectionState): ContentState, + + applyInlineStyle(contentState: ContentState, + selectionState: SelectionState, + inlineStyle: string): ContentState, + + removeInlineStyle(contentState: ContentState, + selectionState: SelectionState, + inlineStyle: string): ContentState, + + setBlockType(contentState: ContentState, + selectionState: SelectionState, + blockType: string): ContentState, + + applyEntity(contentState: ContentState, + selectionState: SelectionState, + entityKey: string): ContentState + } + + interface RichUtils { + currentBlockContainsLink(editorState: EditorState): boolean, + getCurrentBlockType(editor: EditorState): string, + handleKeyCommand(editorState: EditorState, command: string): any, + insertSoftNewline(editorState: EditorState): EditorState, + onBackspace(editorState: EditorState): EditorState, + onDelete(editorState: EditorState): EditorState, + onTab(event: Event, editorState: EditorState, maxDepth: number): EditorState, + toggleBlockType(editorState: EditorState, blockType: string): EditorState, + toggleCode(editorState: EditorState): EditorState, + toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState, + tryToRemoveBlockStyle(editorState: EditorState): EditorState + } + + interface EditorProps { + editorState: EditorState, + onChange(editorState: EditorState): void, + + placeholder?: string, + textAlignment?: any, + blockRendererFn?: (ContentBlock: ContentBlock) => any, + blockStyleFn?: (ContentBlock: ContentBlock) => string, + customStyleMap?: any, + + readOnly?: boolean, + spellCheck?: boolean, + stripPastedStyles?: boolean, + + handleReturn?: (e: any) => boolean, + handleKeyCommand?: (command: string) => boolean, + handleBeforeInput?: (chars: string) => boolean, + handlePastedFiles?: (files: Array) => boolean, + handleDroppedFiles?: (selection: SelectionState, files: Array) => boolean, + handleDrop?: (selection: SelectionState, dataTransfer: any, isInternal: any) => boolean, + + onEscape?: (e: any) => void, + onTab?: (e: any) => void, + onUpArrow?: (e: any) => void, + onDownArrow?: (e: any) => void, + + suppressContentEditableWarning?: any, + + onBlur?: (e: any) => void, + onFocus?: (e: any) => void + } + + interface Editor { + props: EditorProps + state: any, + refs: any, + context: any, + setState(): any, + render(): any, + forceUpdate(): any + } + + var Editor: IEditor; + var EditorState: EditorState; + + var CompositeDecorator: CompositeDecorator; + var Entity: Entity; + var EntityInstance: EntityInstance; + + var BlockMapBuilder: BlockMapBuilder; + var CharacterMetadata: CharacterMetadata; + var ContentBlock: IContentBlock; + var ContentState: ContentState; + var SelectionState: ISelectionState; + + var Modifier: Modifier; + var RichUtils: RichUtils; + + function convertFromRaw(rawState: any): Array; + + function convertToRaw(contentState: ContentState): any; + + function genKey(): string + } + + export = Draft; + +} diff --git a/draft-js/draft-js-tests-0.2.2.tsx b/draft-js/draft-js-tests-0.2.2.tsx new file mode 100644 index 0000000000..d1c0143dd6 --- /dev/null +++ b/draft-js/draft-js-tests-0.2.2.tsx @@ -0,0 +1,183 @@ +/// +/// +/// + +import * as React from "react"; + +import { +Editor, + EditorState, + Entity, + CharacterMetadata, + ContentBlock, + Modifier, + SelectionState, + genKey +} from "draft-js"; + +export class Tag extends React.Component { + constructor(props: any) { + super(props); + } + + remove = (): void => { + this.props.blockProps.removeBlock(this.props.block.getKey()); + } + + render () { + const {block} = this.props; + if (block.getEntityAt(0)) { + const data = Entity.get(block.getEntityAt(0)).getData(); + + return ( +
+ {data.content.name} + + clear + +
+ ); + } + } +} + +export class Hint extends React.Component { + constructor(props: any) { + super(props); + } + + render () { + const {block} = this.props; + if (block.getEntityAt(0)) { + const data = Entity.get(block.getEntityAt(0)).getData(); + + return ( +
+ {this.props.blockProps.autocomplete} + {data.content.text} +
+ ); + } + } +} + +export function removeBlock(editorState: EditorState, blockKey: string) { + const content = editorState.getCurrentContent(); + + const targetRange = new SelectionState({ + anchorKey: blockKey, + anchorOffset: 0, + focusKey: blockKey, + focusOffset: 1 + }); + + const withoutTag = Modifier.removeRange(content, targetRange, "backward"); + const resetBlock = Modifier.setBlockType( + withoutTag, + withoutTag.getSelectionAfter(), + "unstyled" + ); + + const newState = EditorState.push(editorState, resetBlock, "remove-range"); + return EditorState.forceSelection(newState, resetBlock.getSelectionAfter()); +} + +export function applyEntity(editorState: EditorState, blockKey: string, entityKey: string) { + const content = editorState.getCurrentContent(); + + const targetRange = new SelectionState({ + anchorKey: blockKey, + anchorOffset: 0, + focusKey: blockKey, + focusOffset: 1 + }); + + const withNewEntity = Modifier.applyEntity( + content, + targetRange, + entityKey + ) + + const newState = EditorState.push(editorState, withNewEntity, "change-entity"); + return EditorState.forceSelection(newState, withNewEntity.getSelectionAfter()); +} + +export function addTagBlock(content: any, editorState: EditorState): any { + const contentState = editorState.getCurrentContent(); + + const entityKey = Entity.create( + "TOKEN", + "IMMUTABLE", + {content} + ); + + const charData = CharacterMetadata.create({entity: entityKey}); + const tag = new ContentBlock({ + key: genKey(), + type: "tag", + text: "", + characterList: [], + }); + + const withTag = contentState.set("blockMap", contentState.getBlockMap().set(tag.key, tag)); + + const withRemovedPreviousBlock = withTag.set("blockMap", withTag.getBlockMap().delete(contentState.getSelectionBefore().getAnchorKey())) + + const withTagBlock = EditorState.push(editorState, withRemovedPreviousBlock, "insert-fragment"); + + return withTagBlock; +} + +export function addHintBlock(content: any, editorState: EditorState): any { + const contentState = editorState.getCurrentContent(); + const selectionState = editorState.getSelection(); + + const entityKey = Entity.create( + "TOKEN", + "IMMUTABLE", + {content} + ); + + const charData = CharacterMetadata.create({entity: entityKey}); + const hint = new ContentBlock({ + key: genKey(), + type: "hint", + text: "", + characterList: [], + }); + const empty = new ContentBlock({ + key: genKey(), + type: "unstyled", + text: "", + characterList: [], + }); + + const withEmpty = contentState.set("blockMap", contentState.getBlockMap().set(empty.key, empty)); + const withHint = withEmpty.set("blockMap", withEmpty.getBlockMap().set(hint.key, hint)); + return { + editorState: EditorState.forceSelection(EditorState.push(editorState, withHint, "insert-fragment"), selectionState), + blockKey: hint.key + } + +} + +export class SearchField extends React.Component { + public onChange: any; + + constructor(props: any) { + super(props); + this.onChange = (editorState: EditorState) => { + this.setState({editorState}) + }; + } + + render() { + const {editorState} = this.state; + return ( + + ) + } +} diff --git a/draft-js/draft-js-tests.tsx b/draft-js/draft-js-tests.tsx index 91706cd7e0..eb3aaa4012 100644 --- a/draft-js/draft-js-tests.tsx +++ b/draft-js/draft-js-tests.tsx @@ -1,183 +1,184 @@ -/// -/// -/// +/// +/// +/// + +// Using Rich text editor example as a test: https://github.com/facebook/draft-js/tree/master/examples/rich import * as React from "react"; +import * as ReactDOM from "react-dom"; +import {Map} from "immutable"; -import { -Editor, - EditorState, - Entity, - CharacterMetadata, - ContentBlock, - Modifier, - SelectionState, - genKey -} from "draft-js"; +import {Editor, EditorState, RichUtils, DefaultDraftBlockRenderMap, ContentBlock} from 'draft-js'; -export class Tag extends React.Component { - constructor(props: any) { - super(props); +class RichEditorExample extends React.Component<{}, { editorState: EditorState }> { + constructor() { + super(); + + this.state = { editorState: EditorState.createEmpty() }; + } + + onChange: (editorState: EditorState) => void = (editorState: EditorState) => this.setState({ editorState }); + + handleKeyCommand: (command: string) => boolean = (command: string) => { + const {editorState} = this.state; + const newState = RichUtils.handleKeyCommand(editorState, command); + if (newState) { + this.onChange(newState); + return true; } - remove = (): void => { - this.props.blockProps.removeBlock(this.props.block.getKey()); + return false; + } + + toggleBlockType: (blockType: string) => void = (blockType: string) => { + this.onChange(RichUtils.toggleBlockType(this.state.editorState, blockType)); + } + + toggleInlineStyle: (inlineStyle: string) => void = (inlineStyle: string) => { + this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, inlineStyle)); + } + + render(): React.ReactElement<{}> { + // If the user changes block type before entering any text, we can + // either style the placeholder or hide it. Let's just hide it now. + let className = 'RichEditor-editor'; + var contentState = this.state.editorState.getCurrentContent(); + if (!contentState.hasText()) { + if (contentState.getBlockMap().first().getType() !== 'unstyled') { + className += ' RichEditor-hidePlaceholder'; + } } - render () { - const {block} = this.props; - if (block.getEntityAt(0)) { - const data = Entity.get(block.getEntityAt(0)).getData(); - - return ( -
- {data.content.name} - - clear - -
- ); - } - } -} - -export class Hint extends React.Component { - constructor(props: any) { - super(props); - } - - render () { - const {block} = this.props; - if (block.getEntityAt(0)) { - const data = Entity.get(block.getEntityAt(0)).getData(); - - return ( -
- {this.props.blockProps.autocomplete} - {data.content.text} -
- ); - } - } -} - -export function removeBlock(editorState: EditorState, blockKey: string) { - const content = editorState.getCurrentContent(); - - const targetRange = new SelectionState({ - anchorKey: blockKey, - anchorOffset: 0, - focusKey: blockKey, - focusOffset: 1 - }); - - const withoutTag = Modifier.removeRange(content, targetRange, "backward"); - const resetBlock = Modifier.setBlockType( - withoutTag, - withoutTag.getSelectionAfter(), - "unstyled" + return ( +
+ + +
+ +
+
); - - const newState = EditorState.push(editorState, resetBlock, "remove-range"); - return EditorState.forceSelection(newState, resetBlock.getSelectionAfter()); + } } -export function applyEntity(editorState: EditorState, blockKey: string, entityKey: string) { - const content = editorState.getCurrentContent(); +// Custom overrides for "code" style. +const styleMap = { + CODE: { + backgroundColor: 'rgba(0, 0, 0, 0.05)', + fontFamily: '"Inconsolata", "Menlo", "Consolas", monospace', + fontSize: 16, + padding: 2, + }, +}; - const targetRange = new SelectionState({ - anchorKey: blockKey, - anchorOffset: 0, - focusKey: blockKey, - focusOffset: 1 - }); - - const withNewEntity = Modifier.applyEntity( - content, - targetRange, - entityKey - ) - - const newState = EditorState.push(editorState, withNewEntity, "change-entity"); - return EditorState.forceSelection(newState, withNewEntity.getSelectionAfter()); +function getBlockStyle(block: ContentBlock) { + switch (block.getType()) { + case 'blockquote': return 'RichEditor-blockquote'; + default: return null; + } } -export function addTagBlock(content: any, editorState: EditorState): any { - const contentState = editorState.getCurrentContent(); +class StyleButton extends React.Component<{key: string, active: boolean, label: string, onToggle: (blockType: string) => void, style: string}, {}> { + constructor() { + super(); + } - const entityKey = Entity.create( - "TOKEN", - "IMMUTABLE", - {content} + onToggle: (event: Event) => void = (event: Event) => { + event.preventDefault(); + this.props.onToggle(this.props.style); + }; + + render(): React.ReactElement<{}> { + let className = 'RichEditor-styleButton'; + + if (this.props.active) { + className += ' RichEditor-activeButton'; + } + + return ( + + {this.props.label} + ); - - const charData = CharacterMetadata.create({entity: entityKey}); - const tag = new ContentBlock({ - key: genKey(), - type: "tag", - text: "", - characterList: [], - }); - - const withTag = contentState.set("blockMap", contentState.getBlockMap().set(tag.key, tag)); - - const withRemovedPreviousBlock = withTag.set("blockMap", withTag.getBlockMap().delete(contentState.getSelectionBefore().getAnchorKey())) - - const withTagBlock = EditorState.push(editorState, withRemovedPreviousBlock, "insert-fragment"); - - return withTagBlock; + } } -export function addHintBlock(content: any, editorState: EditorState): any { - const contentState = editorState.getCurrentContent(); - const selectionState = editorState.getSelection(); +const BLOCK_TYPES = [ + { label: 'H1', style: 'header-one' }, + { label: 'H2', style: 'header-two' }, + { label: 'H3', style: 'header-three' }, + { label: 'H4', style: 'header-four' }, + { label: 'H5', style: 'header-five' }, + { label: 'H6', style: 'header-six' }, + { label: 'Blockquote', style: 'blockquote' }, + { label: 'UL', style: 'unordered-list-item' }, + { label: 'OL', style: 'ordered-list-item' }, + { label: 'Code Block', style: 'code-block' }, +]; - const entityKey = Entity.create( - "TOKEN", - "IMMUTABLE", - {content} - ); +const BlockStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => { + const {editorState} = props; + const selection = editorState.getSelection(); + const blockType = editorState + .getCurrentContent() + .getBlockForKey(selection.getStartKey()) + .getType(); - const charData = CharacterMetadata.create({entity: entityKey}); - const hint = new ContentBlock({ - key: genKey(), - type: "hint", - text: "", - characterList: [], - }); - const empty = new ContentBlock({ - key: genKey(), - type: "unstyled", - text: "", - characterList: [], - }); + return ( +
+ {BLOCK_TYPES.map((type) => + + ) } +
+ ); +}; - const withEmpty = contentState.set("blockMap", contentState.getBlockMap().set(empty.key, empty)); - const withHint = withEmpty.set("blockMap", withEmpty.getBlockMap().set(hint.key, hint)); - return { - editorState: EditorState.forceSelection(EditorState.push(editorState, withHint, "insert-fragment"), selectionState), - blockKey: hint.key - } +var INLINE_STYLES = [ + { label: 'Bold', style: 'BOLD' }, + { label: 'Italic', style: 'ITALIC' }, + { label: 'Underline', style: 'UNDERLINE' }, + { label: 'Monospace', style: 'CODE' }, +]; -} +const InlineStyleControls = (props: {editorState: EditorState, onToggle: (blockType: string) => void}) => { + var currentStyle = props.editorState.getCurrentInlineStyle(); + return ( +
+ {INLINE_STYLES.map(type => + + ) } +
+ ); +}; -export class SearchField extends React.Component { - public onChange: any; - - constructor(props: any) { - super(props); - this.onChange = (editorState: EditorState) => { - this.setState({editorState}) - }; - } - - render() { - const {editorState} = this.state; - return ( - - ) - } -} +ReactDOM.render( + , + document.getElementById('target') +); \ No newline at end of file diff --git a/draft-js/draft-js.d.ts b/draft-js/draft-js.d.ts index ac5eb21f33..999741b426 100644 --- a/draft-js/draft-js.d.ts +++ b/draft-js/draft-js.d.ts @@ -1,277 +1,939 @@ -// Type definitions for draft-js 0.2.2 -// Project: https://github.com/facebook/draft-js -// Definitions by: Pavel Evsegneev +// Type definitions for Draft.js v0.7.0 +// Project: https://facebook.github.io/draft-js/ +// Definitions by: Dmitry Rogozhny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "draft-js" { - namespace Draft { - interface IEditor { - new(): Editor + +/// +/// + +import SyntheticKeyboardEvent = React.KeyboardEvent; +import SyntheticEvent = React.SyntheticEvent; + +import React = __React; + +declare namespace Draft { + namespace Component { + namespace Base { + import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftDragType = Draft.Model.Constants.DraftDragType; + + import EditorState = Draft.Model.ImmutableData.EditorState; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + import SelectionState = Draft.Model.ImmutableData.SelectionState; + + import DraftBlockRenderConfig = Draft.Model.ImmutableData.DraftBlockRenderConfig; + + type DraftBlockRenderMap = Immutable.Map; + + /** + * `DraftEditor` is the root editor component. It composes a `contentEditable` + * div, and provides a wide variety of useful function props for managing the + * state of the editor. See `DraftEditorProps` for details. + */ + class DraftEditor extends React.Component { + // Force focus back onto the editor node. + focus(): void; + // Remove focus from the editor node. + blur(): void; + } + + /** + * The two most critical props are `editorState` and `onChange`. + * + * The `editorState` prop defines the entire state of the editor, while the + * `onChange` prop is the method in which all state changes are propagated + * upward to higher-level components. + * + * These props are analagous to `value` and `onChange` in controlled React + * text inputs. + */ + interface DraftEditorProps { + editorState: EditorState; + onChange(editorState: EditorState): void; + + placeholder?: string; + + // Specify whether text alignment should be forced in a direction + // regardless of input characters. + textAlignment?: DraftTextAlignment; + + // For a given `ContentBlock` object, return an object that specifies + // a custom block component and/or props. If no object is returned, + // the default `TextEditorBlock` is used. + blockRendererFn?(block: ContentBlock): any; + + // Function that allows to define class names to apply to the given block when it is rendered. + blockStyleFn?(block: ContentBlock): string; + + // Provide a map of inline style names corresponding to CSS style objects + // that will be rendered for matching ranges. + customStyleMap?: any, + + // A function that accepts a synthetic key event and returns + // the matching DraftEditorCommand constant, or null if no command should + // be invoked. + keyBindingFn?(e: SyntheticKeyboardEvent): DraftEditorCommand; + keyBindingFn?(e: SyntheticKeyboardEvent): string; + + // Set whether the `DraftEditor` component should be editable. Useful for + // temporarily disabling edit behavior or allowing `DraftEditor` rendering + // to be used for consumption purposes. + readOnly?: boolean, + + // Note: spellcheck is always disabled for IE. If enabled in Safari, OSX + // autocorrect is enabled as well. + spellCheck?: boolean, + + // Set whether to remove all style information from pasted content. If your + // use case should not have any block or inline styles, it is recommended + // that you set this to `true`. + stripPastedStyles?: boolean, + + tabIndex?: number, + + ariaActiveDescendantID?: string, + ariaAutoComplete?: string, + ariaDescribedBy?: string, + ariaExpanded?: boolean, + ariaHasPopup?: boolean, + ariaLabel?: string, + ariaOwneeID?: string, + + webDriverTestID?: string, + + /** + * Cancelable event handlers, handled from the top level down. A handler + * that returns true will be the last handler to execute for that event. + */ + + // Useful for managing special behavior for pressing the `Return` key. E.g. + // removing the style from an empty list item. + handleReturn?(e: SyntheticKeyboardEvent): boolean, + + // Map a key command string provided by your key binding function to a + // specified behavior. + handleKeyCommand?(command: DraftEditorCommand): boolean, + handleKeyCommand?(command: string): boolean, + + + // Handle intended text insertion before the insertion occurs. This may be + // useful in cases where the user has entered characters that you would like + // to trigger some special behavior. E.g. immediately converting `:)` to an + // emoji Unicode character, or replacing ASCII quote characters with smart + // quotes. + handleBeforeInput?(chars: string): boolean, + + handlePastedText?(text: string, html?: string): boolean, + + handlePastedFiles?(files: Array): boolean, + + // Handle dropped files + handleDroppedFiles?(selection: SelectionState, files: Array): boolean, + + // Handle other drops to prevent default text movement/insertion behaviour + handleDrop?(selection: SelectionState, dataTransfer: Object, isInternal: DraftDragType): boolean, + + /** + * Non-cancelable event triggers. + */ + onEscape?(e: SyntheticKeyboardEvent): void, + onTab?(e: SyntheticKeyboardEvent): void, + onUpArrow?(e: SyntheticKeyboardEvent): void, + onDownArrow?(e: SyntheticKeyboardEvent): void, + + onBlur?(e: SyntheticEvent): void, + onFocus?(e: SyntheticEvent): void, + + // Provide a map of block rendering configurations. Each block type maps to + // an element tag and an optional react element wrapper. This configuration + // is used for both rendering and paste processing. + blockRenderMap?: DraftBlockRenderMap + } + + type DraftTextAlignment = "left" | "center" | "right"; } - interface EditorState { - getCurrentContent(): ContentState, - getSelection(): SelectionState, - getCurrentInlineStyle(): any, - getBlockTree(): any, - - createEmpty(decorator?: any): EditorState, - createWithContent(contentState: ContentState, decorator?: any): EditorState, - create(config: any): EditorState, - push(editorState: EditorState, contentState: ContentState, actionType: string): EditorState, - undo(editorState: EditorState): EditorState, - redo(editorState: EditorState): EditorState, - acceptSelection(editorState: EditorState, selectionState: SelectionState): EditorState, - forceSelection(editorState: EditorState, selectionState: SelectionState): EditorState, - - moveFocusToEnd(editorState: EditorState): EditorState + namespace Components { + class DraftEditorBlock extends React.Component { + } } - interface CompositeDecorator { - getDecorations(): Array, - getComponentForKey(): any, - getPropsForKey(): any + namespace Selection { + interface FakeClientRect { + left: number, + width: number, + right: number, + top: number, + bottom: number, + height: number, + } + + /** + * Return the bounding ClientRect for the visible DOM selection, if any. + * In cases where there are no selected ranges or the bounding rect is + * temporarily invalid, return null. + */ + function getVisibleSelectionRect(global: any): FakeClientRect; } - interface Entity { - create(type: string, mutability: string, data?: Object): EntityInstance, - add(instance: EntityInstance): string, - get(key: string): EntityInstance, - mergeData(key: string, toMerge: any): EntityInstance, - replaceData(key: string, newData: any): EntityInstance + namespace Utils { + import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; + + interface KeyBindingUtil { + /** + * Check whether the ctrlKey modifier is *not* being used in conjunction with + * the altKey modifier. If they are combined, the result is an `altGraph` + * key modifier, which should not be handled by this set of key bindings. + */ + isCtrlKeyCommand(e: SyntheticKeyboardEvent): boolean; + + isOptionKeyCommand(e: SyntheticKeyboardEvent): boolean; + + hasCommandModifier(e: SyntheticKeyboardEvent): boolean; + } + + /** + * Retrieve a bound key command for the given event. + */ + function getDefaultKeyBinding(e: SyntheticKeyboardEvent): DraftEditorCommand; + function getDefaultKeyBinding(e: SyntheticKeyboardEvent): string; } - - interface EntityInstance { - getData(): any, - getKey(): string, - getMutability(): string - } - - interface BlockMapBuilder { - createFromArray(blocks: Array): BlockMap - } - - interface CharacterMetadata { - create(config?: any): CharacterMetadata, - - applyStyle(record: CharacterMetadata, - style: string): CharacterMetadata, - - removeStyle(record: CharacterMetadata, - style: string): CharacterMetadata, - - applyEntity(record: CharacterMetadata, - entityKey?: string): CharacterMetadata, - - getStyle(): any, - hasStyle(style: string): boolean, - - getEntity(): string - } - - interface IContentBlock { - new(draftContentBlock: any): ContentBlock; - } - interface ContentBlock { - key: string, - type: string, - text: string, - characterList: any, - depth: number, - - getKey(): string, - getType(): string, - getText(): string, - getCharacterList(): any, - getLength(): number, - getDepth(): number, - getInlineStyleAt(offset: number): any, - getEntityAt(offset: number): string, - findStyleRanges(filterFn: Function, callback: Function): void, - findEntityRanges(filterFn: Function, callback: Function): void - - } - - interface ContentState { - createFromText(text: string): ContentState, - createFromBlockArray(blocks: Array): ContentState, - - getBlockMap(): BlockMap, - getSelectionBefore(): SelectionState, - getSelectionAfter(): SelectionState, - - getBlockForKey(key: string): ContentBlock, - getKeyBefore(key: string): string, - getKeyAfter(key: string): string, - - getBlockBefore(key: string): ContentBlock, - getBlockAfter(key: string): ContentBlock, - - getBlocksAsArray(): Array, - - getPlainText(): string, - hasText(): boolean, - - set(key: string, value: any): ContentState, - toJS(): any - } - - interface ISelectionState { - new(draftSelectionState: any): SelectionState; - createEmpty(blockKey: string): SelectionState; - } - - interface SelectionState { - getStartKey(): string, - getStartOffset(): number, - getEndKey(): string, - getEndOffset(): number, - getAnchorKey(): string, - getAnchorOffset(): number, - getFocusKey(): string, - getFocusOffset(): number, - - getIsBackward(): boolean, - getHasFocus(): boolean, - isCollapsed(): boolean, - - hasEdgeWithin(blockKey: string, start: number, end: number): boolean, - serialize(): string, - - get(key: string): any, - set(key: string, value: any): SelectionState - } - - interface BlockMap { - get(key: string): ContentBlock, - set(key: string, value: any): BlockMap, - delete(key: string): BlockMap, - find(cb: any): ContentBlock - } - - interface Modifier { - replaceText(contentState: ContentState, - rangeToReplace: SelectionState, - text: string, - inlineStyle?: any, - entityKey?: string): ContentState, - - insertText(contentState: ContentState, - targetRange: SelectionState, - text: string, - inlineStyle?: any, - entityKey?: string): ContentState, - - moveText(contentState: ContentState, - removalRange: SelectionState, - targetRange: SelectionState): ContentState, - - replaceWithFragment(contentState: ContentState, - targetRange: SelectionState, - fragment: BlockMap): ContentState, - - removeRange(contentState: ContentState, - rangeToRemove: SelectionState, - removalDirection: string): ContentState, - - splitBlock(contentState: ContentState, - selectionState: SelectionState): ContentState, - - applyInlineStyle(contentState: ContentState, - selectionState: SelectionState, - inlineStyle: string): ContentState, - - removeInlineStyle(contentState: ContentState, - selectionState: SelectionState, - inlineStyle: string): ContentState, - - setBlockType(contentState: ContentState, - selectionState: SelectionState, - blockType: string): ContentState, - - applyEntity(contentState: ContentState, - selectionState: SelectionState, - entityKey: string): ContentState - } - - interface RichUtils { - currentBlockContainsLink(editorState: EditorState): boolean, - getCurrentBlockType(editor: EditorState): string, - handleKeyCommand(editorState: EditorState, command: string): any, - insertSoftNewline(editorState: EditorState): EditorState, - onBackspace(editorState: EditorState): EditorState, - onDelete(editorState: EditorState): EditorState, - onTab(event: Event, editorState: EditorState, maxDepth: number): EditorState, - toggleBlockType(editorState: EditorState, blockType: string): EditorState, - toggleCode(editorState: EditorState): EditorState, - toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState, - tryToRemoveBlockStyle(editorState: EditorState): EditorState - } - - interface EditorProps { - editorState: EditorState, - onChange(editorState: EditorState): void, - - placeholder?: string, - textAlignment?: any, - blockRendererFn?: (ContentBlock: ContentBlock) => any, - blockStyleFn?: (ContentBlock: ContentBlock) => string, - customStyleMap?: any, - - readOnly?: boolean, - spellCheck?: boolean, - stripPastedStyles?: boolean, - - handleReturn?: (e: any) => boolean, - handleKeyCommand?: (command: string) => boolean, - handleBeforeInput?: (chars: string) => boolean, - handlePastedFiles?: (files: Array) => boolean, - handleDroppedFiles?: (selection: SelectionState, files: Array) => boolean, - handleDrop?: (selection: SelectionState, dataTransfer: any, isInternal: any) => boolean, - - onEscape?: (e: any) => void, - onTab?: (e: any) => void, - onUpArrow?: (e: any) => void, - onDownArrow?: (e: any) => void, - - suppressContentEditableWarning?: any, - - onBlur?: (e: any) => void, - onFocus?: (e: any) => void - } - - interface Editor { - props: EditorProps - state: any, - refs: any, - context: any, - setState(): any, - render(): any, - forceUpdate(): any - } - - var Editor: IEditor; - var EditorState: EditorState; - - var CompositeDecorator: CompositeDecorator; - var Entity: Entity; - var EntityInstance: EntityInstance; - - var BlockMapBuilder: BlockMapBuilder; - var CharacterMetadata: CharacterMetadata; - var ContentBlock: IContentBlock; - var ContentState: ContentState; - var SelectionState: ISelectionState; - - var Modifier: Modifier; - var RichUtils: RichUtils; - - function convertFromRaw(rawState: any): Array; - - function convertToRaw(contentState: ContentState): any; - - function genKey(): string } - export = Draft; + namespace Model { + namespace Constants { + /** + * A set of editor commands that may be invoked by keyboard commands or UI + * controls. These commands should map to operations that modify content or + * selection state and update the editor state accordingly. + */ + type DraftEditorCommand = ( + /** + * Self-explanatory. + */ + "undo" | + "redo" | + /** + * Perform a forward deletion. + */ + "delete" | + + /** + * Perform a forward deletion to the next word boundary after the selection. + */ + "delete-word" | + + /** + * Perform a backward deletion. + */ + "backspace" | + + /** + * Perform a backward deletion to the previous word boundary before the + * selection. + */ + "backspace-word" | + + /** + * Perform a backward deletion to the beginning of the current line. + */ + "backspace-to-start-of-line" | + + /** + * Toggle styles. Commands may be intepreted to modify inline text ranges + * or block types. + */ + "bold" | + "italic" | + "underline" | + "code" | + + /** + * Split a block in two. + */ + "split-block" | + + /** + * Self-explanatory. + */ + "transpose-characters" | + "move-selection-to-start-of-block" | + "move-selection-to-end-of-block" | + + /** + * Commands to support the "secondary" clipboard provided by certain + * browsers and operating systems. + */ + "secondary-cut" | + "secondary-paste" + ); + + /** + * A type that allows us to avoid passing boolean arguments + * around to indicate whether a drag type is internal or external. + */ + type DraftDragType = "internal" | "external"; + + /** + * The list of default valid block types. + */ + type DraftBlockType = ( + "unstyled" | + "paragraph" | + "header-one" | + "header-two" | + "header-three" | + "header-four" | + "header-five" | + "header-six" | + "unordered-list-item" | + "ordered-list-item" | + "blockquote" | + "code-block" | + "atomic" + ); + + /** + * A type that allows us to avoid passing boolean arguments + * around to indicate whether a deletion is forward or backward. + */ + type DraftRemovalDirection = "backward" | "forward"; + } + + namespace Decorators { + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + + /** + * An interface for document decorator classes, allowing the creation of + * custom decorator classes. + * + * See `CompositeDraftDecorator` for the most common use case. + */ + interface DraftDecoratorType { + /** + * Given a `ContentBlock`, return an immutable List of decorator keys. + */ + getDecorations(block: ContentBlock): Immutable.List; + + /** + * Given a decorator key, return the component to use when rendering + * this decorated range. + */ + getComponentForKey(key: string): Function; + + /** + * Given a decorator key, optionally return the props to use when rendering + * this decorated range. + */ + getPropsForKey(key: string): any; + } + + /** + * A DraftDecorator is a strategy-component pair intended for use when + * rendering content. + * + * - A "strategy": A function that accepts a ContentBlock object and + * continuously executes a callback with start/end values corresponding to + * relevant matches in the document text. For example, getHashtagMatches + * uses a hashtag regex to find hashtag strings in the block, and + * for each hashtag match, executes the callback with start/end pairs. + * + * - A "component": A React component that will be used to render the + * "decorated" section of text. + * + * - "props": Props to be passed into the React component that will be used. + */ + interface DraftDecorator { + strategy: (block: ContentBlock, callback: (start: number, end: number) => void) => void; + component: Function; + props?: Object; + } + + /** + * A CompositeDraftDecorator traverses through a list of DraftDecorator + * instances to identify sections of a ContentBlock that should be rendered + * in a "decorated" manner. For example, hashtags, mentions, and links may + * be intended to stand out visually, be rendered as anchors, etc. + * + * The list of decorators supplied to the constructor will be used in the + * order they are provided. This allows the caller to specify a priority for + * string matching, in case of match collisions among decorators. + * + * For instance, I may have a link with a `#` in its text. Though this section + * of text may match our hashtag decorator, it should not be treated as a + * hashtag. I should therefore list my link DraftDecorator + * before my hashtag DraftDecorator when constructing this composite + * decorator instance. + * + * Thus, when a collision like this is encountered, the earlier match is + * preserved and the new match is discarded. + */ + class CompositeDraftDecorator { + constructor(decorators: Array); + + getDecorations(block: ContentBlock): Immutable.List; + getComponentForKey(key: string): Function; + getPropsForKey(key: string): Object; + } + } + + namespace Encoding { + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + import ContentState = Draft.Model.ImmutableData.ContentState; + + import DraftBlockRenderMap = Draft.Component.Base.DraftBlockRenderMap; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + + import DraftEntityType = Draft.Model.Entity.DraftEntityType; + import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + + /** + * A plain object representation of an entity attribution. + * + * The `key` value corresponds to the key of the entity in the `entityMap` of + * a `ComposedText` object, not for use with `DraftEntity.get()`. + */ + interface EntityRange { + key: number, + offset: number, + length: number, + } + + /** + * A plain object representation of an inline style range. + */ + interface InlineStyleRange { + style: string; + offset: number; + length: number; + } + + /** + * A plain object representation of an EntityInstance. + */ + interface RawDraftEntity { + type: DraftEntityType; + mutability: DraftEntityMutability; + data: { [key: string]: any }; + } + + /** + * A plain object representation of a ContentBlock, with all style and entity + * attribution repackaged as range objects. + */ + interface RawDraftContentBlock { + key: string; + type: DraftBlockType; + text: string; + depth: number; + inlineStyleRanges: Array; + entityRanges: Array; + data?: Object; + } + + /** + * A type that represents a composed document as vanilla JavaScript objects, + * with all styles and entities represented as ranges. Corresponding entity + * objects are packaged as objects as well. + * + * This object is especially useful when sending the document state to the + * server for storage, as its representation is more concise than our + * immutable objects. + */ + interface RawDraftContentState { + blocks: Array; + entityMap: { [key: string]: RawDraftEntity }; + } + + function convertFromHTMLtoContentBlocks(html: string, DOMBuilder: Function, blockRenderMap?: DraftBlockRenderMap): Array; + function convertFromRawToDraftState(rawState: RawDraftContentState): ContentState; + function convertFromDraftStateToRaw(contentState: ContentState): RawDraftContentState; + } + + namespace Entity { + type ComposedEntityType = "LINK" | "TOKEN" | "PHOTO"; + type DraftEntityType = string | ComposedEntityType; + + /** + * An enum representing the possible "mutability" options for an entity. + * This refers to the behavior that should occur when inserting or removing + * characters in a text range with an entity applied to it. + * + * `MUTABLE`: + * The text range can be modified freely. Generally used in cases where + * the text content and the entity do not necessarily have a direct + * relationship. For instance, the text and URI for a link may be completely + * different. The user is allowed to edit the text as needed, and the entity + * is preserved and applied to any characters added within the range. + * + * `IMMUTABLE`: + * Not to be confused with immutable data structures used to represent the + * state of the editor. Immutable entity ranges cannot be modified in any + * way. Adding characters within the range will remove the entity from the + * entire range. Deleting characters will delete the entire range. Example: + * Facebook Page mentions. + * + * `SEGMENTED`: + * Segmented entities allow the removal of partial ranges of text, as + * separated by a delimiter. Adding characters wihin the range will remove + * the entity from the entire range. Deleting characters within a segmented + * entity will delete only the segments affected by the deletion. Example: + * Facebook User mentions. + */ + type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; + + /** + * A "document entity" is an object containing metadata associated with a + * piece of text in a ContentBlock. + * + * For example, a `link` entity might include a `uri` property. When a + * ContentBlock is rendered in the browser, text that refers to that link + * entity may be rendered as an anchor, with the `uri` as the href value. + * + * In a ContentBlock, every position in the text may correspond to zero + * or one entities. This correspondence is tracked using a key string, + * generated via DraftEntity.create() and used to obtain entity metadata + * via DraftEntity.get(). + */ + class DraftEntity { + /** + * Create a DraftEntityInstance and store it for later retrieval. + * + * A random key string will be generated and returned. This key may + * be used to track the entity's usage in a ContentBlock, and for + * retrieving data about the entity at render time. + */ + static create(type: DraftEntityType, mutability: DraftEntityMutability, data?: Object): string; + + /** + * Add an existing DraftEntityInstance to the DraftEntity map. This is + * useful when restoring instances from the server. + */ + static add(instance: DraftEntityInstance): string; + + /** + * Retrieve the entity corresponding to the supplied key string. + */ + static get(key: string): DraftEntityInstance; + + /** + * Entity instances are immutable. If you need to update the data for an + * instance, this method will merge your data updates and return a new + * instance. + */ + static mergeData(key: string, toMerge: { [key: string]: any }): DraftEntityInstance; + + /** + * Completely replace the data for a given instance. + */ + static replaceData(key: string, newData: { [key: string]: any }): DraftEntityInstance; + } + + /** + * An instance of a document entity, consisting of a `type` and relevant + * `data`, metadata about the entity. + * + * For instance, a "link" entity might provide a URI, and a "mention" + * entity might provide the mentioned user's ID. These pieces of data + * may be used when rendering the entity as part of a ContentBlock DOM + * representation. For a link, the data would be used as an href for + * the rendered anchor. For a mention, the ID could be used to retrieve + * a hovercard. + */ + interface DraftEntityInstance { + getType(): DraftEntityType; + getMutability(): DraftEntityMutability; + getData(): any; + } + } + + namespace ImmutableData { + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; + + type DraftInlineStyle = Immutable.OrderedSet; + type BlockMap = Immutable.OrderedMap; + + var Record: Immutable.Record.Class; + + interface DraftBlockRenderConfig { + element: string; + wrapper?: React.ReactElement; + } + + class EditorState extends Record { + static createEmpty(decorator?: DraftDecoratorType): EditorState; + static createWithContent(contentState: ContentState, decorator?: DraftDecoratorType): EditorState; + static create(config: Object): EditorState; + static set(editorState: EditorState, put: Object): EditorState; + + /** + * Incorporate native DOM selection changes into the EditorState. This + * method can be used when we simply want to accept whatever the DOM + * has given us to represent selection, and we do not need to re-render + * the editor. + * + * To forcibly move the DOM selection, see `EditorState.forceSelection`. + */ + static acceptSelection(editorState: EditorState, selection: SelectionState): EditorState; + + /** + * At times, we need to force the DOM selection to be where we + * need it to be. This can occur when the anchor or focus nodes + * are non-text nodes, for instance. In this case, we want to trigger + * a re-render of the editor, which in turn forces selection into + * the correct place in the DOM. The `forceSelection` method + * accomplishes this. + * + * This method should be used in cases where you need to explicitly + * move the DOM selection from one place to another without a change + * in ContentState. + */ + static forceSelection(editorState: EditorState, selection: SelectionState): EditorState; + + /** + * Move selection to the end of the editor without forcing focus. + */ + static moveSelectionToEnd(editorState: EditorState): EditorState; + + /** + * Force focus to the end of the editor. This is useful in scenarios + * where we want to programmatically focus the input and it makes sense + * to allow the user to continue working seamlessly. + */ + static moveFocusToEnd(editorState: EditorState): EditorState; + + /** + * Push the current ContentState onto the undo stack if it should be + * considered a boundary state, and set the provided ContentState as the + * new current content. + */ + static push(editorState: EditorState, contentState: ContentState, changeType: EditorChangeType): EditorState; + + /** + * Make the top ContentState in the undo stack the new current content and + * push the current content onto the redo stack. + */ + static undo(editorState: EditorState): EditorState; + + /** + * Make the top ContentState in the redo stack the new current content and + * push the current content onto the undo stack. + */ + static redo(editorState: EditorState): EditorState; + + toJS(): Object; + getAllowUndo(): boolean; + getCurrentContent(): ContentState; + getUndoStack(): Immutable.Stack; + getRedoStack(): Immutable.Stack; + getSelection(): SelectionState; + getDecorator(): DraftDecoratorType; + isInCompositionMode(): boolean; + mustForceSelection(): boolean; + getNativelyRenderedContent(): ContentState; + getLastChangeType(): EditorChangeType; + + /** + * While editing, the user may apply inline style commands with a collapsed + * cursor, intending to type text that adopts the specified style. In this + * case, we track the specified style as an "override" that takes precedence + * over the inline style of the text adjacent to the cursor. + * + * If null, there is no override in place. + */ + getInlineStyleOverride(): DraftInlineStyle; + + static setInlineStyleOverride(editorState: EditorState, inlineStyleOverride: DraftInlineStyle): EditorState; + + /** + * Get the appropriate inline style for the editor state. If an + * override is in place, use it. Otherwise, the current style is + * based on the location of the selection state. + */ + getCurrentInlineStyle(): DraftInlineStyle; + + getBlockTree(blockKey: string): Immutable.List; + isSelectionAtStartOfContent(): boolean; + isSelectionAtEndOfContent(): boolean; + getDirectionMap(): Immutable.OrderedMap; + } + + class ContentBlock extends Record { + getKey(): string; + + getType(): DraftBlockType; + getType(): string; + + getText(): string; + getCharacterList(): Immutable.List; + getLength(): number; + getDepth(): number; + getData(): Immutable.Map; + getInlineStyleAt(offset: number): DraftInlineStyle; + getEntityAt(offset: number): string; + + /** + * Execute a callback for every contiguous range of styles within the block. + */ + findStyleRanges(filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void): void; + + /** + * Execute a callback for every contiguous range of entities within the block. + */ + findEntityRanges(filterFn: (value: CharacterMetadata) => boolean, callback: (start: number, end: number) => void): void; + } + + class ContentState extends Record { + static createFromBlockArray(blocks: Array): ContentState; + static createFromText(text: string, delimiter?: string): ContentState; + + getBlockMap(): BlockMap; + getSelectionBefore(): SelectionState; + getSelectionAfter(): SelectionState; + getBlockForKey(key: string): ContentBlock; + + getKeyBefore(key: string): string; + getKeyAfter(key: string): string; + getBlockAfter(key: string): ContentBlock; + getBlockBefore(key: string): ContentBlock; + + getBlocksAsArray(): Array; + getFirstBlock(): ContentBlock; + getLastBlock(): ContentBlock; + getPlainText(delimiter?: string): string; + hasText(): boolean; + } + + class SelectionState extends Record { + static createEmpty(key: string): SelectionState; + + serialize(): string; + getAnchorKey(): string; + getAnchorOffset(): number; + getFocusKey(): string; + getFocusOffset(): number; + getIsBackward(): boolean; + getHasFocus(): boolean; + /** + * Return whether the specified range overlaps with an edge of the + * SelectionState. + */ + hasEdgeWithin(blockKey: string, start: number, end: number): boolean; + isCollapsed(): boolean; + getStartKey(): string; + getStartOffset(): number; + getEndKey(): string; + getEndOffset(): number; + } + + class CharacterMetadata { + static applyStyle(record: CharacterMetadata, style: string): CharacterMetadata; + static removeStyle(record: CharacterMetadata, style: string): CharacterMetadata; + static applyEntity(record: CharacterMetadata, entityKey: string): CharacterMetadata; + static applyEntity(record: CharacterMetadata): CharacterMetadata; + /** + * Use this function instead of the `CharacterMetadata` constructor. + * Since most content generally uses only a very small number of + * style/entity permutations, we can reuse these objects as often as + * possible. + */ + static create(config?: CharacterMetadataConfig): CharacterMetadata; + static create(): CharacterMetadata; + + getStyle(): DraftInlineStyle; + getEntity(): string; + hasStyle(style: string): boolean; + } + + interface CharacterMetadataConfig { + style?: DraftInlineStyle; + entity?: string; + } + + type EditorChangeType = ( + "adjust-depth" | + "apply-entity" | + "backspace-character" | + "change-block-data" | + "change-block-type" | + "change-inline-style" | + "delete-character" | + "insert-characters" | + "insert-fragment" | + "redo" | + "remove-range" | + "spellcheck-change" | + "split-block" | + "undo" + ) + + interface BlockMapBuilder { + createFromArray(blocks: Array): BlockMap; + } + + const DefaultDraftBlockRenderMap: Immutable.Map; + const DefaultDraftInlineStyle: Immutable.Map; + } + + namespace Keys { + function generateRandomKey(): string; + } + + namespace Modifier { + import EditorState = Draft.Model.ImmutableData.EditorState; + import ContentState = Draft.Model.ImmutableData.ContentState; + import SelectionState = Draft.Model.ImmutableData.SelectionState; + + import BlockMap = Draft.Model.ImmutableData.BlockMap; + import DraftInlineStyle = Draft.Model.ImmutableData.DraftInlineStyle; + + import DraftRemovalDirection = Draft.Model.Constants.DraftRemovalDirection; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + + import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; + + type URI = any; + + interface AtomicBlockUtils { + insertAtomicBlock(editorState: EditorState, entityKey: string, character: string): EditorState; + } + + /** + * `DraftModifier` provides a set of convenience methods that apply + * modifications to a `ContentState` object based on a target `SelectionState`. + * + * Any change to a `ContentState` should be decomposable into a series of + * transaction functions that apply the required changes and return output + * `ContentState` objects. + * + * These functions encapsulate some of the most common transaction sequences. + */ + class DraftModifier { + static replaceText(contentState: ContentState, rangeToReplace: SelectionState, text: string, inlineStyle?: DraftInlineStyle, entityKey?: string): ContentState; + static insertText(contentState: ContentState, targetRange: SelectionState, text: string, inlineStyle?: DraftInlineStyle, entityKey?: string): ContentState; + static moveText(contentState: ContentState, removalRange: SelectionState, targetRange: SelectionState): ContentState; + static replaceWithFragment(contentState: ContentState, targetRange: SelectionState, fragment: BlockMap): ContentState; + + static removeRange(contentState: ContentState, rangeToRemove: SelectionState, removalDirection: DraftRemovalDirection): ContentState; + + static splitBlock(contentState: ContentState, selectionState: SelectionState): ContentState; + static applyInlineStyle(contentState: ContentState, selectionState: SelectionState, inlineStyle: string): ContentState; + static removeInlineStyle(contentState: ContentState, selectionState: SelectionState, inlineStyle: string): ContentState; + + static setBlockType(contentState: ContentState, selectionState: SelectionState, blockType: DraftBlockType): ContentState; + static setBlockType(contentState: ContentState, selectionState: SelectionState, blockType: string): ContentState; + + static setBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; + static mergeBlockData(contentState: ContentState, selectionState: SelectionState, blockData: Immutable.Map): ContentState; + static applyEntity(contentState: ContentState, selectionState: SelectionState, entityKey: string): ContentState; + } + + class RichTextEditorUtil { + static currentBlockContainsLink(editorState: EditorState): boolean; + static getCurrentBlockType(editorState: EditorState): DraftBlockType; + static getCurrentBlockType(editorState: EditorState): string; + static getDataObjectForLinkURL(uri: URI): Object; + + static handleKeyCommand(editorState: EditorState, command: DraftEditorCommand): EditorState; + static handleKeyCommand(editorState: EditorState, command: string): EditorState; + + static insertSoftNewline(editorState: EditorState): EditorState; + + /** + * For collapsed selections at the start of styled blocks, backspace should + * just remove the existing style. + */ + static onBackspace(editorState: EditorState): EditorState; + static onDelete(editorState: EditorState): EditorState; + static onTab(event: SyntheticKeyboardEvent, editorState: EditorState, maxDepth: number): EditorState; + + static toggleBlockType(editorState: EditorState, blockType: DraftBlockType): EditorState; + static toggleBlockType(editorState: EditorState, blockType: string): EditorState; + + static toggleCode(editorState: EditorState): EditorState; + + /** + * Toggle the specified inline style for the selection. If the + * user's selection is collapsed, apply or remove the style for the + * internal state. If it is not collapsed, apply the change directly + * to the document state. + */ + static toggleInlineStyle(editorState: EditorState, inlineStyle: string): EditorState; + + static toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState; + + /** + * When a collapsed cursor is at the start of an empty styled block, allow + * certain key commands (newline, backspace) to simply change the + * style of the block instead of the default behavior. + */ + static tryToRemoveBlockStyle(editorState: EditorState): ContentState; + } + } + } } + +declare module "draft-js" { + import Editor = Draft.Component.Base.DraftEditor; + import EditorBlock = Draft.Component.Components.DraftEditorBlock; + import EditorState = Draft.Model.ImmutableData.EditorState; + + import CompositeDecorator = Draft.Model.Decorators.CompositeDraftDecorator; + import Entity = Draft.Model.Entity.DraftEntity; + import EntityInstance = Draft.Model.Entity.DraftEntityInstance; + + import BlockMapBuilder = Draft.Model.ImmutableData.BlockMapBuilder; + import CharacterMetadata = Draft.Model.ImmutableData.CharacterMetadata; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; + import ContentState = Draft.Model.ImmutableData.ContentState; + import SelectionState = Draft.Model.ImmutableData.SelectionState; + + import AtomicBlockUtils = Draft.Model.Modifier.AtomicBlockUtils; + import KeyBindingUtil = Draft.Component.Utils.KeyBindingUtil; + import Modifier = Draft.Model.Modifier.DraftModifier; + import RichUtils = Draft.Model.Modifier.RichTextEditorUtil; + + import DefaultDraftBlockRenderMap = Draft.Model.ImmutableData.DefaultDraftBlockRenderMap; + import DefaultDraftInlineStyle = Draft.Model.ImmutableData.DefaultDraftInlineStyle; + + import convertFromHTML = Draft.Model.Encoding.convertFromHTMLtoContentBlocks; + import convertFromRaw = Draft.Model.Encoding.convertFromRawToDraftState; + import convertToRaw = Draft.Model.Encoding.convertFromDraftStateToRaw; + import genKey = Draft.Model.Keys.generateRandomKey; + import getDefaultKeyBinding = Draft.Component.Utils.getDefaultKeyBinding; + import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRect; + + export { + Editor, + EditorBlock, + EditorState, + + CompositeDecorator, + Entity, + EntityInstance, + + BlockMapBuilder, + CharacterMetadata, + ContentBlock, + ContentState, + SelectionState, + + AtomicBlockUtils, + KeyBindingUtil, + Modifier, + RichUtils, + + DefaultDraftBlockRenderMap, + DefaultDraftInlineStyle, + + convertFromHTML, + convertFromRaw, + convertToRaw, + genKey, + getDefaultKeyBinding, + getVisibleSelectionRect + }; +} \ No newline at end of file From 9f0e62c22fe83800d314291e8c7457ba6d76687b Mon Sep 17 00:00:00 2001 From: Pedro Poveda Date: Thu, 7 Jul 2016 16:08:42 -0400 Subject: [PATCH 0028/1255] added Media Type --- react-bootstrap/react-bootstrap-tests.tsx | 15 ++++++- react-bootstrap/react-bootstrap.d.ts | 55 +++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/react-bootstrap/react-bootstrap-tests.tsx b/react-bootstrap/react-bootstrap-tests.tsx index 439fe1b96b..2712853f28 100644 --- a/react-bootstrap/react-bootstrap-tests.tsx +++ b/react-bootstrap/react-bootstrap-tests.tsx @@ -7,7 +7,7 @@ // -------------------------------------------------------------------------------- import * as React from 'react'; import { Component, CSSProperties } from 'react'; -import { Button, ButtonToolbar, Modal, Well, ButtonGroup, DropdownButton, MenuItem, Panel, ListGroup, ListGroupItem, Accordion, Tooltip, OverlayTrigger, Popover, ProgressBar, Nav, NavItem, Navbar, NavDropdown, Tabs, Tab, Pager, PageItem, Pagination, Alert, Carousel, CarouselItem, Grid, Row, Col, Thumbnail, Image, Label, Badge, Jumbotron, PageHeader, Glyphicon, Table, Input, ButtonInput, Form, FormGroup, ControlLabel, FormControl, HelpBlock, Radio, Checkbox } from 'react-bootstrap'; +import { Button, ButtonToolbar, Modal, Well, ButtonGroup, DropdownButton, MenuItem, Panel, ListGroup, ListGroupItem, Accordion, Tooltip, OverlayTrigger, Popover, ProgressBar, Nav, NavItem, Navbar, NavDropdown, Tabs, Tab, Pager, PageItem, Pagination, Alert, Carousel, CarouselItem, Grid, Row, Col, Thumbnail, Image, Label, Badge, Jumbotron, PageHeader, Glyphicon, Table, Input, ButtonInput, Form, FormGroup, ControlLabel, FormControl, HelpBlock, Radio, Checkbox, Media } from 'react-bootstrap'; export class ReactBootstrapTest extends Component { @@ -965,6 +965,19 @@ export class ReactBootstrapTest extends Component { + +
+ + + Image + + + Top aligned media +

Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.

+

Donec sed odio dui. Nullam quis risus eget urna mollis ornare vel eu leo. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

+
+
+
); } diff --git a/react-bootstrap/react-bootstrap.d.ts b/react-bootstrap/react-bootstrap.d.ts index 8d75e82f93..443232ce57 100644 --- a/react-bootstrap/react-bootstrap.d.ts +++ b/react-bootstrap/react-bootstrap.d.ts @@ -1071,5 +1071,60 @@ declare module "react-bootstrap" { } class Position extends React.Component { } + // + interface MediaLeftProps { + align?: string; + } + type MediaLeft = React.ClassicComponent; + var MediaLeft: React.ClassicComponentClass; + + // + interface MediaRightProps { + align?: string; + } + type MediaRight = React.ClassicComponent; + var MediaRight: React.ClassicComponentClass; + + // + interface MediaHeadingProps { + componentClass?: React.ReactType; + } + type MediaHeading = React.ClassicComponent; + var MediaHeading: React.ClassicComponentClass; + + // + interface MediaBodyProps { + componentClass?: React.ReactType; + } + type MediaBody = React.ClassicComponent; + var MediaBody: React.ClassicComponentClass; + + // + interface MediaListProps { + } + type MediaList = React.ClassicComponent; + var MediaList: React.ClassicComponentClass; + + // + interface MediaListItemProps { + componentClass?: React.ReactType; + } + type MediaListItem = React.ClassicComponent; + var MediaListItem: React.ClassicComponentClass; + + // + interface MediaProps extends React.HTMLProps { + componentClass?: React.ReactType; + } + interface MediaClass extends React.ClassicComponentClass { + Left?: typeof MediaLeft; + Right?: typeof MediaRight; + Heading?: typeof MediaHeading; + Body?: typeof MediaBody; + List?: typeof MediaList; + ListItem?: typeof MediaListItem; + } + type Media = React.ClassicComponent; + var Media: MediaClass; } From 5ea018ec971715eef2e9de088511eb2f625ded1c Mon Sep 17 00:00:00 2001 From: Pedro Poveda Date: Thu, 7 Jul 2016 17:03:46 -0400 Subject: [PATCH 0029/1255] fixed indenting and made MediaClass attributes mandatory --- react-bootstrap/react-bootstrap.d.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/react-bootstrap/react-bootstrap.d.ts b/react-bootstrap/react-bootstrap.d.ts index 443232ce57..04da49e1b9 100644 --- a/react-bootstrap/react-bootstrap.d.ts +++ b/react-bootstrap/react-bootstrap.d.ts @@ -1071,7 +1071,7 @@ declare module "react-bootstrap" { } class Position extends React.Component { } - // + // interface MediaLeftProps { align?: string; } @@ -1117,12 +1117,12 @@ declare module "react-bootstrap" { componentClass?: React.ReactType; } interface MediaClass extends React.ClassicComponentClass { - Left?: typeof MediaLeft; - Right?: typeof MediaRight; - Heading?: typeof MediaHeading; - Body?: typeof MediaBody; - List?: typeof MediaList; - ListItem?: typeof MediaListItem; + Left: typeof MediaLeft; + Right: typeof MediaRight; + Heading: typeof MediaHeading; + Body: typeof MediaBody; + List: typeof MediaList; + ListItem: typeof MediaListItem; } type Media = React.ClassicComponent; var Media: MediaClass; From 1e92c152ee1b7af9b39f01789de37e2e463fd0de Mon Sep 17 00:00:00 2001 From: Cao Jiannan Date: Sat, 9 Jul 2016 02:51:18 +0800 Subject: [PATCH 0030/1255] enhance IRouter merge use into just one case --- .../express-serve-static-core.d.ts | 117 ++++++++---------- 1 file changed, 55 insertions(+), 62 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 707f506e2a..daa7b6cd0f 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Express 4.x +// Type definitions for Express 4.x // Project: http://expressjs.com // Definitions by: Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,26 +17,33 @@ declare namespace Express { declare module "express-serve-static-core" { import * as http from "http"; - type RequestHandlerParams = RequestHandler | RequestHandler[]; - - interface IRoute { - path: string; - stack: any; - all(...handler: RequestHandlerParams[]): IRoute; - get(...handler: RequestHandlerParams[]): IRoute; - post(...handler: RequestHandlerParams[]): IRoute; - put(...handler: RequestHandlerParams[]): IRoute; - delete(...handler: RequestHandlerParams[]): IRoute; - patch(...handler: RequestHandlerParams[]): IRoute; - options(...handler: RequestHandlerParams[]): IRoute; - head(...handler: RequestHandlerParams[]): IRoute; + interface NextFunction { + (err?: any): void; } + + interface RequestHandler { + (req: Request, res: Response, next: NextFunction): any; + } + + interface ErrorRequestHandler { + (err: any, req: Request, res: Response, next: NextFunction): any; + } + + type PathParams = string | RegExp | (string | RegExp)[] + + type RequestHandlerParams = RequestHandler | ErrorRequestHandler interface IRouterMatcher { - (name: string | RegExp, ...handlers: RequestHandlerParams[]): T; + (path: PathParams, ...handlers: RequestHandler[]): T; + (path: PathParams, ...handlers: RequestHandlerParams[]): T; } - interface IRouter extends RequestHandler { + interface IRouterHandler { + (...handlers: RequestHandler[]): T; + (...handlers: RequestHandlerParams[]): T; + } + + interface IRouter extends RequestHandler { /** * Map the given param placeholder `name`(s) to the given callback(s). * @@ -66,11 +73,11 @@ declare module "express-serve-static-core" { * @param name * @param fn */ - param(name: string, handler: RequestParamHandler): T; - param(name: string, matcher: RegExp): T; - param(name: string, mapper: (param: any) => any): T; + param(name: string | string[], handler: RequestParamHandler): this; + param(name: string | string[], matcher: RegExp): this; + param(name: string | string[], mapper: (param: any) => any): this; // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): T; + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; /** * Special-cased "all" method, applying the given route `path`, @@ -79,30 +86,34 @@ declare module "express-serve-static-core" { * @param path * @param fn */ - all: IRouterMatcher; - get: IRouterMatcher; - post: IRouterMatcher; - put: IRouterMatcher; - delete: IRouterMatcher; - patch: IRouterMatcher; - options: IRouterMatcher; - head: IRouterMatcher; + all: IRouterMatcher; + get: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + delete: IRouterMatcher; + patch: IRouterMatcher; + options: IRouterMatcher; + head: IRouterMatcher; + + use: IRouterHandler & IRouterMatcher; - route(path: string | RegExp): IRoute; - - use(...handler: RequestHandlerParams[]): T; - use(handler: ErrorRequestHandler | RequestHandlerParams): T; - use(path: string, ...handler: RequestHandlerParams[]): T; - use(path: string, handler: ErrorRequestHandler | RequestHandlerParams): T; - use(path: string[], ...handler: RequestHandlerParams[]): T; - use(path: string[], handler: ErrorRequestHandler): T; - use(path: RegExp, ...handler: RequestHandlerParams[]): T; - use(path: RegExp, handler: ErrorRequestHandler): T; - use(path: string, router: Router): T; + route(prefix: PathParams): IRoute; } + interface IRoute { + path: string; + stack: any; + all: IRouterHandler; + get: IRouterHandler; + post: IRouterHandler; + put: IRouterHandler; + delete: IRouterHandler; + patch: IRouterHandler; + options: IRouterHandler; + head: IRouterHandler; + } - export interface Router extends IRouter { } + export interface Router extends IRouter { } interface CookieOptions { maxAge?: number; @@ -782,33 +793,24 @@ declare module "express-serve-static-core" { locals: any; charset: string; - + /** * Adds the field to the Vary response header, if it is not there already. * Examples: - * + * * res.vary('User-Agent').render('docs'); * */ vary(field: string): Response; } - interface NextFunction { - (err?: any): void; - } - - interface ErrorRequestHandler { - (err: any, req: Request, res: Response, next: NextFunction): any; - } - - interface Handler extends RequestHandler { } interface RequestParamHandler { (req: Request, res: Response, next: NextFunction, param: any): any; } - interface Application extends IRouter, Express.Application { + interface Application extends IRouter, Express.Application { /** * Initialize the server. * @@ -869,10 +871,7 @@ declare module "express-serve-static-core" { * @param val */ set(setting: string, val: any): Application; - get: { - (name: string): any; // Getter - (name: string | RegExp, ...handlers: RequestHandlerParams[]): Application; - }; + get: {(name: string): any;} & IRouterMatcher; /** * Return the app's absolute pathname @@ -1017,8 +1016,6 @@ declare module "express-serve-static-core" { listen(path: string, callback?: Function): http.Server; listen(handle: any, listeningListener?: Function): http.Server; - route(path: string | RegExp): IRoute; - router: string; settings: any; @@ -1066,8 +1063,4 @@ declare module "express-serve-static-core" { response: Response; } - - interface RequestHandler { - (req: Request, res: Response, next: NextFunction): any; - } } From 5fd6d6b4eaabda87d19ad13b7d6709443617ddd8 Mon Sep 17 00:00:00 2001 From: Cao Jiannan Date: Sat, 9 Jul 2016 02:52:18 +0800 Subject: [PATCH 0031/1255] expose IRouterHandler --- express/express.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/express/express.d.ts b/express/express.d.ts index 4ab7eb1c90..5f65b60519 100644 --- a/express/express.d.ts +++ b/express/express.d.ts @@ -38,8 +38,9 @@ declare module "express" { interface Express extends core.Express { } interface Handler extends core.Handler { } interface IRoute extends core.IRoute { } - interface IRouter extends core.IRouter { } + interface IRouter extends core.IRouter { } interface IRouterMatcher extends core.IRouterMatcher { } + interface IRouterHandler extends core.IRouterHandler { } interface MediaType extends core.MediaType { } interface NextFunction extends core.NextFunction { } interface Request extends core.Request { } From e53106d303bde4e5ffa298f8e609e5907f4d13ac Mon Sep 17 00:00:00 2001 From: Cao Jiannan Date: Sat, 9 Jul 2016 10:01:54 +0800 Subject: [PATCH 0032/1255] update param, add `;` --- .../express-serve-static-core.d.ts | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 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 daa7b6cd0f..3bfe0a7daf 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -29,9 +29,9 @@ declare module "express-serve-static-core" { (err: any, req: Request, res: Response, next: NextFunction): any; } - type PathParams = string | RegExp | (string | RegExp)[] + type PathParams = string | RegExp | (string | RegExp)[]; - type RequestHandlerParams = RequestHandler | ErrorRequestHandler + type RequestHandlerParams = RequestHandler | ErrorRequestHandler; interface IRouterMatcher { (path: PathParams, ...handlers: RequestHandler[]): T; @@ -73,11 +73,12 @@ declare module "express-serve-static-core" { * @param name * @param fn */ - param(name: string | string[], handler: RequestParamHandler): this; - param(name: string | string[], matcher: RegExp): this; - param(name: string | string[], mapper: (param: any) => any): this; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + param: { + (name: string, handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + // deprecated since express 4.11.0 + (callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + }; /** * Special-cased "all" method, applying the given route `path`, @@ -807,7 +808,7 @@ declare module "express-serve-static-core" { interface Handler extends RequestHandler { } interface RequestParamHandler { - (req: Request, res: Response, next: NextFunction, param: any): any; + (req: Request, res: Response, next: NextFunction, value: any, name: string): any; } interface Application extends IRouter, Express.Application { @@ -872,6 +873,13 @@ declare module "express-serve-static-core" { */ set(setting: string, val: any): Application; get: {(name: string): any;} & IRouterMatcher; + + param: { + (name: string | string[], handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + // deprecated since express 4.11.0 + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + }; /** * Return the app's absolute pathname From ccfd178bb4f9e78f2238e5add93b7b2ed20d0389 Mon Sep 17 00:00:00 2001 From: Cao Jiannan Date: Sat, 9 Jul 2016 10:20:53 +0800 Subject: [PATCH 0033/1255] Update param declare --- .../express-serve-static-core.d.ts | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 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 3bfe0a7daf..4e3bee4691 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -31,7 +31,7 @@ declare module "express-serve-static-core" { type PathParams = string | RegExp | (string | RegExp)[]; - type RequestHandlerParams = RequestHandler | ErrorRequestHandler; + type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; interface IRouterMatcher { (path: PathParams, ...handlers: RequestHandler[]): T; @@ -73,12 +73,10 @@ declare module "express-serve-static-core" { * @param name * @param fn */ - param: { - (name: string, handler: RequestParamHandler): this; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - // deprecated since express 4.11.0 - (callback: (name: string, matcher: RegExp) => RequestParamHandler): this; - }; + param(name: string, handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + // deprecated since express 4.11.0 + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; /** * Special-cased "all" method, applying the given route `path`, @@ -874,12 +872,10 @@ declare module "express-serve-static-core" { set(setting: string, val: any): Application; get: {(name: string): any;} & IRouterMatcher; - param: { - (name: string | string[], handler: RequestParamHandler): this; - // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API - // deprecated since express 4.11.0 - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; - }; + param(name: string[], handler: RequestParamHandler): this; + param(name: string, handler: RequestParamHandler): this; + // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; /** * Return the app's absolute pathname From f77d4a03c47c8953fa6aab76b95fbab5121454da Mon Sep 17 00:00:00 2001 From: Alexey Svetliakov Date: Sat, 9 Jul 2016 06:06:46 +0200 Subject: [PATCH 0034/1255] Updated enzyme to 2.4.1 --- enzyme/enzyme-tests.tsx | 23 ++++++++++++++++++++++ enzyme/enzyme.d.ts | 42 ++++++++++++++++++++++++++++++++++++++--- 2 files changed, 62 insertions(+), 3 deletions(-) diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index 037803024b..efec976d01 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -44,6 +44,15 @@ namespace ShallowWrapperTest { stringVal: String, elementWrapper: ShallowWrapper + function test_shallow_options() { + shallow(, { + context: { + test: "a", + lifecycleExperimental: true + } + }); + } + function test_find() { elementWrapper = shallowWrapper.find('.selector'); shallowWrapper = shallowWrapper.find(MyComponent); @@ -281,6 +290,10 @@ namespace ShallowWrapperTest { function test_everyWhere() { boolVal = shallowWrapper.everyWhere((aShallowWrapper: ShallowWrapper) => true); } + + function test_isEmptyRender() { + boolVal = shallowWrapper.isEmptyRender(); + } } @@ -301,6 +314,13 @@ namespace ReactWrapperTest { function test_mount() { reactWrapper = reactWrapper.mount(); + + mount(, { + attachTo: document.getElementById('test'), + context: { + a: "b" + } + }); } function test_ref() { @@ -542,6 +562,9 @@ namespace ReactWrapperTest { function test_everyWhere() { boolVal = reactWrapper.everyWhere((aReactWrapper: ReactWrapper) => true); } + function test_isEmptyRender() { + boolVal = reactWrapper.isEmptyRender(); + } } // CheerioWrapper diff --git a/enzyme/enzyme.d.ts b/enzyme/enzyme.d.ts index dbc2b4a76c..4a5bf2beac 100644 --- a/enzyme/enzyme.d.ts +++ b/enzyme/enzyme.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Enzyme v2.3.0 +// Type definitions for Enzyme v2.4.1 // Project: https://github.com/airbnb/enzyme // Definitions by: Marian Palkus , Cap3 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -448,6 +448,11 @@ declare module "enzyme" { * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ShallowWrapper; + + /** + * Returns true if renderer returned null + */ + isEmptyRender(): boolean; } export interface ReactWrapper extends CommonWrapper { @@ -544,26 +549,57 @@ declare module "enzyme" { * Returns a wrapper with the direct parent of the node in the current wrapper. */ parent(): ReactWrapper; + + /** + * Returns true if renderer returned null + */ + isEmptyRender(): boolean; } export interface CheerioWrapper extends CommonWrapper { } + export interface ShallowRendererProps { + /** + * Enable experimental support for full react lifecycle methods + */ + lifecycleExperimental?: boolean; + /** + * Context to be passed into the component + */ + context?: {}; + } + + export interface MountRendererProps { + /** + * Context to be passed into the component + */ + context?: {}; + /** + * DOM Element to attach the component to + */ + attachTo?: HTMLElement; + /** + * Merged contextTypes for all children of the wrapper + */ + childContextTypes?: {}; + } + /** * Shallow rendering is useful to constrain yourself to testing a component as a unit, and to ensure that * your tests aren't indirectly asserting on behavior of child components. * @param node * @param [options] */ - export function shallow(node: ReactElement

, options?: any): ShallowWrapper; + export function shallow(node: ReactElement

, options?: ShallowRendererProps): ShallowWrapper; /** * Mounts and renders a react component into the document and provides a testing wrapper around it. * @param node * @param [options] */ - export function mount(node: ReactElement

, options?: any): ReactWrapper; + export function mount(node: ReactElement

, options?: MountRendererProps): ReactWrapper; /** * Render react components to static HTML and analyze the resulting HTML structure. From a8d8d166743373d18365ef837744f14a0a85a458 Mon Sep 17 00:00:00 2001 From: Alexey Svetliakov Date: Sat, 9 Jul 2016 06:15:40 +0200 Subject: [PATCH 0035/1255] wrong param in shallow() test --- enzyme/enzyme-tests.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/enzyme/enzyme-tests.tsx b/enzyme/enzyme-tests.tsx index efec976d01..67dccafeaf 100644 --- a/enzyme/enzyme-tests.tsx +++ b/enzyme/enzyme-tests.tsx @@ -48,8 +48,8 @@ namespace ShallowWrapperTest { shallow(, { context: { test: "a", - lifecycleExperimental: true - } + }, + lifecycleExperimental: true }); } From 6a36f6d5b61602b6c4ad932599097135e80abaf4 Mon Sep 17 00:00:00 2001 From: Alexey Svetliakov Date: Sat, 9 Jul 2016 06:46:14 +0200 Subject: [PATCH 0036/1255] Allow es6 import for addons-create-fragment/addons-shallow-compare --- react/react-addons-create-fragment.d.ts | 3 ++- react/react-addons-shallow-compare.d.ts | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/react/react-addons-create-fragment.d.ts b/react/react-addons-create-fragment.d.ts index 9bfa4c33c6..3b8e0c35a9 100644 --- a/react/react-addons-create-fragment.d.ts +++ b/react/react-addons-create-fragment.d.ts @@ -12,5 +12,6 @@ declare namespace __React { } declare module "react-addons-create-fragment" { - export = __React.__Addons.createFragment; + var createFragment: typeof __React.__Addons.createFragment; + export = createFragment; } diff --git a/react/react-addons-shallow-compare.d.ts b/react/react-addons-shallow-compare.d.ts index 4fb9aa8462..45984c455b 100644 --- a/react/react-addons-shallow-compare.d.ts +++ b/react/react-addons-shallow-compare.d.ts @@ -15,5 +15,6 @@ declare namespace __React { } declare module "react-addons-shallow-compare" { - export = __React.__Addons.shallowCompare; + var shallowCompare: typeof __React.__Addons.shallowCompare; + export = shallowCompare; } From 3af3aec1c295cbb9887820caa07573651d841985 Mon Sep 17 00:00:00 2001 From: Dan Marshall Date: Fri, 8 Jul 2016 23:57:09 -0700 Subject: [PATCH 0037/1255] reduce() returns Bezier[] --- bezier-js/bezier-js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bezier-js/bezier-js.d.ts b/bezier-js/bezier-js.d.ts index dfc699bc15..8ee85790b1 100644 --- a/bezier-js/bezier-js.d.ts +++ b/bezier-js/bezier-js.d.ts @@ -125,7 +125,7 @@ declare module BezierJs { overlaps(curve: Bezier): boolean; offset(t: number, d?: number): Offset | Bezier[]; simple(): boolean; - reduce(): any[]; + reduce(): Bezier[]; scale(d: Function): Bezier; scale(d: number): Bezier; outline(d1: number, d2?: number, d3?: number, d4?: number): PolyBezier; From 203818d338c3454f13298bfe743755260b90382a Mon Sep 17 00:00:00 2001 From: Cao Jiannan Date: Sun, 10 Jul 2016 23:16:00 +0800 Subject: [PATCH 0038/1255] remove unnecessary user property of request leave space to user defined user type --- express-serve-static-core/express-serve-static-core.d.ts | 4 ---- 1 file changed, 4 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 4e3bee4691..a3f707c83a 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -384,10 +384,6 @@ declare module "express-serve-static-core" { params: any; - user: any; - - authenticatedUser: any; - /** * Clear cookie `name`. * From a69c28bb2da00c0678d2c8d8af342cdbb374f933 Mon Sep 17 00:00:00 2001 From: Tony Compton Date: Sun, 10 Jul 2016 19:21:12 -0400 Subject: [PATCH 0039/1255] Added the listen function. Added the listen function to Store interface so that people can use Reflux the non-mixin way. --- reflux/reflux.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/reflux/reflux.d.ts b/reflux/reflux.d.ts index b2d96dd621..91f7316271 100644 --- a/reflux/reflux.d.ts +++ b/reflux/reflux.d.ts @@ -35,6 +35,7 @@ declare module RefluxCore { stopListeningToAll(): void, fetchInitialState(listenable: Listenable, defaultCallback: Function): void, trigger(state: any):void; + listen(callback: Function, bindContext: any) : Function; } interface ActionsDefinition { From 25debf619c11aed1b4d3fe6ba670a612dd508c47 Mon Sep 17 00:00:00 2001 From: denis Date: Mon, 11 Jul 2016 11:23:55 +0200 Subject: [PATCH 0040/1255] Changes according to repo owner Add authors name Indentation: replace tab by spaces Use union type: OnEvent and TriggerEvent Note: `width` is string as it needs units, like "95 %", "100 px". --- chosen/chosen.jquery.d.ts | 34 ++++++++++------------------------ 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/chosen/chosen.jquery.d.ts b/chosen/chosen.jquery.d.ts index 85f233e718..f43a2fefbd 100644 --- a/chosen/chosen.jquery.d.ts +++ b/chosen/chosen.jquery.d.ts @@ -1,15 +1,18 @@ // Type definitions for Chosen.JQuery 1.6.1 // Project: http://harvesthq.github.com/chosen/ -// Definitions by: Boris Yankov +// Definitions by: Boris Yankov , denis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// declare namespace Chosen { + type OnEvent = "chosen:ready" | "chosen:maxselected" | "chosen:showing_dropdown" | "chosen:hiding_dropdown" | "chosen:no_results" + type TriggerEvent = "chosen:updated" | "chosen:activate" | "chosen:open" | "chosen:close" + interface Options { /**When set to true on a single select, Chosen adds a UI element which selects the first element (if it is blank). * @default: false - */ + */ allow_single_deselect?: boolean; /**By default Chosen's search is case-insensitive. Setting this option to true makes the search case-sensitive. * @default: false @@ -74,7 +77,7 @@ declare namespace Chosen { * @default: Infinity */ max_shown_results?: number; - } + } interface SelectedData { selected: string; @@ -84,29 +87,12 @@ declare namespace Chosen { interface JQuery { chosen(): JQuery; - chosen(options: Chosen.Options): JQuery; - /**To destroy Chosen and revert back to the native select. */ - chosen(options: "destroy"): JQuery; + chosen(options: Chosen.Options | "destroy"): JQuery; /**Chosen triggers the standard DOM event whenever a selection is made (it also sends a selected or deselected parameter that tells you which option was changed). */ on(events: "change", handler: (eventObject: JQueryEventObject, args: Chosen.SelectedData) => any): JQuery; - /**Triggered after Chosen has been fully instantiated. */ - on(events: "chosen:ready", handler: (eventObject: JQueryEventObject) => any): JQuery; - /**Triggered if max_selected_options is set and that total is broken. */ - on(events: "chosen:maxselected", handler: (eventObject: JQueryEventObject) => any): JQuery; - /**Triggered when Chosen’s dropdown is opened. */ - on(events: "chosen:showing_dropdown", handler: (eventObject: JQueryEventObject) => any): JQuery; - /**Triggered when Chosen’s dropdown is closed. */ - on(events: "chosen:hiding_dropdown", handler: (eventObject: JQueryEventObject) => any): JQuery; - /**Triggered when a search returns no matching results. */ - on(events: "chosen:no_results", handler: (eventObject: JQueryEventObject) => any): JQuery; - /**This event should be triggered whenever Chosen’s underlying select element changes (such as a change in selected options). */ - trigger(eventType: "chosen:updated"): JQuery; - /**This is the equivalant of focusing a standard HTML select field. When activated, Chosen will capure keypress events as if you had clicked the field directly. */ - trigger(eventType: "chosen:activate"): JQuery; - /**This event activates Chosen and also displays the search results. */ - trigger(eventType: "chosen:open"): JQuery; - /**This event deactivates Chosen and hides the search results. */ - trigger(eventType: "chosen:close"): JQuery; + on(events: Chosen.OnEvent, handler: (eventObject: JQueryEventObject) => any): JQuery; + + trigger(eventType: Chosen.TriggerEvent): JQuery; } From ebb8c657d2b4c92e676b1620ab4d3014e44b8995 Mon Sep 17 00:00:00 2001 From: anuti Date: Mon, 11 Jul 2016 11:45:30 +0200 Subject: [PATCH 0041/1255] Rename chart2.d.ts to chartjs.d.ts --- chartjs/{chart2.d.ts => chartjs.d.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename chartjs/{chart2.d.ts => chartjs.d.ts} (100%) diff --git a/chartjs/chart2.d.ts b/chartjs/chartjs.d.ts similarity index 100% rename from chartjs/chart2.d.ts rename to chartjs/chartjs.d.ts From 1838cdc893299be315e468cd5629d95bc790cc6e Mon Sep 17 00:00:00 2001 From: Tony Compton Date: Mon, 11 Jul 2016 09:28:08 -0400 Subject: [PATCH 0042/1255] Fixing a code style issue. --- reflux/reflux.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reflux/reflux.d.ts b/reflux/reflux.d.ts index 91f7316271..1501d8e636 100644 --- a/reflux/reflux.d.ts +++ b/reflux/reflux.d.ts @@ -35,7 +35,7 @@ declare module RefluxCore { stopListeningToAll(): void, fetchInitialState(listenable: Listenable, defaultCallback: Function): void, trigger(state: any):void; - listen(callback: Function, bindContext: any) : Function; + listen(callback: Function, bindContext: any): Function; } interface ActionsDefinition { From 6c0118ed5f0c4781249556498c5ff4f78c73b672 Mon Sep 17 00:00:00 2001 From: Pedro Poveda Date: Mon, 11 Jul 2016 10:29:24 -0400 Subject: [PATCH 0043/1255] Fixed indentation --- react-bootstrap/react-bootstrap.d.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/react-bootstrap/react-bootstrap.d.ts b/react-bootstrap/react-bootstrap.d.ts index 04da49e1b9..a4e70260f3 100644 --- a/react-bootstrap/react-bootstrap.d.ts +++ b/react-bootstrap/react-bootstrap.d.ts @@ -1058,7 +1058,6 @@ declare module "react-bootstrap" { type Portal = React.ClassicComponent; var Portal: React.ClassicComponentClass; - // interface PositionProps extends TransitionCallbacks, React.Props { dimension?: string | Function; @@ -1073,28 +1072,28 @@ declare module "react-bootstrap" { } // interface MediaLeftProps { - align?: string; + align?: string; } type MediaLeft = React.ClassicComponent; var MediaLeft: React.ClassicComponentClass; // interface MediaRightProps { - align?: string; + align?: string; } type MediaRight = React.ClassicComponent; var MediaRight: React.ClassicComponentClass; // interface MediaHeadingProps { - componentClass?: React.ReactType; + componentClass?: React.ReactType; } type MediaHeading = React.ClassicComponent; var MediaHeading: React.ClassicComponentClass; // interface MediaBodyProps { - componentClass?: React.ReactType; + componentClass?: React.ReactType; } type MediaBody = React.ClassicComponent; var MediaBody: React.ClassicComponentClass; @@ -1107,7 +1106,7 @@ declare module "react-bootstrap" { // interface MediaListItemProps { - componentClass?: React.ReactType; + componentClass?: React.ReactType; } type MediaListItem = React.ClassicComponent; var MediaListItem: React.ClassicComponentClass; @@ -1126,5 +1125,4 @@ declare module "react-bootstrap" { } type Media = React.ClassicComponent; var Media: MediaClass; - } From cb4960033f11e56f51d527e55e3e6fac2be6dbd1 Mon Sep 17 00:00:00 2001 From: Cao Jiannan Date: Mon, 11 Jul 2016 22:57:27 +0800 Subject: [PATCH 0044/1255] add user to Request for http-errors req.user should be declared by developer. --- http-errors/http-errors-tests.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index 4403259008..37dc4b3cd8 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -4,6 +4,12 @@ import * as createError from 'http-errors'; import * as express from 'express'; +declare namespace Express { + export interface Request { + user: any + } +} + var app = express(); app.use(function (req, res, next) { From 6245fffb1898ed4b786b330654e46a86ec20248b Mon Sep 17 00:00:00 2001 From: Cao Jiannan Date: Mon, 11 Jul 2016 22:57:51 +0800 Subject: [PATCH 0045/1255] optional user --- http-errors/http-errors-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index 37dc4b3cd8..d1400bbe4c 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -6,7 +6,7 @@ import * as express from 'express'; declare namespace Express { export interface Request { - user: any + user?: any } } From a591dbfa8e5ee74d3e1a0a0b6ec28601746ccdcc Mon Sep 17 00:00:00 2001 From: "Cao, Jiannan" Date: Mon, 11 Jul 2016 23:16:06 +0800 Subject: [PATCH 0046/1255] add user to http-errors.d.ts --- http-errors/http-errors-tests.ts | 6 ------ http-errors/http-errors.d.ts | 6 ++++++ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index d1400bbe4c..4403259008 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -4,12 +4,6 @@ import * as createError from 'http-errors'; import * as express from 'express'; -declare namespace Express { - export interface Request { - user?: any - } -} - var app = express(); app.use(function (req, res, next) { diff --git a/http-errors/http-errors.d.ts b/http-errors/http-errors.d.ts index 48d7469ba4..745e313995 100644 --- a/http-errors/http-errors.d.ts +++ b/http-errors/http-errors.d.ts @@ -3,6 +3,12 @@ // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare namespace Express { + export interface Request { + user?: any + } +} + declare module 'http-errors' { namespace createHttpError { From dcd4fb55facbfecac80e4a476bcdb2adf5763ab9 Mon Sep 17 00:00:00 2001 From: "Cao, Jiannan" Date: Mon, 11 Jul 2016 23:36:44 +0800 Subject: [PATCH 0047/1255] move req.user to http-errors-tests.d.ts --- http-errors/http-errors-tests.d.ts | 5 +++++ http-errors/http-errors-tests.ts | 2 +- http-errors/http-errors.d.ts | 6 ------ 3 files changed, 6 insertions(+), 7 deletions(-) create mode 100644 http-errors/http-errors-tests.d.ts diff --git a/http-errors/http-errors-tests.d.ts b/http-errors/http-errors-tests.d.ts new file mode 100644 index 0000000000..f6fad5ac4e --- /dev/null +++ b/http-errors/http-errors-tests.d.ts @@ -0,0 +1,5 @@ +declare namespace Express { + export interface Request { + user?: any + } +} diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index 4403259008..e5e0c97567 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -1,5 +1,6 @@ /// /// +/// import * as createError from 'http-errors'; import * as express from 'express'; @@ -11,7 +12,6 @@ app.use(function (req, res, next) { next(); }); - /* Examples taken from https://github.com/jshttp/http-errors/blob/1.3.1/test/test.js */ // createError(status) diff --git a/http-errors/http-errors.d.ts b/http-errors/http-errors.d.ts index 745e313995..48d7469ba4 100644 --- a/http-errors/http-errors.d.ts +++ b/http-errors/http-errors.d.ts @@ -3,12 +3,6 @@ // Definitions by: Tanguy Krotoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace Express { - export interface Request { - user?: any - } -} - declare module 'http-errors' { namespace createHttpError { From 49a98e044371c8d491cf0e451a8b61898ace2f77 Mon Sep 17 00:00:00 2001 From: "Cao, Jiannan" Date: Tue, 12 Jul 2016 00:02:46 +0800 Subject: [PATCH 0048/1255] add comment line --- http-errors/http-errors-tests.d.ts | 1 + http-errors/http-errors-tests.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/http-errors/http-errors-tests.d.ts b/http-errors/http-errors-tests.d.ts index f6fad5ac4e..9005c7ef41 100644 --- a/http-errors/http-errors-tests.d.ts +++ b/http-errors/http-errors-tests.d.ts @@ -1,3 +1,4 @@ +// Type definitions for http-errors-tests.ts declare namespace Express { export interface Request { user?: any diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index e5e0c97567..f8e0ea9b8c 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -1,6 +1,6 @@ /// /// -/// +/// import * as createError from 'http-errors'; import * as express from 'express'; From ef0e322e4f3cece71e9a26584aa82ec52acef982 Mon Sep 17 00:00:00 2001 From: Tom McTiernan Date: Mon, 11 Jul 2016 17:13:24 +0100 Subject: [PATCH 0049/1255] Make `getColHeader` parameter optional --- handsontable/handsontable.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/handsontable/handsontable.d.ts b/handsontable/handsontable.d.ts index 790eb4b087..7a82509baa 100644 --- a/handsontable/handsontable.d.ts +++ b/handsontable/handsontable.d.ts @@ -232,7 +232,7 @@ declare namespace ht { getCellMeta(row: number, col: number): Object; getCellRenderer(row: number, col: number): Function; getCellValidator(row: number, col: number): any; - getColHeader(col: number): any[]|string; + getColHeader(col?: number): any[]|string; getColWidth(col: number): number; getCoords(elem: Element): Object; getCopyableData(row: number, column: number): string; From 4bc3bdf7bbbbaddaabeb5e9b67a7bc154f6fa528 Mon Sep 17 00:00:00 2001 From: Ivo Stratev Date: Mon, 11 Jul 2016 19:31:18 +0300 Subject: [PATCH 0050/1255] Improvement to material-ui type definition case 2. Improvement to existing type definition. From Material-UI Reference (http://www.material-ui.com/#/customization/themes): "The lightBaseTheme is the default so you will not need to do anything to use it other than using MuiThemeProvider as described in Usage. [http://www.material-ui.com/#/get-started/usage]" muiTheme Property should be optional. --- material-ui/material-ui.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 32562aa110..984f57e987 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -452,7 +452,7 @@ declare namespace __MaterialUI { export function themeDecorator(muiTheme: Styles.MuiTheme): (Component: TFunction) => TFunction; interface MuiThemeProviderProps extends React.Props { - muiTheme: Styles.MuiTheme; + muiTheme?: Styles.MuiTheme; } export class MuiThemeProvider extends React.Component{ } From 1f418be731a07eee688e3897899eff6766cf9cc8 Mon Sep 17 00:00:00 2001 From: "Cao, Jiannan" Date: Tue, 12 Jul 2016 01:23:42 +0800 Subject: [PATCH 0051/1255] declare Express in ambient environment --- http-errors/http-errors-tests.d.ts | 6 ------ http-errors/http-errors-tests.ts | 9 ++++++++- 2 files changed, 8 insertions(+), 7 deletions(-) delete mode 100644 http-errors/http-errors-tests.d.ts diff --git a/http-errors/http-errors-tests.d.ts b/http-errors/http-errors-tests.d.ts deleted file mode 100644 index 9005c7ef41..0000000000 --- a/http-errors/http-errors-tests.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -// Type definitions for http-errors-tests.ts -declare namespace Express { - export interface Request { - user?: any - } -} diff --git a/http-errors/http-errors-tests.ts b/http-errors/http-errors-tests.ts index f8e0ea9b8c..61fb9091bf 100644 --- a/http-errors/http-errors-tests.ts +++ b/http-errors/http-errors-tests.ts @@ -1,12 +1,19 @@ /// /// -/// import * as createError from 'http-errors'; import * as express from 'express'; var app = express(); +declare global { + namespace Express { + export interface Request { + user?: any + } + } +} + app.use(function (req, res, next) { if (!req.user) return next(createError(401, 'Please login to view this page.')); next(); From bd06aa2f50af2d1beb4867a97240c53da9fc80a3 Mon Sep 17 00:00:00 2001 From: Elad Zelingher Date: Mon, 11 Jul 2016 20:50:40 +0300 Subject: [PATCH 0052/1255] Fixing progress field --- autobahn/autobahn.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/autobahn/autobahn.d.ts b/autobahn/autobahn.d.ts index 97837b52d0..7fd344f727 100644 --- a/autobahn/autobahn.d.ts +++ b/autobahn/autobahn.d.ts @@ -45,7 +45,7 @@ declare namespace autobahn { interface IInvocation { caller?: number; - progress?: boolean; + progress?: (args : any[], kwargs : any) => void; procedure: string; } From 0dd6ead8f045e40c78caf49404ccc4240c0c7c98 Mon Sep 17 00:00:00 2001 From: "Cao, Jiannan" Date: Tue, 12 Jul 2016 02:36:08 +0800 Subject: [PATCH 0053/1255] merge param --- .../express-serve-static-core.d.ts | 13 ++++++------- 1 file changed, 6 insertions(+), 7 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 a3f707c83a..0851ddad9a 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -20,17 +20,17 @@ declare module "express-serve-static-core" { interface NextFunction { (err?: any): void; } - + interface RequestHandler { (req: Request, res: Response, next: NextFunction): any; } - + interface ErrorRequestHandler { (err: any, req: Request, res: Response, next: NextFunction): any; } type PathParams = string | RegExp | (string | RegExp)[]; - + type RequestHandlerParams = RequestHandler | ErrorRequestHandler | (RequestHandler | ErrorRequestHandler)[]; interface IRouterMatcher { @@ -93,7 +93,7 @@ declare module "express-serve-static-core" { patch: IRouterMatcher; options: IRouterMatcher; head: IRouterMatcher; - + use: IRouterHandler & IRouterMatcher; route(prefix: PathParams): IRoute; @@ -867,9 +867,8 @@ declare module "express-serve-static-core" { */ set(setting: string, val: any): Application; get: {(name: string): any;} & IRouterMatcher; - - param(name: string[], handler: RequestParamHandler): this; - param(name: string, handler: RequestParamHandler): this; + + param(name: string | string[], handler: RequestParamHandler): this; // Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() API param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; From cf1327066b680c6cd9120faf6e87fc069cc2dc1b Mon Sep 17 00:00:00 2001 From: "d.rogozhny@gmail.com" Date: Mon, 11 Jul 2016 22:16:55 +0300 Subject: [PATCH 0054/1255] indentation for Editor in draft-js-tests-0.2.2.tsx --- draft-js/draft-js-tests-0.2.2.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/draft-js/draft-js-tests-0.2.2.tsx b/draft-js/draft-js-tests-0.2.2.tsx index d1c0143dd6..88271465f5 100644 --- a/draft-js/draft-js-tests-0.2.2.tsx +++ b/draft-js/draft-js-tests-0.2.2.tsx @@ -5,7 +5,7 @@ import * as React from "react"; import { -Editor, + Editor, EditorState, Entity, CharacterMetadata, From de82425735f84a10b43921ae4b1d085b3752a626 Mon Sep 17 00:00:00 2001 From: Jerry Feng Date: Tue, 12 Jul 2016 10:55:50 +0800 Subject: [PATCH 0055/1255] Fix ui function's parameter typing (#10062) * RN: add props definition for WebView * RN: Add platform-specific props to WebView * RN: Add getWebViewHandle method * RN: add source props to WebView * RN: fix type of decelerationRate * RN: Update Picker.Item props * RN: Update props name * RN: Clarify mode range * RN: Add definition for DrawerLayoutAndroid * RN: Update Image * RN: Update ListView * RN: Update MapView to 0.25 * RN: Add Modal * RN: Update ScrollView * RN: Add SegmentedControlIOS * RN: Add Slider * RN: Update SliderIOS * RN: Define Status Bar * RN: export StatusBar * RN: Define Switch * RN: Update Text * RN: Update TextInput * RN: Add ToolbarAndroid * RN: Update TouchableOpacity * RN: Update TouchableWithoutFeedback * RN: Update View * RN: Update ViewPagerAndroid * RN: Fix mistakes * RN: Unify indentation * Add 2 components; fix some minor problems * fix: follow the convention * RN: Update ActionSheetIOS * RN: Add Alert api * RN: Fix reference * RN: Update AlertIOS * RN: add typing for type parameter * RN: Update AppRegistry * RN: Update AppState and AppStateIOS * RN: Add BackAndroid * RN: Update Camera Roll * RN: Add Clipboard * RN: Add DatePickerAndroid * RN: Update Dimensions * RN: Update InteractionManager * RN: Add methods to DrawerLayoutAndroid * RN: Export DatePickerAndroid * RN: Add IntentAndroid * RN: Add Linking * RN: Add LinkingIOS * RN: Add NetInfo * RN: Update PixelRatio * RN: Update PushNotificationIOS * RN: Update StyleSheet * RN: Add TimePickerAndroid * RN: Update ToastAndroid * RN: Add Vibration * RN: Set stricter definition for flexbox props * RN: Define ShadowPropTypesIOSStatic * RN: Fix indentation * RN: Add Geolocation * RN: Export Geolocation * RN: Move Geolocation to proper position * RN: Define fetch * RN: Fix tabs * RN: Define schedulers * RN: Major fixes from @PublicParadise * RN: Update version * RN: Add documentation as comments * RN: Add more comments * fix: typo * add some missing callbacks * RN: Export switch * add missing commentes * Fix(Switch): add style property * RN: Update Navigation Experimental * RN: Define SwipableListView * RN: Add necessary marks * RN: Improve unclear typing * RN: Enable pagingEnabled for ScrollView * RN: Enable returnKeyType for both platforms * RN: Add returnKeyLabel to Android * RN: Add a prop * RN: Add scrollEnabled prop in 0.27 * RN: Add new prop from 0.27 * RN: Fix typo * RN: Remove redundant export * RN: Fix typo * RN: Add missing definitions * RN: Fix missing type declarations * Annotate params * Define redux-ui * update ReactRedux reference * Remove ReactRedux dependency * Add additional UI props for extension * Add generics to specify shape of UI state * Add comments on ReduxUIProps from official documentation * Shorten long line * Supply type parameter * Make value parameter optional * Overload ui function to improve precision * Fix parameter of ui function * Use semicolon --- redux-ui/redux-ui.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/redux-ui/redux-ui.d.ts b/redux-ui/redux-ui.d.ts index 7ba61a3f8a..6114931320 100644 --- a/redux-ui/redux-ui.d.ts +++ b/redux-ui/redux-ui.d.ts @@ -51,5 +51,5 @@ declare module "redux-ui" { export const reducer: Redux.Reducer; - export default function ui(params: uiParams): (component: T) => T; + export default function ui(params?: uiParams): (component: T) => T; } From 6f664bd4fecc70dac11661e4b67436d8aa12fa4d Mon Sep 17 00:00:00 2001 From: Andrey Kurdyumov Date: Wed, 13 Jul 2016 12:12:31 +0600 Subject: [PATCH 0056/1255] Add support for using React Bootstrap in glbal setup (#10051) --- react-bootstrap/react-bootstrap.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/react-bootstrap/react-bootstrap.d.ts b/react-bootstrap/react-bootstrap.d.ts index a4e70260f3..0473057b04 100644 --- a/react-bootstrap/react-bootstrap.d.ts +++ b/react-bootstrap/react-bootstrap.d.ts @@ -5,9 +5,9 @@ /// -declare module "react-bootstrap" { +declare namespace ReactBootstrap { // Import React - import React = require("react"); + import React = __React; type Sizes = 'xs' | 'xsmall' | 'sm' | 'small' | 'lg' | 'large'; @@ -1126,3 +1126,7 @@ declare module "react-bootstrap" { type Media = React.ClassicComponent; var Media: MediaClass; } + +declare module "react-bootstrap" { + export = ReactBootstrap; +} From 21b05005073a35496f9fda2d133a27b4627abf1c Mon Sep 17 00:00:00 2001 From: davidlipo Date: Wed, 13 Jul 2016 07:22:31 +0100 Subject: [PATCH 0057/1255] Update react-day-picker.d.ts (#10052) * Update react-day-picker.d.ts Upgrade following some breaking changes in react-day-picker 2.0 * Added in more react-day-picker props. * Update react-day-picker.d.ts --- react-day-picker/react-day-picker.d.ts | 43 +++++++++++++++++++++++--- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/react-day-picker/react-day-picker.d.ts b/react-day-picker/react-day-picker.d.ts index e20f670184..c9714261e3 100644 --- a/react-day-picker/react-day-picker.d.ts +++ b/react-day-picker/react-day-picker.d.ts @@ -23,6 +23,12 @@ declare namespace ReactDayPicker { getMonths: (locale: string) => string[]; } + interface DayModifiers { + selected?: boolean; + disabled?: boolean; + [name: string]: boolean; + } + interface Modifiers { [name: string]: (date: Date) => boolean; } @@ -33,6 +39,27 @@ declare namespace ReactDayPicker { locale?: string; onClick?: React.MouseEventHandler; } + + interface NavbarElementProps extends React.Props { + className?: string; + previousMonth?: Date; + nextMonth?: Date; + showPreviousButton?: boolean; + showNextButton?: boolean; + onPreviousClick(): void; + onNextClick(): void; + dir?: string; + localeUtils?: LocaleUtils; + locale?: string; + + } + + interface WeekdayElementProps extends React.Props { + weekday?: number; + className?: string; + localeUtils?: LocaleUtils; + locale?: string; + } interface Props extends React.Props{ modifiers?: Modifiers; @@ -41,18 +68,26 @@ declare namespace ReactDayPicker { renderDay?: (date: Date) => number | string | JSX.Element; enableOutsideDays?: boolean; canChangeMonth?: boolean; + disabledDays?: (date: Date) => boolean; + fixedWeeks?: boolean; fromMonth?: Date; + reverseMonths?: boolean; toMonth?: Date; localeUtils?: LocaleUtils; locale?: string; captionElement?: React.ReactElement; - onDayClick?: (e: React.SyntheticEvent, day: Date, modifiers: string[]) => any; - onDayTouchTap?: (e: React.SyntheticEvent, day: Date, modifiers: string[]) => any; - onDayMouseEnter?: (e: React.SyntheticEvent, day: Date, modifiers: string[]) => any; - onDayMouseLeave?: (e: React.SyntheticEvent, day: Date, modifiers: string[]) => any; + navbarElement?: React.ReactElement; + weekdayElement?: React.ReactElement; + onDayClick?: (e: React.SyntheticEvent, day: Date, modifiers: DayModifiers) => any; + onDayKeyDown?: (e: React.SyntheticEvent, day: Date, modifiers: DayModifiers) => any; + onDayMouseEnter?: (e: React.SyntheticEvent, day: Date, modifiers: DayModifiers) => any; + onDayMouseLeave?: (e: React.SyntheticEvent, day: Date, modifiers: DayModifiers) => any; + onDayTouchEnd?: (e: React.SyntheticEvent, day: Date, modifiers: DayModifiers) => any; + onDayTouchStart?: (e: React.SyntheticEvent, day: Date, modifiers: DayModifiers) => any; onMonthChange?: (month: Date) => any; onCaptionClick?: (e: React.SyntheticEvent, month: Date) => any; className?: string; + selectedDays?: (date: Date) => boolean; style?: React.CSSProperties; tabIndex?: number; } From c6757a1399183160731855df852b3b1bdb80a006 Mon Sep 17 00:00:00 2001 From: Simon Xiong Date: Wed, 13 Jul 2016 02:23:30 -0400 Subject: [PATCH 0058/1255] Updates to Mongoose 4.5.x (#10084) * updated to mongoose 4.x and beyond, closes #2904 closes #3345 closes #4219 closes #4262 closes #4773 closes #5791 closes #6957 closes #8248 closes #9423 closes #9547 * add to contributor list * fixes travis errors * fix header issue --- CONTRIBUTORS.md | 2 +- mongoose/mongoose-3.x-tests.ts | 392 ++++ mongoose/mongoose-3.x.d.ts | 653 +++++++ mongoose/mongoose-tests.ts | 1514 +++++++++++---- mongoose/mongoose.d.ts | 3279 ++++++++++++++++++++++++++------ 5 files changed, 4876 insertions(+), 964 deletions(-) create mode 100644 mongoose/mongoose-3.x-tests.ts create mode 100644 mongoose/mongoose-3.x.d.ts diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4317128869..06ca43b24c 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -1123,7 +1123,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](moment/moment.d.ts) [Moment.js](https://github.com/timrwood/moment) by [Michael Lakerveld](https://github.com/Lakerfield), [Aaron King](https://github.com/kingdango), [Hiroki Horiuchi](https://github.com/horiuchi), [Dick van den Brink](https://github.com/DickvdBrink), [Adi Dahiya](https://github.com/adidahiya), [Matt Brooks](https://github.com/EnableSoftware) * [:link:](moment-range/moment-range.d.ts) [Moment.js](https://github.com/gf3/moment-range) by [Bart van den Burg](https://github.com/Burgov), [Wilgert Velinga](https://github.com/wilgert) * [:link:](mongodb/mongodb.d.ts) [MongoDB](https://github.com/mongodb/node-mongodb-native/tree/2.1) by [Federico Caselli](https://github.com/CaselIT) -* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [horiuchi](https://github.com/horiuchi) +* [:link:](mongoose/mongoose.d.ts) [Mongoose](http://mongoosejs.com) by [simonxca](https://github.com/simonxca), [horiuchi](https://github.com/horiuchi) * [:link:](mongoose-auto-increment/mongoose-auto-increment.d.ts) [mongoose-auto-increment](https://github.com/codetunnel/mongoose-auto-increment) by [Aya Morisawa](https://github.com/AyaMorisawa) * [:link:](mongoose-deep-populate/mongoose-deep-populate.d.ts) [mongoose-deep-populate](https://github.com/buunguyen/mongoose-deep-populate) by [Aya Morisawa](https://github.com/AyaMorisawa) * [:link:](mongoose-mock/mongoose-mock.d.ts) [mongoose-mock](https://github.com/JohanObrink/mongoose-mock) by [jt000](https://github.com/jt000) diff --git a/mongoose/mongoose-3.x-tests.ts b/mongoose/mongoose-3.x-tests.ts new file mode 100644 index 0000000000..5264b7cd0b --- /dev/null +++ b/mongoose/mongoose-3.x-tests.ts @@ -0,0 +1,392 @@ +/// + +var fs = require('fs'); +import mongoose = require('mongoose'); + +var createInstance = new mongoose.Mongoose(); + +var Schema = mongoose.Schema; +var CreateSchema = new Schema({}); + +mongoose.connect('mongodb://user:pass@localhost:port/database'); +mongoose.connect('mongodb://hostA:27501,hostB:27501', { mongos: true }); + +var conn: mongoose.Connection = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); +conn = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', { replset: { strategy: 'ping', rs_name: 'testSet' }}); +conn = mongoose.createConnection('localhost', 'database', 27014); +conn = mongoose.createConnection('localhost', 'database', 27014, { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }); +conn = mongoose.createConnection(); +conn.open('localhost', 'database', 27014, {}); + +var db = mongoose.createConnection(); +db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"); +db.openSet('mongodb://mongosA:27501,mongosB:27501', 'db', { mongos: true }, (err: any) => {}); +db.close(); + +var collection = db.collection('collection1'); + +mongoose.connection.on('error', (err: any) => {}); +mongoose.disconnect(); + +mongoose.set('test', 1234567890); +var value = mongoose.get('test'); +mongoose.set('debug', true); + +interface IActor extends mongoose.Document { + name: string; +} +mongoose.model('Actor', new Schema({ name: String })); +db.model('Actor', new Schema({ name: String })); +var schema: mongoose.Schema = new Schema({ name: String }, { collection: 'actor' }); +schema.set('collection', 'actor'); +var Model = mongoose.model('Actor', schema, 'actor'); + +interface IZip extends mongoose.Document { + _id: string; +} +interface IPerson extends mongoose.Document { + _id: mongoose.Types.ObjectId; +} +interface IThing extends mongoose.Document { + _id: number; +} + +var names: string[] = mongoose.modelNames(); +var names: string[] = db.modelNames(); +mongoose.plugin((schema: mongoose.Schema) => { +}, { index: true }); + + +var aggregate = new mongoose.Aggregate(); +var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }); +var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); +var aggregate = new mongoose.Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); +aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); +aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]); +aggregate.group({ _id: "$department" }); +aggregate.skip(10); +aggregate.limit(10); +aggregate.match({ department: { $in: [ "sales", "engineering" ] } }); +aggregate.near({ + near: [40.724, -73.997], + distanceField: "dist.calculated", // required + maxDistance: 0.008, + query: { type: "public" }, + includeLocs: "dist.location", + uniqueDocs: true, + num: 5 +}); +aggregate.project("a b -_id"); +aggregate.project({a: 1, b: 1, _id: 0}); +aggregate.project({ + newField: '$b.nested', + plusTen: { $add: ['$val', 10]}, + sub: { + name: '$a' + } +}); +aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); +aggregate.sort({ field: 'asc', test: -1 }); +aggregate.sort('field -test'); +aggregate.unwind("tags"); +aggregate.unwind("a", "b", "c"); +var p = aggregate.exec(); +aggregate.read('primaryPreferred').exec((err: any, result: {}) => {}); + + +var p = new mongoose.Promise; +var p2 = p.then(function() { throw new Error('shucks') }).end(); +setTimeout(function() { + p.fulfill({}); +}, 10); +var promise = new mongoose.Promise(); +promise.then(function (meetups: number) { + return new mongoose.Promise(); +}).then(function (people: string[]) { + if (people.length < 10000) { + throw new Error('Too few people!!!'); + } else { + throw new Error('Still need more people!!!'); + } +}).then(null, function (err: Error) { +}).end(); + + +Model.findOne({ name: 'john' }, (err: any, doc: mongoose.Document) => { + doc.invalidate('size', 'must be less than 20', 14); + doc.validate((err: any) => { }); + + doc.set('documents.0.title', 'changed'); + doc.get('documents.0'); + doc.set({ + 'path' : 1, + 'path2' : { + 'path' : 2 + } + }); + doc.set('path', 'value', { strict: false }); + doc.set('path3', '1', Number); + doc.get('path3', Number); + doc.id; + doc._id; + + doc.isModified(); + doc.isModified('documents'); + doc.isModified('documents.0.title'); + doc.isDirectModified('documents.0.title'); + doc.isDirectModified('documents'); + doc.isSelected('name'); + + doc.markModified('mixed.type'); + doc.populate('user'); + doc.populate('other', (err: any, doc: mongoose.Document) => {}); + doc.populated('author'); + doc.save(); + + doc.toJSON({ getters: true, virtuals: false }); + var data: any = doc.toObject(); + delete data['age']; + delete data['weight']; + data['isAwesome'] = true; +}); + +Model.model('User').findById('id', (err: any, res: IActor) => {}); +Model.count({ type: 'jungle' }, (err: any, count: number) => {}); +Model.remove((err: any, res: IActor[]) => {}); +Model.save((err: any, res: IActor, numberAffected: number) => {}); +Model.create({ type: 'jelly bean' }, { type: 'snickers' }, (err: any, res1: IActor, res2: IActor) => {}); +Model.create({ type: 'jawbreaker' }); +Model.create({ type: 'muffin' }).then(function (res) { + res.name; +}); +Model.distinct('url', { clicks: {$gt: 100}}, (err: any, result: IActor[]) => {}); +Model.distinct('url'); + +Model.aggregate( + { $group: { _id: null, maxBalance: { $max: '$balance' }}}, + { $project: { _id: 0, maxBalance: 1 }}, + (err: any, res: IActor[]) => {}); +Model.aggregate() + .group({ _id: null, maxBalance: { $max: '$balance' } }) + .select('-id maxBalance') + .exec((err: any, res: IActor[]) => {}); +Model.ensureIndexes((err) => {}); + +Model.find({ name: 'john', age: { $gte: 18 }}); +Model.find({ name: 'john', age: { $gte: 18 }}, (err: any, docs: IActor[]) => {}); +Model.find({ name: /john/i }, 'name friends', (err: any, docs: IActor[]) => {}); +Model.find({ name: /john/i }, null, { skip: 10 }); +Model.find({ name: /john/i }, null, { skip: 10 }, (err: any, docs: IActor[]) => {}); +Model.find({ name: /john/i }, null, { skip: 10 }).exec((err: any, docs: IActor[]) => {}); +var query = Model.find({ name: /john/i }, null, { skip: 10 }); +var promise1 = query.exec(); +promise1.addBack((err: any, docs: IActor[]) => {}); + +Model.findById('id', (err: any, res: IActor) => {}); +Model.findById('id').exec((err: any, res: IActor) => {}); +Model.findById('id', 'name length', (err: any, res: IActor) => {}); +Model.findById('id', '-length').exec((err: any, res: IActor) => {}); +Model.findById('id', 'name', { lean: true }, (err: any, res: IActor) => {}); +Model.findById('id', 'name').lean().exec((err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1', { select: 'name' }, (err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1', { select: 'name' }).exec((err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1', (err: any, res: IActor) => {}); +Model.findByIdAndRemove('id1').exec((err: any, res: IActor) => {}); +Model.findByIdAndUpdate('id2', { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); + +Model.findOne({ type: 'iphone' }, (err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }).exec((err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name', (err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name').exec((err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name', { lean: true }, (err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }, 'name', { lean: true }).exec((err: any, res: IActor) => {}); +Model.findOne({ type: 'iphone' }).select('name').lean().exec((err: any, res: IActor) => {}); +Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }, (err: any, res: IActor) => {}); +Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }).exec((err: any, res: IActor) => {}); +Model.findOneAndUpdate({ type: 'iphone' }, { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); + +Model.geoNear([1, 3], { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); +Model.geoNear({ type : "Point", coordinates : [9,9] }, { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); +Model.geoSearch({ type : "house" }, { near: [10, 10], maxDistance: 5 }, (err: any, res: IActor[]) => {}); + +var o = { + map: function () { this.emit(this.name, 1) }, + reduce: function (k: string, vals: IActor[]) { return vals.length }, +}; +Model.mapReduce(o, (err: any, res: any[]) => {}); + +Model.findById('id', (err: any, res: IActor) => { + var opts = [ + { path: 'company', match: { x: 1 }, select: 'name' }, + { path: 'notes', options: { limit: 10 }, model: 'override' } + ]; + Model.populate(res, opts, (err: any, res: IActor) => {}); +}); +Model.find({ type: 'iphone' }, (err: any, res: IActor[]) => { + var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]; + var promise = Model.populate(res, opts); + promise.then(console.log).end(); +}); +Model.populate({ name: 'Test A' }, { path: 'weapon', model: 'Weapon' }, (err: any, user: IActor) => {}); +Model.populate([ + { name: 'User hoge' }, + { name: 'User fuga' }, +], { path: 'weapon' }, (err: any, users: IActor[]) => {}); + +Model.remove({ title: 'baby born from alien father' }, (err: any) => {}); +var query2 = Model.remove({ _id: 'id' }); +query2.exec(); +Model.update({ age: { $gt: 18 } }, { oldEnough: true }, (err: any, numberAffected: number, raw: any) => {}); +Model.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, (err: any, numberAffected: number, raw: any) => {}); +Model.update({ _id: 'id' }, { $set: { text: 'changed' }}).exec(); + +Model.where('age').gte(21).lte(65).exec((err: any, res: IActor[]) => {}); +var query3 =Model + .where('age').gt(21).lt(65) + .where('name', /^b/i).all('type', 1); +query3.all(25); +query3.and([{ color: 'green' }, { status: 'ok' }]); +query3.batchSize(100); +query3.where('loc').within().box([40.73083, -73.99756], [40.741404, -73.988135]); +query3.where('loc').within().circle({ center: [50, 50], radius: 10, unique: true }); +query3.circle('loc', { center: [50, 50], radius: 10, unique: true }); +query3.comment('login query'); +query3.where({ 'color': 'black' }).count(); +query3.count({ color: 'black' }).count((err: any, count: number) => {}); +query3.count({ color: 'black' }, (err: any, count: number) => {}); +query3.where({ color: 'black' }).count((err: any, count: number) => {}); +query3.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}); +query3.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}); +query.elemMatch('comment', (elem: mongoose.Query) => { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}); +query3.where('age').equals(49); +query3.where('age', 49); +query3.exec(); +query3.exec('update'); +query3.where('name').exists(); +query3.where('name').exists(true); +query3.find().exists('name'); +query3.where('name').exists(false); +query3.find().exists('name', false); +query3.find({ name: 'Los Pollos Hermanos' }).find((err: any, res: IActor[]) => {}); +query3.where('loc').within().geometry({ type: 'Polygon', coordinates: [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] }); +query3.find().where('age').gt(21); +query3.find().gt('age', 21); +query3.hint({ indexA: 1, indexB: -1}); +query3.where('path').intersects().geometry({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); +query3.where('path').intersects({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); +query3.maxScan(100); +query3.where('loc').near({ center: [10, 10] }); +query3.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query3.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); +query3.near('loc', { center: [10, 10], maxDistance: 5 }); +query3.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); +query3.nor([{ color: 'green' }, { status: 'ok' }]); +query3.or([{ color: 'red' }, { status: 'emergency' }]); +query3.where('loc').within().polygon([10,20], [13, 25], [7,15]); +query3.polygon('loc', [10,20], [13, 25], [7,15]); + +query3.findOne().populate('owner').exec((err: any, res: IActor[]) => {}); +query3.find().populate({ + path: 'owner', + select: 'name', + match: { color: 'black' }, + options: { sort: { name: -1 }} +}).exec((err: any, res: IActor[]) => {}); +query3.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec((err: any, res: IActor[]) => {}); + +query3.read('primary'); +query3.read('p'); +query3.read('primaryPreferred'); +query3.read('pp'); +query3.read('secondary'); +query3.read('s'); +query3.read('secondaryPreferred'); +query3.read('sp'); +query3.read('nearest'); +query3.read('n'); +query3.read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); +query3.remove({ artist: 'Anne Murray' }, (err: any, res: IActor[]) => {}); +query3.select('a b -c'); +query3.select({a: 1, b: 1, c: 0}); +query3.select('+path'); +query3.where('tags').size(0); +query3.skip(100).limit(20); +query3.slaveOk(); +query3.slaveOk(true); +query3.slaveOk(false); +query3.slice('comments', -5); +query3.slice('comments', [10, 5]) +query3.where('comments').slice(5); +query3.where('comments').slice([-10, 5]); +query3.snapshot(); +query3.snapshot(true); +query3.snapshot(false); +query3.sort({ field: 'asc', test: -1 }); +query3.sort('field -test'); +Model.find({ name: /^hello/ }).stream({ transform: JSON.stringify }).pipe(fs.createWriteStream('./test.json')); +var stream = Model.find({ name: /^hello/ }).stream(); +stream + .on('data', (doc: IActor) => {}) + .on('error', (err: any) => {}) + .on('close', () => {}); + +query3.tailable(); +query3.tailable(false); +var AdvQuery = query3.toConstructor(); +query3.update({ title: 'words' }); +query3.update({ $set: { title: 'words' }}); +query3.update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, (err: any, row: number, raw: any) => {}); + +query3.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +query3.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +query3.where('loc').within({ polygon: [[],[],[],[]] }); +query3.where('loc').within([], [], []); // polygon +query3.where('loc').within([], []); // box +query3.where('loc').within({ type: 'LineString', coordinates: [] }); // geometry + +mongoose.Query.use$geoWithin = false; + + +var ToySchema = new Schema({}); +ToySchema.add({ name: 'string', color: 'string', price: 'number' }); +schema.eachPath(function(path: string, value: any) {}); +schema.index({ first: 1, last: -1 }); +schema.indexes(); +schema.method('meow', function() { + console.log('meeeeeoooooooooooow'); +}); +var Kitty = mongoose.model('Kitty', schema); +var fizz: any = new Kitty({ name: 'kitty' }); +fizz.meow(); +schema.method({ + purr: function() {}, + scratch: function() {}, +}); +schema.path('name'); +schema.path('name', Number); +schema.pathType('name'); +schema.plugin(function() {}); +schema.post('save', function(doc: IActor) {}); +schema.pre('save', function(next: () => void) {}); +schema.requiredPaths(); +schema.static('findByName', function(name: string, callback: () => void) {}); +schema.virtual('display_name') + .get(function(): string { return this.name; }) + .set((value: string): void => {}); + +var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId('foo'); +var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(); +var id2: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(123); +var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromTime(123); +var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexString('foo'); +var isValid:boolean = mongoose.Types.ObjectId.isValid('570d350b67b1ae0600e8bee8'); +var s = id.toHexString(); +var valid = id.isValid(); +var eq = id.equals(id2); + +var kitty1 = new Kitty({}); +var kitty2 = new Kitty({}); +var kittyEq = kitty1._id.equals(kitty2._id); \ No newline at end of file diff --git a/mongoose/mongoose-3.x.d.ts b/mongoose/mongoose-3.x.d.ts new file mode 100644 index 0000000000..6602cd9953 --- /dev/null +++ b/mongoose/mongoose-3.x.d.ts @@ -0,0 +1,653 @@ +// Type definitions for Mongoose 3.8.5 +// Project: http://mongoosejs.com/ +// Definitions by: horiuchi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "mongoose" { + function connect(uri: string, options?: ConnectionOptions , callback?: (err: any) => void): Mongoose; + function createConnection(): Connection; + function createConnection(uri: string, options?: ConnectionOptions): Connection; + function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOptions): Connection; + function disconnect(callback?: (err?: any) => void): Mongoose; + + function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; + function modelNames(): string[]; + function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + + function get(key: string): any; + function set(key: string, value: any): void; + + var mongo: any; + var mquery: any; + var version: string; + var connection: Connection; + + export class Mongoose { + connect(uri: string, options?: ConnectOpenOptionsBase, callback?: (err: any) => void): Mongoose; + createConnection(): Connection; + createConnection(uri: string, options?: Object): Connection; + createConnection(host: string, database_name: string, port?: number, options?: ConnectOpenOptionsBase): Connection; + disconnect(callback?: (err?: any) => void): Mongoose; + get(key: string): any; + model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; + modelNames(): string[]; + plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + set(key: string, value: any): void; + + mongo: any; + mquery: any; + version: string; + connection: Connection; + Promise: any; + } + + export interface Connection extends NodeJS.EventEmitter { + constructor(base: Mongoose): Connection; + + close(callback?: (err: any) => void): Connection; + collection(name: string, options?: Object): Collection; + model(name: string, schema?: Schema, collection?: string): Model; + modelNames(): string[]; + open(host: string, database?: string, port?: number, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; + openSet(uris: string, database?: string, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; + + db: any; + collections: {[index: string]: Collection}; + readyState: number; + } + + export interface ConnectOpenOptionsBase { + db?: any; + server?: any; + replset?: any; + /** Username for authentication if not supplied in the URI. */ + user?: string; + /** Password for authentication if not supplied in the URI. */ + pass?: string; + /** Options for authentication */ + auth?: any; + } + + export interface ConnectionOptions extends ConnectOpenOptionsBase { + /** Passed to the underlying driver's Mongos instance. */ + mongos?: MongosOptions; + } + + interface OpenSetConnectionOptions extends ConnectOpenOptionsBase { + /** If true, enables High Availability support for mongos */ + mongos?: boolean; + } + + interface MongosOptions { + /** Turn on high availability monitoring. (default: true) */ + ha?: boolean; + /** Time between each replicaset status check. (default: 5000) */ + haInterval?: number; + /** + * Number of connections in the connection pool for each + * server instance. (default: 5 (for legacy reasons)) */ + poolSize?: number; + /** + * Use ssl connection (needs to have a mongod server with + * ssl support). (default: false). + */ + ssl?: boolean; + /** + * Validate mongod server certificate against ca + * (needs to have a mongod server with ssl support, 2.4 or higher) + * (default: true) + */ + sslValidate?: boolean; + /** Turn on high availability monitoring. */ + sslCA?: (Buffer|string)[]; + sslKey?: Buffer|string; + sslPass?: Buffer|string; + socketOptions?: { + noDelay?: boolean; + keepAlive?: number; + connectionTimeoutMS?: number; + socketTimeoutMS?: number; + }; + } + + export interface Collection { + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeOrderedBulkOp + initializeOrderedBulkOp(options?: CollectionOptions): OrderedBulkOperation; + //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeUnorderedBulkOp + initializeUnorderedBulkOp(options?: CollectionOptions): UnorderedBulkOperation; + } + + export interface CollectionOptions { + //The write concern. + w?: number | string; + //The write concern timeout. + wtimeout?: number; + //Specify a journal write concern. + j?: boolean; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html + export interface OrderedBulkOperation { + length: number; + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#execute + execute(callback: MongoCallback): void; + execute(options?: FSyncOptions): Promise; + execute(options: FSyncOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#find + find(selector: Object): FindOperatorsOrdered; + //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#insert + insert(doc: Object): OrderedBulkOperation; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html + export interface UnorderedBulkOperation { + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#execute + execute(callback: MongoCallback): void; + execute(options?: FSyncOptions): Promise; + execute(options: FSyncOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#find + find(selector: Object): FindOperatorsUnordered; + //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#insert + insert(doc: Object): UnorderedBulkOperation; + } + + export interface MongoCallback { + (error: MongoError, result: T): void; + } + + // http://mongodb.github.io/node-mongodb-native/2.1/api/MongoError.html + export class MongoError extends Error { + constructor(message: string); + static create(options: Object): MongoError; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/BulkWriteResult.html + export interface BulkWriteResult { + ok: number; + nInserted: number; + nUpdated: number; + nUpserted: number; + nModified: number; + nRemoved: number; + + getInsertedIds(): Array; + getLastOp(): Object; + getRawResponse(): Object; + getUpsertedIdAt(index: number): Object; + getUpsertedIds(): Array; + getWriteConcernError(): WriteConcernError; + getWriteErrorAt(index: number): WriteError; + getWriteErrorCount(): number; + getWriteErrors(): Array; + hasWriteErrors(): boolean; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/WriteError.html + export interface WriteError { + //Write concern error code. + code: number; + //Write concern error original bulk operation index. + index: number; + //Write concern error message. + errmsg: string; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/WriteConcernError.html + export interface WriteConcernError { + //Write concern error code. + code: number; + //Write concern error message. + errmsg: string; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser + export interface FSyncOptions { + w?: number | string; + wtimeout?: number; + j?: boolean; + fsync?: boolean + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsOrdered.html + export interface FindOperatorsOrdered { + delete(): OrderedBulkOperation; + deleteOne(): OrderedBulkOperation; + replaceOne(doc: Object): OrderedBulkOperation; + update(doc: Object): OrderedBulkOperation; + updateOne(doc: Object): OrderedBulkOperation; + upsert(): FindOperatorsOrdered; + } + + //http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsUnordered.html + export interface FindOperatorsUnordered { + length: number; + remove(): UnorderedBulkOperation; + removeOne(): UnorderedBulkOperation; + replaceOne(doc: Object): UnorderedBulkOperation; + update(doc: Object): UnorderedBulkOperation; + updateOne(doc: Object): UnorderedBulkOperation; + upsert(): FindOperatorsUnordered; + } + + export class SchemaType { } + export class VirtualType { + get(fn: Function): VirtualType; + set(fn: Function): VirtualType; + } + export module Types { + export class ObjectId { + constructor(id?: string|number); + toHexString(): string; + equals(other: ObjectId): boolean; + getTimestamp(): Date; + isValid(): boolean; + static createFromTime(time: number): ObjectId; + static createFromHexString(hexString: string): ObjectId; + static isValid(id?: string|number):boolean; + } + } + + export class Schema { + static Types: { + String: String; + ObjectId: Types.ObjectId; + OId: Types.ObjectId; + Mixed: any; + }; + + methods: any; + statics: any; + + constructor(schema?: Object, options?: Object); + + add(obj: Object, prefix?: string): void; + eachPath(fn: (path: string, type: any) => void): Schema; + get(key: string): any; + index(fields: Object, options?: Object): Schema; + indexes(): void; + method(name: string, fn: Function): Schema; + method(method: Object): Schema; + path(path: string): any; + path(path: string, constructor: any): Schema; + pathType(path: string): string; + plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema; + + pre(method: string, fn: HookSyncCallback, errorCb?: HookErrorCallback): Schema; + pre(method: string, isAsync: boolean, fn: HookAsyncCallback, errorCb?: HookErrorCallback): Schema; + post(method: string, fn: (doc: Document, next?: HookNextFunction) => any ): Schema; + + requiredPaths(): string[]; + set(key: string, value: any): void; + static(name: string, fn: Function): Schema; + virtual(name: string, options?: Object): VirtualType; + virtualpath(name: string): VirtualType; + + } + + // hook functions: https://github.com/vkarpov15/hooks-fixed + export interface HookSyncCallback { + (next: HookNextFunction, ...hookArgs:any[]): any; + } + + export interface HookAsyncCallback { + (next: HookNextFunction, done: HookDoneFunction, ...hookArgs:any[]): any; + } + + export interface HookErrorCallback { + (error: Error): any; + } + + export interface HookNextFunction { + (error: Error): any; + (...hookArgs:any[]): any; + } + + export interface HookDoneFunction { + (error: Error): any; + (...hookArgs:any[]): any; + } + + export interface SchemaOption { + autoIndex?: boolean; + bufferCommands?: boolean; + capped?: boolean; + collection?: string; + id?: boolean; + _id?: boolean; + minimize?: boolean; + read?: string; + safe?: boolean; + shardKey?: boolean; + strict?: boolean; + toJSON?: Object; + toObject?: Object; + versionKey?: boolean; + } + + export interface Model extends NodeJS.EventEmitter { + new(doc?: Object, fields?: Object, skipInit?: boolean): T; + + aggregate(...aggregations: Object[]): Aggregate; + aggregate(aggregation: Object, callback: (err: any, res: T[]) => void): Promise; + aggregate(aggregation1: Object, aggregation2: Object, callback: (err: any, res: T[]) => void): Promise; + aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise; + count(conditions: Object, callback?: (err: any, count: number) => void): Query; + + create(doc: Object, fn?: (err: any, res: T) => void): Promise; + create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise; + create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise; + discriminator(name: string, schema: Schema): Model; + distinct(field: string, callback?: (err: any, res: T[]) => void): Query; + distinct(field: string, conditions: Object, callback?: (err: any, res: T[]) => void): Query; + ensureIndexes(callback: (err: any) => void): Promise; + + find(): Query; + find(cond: Object, callback?: (err: any, res: T[]) => void): Query; + find(cond: Object, fields: Object, callback?: (err: any, res: T[]) => void): Query; + find(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T[]) => void): Query; + findById(id: string, callback?: (err: any, res: T) => void): Query; + findById(id: string, fields: Object, callback?: (err: any, res: T) => void): Query; + findById(id: string, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndRemove(id: string, callback?: (err: any, res: T) => void): Query; + findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query; + findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + findOne(cond?: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query; + findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + + geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; + geoNear(point: number[], options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; + geoSearch(cond: Object, options: GeoSearchOption, callback?: (err: any, res: T[]) => void): Query; + increment(): T; + mapReduce(options: MapReduceOption, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; + mapReduce(options: MapReduceOption2, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; + model(name: string): Model; + + populate(doc: U, options: Object, callback?: (err: any, res: U) => void): Promise; + populate(doc: U[], options: Object, callback?: (err: any, res: U[]) => void): Promise; + update(cond: Object, update: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; + update(cond: Object, update: Object, options: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; + remove(cond: Object, callback?: (err: any) => void): Query<{}>; + save(callback?: (err: any, result: T, numberAffected: number) => void): Query; + where(path: string, val?: Object): Query; + + $where(argument: string): Query; + $where(argument: Function): Query; + + base: Mongoose; + collection: Collection; + db: any; + discriminators: any; + modelName: string; + schema: Schema; + } + export interface FindAndUpdateOption { + new?: boolean; + upsert?: boolean; + sort?: Object; + select?: Object; + } + export interface GeoSearchOption { + near: number[]; + maxDistance: number; + limit?: number; + lean?: boolean; + } + export interface MapReduceOption { + map: () => void; + reduce: (key: Key, vals: T[]) => Val; + query?: Object; + limit?: number; + keeptemp?: boolean; + finalize?: (key: Key, val: Val) => Val; + scope?: Object; + jsMode?: boolean; + verbose?: boolean; + out?: { + inline?: number; + replace?: string; + reduce?: string; + merge?: string; + }; + } + export interface MapReduceOption2 { + map: string; + reduce: (key: Key, vals: T[]) => Val; + query?: Object; + limit?: number; + keeptemp?: boolean; + finalize?: (key: Key, val: Val) => Val; + scope?: Object; + jsMode?: boolean; + verbose?: boolean; + out?: { + inline?: number; + replace?: string; + reduce?: string; + merge?: string; + }; + } + export interface MapReduceResult { + _id: Key; + value: Val; + } + + export class Query { + exec(callback?: (err: any, res: T) => void): Promise; + exec(operation: string, callback?: (err: any, res: T) => void): Promise; + exec(operation: Function, callback?: (err: any, res: T) => void): Promise; + + all(val: number): Query; + all(path: string, val: number): Query; + and(array: Object[]): Query; + box(val: Object): Query; + box(a: number[], b: number[]): Query; + batchSize(val: number): Query; + cast(model: Model, obj: Object): U; + //center(): Query; + //centerSphere(path: string, val: Object): Query; + circle(area: Object): Query; + circle(path: string, area: Object): Query; + comment(val: any): Query; + count(callback?: (err: any, count: number) => void): Query; + count(criteria: Object, callback?: (err: any, count: number) => void): Query; + distinct(callback?: (err: any, res: T) => void): Query; + distinct(field: string, callback?: (err: any, res: T) => void): Query; + distinct(criteria: Object, field: string, callback?: (err: any, res: T) => void): Query; + distinct(criteria: Query, field: string, callback?: (err: any, res: T) => void): Query; + elemMatch(criteria: Object): Query; + elemMatch(criteria: (elem: Query) => void): Query; + elemMatch(path: string, criteria: Object): Query; + elemMatch(path: string, criteria: (elem: Query) => void): Query; + equals(val: Object): Query; + exists(val?: boolean): Query; + exists(path: string, val?: boolean): Query; + find(callback?: (err: any, res: T) => void): Query; + find(criteria: Object, callback?: (err: any, res: T) => void): Query; + findOne(callback?: (err: any, res: T) => void): Query; + findOne(criteria: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; + findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; + findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; + geometry(object: Object): Query; + gt(val: number): Query; + gt(path: string, val: number): Query; + gte(val: number): Query; + gte(path: string, val: number): Query; + hint(val: Object): Query; + in(val: any[]): Query; + in(path: string, val: any[]): Query; + intersects(arg?: Object): Query; + lean(bool?: boolean): Query; + limit(val: number): Query; + lt(val: number): Query; + lt(path: string, val: number): Query; + lte(val: number): Query; + lte(path: string, val: number): Query; + maxDistance(val: number): Query; + maxDistance(path: string, val: number): Query; + maxScan(val: number): Query; + merge(source: Query): Query; + merge(source: Object): Query; + mod(val: number[]): Query; + mod(path: string, val: number[]): Query; + ne(val: any): Query; + ne(path: string, val: any): Query; + near(val: Object): Query; + near(path: string, val: Object): Query; + nearSphere(val: Object): Query; + nearSphere(path: string, val: Object): Query; + nin(val: any[]): Query; + nin(path: string, val: any[]): Query; + nor(array: Object[]): Query; + or(array: Object[]): Query; + polygon(...coordinatePairs: number[][]): Query; + polygon(path: string, ...coordinatePairs: number[][]): Query; + populate(path: string, select?: string, match?: Object, options?: Object): Query; + populate(path: string, select: string, model: string, match?: Object, options?: Object): Query; + populate(opt: PopulateOption): Query; + read(pref: string, tags?: Object[]): Query; + regex(val: RegExp): Query; + regex(path: string, val: RegExp): Query; + remove(callback?: (err: any, res: T) => void): Query; + remove(criteria: Object, callback?: (err: any, res: T) => void): Query; + select(arg: string): Query; + select(arg: Object): Query; + setOptions(options: Object): Query; + size(val: number): Query; + size(path: string, val: number): Query; + skip(val: number): Query; + slaveOk(v?: boolean): Query; + slice(val: number): Query; + slice(val: number[]): Query; + slice(path: string, val: number): Query; + slice(path: string, val: number[]): Query; + snapshot(v?: boolean): Query; + sort(arg: Object): Query; + sort(arg: string): Query; + stream(options?: { transform?: Function; }): QueryStream; + tailable(v?: boolean): Query; + toConstructor(): Query; + update(callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(criteria: Object, doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + update(criteria: Object, doc: Object, options: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; + where(path?: string, val?: any): Query; + where(path?: Object, val?: any): Query; + within(val?: Object): Query; + within(coordinate: number[], ...coordinatePairs: number[][]): Query; + + $where(argument: string): Query; + $where(argument: Function): Query; + + static use$geoWithin: boolean; + } + + export interface PopulateOption { + path: string; + select?: string; + model?: string; + match?: Object; + options?: Object; + } + + export interface QueryStream extends NodeJS.EventEmitter { + destory(err?: any): void; + pause(): void; + resume(): void; + pipe(destination: T, options?: { end?: boolean; }): T; + paused: number; + readable: boolean; + } + + export interface Document { + id?: string; + _id: any; + + equals(doc: Document): boolean; + get(path: string, type?: new(...args: any[]) => any): any; + inspect(options?: Object): string; + invalidate(path: string, errorMsg: string, value: any): void; + invalidate(path: string, error: Error, value: any): void; + isDirectModified(path: string): boolean; + isInit(path: string): boolean; + isModified(path?: string): boolean; + isSelected(path: string): boolean; + markModified(path: string): void; + modifiedPaths(): string[]; + populate(callback?: (err: any, res: T) => void): Document; + populate(path?: string, callback?: (err: any, res: T) => void): Document; + populate(opt: PopulateOption, callback?: (err: any, res: T) => void): Document; + populated(path: string): any; + remove(callback?: (err: any) => void): Query; + save(callback?: (err: any, res: T) => void): void; + set(path: string, val: any, type?: new(...args: any[]) => any, options?: Object): void; + set(path: string, val: any, options?: Object): void; + set(value: Object): void; + toJSON(options?: Object): Object; + toObject(options?: Object): Object; + toString(): string; + update(doc: Object, options: Object, callback: (err: any, affectedRows: number, raw: any) => void): Query; + validate(cb: (err: any) => void): void; + + isNew: boolean; + errors: Object; + schema: Object; + } + + + export class Aggregate { + constructor(...options: Object[]); + + append(...options: Object[]): Aggregate; + group(arg: Object): Aggregate; + limit(num: number): Aggregate; + match(arg: Object): Aggregate; + near(parameters: Object): Aggregate; + project(arg: string): Aggregate; + project(arg: Object): Aggregate; + select(filter: string): Aggregate; + skip(num: number): Aggregate; + sort(arg: string): Aggregate; + sort(arg: Object): Aggregate; + unwind(fiels: string, ...rest: string[]): Aggregate; + + exec(callback?: (err: any, result: T) => void): Promise; + read(pref: string, ...tags: Object[]): Aggregate; + } + + export class Promise { + constructor(fn?: (err: any, result: T) => void); + + then(onFulFill: (result: T) => void | U | Promise, onReject?: (err: any) => void | U | Promise): Promise; + end(): void; + + fulfill(result: T): Promise; + reject(err: any): Promise; + resolve(err: any, result: T): Promise; + + onFulfill(listener: (result: T) => void): Promise; + onReject(listener: (err: any) => void): Promise; + onResolve(listener: (err: any, result: T) => void): Promise; + on(event: string, listener: Function): Promise; + + // Deprecated methods. + addBack(listener: (err: any, result: T) => void): Promise; + addCallback(listener: (result: T) => void): Promise; + addErrback(listener: (err: any) => void): Promise; + complete(result: T): Promise; + error(err: any): Promise; + } + +} \ No newline at end of file diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 2f6467437c..d2a36aeb54 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1,75 +1,894 @@ /// +/// +import * as bluebird from 'bluebird'; +import * as mongoose from 'mongoose'; var fs = require('fs'); -import mongoose = require('mongoose'); -var createInstance = new mongoose.Mongoose(); +// dummy variables +var cb = function () {}; -var Schema = mongoose.Schema; -var CreateSchema = new Schema({}); +/* + * Most of these tests are taken directly from the examples + * in the Mongoose API documentation. + * + * http://mongoosejs.com/docs/guide.html + * http://mongoosejs.com/docs/api.html + */ -mongoose.connect('mongodb://user:pass@localhost:port/database'); -mongoose.connect('mongodb://hostA:27501,hostB:27501', { mongos: true }); +/* + * section index.js + * http://mongoosejs.com/docs/api.html#index-js + */ +var connectUri = 'mongodb://user:pass@localhost:port/database'; +mongoose.connect(connectUri).then(cb).catch(cb); +mongoose.connect(connectUri, { + user: 'larry', + pass: 'housan', + config: { + autoIndex: true + }, + mongos: true +}).then(cb); +mongoose.connect(connectUri, function (error) { + error.stack; +}); +var mongooseConnection: mongoose.Connection = mongoose.createConnection(); +mongoose.createConnection(connectUri).open(''); +mongoose.createConnection(connectUri, { + db: { + native_parser: true + } +}).open(''); +mongoose.createConnection('localhost', 'database', 3000).open(''); +mongoose.createConnection('localhost', 'database', 3000, { + user: 'larry', + config: { + autoIndex: false + } +}).open(''); +mongoose.disconnect(cb).then(cb); +mongoose.get('test'); +mongoose.model('Actor', new mongoose.Schema({ + name: String +}), 'collectionName', true).find({}); +mongoose.model('Actor').find({}); +mongoose.modelNames()[0].toLowerCase(); +new (new mongoose.Mongoose()).Mongoose().connect(''); +mongoose.plugin(cb, {}).connect(''); +mongoose.set('test', 'value'); +mongoose.set('debug', function(collectionName: any, methodName: any, arg1: any, arg2: any) {}); +mongoose.STATES.hasOwnProperty(''); +mongoose.connection.on('error', cb); +new mongoose.mongo.MongoError('error').stack; +mongoose.SchemaTypes.String; +mongoose.Types.ObjectId; +mongoose.version.toLowerCase(); -var conn: mongoose.Connection = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); -conn = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', { replset: { strategy: 'ping', rs_name: 'testSet' }}); -conn = mongoose.createConnection('localhost', 'database', 27014); -conn = mongoose.createConnection('localhost', 'database', 27014, { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }); -conn = mongoose.createConnection(); -conn.open('localhost', 'database', 27014, {}); +/* + * section querystream.js + * http://mongoosejs.com/docs/api.html#querystream-js + */ +var querystream: mongoose.QueryStream; +querystream.destroy(new Error()); +querystream.pause(); +querystream.pipe(process.stdout, {end: true}).end(); +querystream.resume(); +querystream.paused; +querystream.readable; +/* inherited properties */ +querystream.getMaxListeners(); +/* practical examples */ +var QSModel: typeof mongoose.Model; +var QSStream: mongoose.QueryStream = QSModel.find().stream(); +QSStream.on('data', function (doc: any) { + doc.save(); +}).on('error', function (err: any) { + throw err; +}).on('close', cb); +QSModel.where('created').gte(20000).stream().pipe(process.stdout); -var db = mongoose.createConnection(); -db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"); -db.openSet('mongodb://mongosA:27501,mongosB:27501', 'db', { mongos: true }, (err: any) => {}); -db.close(); +/* + * section collection.js + * http://mongoosejs.com/docs/api.html#collection-js + * + * section drivers/node-mongodb-native/collection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js + */ +var coll1: mongoose.Collection; +coll1.$format(999).toLowerCase(); +coll1.$print('name', 'i', [1, 2, 3]); +coll1.getIndexes(); +/* inherited properties */ +coll1.collectionName; +coll1.conn; +coll1.name; +coll1.insureIndex(); +coll1.find({}); +coll1.insert({}, {}, {}); -var collection = db.collection('collection1'); +/* + * section connection.js + * http://mongoosejs.com/docs/api.html#connection-js + * + * section section drivers/node-mongodb-native/connection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js + */ +var conn1: mongoose.Connection = mongoose.createConnection('mongodb://user:pass@localhost:port/database'); +conn1 = new mongoose.Connection(mongoose); +conn1.open('mongodb://localhost/test', 'myDb', 27017, { + replset: null, + config: { + autoIndex: false + } +}, function (err) {}).open(''); +conn1.openSet('mongodb://localhost/test', 'db', { + replset: null, + mongos: true +}, function (err) {}).then(cb).catch(cb); +conn1.close().catch(function (err) {}); +conn1.collection('name').$format(999); +conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); +conn1.modelNames()[0].toLowerCase(); +conn1.config.hasOwnProperty(''); +conn1.db.bufferMaxEntries; +conn1.collections['coll'].$format(999); +conn1.readyState.toFixed(); +conn1.useDb('myDb').useDb(''); +mongoose.Connection.STATES.hasOwnProperty(''); +/* inherited properties */ +conn1.on('data', cb); +conn1.addListener('close', cb); -mongoose.connection.on('error', (err: any) => {}); -mongoose.disconnect(); +/* + * section error/validation.js + * http://mongoosejs.com/docs/api.html#error-validation-js + */ +var validationError: mongoose.ValidationError; +validationError.toString().toLowerCase(); +/* inherited properties */ +validationError.stack; +validationError.message; -mongoose.set('test', 1234567890); -var value = mongoose.get('test'); -mongoose.set('debug', true); +/* + * section error.js + * http://mongoosejs.com/docs/api.html#error-js + */ +var mongooseError: mongoose.Error = new mongoose.Error('error'); +/* inherited properties */ +mongooseError.message; +mongooseError.name; +mongooseError.stack; +/* static properties */ +mongoose.Error.messages.hasOwnProperty(''); +mongoose.Error.Messages.hasOwnProperty(''); -interface IActor extends mongoose.Document { - name: string; +/* + * section querycursor.js + * http://mongoosejs.com/docs/api.html#querycursor-js + */ +var querycursor: mongoose.QueryCursor; +querycursor.close(function (error, result) { + result.execPopulate(); +}).catch(cb); +querycursor.eachAsync(function (doc) { + doc.execPopulate(); +}, function (err) {}).catch(cb); +querycursor.next(cb).catch(cb); +/* inherited properties */ +querycursor.pause(); +querycursor.pipe(process.stdout); +/* practical example */ +var QCModel = mongoose.model('QC', new mongoose.Schema({name: String})); +QCModel.find({}).cursor({}).on('data', function (doc: any) { + doc.depopulate('name'); +}).on('error', function (error: any) { + throw error; +}).close().then(cb).catch(cb); + +/* + * section virtualtype.js + * http://mongoosejs.com/docs/api.html#virtualtype-js + */ +var virtualtype: mongoose.VirtualType = new mongoose.VirtualType({}, 'hello'); +virtualtype.applyGetters({}, {}); +virtualtype.applySetters({}, {}); +virtualtype.get(cb).get(cb); +virtualtype.set(cb).set(cb); + +/* + * section schema.js + * http://mongoosejs.com/docs/api.html#schema-js + */ +var schema: mongoose.Schema = new mongoose.Schema({ + name: String, + binary: Buffer, + living: Boolean, + updated: { type: Date, default: Date.now }, + age: { type: Number, min: 18, max: 65 }, + mixed: mongoose.Schema.Types.Mixed, + _someId: mongoose.Schema.Types.ObjectId, + array: [], + ofString: [String], + ofNumber: [Number], + ofDates: [Date], + ofBuffer: [Buffer], + ofBoolean: [Boolean], + ofMixed: [mongoose.Schema.Types.Mixed], + ofObjectId: [mongoose.Schema.Types.ObjectId], + nested: { + stuff: { type: String, lowercase: true, trim: true } + } +}); +schema.add({ + mixedArray: { + type: [mongoose.Schema.Types.Mixed], + required: true + } +}, 'prefix'); +schema.eachPath(function (path, type) { + path.toLowerCase(); + type.sparse(true); +}).eachPath(cb); +schema.get('path'); +schema.index({ + name: 1, + binary: -1 +}).index({}, {}); +schema.indexes().slice(); +schema.method('name', cb).method({ + m1: cb, + m2: cb +}); +schema.path('a', mongoose.Schema.Types.Buffer).path('a'); +schema.pathType('m1').toLowerCase(); +schema.plugin(function (schema, opts) { + schema.get('path'); + opts.hasOwnProperty(''); +}).plugin(cb, {opts: true}); +schema.post('post', function (doc) {}).post('post', function (doc, next) { + next(new Error()); +}); +schema.queue('m1', [1, 2, 3]).queue('m2', [[]]); +schema.remove('path'); +schema.remove(['path1', 'path2', 'path3']); +schema.requiredPaths(true)[0].toLowerCase(); +schema.set('key', 999).set('key'); +schema.static('static', cb).static({ + s1: cb, + s2: cb +}); +schema.virtual('virt', {}).applyGetters({}, {}); +schema.virtualpath('path').applyGetters({}, {}); +/* static properties */ +mongoose.Schema.indexTypes[0].toLowerCase(); +mongoose.Schema.reserved.hasOwnProperty(''); +/* inherited properties */ +schema.addListener('e', cb); +/* practical examples */ +var animalSchema = new mongoose.Schema({ + name: String, + type: String +}); +animalSchema.methods.findSimilarTypes = function (cb: any) { + return this.model('Aminal').find({ type: this.type }, cb); +}; +var Animal: any = mongoose.model('Animal', animalSchema); +var dog: any = new Animal({type: 'dog'}); +dog['findSimilarTypes'](function (err: any, dogs: any) { + console.log(dogs); +}); +new mongoose.Schema({ + title: String, + author: String, + body: String, + comments: [{ body: String, date: Date }], + date: { type: Date, default: Date.now }, + hidden: Boolean, + meta: { + votes: Number, + favs: Number + } +}); +animalSchema.statics.findByName = function(name: any, cb: any) { + return this.find({ name: new RegExp(name, 'i') }, cb); +}; +Animal['findByName']('fido', function(err: any, animals: any) { + console.log(animals); +}); +animalSchema.virtual('name.full').get(function () { + return this.name.first + ' ' + this.name.last; +}); +new mongoose.Schema({ + child: new mongoose.Schema({ name: 'string' }) +}); +new mongoose.Schema({ + eggs: { + type: Number, + min: [6, 'Too few eggs'], + max: 12 + }, + bacon: { + type: Number, + required: [true, 'Why no bacon?'] + }, + drink: { + type: String, + enum: ['Coffee', 'Tea'] + } +}); + +(new mongoose.Schema({})).plugin(function (schema: any, options: any) { + schema.add({ lastMod: Date }) + schema.pre('save', function (next: Function) { + this.lastMod = new Date + next() + }) + if (options && options['index']) { + schema.path('lastMod').index(options['index']) + } +}, { index: true }).plugin(function (schema: any, options: any) { + schema.add({ lastMod: Date }) + schema.pre('save', function (next: Function) { + this.lastMod = new Date + next() + }) + if (options && options['index']) { + schema.path('lastMod').index(options['index']) + } +}); + +/* + * section document.js + * http://mongoosejs.com/docs/api.html#document-js + */ +var doc: mongoose.Document; +doc.$isDefault('path').valueOf(); +doc.depopulate('path'); +doc.equals(doc).valueOf(); +doc.execPopulate().then(function (arg) { + arg.execPopulate(); +}).catch(function (err) {}); +doc.get('path', Number); +doc.init(doc, cb).init(doc, {}, cb); +doc.inspect(); +doc.invalidate('path', new Error('hi'), 999).toString(); +doc.isDirectModified('path').valueOf(); +doc.isInit('path').valueOf(); +doc.isModified('path').valueOf(); +doc.isSelected('path').valueOf(); +doc.markModified('path'); +doc.modifiedPaths()[0].toLowerCase(); +doc.populate(function (err, doc) { + doc.populate('path', function (err, doc) { + doc.populate({ + path: 'path', + select: 'path', + match: {} + }); + }); +}); +doc.populated('path'); +doc.set('path', 999, {}); +doc.set({ + path: 999 +}); +doc.toJSON({ + getters: true, + virtuals: false +}); +doc.toObject({ + transform: function (doc, ret, options) { + doc.toObject(); + } +}); +doc.toString().toLowerCase(); +doc.unmarkModified('path'); +doc.update(doc, cb).cursor(); +doc.update(doc, { + safe: true, + upsert: true +}, cb).cursor(); +doc.validate({}, function (err) {}); +doc.validate().then(null).catch(null); +doc.validateSync(['path1', 'path2']).stack; +/* practical examples */ +var MyModel = mongoose.model('test', new mongoose.Schema({ + name: { + type: String, + default: 'Val ' + } +})); +doc = new MyModel(); +doc.$isDefault('name'); +MyModel.findOne().populate('author').exec(function (err, doc) { + doc.depopulate('author'); +}); +doc.populate('path'); +doc.populate({path: 'hello'}); +doc.populate('path', cb) +doc.populate({path: 'hello'}, cb); +doc.populate(cb); +doc.populate({path: 'hello'}).execPopulate().catch(cb); +doc.update({$inc: {wheels:1}}, { w: 1 }, cb); + +/* + * section types/subdocument.js + * http://mongoosejs.com/docs/api.html#types-subdocument-js + */ +// The constructor is private api, but we'll use it to test +var subdocument: mongoose.Types.Subdocument = new mongoose.Types.Subdocument(); +subdocument.ownerDocument().errors; +subdocument.remove({}, function (err) { + return 6; +}); +/* inherited properties */ +subdocument.execPopulate(); + +/* + * section types/array.js + * http://mongoosejs.com/docs/api.html#types-array-js + */ +var mongooseArray: mongoose.Types.Array = new mongoose.Types.Array(); +mongooseArray.$shift().toLowerCase(); +mongooseArray.remove().$shift(); +mongooseArray.$pop().toLowerCase(); +mongooseArray.addToSet('hi', 9, 9, '4')[0].toLowerCase(); +mongooseArray.indexOf({name: 'obj'}).toFixed(); +mongooseArray.inspect(); +mongooseArray.nonAtomicPush(9, 8, 'hi').toFixed(); +mongooseArray.pop().toLowerCase(); +mongooseArray.pull(5, 4, 'hi').$shift(); +mongooseArray.push([]).toFixed(); +mongooseArray.set(1, 'hi').$shift(); +mongooseArray.shift().toLowerCase(); +mongooseArray.sort(function (a: any, b: any) { + return a.length - b.length; +}).unshift(); +mongooseArray.splice(4, 1).unshift(); +mongooseArray.toObject({depopulate: true}).unshift(); +mongooseArray.unshift(2, 4, 'hi').toFixed(); +/* inherited properties */ +mongooseArray.concat(); +mongooseArray.length; + +/* + * section types/documentarray.js + * 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 = + new mongoose.Types.DocumentArray(); +documentArray.create({}).errors; +documentArray.id(new Buffer('hi')); +documentArray.inspect(); +documentArray.toObject({}).length; +/* inherited from mongoose.Types.Array */ +documentArray.$shift(); +/* inherited from Native Array */ +documentArray.concat(); + +/* + * section types/buffer.js + * http://mongoosejs.com/docs/api.html#types-buffer-js + */ +var mongooseBuffer: mongoose.Types.Buffer = new mongoose.Types.Buffer('hello'); +mongooseBuffer.copy(mongooseBuffer, 1, 2, 3).toFixed(); +mongooseBuffer.copy(new Buffer('hi')).toFixed(); +mongooseBuffer.equals(new Buffer('hi')).valueOf(); +mongooseBuffer.subtype(123); +mongooseBuffer.toObject().value(); +mongooseBuffer.write('world', 3, 2, 1).toFixed(); +/* inherited properties */ +mongooseBuffer.compare(mongooseBuffer); +/* inherited static properties */ +mongoose.Types.Buffer.from([1, 2, 3]); + +/* + * section types/objectid.js + * http://mongoosejs.com/docs/api.html#types-objectid-js + */ +var objectId: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexString('0x1234'); +objectId = new mongoose.Types.ObjectId(12345); +objectId.getTimestamp(); +/* practical examples */ +export interface IManagerSchema extends mongoose.Document { + user: mongoose.Schema.Types.ObjectId; } -mongoose.model('Actor', new Schema({ name: String })); -db.model('Actor', new Schema({ name: String })); -var schema: mongoose.Schema = new Schema({ name: String }, { collection: 'actor' }); -schema.set('collection', 'actor'); -var Model = mongoose.model('Actor', schema, 'actor'); +export var ManagerSchema = new mongoose.Schema({ + user: { + type: mongoose.Schema.Types.ObjectId, + ref: 'User', + required: true + } +}); -interface IZip extends mongoose.Document { - _id: string; -} -interface IPerson extends mongoose.Document { - _id: mongoose.Types.ObjectId; -} -interface IThing extends mongoose.Document { - _id: number; -} +/* + * section types/embedded.js + * http://mongoosejs.com/docs/api.html#types-embedded-js + */ +var embeddedDocument: mongoose.Types.Embedded = new mongoose.Types.Embedded(); +embeddedDocument.inspect().hasOwnProperty(''); +embeddedDocument.invalidate('hi', new Error('bleh')).valueOf(); +embeddedDocument.ownerDocument().execPopulate(); +embeddedDocument.parent().execPopulate(); +embeddedDocument.parentArray().$shift(); +embeddedDocument.remove().invalidate('hi', new Error('hi')); +embeddedDocument.markModified('path'); +/* inherited properties */ +embeddedDocument.execPopulate(); -var names: string[] = mongoose.modelNames(); -var names: string[] = db.modelNames(); -mongoose.plugin((schema: mongoose.Schema) => { -}, { index: true }); +/* + * section query.js + * http://mongoosejs.com/docs/api.html#query-js + */ +var query: mongoose.Query; +query.$where('').$where(cb); +query.all(99).all('path', 99); +query.and([{ color: 'green' }, { status: 'ok' }]).and([]); +query.batchSize(100).batchSize(100); +var lowerLeft = [40.73083, -73.99756] +var upperRight = [40.741404, -73.988135] +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.center({}).center({}); +query.centerSphere({ center: [50, 50], radius: 10 }).centerSphere('path', {}); +query.circle({ center: [50, 50], radius: 10 }).circle('path'); +query.comment('comment').comment('comment'); +query.where({color: 'black'}).count(function (err, count) { + count.toFixed(); +}).then(function (res) { + res.toFixed(); +}).catch(function (err) {}); +query.cursor().close(); +query.distinct('field', {}, cb); +query.distinct('field', {}); +query.distinct('field', cb); +query.distinct('field'); +query.distinct(cb); +query.distinct(); +query.elemMatch('comment', { + author: 'autobot', + votes: {$gte: 5} +}).elemMatch('comment', function (elem) { + elem.where('author').equals('autobot'); + elem.where('votes').gte(5); +}); +query.where('age').equals(49); +query.exec('find', function (err, res) { + res[0].execPopulate(); +}).then(function (arg) { + arg[0].execPopulate(); +}).catch(cb); +query.where('name').exists().exists('age', false); +query.find({name: 'aa'}, function (err, res) { + res[0].execPopulate(); +}).find(); +query.findOne(function (err, res) { + res.execPopulate(); +}).findOne(); +query.findOneAndRemove({name: 'aa'}, { + passRawResult: true +}, function (err, doc) { + doc.execPopulate(); +}).findOneAndRemove(); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, { +}); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, { + passRawResult: true +}, cb); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}, cb); +query.findOneAndUpdate({name: 'aa'}, {name: 'bb'}); +query.findOneAndUpdate({name: 'bb'}, cb); +query.findOneAndUpdate({name: 'bb'}); +query.findOneAndUpdate(cb); +query.findOneAndUpdate().then(function (doc) { + doc.execPopulate(); +}).catch(cb); +var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] +query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA }) +var polyB = [[ 0, 0 ], [ 1, 1 ]] +query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB }) +var polyC = [ 0, 0 ] +query.where('loc').within().geometry({ type: 'Point', coordinates: polyC }) +query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC }) +query.getQuery(); +query.getUpdate(); +query.find().where('age').gt(21); +query.find().gt('age', 21); +query.find().where('age').gte(21); +query.find().gte('age', 21); +query.hint({ indexA: 1, indexB: -1}).hint({}); +query.in([1, 2, 3]).in('num', [1, 2, 3]); +query.where('path').intersects().geometry({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}); +query.where('path').intersects({ + type: 'LineString' + , coordinates: [[180.0, 11.0], [180, 9.0]] +}); +query.find().lean().exec(function (err: any, docs: any) { + docs[0]; +}); +query.limit(20).limit(20); +query.find().where('age').lt(21); +query.find().lt('age', 21); +query.find().where('age').lte(21); +query.find().lte('age', 21); +query.maxDistance('path', 21).maxDistance(21); +query.maxscan(100).maxScan(100); +query.maxScan(100).maxScan(100); +query.merge(query).merge({}); +query.mod([1, 2]).mod([5, 6]); +query.find().where('age').ne(21); +query.find().ne('age', 21); +query.where('loc').near({ center: [10, 10] }); +query.where('loc').near({ center: [10, 10], maxDistance: 5 }); +query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); +query.near('loc', { center: [10, 10], maxDistance: 5 }); +query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); +query.find().where('age').in([20, 21]); +query.find().in('age', [20, 21]); +query.nor([{ color: 'green' }, { status: 'ok' }]).nor([]); +query.or([{ color: 'red' }, { status: 'emergency' }]).or([]); +query.where('loc').within().polygon([10,20], [13, 25], [7,15]); +query.polygon('loc', [10,20], [13, 25], [7,15]); +query.findOne().populate('owner').exec(function (err, kitten) { + kitten.execPopulate(); +}); +query.find().populate({ + path: 'owner' + , select: 'name' + , match: { color: 'black' } + , options: { sort: { name: -1 }} +}).exec(function (err, kittens) { + kittens[0].execPopulate(); +}); +query.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) { + kittens[0].execPopulate(); +}); +query.read('primary', []).read('primary'); +query.regex(/re/).regex('path', /re/); +query.remove({}, cb); +query.remove({}); +query.remove(cb); +query.remove(); +query.select('a b'); +query.select('-c -d'); +query.select({ a: 1, b: 1 }); +query.select({ c: 0, d: 0 }); +query.select('+path'); +query.selected(); +query.selectedExclusively(); +query.selectedInclusively(); +query.setOptions({ + tailable: true, + batchSize: true, + lean: false +}); +query.size(0).size('age', 0); +query.skip(100).skip(100); +query.slaveOk().slaveOk(false); +query.slice('comments', 5); +query.slice('comments', -5); +query.slice('comments', [10, 5]); +query.where('comments').slice(5); +query.where('comments').slice([-10, 5]); +query.snapshot().snapshot(true); +query.sort({ field: 'asc', test: -1 }); +query.sort('field -test'); +query.stream().on('data', function (doc: any) { +}).on('error', function (err: any) { +}).on('close', function () { +}); +query.tailable().tailable(false); +query.then(cb).catch(cb); +(new (query.toConstructor())()).toConstructor(); +query.update({}, doc, { -var aggregate = new mongoose.Aggregate(); -var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }); -var aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); -var aggregate = new mongoose.Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); +}, cb); +query.update({}, doc, { + +}); +query.update({}, doc, cb); +query.update({}, doc); +query.update(doc, cb); +query.update(doc); +query.update(cb); +query.update(true); +query.update(); +query.where('age').gte(21).lte(65) + .where('name', /^vonderful/i) + .where('friends').slice(10) + .exec(cb); +query.where('path').within().box({}) +query.where('path').within().circle({}) +query.where('path').within().geometry({type: 'c', coordinates: []}); +query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); +query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); +query.where('loc').within({ polygon: [[],[],[],[]] }); +query.where('loc').within([], [], []); +query.where('loc').within([], []); +query.where('loc').within({ type: 'LineString', coordinates: [] }); +mongoose.Query.use$geoWithin = false; +/* practical example */ +query. + find({ + occupation: /host/, + 'name.last': 'Ghost', + age: { $gt: 17, $lt: 66 }, + likes: { $in: ['vaporizing', 'talking'] } + }). + limit(10). + sort({ occupation: -1 }). + select({ name: 1, occupation: 1 }). + exec(cb).then(cb).catch(cb); +query. + find({ occupation: /host/ }). + where('name.last').equals('Ghost'). + where('age').gt(17).lt(66). + where('likes').in(['vaporizing', 'talking']). + limit(10). + sort('-occupation'). + select('name occupation'). + exec(cb).then(cb).catch(cb); + +/* + * section schema/array.js + * http://mongoosejs.com/docs/api.html#schema-array-js + */ +var schemaArray: mongoose.Schema.Types.Array = new mongoose.Schema.Types.Array('key', new mongoose.SchemaType('hi'), {}); +schemaArray.checkRequired('hello').valueOf(); +/** static properties */ +mongoose.Schema.Types.Array.schemaName.toLowerCase(); +/** inherited properties */ +schemaArray.sparse(true); + +/* + * section schema/string.js + * http://mongoosejs.com/docs/api.html#schema-string-js + */ +var schemastring: mongoose.Schema.Types.String = new mongoose.Schema.Types.String('hello'); +schemastring.checkRequired(234, new mongoose.Document()).valueOf(); +schemastring.enum(['hi', 'a', 'b']).enum('hi').enum({}); +schemastring.lowercase().lowercase(); +schemastring.match(/re/, 'error').match(/re/); +schemastring.maxlength(999, 'error').maxlength(999); +schemastring.minlength(999, 'error').minlength(999); +schemastring.trim().trim(); +schemastring.uppercase().uppercase(); +/* static properties */ +mongoose.Schema.Types.String.schemaName.toLowerCase(); +/* inherited properties */ +schemastring.sparse(true); + +/* + * section schema/documentarray.js + * http://mongoosejs.com/docs/api.html#schema-documentarray-js + */ +var documentarray: mongoose.Schema.Types.DocumentArray = new mongoose.Schema.Types.DocumentArray('key', new mongoose.Schema()); +/* static properties */ +mongoose.Schema.Types.DocumentArray.schemaName.toLowerCase(); +/* inherited properties */ +documentarray.sparse(true); + +/* + * section schema/number.js + * 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.max(999, 'error').max(999); +schemanumber.min(999, 'error').min(999); +/* static properties */ +mongoose.Schema.Types.Number.schemaName.toLowerCase(); +/* inherited properties */ +schemanumber.sparse(true); + +/* + * section schema/date.js + * 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.expires(99).expires('now'); +schemadate.max(new Date(), 'error').max(new Date('')); +schemadate.min(new Date(), 'error').min(new Date('')); +/* static properties */ +mongoose.Schema.Types.Date.schemaName.toLowerCase(); +/* inherited properties */ +schemadate.sparse(true); + +/* + * section schema/buffer.js + * 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(); +/* static properties */ +mongoose.Schema.Types.Buffer.schemaName.toLowerCase(); +/* inherited properties */ +schemabuffer.sparse(true); + +/* + * section schema/boolean.js + * http://mongoosejs.com/docs/api.html#schema-boolean-js + */ +var schemaboolean: mongoose.Schema.Types.Boolean = new mongoose.Schema.Types.Boolean('99'); +schemaboolean.checkRequired(99).valueOf(); +/* static properties */ +mongoose.Schema.Types.Boolean.schemaName.toLowerCase(); +/* inherited properties */ +schemaboolean.sparse(true); + +/* + * section schema/objectid.js + * http://mongoosejs.com/docs/api.html#schema-objectid-js + */ +var schemaobjectid: mongoose.Schema.Types.ObjectId = new mongoose.Schema.Types.ObjectId('99'); +schemaobjectid.auto(true).auto(false); +schemaobjectid.checkRequired(99, new mongoose.Document()).valueOf(); +/* static properties */ +mongoose.Schema.Types.ObjectId.schemaName.toLowerCase(); +/* inherited properties */ +schemaobjectid.sparse(true); + +/* + * section schema/mixed.js + * http://mongoosejs.com/docs/api.html#schema-mixed-js + */ +var schemamixed: mongoose.Schema.Types.Mixed = new mongoose.Schema.Types.Mixed('99'); +/* static properties */ +mongoose.Schema.Types.Mixed.schemaName.toLowerCase(); +/* inherited properties */ +schemamixed.sparse(true); + +/* + * section schema/embedded.js + * http://mongoosejs.com/docs/api.html#schema-embedded-js + */ +var schemaembedded: mongoose.Schema.Types.Embedded = + new mongoose.Schema.Types.Embedded(new mongoose.Schema(), '99'); +/* inherited properties */ +schemaembedded.sparse(true); + +/* + * section aggregate.js + * http://mongoosejs.com/docs/api.html#aggregate-js + */ +var aggregate: mongoose.Aggregate; +aggregate = mongoose.model('ex').aggregate({ $match: { age: { $gte: 21 }}}); +aggregate = new mongoose.Aggregate(); +aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }); +aggregate = new mongoose.Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); +aggregate = new mongoose.Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); +aggregate.addCursorFlag('flag', true).addCursorFlag('', false); +aggregate.allowDiskUse(true).allowDiskUse(false, []); aggregate.append({ $project: { field: 1 }}, { $limit: 2 }); aggregate.append([{ $match: { daw: 'Logic Audio X' }} ]); -aggregate.group({ _id: "$department" }); -aggregate.skip(10); -aggregate.limit(10); -aggregate.match({ department: { $in: [ "sales", "engineering" ] } }); +aggregate.cursor({ batchSize: 1000 }).exec().each(cb); +aggregate.exec().then(cb).catch(cb); +aggregate.explain(cb).then(cb).catch(cb); +aggregate.group({ _id: "$department" }).group({ _id: "$department" }); +aggregate.limit(10).limit(10); +var lookupOpt = { + from: 'users', localField: + 'userId', foreignField: '_id', + as: 'users' +}; +aggregate.lookup(lookupOpt).lookup(lookupOpt); +aggregate.match({ + department: {$in: [ "sales", "engineering"]} +}); +aggregate.model(new (mongoose.model('xx'))()).model(null); aggregate.near({ near: [40.724, -73.997], - distanceField: "dist.calculated", // required + distanceField: "dist.calculated", maxDistance: 0.008, query: { type: "public" }, includeLocs: "dist.location", @@ -79,314 +898,317 @@ aggregate.near({ aggregate.project("a b -_id"); aggregate.project({a: 1, b: 1, _id: 0}); aggregate.project({ - newField: '$b.nested', - plusTen: { $add: ['$val', 10]}, - sub: { - name: '$a' - } -}); -aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); + newField: '$b.nested' + , plusTen: { $add: ['$val', 10]} + , sub: { + name: '$a' + } +}) +aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ]}}); +aggregate.read('primaryPreferred').read('pp'); +aggregate.sample(3).sample(3); +aggregate.skip(10).skip(10); aggregate.sort({ field: 'asc', test: -1 }); aggregate.sort('field -test'); -aggregate.unwind("tags"); -aggregate.unwind("a", "b", "c"); -var p = aggregate.exec(); -aggregate.read('primaryPreferred').exec((err: any, result: {}) => {}); +aggregate.then(cb).catch(cb); +aggregate.unwind("tags").unwind('tags'); +aggregate.unwind("a", "b", "c").unwind('tag1', 'tag2'); +/* + * section schematype.js + * http://mongoosejs.com/docs/api.html#schematype-js + */ +new mongoose.SchemaType('hello', 9, 'hello' ); +var STSchema = new mongoose.Schema({ + mixed: mongoose.Schema.Types.Mixed +}); +var schematype = schema.path('mixed'); +schematype.default('default'); +STSchema.path('born').get(cb).get(cb); +STSchema.path('name').index(true).index({ unique: true, sparse: true }); +schematype.required(true, 'mess').required(true); +schematype.select(true).select(false); +STSchema.path('name').set(cb).set(cb); +schematype.sparse(true).sparse(true); +schematype.text(true).text(true); +schematype.unique(true).unique(true); +schematype.validate(/re/) + .validate({}, 'error') + .validate(cb, 'try', 'tri'); -var p = new mongoose.Promise; -var p2 = p.then(function() { throw new Error('shucks') }).end(); -setTimeout(function() { - p.fulfill({}); -}, 10); -var promise = new mongoose.Promise(); -promise.then(function (meetups: number) { - return new mongoose.Promise(); -}).then(function (people: string[]) { - if (people.length < 10000) { - throw new Error('Too few people!!!'); - } else { - throw new Error('Still need more people!!!'); - } -}).then(null, function (err: Error) { +/* + * section promise.js + * http://mongoosejs.com/docs/api.html#promise-js + */ +var mongopromise = new mongoose.Promise(); +mongopromise = new mongoose.Promise(function (err: any, arg: any) { + arg.sparse(true); + err.stack; +}); +mongopromise = new mongoose.Promise(function (err: any, arg1: any, arg2: any) { + arg1.sparse(true); + arg2.sparse(true); + err.stack; +}); +mongopromise.addBack(function (err: any, arg: any) { + err.stack; + arg.sparse(true); +}).addBack(function (err: any, arg1: any, arg2: any) { + err.stack; + arg1.sparse(true); + arg2.sparse(true); +}); +mongopromise.addCallback(function (arg: any) { + arg.sparse(true); +}).addCallback(function (arg1: any, arg2: any) { + arg1.sparse(true); + arg2.sparse(true); +}); +mongopromise.addErrback(function (err: any) { + err.stack; +}).addErrback(function () {}); +mongopromise.catch(function (err: any) { + err.stack; +}).catch(function () {}); +mongopromise.end(); +mongopromise.error(999).error([]); +mongopromise.on('init', function () {}).on('init', function () {}); +mongopromise.reject({}).reject('').reject(new Error('hi')); +mongopromise.resolve(new Error('hi'), {}).resolve(); +mongopromise.then(function (arg: any) { + arg.sparse(true); +}, function (err: any) { + err.stack; +}).then(function (arg1: any, arg2: any) { + arg1.sparse(true); + arg2.sparse(true); +}); +mongopromise.complete(new mongoose.SchemaType('')).complete( + new mongoose.SchemaType(''), + new mongoose.SchemaType('') +); +/* static properties */ +mongoose.Promise.ES6(function (complete: any, error: any) { + complete.apply(this); + error.apply(this); }).end(); +/* inherited properties */ +mongopromise.chain(mongopromise); +mongoose.Promise.FAILURE; +/* pluggable promise */ +mongoose.Promise = global.Promise; +var nativePromise: Promise = new mongoose.Promise(); +nativePromise.race().then(cb).catch(cb); -Model.findOne({ name: 'john' }, (err: any, doc: mongoose.Document) => { - doc.invalidate('size', 'must be less than 20', 14); - doc.validate((err: any) => { }); +mongoose.Promise = bluebird; +var bluebirdPromise: bluebird = new mongoose.Promise(); +bluebirdPromise.cancellable().lastly(cb); - doc.set('documents.0.title', 'changed'); - doc.get('documents.0'); - doc.set({ - 'path' : 1, - 'path2' : { - 'path' : 2 - } +var PQuery: any; +PQuery.find().exec()['reduce']().then(cb).catch(cb); +(PQuery).find().exec().reduce().then(cb).catch(cb); + +/* + * section model.js + * http://mongoosejs.com/docs/api.html#model-js + */ +var MongoModel = mongoose.model('MongoModel', new mongoose.Schema({ + name: String, + type: { + type: mongoose.Schema.Types.Mixed, + required: true + } +}), 'myCollection', true); +MongoModel.$where('indexOf("val") !== -1').exec(function (err, docs) { + docs[0].save(); +}); +MongoModel.findById(999, function (err, doc) { + doc.increment(); + doc.save(cb).then(cb).catch(cb); +}); +MongoModel = (new MongoModel()).model('MongoModel'); +var mongoModel = new MongoModel(); +mongoModel.remove(function (err, product) { + if (err) throw(err); + MongoModel.findById(product._id, function (err, product) { + product.remove(); }); - doc.set('path', 'value', { strict: false }); - doc.set('path3', '1', Number); - doc.get('path3', Number); - doc.id; - doc._id; - - doc.isModified(); - doc.isModified('documents'); - doc.isModified('documents.0.title'); - doc.isDirectModified('documents.0.title'); - doc.isDirectModified('documents'); - doc.isSelected('name'); - - doc.markModified('mixed.type'); - doc.populate('user'); - doc.populate('other', (err: any, doc: mongoose.Document) => {}); - doc.populated('author'); - doc.save(); - - doc.toJSON({ getters: true, virtuals: false }); - var data: any = doc.toObject(); - delete data['age']; - delete data['weight']; - data['isAwesome'] = true; }); - -Model.model('User').findById('id', (err: any, res: IActor) => {}); -Model.count({ type: 'jungle' }, (err: any, count: number) => {}); -Model.remove((err: any, res: IActor[]) => {}); -Model.save((err: any, res: IActor, numberAffected: number) => {}); -Model.create({ type: 'jelly bean' }, { type: 'snickers' }, (err: any, res1: IActor, res2: IActor) => {}); -Model.create({ type: 'jawbreaker' }); -Model.create({ type: 'muffin' }).then(function (res) { - res.name; +mongoModel.save().then(function (product) { + product.save().then(cb).catch(cb); }); -Model.distinct('url', { clicks: {$gt: 100}}, (err: any, result: IActor[]) => {}); -Model.distinct('url'); - -Model.aggregate( - { $group: { _id: null, maxBalance: { $max: '$balance' }}}, - { $project: { _id: 0, maxBalance: 1 }}, - (err: any, res: IActor[]) => {}); -Model.aggregate() +MongoModel.aggregate( + { $group: { _id: null, maxBalance: { $max: '$balance' }}} + , { $project: { _id: 0, maxBalance: 1 }} + , cb); +MongoModel.aggregate() .group({ _id: null, maxBalance: { $max: '$balance' } }) - .select('-id maxBalance') - .exec((err: any, res: IActor[]) => {}); -Model.ensureIndexes((err) => {}); - -Model.find({ name: 'john', age: { $gte: 18 }}); -Model.find({ name: 'john', age: { $gte: 18 }}, (err: any, docs: IActor[]) => {}); -Model.find({ name: /john/i }, 'name friends', (err: any, docs: IActor[]) => {}); -Model.find({ name: /john/i }, null, { skip: 10 }); -Model.find({ name: /john/i }, null, { skip: 10 }, (err: any, docs: IActor[]) => {}); -Model.find({ name: /john/i }, null, { skip: 10 }).exec((err: any, docs: IActor[]) => {}); -var query = Model.find({ name: /john/i }, null, { skip: 10 }); -var promise1 = query.exec(); -promise1.addBack((err: any, docs: IActor[]) => {}); - -Model.findById('id', (err: any, res: IActor) => {}); -Model.findById('id').exec((err: any, res: IActor) => {}); -Model.findById('id', 'name length', (err: any, res: IActor) => {}); -Model.findById('id', '-length').exec((err: any, res: IActor) => {}); -Model.findById('id', 'name', { lean: true }, (err: any, res: IActor) => {}); -Model.findById('id', 'name').lean().exec((err: any, res: IActor) => {}); -Model.findByIdAndRemove('id1', { select: 'name' }, (err: any, res: IActor) => {}); -Model.findByIdAndRemove('id1', { select: 'name' }).exec((err: any, res: IActor) => {}); -Model.findByIdAndRemove('id1', (err: any, res: IActor) => {}); -Model.findByIdAndRemove('id1').exec((err: any, res: IActor) => {}); -Model.findByIdAndUpdate('id2', { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); - -Model.findOne({ type: 'iphone' }, (err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }).exec((err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }, 'name', (err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }, 'name').exec((err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }, 'name', { lean: true }, (err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }, 'name', { lean: true }).exec((err: any, res: IActor) => {}); -Model.findOne({ type: 'iphone' }).select('name').lean().exec((err: any, res: IActor) => {}); -Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }, (err: any, res: IActor) => {}); -Model.findOneAndRemove({ type: 'iphone' }, { select: 'name' }).exec((err: any, res: IActor) => {}); -Model.findOneAndUpdate({ type: 'iphone' }, { $set: { name: 'jason borne' }}, { upsert: true }, (err: any, res: IActor) => {}); - -Model.geoNear([1, 3], { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); -Model.geoNear({ type : "Point", coordinates : [9,9] }, { maxDistance : 5, spherical : true }, (err: any, res: IActor[], stats: any) => {}); -Model.geoSearch({ type : "house" }, { near: [10, 10], maxDistance: 5 }, (err: any, res: IActor[]) => {}); - -var o = { - map: function () { this.emit(this.name, 1) }, - reduce: function (k: string, vals: IActor[]) { return vals.length }, -}; -Model.mapReduce(o, (err: any, res: any[]) => {}); - -Model.findById('id', (err: any, res: IActor) => { - var opts = [ - { path: 'company', match: { x: 1 }, select: 'name' }, - { path: 'notes', options: { limit: 10 }, model: 'override' } - ]; - Model.populate(res, opts, (err: any, res: IActor) => {}); + .exec(cb); +MongoModel.count({ type: 'jungle' }, function (err, count) { + count.toFixed(); }); -Model.find({ type: 'iphone' }, (err: any, res: IActor[]) => { - var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]; - var promise = Model.populate(res, opts); +MongoModel.create({ + type: 'jelly bean' +}, { + type: 'snickers' +}, cb).then(function (a, b, c) { + a.save(); + b.save(); + c.save(); +}) +MongoModel.create([{ type: 'jelly bean' }, { + type: 'snickers' +}], function (err, candies) { + var jellybean = candies[0]; + var snickers = candies[1]; +}).then(function (arg) { + arg[0].save(); + arg[1].save(); +}); +MongoModel.discriminator('M', new mongoose.Schema({name: String})); +MongoModel.distinct('url', { clicks: {$gt: 100}}, function (err, result) { +}); +MongoModel.distinct('url').exec(cb); +MongoModel.ensureIndexes({}, cb); +MongoModel.find({ name: 'john', age: { $gte: 18 }}); +MongoModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) { + docs[0].remove(); + docs[1].execPopulate(); +}); +MongoModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) +MongoModel.find({ name: /john/i }, null, { skip: 10 }) +MongoModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); +MongoModel.find({ name: /john/i }, null, { skip: 10 }).exec(function (err, docs) {}); +MongoModel.find({ name: /john/i }, null, { skip: 10 }).exec() + .addBack(function (err, docs) {}); +MongoModel.findById(999, function (err, adventure) {}); +MongoModel.findById(999).exec(cb); +MongoModel.findById(999, 'name length', function (err, adventure) { + adventure.save(); +}); +MongoModel.findById(999, 'name length').exec(cb); +MongoModel.findById(999, '-length').exec(function (err, adventure) { + adventure.addListener('click', cb); +}); +MongoModel.findById(999, 'name', { lean: true }, function (err, doc) {}); +MongoModel.findById(999, 'name').lean().exec(function (err, doc) {}); +MongoModel.findByIdAndRemove(999, {}, cb); +MongoModel.findByIdAndRemove(999, {}); +MongoModel.findByIdAndRemove(999, cb); +MongoModel.findByIdAndRemove(999); +MongoModel.findByIdAndRemove(); +MongoModel.findByIdAndUpdate(999, {}, {}, cb); +MongoModel.findByIdAndUpdate(999, {}, {}); +MongoModel.findByIdAndUpdate(999, {}, cb); +MongoModel.findByIdAndUpdate(999, {}); +MongoModel.findByIdAndUpdate(); +MongoModel.findOne({ type: 'iphone' }, function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); +MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }, cb); +MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(cb); +MongoModel.findOne({ type: 'iphone' }).select('name').lean().exec(cb); +MongoModel.findOneAndRemove({}, {}, cb); +MongoModel.findOneAndRemove({}, {}); +MongoModel.findOneAndRemove({}, cb); +MongoModel.findOneAndRemove({}); +MongoModel.findOneAndRemove(); +MongoModel.findOneAndUpdate({}, {}, {}, cb); +MongoModel.findOneAndUpdate({}, {}, {}); +MongoModel.findOneAndUpdate({}, {}, cb); +MongoModel.findOneAndUpdate({}, {}); +MongoModel.findOneAndUpdate(); +MongoModel.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) { + results[0].on('data', cb); +}); +MongoModel.geoNear({ type : "Point", coordinates : [9,9] }, { + maxDistance : 5, spherical : true +}, function(err, results, stats) { + console.log(results); +}); +MongoModel.geoSearch({ type : "house" }, { + near: [10, 10], maxDistance: 5 +}, function(err, res) { + res[0].remove(); +}); +MongoModel.hydrate({ + _id: '54108337212ffb6d459f854c', + type: 'jelly bean' +}).execPopulate(); +MongoModel.insertMany([ + { name: 'Star Wars' }, + { name: 'The Empire Strikes Back' } +], function(error, docs) {}); +MongoModel.insertMany({name: 'Star Wars'}, function(error, doc) {}); +MongoModel.mapReduce({ + map: cb, + reduce: cb +}, function (err, results) { + console.log(results) +}).then(function (model, stats) { + return model.find().where('value').gt(10).exec(); +}).then(function (docs) { + console.log(docs); +}).then(null, cb).end(); +MongoModel.findById(999, function (err, user) { + var opts = [ + { path: 'company', match: { x: 1 }, select: 'name' } + , { path: 'notes', options: { limit: 10 }, model: 'override' } + ] + MongoModel.populate(user, opts, cb); + MongoModel.populate(user, opts, function (err, user) { + console.log(user); + }); +}); +MongoModel.find(999, function (err, users) { + var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }] + var promise = MongoModel.populate(users, opts); promise.then(console.log).end(); }); -Model.populate({ name: 'Test A' }, { path: 'weapon', model: 'Weapon' }, (err: any, user: IActor) => {}); -Model.populate([ - { name: 'User hoge' }, - { name: 'User fuga' }, -], { path: 'weapon' }, (err: any, users: IActor[]) => {}); - -Model.remove({ title: 'baby born from alien father' }, (err: any) => {}); -var query2 = Model.remove({ _id: 'id' }); -query2.exec(); -Model.update({ age: { $gt: 18 } }, { oldEnough: true }, (err: any, numberAffected: number, raw: any) => {}); -Model.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, (err: any, numberAffected: number, raw: any) => {}); -Model.update({ _id: 'id' }, { $set: { text: 'changed' }}).exec(); - -Model.where('age').gte(21).lte(65).exec((err: any, res: IActor[]) => {}); -var query3 =Model - .where('age').gt(21).lt(65) - .where('name', /^b/i).all('type', 1); -query3.all(25); -query3.and([{ color: 'green' }, { status: 'ok' }]); -query3.batchSize(100); -query3.where('loc').within().box([40.73083, -73.99756], [40.741404, -73.988135]); -query3.where('loc').within().circle({ center: [50, 50], radius: 10, unique: true }); -query3.circle('loc', { center: [50, 50], radius: 10, unique: true }); -query3.comment('login query'); -query3.where({ 'color': 'black' }).count(); -query3.count({ color: 'black' }).count((err: any, count: number) => {}); -query3.count({ color: 'black' }, (err: any, count: number) => {}); -query3.where({ color: 'black' }).count((err: any, count: number) => {}); -query3.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}}); -query3.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}}); -query.elemMatch('comment', (elem: mongoose.Query) => { - elem.where('author').equals('autobot'); - elem.where('votes').gte(5); +MongoModel.populate({ + name: 'Indiana Jones', + weapon: 389 +}, { + path: 'weapon', + model: 'Weapon' +}, cb); +var users = [{ name: 'Indiana Jones', weapon: 389 }] +users.push({ name: 'Batman', weapon: 8921 }) +MongoModel.populate(users, { path: 'weapon' }, function (err, users) { + users.forEach(cb); }); -query3.where('age').equals(49); -query3.where('age', 49); -query3.exec(); -query3.exec('update'); -query3.where('name').exists(); -query3.where('name').exists(true); -query3.find().exists('name'); -query3.where('name').exists(false); -query3.find().exists('name', false); -query3.find({ name: 'Los Pollos Hermanos' }).find((err: any, res: IActor[]) => {}); -query3.where('loc').within().geometry({ type: 'Polygon', coordinates: [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]] }); -query3.find().where('age').gt(21); -query3.find().gt('age', 21); -query3.hint({ indexA: 1, indexB: -1}); -query3.where('path').intersects().geometry({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); -query3.where('path').intersects({ type: 'LineString', coordinates: [[180.0, 11.0], [180, 9.0]] }); -query3.maxScan(100); -query3.where('loc').near({ center: [10, 10] }); -query3.where('loc').near({ center: [10, 10], maxDistance: 5 }); -query3.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); -query3.near('loc', { center: [10, 10], maxDistance: 5 }); -query3.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); -query3.nor([{ color: 'green' }, { status: 'ok' }]); -query3.or([{ color: 'red' }, { status: 'emergency' }]); -query3.where('loc').within().polygon([10,20], [13, 25], [7,15]); -query3.polygon('loc', [10,20], [13, 25], [7,15]); - -query3.findOne().populate('owner').exec((err: any, res: IActor[]) => {}); -query3.find().populate({ - path: 'owner', - select: 'name', - match: { color: 'black' }, - options: { sort: { name: -1 }} -}).exec((err: any, res: IActor[]) => {}); -query3.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec((err: any, res: IActor[]) => {}); - -query3.read('primary'); -query3.read('p'); -query3.read('primaryPreferred'); -query3.read('pp'); -query3.read('secondary'); -query3.read('s'); -query3.read('secondaryPreferred'); -query3.read('sp'); -query3.read('nearest'); -query3.read('n'); -query3.read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }]); -query3.remove({ artist: 'Anne Murray' }, (err: any, res: IActor[]) => {}); -query3.select('a b -c'); -query3.select({a: 1, b: 1, c: 0}); -query3.select('+path'); -query3.where('tags').size(0); -query3.skip(100).limit(20); -query3.slaveOk(); -query3.slaveOk(true); -query3.slaveOk(false); -query3.slice('comments', -5); -query3.slice('comments', [10, 5]) -query3.where('comments').slice(5); -query3.where('comments').slice([-10, 5]); -query3.snapshot(); -query3.snapshot(true); -query3.snapshot(false); -query3.sort({ field: 'asc', test: -1 }); -query3.sort('field -test'); -Model.find({ name: /^hello/ }).stream({ transform: JSON.stringify }).pipe(fs.createWriteStream('./test.json')); -var stream = Model.find({ name: /^hello/ }).stream(); -stream - .on('data', (doc: IActor) => {}) - .on('error', (err: any) => {}) - .on('close', () => {}); - -query3.tailable(); -query3.tailable(false); -var AdvQuery = query3.toConstructor(); -query3.update({ title: 'words' }); -query3.update({ $set: { title: 'words' }}); -query3.update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, (err: any, row: number, raw: any) => {}); - -query3.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); -query3.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); -query3.where('loc').within({ polygon: [[],[],[],[]] }); -query3.where('loc').within([], [], []); // polygon -query3.where('loc').within([], []); // box -query3.where('loc').within({ type: 'LineString', coordinates: [] }); // geometry - -mongoose.Query.use$geoWithin = false; - - -var ToySchema = new Schema({}); -ToySchema.add({ name: 'string', color: 'string', price: 'number' }); -schema.eachPath(function(path: string, value: any) {}); -schema.index({ first: 1, last: -1 }); -schema.indexes(); -schema.method('meow', function() { - console.log('meeeeeoooooooooooow'); -}); -var Kitty = mongoose.model('Kitty', schema); -var fizz: any = new Kitty({ name: 'kitty' }); -fizz.meow(); -schema.method({ - purr: function() {}, - scratch: function() {}, -}); -schema.path('name'); -schema.path('name', Number); -schema.pathType('name'); -schema.plugin(function() {}); -schema.post('save', function(doc: IActor) {}); -schema.pre('save', function(next: () => void) {}); -schema.requiredPaths(); -schema.static('findByName', function(name: string, callback: () => void) {}); -schema.virtual('display_name') - .get(function(): string { return this.name; }) - .set((value: string): void => {}); - -var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId('foo'); -var id: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(); -var id2: mongoose.Types.ObjectId = new mongoose.Types.ObjectId(123); -var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromTime(123); -var id2: mongoose.Types.ObjectId = mongoose.Types.ObjectId.createFromHexString('foo'); -var isValid:boolean = mongoose.Types.ObjectId.isValid('570d350b67b1ae0600e8bee8'); -var s = id.toHexString(); -var valid = id.isValid(); -var eq = id.equals(id2); - -var kitty1 = new Kitty({}); -var kitty2 = new Kitty({}); -var kittyEq = kitty1._id.equals(kitty2._id); +MongoModel.remove({ title: 'baby born from alien father' }, cb); +MongoModel.remove({_id: '999'}).exec().then(cb).catch(cb); +MongoModel.update({ age: { $gt: 18 } }, { oldEnough: true }, cb); +MongoModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, cb); +MongoModel.where('age').gte(21).lte(65).exec(cb); +MongoModel.where('age').gte(21).lte(65).where('name', /^b/i); +new (mongoModel.base.model(''))(); +mongoModel.baseModelName.toLowerCase(); +mongoModel.collection.$format(99); +mongoModel.db.openSet(''); +mongoModel.discriminators; +mongoModel.modelName.toLowerCase(); +MongoModel = mongoModel.base.model('new', mongoModel.schema); +/* inherited properties */ +mongoModel._id; +mongoModel.execPopulate(); +mongoModel.on('data', cb); +mongoModel.addListener('event', cb); +MongoModel.findOne({ title: /timex/i }) + .populate('_creator', 'name') + .exec(function (err, story) { + story.execPopulate(); + }); +MongoModel.find({ + id: 999 +}) +.populate({ + path: 'fans', + match: { age: { $gte: 21 }}, + select: 'name -_id', + options: { limit: 5 } +}) +.exec(); \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 7a4d33c522..01a149f001 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -1,653 +1,2698 @@ -// Type definitions for Mongoose 3.8.5 +// Type definitions for Mongoose 4.5.4 // Project: http://mongoosejs.com/ -// Definitions by: horiuchi +// Definitions by: simonxca , horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +/// /// +/* + * Guidelines for maintaining these definitions: + * - If you spot an error here or there, please submit a PR. + * Give some examples/links to documentation if you can. + * + * For patches and minor releases: + * - Browse the changelog at https://github.com/Automattic/mongoose/blob/master/History.md + * and make necessary changes. Afterwards, update the version number at the top so we know + * which version we are on. + * + * For major releases: + * - Refer to the updated docs at http://mongoosejs.com/docs/api.html + * - On the left-hand side of the docs is a list of .js files. Reset and update the TODO list below + * then go through one-by-one, making any updates to params list, return type, etc. For documentation + * changes just copy/paste them into here. + * - Check the files off as you go. Some files below might not have anything in them. That's ok, this + * 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 + */ + +/* +For easier searching, add a header to each section like so: +To find a section, CTRL+F and type "section ___.js" +/* + * section filename.js + * http://mongoosejs.com/docs/api.html#filename-js + */ + declare module "mongoose" { - function connect(uri: string, options?: ConnectionOptions , callback?: (err: any) => void): Mongoose; - function createConnection(): Connection; - function createConnection(uri: string, options?: ConnectionOptions): Connection; - function createConnection(host: string, database_name: string, port?: number, options?: ConnectionOptions): Connection; - function disconnect(callback?: (err?: any) => void): Mongoose; + import events = require('events'); + import mongodb = require('mongodb'); + import mPromise = require('mpromise'); + import stream = require('stream'); - function model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; - function modelNames(): string[]; - function plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; + /* + * Some mongoose classes have the same name as the native JS classes + * Keep references to native classes using a "Native" prefix + */ + interface NativeBuffer extends Buffer {} + interface NativeDate extends Date {} + interface NativeError extends Error {} - function get(key: string): any; - function set(key: string, value: any): void; + /* + * Public API + */ + export = mongoose; - var mongo: any; - var mquery: any; - var version: string; - var connection: Connection; + /* + * section index.js + * http://mongoosejs.com/docs/api.html#index-js + * + * require('mongoose') is not actually a class with static + * methods. It is an instance of the Mongoose class. + * + * Reasons we use a class with static properties below: + * 1. MongooseThenable extends mongoose, so we need a + * scope to wrap everything. We can't use a namespace + * since namespaces can't be inherited from. + * 2. We can't use an interface to wrap everything, since + * some properties of mongoose are class constructors. + * Exporting an interface won't, for example, let us + * call new mongoose.Schema({}) + * 3. We can't use a normal class since require('mongoose') + * is an instance object. All of its properties are + * immediately accessible: require('mongoose').model('') + * If we export a normal class and import * as mongoose + * we'll have to call new mongoose() before we can use + * any of its methods, which would be inaccurate. + * + * NOTE: the static properties below cannot be used for + * type-checking. If you want to use the names for + * type-checking you must add a corresponding interface + * inside namespace mongoose {} defined below. + */ + /** + * Contains all the public properties and methods that can + * be accessed by mongoose = require('mongoose') + */ + class mongoose { + /* Class constructors */ + static Aggregate: typeof _mongoose.Aggregate; + static CastError: typeof _mongoose.CastError; + static Collection: typeof _mongoose.Collection; + static Connection: typeof _mongoose.Connection; + static Document: typeof _mongoose.Document; + static DocumentProvider: any; + static Error: typeof _mongoose.Error; + static Model: _mongoose.ModelConstructor; + static Mongoose: { + // recursive constructor + new(...args: any[]): typeof mongoose; + } + /** + * To use your own promise library: + * mongoose.Promise = bluebird; + * mongoose.Promise = q; + * + * Note: you will lose type-checking and code completion + * provided by mongoose's built-in promises. + * + * To use, either: + * - Access its methods using [] + * query.exec()['reduce']().then() // the rest works normally + * - Cast to + * (Model).find().exec().reduce().then() + */ + static Promise: typeof _mongoose.Promise | any; + static PromiseProvider: any; + static Query: typeof _mongoose.Query; + static Schema: typeof _mongoose.Schema; + static SchemaType: typeof _mongoose.SchemaType; + static SchemaTypes: typeof _mongoose.Schema.Types; + static 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; + } + static VirtualType: typeof _mongoose.VirtualType; - export class Mongoose { - connect(uri: string, options?: ConnectOpenOptionsBase, callback?: (err: any) => void): Mongoose; - createConnection(): Connection; - createConnection(uri: string, options?: Object): Connection; - createConnection(host: string, database_name: string, port?: number, options?: ConnectOpenOptionsBase): Connection; - disconnect(callback?: (err?: any) => void): Mongoose; - get(key: string): any; - model(name: string, schema?: Schema, collection?: string, skipInit?: boolean): Model; - modelNames(): string[]; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Mongoose; - set(key: string, value: any): void; + /* Properties */ + /** Expose connection states for user-land */ + static STATES: Object + /** The default connection of the mongoose module. */ + static connection: _mongoose.Connection; + /** The node-mongodb-native driver Mongoose uses. */ + static mongo: typeof mongodb; + /** + * The mquery query builder Mongoose uses. + * Currently there is no mquery type definition. + */ + static mquery: any; + /** The Mongoose version */ + static version: string; - mongo: any; - mquery: any; - version: string; - connection: Connection; - Promise: any; + /* Methods */ + /** + * Opens the default mongoose connection. + * Options passed take precedence over options included in connection strings. + * @returns pseudo-promise wrapper around this + */ + static connect(uris: string, + options?: _mongoose.MongooseConnectOptions, + callback?: (err: mongodb.MongoError) => void): typeof _mongoose.MongooseThenable; + static connect(uris: string, + callback?: (err: mongodb.MongoError) => void): typeof _mongoose.MongooseThenable; + + /** + * Creates a Connection instance. + * Each connection instance maps to a single database. This method is helpful + * when mangaging multiple db connections. + * @param uri a mongodb:// URI + * @param options options to pass to the driver + * @returns the created Connection object + */ + static createConnection(): _mongoose.Connection; + static createConnection(uri: string, + options?: _mongoose.MongooseConnectOptions + ): _mongoose.Connection; + static createConnection(host: string, database_name: string, port?: number, + options?: _mongoose.MongooseConnectOptions + ): _mongoose.Connection; + + /** + * Disconnects all connections. + * @param fn called after all connection close. + * @returns pseudo-promise wrapper around this + */ + static disconnect(fn?: (error: any) => void): typeof _mongoose.MongooseThenable; + + /** Gets mongoose options */ + static get(key: string): any; + + /** + * Defines a model or retrieves it. + * Models defined on the mongoose instance are available to all connection + * created by the same mongoose instance. + * @param name model name + * @param collection (optional, induced from model name) + * @param skipInit whether to skip initialization (defaults to false) + */ + static model(name: string, schema?: _mongoose.Schema, collection?: string, + skipInit?: boolean): _mongoose.ModelConstructor; + + /** + * Returns an array of model names created on this instance of Mongoose. + * Does not include names of models created using connection.model(). + */ + static modelNames(): string[]; + + /** + * Declares a global plugin executed on all Schemas. + * Equivalent to calling .plugin(fn) on each Schema you create. + * @param fn plugin callback + * @param opts optional options + */ + static plugin(fn: Function, opts?: Object): typeof mongoose; + + /** Sets mongoose options */ + static set(key: string, value: any): void; } - export interface Connection extends NodeJS.EventEmitter { - constructor(base: Mongoose): Connection; - - close(callback?: (err: any) => void): Connection; - collection(name: string, options?: Object): Collection; - model(name: string, schema?: Schema, collection?: string): Model; - modelNames(): string[]; - open(host: string, database?: string, port?: number, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; - openSet(uris: string, database?: string, options?: OpenSetConnectionOptions, callback?: (err: any) => void): Connection; - - db: any; - collections: {[index: string]: Collection}; - readyState: number; + /** Interfaces for all classes in mongoose used for type-checking. */ + namespace mongoose { + interface Aggregate extends _mongoose.Aggregate {} + interface CastError extends _mongoose.CastError {} + interface Collection extends _mongoose.Collection {} + interface Connection extends _mongoose.Connection {} + interface Document extends _mongoose.Document {} + interface Error extends _mongoose.Error {} + interface ValidationError extends _mongoose.ValidationError {} + type model = _mongoose.Model; + type Model = _mongoose.ModelConstructor; // compatibilty with rest-io.d.ts + type Mongoose = typeof mongoose; + interface Promise extends _mongoose.Promise {} + interface Query extends _mongoose.Query {} + interface QueryCursor extends _mongoose.QueryCursor {} + interface QueryStream extends _mongoose.QueryStream {} + interface Schema extends _mongoose.Schema {} + namespace Schema { + namespace Types { + interface Array extends _mongoose.Schema._Types.Array {} + interface String extends _mongoose.Schema._Types.String {} + interface DocumentArray extends _mongoose.Schema._Types.DocumentArray {} + interface Number extends _mongoose.Schema._Types.Number {} + interface Date extends _mongoose.Schema._Types.Date {} + interface Buffer extends _mongoose.Schema._Types.Buffer {} + interface Boolean extends _mongoose.Schema._Types.Boolean {} + interface Bool extends _mongoose.Schema._Types.Boolean {} + interface ObjectId extends _mongoose.Schema._Types.ObjectId {} + interface Oid extends _mongoose.Schema._Types.ObjectId {} + interface Mixed extends _mongoose.Schema._Types.Mixed {} + interface Object extends _mongoose.Schema._Types.Mixed {} + interface Embedded extends _mongoose.Schema._Types.Embedded {} + } + } + interface SchemaType extends _mongoose.SchemaType {} + namespace Types { + interface Subdocument extends _mongoose.Types.Subdocument {} + interface Array extends _mongoose.Types.Array {} + interface DocumentArray extends _mongoose.Types.DocumentArray {} + interface Buffer extends _mongoose.Types.Buffer {} + interface ObjectId extends _mongoose.Types.ObjectId {} + interface Embedded extends _mongoose.Types.Embedded {} + } + interface VirtualType extends _mongoose.VirtualType {} + interface ConnectionOptions extends _mongoose.MongooseConnectOptions {} } - export interface ConnectOpenOptionsBase { - db?: any; - server?: any; - replset?: any; - /** Username for authentication if not supplied in the URI. */ - user?: string; - /** Password for authentication if not supplied in the URI. */ - pass?: string; - /** Options for authentication */ - auth?: any; - } - - export interface ConnectionOptions extends ConnectOpenOptionsBase { - /** Passed to the underlying driver's Mongos instance. */ - mongos?: MongosOptions; - } - - interface OpenSetConnectionOptions extends ConnectOpenOptionsBase { - /** If true, enables High Availability support for mongos */ - mongos?: boolean; - } - - interface MongosOptions { - /** Turn on high availability monitoring. (default: true) */ - ha?: boolean; - /** Time between each replicaset status check. (default: 5000) */ - haInterval?: number; + /* + * Public API Details. + */ + namespace _mongoose { + /* + * section index.js + * http://mongoosejs.com/docs/api.html#index-js + */ + class MongooseThenable extends mongoose { /** - * Number of connections in the connection pool for each - * server instance. (default: 5 (for legacy reasons)) */ - poolSize?: number; - /** - * Use ssl connection (needs to have a mongod server with - * ssl support). (default: false). + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. */ - ssl?: boolean; + static then(onFulfill?: () => void, onRejected?: (err: mongodb.MongoError) => void): typeof MongooseThenable; + /** - * Validate mongod server certificate against ca - * (needs to have a mongod server with ssl support, 2.4 or higher) - * (default: true) + * Ability to use mongoose object as a pseudo-promise so .connect().then() + * and .disconnect().then() are viable. */ - sslValidate?: boolean; - /** Turn on high availability monitoring. */ - sslCA?: (Buffer|string)[]; - sslKey?: Buffer|string; - sslPass?: Buffer|string; - socketOptions?: { - noDelay?: boolean; - keepAlive?: number; - connectionTimeoutMS?: number; - socketTimeoutMS?: number; + static catch(onRejected?: (err: mongodb.MongoError) => void): typeof MongooseThenable; + } + + 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): Promise; + + /** + * 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; + + /** 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; }; - } + } - export interface Collection { - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeOrderedBulkOp - initializeOrderedBulkOp(options?: CollectionOptions): OrderedBulkOperation; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#initializeUnorderedBulkOp - initializeUnorderedBulkOp(options?: CollectionOptions): UnorderedBulkOperation; - } + /** 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; + } - export interface CollectionOptions { - //The write concern. - w?: number | string; - //The write concern timeout. - wtimeout?: number; - //Specify a journal write concern. - j?: boolean; - } + /* + * section drivers/node-mongodb-native/collection.js + * http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-collection-js + */ + class Collection extends CollectionBase { + /** 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; + } - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html - export interface OrderedBulkOperation { - length: number; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#execute - execute(callback: MongoCallback): void; - execute(options?: FSyncOptions): Promise; - execute(options: FSyncOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#find - find(selector: Object): FindOperatorsOrdered; - //http://mongodb.github.io/node-mongodb-native/2.1/api/OrderedBulkOperation.html#insert - insert(doc: Object): OrderedBulkOperation; - } + /* + * 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; - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html - export interface UnorderedBulkOperation { - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#execute - execute(callback: MongoCallback): void; - execute(options?: FSyncOptions): Promise; - execute(options: FSyncOptions, callback: MongoCallback): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#find - find(selector: Object): FindOperatorsUnordered; - //http://mongodb.github.io/node-mongodb-native/2.1/api/UnorderedBulkOperation.html#insert - insert(doc: Object): UnorderedBulkOperation; - } + /** Expose the possible connection states. */ + static STATES: Object; + } - export interface MongoCallback { - (error: MongoError, result: T): void; - } + /* + * section error/validation.js + * http://mongoosejs.com/docs/api.html#error-validation-js + */ + class ValidationError extends Error { + /** Console.log helper */ + toString(): string; + } - // http://mongodb.github.io/node-mongodb-native/2.1/api/MongoError.html - export class MongoError extends Error { - constructor(message: string); - static create(options: Object): MongoError; - } + /* + * 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); - //http://mongodb.github.io/node-mongodb-native/2.1/api/BulkWriteResult.html - export interface BulkWriteResult { - ok: number; - nInserted: number; - nUpdated: number; - nUpserted: number; - nModified: number; - nRemoved: number; + /** + * 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; - getInsertedIds(): Array; - getLastOp(): Object; - getRawResponse(): Object; - getUpsertedIdAt(index: number): Object; - getUpsertedIds(): Array; - getWriteConcernError(): WriteConcernError; - getWriteErrorAt(index: number): WriteError; - getWriteErrorCount(): number; - getWriteErrors(): Array; - hasWriteErrors(): boolean; - } + /** For backwards compatibility. Same as mongoose.Error.messages */ + static Messages: Object; + } - //http://mongodb.github.io/node-mongodb-native/2.1/api/WriteError.html - export interface WriteError { - //Write concern error code. - code: number; - //Write concern error original bulk operation index. - index: number; - //Write concern error message. - errmsg: string; - } + /* + * 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; - //http://mongodb.github.io/node-mongodb-native/2.1/api/WriteConcernError.html - export interface WriteConcernError { - //Write concern error code. - code: number; - //Write concern error message. - errmsg: string; - } + /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ + close(callback?: (error: mongodb.MongoError, result: any) => void): Promise; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Admin.html#removeUser - export interface FSyncOptions { - w?: number | string; - wtimeout?: number; - j?: boolean; - fsync?: boolean - } + /** + * 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): Promise; - //http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsOrdered.html - export interface FindOperatorsOrdered { - delete(): OrderedBulkOperation; - deleteOne(): OrderedBulkOperation; - replaceOne(doc: Object): OrderedBulkOperation; - update(doc: Object): OrderedBulkOperation; - updateOne(doc: Object): OrderedBulkOperation; - upsert(): FindOperatorsOrdered; - } + /** + * Get the next document from this cursor. Will return null when there are + * no documents left. + */ + next(callback?: (err: any) => void): Promise; + } - //http://mongodb.github.io/node-mongodb-native/2.1/api/FindOperatorsUnordered.html - export interface FindOperatorsUnordered { - length: number; - remove(): UnorderedBulkOperation; - removeOne(): UnorderedBulkOperation; - replaceOne(doc: Object): UnorderedBulkOperation; - update(doc: Object): UnorderedBulkOperation; - updateOne(doc: Object): UnorderedBulkOperation; - upsert(): FindOperatorsUnordered; - } + /* + * 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; + } - export class SchemaType { } - export class VirtualType { - get(fn: Function): VirtualType; - set(fn: Function): VirtualType; - } - export module Types { - export class ObjectId { - constructor(id?: string|number); - toHexString(): string; - equals(other: ObjectId): boolean; - getTimestamp(): Date; - isValid(): boolean; - static createFromTime(time: number): ObjectId; - static createFromHexString(hexString: string): ObjectId; - static isValid(id?: string|number):boolean; + /* + * 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; + /** + * 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 Document { + /** 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: Document): boolean; + + /** + * Explicitly executes population and returns a promise. + * Useful for ES2015 integration. + * @returns promise that resolves to the document when population is done + */ + execPopulate(): Promise; + + /** + * 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; + + /** 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): Promise; + validate(optional: Object, callback?: (err: any) => void): Promise; + + /** + * 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; + } + + 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[]): Array; + + /** + * 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[]): Array; + + /** + * 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): Array; + + /** + * 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. + */ + sort(compare?: Function): 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 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 + */ + class Query 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 | 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): Promise; + + /** + * 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): Promise; + exec(operation: string | Function, callback?: (err: any, res: T) => void): Promise; + + /** 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): Query; + find(criteria: Object, callback?: (err: any, res: Model[]) => void): Query; + + /** + * 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): Query; + findOne(criteria: Object, callback?: (err: any, res: Model) => void): Query; + + /** + * 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): Query; + findOneAndRemove(conditions: Object, callback?: (error: any, doc: Model, result: any) => void): Query; + findOneAndRemove(conditions: Object, options: QueryFindOneAndRemoveOptions, + callback?: (error: any, doc: Model, result: any) => void): Query; + + /** + * 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): Query; + findOneAndUpdate(update: Object, callback?: (err: any, doc: Model) => void): Query; + findOneAndUpdate(query: Object | Query, update: Object, + callback?: (err: any, doc: Model) => void): Query; + findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, + callback?: (err: any, doc: Model) => void): Query; + + /** + * 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, reject?: (err: any) => void): Promise; + + /** + * Converts this query to a customized, reusable query + * constructor with all arguments and options retained. + */ + toConstructor(): typeof Query; + + /** + * 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): Promise | any; + + /** Execute the aggregation with explain */ + explain(callback?: (err: any, result: T) => void): Promise; + + /** + * 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 | 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, reject?: (err: any) => void): Promise + + /** + * 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 + * + * Callback signatures are from the mPromise type definitions + */ + class Promise 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: R, arg: F) => void); + constructor(fn?: (err: R, ...args: F[]) => 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: R, arg: F) => void): this; + addBack(listener: (err: R, ...args: F[]) => void): this; + + /** + * Adds a listener to the complete (success) event. + * @deprecated Adds a listener to the complete (success) event. + */ + addCallback(listener: (arg: F) => void): this; + addCallback(listener: (...args: F[]) => void): this; + + /** + * Adds a listener to the err (rejected) event. + * @deprecated Use onReject instead. + */ + addErrback(listener: (err: R) => void): this; + + /** ES6-style .catch() shorthand */ + catch(onReject?: (err: R) => void): Promise; + + /** + * 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 | NativeError): 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?: R, 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: F) => void, onReject?: (err: R) => void): Promise; + then(onFulfill: (...args: F[]) => void, onReject?: (err: R) => void): Promise; + + /** + * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. + * @deprecated Use fulfill instead. + */ + complete(args: F): this; + complete(...args: F[]): this; + + /** Fulfills this promise with passed arguments. */ + fulfill(...args: F[]): this; + fulfill(arg: F): this; + + /** ES6-style promise constructor wrapper around mpromise. */ + static ES6(resolver: ( + complete: (...args: F[]) => void, + error: (e: R) => void + ) => void): Promise; + } + + /* + * 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. + */ + type ModelConstructor = IModel & typeof _Model & events.EventEmitter; + type Model = _Model & events.EventEmitter; + + // we must use an interface with a custom new function to create + // the Model type above + interface IModel { + /** + * 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; + } + + class _Model extends Document { + /** Signal that we desire an increment of this documents version. */ + increment(): this; + + /** + * Returns another Model instance. + * @param name model name + */ + model(name: string): ModelConstructor; + static model(name: string): ModelConstructor; + + /** + * Removes this document from the db. + * @param fn optional callback + */ + remove(fn?: (err: any, product: Model) => void): Promise; + + /** + * 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): Promise; + + /** + * Creates a Query and specifies a $where condition. + * @param argument is a javascript string or anonymous function + */ + static $where(argument: string | Function): Query; + + /** + * 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 + */ + static aggregate(...aggregations: Object[]): Aggregate; + static aggregate(...aggregationsWithCallback: Object[]): Promise; + + /** Counts number of matching documents in a database collection. */ + static 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. + */ + static create(docs: any[], callback?: (err: any, res: Model[]) => void): Promise; + static create(...docs: Object[]): Promise; + static create(...docsWithCallback: Object[]): Promise; + + /** + * Adds a discriminator type. + * @param name discriminator model name + * @param schema discriminator model schema + */ + static discriminator(name: string, schema: Schema): Model; + + /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ + static distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + static 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 + */ + static ensureIndexes(callback?: (err: any) => void): Promise; + static ensureIndexes(options: Object, callback?: (err: any) => void): Promise; + + /** + * Finds documents. + * @param projection optional fields to return + */ + static find(callback?: (err: any, res: Model[]) => void): Query; + static find(conditions: Object, callback?: (err: any, res: Model[]) => void): Query; + static find(conditions: Object, projection: Object, + callback?: (err: any, res: Model[]) => void): Query; + static find(conditions: Object, projection: Object, options: Object, + callback?: (err: any, res: Model[]) => void): Query; + + /** + * 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 + */ + static findById(id: Object | string | number, + callback?: (err: any, res: Model) => void): Query; + static findById(id: Object | string | number, projection: Object, + callback?: (err: any, res: Model) => void): Query; + static findById(id: Object | string | number, projection: Object, options: Object, + callback?: (err: any, res: Model) => void): Query; + + /** + * 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 + */ + static findByIdAndRemove(): Query; + static findByIdAndRemove(id: Object | number | string, callback?: (err: any, res: Model) => void): Query; + static 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): Query; + + /** + * 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 + */ + static findByIdAndUpdate(): Query; + static findByIdAndUpdate(id: Object | number | string, update: Object, + callback?: (err: any, res: Model) => void): Query; + static findByIdAndUpdate(id: Object | number | string, update: Object, + options: ModelFindByIdAndUpdateOptions, + callback?: (err: any, res: Model) => void): Query; + + /** + * Finds one document. + * The conditions are cast to their respective SchemaTypes before the command is sent. + * @param projection optional fields to return + */ + static findOne(conditions?: Object, + callback?: (err: any, res: Model) => void): Query; + static findOne(conditions: Object, projection: Object, + callback?: (err: any, res: Model) => void): Query; + static findOne(conditions: Object, projection: Object, options: Object, + callback?: (err: any, res: Model) => void): Query; + + /** + * 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. + */ + static findOneAndRemove(): Query; + static findOneAndRemove(conditions: Object, + callback?: (err: any, res: Model) => void): Query; + static 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; + /** sets the document fields to return */ + select?: Object; + }, callback?: (err: any, res: Model) => void): Query; + + /** + * 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. + */ + static findOneAndUpdate(): Query; + static findOneAndUpdate(conditions: Object, update: Object, + callback?: (err: any, res: Model) => void): Query; + static findOneAndUpdate(conditions: Object, update: Object, + options: ModelFindOneAndUpdateOptions, + callback?: (err: any, res: Model) => void): Query; + + /** + * 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 + */ + static 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): Query; + + /** + * 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 + */ + static 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): Query; + + /** + * 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. + */ + static hydrate(obj: Object): Model; + + /** + * 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. + */ + static insertMany(docs: any[], callback?: (error: any, docs: Model[]) => void): Promise; + static insertMany(doc: any, callback?: (error: any, doc: Model) => void): Promise; + static insertMany(...docsWithCallback: Object[]): Promise; + + /** + * Executes a mapReduce command. + * @param o an object specifying map-reduce options + * @param callbackoptional callback + */ + static mapReduce( + o: ModelMapReduceOption, + callback?: (err: any, res: any) => void + ): Promise; + + /** + * 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). + */ + static populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: Model[]) => void): Promise; + static populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: Model) => void): Promise; + + /** Removes documents from the collection. */ + static 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. + */ + static update(conditions: Object, doc: Object, + callback?: (err: any, raw: any) => void): Query; + static 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. */ + static where(path: string, val?: Object): Query; + + /** 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 + */ + abstract class CollectionBase { + /** + * Abstract Collection constructor + * This is the base class that drivers inherit from and implement. + * @param name name of the collection + * @param conn A MongooseConnection instance + * @param opts optional collection options + */ + constructor(name: string, conn: Connection, opts: Object); + + /* abstract methods */ + insureIndex(...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; } } - - export class Schema { - static Types: { - String: String; - ObjectId: Types.ObjectId; - OId: Types.ObjectId; - Mixed: any; - }; - - methods: any; - statics: any; - - constructor(schema?: Object, options?: Object); - - add(obj: Object, prefix?: string): void; - eachPath(fn: (path: string, type: any) => void): Schema; - get(key: string): any; - index(fields: Object, options?: Object): Schema; - indexes(): void; - method(name: string, fn: Function): Schema; - method(method: Object): Schema; - path(path: string): any; - path(path: string, constructor: any): Schema; - pathType(path: string): string; - plugin(plugin: (schema: Schema, options?: Object) => void, options?: Object): Schema; - - pre(method: string, fn: HookSyncCallback, errorCb?: HookErrorCallback): Schema; - pre(method: string, isAsync: boolean, fn: HookAsyncCallback, errorCb?: HookErrorCallback): Schema; - post(method: string, fn: (doc: Document, next?: HookNextFunction) => any ): Schema; - - requiredPaths(): string[]; - set(key: string, value: any): void; - static(name: string, fn: Function): Schema; - virtual(name: string, options?: Object): VirtualType; - virtualpath(name: string): VirtualType; - - } - - // hook functions: https://github.com/vkarpov15/hooks-fixed - export interface HookSyncCallback { - (next: HookNextFunction, ...hookArgs:any[]): any; - } - - export interface HookAsyncCallback { - (next: HookNextFunction, done: HookDoneFunction, ...hookArgs:any[]): any; - } - - export interface HookErrorCallback { - (error: Error): any; - } - - export interface HookNextFunction { - (error: Error): any; - (...hookArgs:any[]): any; - } - - export interface HookDoneFunction { - (error: Error): any; - (...hookArgs:any[]): any; - } - - export interface SchemaOption { - autoIndex?: boolean; - bufferCommands?: boolean; - capped?: boolean; - collection?: string; - id?: boolean; - _id?: boolean; - minimize?: boolean; - read?: string; - safe?: boolean; - shardKey?: boolean; - strict?: boolean; - toJSON?: Object; - toObject?: Object; - versionKey?: boolean; - } - - export interface Model extends NodeJS.EventEmitter { - new(doc?: Object, fields?: Object, skipInit?: boolean): T; - - aggregate(...aggregations: Object[]): Aggregate; - aggregate(aggregation: Object, callback: (err: any, res: T[]) => void): Promise; - aggregate(aggregation1: Object, aggregation2: Object, callback: (err: any, res: T[]) => void): Promise; - aggregate(aggregation1: Object, aggregation2: Object, aggregation3: Object, callback: (err: any, res: T[]) => void): Promise; - count(conditions: Object, callback?: (err: any, count: number) => void): Query; - - create(doc: Object, fn?: (err: any, res: T) => void): Promise; - create(doc1: Object, doc2: Object, fn?: (err: any, res1: T, res2: T) => void): Promise; - create(doc1: Object, doc2: Object, doc3: Object, fn?: (err: any, res1: T, res2: T, res3: T) => void): Promise; - discriminator(name: string, schema: Schema): Model; - distinct(field: string, callback?: (err: any, res: T[]) => void): Query; - distinct(field: string, conditions: Object, callback?: (err: any, res: T[]) => void): Query; - ensureIndexes(callback: (err: any) => void): Promise; - - find(): Query; - find(cond: Object, callback?: (err: any, res: T[]) => void): Query; - find(cond: Object, fields: Object, callback?: (err: any, res: T[]) => void): Query; - find(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T[]) => void): Query; - findById(id: string, callback?: (err: any, res: T) => void): Query; - findById(id: string, fields: Object, callback?: (err: any, res: T) => void): Query; - findById(id: string, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findByIdAndRemove(id: string, callback?: (err: any, res: T) => void): Query; - findByIdAndRemove(id: string, options: Object, callback?: (err: any, res: T) => void): Query; - findByIdAndUpdate(id: string, update: Object, callback?: (err: any, res: T) => void): Query; - findByIdAndUpdate(id: string, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - findOne(cond?: Object, callback?: (err: any, res: T) => void): Query; - findOne(cond: Object, fields: Object, callback?: (err: any, res: T) => void): Query; - findOne(cond: Object, fields: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - - geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; - geoNear(point: number[], options: Object, callback?: (err: any, res: T[], stats: any) => void): Query; - geoSearch(cond: Object, options: GeoSearchOption, callback?: (err: any, res: T[]) => void): Query; - increment(): T; - mapReduce(options: MapReduceOption, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; - mapReduce(options: MapReduceOption2, callback?: (err: any, res: MapReduceResult[]) => void): Promise[]>; - model(name: string): Model; - - populate(doc: U, options: Object, callback?: (err: any, res: U) => void): Promise; - populate(doc: U[], options: Object, callback?: (err: any, res: U[]) => void): Promise; - update(cond: Object, update: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; - update(cond: Object, update: Object, options: Object, callback?: (err: any, affectedRows: number, raw: any) => void): Query; - remove(cond: Object, callback?: (err: any) => void): Query<{}>; - save(callback?: (err: any, result: T, numberAffected: number) => void): Query; - where(path: string, val?: Object): Query; - - $where(argument: string): Query; - $where(argument: Function): Query; - - base: Mongoose; - collection: Collection; - db: any; - discriminators: any; - modelName: string; - schema: Schema; - } - export interface FindAndUpdateOption { - new?: boolean; - upsert?: boolean; - sort?: Object; - select?: Object; - } - export interface GeoSearchOption { - near: number[]; - maxDistance: number; - limit?: number; - lean?: boolean; - } - export interface MapReduceOption { - map: () => void; - reduce: (key: Key, vals: T[]) => Val; - query?: Object; - limit?: number; - keeptemp?: boolean; - finalize?: (key: Key, val: Val) => Val; - scope?: Object; - jsMode?: boolean; - verbose?: boolean; - out?: { - inline?: number; - replace?: string; - reduce?: string; - merge?: string; - }; - } - export interface MapReduceOption2 { - map: string; - reduce: (key: Key, vals: T[]) => Val; - query?: Object; - limit?: number; - keeptemp?: boolean; - finalize?: (key: Key, val: Val) => Val; - scope?: Object; - jsMode?: boolean; - verbose?: boolean; - out?: { - inline?: number; - replace?: string; - reduce?: string; - merge?: string; - }; - } - export interface MapReduceResult { - _id: Key; - value: Val; - } - - export class Query { - exec(callback?: (err: any, res: T) => void): Promise; - exec(operation: string, callback?: (err: any, res: T) => void): Promise; - exec(operation: Function, callback?: (err: any, res: T) => void): Promise; - - all(val: number): Query; - all(path: string, val: number): Query; - and(array: Object[]): Query; - box(val: Object): Query; - box(a: number[], b: number[]): Query; - batchSize(val: number): Query; - cast(model: Model, obj: Object): U; - //center(): Query; - //centerSphere(path: string, val: Object): Query; - circle(area: Object): Query; - circle(path: string, area: Object): Query; - comment(val: any): Query; - count(callback?: (err: any, count: number) => void): Query; - count(criteria: Object, callback?: (err: any, count: number) => void): Query; - distinct(callback?: (err: any, res: T) => void): Query; - distinct(field: string, callback?: (err: any, res: T) => void): Query; - distinct(criteria: Object, field: string, callback?: (err: any, res: T) => void): Query; - distinct(criteria: Query, field: string, callback?: (err: any, res: T) => void): Query; - elemMatch(criteria: Object): Query; - elemMatch(criteria: (elem: Query) => void): Query; - elemMatch(path: string, criteria: Object): Query; - elemMatch(path: string, criteria: (elem: Query) => void): Query; - equals(val: Object): Query; - exists(val?: boolean): Query; - exists(path: string, val?: boolean): Query; - find(callback?: (err: any, res: T) => void): Query; - find(criteria: Object, callback?: (err: any, res: T) => void): Query; - findOne(callback?: (err: any, res: T) => void): Query; - findOne(criteria: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, callback?: (err: any, res: T) => void): Query; - findOneAndRemove(cond: Object, options: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(update: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, callback?: (err: any, res: T) => void): Query; - findOneAndUpdate(cond: Object, update: Object, options: FindAndUpdateOption, callback?: (err: any, res: T) => void): Query; - geometry(object: Object): Query; - gt(val: number): Query; - gt(path: string, val: number): Query; - gte(val: number): Query; - gte(path: string, val: number): Query; - hint(val: Object): Query; - in(val: any[]): Query; - in(path: string, val: any[]): Query; - intersects(arg?: Object): Query; - lean(bool?: boolean): Query; - limit(val: number): Query; - lt(val: number): Query; - lt(path: string, val: number): Query; - lte(val: number): Query; - lte(path: string, val: number): Query; - maxDistance(val: number): Query; - maxDistance(path: string, val: number): Query; - maxScan(val: number): Query; - merge(source: Query): Query; - merge(source: Object): Query; - mod(val: number[]): Query; - mod(path: string, val: number[]): Query; - ne(val: any): Query; - ne(path: string, val: any): Query; - near(val: Object): Query; - near(path: string, val: Object): Query; - nearSphere(val: Object): Query; - nearSphere(path: string, val: Object): Query; - nin(val: any[]): Query; - nin(path: string, val: any[]): Query; - nor(array: Object[]): Query; - or(array: Object[]): Query; - polygon(...coordinatePairs: number[][]): Query; - polygon(path: string, ...coordinatePairs: number[][]): Query; - populate(path: string, select?: string, match?: Object, options?: Object): Query; - populate(path: string, select: string, model: string, match?: Object, options?: Object): Query; - populate(opt: PopulateOption): Query; - read(pref: string, tags?: Object[]): Query; - regex(val: RegExp): Query; - regex(path: string, val: RegExp): Query; - remove(callback?: (err: any, res: T) => void): Query; - remove(criteria: Object, callback?: (err: any, res: T) => void): Query; - select(arg: string): Query; - select(arg: Object): Query; - setOptions(options: Object): Query; - size(val: number): Query; - size(path: string, val: number): Query; - skip(val: number): Query; - slaveOk(v?: boolean): Query; - slice(val: number): Query; - slice(val: number[]): Query; - slice(path: string, val: number): Query; - slice(path: string, val: number[]): Query; - snapshot(v?: boolean): Query; - sort(arg: Object): Query; - sort(arg: string): Query; - stream(options?: { transform?: Function; }): QueryStream; - tailable(v?: boolean): Query; - toConstructor(): Query; - update(callback?: (err: any, affectedRows: number, doc: T) => void): Query; - update(doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; - update(criteria: Object, doc: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; - update(criteria: Object, doc: Object, options: Object, callback?: (err: any, affectedRows: number, doc: T) => void): Query; - where(path?: string, val?: any): Query; - where(path?: Object, val?: any): Query; - within(val?: Object): Query; - within(coordinate: number[], ...coordinatePairs: number[][]): Query; - - $where(argument: string): Query; - $where(argument: Function): Query; - - static use$geoWithin: boolean; - } - - export interface PopulateOption { - path: string; - select?: string; - model?: string; - match?: Object; - options?: Object; - } - - export interface QueryStream extends NodeJS.EventEmitter { - destory(err?: any): void; - pause(): void; - resume(): void; - pipe(destination: T, options?: { end?: boolean; }): T; - paused: number; - readable: boolean; - } - - export interface Document { - id?: string; - _id: any; - - equals(doc: Document): boolean; - get(path: string, type?: new(...args: any[]) => any): any; - inspect(options?: Object): string; - invalidate(path: string, errorMsg: string, value: any): void; - invalidate(path: string, error: Error, value: any): void; - isDirectModified(path: string): boolean; - isInit(path: string): boolean; - isModified(path?: string): boolean; - isSelected(path: string): boolean; - markModified(path: string): void; - modifiedPaths(): string[]; - populate(callback?: (err: any, res: T) => void): Document; - populate(path?: string, callback?: (err: any, res: T) => void): Document; - populate(opt: PopulateOption, callback?: (err: any, res: T) => void): Document; - populated(path: string): any; - remove(callback?: (err: any) => void): Query; - save(callback?: (err: any, res: T) => void): void; - set(path: string, val: any, type?: new(...args: any[]) => any, options?: Object): void; - set(path: string, val: any, options?: Object): void; - set(value: Object): void; - toJSON(options?: Object): Object; - toObject(options?: Object): Object; - toString(): string; - update(doc: Object, options: Object, callback: (err: any, affectedRows: number, raw: any) => void): Query; - validate(cb: (err: any) => void): void; - - isNew: boolean; - errors: Object; - schema: Object; - } - - - export class Aggregate { - constructor(...options: Object[]); - - append(...options: Object[]): Aggregate; - group(arg: Object): Aggregate; - limit(num: number): Aggregate; - match(arg: Object): Aggregate; - near(parameters: Object): Aggregate; - project(arg: string): Aggregate; - project(arg: Object): Aggregate; - select(filter: string): Aggregate; - skip(num: number): Aggregate; - sort(arg: string): Aggregate; - sort(arg: Object): Aggregate; - unwind(fiels: string, ...rest: string[]): Aggregate; - - exec(callback?: (err: any, result: T) => void): Promise; - read(pref: string, ...tags: Object[]): Aggregate; - } - - export class Promise { - constructor(fn?: (err: any, result: T) => void); - - then(onFulFill: (result: T) => void | U | Promise, onReject?: (err: any) => void | U | Promise): Promise; - end(): void; - - fulfill(result: T): Promise; - reject(err: any): Promise; - resolve(err: any, result: T): Promise; - - onFulfill(listener: (result: T) => void): Promise; - onReject(listener: (err: any) => void): Promise; - onResolve(listener: (err: any, result: T) => void): Promise; - on(event: string, listener: Function): Promise; - - // Deprecated methods. - addBack(listener: (err: any, result: T) => void): Promise; - addCallback(listener: (result: T) => void): Promise; - addErrback(listener: (err: any) => void): Promise; - complete(result: T): Promise; - error(err: any): Promise; - } - -} +} \ No newline at end of file From e0896e285bce6c3567310b39c9a9039e9d5b038b Mon Sep 17 00:00:00 2001 From: Zev Spitz Date: Wed, 13 Jul 2016 09:28:46 +0300 Subject: [PATCH 0059/1255] Rename WIA files; removed VarDate interface (#10081) * Rename WIA files * Removed VarDate definition; is now in lib.d.ts Renamed WIA definition Added ADO definitions * Restored VarDate; TS lint fixes DefinitelyTyped is still using Typescript 1.8 in Travis CI compile checks. --- ts-activex/activex-data-objects-tests.ts | 21 + ts-activex/activex-data-objects.d.ts | 836 ++++++++++++++++++ .../microsoft-scripting-runtime-tests.ts | 16 +- ts-activex/microsoft-scripting-runtime.d.ts | 7 +- ....ts => windows-image-acquisition-tests.ts} | 14 +- ...on.d.ts => windows-image-acquisition.d.ts} | 73 +- 6 files changed, 913 insertions(+), 54 deletions(-) create mode 100644 ts-activex/activex-data-objects-tests.ts create mode 100644 ts-activex/activex-data-objects.d.ts rename ts-activex/{microsoft-windows-image-acquisition-tests.ts => windows-image-acquisition-tests.ts} (82%) rename ts-activex/{microsoft-windows-image-acquisition.d.ts => windows-image-acquisition.d.ts} (83%) diff --git a/ts-activex/activex-data-objects-tests.ts b/ts-activex/activex-data-objects-tests.ts new file mode 100644 index 0000000000..27373ff8f0 --- /dev/null +++ b/ts-activex/activex-data-objects-tests.ts @@ -0,0 +1,21 @@ +/// + + +//open connection to an Excel file +var pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx'; +var conn = new ActiveXObject('ADODB.Connection'); +conn.Provider = 'Microsoft.ACE.OLEDB.12.0'; +conn.ConnectionString = + 'Data Source="' + pathToExcelFile + '";' + + 'Extended Properties="Excel 12.0;HDR=Yes"'; +conn.Open(); + +//create a Command to access the data +var cmd = new ActiveXObject('ADODB.Command'); +cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]'; +//get a Recordset +var rs = cmd.Execute(); +//build a string from the Recordset +var s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)'); +rs.Close(); +WScript.Echo(s); \ No newline at end of file diff --git a/ts-activex/activex-data-objects.d.ts b/ts-activex/activex-data-objects.d.ts new file mode 100644 index 0000000000..5b6844fef4 --- /dev/null +++ b/ts-activex/activex-data-objects.d.ts @@ -0,0 +1,836 @@ +// Type definitions for Microsoft ActiveX Data Objects +// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms675532(v=vs.85).aspx +// Definitions by: Zev Spitz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ADODB { + + //Enums + const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM { + adPriorityAboveNormal = 4, + adPriorityBelowNormal = 2, + adPriorityHighest = 5, + adPriorityLowest = 1, + adPriorityNormal = 3 + } + + const enum ADCPROP_AUTORECALC_ENUM { + adRecalcAlways = 1, + adRecalcUpFront = 0 + } + + const enum ADCPROP_UPDATECRITERIA_ENUM { + adCriteriaAllCols = 1, + adCriteriaKey = 0, + adCriteriaTimeStamp = 3, + adCriteriaUpdCols = 2 + } + + const enum ADCPROP_UPDATERESYNC_ENUM { + adResyncAll = 15, + adResyncAutoIncrement = 1, + adResyncConflicts = 2, + adResyncInserts = 8, + adResyncNone = 0, + adResyncUpdates = 4 + } + + const enum AffectEnum { + adAffectAll = 3, + adAffectAllChapters = 4, + adAffectCurrent = 1, + adAffectGroup = 2 + } + + const enum BookmarkEnum { + adBookmarkCurrent = 0, + adBookmarkFirst = 1, + adBookmarkLast = 2 + } + + const enum CommandTypeEnum { + adCmdFile = 256, + adCmdStoredProc = 4, + adCmdTable = 2, + adCmdTableDirect = 512, + adCmdText = 1, + adCmdUnknown = 8, + adCmdUnspecified = -1 + } + + const enum CompareEnum { + adCompareEqual = 1, + adCompareGreaterThan = 2, + adCompareLessThan = 0, + adCompareNotComparable = 4, + adCompareNotEqual = 3 + } + + const enum ConnectModeEnum { + adModeRead = 1, + adModeReadWrite = 3, + adModeRecursive = 4194304, + adModeShareDenyNone = 16, + adModeShareDenyRead = 4, + adModeShareDenyWrite = 8, + adModeShareExclusive = 12, + adModeUnknown = 0, + adModeWrite = 2 + } + + const enum ConnectOptionEnum { + adAsyncConnect = 16, + adConnectUnspecified = -1 + } + + const enum ConnectPromptEnum { + adPromptAlways = 1, + adPromptComplete = 2, + adPromptCompleteRequired = 3, + adPromptNever = 4 + } + + const enum CopyRecordOptionsEnum { + adCopyAllowEmulation = 4, + adCopyNonRecursive = 2, + adCopyOverWrite = 1, + adCopyUnspecified = -1 + } + + const enum CursorLocationEnum { + adUseClient = 3, + adUseClientBatch = 3, + adUseNone = 1, + adUseServer = 2 + } + + const enum CursorOptionEnum { + adAddNew = 16778240, + adApproxPosition = 16384, + adBookmark = 8192, + adDelete = 16779264, + adFind = 524288, + adHoldRecords = 256, + adIndex = 8388608, + adMovePrevious = 512, + adNotify = 262144, + adResync = 131072, + adSeek = 4194304, + adUpdate = 16809984, + adUpdateBatch = 65536 + } + + const enum CursorTypeEnum { + adOpenDynamic = 2, + adOpenForwardOnly = 0, + adOpenKeyset = 1, + adOpenStatic = 3, + adOpenUnspecified = -1 + } + + const enum DataTypeEnum { + adArray = 8192, + adBigInt = 20, + adBinary = 128, + adBoolean = 11, + adBSTR = 8, + adChapter = 136, + adChar = 129, + adCurrency = 6, + adDate = 7, + adDBDate = 133, + adDBTime = 134, + adDBTimeStamp = 135, + adDecimal = 14, + adDouble = 5, + adEmpty = 0, + adError = 10, + adFileTime = 64, + adGUID = 72, + adIDispatch = 9, + adInteger = 3, + adIUnknown = 13, + adLongVarBinary = 205, + adLongVarChar = 201, + adLongVarWChar = 203, + adNumeric = 131, + adPropVariant = 138, + adSingle = 4, + adSmallInt = 2, + adTinyInt = 16, + adUnsignedBigInt = 21, + adUnsignedInt = 19, + adUnsignedSmallInt = 18, + adUnsignedTinyInt = 17, + adUserDefined = 132, + adVarBinary = 204, + adVarChar = 200, + adVariant = 12, + adVarNumeric = 139, + adVarWChar = 202, + adWChar = 130 + } + + const enum EditModeEnum { + adEditAdd = 2, + adEditDelete = 4, + adEditInProgress = 1, + adEditNone = 0 + } + + const enum ErrorValueEnum { + adErrBoundToCommand = 3707, + adErrCannotComplete = 3732, + adErrCantChangeConnection = 3748, + adErrCantChangeProvider = 3220, + adErrCantConvertvalue = 3724, + adErrCantCreate = 3725, + adErrCatalogNotSet = 3747, + adErrColumnNotOnThisRow = 3726, + adErrConnectionStringTooLong = 3754, + adErrDataConversion = 3421, + adErrDataOverflow = 3721, + adErrDelResOutOfScope = 3738, + adErrDenyNotSupported = 3750, + adErrDenyTypeNotSupported = 3751, + adErrFeatureNotAvailable = 3251, + adErrFieldsUpdateFailed = 3749, + adErrIllegalOperation = 3219, + adErrIntegrityViolation = 3719, + adErrInTransaction = 3246, + adErrInvalidArgument = 3001, + adErrInvalidConnection = 3709, + adErrInvalidParamInfo = 3708, + adErrInvalidTransaction = 3714, + adErrInvalidURL = 3729, + adErrItemNotFound = 3265, + adErrNoCurrentRecord = 3021, + adErrNotExecuting = 3715, + adErrNotReentrant = 3710, + adErrObjectClosed = 3704, + adErrObjectInCollection = 3367, + adErrObjectNotSet = 3420, + adErrObjectOpen = 3705, + adErrOpeningFile = 3002, + adErrOperationCancelled = 3712, + adErrOutOfSpace = 3734, + adErrPermissionDenied = 3720, + adErrPropConflicting = 3742, + adErrPropInvalidColumn = 3739, + adErrPropInvalidOption = 3740, + adErrPropInvalidValue = 3741, + adErrPropNotAllSettable = 3743, + adErrPropNotSet = 3744, + adErrPropNotSettable = 3745, + adErrPropNotSupported = 3746, + adErrProviderFailed = 3000, + adErrProviderNotFound = 3706, + adErrProviderNotSpecified = 3753, + adErrReadFile = 3003, + adErrResourceExists = 3731, + adErrResourceLocked = 3730, + adErrResourceOutOfScope = 3735, + adErrSchemaViolation = 3722, + adErrSignMismatch = 3723, + adErrStillConnecting = 3713, + adErrStillExecuting = 3711, + adErrTreePermissionDenied = 3728, + adErrUnavailable = 3736, + adErrUnsafeOperation = 3716, + adErrURLDoesNotExist = 3727, + adErrURLNamedRowDoesNotExist = 3737, + adErrVolumeNotFound = 3733, + adErrWriteFile = 3004, + adwrnSecurityDialog = 3717, + adwrnSecurityDialogHeader = 3718 + } + + const enum EventReasonEnum { + adRsnAddNew = 1, + adRsnClose = 9, + adRsnDelete = 2, + adRsnFirstChange = 11, + adRsnMove = 10, + adRsnMoveFirst = 12, + adRsnMoveLast = 15, + adRsnMoveNext = 13, + adRsnMovePrevious = 14, + adRsnRequery = 7, + adRsnResynch = 8, + adRsnUndoAddNew = 5, + adRsnUndoDelete = 6, + adRsnUndoUpdate = 4, + adRsnUpdate = 3 + } + + const enum EventStatusEnum { + adStatusCancel = 4, + adStatusCantDeny = 3, + adStatusErrorsOccurred = 2, + adStatusOK = 1, + adStatusUnwantedEvent = 5 + } + + const enum ExecuteOptionEnum { + adAsyncExecute = 16, + adAsyncFetch = 32, + adAsyncFetchNonBlocking = 64, + adExecuteNoRecords = 128, + adExecuteRecord = 2048, + adExecuteStream = 1024, + adOptionUnspecified = -1 + } + + const enum FieldAttributeEnum { + adFldCacheDeferred = 4096, + adFldFixed = 16, + adFldIsChapter = 8192, + adFldIsCollection = 262144, + adFldIsDefaultStream = 131072, + adFldIsNullable = 32, + adFldIsRowURL = 65536, + adFldKeyColumn = 32768, + adFldLong = 128, + adFldMayBeNull = 64, + adFldMayDefer = 2, + adFldNegativeScale = 16384, + adFldRowID = 256, + adFldRowVersion = 512, + adFldUnknownUpdatable = 8, + adFldUnspecified = -1, + adFldUpdatable = 4 + } + + const enum FieldEnum { + adDefaultStream = -1, + adRecordURL = -2 + } + + const enum FieldStatusEnum { + adFieldAlreadyExists = 26, + adFieldBadStatus = 12, + adFieldCannotComplete = 20, + adFieldCannotDeleteSource = 23, + adFieldCantConvertValue = 2, + adFieldCantCreate = 7, + adFieldDataOverflow = 6, + adFieldDefault = 13, + adFieldDoesNotExist = 16, + adFieldIgnore = 15, + adFieldIntegrityViolation = 10, + adFieldInvalidURL = 17, + adFieldIsNull = 3, + adFieldOK = 0, + adFieldOutOfSpace = 22, + adFieldPendingChange = 262144, + adFieldPendingDelete = 131072, + adFieldPendingInsert = 65536, + adFieldPendingUnknown = 524288, + adFieldPendingUnknownDelete = 1048576, + adFieldPermissionDenied = 9, + adFieldReadOnly = 24, + adFieldResourceExists = 19, + adFieldResourceLocked = 18, + adFieldResourceOutOfScope = 25, + adFieldSchemaViolation = 11, + adFieldSignMismatch = 5, + adFieldTruncated = 4, + adFieldUnavailable = 8, + adFieldVolumeNotFound = 21 + } + + const enum FilterGroupEnum { + adFilterAffectedRecords = 2, + adFilterConflictingRecords = 5, + adFilterFetchedRecords = 3, + adFilterNone = 0, + adFilterPendingRecords = 1, + adFilterPredicate = 4 + } + + const enum GetRowsOptionEnum { + adGetRowsRest = -1 + } + + const enum IsolationLevelEnum { + adXactBrowse = 256, + adXactChaos = 16, + adXactCursorStability = 4096, + adXactIsolated = 1048576, + adXactReadCommitted = 4096, + adXactReadUncommitted = 256, + adXactRepeatableRead = 65536, + adXactSerializable = 1048576, + adXactUnspecified = -1 + } + + const enum LineSeparatorEnum { + adCR = 13, + adCRLF = -1, + adLF = 10 + } + + const enum LockTypeEnum { + adLockBatchOptimistic = 4, + adLockOptimistic = 3, + adLockPessimistic = 2, + adLockReadOnly = 1, + adLockUnspecified = -1 + } + + const enum MarshalOptionsEnum { + adMarshalAll = 0, + adMarshalModifiedOnly = 1 + } + + const enum MoveRecordOptionsEnum { + adMoveAllowEmulation = 4, + adMoveDontUpdateLinks = 2, + adMoveOverWrite = 1, + adMoveUnspecified = -1 + } + + const enum ObjectStateEnum { + adStateClosed = 0, + adStateConnecting = 2, + adStateExecuting = 4, + adStateFetching = 8, + adStateOpen = 1 + } + + const enum ParameterAttributesEnum { + adParamLong = 128, + adParamNullable = 64, + adParamSigned = 16 + } + + const enum ParameterDirectionEnum { + adParamInput = 1, + adParamInputOutput = 3, + adParamOutput = 2, + adParamReturnValue = 4, + adParamUnknown = 0 + } + + const enum PersistFormatEnum { + adPersistADTG = 0, + adPersistXML = 1 + } + + const enum PositionEnum { + adPosBOF = -2, + adPosEOF = -3, + adPosUnknown = -1 + } + + const enum PositionEnum_Param { + adPosBOF = -2, + adPosEOF = -3, + adPosUnknown = -1 + } + + const enum PropertyAttributesEnum { + adPropNotSupported = 0, + adPropOptional = 2, + adPropRead = 512, + adPropRequired = 1, + adPropWrite = 1024 + } + + const enum RecordCreateOptionsEnum { + adCreateCollection = 8192, + adCreateNonCollection = 0, + adCreateOverwrite = 67108864, + adCreateStructDoc = -2147483648, + adFailIfNotExists = -1, + adOpenIfExists = 33554432 + } + + const enum RecordOpenOptionsEnum { + adDelayFetchFields = 32768, + adDelayFetchStream = 16384, + adOpenAsync = 4096, + adOpenExecuteCommand = 65536, + adOpenOutput = 8388608, + adOpenRecordUnspecified = -1, + adOpenSource = 8388608 + } + + const enum RecordStatusEnum { + adRecCanceled = 256, + adRecCantRelease = 1024, + adRecConcurrencyViolation = 2048, + adRecDBDeleted = 262144, + adRecDeleted = 4, + adRecIntegrityViolation = 4096, + adRecInvalid = 16, + adRecMaxChangesExceeded = 8192, + adRecModified = 2, + adRecMultipleChanges = 64, + adRecNew = 1, + adRecObjectOpen = 16384, + adRecOK = 0, + adRecOutOfMemory = 32768, + adRecPendingChanges = 128, + adRecPermissionDenied = 65536, + adRecSchemaViolation = 131072, + adRecUnmodified = 8 + } + + const enum RecordTypeEnum { + adCollectionRecord = 1, + adSimpleRecord = 0, + adStructDoc = 2 + } + + const enum ResyncEnum { + adResyncAllValues = 2, + adResyncUnderlyingValues = 1 + } + + const enum SaveOptionsEnum { + adSaveCreateNotExist = 1, + adSaveCreateOverWrite = 2 + } + + const enum SchemaEnum { + adSchemaActions = 41, + adSchemaAsserts = 0, + adSchemaCatalogs = 1, + adSchemaCharacterSets = 2, + adSchemaCheckConstraints = 5, + adSchemaCollations = 3, + adSchemaColumnPrivileges = 13, + adSchemaColumns = 4, + adSchemaColumnsDomainUsage = 11, + adSchemaCommands = 42, + adSchemaConstraintColumnUsage = 6, + adSchemaConstraintTableUsage = 7, + adSchemaCubes = 32, + adSchemaDBInfoKeywords = 30, + adSchemaDBInfoLiterals = 31, + adSchemaDimensions = 33, + adSchemaForeignKeys = 27, + adSchemaFunctions = 40, + adSchemaHierarchies = 34, + adSchemaIndexes = 12, + adSchemaKeyColumnUsage = 8, + adSchemaLevels = 35, + adSchemaMeasures = 36, + adSchemaMembers = 38, + adSchemaPrimaryKeys = 28, + adSchemaProcedureColumns = 29, + adSchemaProcedureParameters = 26, + adSchemaProcedures = 16, + adSchemaProperties = 37, + adSchemaProviderSpecific = -1, + adSchemaProviderTypes = 22, + adSchemaReferentialConstraints = 9, + adSchemaReferentialContraints = 9, + adSchemaSchemata = 17, + adSchemaSets = 43, + adSchemaSQLLanguages = 18, + adSchemaStatistics = 19, + adSchemaTableConstraints = 10, + adSchemaTablePrivileges = 14, + adSchemaTables = 20, + adSchemaTranslations = 21, + adSchemaTrustees = 39, + adSchemaUsagePrivileges = 15, + adSchemaViewColumnUsage = 24, + adSchemaViews = 23, + adSchemaViewTableUsage = 25 + } + + const enum SearchDirection { + adSearchBackward = -1, + adSearchForward = 1 + } + + const enum SearchDirectionEnum { + adSearchBackward = -1, + adSearchForward = 1 + } + + const enum SeekEnum { + adSeekAfter = 8, + adSeekAfterEQ = 4, + adSeekBefore = 32, + adSeekBeforeEQ = 16, + adSeekFirstEQ = 1, + adSeekLastEQ = 2 + } + + const enum StreamOpenOptionsEnum { + adOpenStreamAsync = 1, + adOpenStreamFromRecord = 4, + adOpenStreamUnspecified = -1 + } + + const enum StreamReadEnum { + adReadAll = -1, + adReadLine = -2 + } + + const enum StreamTypeEnum { + adTypeBinary = 1, + adTypeText = 2 + } + + const enum StreamWriteEnum { + adWriteChar = 0, + adWriteLine = 1, + stWriteChar = 0, + stWriteLine = 1 + } + + const enum StringFormatEnum { + adClipString = 2 + } + + const enum XactAttributeEnum { + adXactAbortRetaining = 262144, + adXactAsyncPhaseOne = 524288, + adXactCommitRetaining = 131072, + adXactSyncPhaseOne = 1048576 + } + + //Interfaces + interface Command { + ActiveConnection: Connection; + Cancel: () => void; + CommandStream: any /*VT_UNKNOWN*/; + CommandText: string; + CommandTimeout: number; + CommandType: CommandTypeEnum; + CreateParameter: (Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any) => Parameter; + Dialect: string; + Execute: (RecordsAffected?: any, Parameters?: any, Options?: number) => Recordset; + Name: string; + NamedParameters: boolean; + Parameters: Parameters; + Prepared: boolean; + Properties: Properties; + State: number; + } + + interface Connection { + Attributes: number; + BeginTrans: () => number; + Cancel: () => void; + Close: () => void; + CommandTimeout: number; + CommitTrans: () => void; + ConnectionString: string; + ConnectionTimeout: number; + CursorLocation: CursorLocationEnum; + DefaultDatabase: string; + Errors: Errors; + Execute: (CommandText: string, RecordsAffected: any, Options?: number) => Recordset; + IsolationLevel: IsolationLevelEnum; + Mode: ConnectModeEnum; + Open: (ConnectionString?: string, UserID?: string, Password?: string, Options?: number) => void; + OpenSchema: (Schema: SchemaEnum, Restrictions?: any, SchemaID?: any) => Recordset; + Properties: Properties; + Provider: string; + RollbackTrans: () => void; + State: number; + Version: string; + } + + interface Error { + Description: string; + HelpContext: number; + HelpFile: string; + NativeError: number; + Number: number; + Source: string; + SQLState: string; + } + + interface Errors { + Clear: () => void; + Count: number; + Item: (Index: any) => Error; + Refresh: () => void; + } + + interface Field { + ActualSize: number; + AppendChunk: (Data: any) => void; + Attributes: number; + DataFormat: any /*VT_UNKNOWN*/; + DefinedSize: number; + GetChunk: (Length: number) => any; + Name: string; + NumericScale: number; + OriginalValue: any; + Precision: number; + Properties: Properties; + Status: number; + Type: DataTypeEnum; + UnderlyingValue: any; + Value: any; + } + + interface Fields { + _Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum) => void; + Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any) => void; + CancelUpdate: () => void; + Count: number; + Delete: (Index: any) => void; + Item: (Index: any) => Field; + Refresh: () => void; + Resync: (ResyncValues?: ResyncEnum) => void; + Update: () => void; + } + + interface Parameter { + AppendChunk: (Val: any) => void; + Attributes: number; + Direction: ParameterDirectionEnum; + Name: string; + NumericScale: number; + Precision: number; + Properties: Properties; + Size: number; + Type: DataTypeEnum; + Value: any; + } + + interface Parameters { + Append: (Object: any /*VT_DISPATCH*/) => void; + Count: number; + Delete: (Index: any) => void; + Item: (Index: any) => Parameter; + Refresh: () => void; + } + + interface Properties { + Count: number; + Item: (Index: any) => Property; + Refresh: () => void; + } + + interface Property { + Attributes: number; + Name: string; + Type: DataTypeEnum; + Value: any; + } + + interface Record { + ActiveConnection: any; + Cancel: () => void; + Close: () => void; + CopyRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean) => string; + DeleteRecord: (Source?: string, Async?: boolean) => void; + Fields: Fields; + GetChildren: () => Recordset; + Mode: ConnectModeEnum; + MoveRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean) => string; + Open: (Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string) => void; + ParentURL: string; + Properties: Properties; + RecordType: RecordTypeEnum; + Source: any; + State: ObjectStateEnum; + } + + interface Recordset { + _xClone: () => Recordset; + _xResync: (AffectRecords?: AffectEnum) => void; + _xSave: (FileName?: string, PersistFormat?: PersistFormatEnum) => void; + AbsolutePage: PositionEnum; + AbsolutePosition: PositionEnum; + ActiveCommand: any /*VT_DISPATCH*/; + ActiveConnection: any /*VT_DISPATCH*/; + AddNew: (FieldList?: any, Values?: any) => void; + BOF: boolean; + Bookmark: any; + CacheSize: number; + Cancel: () => void; + CancelBatch: (AffectRecords?: AffectEnum) => void; + CancelUpdate: () => void; + Clone: (LockType?: LockTypeEnum) => Recordset; + Close: () => void; + Collect: (Index: any) => any; //Also has setter with parameters + CompareBookmarks: (Bookmark1: any, Bookmark2: any) => CompareEnum; + CursorLocation: CursorLocationEnum; + CursorType: CursorTypeEnum; + DataMember: string; + DataSource: any /*VT_UNKNOWN*/; + Delete: (AffectRecords?: AffectEnum) => void; + EditMode: EditModeEnum; + EOF: boolean; + Fields: Fields; + Filter: any; + Find: (Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any) => void; + GetRows: (Rows?: number, Start?: any, Fields?: any) => any; + GetString: (StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string) => string; + Index: string; + LockType: LockTypeEnum; + MarshalOptions: MarshalOptionsEnum; + MaxRecords: number; + Move: (NumRecords: number, Start?: any) => void; + MoveFirst: () => void; + MoveLast: () => void; + MoveNext: () => void; + MovePrevious: () => void; + NextRecordset: (RecordsAffected?: any) => Recordset; + Open: (Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number) => void; + PageCount: number; + PageSize: number; + Properties: Properties; + RecordCount: number; + Requery: (Options?: number) => void; + Resync: (AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum) => void; + Save: (Destination: any, PersistFormat?: PersistFormatEnum) => void; + Seek: (KeyValues: any, SeekOption?: SeekEnum) => void; + Sort: string; + Source: any /*VT_DISPATCH*/; + State: number; + Status: number; + StayInSync: boolean; + Supports: (CursorOptions: CursorOptionEnum) => boolean; + Update: (Fields?: any, Values?: any) => void; + UpdateBatch: (AffectRecords?: AffectEnum) => void; + } + + interface Stream { + Cancel: () => void; + Charset: string; + Close: () => void; + CopyTo: (DestStream: Stream, CharNumber?: number) => void; + EOS: boolean; + Flush: () => void; + LineSeparator: LineSeparatorEnum; + LoadFromFile: (FileName: string) => void; + Mode: ConnectModeEnum; + Open: (Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string) => void; + Position: number; + Read: (NumBytes?: number) => any; + ReadText: (NumChars?: number) => string; + SaveToFile: (FileName: string, Options?: SaveOptionsEnum) => void; + SetEOS: () => void; + Size: number; + SkipLine: () => void; + State: ObjectStateEnum; + Type: StreamTypeEnum; + Write: (Buffer: any) => void; + WriteText: (Data: string, Options?: StreamWriteEnum) => void; + } + +} + +interface ActiveXObject { + new (progID: 'ADODB.Connection'): ADODB.Connection; + new (progID: 'ADODB.Record'): ADODB.Record; + new (progID: 'ADODB.Stream'): ADODB.Stream; + new (progID: 'ADODB.Command'): ADODB.Command; + new (progID: 'ADODB.Recordset'): ADODB.Recordset; + new (progID: 'ADODB.Parameter'): ADODB.Parameter; +} + diff --git a/ts-activex/microsoft-scripting-runtime-tests.ts b/ts-activex/microsoft-scripting-runtime-tests.ts index 623b48368a..d08dc5cf96 100644 --- a/ts-activex/microsoft-scripting-runtime-tests.ts +++ b/ts-activex/microsoft-scripting-runtime-tests.ts @@ -26,7 +26,7 @@ var showDriveType = (drive: Scripting.Drive) => { //Generates a string describing the attributes of a file or folder. var showFileAttributes = (file: Scripting.File) => { var attr = file.Attributes; - if (attr == 0) { + if (attr === 0) { return 'Normal'; } var attributeStrings: string[] = []; @@ -44,24 +44,24 @@ var showFileAttributes = (file: Scripting.File) => { //source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx var showFreeSpace = (drvPath: string) => { - var fso = new ActiveXObject("Scripting.FileSystemObject"); + var fso = new ActiveXObject('Scripting.FileSystemObject'); var d = fso.GetDrive(fso.GetDriveName(drvPath)); - var s = "Drive " + drvPath + " - "; - s += d.VolumeName + "
"; - s += "Free Space: " + d.FreeSpace / 1024 + " Kbytes"; + var s = 'Drive ' + drvPath + ' - '; + s += d.VolumeName + '
'; + s += 'Free Space: ' + d.FreeSpace / 1024 + ' Kbytes'; return (s); }; //source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx var getALine = (filespec: string) => { - var fso = new ActiveXObject("Scripting.FileSystemObject"); + var fso = new ActiveXObject('Scripting.FileSystemObject'); var file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false); - var s = ""; + var s = ''; while (!file.AtEndOfLine) { s += file.Read(1); } file.Close(); return (s); -} \ No newline at end of file +}; diff --git a/ts-activex/microsoft-scripting-runtime.d.ts b/ts-activex/microsoft-scripting-runtime.d.ts index 0f2f734818..fd50b7504f 100644 --- a/ts-activex/microsoft-scripting-runtime.d.ts +++ b/ts-activex/microsoft-scripting-runtime.d.ts @@ -1,5 +1,5 @@ // Type definitions for Microsoft Scripting Runtime -// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx?f=255&MSPPError=-2147217396 +// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx // Definitions by: Zev Spitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -60,14 +60,14 @@ declare namespace Scripting { TristateUseDefault = -2 } - //Classes + //Interfaces interface Dictionary { Add: (Key: any, Item: any) => void; CompareMode: CompareMethod; Count: number; Exists: (Key: any) => boolean; HashVal: (Key: any) => any; - Item: (Key: any) => any //Also has setter with parameters; + Item: (Key: any) => any; //Also has setter with parameters Items: () => any; Key: (Key: any) => any; Keys: () => any; @@ -204,3 +204,4 @@ interface ActiveXObject { new (progID: 'Scripting.FileSystemObject'): Scripting.FileSystemObject; new (progID: 'Scripting.Encoder'): Scripting.Encoder; } + diff --git a/ts-activex/microsoft-windows-image-acquisition-tests.ts b/ts-activex/windows-image-acquisition-tests.ts similarity index 82% rename from ts-activex/microsoft-windows-image-acquisition-tests.ts rename to ts-activex/windows-image-acquisition-tests.ts index 66a9d75a7d..ae394a99f8 100644 --- a/ts-activex/microsoft-windows-image-acquisition-tests.ts +++ b/ts-activex/windows-image-acquisition-tests.ts @@ -1,4 +1,4 @@ -/// +/// //source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx @@ -6,17 +6,17 @@ //Convert a file var commonDialog = new ActiveXObject('WIA.CommonDialog'); var img = commonDialog.ShowAcquireImage(); -if (img.FormatID != WIA.FormatID.wiaFormatJPEG) { +if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) { var ip = new ActiveXObject('WIA.ImageProcess'); ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID); - ip.Filters.Item(1).Properties.Item("FormatID").Value = WIA.FormatID.wiaFormatJPEG; + ip.Filters.Item(1).Properties.Item('FormatID').Value = WIA.FormatID.wiaFormatJPEG; img = ip.Apply(img); } //Take a picture var dev = commonDialog.ShowSelectDevice(); -if (dev.Type == WIA.WiaDeviceType.CameraDeviceType) { +if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) { var itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); } @@ -32,8 +32,8 @@ while (!e.atEnd()) { s += '[vector of data]'; } else { s += p.Value; - if (p.SubType != WIA.WiaSubType.UnspecifiedSubType) { - if (p.Value != p.SubTypeDefault) { + if (p.SubType !== WIA.WiaSubType.UnspecifiedSubType) { + if (p.Value !== p.SubTypeDefault) { s += ' (Default = ' + p.SubTypeDefault + ')'; } } @@ -45,7 +45,7 @@ while (!e.atEnd()) { switch (p.SubType) { case WIA.WiaSubType.FlagSubType: case WIA.WiaSubType.ListSubType: - if (p.SubType == WIA.WiaSubType.FlagSubType) { + if (p.SubType === WIA.WiaSubType.FlagSubType) { s += ' [valid flags include: '; } else { s += ' [valid values include: '; diff --git a/ts-activex/microsoft-windows-image-acquisition.d.ts b/ts-activex/windows-image-acquisition.d.ts similarity index 83% rename from ts-activex/microsoft-windows-image-acquisition.d.ts rename to ts-activex/windows-image-acquisition.d.ts index ccae387346..7be1884a4e 100644 --- a/ts-activex/microsoft-windows-image-acquisition.d.ts +++ b/ts-activex/windows-image-acquisition.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Microsoft Windows Image Acquisition +// Type definitions for Microsoft Windows Image Acquisition Library v2.0 // Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630827(v=vs.85).aspx // Definitions by: Zev Spitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,34 +8,34 @@ declare namespace WIA { //Enums - type CommandID = - "{04E725B0-ACAE-11D2-A093-00C04F72DC3C}" //wiaCommandChangeDocument - | "{E208C170-ACAD-11D2-A093-00C04F72DC3C}" //wiaCommandDeleteAllItems - | "{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}" //wiaCommandSynchronize - | "{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}" //wiaCommandTakePicture - | "{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}" //wiaCommandUnloadDocument + type CommandID = + "'{04E725B0-ACAE-11D2-A093-00C04F72DC3C}'" //wiaCommandChangeDocument + | "'{E208C170-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandDeleteAllItems + | "'{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandSynchronize + | "'{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandTakePicture + | "'{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}'"; //wiaCommandUnloadDocument const CommandID: { wiaCommandChangeDocument: CommandID, wiaCommandDeleteAllItems: CommandID, wiaCommandSynchronize: CommandID, wiaCommandTakePicture: CommandID, wiaCommandUnloadDocument: CommandID - } + }; - type EventID = - "{A28BBADE-64B6-11D2-A231-00C04FA31809}" //wiaEventDeviceConnected - | "{143E4E83-6497-11D2-A231-00C04FA31809}" //wiaEventDeviceDisconnected - | "{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}" //wiaEventItemCreated - | "{1D22A559-E14F-11D2-B326-00C04F68CE61}" //wiaEventItemDeleted - | "{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}" //wiaEventScanEmailImage - | "{C00EB793-8C6E-11D2-977A-0000F87A926F}" //wiaEventScanFaxImage - | "{9B2B662C-6185-438C-B68B-E39EE25E71CB}" //wiaEventScanFilmImage - | "{A6C5A715-8C6E-11D2-977A-0000F87A926F}" //wiaEventScanImage - | "{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}" //wiaEventScanImage2 - | "{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}" //wiaEventScanImage3 - | "{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}" //wiaEventScanImage4 - | "{9D095B89-37D6-4877-AFED-62A297DC6DBE}" //wiaEventScanOCRImage - | "{B441F425-8C6E-11D2-977A-0000F87A926F}" //wiaEventScanPrintImage + type EventID = + "'{A28BBADE-64B6-11D2-A231-00C04FA31809}'" //wiaEventDeviceConnected + | "'{143E4E83-6497-11D2-A231-00C04FA31809}'" //wiaEventDeviceDisconnected + | "'{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemCreated + | "'{1D22A559-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemDeleted + | "'{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}'" //wiaEventScanEmailImage + | "'{C00EB793-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanFaxImage + | "'{9B2B662C-6185-438C-B68B-E39EE25E71CB}'" //wiaEventScanFilmImage + | "'{A6C5A715-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanImage + | "'{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}'" //wiaEventScanImage2 + | "'{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}'" //wiaEventScanImage3 + | "'{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}'" //wiaEventScanImage4 + | "'{9D095B89-37D6-4877-AFED-62A297DC6DBE}'" //wiaEventScanOCRImage + | "'{B441F425-8C6E-11D2-977A-0000F87A926F}'"; //wiaEventScanPrintImage const EventID: { wiaEventDeviceConnected: EventID, wiaEventDeviceDisconnected: EventID, @@ -50,29 +50,29 @@ declare namespace WIA { wiaEventScanImage4: EventID, wiaEventScanOCRImage: EventID, wiaEventScanPrintImage: EventID - } + }; - type FormatID = - "{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatBMP - | "{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatGIF - | "{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatJPEG - | "{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatPNG - | "{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}" //wiaFormatTIFF + type FormatID = + "'{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatBMP + | "'{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatGIF + | "'{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatJPEG + | "'{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatPNG + | "'{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}'"; //wiaFormatTIFF const FormatID: { wiaFormatBMP: FormatID, wiaFormatGIF: FormatID, wiaFormatJPEG: FormatID, wiaFormatPNG: FormatID, wiaFormatTIFF: FormatID - } + }; - type Miscellaneous = - "*" //wiaAnyDeviceID - | "{00000000-0000-0000-0000-000000000000}" //wiaIDUnknown + type Miscellaneous = + "'*'" //wiaAnyDeviceID + | "'{00000000-0000-0000-0000-000000000000}'"; //wiaIDUnknown const Miscellaneous: { wiaAnyDeviceID: Miscellaneous, wiaIDUnknown: Miscellaneous - } + }; const enum WiaDeviceType { CameraDeviceType = 2, @@ -185,7 +185,7 @@ declare namespace WIA { UnspecifiedSubType = 0 } - //Classes + //Interfaces interface CommonDialog { ShowAcquireImage: (DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean) => ImageFile; ShowAcquisitionWizard: (Device: Device) => any; @@ -361,7 +361,7 @@ declare namespace WIA { Count: number; Date: VarDate; ImageFile: (Width?: number, Height?: number) => ImageFile; - Item: (Index: number) => any //Also has setter with parameters; + Item: (Index: number) => any; //Also has setter with parameters Picture: (Width?: number, Height?: number) => any; Remove: (Index: number) => any; SetFromString: (Value: string, Resizable?: boolean, Unicode?: boolean) => void; @@ -378,3 +378,4 @@ interface ActiveXObject { new (progID: 'WIA.CommonDialog'): WIA.CommonDialog; new (progID: 'WIA.DeviceManager'): WIA.DeviceManager; } + From b66d6115d7a8cd74af45e59d36c4447e5d1e9a52 Mon Sep 17 00:00:00 2001 From: Jeffery Grajkowski Date: Tue, 12 Jul 2016 23:29:41 -0700 Subject: [PATCH 0060/1255] Added typings for react-flex (#10054) * Added typings for react-flex * Fix react-flex-tests.tsx import of React --- react-flex/react-flex-tests.tsx | 40 ++++++++++++++ react-flex/react-flex.d.ts | 94 +++++++++++++++++++++++++++++++++ 2 files changed, 134 insertions(+) create mode 100644 react-flex/react-flex-tests.tsx create mode 100644 react-flex/react-flex.d.ts diff --git a/react-flex/react-flex-tests.tsx b/react-flex/react-flex-tests.tsx new file mode 100644 index 0000000000..8e562dbeff --- /dev/null +++ b/react-flex/react-flex-tests.tsx @@ -0,0 +1,40 @@ +/// + +import { Flex, Item } from "react-flex"; +import * as React from "react"; + +const ex1: JSX.Element = ( + +
a first div
+ flexes to 1 +
+); + +const ex2: JSX.Element = ( + + + content here + + +); + +const ex3: JSX.Element = ( + + + content here + + +); + +const ex4: JSX.Element = ( + + + Flex also supports the `flex` prop + + + Yup. + + + + +); diff --git a/react-flex/react-flex.d.ts b/react-flex/react-flex.d.ts new file mode 100644 index 0000000000..ddb7c3e5da --- /dev/null +++ b/react-flex/react-flex.d.ts @@ -0,0 +1,94 @@ +// Type definitions for react-flex v2.2.7 +// Project: https://github.com/zippyui/react-flex +// Definitions by: Jeffery Grajkowski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace __ReactFlex { + export import React = __React; + + interface CommonFlexProps { + /** + * For `display: inline-flex`. + */ + inline?: boolean; + + /** + * For `flex-direction: row`. Defaults to `true`. + */ + row?: boolean; + + /** + * For `flex-direction: column`. + */ + column?: boolean; + + /** + * For reverse direction (eg. `flex-direction: column-reverse` or `row-reverse`). + */ + reverse?: boolean; + + /** + * For `flex-wrap: wrap`. Defaults to `true`. + */ + wrap?: boolean; + + /** + * A number/string from 0 to 24 for the `flex` css property. `false` for `'none'`. + */ + flex?: number | string | boolean; + + /** + * A value for the `align-items` css property. Defaults to `'center'`. + */ + alignItems?: string; + + /** + * A value for the `justify-content` css property. + */ + justifyContent?: string; + + /** + * A value for the `align-content` css property. + */ + alignContent?: string; + + /** + * Customize the display to be `'flex'` or `'inline-flex'`. + * Defaults to `'flex'`. + */ + display?: string; + } + + interface FlexProps extends React.Props, CommonFlexProps { + } + + export class Flex extends React.Component { + } + + interface ItemProps extends React.Props, CommonFlexProps { + /** + * A number/string from 0 to 24 for `flex-grow`. Most of the times, using `flex` is just enough. + */ + flexGrow?: number | string | boolean; + + /** + * A value for the `flex-shrink` css property. From `0` to `24`. + */ + flexShrink?: number | string; + + /** + * A value for the flex-basis css property. Valid values are: `0` (and `'none'`, which is the same), + * `'auto'`, `'content'`, `'fit-content'`, `'min-content'`, `'max-content'`, `'fit'`. + */ + flexBasis?: number | "none" | "auto" | "content" | "fit-content" | "min-content" | "max-content" | "fit"; + } + + export class Item extends React.Component { + } +} + +declare module "react-flex" { + export = __ReactFlex; +} From fcfde8ed43a289559e69b13f55d231923a69a4e9 Mon Sep 17 00:00:00 2001 From: Blessing Pascal Date: Wed, 13 Jul 2016 09:10:05 +0200 Subject: [PATCH 0061/1255] Added @deprecated on request.param --- express-serve-static-core/express-serve-static-core.d.ts | 2 ++ 1 file changed, 2 insertions(+) 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 8bb4863c6b..f133ab2f52 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -241,6 +241,8 @@ declare module "express-serve-static-core" { accepted: MediaType[]; /** + * @deprecated Use either req.params, req.body or req.query, as applicable. + * * Return the value of param `name` when present or `defaultValue`. * * - Checks route placeholders, ex: _/user/:id_ From 8dc966a11cb7c3c1ee21607fb4f1f5cb91475cb9 Mon Sep 17 00:00:00 2001 From: denis Date: Thu, 14 Jul 2016 10:42:17 +0200 Subject: [PATCH 0062/1255] Formatting Add semicolon --- chosen/chosen.jquery.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chosen/chosen.jquery.d.ts b/chosen/chosen.jquery.d.ts index f43a2fefbd..c7f7c6b7ee 100644 --- a/chosen/chosen.jquery.d.ts +++ b/chosen/chosen.jquery.d.ts @@ -6,8 +6,8 @@ /// declare namespace Chosen { - type OnEvent = "chosen:ready" | "chosen:maxselected" | "chosen:showing_dropdown" | "chosen:hiding_dropdown" | "chosen:no_results" - type TriggerEvent = "chosen:updated" | "chosen:activate" | "chosen:open" | "chosen:close" + type OnEvent = "chosen:ready" | "chosen:maxselected" | "chosen:showing_dropdown" | "chosen:hiding_dropdown" | "chosen:no_results"; + type TriggerEvent = "chosen:updated" | "chosen:activate" | "chosen:open" | "chosen:close"; interface Options { /**When set to true on a single select, Chosen adds a UI element which selects the first element (if it is blank). From 679c3b36fe6ff78e323f0940b6e7c170acdfbc1b Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 08:48:05 -0400 Subject: [PATCH 0063/1255] Create masonry-layout-tests.ts --- masonry-layout/masonry-layout-tests.ts | 1 + 1 file changed, 1 insertion(+) create mode 100644 masonry-layout/masonry-layout-tests.ts diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/masonry-layout/masonry-layout-tests.ts @@ -0,0 +1 @@ + From 8b6b2cad03bc33b0b3b5018c5adbdc802f0b17c6 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:21:19 -0400 Subject: [PATCH 0064/1255] Delete masonry-layout-tests.ts --- masonry-layout/masonry-layout-tests.ts | 1 - 1 file changed, 1 deletion(-) delete mode 100644 masonry-layout/masonry-layout-tests.ts diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts deleted file mode 100644 index 8b13789179..0000000000 --- a/masonry-layout/masonry-layout-tests.ts +++ /dev/null @@ -1 +0,0 @@ - From f595e716b97bab9d3d8a22e4b81a5a989cd913a6 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:22:32 -0400 Subject: [PATCH 0065/1255] Add files via upload --- masonry-layout-tests.ts | 48 ++++++++++++++++++++++++++++ masonry-layout.d.ts | 70 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+) create mode 100644 masonry-layout-tests.ts create mode 100644 masonry-layout.d.ts diff --git a/masonry-layout-tests.ts b/masonry-layout-tests.ts new file mode 100644 index 0000000000..e83a898f54 --- /dev/null +++ b/masonry-layout-tests.ts @@ -0,0 +1,48 @@ +// test file for masonry-layout.d.ts + +/// +/// + +//import {Masonry} from "./masonry-layout.d.ts"; + +// responsive layouts +function testResponsiveLayouts() { + $('.grid').masonry({ + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true + }); +} + +// recommended Options +function testRecommendedOptions() { + $('.grid').masonry({ + columnWidth: 200, + itemSelector: '.grid-item' + }); + + var msnry = new Masonry.Masonry('.grid', { + columnWidth: 200, + itemSelector: '.grid-item' + }); +} + +// extended Options +function testExtendedOptions() { + var msnry = new Masonry.Masonry('.grid', { + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true, + gutter: '.gutter-sizer', + stamp: '.stamp', + fitWidth: true, + originLeft: true, + originTop: true, + containerStyle: { + position: 'relative' + }, + transitionDuration: '0.4s', + resize: true, + initLayout: true + }); +} diff --git a/masonry-layout.d.ts b/masonry-layout.d.ts new file mode 100644 index 0000000000..0923a8f463 --- /dev/null +++ b/masonry-layout.d.ts @@ -0,0 +1,70 @@ +// Type definitions for Masonry 4.0.0 +// Project: https://github.com/desandro/masonry +// Definitions by: Mark Wilson +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +// Modified from original definitions by: +// Travis Brown < https://github.com/warriorrocker> + +declare module Masonry { + + class Masonry implements MasonryGrid { + constructor(options?: MasonryOptions); + constructor(selector: string, options?: MasonryOptions); + } + + interface MasonryGrid { + masonry?(): void; + masonry?(eventName: string, listener: any): void; + + // layout + layout?(): void; + layoutItems?(items: Array, isStill?: boolean): void; + stamp?(elements: Array): void; + unstamp?(elements: Array): void; + + // add and remove items + appended?(elements: Array): void; + prepended?(elements: Array): void; + addItems?(elements: Array): void; + remove?(elements: Array): void; + + // events + on?(eventName: string, listener: any): void; + off?(eventName: string, listener: any): void; + once?(eventName: string, listener: any): void; + + // utilities + reloadItems?(): void; + destroy?(): void; + getItemElements?(): Array; + data?(element: Element): Masonry; + } + + interface MasonryOptions { + + // layout + itemSelector?: string; + columnWidth?: any; + percentPosition?: boolean; + gutter?: any; + stamp?: string; + fitWidth?: boolean; + originLeft?: boolean; + originTop?: boolean; + + // setup + containerStyle?: Object; + transitionDuration?: any; + resize?: boolean; + initLayout?: boolean; + } +} + +interface JQuery { + masonry(options?: Masonry.MasonryOptions): JQuery; +} + + From c8b868b4f4dbeb4459effd91ea29aad21f83f860 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:23:49 -0400 Subject: [PATCH 0066/1255] Delete masonry-layout.d.ts --- masonry-layout.d.ts | 70 --------------------------------------------- 1 file changed, 70 deletions(-) delete mode 100644 masonry-layout.d.ts diff --git a/masonry-layout.d.ts b/masonry-layout.d.ts deleted file mode 100644 index 0923a8f463..0000000000 --- a/masonry-layout.d.ts +++ /dev/null @@ -1,70 +0,0 @@ -// Type definitions for Masonry 4.0.0 -// Project: https://github.com/desandro/masonry -// Definitions by: Mark Wilson -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -// Modified from original definitions by: -// Travis Brown < https://github.com/warriorrocker> - -declare module Masonry { - - class Masonry implements MasonryGrid { - constructor(options?: MasonryOptions); - constructor(selector: string, options?: MasonryOptions); - } - - interface MasonryGrid { - masonry?(): void; - masonry?(eventName: string, listener: any): void; - - // layout - layout?(): void; - layoutItems?(items: Array, isStill?: boolean): void; - stamp?(elements: Array): void; - unstamp?(elements: Array): void; - - // add and remove items - appended?(elements: Array): void; - prepended?(elements: Array): void; - addItems?(elements: Array): void; - remove?(elements: Array): void; - - // events - on?(eventName: string, listener: any): void; - off?(eventName: string, listener: any): void; - once?(eventName: string, listener: any): void; - - // utilities - reloadItems?(): void; - destroy?(): void; - getItemElements?(): Array; - data?(element: Element): Masonry; - } - - interface MasonryOptions { - - // layout - itemSelector?: string; - columnWidth?: any; - percentPosition?: boolean; - gutter?: any; - stamp?: string; - fitWidth?: boolean; - originLeft?: boolean; - originTop?: boolean; - - // setup - containerStyle?: Object; - transitionDuration?: any; - resize?: boolean; - initLayout?: boolean; - } -} - -interface JQuery { - masonry(options?: Masonry.MasonryOptions): JQuery; -} - - From 1b6467c9f19e2ed180b92c1ac430311d1e557a29 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:25:31 -0400 Subject: [PATCH 0067/1255] Delete masonry-layout-tests.ts --- masonry-layout-tests.ts | 48 ----------------------------------------- 1 file changed, 48 deletions(-) delete mode 100644 masonry-layout-tests.ts diff --git a/masonry-layout-tests.ts b/masonry-layout-tests.ts deleted file mode 100644 index e83a898f54..0000000000 --- a/masonry-layout-tests.ts +++ /dev/null @@ -1,48 +0,0 @@ -// test file for masonry-layout.d.ts - -/// -/// - -//import {Masonry} from "./masonry-layout.d.ts"; - -// responsive layouts -function testResponsiveLayouts() { - $('.grid').masonry({ - itemSelector: '.grid-item', - columnWidth: '.grid-sizer', - percentPosition: true - }); -} - -// recommended Options -function testRecommendedOptions() { - $('.grid').masonry({ - columnWidth: 200, - itemSelector: '.grid-item' - }); - - var msnry = new Masonry.Masonry('.grid', { - columnWidth: 200, - itemSelector: '.grid-item' - }); -} - -// extended Options -function testExtendedOptions() { - var msnry = new Masonry.Masonry('.grid', { - itemSelector: '.grid-item', - columnWidth: '.grid-sizer', - percentPosition: true, - gutter: '.gutter-sizer', - stamp: '.stamp', - fitWidth: true, - originLeft: true, - originTop: true, - containerStyle: { - position: 'relative' - }, - transitionDuration: '0.4s', - resize: true, - initLayout: true - }); -} From 4a63acbbde3f494510e7bafea9d143a4f6caa907 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:44:05 -0400 Subject: [PATCH 0068/1255] Create masonry-layout-tests.ts --- masonry-layout/masonry-layout-tests.ts | 1 + 1 file changed, 1 insertion(+) create mode 100644 masonry-layout/masonry-layout-tests.ts diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/masonry-layout/masonry-layout-tests.ts @@ -0,0 +1 @@ + From 8c3dd98cd712050a5a50c232b074ba74758de453 Mon Sep 17 00:00:00 2001 From: m-a-wilson Date: Thu, 14 Jul 2016 09:44:37 -0400 Subject: [PATCH 0069/1255] Add files via upload --- masonry-layout/masonry-layout-tests.ts | 49 +++++++++++++++++- masonry-layout/masonry-layout.d.ts | 70 ++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 masonry-layout/masonry-layout.d.ts diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts index 8b13789179..e83a898f54 100644 --- a/masonry-layout/masonry-layout-tests.ts +++ b/masonry-layout/masonry-layout-tests.ts @@ -1 +1,48 @@ - +// test file for masonry-layout.d.ts + +/// +/// + +//import {Masonry} from "./masonry-layout.d.ts"; + +// responsive layouts +function testResponsiveLayouts() { + $('.grid').masonry({ + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true + }); +} + +// recommended Options +function testRecommendedOptions() { + $('.grid').masonry({ + columnWidth: 200, + itemSelector: '.grid-item' + }); + + var msnry = new Masonry.Masonry('.grid', { + columnWidth: 200, + itemSelector: '.grid-item' + }); +} + +// extended Options +function testExtendedOptions() { + var msnry = new Masonry.Masonry('.grid', { + itemSelector: '.grid-item', + columnWidth: '.grid-sizer', + percentPosition: true, + gutter: '.gutter-sizer', + stamp: '.stamp', + fitWidth: true, + originLeft: true, + originTop: true, + containerStyle: { + position: 'relative' + }, + transitionDuration: '0.4s', + resize: true, + initLayout: true + }); +} diff --git a/masonry-layout/masonry-layout.d.ts b/masonry-layout/masonry-layout.d.ts new file mode 100644 index 0000000000..0923a8f463 --- /dev/null +++ b/masonry-layout/masonry-layout.d.ts @@ -0,0 +1,70 @@ +// Type definitions for Masonry 4.0.0 +// Project: https://github.com/desandro/masonry +// Definitions by: Mark Wilson +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/// + +// Modified from original definitions by: +// Travis Brown < https://github.com/warriorrocker> + +declare module Masonry { + + class Masonry implements MasonryGrid { + constructor(options?: MasonryOptions); + constructor(selector: string, options?: MasonryOptions); + } + + interface MasonryGrid { + masonry?(): void; + masonry?(eventName: string, listener: any): void; + + // layout + layout?(): void; + layoutItems?(items: Array, isStill?: boolean): void; + stamp?(elements: Array): void; + unstamp?(elements: Array): void; + + // add and remove items + appended?(elements: Array): void; + prepended?(elements: Array): void; + addItems?(elements: Array): void; + remove?(elements: Array): void; + + // events + on?(eventName: string, listener: any): void; + off?(eventName: string, listener: any): void; + once?(eventName: string, listener: any): void; + + // utilities + reloadItems?(): void; + destroy?(): void; + getItemElements?(): Array; + data?(element: Element): Masonry; + } + + interface MasonryOptions { + + // layout + itemSelector?: string; + columnWidth?: any; + percentPosition?: boolean; + gutter?: any; + stamp?: string; + fitWidth?: boolean; + originLeft?: boolean; + originTop?: boolean; + + // setup + containerStyle?: Object; + transitionDuration?: any; + resize?: boolean; + initLayout?: boolean; + } +} + +interface JQuery { + masonry(options?: Masonry.MasonryOptions): JQuery; +} + + From e1b93de8678747cb9a67d5b3931db3cfb635d85a Mon Sep 17 00:00:00 2001 From: Gregory Moore Date: Thu, 14 Jul 2016 13:09:04 -0700 Subject: [PATCH 0070/1255] Add Query and QueryResponse definitions --- .../google.visualization.d.ts | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index 9ed800798c..d53061a5dc 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -1,6 +1,6 @@ // Type definitions for Google Visualisation Apis // Project: https://developers.google.com/chart/ -// Definitions by: Dan Ludwig +// Definitions by: Dan Ludwig , Gregory Moore // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace google { @@ -186,6 +186,42 @@ declare namespace google { function arrayToDataTable(data: any[], firstRowIsData?: boolean): DataTable; + //#endregion + //#region Query + + // https://developers.google.com/chart/interactive/docs/reference#query + export class Query { + constructor(dataSourceUrl: string, options?: QueryOptions); + + abort(): void; + + setRefreshInterval(intervalSeconds: number): void; + setTimeout(timeoutSeconds: number): void; + setQuery(queryString:string): void; + + send(responseHandler): void; + } + + export interface QueryOptions { + sendMethod?: string, + makeRequestParams?: Object + } + + //#endregion + //#region QueryResponse + + // https://developers.google.com/chart/interactive/docs/reference#queryresponse + export class QueryResponse { + constructor(responseObject: Object); + + getDataTable(): DataTable; + getDetailedMessage(): string; + getMessage(): string; + getReasons(): string[]; + hasWarning(): boolean; + isError(): boolean; + } + //#endregion //#region DataView From 06026495fbc5e6d6ad6917a80b6ac35d584be0fc Mon Sep 17 00:00:00 2001 From: Gregory Moore Date: Thu, 14 Jul 2016 13:40:02 -0700 Subject: [PATCH 0071/1255] Fix callback definition in Query send method --- google.visualization/google.visualization.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/google.visualization/google.visualization.d.ts b/google.visualization/google.visualization.d.ts index d53061a5dc..a2a4bf21aa 100644 --- a/google.visualization/google.visualization.d.ts +++ b/google.visualization/google.visualization.d.ts @@ -199,7 +199,7 @@ declare namespace google { setTimeout(timeoutSeconds: number): void; setQuery(queryString:string): void; - send(responseHandler): void; + send(callback: (response: QueryResponse) => void): void; } export interface QueryOptions { From c85a7d624b9d3250f402c47172971dee76686513 Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 14 Jul 2016 11:35:29 -0400 Subject: [PATCH 0072/1255] adds type parameter for mongoose.Model, fixes #10110 --- mongoose/mongoose-tests.ts | 46 ++++- mongoose/mongoose.d.ts | 351 +++++++++++++++++++------------------ 2 files changed, 223 insertions(+), 174 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index d2a36aeb54..6cd79f0719 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -167,7 +167,7 @@ mongoose.Error.Messages.hasOwnProperty(''); * section querycursor.js * http://mongoosejs.com/docs/api.html#querycursor-js */ -var querycursor: mongoose.QueryCursor; +var querycursor: mongoose.QueryCursor; querycursor.close(function (error, result) { result.execPopulate(); }).catch(cb); @@ -1211,4 +1211,46 @@ MongoModel.find({ select: 'name -_id', options: { limit: 5 } }) -.exec(); \ No newline at end of file +.exec(); +/* practical example */ +interface Location extends mongoose.Document { + name: string; + address: string; + rating: number; + facilities: string[]; + coords: number[]; + openingTimes: any[]; + reviews: any[]; +}; +const locationSchema = new mongoose.Schema({ + name: { type: String, required: true }, + address: String, + rating: { type: Number, "default": 0, min: 0, max: 5 }, + facilities: [String], + coords: { type: [Number], index: "2dsphere" }, + openingTimes: [mongoose.Schema.Types.Mixed], + reviews: [mongoose.SchemaTypes.Mixed] +}); +var LocModel = mongoose.model("Location", locationSchema); +LocModel.findById(999) + .select("-reviews -rating") + .exec(function (err, location) { + location.name = 'blah'; + location.address = 'blah'; + location.reviews.forEach(review => {}); + location.facilities.forEach(facility => { + facility.toLowerCase(); + }); + }); +LocModel.find() + .select('-reviews -rating') + .exec(function (err, locations) { + locations.forEach(location => { + location.name = 'blah'; + location.address = 'blah'; + location.reviews.forEach(review => {}); + location.facilities.forEach(facility => { + facility.toLowerCase(); + }); + }); + }); \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 01a149f001..6de1fddf44 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -132,7 +132,7 @@ declare module "mongoose" { static Document: typeof _mongoose.Document; static DocumentProvider: any; static Error: typeof _mongoose.Error; - static Model: _mongoose.ModelConstructor; + static Model: _mongoose.ModelConstructor<{}>; static Mongoose: { // recursive constructor new(...args: any[]): typeof mongoose; @@ -153,7 +153,7 @@ declare module "mongoose" { */ static Promise: typeof _mongoose.Promise | any; static PromiseProvider: any; - static Query: typeof _mongoose.Query; + static Query: typeof _mongoose.ModelQuery; static Schema: typeof _mongoose.Schema; static SchemaType: typeof _mongoose.SchemaType; static SchemaTypes: typeof _mongoose.Schema.Types; @@ -228,8 +228,8 @@ declare module "mongoose" { * @param collection (optional, induced from model name) * @param skipInit whether to skip initialization (defaults to false) */ - static model(name: string, schema?: _mongoose.Schema, collection?: string, - skipInit?: boolean): _mongoose.ModelConstructor; + static model(name: string, schema?: _mongoose.Schema, collection?: string, + skipInit?: boolean): _mongoose.ModelConstructor; /** * Returns an array of model names created on this instance of Mongoose. @@ -258,12 +258,12 @@ declare module "mongoose" { interface Document extends _mongoose.Document {} interface Error extends _mongoose.Error {} interface ValidationError extends _mongoose.ValidationError {} - type model = _mongoose.Model; - type Model = _mongoose.ModelConstructor; // compatibilty with rest-io.d.ts + type model = _mongoose.Model; + type Model = _mongoose.ModelConstructor; type Mongoose = typeof mongoose; interface Promise extends _mongoose.Promise {} interface Query extends _mongoose.Query {} - interface QueryCursor extends _mongoose.QueryCursor {} + interface QueryCursor extends _mongoose.QueryCursor {} interface QueryStream extends _mongoose.QueryStream {} interface Schema extends _mongoose.Schema {} namespace Schema { @@ -447,7 +447,7 @@ declare module "mongoose" { * @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): ModelConstructor; /** Returns an array of model names created on this connection. */ modelNames(): string[]; @@ -580,7 +580,7 @@ declare module "mongoose" { * QueryCursor can only be accessed by query#cursor(), we only * expose its interface to enable type-checking. */ - interface QueryCursor extends stream.Readable { + 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, @@ -594,7 +594,7 @@ declare module "mongoose" { * @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; + constructor(query: Query, options: Object): QueryCursor; /** Marks this cursor as closed. Will stop streaming and subsequent calls to next() will error. */ close(callback?: (error: mongodb.MongoError, result: any) => void): Promise; @@ -605,7 +605,7 @@ declare module "mongoose" { * 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): Promise; + eachAsync(fn: (doc: Model) => any, callback?: (err: any) => void): Promise, any>; /** * Get the next document from this cursor. Will return null when there are @@ -708,8 +708,8 @@ declare module "mongoose" { * @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, + post(method: string, fn: (doc: Model) => void, ...args: any[]): this; + post(method: string, fn: (doc: Model, next: (err?: NativeError) => void, ...otherArgs: any[]) => void): this; /** @@ -1023,7 +1023,7 @@ declare module "mongoose" { * @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; + 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) */ @@ -1261,7 +1261,8 @@ declare module "mongoose" { * section query.js * http://mongoosejs.com/docs/api.html#query-js */ - class Query extends mquery { + type Query = ModelQuery; + 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 @@ -1294,7 +1295,7 @@ declare module "mongoose" { 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 | Model | ModelConstructor, obj?: Object): Object; + cast(model: Model | ModelConstructor, obj?: Object): Object; /** * Executes the query returning a Promise which will be @@ -1336,7 +1337,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; @@ -1366,8 +1367,9 @@ declare module "mongoose" { * query is executed, the result will be an array of documents. * @param criteria mongodb selector */ - find(callback?: (err: any, res: Model[]) => void): Query; - find(criteria: Object, callback?: (err: any, res: Model[]) => void): Query; + 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 @@ -1376,30 +1378,33 @@ declare module "mongoose" { * @param criteria mongodb selector * @param projection optional fields to return */ - findOne(callback?: (err: any, res: Model) => void): Query; - findOne(criteria: Object, callback?: (err: any, res: Model) => void): Query; + 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): Query; - findOneAndRemove(conditions: Object, callback?: (error: any, doc: Model, result: any) => void): Query; + 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): Query; + 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): Query; - findOneAndUpdate(update: Object, callback?: (err: any, doc: Model) => void): Query; + 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): Query; + callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; findOneAndUpdate(query: Object | Query, update: Object, options: QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: Model) => void): Query; + callback?: (err: any, doc: Model) => void): ModelQuery, ModelType>; /** * Specifies a $geometry condition. geometry() must come after either intersects() or within(). @@ -1551,7 +1556,7 @@ declare module "mongoose" { * @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, + populate(path: string | Object, select?: string | Object, model?: string | Model, match?: Object, options?: Object): this; populate(options: ModelPopulateOptions): this; @@ -1647,7 +1652,7 @@ declare module "mongoose" { * Converts this query to a customized, reusable query * constructor with all arguments and options retained. */ - toConstructor(): typeof Query; + toConstructor(): typeof ModelQuery; /** * Declare and/or execute this query as an update() operation. @@ -2017,7 +2022,7 @@ declare module "mongoose" { * Binds this aggregate to a model. * @param model the model to which the aggregate is to be bound */ - model(model: _Model | Model): this; + model(model: Model): this; /** * Appends a new $geoNear operator to this aggregate pipeline. @@ -2245,12 +2250,10 @@ declare module "mongoose" { * they actual return an instance of the Model constructor (think of it * like a new class) which can then instantiate its own objects. */ - type ModelConstructor = IModel & typeof _Model & events.EventEmitter; - type Model = _Model & events.EventEmitter; + type ModelConstructor = IModelConstructor & events.EventEmitter; + type Model = T & _Model & events.EventEmitter; - // we must use an interface with a custom new function to create - // the Model type above - interface IModel { + interface IModelConstructor { /** * Model constructor * Provides the interface to MongoDB collections as well as creates document instances. @@ -2267,92 +2270,7 @@ declare module "mongoose" { * 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; - } - - class _Model extends Document { - /** Signal that we desire an increment of this documents version. */ - increment(): this; - - /** - * Returns another Model instance. - * @param name model name - */ - model(name: string): ModelConstructor; - static model(name: string): ModelConstructor; - - /** - * Removes this document from the db. - * @param fn optional callback - */ - remove(fn?: (err: any, product: Model) => void): Promise; - - /** - * 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): Promise; - - /** - * Creates a Query and specifies a $where condition. - * @param argument is a javascript string or anonymous function - */ - static $where(argument: string | Function): Query; - - /** - * 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 - */ - static aggregate(...aggregations: Object[]): Aggregate; - static aggregate(...aggregationsWithCallback: Object[]): Promise; - - /** Counts number of matching documents in a database collection. */ - static 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. - */ - static create(docs: any[], callback?: (err: any, res: Model[]) => void): Promise; - static create(...docs: Object[]): Promise; - static create(...docsWithCallback: Object[]): Promise; - - /** - * Adds a discriminator type. - * @param name discriminator model name - * @param schema discriminator model schema - */ - static discriminator(name: string, schema: Schema): Model; - - /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ - static distinct(field: string, callback?: (err: any, res: any[]) => void): Query; - static 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 - */ - static ensureIndexes(callback?: (err: any) => void): Promise; - static ensureIndexes(options: Object, callback?: (err: any) => void): Promise; - - /** - * Finds documents. - * @param projection optional fields to return - */ - static find(callback?: (err: any, res: Model[]) => void): Query; - static find(conditions: Object, callback?: (err: any, res: Model[]) => void): Query; - static find(conditions: Object, projection: Object, - callback?: (err: any, res: Model[]) => void): Query; - static find(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: Model[]) => void): Query; + new(doc?: Object): Model; /** * Finds a single document by its _id field. findById(id) is almost* @@ -2360,12 +2278,74 @@ declare module "mongoose" { * @param id value of _id to query by * @param projection optional fields to return */ - static findById(id: Object | string | number, - callback?: (err: any, res: Model) => void): Query; - static findById(id: Object | string | number, projection: Object, - callback?: (err: any, res: Model) => void): Query; - static findById(id: Object | string | number, projection: Object, options: Object, - callback?: (err: any, res: Model) => void): Query; + 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>; + + model(name: string): ModelConstructor; + + /** + * Creates a Query and specifies a $where condition. + * @param argument is a javascript string or anonymous function + */ + $where(argument: string | Function): ModelQuery[], T>; + + /** + * 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[]): Promise; + + /** 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: Model[]) => void): Promise[], any>; + create(...docs: Object[]): Promise, any>; + create(...docsWithCallback: Object[]): Promise, any>; + + /** + * Adds a discriminator type. + * @param name discriminator model name + * @param schema discriminator model schema + */ + discriminator(name: string, schema: Schema): Model; + + /** 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): Promise; + ensureIndexes(options: Object, callback?: (err: any) => void): Promise; + + /** + * 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>; + + /** * Issue a mongodb findAndModify remove command by a document's _id field. @@ -2374,48 +2354,49 @@ declare module "mongoose" { * Executes immediately if callback is passed, else a Query object is returned. * @param id value of _id to query by */ - static findByIdAndRemove(): Query; - static findByIdAndRemove(id: Object | number | string, callback?: (err: any, res: Model) => void): Query; - static findByIdAndRemove(id: Object | number | string, options: { + 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): Query; + }, callback?: (err: any, res: Model) => void): ModelQuery, T>; /** * 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 */ - static findByIdAndUpdate(): Query; - static findByIdAndUpdate(id: Object | number | string, update: Object, - callback?: (err: any, res: Model) => void): Query; - static findByIdAndUpdate(id: Object | number | string, update: Object, + 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): Query; + callback?: (err: any, res: Model) => void): ModelQuery, T>; /** * Finds one document. * The conditions are cast to their respective SchemaTypes before the command is sent. * @param projection optional fields to return */ - static findOne(conditions?: Object, - callback?: (err: any, res: Model) => void): Query; - static findOne(conditions: Object, projection: Object, - callback?: (err: any, res: Model) => void): Query; - static findOne(conditions: Object, projection: Object, options: Object, - callback?: (err: any, res: Model) => void): Query; + 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>; /** * 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. */ - static findOneAndRemove(): Query; - static findOneAndRemove(conditions: Object, - callback?: (err: any, res: Model) => void): Query; - static findOneAndRemove(conditions: Object, options: { + 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 @@ -2425,7 +2406,7 @@ declare module "mongoose" { maxTimeMS?: number; /** sets the document fields to return */ select?: Object; - }, callback?: (err: any, res: Model) => void): Query; + }, callback?: (err: any, res: Model) => void): ModelQuery, T>; /** * Issues a mongodb findAndModify update command. @@ -2433,12 +2414,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. */ - static findOneAndUpdate(): Query; - static findOneAndUpdate(conditions: Object, update: Object, - callback?: (err: any, res: Model) => void): Query; - static findOneAndUpdate(conditions: Object, update: Object, + 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): Query; + callback?: (err: any, res: Model) => void): ModelQuery, T>; /** * geoNear support for Mongoose @@ -2446,14 +2427,14 @@ declare module "mongoose" { * @param options for the qurery * @param callback optional callback for the query */ - static geoNear(point: number[] | { + 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): Query; + }, callback?: (err: any, res: Model[], stats: any) => void): ModelQuery[], T>; /** * Implements $geoSearch functionality for Mongoose @@ -2461,7 +2442,7 @@ declare module "mongoose" { * @param options for the geoSearch, some (near, maxDistance) are required * @param callback optional callback */ - static geoSearch(conditions: Object, options: { + geoSearch(conditions: Object, options: { /** x,y point to search for */ near: number[]; /** the maximum distance from the point near that a result can be */ @@ -2470,14 +2451,14 @@ declare module "mongoose" { limit?: number; /** return the raw object instead of the Mongoose Model */ lean?: boolean; - }, callback?: (err: any, res: Model[]) => void): Query; + }, callback?: (err: any, res: Model[]) => void): ModelQuery[], T>; /** * 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. */ - static hydrate(obj: Object): Model; + hydrate(obj: Object): Model; /** * Shortcut for validating an array of documents and inserting them into @@ -2486,17 +2467,17 @@ declare module "mongoose" { * document. * This function does not trigger save middleware. */ - static insertMany(docs: any[], callback?: (error: any, docs: Model[]) => void): Promise; - static insertMany(doc: any, callback?: (error: any, doc: Model) => void): Promise; - static insertMany(...docsWithCallback: Object[]): Promise; + insertMany(docs: any[], callback?: (error: any, docs: Model[]) => void): Promise[], any>; + insertMany(doc: any, callback?: (error: any, doc: Model) => void): Promise, any>; + insertMany(...docsWithCallback: Object[]): Promise, any>; /** * Executes a mapReduce command. * @param o an object specifying map-reduce options * @param callbackoptional callback */ - static mapReduce( - o: ModelMapReduceOption, + mapReduce( + o: ModelMapReduceOption, Key, Value>, callback?: (err: any, res: any) => void ): Promise; @@ -2506,25 +2487,51 @@ declare module "mongoose" { * @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). */ - static populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: Model[]) => void): Promise; - static populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: Model) => void): Promise; + populate(docs: Object[], options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: Model[]) => void): Promise[], any>; + populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], + callback?: (err: any, res: Model) => void): Promise, any>; /** Removes documents from the collection. */ - static remove(conditions: Object, callback?: (err: any) => void): Query; + 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. */ - static update(conditions: Object, doc: Object, + update(conditions: Object, doc: Object, callback?: (err: any, raw: any) => void): Query; - static update(conditions: Object, doc: Object, options: ModelUpdateOptions, + 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. */ - static where(path: string, val?: Object): Query; + where(path: string, val?: Object): Query; + } + + class _Model extends Document { + /** Signal that we desire an increment of this documents version. */ + increment(): this; + + /** + * Returns another Model instance. + * @param name model name + */ + model(name: string): ModelConstructor; + + /** + * Removes this document from the db. + * @param fn optional callback + */ + remove(fn?: (err: any, product: Model) => void): Promise, any>; + + /** + * 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): Promise, any>; /** Base Mongoose instance the model uses. */ base: typeof mongoose; @@ -2615,7 +2622,7 @@ declare module "mongoose" { [other: string]: any; } - interface ModelMapReduceOption { + interface ModelMapReduceOption { map: Function | string; reduce: (key: Key, vals: T[]) => Val; /** query filter object. */ From 1f09db13e7f42d2ab5f398bcb2c8a223f0daf22d Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 14 Jul 2016 11:49:59 -0400 Subject: [PATCH 0073/1255] adds comments explaining ModelQuery --- mongoose/mongoose.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 6de1fddf44..8d0fe35a89 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -1262,6 +1262,11 @@ declare module "mongoose" { * http://mongoosejs.com/docs/api.html#query-js */ 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. From ae5432ee12d1bf626eb9671a2711da7188864c04 Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 14 Jul 2016 20:23:21 -0400 Subject: [PATCH 0074/1255] adds test cases for model type parameters --- mongoose/mongoose-tests.ts | 35 ++++++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 6cd79f0719..e5c9687c84 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1253,4 +1253,37 @@ LocModel.find() facility.toLowerCase(); }); }); - }); \ No newline at end of file + }); +LocModel.$where('') + .exec(function (err, locations) { + locations[0].name; + locations[1].openingTimes; + }); +LocModel.count({}) + .exec(function (err, count) { + count.toFixed(); + }); +LocModel.distinct('') + .select('-review') + .exec(function (err, distinct) { + distinct.concat; + }) + .then(cb).catch(cb); +LocModel.findByIdAndRemove() + .exec(function (err, doc) { + doc.addListener; + doc.openingTimes; + }); +LocModel.findByIdAndUpdate() + .select({}) + .exec(function (err, location) { + location.reviews; + }); +LocModel.findOne({}, function (err, doc) { doc.openingTimes; }); +LocModel.findOneAndRemove() + .exec(function (err, location) { location.name; }); +LocModel.findOneAndUpdate().exec().then(function (arg) { arg.openingTimes; }); +LocModel.geoSearch({}, { + near: [1, 2], + maxDistance: 22 +}, function (err, res) { res[0].openingTimes; }); \ No newline at end of file From d8af314e45cdd0d1cc622e09cb77bcef0a1a7fa2 Mon Sep 17 00:00:00 2001 From: Simon Date: Thu, 14 Jul 2016 22:59:54 -0400 Subject: [PATCH 0075/1255] fixes return types of MongooseArray --- 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 8d0fe35a89..5ed2963874 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -1067,7 +1067,7 @@ declare module "mongoose" { $shift(): T; /** Alias of pull */ - remove(...args: any[]): Array; + remove(...args: any[]): this; /** * Pops the array atomically at most one time per document save(). @@ -1113,7 +1113,7 @@ declare module "mongoose" { * the provided value to an embedded document and comparing using * the Document.equals() function. */ - pull(...args: any[]): Array; + pull(...args: any[]): this; /** * Wraps Array#push with proper change tracking. @@ -1122,7 +1122,7 @@ declare module "mongoose" { push(...args: any[]): number; /** Sets the casted val at index i and marks the array modified. */ - set(i: number, val: any): Array; + set(i: number, val: any): this; /** * Wraps Array#shift with proper change tracking. From 7ba164ada39d6f7b6bee21b444c9f31d421f71b4 Mon Sep 17 00:00:00 2001 From: Simon Date: Fri, 15 Jul 2016 21:40:32 -0400 Subject: [PATCH 0076/1255] fixes return types of mongoose promises --- mongoose/mongoose-tests.ts | 51 +++++++++++++++++++++++++++----------- mongoose/mongoose.d.ts | 16 ++++++------ 2 files changed, 45 insertions(+), 22 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index e5c9687c84..ff57a0afdd 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1,8 +1,8 @@ /// -/// +/// -import * as bluebird from 'bluebird'; import * as mongoose from 'mongoose'; +import * as core from 'core-js'; var fs = require('fs'); // dummy variables @@ -988,26 +988,47 @@ mongopromise.complete(new mongoose.SchemaType('')).complete( new mongoose.SchemaType('') ); /* static properties */ -mongoose.Promise.ES6(function (complete: any, error: any) { +mongoose.Promise.ES6(function (complete: Function, error: Function) { complete.apply(this); error.apply(this); -}).end(); +}); + /* inherited properties */ mongopromise.chain(mongopromise); mongoose.Promise.FAILURE; +/* practical example */ +mongoose.model('') + .findOne({}) + .exec() + .then(function (arg) { + arg.save; + return 1; + }).then(function (num) { + num.toFixed; + return new Promise((resolve, reject) => { + resolve('string'); + }); + }).then(function (str) { + str.toLowerCase + return (mongoose.model('')).findOne({}).exec(); + }).then(function (arg) { + arg.save; + }).catch(function (err) { + return 1; + }).then(function (arg) { + arg.toFixed; + return new Promise<{a: string, b: number}>((resolve, reject) => { + resolve({a: 'hi', b: 29}); + }); + }).then(function (arg) { + arg.a.toLowerCase; + arg.b.toFixed; + }); /* pluggable promise */ -mongoose.Promise = global.Promise; -var nativePromise: Promise = new mongoose.Promise(); -nativePromise.race().then(cb).catch(cb); - -mongoose.Promise = bluebird; -var bluebirdPromise: bluebird = new mongoose.Promise(); -bluebirdPromise.cancellable().lastly(cb); - -var PQuery: any; -PQuery.find().exec()['reduce']().then(cb).catch(cb); -(PQuery).find().exec().reduce().then(cb).catch(cb); +mongoose.Promise = core.Promise; +mongoose.Promise.race; +mongoose.Promise.all; /* * section model.js diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 5ed2963874..ccd4a5d134 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2182,7 +2182,7 @@ declare module "mongoose" { addErrback(listener: (err: R) => void): this; /** ES6-style .catch() shorthand */ - catch(onReject?: (err: R) => void): Promise; + catch(onReject?: (err: R) => void | TRes | Promise | PromiseLike): Promise; /** * Signifies that this promise was the last in a chain of then()s: if a handler passed @@ -2225,8 +2225,10 @@ declare module "mongoose" { * SUCCESS/ERROR callbacks to this promise after the nextTick. * Conforms to promises/A+ specification. */ - then(onFulFill: (arg: F) => void, onReject?: (err: R) => void): Promise; - then(onFulfill: (...args: F[]) => void, onReject?: (err: R) => void): Promise; + then(onFulFill: (arg: F) => void | TRes | Promise | PromiseLike, + onReject?: (err: R) => void | TRes | Promise | PromiseLike): Promise; + then(onFulfill: (...args: F[]) => void | TRes | Promise | PromiseLike, + onReject?: (err: R) => void | TRes | Promise | PromiseLike): Promise; /** * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. @@ -2240,10 +2242,10 @@ declare module "mongoose" { fulfill(arg: F): this; /** ES6-style promise constructor wrapper around mpromise. */ - static ES6(resolver: ( - complete: (...args: F[]) => void, - error: (e: R) => void - ) => void): Promise; + static ES6(resolver: ( + complete: (...args: TRes[]) => void | TRes | Promise | PromiseLike, + error: (e: TErr) => void | TRes | Promise | PromiseLike + ) => void): Promise; } /* From 7e4710a23ce3779826c4d26d1cf637851924a299 Mon Sep 17 00:00:00 2001 From: Simon Date: Fri, 15 Jul 2016 21:46:38 -0400 Subject: [PATCH 0077/1255] simplifies mongoose.Promise by removing unecessary 2nd type parameter --- mongoose/mongoose-tests.ts | 5 +- mongoose/mongoose.d.ts | 102 ++++++++++++++++++------------------- 2 files changed, 53 insertions(+), 54 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index ff57a0afdd..607058093c 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1,8 +1,7 @@ /// -/// +/// import * as mongoose from 'mongoose'; -import * as core from 'core-js'; var fs = require('fs'); // dummy variables @@ -1026,7 +1025,7 @@ mongoose.model('') }); /* pluggable promise */ -mongoose.Promise = core.Promise; +mongoose.Promise = Promise; mongoose.Promise.race; mongoose.Promise.all; diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index ccd4a5d134..71cb91bf8c 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -261,7 +261,7 @@ declare module "mongoose" { type model = _mongoose.Model; type Model = _mongoose.ModelConstructor; type Mongoose = typeof mongoose; - interface Promise extends _mongoose.Promise {} + interface Promise extends _mongoose.Promise {} interface Query extends _mongoose.Query {} interface QueryCursor extends _mongoose.QueryCursor {} interface QueryStream extends _mongoose.QueryStream {} @@ -426,7 +426,7 @@ declare module "mongoose" { callback?: (err: any) => void): any; /** Closes the connection */ - close(callback?: (err: any) => void): Promise; + close(callback?: (err: any) => void): Promise; /** * Retrieves a collection, creating it if not cached. @@ -597,7 +597,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: mongodb.MongoError, result: any) => void): Promise; + close(callback?: (error: any, result: any) => void): Promise; /** * Execute fn for every document in the cursor. If fn returns a promise, @@ -605,13 +605,13 @@ declare module "mongoose" { * 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): Promise, any>; + eachAsync(fn: (doc: Model) => 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): Promise; + next(callback?: (err: any) => void): Promise; } /* @@ -868,7 +868,7 @@ declare module "mongoose" { * Useful for ES2015 integration. * @returns promise that resolves to the document when population is done */ - execPopulate(): Promise; + execPopulate(): Promise; /** * Returns the value of a path. @@ -987,8 +987,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): Promise; - validate(optional: Object, callback?: (err: any) => void): Promise; + validate(callback?: (err: any) => void): Promise; + validate(optional: Object, callback?: (err: any) => void): Promise; /** * Executes registered validation rules (skipping asynchronous validators) for this document. @@ -1307,7 +1307,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): Promise; + catch(reject?: (err: any) => void): Promise; /** * DEPRECATED Alias for circle @@ -1360,8 +1360,8 @@ declare module "mongoose" { equals(val: Object): this; /** Executes the query */ - exec(callback?: (err: any, res: T) => void): Promise; - exec(operation: string | Function, callback?: (err: any, res: T) => void): Promise; + 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; @@ -1651,7 +1651,7 @@ declare module "mongoose" { }): this; /** Executes this query and returns a promise */ - then(resolve?: (res: T) => void, reject?: (err: any) => void): Promise; + then(resolve?: (res: T) => void, reject?: (err: any) => void): Promise; /** * Converts this query to a customized, reusable query @@ -1994,10 +1994,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): Promise | any; + exec(callback?: (err: any, result: T) => void): Promise | any; /** Execute the aggregation with explain */ - explain(callback?: (err: any, result: T) => void): Promise; + explain(callback?: (err: any, result: T) => void): Promise; /** * Appends a new custom $group operator to this aggregate pipeline. @@ -2071,7 +2071,7 @@ declare module "mongoose" { sort(arg: string | Object): this; /** Provides promise for aggregate. */ - then(resolve?: (val: T) => void, reject?: (err: any) => void): Promise + then(resolve?: (val: T) => void, reject?: (err: any) => void): Promise /** * Appends new custom $unwind operator(s) to this aggregate pipeline. @@ -2145,7 +2145,7 @@ declare module "mongoose" { * * Callback signatures are from the mPromise type definitions */ - class Promise extends mPromise { + class Promise extends mPromise { /** * Promise constructor. * Promises are returned from executed queries. @@ -2157,32 +2157,32 @@ declare module "mongoose" { * 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: R, arg: F) => void); - constructor(fn?: (err: R, ...args: F[]) => void); + 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: R, arg: F) => void): this; - addBack(listener: (err: R, ...args: F[]) => void): this; + 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: F) => void): this; - addCallback(listener: (...args: F[]) => void): this; + 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: R) => void): this; + addErrback(listener: (err: any) => void): this; /** ES6-style .catch() shorthand */ - catch(onReject?: (err: R) => void | TRes | Promise | PromiseLike): Promise; + catch(onReject?: (err: any) => void | TRes | PromiseLike): Promise; /** * Signifies that this promise was the last in a chain of then()s: if a handler passed @@ -2218,34 +2218,34 @@ declare module "mongoose" { * @param err error or null * @param val value to fulfill the promise with */ - resolve(err?: R, val?: Object): this; + 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: F) => void | TRes | Promise | PromiseLike, - onReject?: (err: R) => void | TRes | Promise | PromiseLike): Promise; - then(onFulfill: (...args: F[]) => void | TRes | Promise | PromiseLike, - onReject?: (err: R) => void | TRes | Promise | PromiseLike): Promise; + then(onFulFill: (arg: T) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): Promise; + then(onFulfill: (...args: T[]) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): Promise; /** * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. * @deprecated Use fulfill instead. */ - complete(args: F): this; - complete(...args: F[]): this; + complete(args: T): this; + complete(...args: T[]): this; /** Fulfills this promise with passed arguments. */ - fulfill(...args: F[]): this; - fulfill(arg: F): this; + fulfill(...args: T[]): this; + fulfill(arg: T): this; /** ES6-style promise constructor wrapper around mpromise. */ - static ES6(resolver: ( - complete: (...args: TRes[]) => void | TRes | Promise | PromiseLike, - error: (e: TErr) => void | TRes | Promise | PromiseLike - ) => void): Promise; + static ES6(resolver: ( + complete: (...args: TRes[]) => void | TRes | PromiseLike, + error: (e: any) => void | TRes | PromiseLike + ) => void): Promise; } /* @@ -2307,7 +2307,7 @@ declare module "mongoose" { * @param ... aggregation pipeline operator(s) or operator array */ aggregate(...aggregations: Object[]): Aggregate; - aggregate(...aggregationsWithCallback: Object[]): Promise; + aggregate(...aggregationsWithCallback: Object[]): Promise; /** Counts number of matching documents in a database collection. */ count(conditions: Object, callback?: (err: any, count: number) => void): Query; @@ -2317,9 +2317,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: Model[]) => void): Promise[], any>; - create(...docs: Object[]): Promise, any>; - create(...docsWithCallback: Object[]): Promise, any>; + create(docs: any[], callback?: (err: any, res: Model[]) => void): Promise[]>; + create(...docs: Object[]): Promise>; + create(...docsWithCallback: Object[]): Promise>; /** * Adds a discriminator type. @@ -2338,8 +2338,8 @@ declare module "mongoose" { * @param options internal options * @param cb optional callback */ - ensureIndexes(callback?: (err: any) => void): Promise; - ensureIndexes(options: Object, callback?: (err: any) => void): Promise; + ensureIndexes(callback?: (err: any) => void): Promise; + ensureIndexes(options: Object, callback?: (err: any) => void): Promise; /** * Finds documents. @@ -2474,9 +2474,9 @@ declare module "mongoose" { * document. * This function does not trigger save middleware. */ - insertMany(docs: any[], callback?: (error: any, docs: Model[]) => void): Promise[], any>; - insertMany(doc: any, callback?: (error: any, doc: Model) => void): Promise, any>; - insertMany(...docsWithCallback: Object[]): Promise, any>; + insertMany(docs: any[], callback?: (error: any, docs: Model[]) => void): Promise[]>; + insertMany(doc: any, callback?: (error: any, doc: Model) => void): Promise>; + insertMany(...docsWithCallback: Object[]): Promise>; /** * Executes a mapReduce command. @@ -2486,7 +2486,7 @@ declare module "mongoose" { mapReduce( o: ModelMapReduceOption, Key, Value>, callback?: (err: any, res: any) => void - ): Promise; + ): Promise; /** * Populates document references. @@ -2495,9 +2495,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: Model[]) => void): Promise[], any>; + callback?: (err: any, res: Model[]) => void): Promise[]>; populate(docs: Object, options: ModelPopulateOptions | ModelPopulateOptions[], - callback?: (err: any, res: Model) => void): Promise, any>; + callback?: (err: any, res: Model) => void): Promise>; /** Removes documents from the collection. */ remove(conditions: Object, callback?: (err: any) => void): Query; @@ -2529,7 +2529,7 @@ declare module "mongoose" { * Removes this document from the db. * @param fn optional callback */ - remove(fn?: (err: any, product: Model) => void): Promise, any>; + remove(fn?: (err: any, product: Model) => void): Promise>; /** * Saves this document. @@ -2538,7 +2538,7 @@ declare module "mongoose" { * @param options.validateBeforeSave set to false to save without validating. * @param fn optional callback */ - save(fn?: (err: any, product: Model, numAffected: number) => void): Promise, any>; + save(fn?: (err: any, product: Model, numAffected: number) => void): Promise>; /** Base Mongoose instance the model uses. */ base: typeof mongoose; From 8c8643c90bcbb5f2347e1935ce34f4abe02d14e3 Mon Sep 17 00:00:00 2001 From: Alan Wright Date: Sat, 16 Jul 2016 12:03:05 -0700 Subject: [PATCH 0078/1255] Adding support for JQueryUI Select Menu jQuery UI 1.11 selectmenu http://jqueryui.com/selectmenu/ --- jqueryui/jqueryui-tests.ts | 53 ++++++++++++++++++++++++++++++++++++++ jqueryui/jqueryui.d.ts | 46 +++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) diff --git a/jqueryui/jqueryui-tests.ts b/jqueryui/jqueryui-tests.ts index 607a5bd1dd..042d822332 100644 --- a/jqueryui/jqueryui-tests.ts +++ b/jqueryui/jqueryui-tests.ts @@ -1475,6 +1475,59 @@ function test_menu() { $(".selector").menu({ select: (e, ui) => { } }); } +function test_selectmenu() { + // Options + $("#selectmenu").selectmenu(); + $(".selector").selectmenu({ appendTo: ".selector" }); + $(".selector").selectmenu({ disabled: true }); + $(".selector").selectmenu({ icons: { submenu: "ui-icon-circle-triangle-e" } }); + $(".selector").selectmenu({ position: { my: "left top", at: "right-5 top+5" } }); + $(".selector").selectmenu({ width: 47 }); + + // Events + $("#selectmenu").selectmenu({ change: (event, ui) => {}}); + $("#selectmenu").selectmenu({ close: (event, ui) => {}}); + $("#selectmenu").selectmenu({ create: (event, ui) => {}}); + $("#selectmenu").selectmenu({ focus: (event, ui) => {}}); + $("#selectmenu").selectmenu({ open: (event, ui) => {}}); + $("#selectmenu").selectmenu({ select: (event, ui) => {}}); + + // Events and options + $("#selectmenu").selectmenu({ + appendTo: ".selector", + disabled: true, + icons: { submenu: "ui-icon-circle-triangle-e" }, + position: { my: "left top", at: "right-5 top+5" }, + width: 47, + change: (event, ui) => {}, + close: (event, ui) => {}, + create: (event, ui) => {}, + focus: (event, ui) => {}, + open: (event, ui) => {}, + select: (event, ui) => {} + }); + + // passing in option + $(".selector").selectmenu("option", { disabled: true }); + + // Fetching option value + var disabled = $(".selector").selectmenu("option", "disabled"); + + // Setting option value + $(".selector").selectmenu("option", "disabled", true); + $(".selector").selectmenu("option", "position", { my: "left top", at: "right-5 top+5" } ); + + // Methods + $(".selector").selectmenu("close"); + $(".selector").selectmenu("destroy"); + + // Chaining + $("#number") + .selectmenu() + .selectmenu("menuWidget") + .addClass("overflow"); +} + function test_progressbar() { $("#progressbar").progressbar({ diff --git a/jqueryui/jqueryui.d.ts b/jqueryui/jqueryui.d.ts index 724e32e5cb..d508eba8a9 100644 --- a/jqueryui/jqueryui.d.ts +++ b/jqueryui/jqueryui.d.ts @@ -625,6 +625,36 @@ declare namespace JQueryUI { interface Selectable extends Widget, SelectableOptions { } + + // SelectMenu ////////////////////////////////////////////////// + + interface SelectMenuOptions extends SelectMenuEvents { + appendTo?: string; + disabled?: boolean; + icons?: any; + position?: JQueryPositionOptions; + width?: number; + } + + interface SelectMenuUIParams { + item?: JQuery; + } + + interface SelectMenuEvent { + (event: Event, ui: SelectMenuUIParams): void; + } + + interface SelectMenuEvents { + change?: SelectMenuEvent; + close?: SelectMenuEvent; + create?: SelectMenuEvent; + focus?: SelectMenuEvent; + open?: SelectMenuEvent; + select?: SelectMenuEvent; + } + + interface SelectMenu extends Widget, SelectMenuOptions { + } // Slider ////////////////////////////////////////////////// @@ -1675,6 +1705,22 @@ interface JQuery { selectable(optionLiteral: string, optionName: string): any; selectable(optionLiteral: string, options: JQueryUI.SelectableOptions): any; selectable(optionLiteral: string, optionName: string, optionValue: any): JQuery; + + selectmenu(): JQuery; + selectmenu(methodName: 'close'): JQuery; + selectmenu(methodName: 'destroy'): JQuery; + selectmenu(methodName: 'disable'): JQuery; + selectmenu(methodName: 'enable'): JQuery; + selectmenu(methodName: 'instance'): any; + selectmenu(methodName: 'menuWidget'): JQuery; + selectmenu(methodName: 'open'): JQuery; + selectmenu(methodName: 'refresh'): JQuery; + selectmenu(methodName: 'widget'): JQuery; + selectmenu(methodName: string): JQuery; + selectmenu(options: JQueryUI.SelectMenuOptions): JQuery; + selectmenu(optionLiteral: string, optionName: string): any; + selectmenu(optionLiteral: string, options: JQueryUI.SelectMenuOptions): any; + selectmenu(optionLiteral: string, optionName: string, optionValue: any): JQuery; slider(): JQuery; slider(methodName: 'destroy'): void; From 65836b3ed7e704d57005cdd5e12b5e6e09afede5 Mon Sep 17 00:00:00 2001 From: ersimont Date: Sat, 16 Jul 2016 22:06:03 -0400 Subject: [PATCH 0079/1255] Update rosie.d.ts --- rosie/rosie.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/rosie/rosie.d.ts b/rosie/rosie.d.ts index a92359c3d9..f7f679ebb2 100644 --- a/rosie/rosie.d.ts +++ b/rosie/rosie.d.ts @@ -134,11 +134,11 @@ declare namespace rosie { * Factory.define('Person').sequence('id'); * * @param {string} attr - * @param {Array.=} dependencies + * @param {Array.=} | Function dependencies or builder * @param {function(number): *=} builder * @return {Factory} */ - sequence(name: string, dependencies?: string[], builder?: Function) : IFactory; + sequence(name: string, dependenciesOrBuilder?: Function | string[], builder?: Function) : IFactory; /** * Sets a post-processor callback that will receive built objects and the From 1b755999edaef40d884b959ca2e76f97305c7bda Mon Sep 17 00:00:00 2001 From: Simon Date: Sat, 16 Jul 2016 22:28:34 -0400 Subject: [PATCH 0080/1255] fixes return types of some promises that were missed --- mongoose/mongoose-tests.ts | 25 +++++++++++++++++++++++++ mongoose/mongoose.d.ts | 8 +++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 607058093c..dc8f795672 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1024,6 +1024,31 @@ mongoose.model('') arg.b.toFixed; }); +mongoose.model('').findOne({}) + .then(function (arg) { + arg.save; + return 2; + }).then(function (num) { + num.toFixed; + return new Promise((resolve, reject) => { + resolve('str'); + }); + }).then(function (str) { + str.toLowerCase; + }); + +mongoose.model('').aggregate() + .then(function (arg) { + return 2; + }).then(function (num) { + num.toFixed; + return new Promise((resolve, reject) => { + resolve('str'); + }); + }).then(function (str) { + str.toLowerCase; + }); + /* pluggable promise */ mongoose.Promise = Promise; mongoose.Promise.race; diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 71cb91bf8c..eb4c355237 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -1307,7 +1307,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): Promise; + catch(reject?: (err: any) => void | TRes | PromiseLike): Promise; /** * DEPRECATED Alias for circle @@ -1651,7 +1651,8 @@ declare module "mongoose" { }): this; /** Executes this query and returns a promise */ - then(resolve?: (res: T) => void, reject?: (err: any) => void): Promise; + then(resolve?: (res: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): Promise; /** * Converts this query to a customized, reusable query @@ -2071,7 +2072,8 @@ declare module "mongoose" { sort(arg: string | Object): this; /** Provides promise for aggregate. */ - then(resolve?: (val: T) => void, reject?: (err: any) => void): Promise + then(resolve?: (val: T) => void | TRes | PromiseLike, + reject?: (err: any) => void | TRes | PromiseLike): Promise /** * Appends new custom $unwind operator(s) to this aggregate pipeline. From b301b3e81c8c5d94c1d56eb57c2c054c6a88158b Mon Sep 17 00:00:00 2001 From: Simon Date: Sat, 16 Jul 2016 22:39:41 -0400 Subject: [PATCH 0081/1255] fixes return type of mongoosethenable --- mongoose/mongoose-tests.ts | 4 ++-- mongoose/mongoose.d.ts | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index dc8f795672..de2bffaf05 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -28,7 +28,7 @@ mongoose.connect(connectUri, { autoIndex: true }, mongos: true -}).then(cb); +}).then(cb).onReject; mongoose.connect(connectUri, function (error) { error.stack; }); @@ -46,7 +46,7 @@ mongoose.createConnection('localhost', 'database', 3000, { autoIndex: false } }).open(''); -mongoose.disconnect(cb).then(cb); +mongoose.disconnect(cb).then(cb).fulfill; mongoose.get('test'); mongoose.model('Actor', new mongoose.Schema({ name: String diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index eb4c355237..8112fc09a1 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -309,13 +309,14 @@ declare module "mongoose" { * Ability to use mongoose object as a pseudo-promise so .connect().then() * and .disconnect().then() are viable. */ - static then(onFulfill?: () => void, onRejected?: (err: mongodb.MongoError) => void): typeof MongooseThenable; + static then(onFulfill?: () => void | TRes | PromiseLike, + 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. */ - static catch(onRejected?: (err: mongodb.MongoError) => void): typeof MongooseThenable; + static catch(onRejected?: (err: mongodb.MongoError) => void | TRes | PromiseLike): Promise; } class CastError extends _mongoose.Error { From 8a33d5322850ef83ba0c68fb3a9e34cb95d52277 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 18 Jul 2016 17:17:27 +0200 Subject: [PATCH 0082/1255] Add stronger typed version of gl-matrix definitions. Also contains all methods of gl-matrix available on 18 july 2016. No tests yet. --- gl-matrix/gl-matrix-typed.d.ts | 3063 ++++++++++++++++++++++++++++++++ 1 file changed, 3063 insertions(+) create mode 100644 gl-matrix/gl-matrix-typed.d.ts diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts new file mode 100644 index 0000000000..f64225c6f7 --- /dev/null +++ b/gl-matrix/gl-matrix-typed.d.ts @@ -0,0 +1,3063 @@ +// Type definitions for gl-matrix 2.2.2 +// Project: https://github.com/toji/gl-matrix +// Definitions by: Tat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Common +declare namespace glMatrix { + /** + * Convert Degree To Radian + * + * @param a Angle in Degrees + */ + export function toRadian(a: number): number; +} + +// vec2 +export class vec2 extends Float32Array { + private typeVec2:number; + + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + public static create(): vec2; + + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + public static clone(a: vec2): vec2; + + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + public static fromValues(x: number, y: number): vec2; + + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec2, a: vec2): vec2; + + /** + * Set the components of a vec2 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @returns out + */ + public static set(out: vec2, x: number, y: number): vec2; + + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Math.ceil the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to ceil + * @returns {vec2} out + */ + public static ceil(out:vec2, a:vec2):vec2; + + /** + * Math.floor the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to floor + * @returns {vec2} out + */ + public static floor (out:vec2, a:vec2):vec2; + + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Math.round the components of a vec2 + * + * @param {vec2} out the receiving vector + * @param {vec2} a vector to round + * @returns {vec2} out + */ + public static round(out:vec2, a:vec2):vec2; + + + /** + * Scales a vec2 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec2, a: vec2, b: number): vec2; + + /** + * Adds two vec2's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec2, a: vec2, b: vec2, scale: number): vec2; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec2, b: vec2): number; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec2, b: vec2): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec2, b: vec2): number; + + /** + * Calculates the squared euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec2, b: vec2): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec2): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec2): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec2): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec2): number; + + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec2, a: vec2): vec2; + + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec2, a: vec2): vec2; + + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec2, a: vec2): vec2; + + /** + * Calculates the dot product of two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec2, b: vec2): number; + + /** + * Computes the cross product of two vec2's + * Note that the cross product must by definition produce a 3D vector + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static cross(out: vec2, a: vec2, b: vec2): vec2; + + /** + * Performs a linear interpolation between two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec2, a: vec2, b: vec2, t: number): vec2; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec2): vec2; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec2, scale: number): vec2; + + /** + * Transforms the vec2 with a mat2 + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat2(out: vec2, a: vec2, m: mat2): vec2; + + /** + * Transforms the vec2 with a mat2d + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat2d(out: vec2, a: vec2, m: mat2d): vec2; + + /** + * Transforms the vec2 with a mat3 + * 3rd vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat3(out: vec2, a: vec2, m: mat3): vec2; + + /** + * Transforms the vec2 with a mat4 + * 3rd vector component is implicitly '0' + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec2, a: vec2, m: mat4): vec2; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + */ + public static forEach(a: vec2, stride: number, offset: number, count: number, + fn: (a: vec2, b: vec2, arg: any) => void, arg: any): vec2; + + /** + * Perform some operation over an array of vec2s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec2. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec2s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + */ + public static forEach(a: vec2, stride: number, offset: number, count: number, + fn: (a: vec2, b: vec2) => void): vec2; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec2): string; + + /** + * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a:vec2, b:vec2): boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec2} a The first vector. + * @param {vec2} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a:vec2, b:vec2) : boolean; +} + +// vec3 +export class vec3 extends Float32Array { + private typeVec3:number; + + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + public static create(): vec3; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + public static clone(a: vec3): vec3; + + /** + * Creates a new vec3 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @returns a new 3D vector + */ + public static fromValues(x: number, y: number, z: number): vec3; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec3, a: vec3): vec3; + + /** + * Set the components of a vec3 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @returns out + */ + public static set(out: vec3, x: number, y: number, z: number): vec3; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec3, a: vec3, b: vec3): vec3 + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Math.ceil the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to ceil + * @returns {vec3} out + */ + public static ceil (out:vec3, a:vec3) : vec3; + + /** + * Math.floor the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to floor + * @returns {vec3} out + */ + public static floor (out:vec3, a:vec3) :vec3; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Math.round the components of a vec3 + * + * @param {vec3} out the receiving vector + * @param {vec3} a vector to round + * @returns {vec3} out + */ + public static round (out:vec3, a:vec3) : vec3 + + /** + * Scales a vec3 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec3, a: vec3, b: number): vec3; + + /** + * Adds two vec3's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec3, a: vec3, b: vec3, scale: number): vec3; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec3, b: vec3): number; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec3, b: vec3): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec3, b: vec3): number; + + /** + * Calculates the squared euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec3, b: vec3): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec3): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec3): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec3): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec3): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec3, a: vec3): vec3; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec3, a: vec3): vec3; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec3, a: vec3): vec3; + + /** + * Calculates the dot product of two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec3, b: vec3): number; + + /** + * Computes the cross product of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static cross(out: vec3, a: vec3, b: vec3): vec3; + + /** + * Performs a linear interpolation between two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec3, a: vec3, b: vec3, t: number): vec3; + + /** + * Performs a hermite interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static hermite (out:vec3, a:vec3, b:vec3, c:vec3, d:vec3, t:number) : vec3; + + /** + * Performs a bezier interpolation with two control points + * + * @param {vec3} out the receiving vector + * @param {vec3} a the first operand + * @param {vec3} b the second operand + * @param {vec3} c the third operand + * @param {vec3} d the fourth operand + * @param {number} t interpolation amount between the two inputs + * @returns {vec3} out + */ + public static bezier (out:vec3, a:vec3, b:vec3, c:vec3, d:vec3, t:number) :vec3; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec3): vec3; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec3, scale: number): vec3; + + /** + * Transforms the vec3 with a mat3. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m the 3x3 matrix to transform with + * @returns out + */ + public static transformMat3(out: vec3, a: vec3, m: mat3): vec3; + + /** + * Transforms the vec3 with a mat4. + * 4th vector component is implicitly '1' + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec3, a: vec3, m: mat4): vec3; + + /** + * Transforms the vec3 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + public static transformQuat(out: vec3, a: vec3, q: quat): vec3; + + + /** + * Rotate a 3D vector around the x-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateX(out: vec3, a: vec3, b: vec3, c: number): vec3; + + /** + * Rotate a 3D vector around the y-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateY(out: vec3, a: vec3, b: vec3, c: number): vec3; + + /** + * Rotate a 3D vector around the z-axis + * @param out The receiving vec3 + * @param a The vec3 point to rotate + * @param b The origin of the rotation + * @param c The angle of rotation + * @returns out + */ + public static rotateZ(out: vec3, a: vec3, b: vec3, c: number): vec3; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + public static forEach(a: vec3, stride: number, offset: number, count: number, + fn: (a: vec3, b: vec3, arg: any) => void, arg: any): vec3; + + /** + * Perform some operation over an array of vec3s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec3. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec3s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + public static forEach(a: vec3, stride: number, offset: number, count: number, + fn: (a: vec3, b: vec3) => void): vec3; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + public static angle(a: vec3, b: vec3): number; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec3): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a, b): boolean + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec3} a The first vector. + * @param {vec3} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a, b) : boolean +} + +// vec4 +export class vec4 extends Float32Array { + private typeVec3:number; + + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + public static create(): vec4; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + public static clone(a: vec4): vec4; + + /** + * Creates a new vec4 initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new 4D vector + */ + public static fromValues(x: number, y: number, z: number, w: number): vec4; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + public static copy(out: vec4, a: vec4): vec4; + + /** + * Set the components of a vec4 to the given values + * + * @param out the receiving vector + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + */ + public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static add(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static subtract(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static sub(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static divide(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static div(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Math.ceil the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to ceil + * @returns {vec4} out + */ + public static ceil (out:vec4, a:vec4) : vec4; + + /** + * Math.floor the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to floor + * @returns {vec4} out + */ + public static floor (out:vec4, a:vec4) : vec4; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static min(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static max(out: vec4, a: vec4, b: vec4): vec4; + + /** + * Math.round the components of a vec4 + * + * @param {vec4} out the receiving vector + * @param {vec4} a vector to round + * @returns {vec4} out + */ + public static round (out:vec4, a:vec4): vec4; + + /** + * Scales a vec4 by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + */ + public static scale(out: vec4, a: vec4, b: number): vec4; + + /** + * Adds two vec4's after scaling the second operand by a scalar value + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param scale the amount to scale b by before adding + * @returns out + */ + public static scaleAndAdd(out: vec4, a: vec4, b: vec4, scale: number): vec4; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static distance(a: vec4, b: vec4): number; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + public static dist(a: vec4, b: vec4): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static squaredDistance(a: vec4, b: vec4): number; + + /** + * Calculates the squared euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns squared distance between a and b + */ + public static sqrDist(a: vec4, b: vec4): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static length(a: vec4): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + public static len(a: vec4): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static squaredLength(a: vec4): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + public static sqrLen(a: vec4): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + public static negate(out: vec4, a: vec4): vec4; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + public static inverse(out: vec4, a: vec4): vec4; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + public static normalize(out: vec4, a: vec4): vec4; + + /** + * Calculates the dot product of two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + */ + public static dot(a: vec4, b: vec4): number; + + /** + * Performs a linear interpolation between two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static lerp(out: vec4, a: vec4, b: vec4, t: number): vec4; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + public static random(out: vec4): vec4; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param scale length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + public static random(out: vec4, scale: number): vec4; + + /** + * Transforms the vec4 with a mat4. + * + * @param out the receiving vector + * @param a the vector to transform + * @param m matrix to transform with + * @returns out + */ + public static transformMat4(out: vec4, a: vec4, m: mat4): vec4; + + /** + * Transforms the vec4 with a quat + * + * @param out the receiving vector + * @param a the vector to transform + * @param q quaternion to transform with + * @returns out + */ + + public static transformQuat(out: vec4, a: vec4, q: quat): vec4; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @param arg additional argument to pass to fn + * @returns a + * @function + */ + public static forEach(a: vec4, stride: number, offset: number, count: number, + fn: (a: vec4, b: vec4, arg: any) => void, arg: any): vec4; + + /** + * Perform some operation over an array of vec4s. + * + * @param a the array of vectors to iterate over + * @param stride Number of elements between the start of each vec4. If 0 assumes tightly packed + * @param offset Number of elements to skip at the beginning of the array + * @param count Number of vec4s to iterate over. If 0 iterates over entire array + * @param fn Function to call for each vector in the array + * @returns a + * @function + */ + public static forEach(a: vec4, stride: number, offset: number, count: number, + fn: (a: vec4, b: vec4) => void): vec4; + + /** + * Returns a string representation of a vector + * + * @param a vector to represent as a string + * @returns string representation of the vector + */ + public static str(a: vec4): string; + + /** + * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static exactEquals (a:vec4, b:vec4) : boolean; + + /** + * Returns whether or not the vectors have approximately the same elements in the same position. + * + * @param {vec4} a The first vector. + * @param {vec4} b The second vector. + * @returns {boolean} True if the vectors are equal, false otherwise. + */ + public static equals (a:vec4, b:vec4) : boolean; +} + +// mat2 +export class mat2 extends Float32Array { + private typeMat2:number; + + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + public static create():mat2; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + public static clone(a:mat2):mat2; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out:mat2, a:mat2):mat2; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out:mat2):mat2; + + /** + * Create a new mat2 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out A new 2x2 matrix + */ + public static fromValues(m00:number, m01:number, m10:number, m11:number):mat2; + + /** + * Set the components of a mat2 to the given values + * + * @param {mat2} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m10 Component in column 1, row 0 position (index 2) + * @param {number} m11 Component in column 1, row 1 position (index 3) + * @returns {mat2} out + */ + public static set(out:mat2, m00:number, m01:number, m10:number, m11:number):mat2; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out:mat2, a:mat2):mat2; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out:mat2, a:mat2):mat2; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out:mat2, a:mat2):mat2; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a:mat2):number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out:mat2, a:mat2, b:mat2):mat2; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out:mat2, a:mat2, b:mat2):mat2; + + /** + * Rotates a mat2 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out:mat2, a:mat2, rad:number):mat2; + + /** + * Scales the mat2 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out:mat2, a:mat2, v:vec2):mat2; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.rotate(dest, dest, rad); + * + * @param {mat2} out mat2 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2} out + */ + public static fromRotation(out:mat2, rad:number):mat2; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2.identity(dest); + * mat2.scale(dest, dest, vec); + * + * @param {mat2} out mat2 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2} out + */ + public static fromScaling(out:mat2, v:vec2); + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(a:mat2):string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a:mat2):number; + + /** + * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix + * @param L the lower triangular matrix + * @param D the diagonal matrix + * @param U the upper triangular matrix + * @param a the input matrix to factorize + */ + public static LDU(L:mat2, D:mat2, U:mat2, a:mat2):mat2; + + /** + * Adds two mat2's + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static add(out:mat2, a:mat2, b:mat2):mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static subtract (out:mat2, a:mat2, b:mat2):mat2; + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @returns {mat2} out + */ + public static sub (out:mat2, a:mat2, b:mat2):mat2; + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a:mat2, b:mat2):boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2} a The first matrix. + * @param {mat2} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a:mat2, b:mat2) :boolean; + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2} out the receiving matrix + * @param {mat2} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2} out + */ + public static multiplyScalar (out:mat2, a:mat2, b:number) :mat2 + + /** + * Adds two mat2's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2} out the receiving vector + * @param {mat2} a the first operand + * @param {mat2} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2} out + */ + public static multiplyScalarAndAdd (out:mat2, a:mat2, b:mat2, scale:number): mat2 + + + +} + +// mat2d +export class mat2d extends Float32Array { + private typeMat2d:number; + + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + public static create(): mat2d; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + public static clone(a: mat2d): mat2d; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out: mat2d, a: mat2d): mat2d; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out: mat2d): mat2d; + + /** + * Create a new mat2d with the given values + * + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} A new mat2d + */ + public static fromValues (a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d + + + /** + * Set the components of a mat2d to the given values + * + * @param {mat2d} out the receiving matrix + * @param {number} a Component A (index 0) + * @param {number} b Component B (index 1) + * @param {number} c Component C (index 2) + * @param {number} d Component D (index 3) + * @param {number} tx Component TX (index 4) + * @param {number} ty Component TY (index 5) + * @returns {mat2d} out + */ + public static set (out:mat2d, a:number, b:number, c:number, d:number, tx:number, ty:number) :mat2d + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out: mat2d, a: mat2d): mat2d; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a: mat2d): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; + + /** + * Rotates a mat2d by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; + + /** + * Scales the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out: mat2d, a: mat2d, v: vec2): mat2d; + + /** + * Translates the mat2d by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v the vec2 to translate the matrix by + * @returns out + **/ + public static translate(out: mat2d, a: mat2d, v: vec2): mat2d; + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.rotate(dest, dest, rad); + * + * @param {mat2d} out mat2d receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat2d} out + */ + public static fromRotation (out:mat2d, rad:number): mat2d; + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.scale(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat2d} out + */ + public static fromScaling (out:mat2d, v:vec2):mat2d; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat2d.identity(dest); + * mat2d.translate(dest, dest, vec); + * + * @param {mat2d} out mat2d receiving operation result + * @param {vec2} v Translation vector + * @returns {mat2d} out + */ + public static fromTranslation (out:mat2d, v:vec2):mat2d + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(a: mat2d): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a: mat2d): number; + + /** + * Adds two mat2d's + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static add (out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static subtract(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Subtracts matrix b from matrix a + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @returns {mat2d} out + */ + public static sub(out: mat2d, a: mat2d, b: mat2d): mat2d + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat2d} out the receiving matrix + * @param {mat2d} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat2d} out + */ + public static multiplyScalar (out: mat2d, a: mat2d, b: mat2d): mat2d; + + /** + * Adds two mat2d's after multiplying each element of the second operand by a scalar value. + * + * @param {mat2d} out the receiving vector + * @param {mat2d} a the first operand + * @param {mat2d} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat2d} out + */ + public static multiplyScalarAndAdd (out: mat2d, a: mat2d, b: mat2d, scale:number) : mat2d + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a: mat2d, b: mat2d): boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat2d} a The first matrix. + * @param {mat2d} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a: mat2d, b: mat2d): boolean +} + +// mat3 +export class mat3 extends Float32Array { + private typeMat3:number; + + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + public static create():mat3; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param {mat3} out the receiving 3x3 matrix + * @param {mat4} a the source 4x4 matrix + * @returns {mat3} out + */ + public static fromMat4(out:mat3, a:mat4):mat3 + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + public static clone(a:mat3):mat3; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out:mat3, a:mat3):mat3; + + /** + * Create a new mat3 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} A new mat3 + */ + public static fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22):mat3; + + + /** + * Set the components of a mat3 to the given values + * + * @param {mat3} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m10 Component in column 1, row 0 position (index 3) + * @param {number} m11 Component in column 1, row 1 position (index 4) + * @param {number} m12 Component in column 1, row 2 position (index 5) + * @param {number} m20 Component in column 2, row 0 position (index 6) + * @param {number} m21 Component in column 2, row 1 position (index 7) + * @param {number} m22 Component in column 2, row 2 position (index 8) + * @returns {mat3} out + */ + public static set(out:mat3, m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number):mat3 + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out:mat3):mat3; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out:mat3, a:mat3):mat3; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out:mat3, a:mat3):mat3; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out:mat3, a:mat3):mat3; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a:mat3):number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out:mat3, a:mat3, b:mat3):mat3; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out:mat3, a:mat3, b:mat3):mat3; + + + /** + * Translate a mat3 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + public static translate(out:mat3, a:mat3, v:vec3):mat3; + + /** + * Rotates a mat3 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotate(out:mat3, a:mat3, rad:number):mat3; + + /** + * Scales the mat3 by the dimensions in the given vec2 + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param v the vec2 to scale the matrix by + * @returns out + **/ + public static scale(out:mat3, a:mat3, v:vec2):mat3; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.translate(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Translation vector + * @returns {mat3} out + */ + public static fromTranslation(out:mat3, v:vec2):mat3 + + /** + * Creates a matrix from a given angle + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.rotate(dest, dest, rad); + * + * @param {mat3} out mat3 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat3} out + */ + public static fromRotation(out:mat3, rad:number):mat3 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat3.identity(dest); + * mat3.scale(dest, dest, vec); + * + * @param {mat3} out mat3 receiving operation result + * @param {vec2} v Scaling vector + * @returns {mat3} out + */ + public static fromScaling(out:mat3, v:vec2):mat3 + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + public static fromMat2d(out:mat3, a:mat2d):mat3; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param out the receiving 3x3 matrix + * @param a the source 4x4 matrix + * @returns out + */ + public static fromMat4(out:mat3, a:mat4):mat3; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + public static fromQuat(out:mat3, q:quat):mat3; + + /** + * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix + * + * @param out mat3 receiving operation result + * @param a Mat4 to derive the normal matrix from + * + * @returns out + */ + public static normalFromMat4(out:mat3, a:mat3):mat3; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat:mat3):string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a:mat3):number; + + /** + * Adds two mat3's + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static add(out:mat3, a:mat3, b:mat3):mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static subtract(out:mat3, a:mat3, b:mat3):mat3 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @returns {mat3} out + */ + public static sub(out:mat3, a:mat3, b:mat3):mat3 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat3} out the receiving matrix + * @param {mat3} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat3} out + */ + public static multiplyScalar(out:mat3, a:mat3, b:number):mat3 + + /** + * Adds two mat3's after multiplying each element of the second operand by a scalar value. + * + * @param {mat3} out the receiving vector + * @param {mat3} a the first operand + * @param {mat3} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat3} out + */ + public static multiplyScalarAndAdd(out:mat3, a:mat3, b:mat3, scale:number):mat3 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals(a:mat3, b:mat3):boolean; + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat3} a The first matrix. + * @param {mat3} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals(a:mat3, b:mat3):boolean +} + +// mat4 +export class mat4 extends Float32Array { + private typeMat4:number; + + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + public static create():mat4; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + public static clone(a:mat4):mat4; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static copy(out:mat4, a:mat4):mat4; + + + /** + * Create a new mat4 with the given values + * + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} A new mat4 + */ + public static fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33):mat4; + + /** + * Set the components of a mat4 to the given values + * + * @param {mat4} out the receiving matrix + * @param {number} m00 Component in column 0, row 0 position (index 0) + * @param {number} m01 Component in column 0, row 1 position (index 1) + * @param {number} m02 Component in column 0, row 2 position (index 2) + * @param {number} m03 Component in column 0, row 3 position (index 3) + * @param {number} m10 Component in column 1, row 0 position (index 4) + * @param {number} m11 Component in column 1, row 1 position (index 5) + * @param {number} m12 Component in column 1, row 2 position (index 6) + * @param {number} m13 Component in column 1, row 3 position (index 7) + * @param {number} m20 Component in column 2, row 0 position (index 8) + * @param {number} m21 Component in column 2, row 1 position (index 9) + * @param {number} m22 Component in column 2, row 2 position (index 10) + * @param {number} m23 Component in column 2, row 3 position (index 11) + * @param {number} m30 Component in column 3, row 0 position (index 12) + * @param {number} m31 Component in column 3, row 1 position (index 13) + * @param {number} m32 Component in column 3, row 2 position (index 14) + * @param {number} m33 Component in column 3, row 3 position (index 15) + * @returns {mat4} out + */ + public static set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33):mat4; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + public static identity(out:mat4):mat4; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static transpose(out:mat4, a:mat4):mat4; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static invert(out:mat4, a:mat4):mat4; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + public static adjoint(out:mat4, a:mat4):mat4; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + public static determinant(a:mat4):number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out:mat4, a:mat4, b:mat4):mat4; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out:mat4, a:mat4, b:mat4):mat4; + + /** + * Translate a mat4 by the given vector + * + * @param out the receiving matrix + * @param a the matrix to translate + * @param v vector to translate by + * @returns out + */ + public static translate(out:mat4, a:mat4, v:vec3):mat4; + + /** + * Scales the mat4 by the dimensions in the given vec3 + * + * @param out the receiving matrix + * @param a the matrix to scale + * @param v the vec3 to scale the matrix by + * @returns out + **/ + public static scale(out:mat4, a:mat4, v:vec3):mat4; + + /** + * Rotates a mat4 by the given angle + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @param axis the axis to rotate around + * @returns out + */ + public static rotate(out:mat4, a:mat4, rad:number, axis:vec3):mat4; + + /** + * Rotates a matrix by the given angle around the X axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateX(out:mat4, a:mat4, rad:number):mat4; + + /** + * Rotates a matrix by the given angle around the Y axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateY(out:mat4, a:mat4, rad:number):mat4; + + /** + * Rotates a matrix by the given angle around the Z axis + * + * @param out the receiving matrix + * @param a the matrix to rotate + * @param rad the angle to rotate the matrix by + * @returns out + */ + public static rotateZ(out:mat4, a:mat4, rad:number):mat4; + + /** + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out + */ + public static fromTranslation(out:mat4, v:vec3):mat4 + + /** + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out + */ + public static fromScaling(out:mat4, v:vec3):mat4 + + /** + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotate(dest, dest, rad, axis); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @param {vec3} axis the axis to rotate around + * @returns {mat4} out + */ + public static fromRotation(out:mat4, rad:number, axis:vec3):mat4 + + /** + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateX(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromXRotation(out:mat4, rad:number):mat4 + + /** + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateY(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromYRotation(out:mat4, rad:number):mat4 + + + /** + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.rotateZ(dest, dest, rad); + * + * @param {mat4} out mat4 receiving operation result + * @param {number} rad the angle to rotate the matrix by + * @returns {mat4} out + */ + public static fromZRotation(out:mat4, rad:number):mat4 + + /** + * Creates a matrix from a quaternion rotation and vector translation + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @returns out + */ + public static fromRotationTranslation(out:mat4, q:quat, v:vec3):mat4; + + /** + * Returns the translation vector component of a transformation + * matrix. If a matrix is built with fromRotationTranslation, + * the returned vector will be the same as the translation vector + * originally supplied. + * @param {vec3} out Vector to receive translation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {vec3} out + */ + public static getTranslation(out:vec3, mat:mat4):vec3; + + /** + * Returns a quaternion representing the rotational component + * of a transformation matrix. If a matrix is built with + * fromRotationTranslation, the returned quaternion will be the + * same as the quaternion originally supplied. + * @param {quat} out Quaternion to receive the rotation component + * @param {mat4} mat Matrix to be decomposed (input) + * @return {quat} out + */ + public static getRotation(out:quat, mat:mat4):quat; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @param v Translation vector + * @param s Scaling vector + * @returns out + */ + public static fromRotationTranslationScale(out:mat4, q:quat, v:vec3, s:vec3):mat4; + + /** + * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin + * This is equivalent to (but much faster than): + * + * mat4.identity(dest); + * mat4.translate(dest, vec); + * mat4.translate(dest, origin); + * var quatMat = mat4.create(); + * quat4.toMat4(quat, quatMat); + * mat4.multiply(dest, quatMat); + * mat4.scale(dest, scale) + * mat4.translate(dest, negativeOrigin); + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Rotation quaternion + * @param {vec3} v Translation vector + * @param {vec3} s Scaling vector + * @param {vec3} o The origin vector around which to scale and rotate + * @returns {mat4} out + */ + public static fromRotationTranslationScaleOrigin(out:mat4, q:quat, v:vec3, s:vec3, o:vec3):mat4 + + /** + * Calculates a 4x4 matrix from the given quaternion + * + * @param {mat4} out mat4 receiving operation result + * @param {quat} q Quaternion to create matrix from + * + * @returns {mat4} out + */ + public static fromQuat(out:mat4, q:quat):mat4 + + /** + * Generates a frustum matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static frustum(out:mat4, left:number, right:number, + bottom:number, top:number, near:number, far:number):mat4; + + /** + * Generates a perspective projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param fovy Vertical field of view in radians + * @param aspect Aspect ratio. typically viewport width/height + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static perspective(out:mat4, fovy:number, aspect:number, + near:number, far:number):mat4; + + /** + * Generates a perspective projection matrix with the given field of view. + * This is primarily useful for generating projection matrices to be used + * with the still experimental WebVR API. + * + * @param {mat4} out mat4 frustum matrix will be written into + * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees + * @param {number} near Near bound of the frustum + * @param {number} far Far bound of the frustum + * @returns {mat4} out + */ + public static perspectiveFromFieldOfView(out:mat4, + fov:{upDegrees:number, downDegrees:number, leftDegrees:number, rightDegrees:number}, + near, far):mat4 + + /** + * Generates a orthogonal projection matrix with the given bounds + * + * @param out mat4 frustum matrix will be written into + * @param left Left bound of the frustum + * @param right Right bound of the frustum + * @param bottom Bottom bound of the frustum + * @param top Top bound of the frustum + * @param near Near bound of the frustum + * @param far Far bound of the frustum + * @returns out + */ + public static ortho(out:mat4, left:number, right:number, + bottom:number, top:number, near:number, far:number):mat4; + + /** + * Generates a look-at matrix with the given eye position, focal point, and up axis + * + * @param out mat4 frustum matrix will be written into + * @param eye Position of the viewer + * @param center Point the viewer is looking at + * @param up vec3 pointing up + * @returns out + */ + public static lookAt(out:mat4, eye:vec3, center:vec3, up:vec3):mat4; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + public static str(mat:mat4):string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + public static frob(a:mat4):number; + + /** + * Adds two mat4's + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static add(out:mat4, a:mat4, b:mat4):mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static subtract(out:mat4, a:mat4, b:mat4):mat4 + + /** + * Subtracts matrix b from matrix a + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @returns {mat4} out + */ + public static sub(out:mat4, a:mat4, b:mat4):mat4 + + /** + * Multiply each element of the matrix by a scalar. + * + * @param {mat4} out the receiving matrix + * @param {mat4} a the matrix to scale + * @param {number} b amount to scale the matrix's elements by + * @returns {mat4} out + */ + public static multiplyScalar(out:mat4, a:mat4, b:mat4):mat4 + + /** + * Adds two mat4's after multiplying each element of the second operand by a scalar value. + * + * @param {mat4} out the receiving vector + * @param {mat4} a the first operand + * @param {mat4} b the second operand + * @param {number} scale the amount to scale b's elements by before adding + * @returns {mat4} out + */ + public static multiplyScalarAndAdd (out:mat4, a:mat4, b:mat4, scale:number):mat4 + + /** + * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static exactEquals (a:mat4, b:mat4) :boolean + + /** + * Returns whether or not the matrices have approximately the same elements in the same position. + * + * @param {mat4} a The first matrix. + * @param {mat4} b The second matrix. + * @returns {boolean} True if the matrices are equal, false otherwise. + */ + public static equals (a:mat4, b:mat4): boolean + +} + +// quat +export class quat extends Float32Array { + private typeQuat:number; + + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + public static create(): quat; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + public static clone(a: quat): quat; + + /** + * Creates a new quat initialized with the given values + * + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns a new quaternion + * @function + */ + public static fromValues(x: number, y: number, z: number, w: number): quat; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + public static copy(out: quat, a: quat): quat; + + /** + * Set the components of a quat to the given values + * + * @param out the receiving quaternion + * @param x X component + * @param y Y component + * @param z Z component + * @param w W component + * @returns out + * @function + */ + public static set(out: quat, x: number, y: number, z: number, w: number): quat; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + public static identity(out: quat): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param {quat} out the receiving quaternion. + * @param {vec3} a the initial vector + * @param {vec3} b the destination vector + * @returns {quat} out + */ + public static rotationTo (out:quat, a:vec3, b:vec3): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param {vec3} view the vector representing the viewing direction + * @param {vec3} right the vector representing the local "right" direction + * @param {vec3} up the vector representing the local "up" direction + * @returns {quat} out + */ + public static setAxes (out:quat, view:vec3, right:vec3, up:vec3):quat + + + + /** + * Sets a quat from the given angle and rotation axis, + * then returns it. + * + * @param out the receiving quaternion + * @param axis the axis around which to rotate + * @param rad the angle in radians + * @returns out + **/ + public static setAxisAngle(out: quat, axis: vec3, rad: number): quat; + + /** + * Gets the rotation axis and angle for a given + * quaternion. If a quaternion is created with + * setAxisAngle, this method will return the same + * values as providied in the original parameter list + * OR functionally equivalent values. + * Example: The quaternion formed by axis [0, 0, 1] and + * angle -90 is the same as the quaternion formed by + * [0, 0, 1] and 270. This method favors the latter. + * @param {vec3} out_axis Vector receiving the axis of rotation + * @param {quat} q Quaternion to be decomposed + * @return {number} Angle, in radians, of the rotation + */ + public static getAxisAngle (out_axis:vec3, q:quat) :number + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + public static add(out: quat, a: quat, b: quat): quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static multiply(out: quat, a: quat, b: quat): quat; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + public static mul(out: quat, a: quat, b: quat): quat; + + /** + * Scales a quat by a scalar number + * + * @param out the receiving vector + * @param a the vector to scale + * @param b amount to scale the vector by + * @returns out + * @function + */ + public static scale(out: quat, a: quat, b: number): quat; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + public static length(a: quat): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + public static len(a: quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + public static squaredLength(a: quat): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + public static sqrLen(a: quat): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + public static normalize(out: quat, a: quat): quat; + + /** + * Calculates the dot product of two quat's + * + * @param a the first operand + * @param b the second operand + * @returns dot product of a and b + * @function + */ + public static dot(a: quat, b: quat): number; + + /** + * Performs a linear interpolation between two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + * @function + */ + public static lerp(out: quat, a: quat, b: quat, t: number): quat; + + /** + * Performs a spherical linear interpolation between two quat + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @param t interpolation amount between the two inputs + * @returns out + */ + public static slerp(out:quat, a:quat, b:quat, t:number): quat; + + /** + * Performs a spherical linear interpolation with two control points + * + * @param {quat} out the receiving quaternion + * @param {quat} a the first operand + * @param {quat} b the second operand + * @param {quat} c the third operand + * @param {quat} d the fourth operand + * @param {number} t interpolation amount + * @returns {quat} out + */ + public static sqlerp(out: quat, a: quat, b: quat, c: quat, d: quat, t: number): quat; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + public static invert(out: quat, a: quat): quat; + + /** + * Calculates the conjugate of a quat + * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result. + * + * @param out the receiving quaternion + * @param a quat to calculate conjugate of + * @returns out + */ + public static conjugate(out: quat, a: quat): quat; + + /** + * Returns a string representation of a quaternion + * + * @param a quat to represent as a string + * @returns string representation of the quat + */ + public static str(a: quat): string; + + /** + * Rotates a quaternion by the given angle about the X axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateX(out: quat, a: quat, rad: number): quat; + + /** + * Rotates a quaternion by the given angle about the Y axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateY(out: quat, a: quat, rad: number): quat; + + /** + * Rotates a quaternion by the given angle about the Z axis + * + * @param out quat receiving operation result + * @param a quat to rotate + * @param rad angle (in radians) to rotate + * @returns out + */ + public static rotateZ(out: quat, a: quat, rad: number): quat; + + /** + * Creates a quaternion from the given 3x3 rotation matrix. + * + * NOTE: The resultant quaternion is not normalized, so you should be sure + * to renormalize the quaternion yourself where necessary. + * + * @param out the receiving quaternion + * @param m rotation matrix + * @returns out + * @function + */ + public static fromMat3(out: quat, m: mat3): quat; + + /** + * Sets the specified quaternion with values corresponding to the given + * axes. Each axis is a vec3 and is expected to be unit length and + * perpendicular to all other specified axes. + * + * @param out the receiving quat + * @param view the vector representing the viewing direction + * @param right the vector representing the local "right" direction + * @param up the vector representing the local "up" direction + * @returns out + */ + public static setAxes(out: quat, view: vec3, right: vec3, up: vec3): quat; + + /** + * Sets a quaternion to represent the shortest rotation from one + * vector to another. + * + * Both vectors are assumed to be unit length. + * + * @param out the receiving quaternion. + * @param a the initial vector + * @param b the destination vector + * @returns out + */ + public static rotationTo(out: quat, a: vec3, b: vec3): quat; + + /** + * Calculates the W component of a quat from the X, Y, and Z components. + * Assumes that quaternion is 1 unit in length. + * Any existing W component will be ignored. + * + * @param out the receiving quaternion + * @param a quat to calculate W component of + * @returns out + */ + public static calculateW(out: quat, a: quat): quat; + + /** + * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===) + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static exactEquals (a:quat, b:quat) : boolean; + + /** + * Returns whether or not the quaternions have approximately the same elements in the same position. + * + * @param {quat} a The first vector. + * @param {quat} b The second vector. + * @returns {boolean} True if the quaternions are equal, false otherwise. + */ + public static equals (a:quat, b:quat) : boolean; +} From 9d33ed7f26cd37bf99bae074b6ddca5c4b0b8aef Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 18 Jul 2016 19:29:05 +0200 Subject: [PATCH 0083/1255] Add gl-matrix-typed tests and fix gl-matrix-typed --- gl-matrix/gl-matrix-typed-tests.ts | 346 +++++++++++++++++++++++++++++ gl-matrix/gl-matrix-typed.d.ts | 71 +++--- 2 files changed, 377 insertions(+), 40 deletions(-) create mode 100644 gl-matrix/gl-matrix-typed-tests.ts diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts new file mode 100644 index 0000000000..7364ec0a83 --- /dev/null +++ b/gl-matrix/gl-matrix-typed-tests.ts @@ -0,0 +1,346 @@ +/// + +// common +import {vec2, mat2, mat3, mat4, vec3, vec4, glMatrix, mat2d, quat} from "./gl-matrix-typed"; +var result: number = glMatrix.toRadian(180); + +var outVal: number; +var outBool: boolean; +var outStr: string; + +let vecArray = new Float32Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]); + +let vec2A = vec2.fromValues(1, 2); +let vec2B = vec2.fromValues(3, 4); +let vec3A = vec3.fromValues(1, 2, 3); +let vec3B = vec3.fromValues(3, 4, 5); +let vec4A = vec4.fromValues(1, 2, 3, 4); +let vec4B = vec4.fromValues(3, 4, 5, 6); +let mat2A = mat2.fromValues(1, 2, 3, 4); +let mat2B = mat2.fromValues(1, 2, 3, 4); +let mat2dA = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat2dB = mat2d.fromValues(1, 2, 3, 4, 5, 6); +let mat3A = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat3B = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +let mat4A = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let mat4B = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +let quatA = quat.fromValues(1, 2, 3, 4); +let quatB = quat.fromValues(5, 6, 7, 8); + +let outVec2 = vec2.create(); +let outVec3 = vec3.create(); +let outVec4 = vec4.create(); +let outMat2 = mat2.create(); +let outMat2d = mat2d.create(); +let outMat3 = mat3.create(); +let outMat4 = mat4.create(); +let outQuat = quat.create(); + +// vec2 +outVec2 = vec2.create(); +outVec2 = vec2.clone(vec2A); +outVec2 = vec2.fromValues(1, 2); +outVec2 = vec2.copy(outVec2, vec2A); +outVec2 = vec2.set(outVec2, 1, 2); +outVec2 = vec2.add(outVec2, vec2A, vec2B); +outVec2 = vec2.subtract(outVec2, vec2A, vec2B); +outVec2 = vec2.sub(outVec2, vec2A, vec2B); +outVec2 = vec2.multiply(outVec2, vec2A, vec2B); +outVec2 = vec2.mul(outVec2, vec2A, vec2B); +outVec2 = vec2.divide(outVec2, vec2A, vec2B); +outVec2 = vec2.div(outVec2, vec2A, vec2B); +outVec2 = vec2.ceil(outVec2, vec2A); +outVec2 = vec2.floor(outVec2, vec2A); +outVec2 = vec2.min(outVec2, vec2A, vec2B); +outVec2 = vec2.max(outVec2, vec2A, vec2B); +outVec2 = vec2.round(outVec2, vec2A); +outVec2 = vec2.scale(outVec2, vec2A, 2); +outVec2 = vec2.scaleAndAdd(outVec2, vec2A, vec2B, 0.5); +outVal = vec2.distance(vec2A, vec2B); +outVal = vec2.dist(vec2A, vec2B); +outVal = vec2.squaredDistance(vec2A, vec2B); +outVal = vec2.sqrDist(vec2A, vec2B); +outVal = vec2.length(vec2A); +outVal = vec2.len(vec2A); +outVal = vec2.squaredLength(vec2A); +outVal = vec2.sqrLen(vec2A); +outVec2 = vec2.negate(outVec2, vec2A); +outVec2 = vec2.inverse(outVec2, vec2A); +outVec2 = vec2.normalize(outVec2, vec2A); +outVal = vec2.dot(vec2A, vec2B); +outVec2 = vec2.cross(outVec2, vec2A, vec2B); +outVec2 = vec2.lerp(outVec2, vec2A, vec2B, 0.5); +outVec2 = vec2.random(outVec2); +outVec2 = vec2.random(outVec2, 5.0); +outVec2 = vec2.transformMat2(outVec2, vec2A, mat2A); +outVec2 = vec2.transformMat2d(outVec2, vec2A, mat2dA); +outVec2 = vec2.transformMat3(outVec2, vec2A, mat3A); +outVec2 = vec2.transformMat4(outVec2, vec2A, mat4A); +vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vec2A); +outBool = vec2.exactEquals(vec2A, vec2B); +outBool = vec2.equals(vec2A, vec2B); + +// vec3 +outVec3 = vec3.create(); +outVec3 = vec3.clone(vec3A); +outVec3 = vec3.fromValues(1, 2, 3); +outVec3 = vec3.copy(outVec3, vec3A); +outVec3 = vec3.set(outVec3, 1, 2, 3); +outVec3 = vec3.add(outVec3, vec3A, vec3B); +outVec3 = vec3.subtract(outVec3, vec3A, vec3B); +outVec3 = vec3.sub(outVec3, vec3A, vec3B); +outVec3 = vec3.multiply(outVec3, vec3A, vec3B); +outVec3 = vec3.mul(outVec3, vec3A, vec3B); +outVec3 = vec3.divide(outVec3, vec3A, vec3B); +outVec3 = vec3.div(outVec3, vec3A, vec3B); +outVec3 = vec3.ceil(outVec3, vec3A); +outVec3 = vec3.floor(outVec3, vec3A); +outVec3 = vec3.min(outVec3, vec3A, vec3B); +outVec3 = vec3.max(outVec3, vec3A, vec3B); +outVec3 = vec3.round(outVec3, vec3A); +outVec3 = vec3.scale(outVec3, vec3A, 2); +outVec3 = vec3.scaleAndAdd(outVec3, vec3A, vec3B, 0.5); +outVal = vec3.distance(vec3A, vec3B); +outVal = vec3.dist(vec3A, vec3B); +outVal = vec3.squaredDistance(vec3A, vec3B); +outVal = vec3.sqrDist(vec3A, vec3B); +outVal = vec3.length(vec3A); +outVal = vec3.len(vec3A); +outVal = vec3.squaredLength(vec3A); +outVal = vec3.sqrLen(vec3A); +outVec3 = vec3.negate(outVec3, vec3A); +outVec3 = vec3.inverse(outVec3, vec3A); +outVec3 = vec3.normalize(outVec3, vec3A); +outVal = vec3.dot(vec3A, vec3B); +outVec3 = vec3.cross(outVec3, vec3A, vec3B); +outVec3 = vec3.lerp(outVec3, vec3A, vec3B, 0.5); +outVec3 = vec3.hermite(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.bezier(outVec3, vec3A, vec3B, vec3A, vec3B, 0.5); +outVec3 = vec3.random(outVec3); +outVec3 = vec3.random(outVec3, 5.0); +outVec3 = vec3.transformMat3(outVec3, vec3A, mat3A); +outVec3 = vec3.transformMat4(outVec3, vec3A, mat4A); +outVec3 = vec3.transformQuat(outVec3, vec3A, quatA); +outVec3 = vec3.rotateX(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateY(outVec3, vec3A, vec3B, Math.PI); +outVec3 = vec3.rotateZ(outVec3, vec3A, vec3B, Math.PI); +vecArray = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vec3A, vec3B); +outStr = vec3.str(vec3A); +outBool = vec3.exactEquals(vec3A, vec3B); +outBool = vec3.equals(vec3A, vec3B); + +// vec4 +outVec4 = vec4.create(); +outVec4 = vec4.clone(vec4A); +outVec4 = vec4.fromValues(1, 2, 3, 4); +outVec4 = vec4.copy(outVec4, vec4A); +outVec4 = vec4.set(outVec4, 1, 2, 3, 4); +outVec4 = vec4.add(outVec4, vec4A, vec4B); +outVec4 = vec4.subtract(outVec4, vec4A, vec4B); +outVec4 = vec4.sub(outVec4, vec4A, vec4B); +outVec4 = vec4.multiply(outVec4, vec4A, vec4B); +outVec4 = vec4.mul(outVec4, vec4A, vec4B); +outVec4 = vec4.divide(outVec4, vec4A, vec4B); +outVec4 = vec4.div(outVec4, vec4A, vec4B); +outVec4 = vec4.ceil(outVec4, vec4A); +outVec4 = vec4.floor(outVec4, vec4A); +outVec4 = vec4.min(outVec4, vec4A, vec4B); +outVec4 = vec4.max(outVec4, vec4A, vec4B); +outVec4 = vec4.scale(outVec4, vec4A, 2); +outVec4 = vec4.scaleAndAdd(outVec4, vec4A, vec4B, 0.5); +outVal = vec4.distance(vec4A, vec4B); +outVal = vec4.dist(vec4A, vec4B); +outVal = vec4.squaredDistance(vec4A, vec4B); +outVal = vec4.sqrDist(vec4A, vec4B); +outVal = vec4.length(vec4A); +outVal = vec4.len(vec4A); +outVal = vec4.squaredLength(vec4A); +outVal = vec4.sqrLen(vec4A); +outVec4 = vec4.negate(outVec4, vec4A); +outVec4 = vec4.inverse(outVec4, vec4A); +outVec4 = vec4.normalize(outVec4, vec4A); +outVal = vec4.dot(vec4A, vec4B); +outVec4 = vec4.lerp(outVec4, vec4A, vec4B, 0.5); +outVec4 = vec4.random(outVec4); +outVec4 = vec4.random(outVec4, 5.0); +outVec4 = vec4.transformMat4(outVec4, vec4A, mat4A); +outVec4 = vec4.transformQuat(outVec4, vec4A, quatA); +vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vec4A); +outBool = vec4.exactEquals(vec4A, vec4B); +outBool = vec4.equals(vec4A, vec4B); + +// mat2 +outMat2 = mat2.create(); +outMat2 = mat2.clone(mat2A); +outMat2 = mat2.copy(outMat2, mat2A); +outMat2 = mat2.identity(outMat2); +outMat2 = mat2.fromValues(1, 2, 3, 4); +outMat2 = mat2.set(outMat2, 1, 2, 3, 4); +outMat2 = mat2.transpose(outMat2, mat2A); +outMat2 = mat2.invert(outMat2, mat2A); +outMat2 = mat2.adjoint(outMat2, mat2A); +outVal = mat2.determinant(mat2A); +outMat2 = mat2.multiply(outMat2, mat2A, mat2B); +outMat2 = mat2.mul(outMat2, mat2A, mat2B); +outMat2 = mat2.rotate(outMat2, mat2A, Math.PI * 0.5); +outMat2 = mat2.scale(outMat2, mat2A, vec2A); +outMat2 = mat2.fromRotation(outMat2, 0.5); +outMat2 = mat2.fromScaling(outMat2, vec2A); +outStr = mat2.str(mat2A); +outVal = mat2.frob(mat2A); +var L = mat2.create(); +var D = mat2.create(); +var U = mat2.create(); +outMat2 = mat2.LDU(L, D, U, mat2A); +outMat2 = mat2.add(outMat2, mat2A, mat2B); +outMat2 = mat2.subtract(outMat2, mat2A, mat2B); +outMat2 = mat2.sub(outMat2, mat2A, mat2B); +outBool = mat2.exactEquals(mat2A, mat2B); +outBool = mat2.equals(mat2A, mat2B); +outMat2 = mat2.multiplyScalar (outMat2, mat2A, 2); +outMat2 = mat2.multiplyScalarAndAdd (outMat2, mat2A, mat2B, 2); + +// mat2d +outMat2d = mat2d.create(); +outMat2d = mat2d.clone(mat2dA); +outMat2d = mat2d.copy(outMat2d, mat2dA); +outMat2d = mat2d.identity(outMat2d); +outMat2d = mat2d.fromValues(1, 2, 3, 4, 5, 6); +outMat2d = mat2d.set(outMat2d, 1, 2, 3, 4, 5, 6); +outMat2d = mat2d.invert(outMat2d, mat2dA); +outVal = mat2d.determinant(mat2dA); +outMat2d = mat2d.multiply(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.mul(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.rotate(outMat2d, mat2dA, Math.PI * 0.5); +outMat2d = mat2d.scale(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.translate(outMat2d, mat2dA, vec2A); +outMat2d = mat2d.fromRotation(outMat2d, 0.5); +outMat2d = mat2d.fromScaling(outMat2d, vec2A); +outMat2d = mat2d.fromTranslation(outMat2d, vec2A); +outStr = mat2d.str(mat2dA); +outVal = mat2d.frob(mat2dA); +outMat2d = mat2d.add(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.subtract(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.sub(outMat2d, mat2dA, mat2dB); +outMat2d = mat2d.multiplyScalar (outMat2d, mat2dA, 2); +outMat2d = mat2d.multiplyScalarAndAdd (outMat2d, mat2dA, mat2dB, 2); +outBool = mat2d.exactEquals(mat2dA, mat2dB); +outBool = mat2d.equals(mat2dA, mat2dB); + + +// mat3 +outMat3 = mat3.create(); +outMat3 = mat3.fromMat4(outMat3, mat4A); +outMat3 = mat3.clone(mat3A); +outMat3 = mat3.copy(outMat3, mat3A); +outMat3 = mat3.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.set(outMat3, 1, 2, 3, 4, 5, 6, 7, 8, 9); +outMat3 = mat3.identity(outMat3); +outMat3 = mat3.transpose(outMat3, mat3A); +outMat3 = mat3.invert(outMat3, mat3A); +outMat3 = mat3.adjoint(outMat3, mat3A); +outVal = mat3.determinant(mat3A); +outMat3 = mat3.multiply(outMat3, mat3A, mat3B); +outMat3 = mat3.mul(outMat3, mat3A, mat3B); +outMat3 = mat3.translate(outMat3, mat3A, vec3A); +outMat3 = mat3.rotate(outMat3, mat3A, Math.PI/2); +outMat3 = mat3.scale(outMat3, mat3A, vec2A); +outMat3 = mat3.fromTranslation(outMat3, vec2A); +outMat3 = mat3.fromRotation(outMat3, Math.PI); +outMat3 = mat3.fromScaling(outMat3, vec2A); +outMat3 = mat3.fromMat2d(outMat3, mat2dA); +outMat3 = mat3.fromQuat(outMat3, quatA); +outMat3 = mat3.normalFromMat4(outMat3, mat4A); +outStr = mat3.str(mat3A); +outVal = mat3.frob(mat3A); +outMat3 = mat3.add(outMat3, mat3A, mat3B); +outMat3 = mat3.subtract(outMat3, mat3A, mat3B); +outMat3 = mat3.sub(outMat3, mat3A, mat3B); +outMat3 = mat3.multiplyScalar (outMat3, mat3A, 2); +outMat3 = mat3.multiplyScalarAndAdd (outMat3, mat3A, mat3B, 2); +outBool = mat3.exactEquals(mat3A, mat3B); +outBool = mat3.equals(mat3A, mat3B); + +//mat4 +outMat4 = mat4.create(); +outMat4 = mat4.clone(mat4A); +outMat4 = mat4.copy(outMat4, mat4A); +outMat4 = mat4.fromValues(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.set(outMat4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); +outMat4 = mat4.identity(outMat4); +outMat4 = mat4.transpose(outMat4, mat4A); +outMat4 = mat4.invert(outMat4, mat4A); +outMat4 = mat4.adjoint(outMat4, mat4A); +outVal = mat4.determinant(mat4A); +outMat4 = mat4.multiply(outMat4, mat4A, mat4B); +outMat4 = mat4.mul(outMat4, mat4A, mat4B); +outMat4 = mat4.translate(outMat4, mat4A, vec3A); +outMat4 = mat4.scale(outMat4, mat4A, vec3A); +outMat4 = mat4.rotate(outMat4, mat4A, Math.PI, vec3A); +outMat4 = mat4.rotateX(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateY(outMat4, mat4A, Math.PI); +outMat4 = mat4.rotateZ(outMat4, mat4A, Math.PI); +outMat4 = mat4.fromTranslation(outMat4, vec3A); +outMat4 = mat4.fromRotation(outMat4, Math.PI, vec3A); +outMat4 = mat4.fromScaling(outMat4, vec3A); +outMat4 = mat4.fromXRotation(outMat4, Math.PI); +outMat4 = mat4.fromYRotation(outMat4, Math.PI); +outMat4 = mat4.fromZRotation(outMat4, Math.PI); +outMat4 = mat4.fromRotationTranslation(outMat4, quatA, vec3A); +outVec3 = mat4.getTranslation(outVec3, mat4A) +outQuat = mat4.getRotation(outQuat, mat4A) +outMat4 = mat4.fromRotationTranslationScale(outMat4, quatA, vec3A, vec3B); +outMat4 = mat4.fromRotationTranslationScaleOrigin(outMat4, quatA, vec3A, vec3B, vec3A); +outMat4 = mat4.fromQuat(outMat4, quatB); +outMat4 = mat4.frustum(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.perspective(outMat4, Math.PI, 1, 0, 1); +outMat4 = mat4.perspectiveFromFieldOfView(outMat4, {upDegrees:Math.PI, downDegrees:-Math.PI, leftDegrees:-Math.PI, rightDegrees:Math.PI}, 1, 0); +outMat4 = mat4.ortho(outMat4, -1, 1, -1, 1, -1, 1); +outMat4 = mat4.lookAt(outMat4, vec3A, vec3B, vec3A); +outStr = mat4.str(mat4A); +outVal = mat4.frob(mat4A); +outMat4 = mat4.add(outMat4, mat4A, mat4B); +outMat4 = mat4.subtract(outMat4, mat4A, mat4B); +outMat4 = mat4.sub(outMat4, mat4A, mat4B); +outMat4 = mat4.multiplyScalar (outMat4, mat4A, 2); +outMat4 = mat4.multiplyScalarAndAdd (outMat4, mat4A, mat4B, 2); +outBool = mat4.exactEquals(mat4A, mat4B); +outBool = mat4.equals(mat4A, mat4B); + +// quat +var deg90 = Math.PI / 2; +outQuat = quat.create(); +outQuat = quat.clone(quatA); +outQuat = quat.fromValues(1, 2, 3, 4); +outQuat = quat.copy(outQuat, quatA); +outQuat = quat.set(outQuat, 1, 2, 3, 4); +outQuat = quat.identity(outQuat); +outQuat = quat.rotationTo(outQuat, vec3A, vec3B); +outQuat = quat.setAxes(outQuat, vec3A, vec3B, vec3A); +outQuat = quat.setAxisAngle(outQuat, vec3A, Math.PI * 0.5); +outVal = quat.getAxisAngle (outVec3, quatA); +outQuat = quat.add(outQuat, quatA, quatB); +outQuat = quat.multiply(outQuat, quatA, quatB); +outQuat = quat.mul(outQuat, quatA, quatB); +outQuat = quat.scale(outQuat, quatA, 2); +outVal = quat.length(quatA); +outVal = quat.len(quatA); +outVal = quat.squaredLength(quatA); +outVal = quat.sqrLen(quatA); +outQuat = quat.normalize(outQuat, quatA); +outVal = quat.dot(quatA, quatB); +outQuat = quat.lerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.slerp(outQuat, quatA, quatB, 0.5); +outQuat = quat.invert(outQuat, quatA); +outQuat = quat.conjugate(outQuat, quatA); +outStr = quat.str(quatA); +outQuat = quat.rotateX(outQuat, quatA, deg90); +outQuat = quat.rotateY(outQuat, quatA, deg90); +outQuat = quat.rotateZ(outQuat, quatA, deg90); +outQuat = quat.fromMat3(outQuat, mat3A); +outQuat = quat.calculateW(outQuat, quatA); +outBool = quat.exactEquals(quatA, quatB); +outBool = quat.equals(quatA, quatB); \ No newline at end of file diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts index f64225c6f7..e172074fec 100644 --- a/gl-matrix/gl-matrix-typed.d.ts +++ b/gl-matrix/gl-matrix-typed.d.ts @@ -1,16 +1,16 @@ // Type definitions for gl-matrix 2.2.2 // Project: https://github.com/toji/gl-matrix -// Definitions by: Tat +// Definitions by: Mattijs Kneppers , based on definitions by Tat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Common -declare namespace glMatrix { +export class glMatrix { /** - * Convert Degree To Radian - * - * @param a Angle in Degrees - */ - export function toRadian(a: number): number; + * Convert Degree To Radian + * + * @param a Angle in Degrees + */ + public static toRadian(a: number): number; } // vec2 @@ -396,8 +396,8 @@ export class vec2 extends Float32Array { * @param arg additional argument to pass to fn * @returns a */ - public static forEach(a: vec2, stride: number, offset: number, count: number, - fn: (a: vec2, b: vec2, arg: any) => void, arg: any): vec2; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2, b: vec2, arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec2s. @@ -409,8 +409,8 @@ export class vec2 extends Float32Array { * @param fn Function to call for each vector in the array * @returns a */ - public static forEach(a: vec2, stride: number, offset: number, count: number, - fn: (a: vec2, b: vec2) => void): vec2; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2, b: vec2) => void): Float32Array; /** * Returns a string representation of a vector @@ -868,8 +868,8 @@ export class vec3 extends Float32Array { * @returns a * @function */ - public static forEach(a: vec3, stride: number, offset: number, count: number, - fn: (a: vec3, b: vec3, arg: any) => void, arg: any): vec3; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3, b: vec3, arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec3s. @@ -882,8 +882,8 @@ export class vec3 extends Float32Array { * @returns a * @function */ - public static forEach(a: vec3, stride: number, offset: number, count: number, - fn: (a: vec3, b: vec3) => void): vec3; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3, b: vec3) => void): Float32Array; /** * Get the angle between two 3D vectors @@ -908,7 +908,7 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a, b): boolean + public static exactEquals (a:vec3, b:vec3): boolean /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -917,7 +917,7 @@ export class vec3 extends Float32Array { * @param {vec3} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a, b) : boolean + public static equals (a:vec3, b:vec3) : boolean } // vec4 @@ -1274,8 +1274,8 @@ export class vec4 extends Float32Array { * @returns a * @function */ - public static forEach(a: vec4, stride: number, offset: number, count: number, - fn: (a: vec4, b: vec4, arg: any) => void, arg: any): vec4; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4, b: vec4, arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec4s. @@ -1288,8 +1288,8 @@ export class vec4 extends Float32Array { * @returns a * @function */ - public static forEach(a: vec4, stride: number, offset: number, count: number, - fn: (a: vec4, b: vec4) => void): vec4; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4, b: vec4) => void): Float32Array; /** * Returns a string representation of a vector @@ -1476,7 +1476,7 @@ export class mat2 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2} out */ - public static fromScaling(out:mat2, v:vec2); + public static fromScaling(out:mat2, v:vec2):mat2; /** * Returns a string representation of a mat2 @@ -1623,7 +1623,7 @@ export class mat2d extends Float32Array { * @param {number} ty Component TY (index 5) * @returns {mat2d} A new mat2d */ - public static fromValues (a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d + public static fromValues (a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d /** @@ -1800,7 +1800,7 @@ export class mat2d extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat2d} out */ - public static multiplyScalar (out: mat2d, a: mat2d, b: mat2d): mat2d; + public static multiplyScalar (out: mat2d, a: mat2d, b: number): mat2d; /** * Adds two mat2d's after multiplying each element of the second operand by a scalar value. @@ -1883,7 +1883,7 @@ export class mat3 extends Float32Array { * @param {number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} A new mat3 */ - public static fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22):mat3; + public static fromValues(m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number):mat3; /** @@ -2045,15 +2045,6 @@ export class mat3 extends Float32Array { **/ public static fromMat2d(out:mat3, a:mat2d):mat3; - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param out the receiving 3x3 matrix - * @param a the source 4x4 matrix - * @returns out - */ - public static fromMat4(out:mat3, a:mat4):mat3; - /** * Calculates a 3x3 matrix from the given quaternion * @@ -2072,7 +2063,7 @@ export class mat3 extends Float32Array { * * @returns out */ - public static normalFromMat4(out:mat3, a:mat3):mat3; + public static normalFromMat4(out:mat3, a:mat4):mat3; /** * Returns a string representation of a mat3 @@ -2210,7 +2201,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} A new mat4 */ - public static fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33):mat4; + public static fromValues(m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number):mat4; /** * Set the components of a mat4 to the given values @@ -2234,7 +2225,7 @@ export class mat4 extends Float32Array { * @param {number} m33 Component in column 3, row 3 position (index 15) * @returns {mat4} out */ - public static set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33):mat4; + public static set(out:mat4, m00:number, m01:number, m02:number, m03:number, m10:number, m11:number, m12:number, m13:number, m20:number, m21:number, m22:number, m23:number, m30:number, m31:number, m32:number, m33:number):mat4; /** * Set a mat4 to the identity matrix @@ -2571,7 +2562,7 @@ export class mat4 extends Float32Array { */ public static perspectiveFromFieldOfView(out:mat4, fov:{upDegrees:number, downDegrees:number, leftDegrees:number, rightDegrees:number}, - near, far):mat4 + near:number, far:number):mat4 /** * Generates a orthogonal projection matrix with the given bounds @@ -2653,7 +2644,7 @@ export class mat4 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat4} out */ - public static multiplyScalar(out:mat4, a:mat4, b:mat4):mat4 + public static multiplyScalar(out:mat4, a:mat4, b:number):mat4 /** * Adds two mat4's after multiplying each element of the second operand by a scalar value. @@ -3059,5 +3050,5 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static equals (a:quat, b:quat) : boolean; + public static equals (a:quat, b:quat) : boolean; } From 0e5388394d5e3662de092a0c87b2c32d455bccca Mon Sep 17 00:00:00 2001 From: Alex Staroselsky Date: Mon, 18 Jul 2016 22:25:08 -0500 Subject: [PATCH 0084/1255] Updated service options object to remove invalid properties and add missing properties. Updated via overloading service to include optional async instance lookup. --- angular-material/angular-material-tests.ts | 14 +++++++++++++- angular-material/angular-material.d.ts | 12 +++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index 8e2bdfdf43..4464c599e3 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -30,7 +30,11 @@ myApp.config(( myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.IBottomSheetService) => { $scope['openBottomSheet'] = () => { $mdBottomSheet.show({ - template: 'Hello!' + template: 'Hello!', + clickOutsideToClose: true, + disableBackdrop: true, + disableParentScroll: false, + parent: () => {} }); }; $scope['hideBottomSheet'] = $mdBottomSheet.hide.bind($mdBottomSheet, 'hide'); @@ -115,6 +119,14 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia $scope['close'] = () => $mdSidenav(componentId).close(); $scope['isOpen'] = $mdSidenav(componentId).isOpen(); $scope['isLockedOpen'] = $mdSidenav(componentId).isLockedOpen(); + + $scope['asyncLookup'] = $mdSidenav(componentId, true).then((instance) => { + instance.toggle(); + instance.open(); + instance.close(); + instance.isOpen(); + instance.isLockedOpen(); + }); }); myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => { diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index d79e75a07d..2be0a6d874 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Angular Material 1.0.0-rc5+ (angular.material module) +// Type definitions for Angular Material 1.1.0-rc5+ (angular.material module) // Project: https://github.com/angular/material // Definitions by: Matt Traynham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -19,11 +19,12 @@ declare namespace angular.material { preserveScope?: boolean; // default: false controller?: string|Function; locals?: {[index: string]: any}; - targetEvent?: MouseEvent; - resolve?: {[index: string]: angular.IPromise} + clickOutsideToClose?: boolean; + disableBackdrop?: boolean; + escapeToClose?: boolean; + resolve?: {[index: string]: angular.IPromise}; controllerAs?: string; - bindToController?: boolean; - parent?: string|Element|JQuery; // default: root node + parent?: Function|string|Object; // default: root node disableParentScroll?: boolean; // default: true } @@ -134,6 +135,7 @@ declare namespace angular.material { } interface ISidenavService { + (component: string, enableWait: boolean): angular.IPromise; (component: string): ISidenavObject; } From 4fa75f472975f92ff217c672a58e006cdd04a57c Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Tue, 19 Jul 2016 17:09:23 +0900 Subject: [PATCH 0085/1255] Node-Scanf --- scanf/scanf-tests.ts | 5 ++ scanf/scanf.d.ts | 200 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 205 insertions(+) create mode 100644 scanf/scanf-tests.ts create mode 100644 scanf/scanf.d.ts diff --git a/scanf/scanf-tests.ts b/scanf/scanf-tests.ts new file mode 100644 index 0000000000..62966f26c0 --- /dev/null +++ b/scanf/scanf-tests.ts @@ -0,0 +1,5 @@ +/// + +import scanf = require("scanf"); + +console.log(scanf.sscanf("3", "%d")); \ No newline at end of file diff --git a/scanf/scanf.d.ts b/scanf/scanf.d.ts new file mode 100644 index 0000000000..a1f6cdc549 --- /dev/null +++ b/scanf/scanf.d.ts @@ -0,0 +1,200 @@ +// Type definitions for node-scanf +// Project: https://github.com/Lellansin/node-scanf +// Definitions by: Jeongho Nam +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "scanf" +{ + export = __node_scanf.scanf; +} + +declare namespace __node_scanf +{ + /* ------------------------------------------------------------ + SCANF - FROM STDIN + ------------------------------------------------------------ */ + /** + *

Read formatted word from stdin.

+ * + *

Reads a word from stdin and returns it according to parameter format.

+ * + * @param format The format represents a word. + * @return A word. + */ + function scanf(format: "%s"): string; + + /** + *

Read formatted line from stdin.

+ * + *

Reads a word from stdin and returns it according to parameter format.

+ * + * @param format The format represents a word. + * @return A word. + */ + function scanf(format: "%S"): string; + + /** + *

Read formatted integer from stdin.

+ * + *

Reads an integer from stdin and returns it according to parameter format.

+ * + * @param format The format represents an integer value. + * @return An integer. + */ + function scanf(format: "%d"): number; + + /** + *

Read formatted float from stdin.

+ * + *

Reads a float from stdin and returns it according to parameter format.

+ * + * @param format The format represents an float value. + * @return A float. + */ + function scanf(format: "%f"): number; + + /** + *

Read formatted octal from stdin.

+ * + *

Reads an octal from stdin and returns it according to parameter format.

+ * + * @param format The format represents an octal value. + * @return An octal. + */ + function scanf(format: "%o"): number; + + /** + *

Read formatted hex from stdin.

+ * + *

Reads a hex from stdin and returns it according to parameter format.

+ * + * @param format The format represents a hex value. + * @return A hex. + */ + function scanf(format: "%x"): number; + + /** + *

Reads formatted data from stdin.

+ * + *

Reads data from stdin and stores them according to the parameter format into an array to be returned.

+ * + * @param format The format contains a sequence of characters that control how characters extracted from the stream are tread. + * @return An array containing data constructed from stdin with the format. + */ + function scanf(format: string): Array; + + /** + *

Reads formatted data from stdin.

+ * + *

Reads data from stdin and stores them according to the parameter format into a JSON object following sequence of names.

+ * + * @param format The format contains a sequence of characters that control how characters extracted from the stream are tread. + * @param names Names of data constructed from stdin with the format. + * + * @return A JSON object containing data constructed from stdin with the format and following names. + */ + function scanf(format: string, ...names: string[]): Object; + + /* ------------------------------------------------------------ + SSCANF - FROM SOURCE STRING + ------------------------------------------------------------ */ + namespace scanf + { + /** + *

Read formatted word from string.

+ * + *

Reads a word from source and returns it according to parameter format.

+ * + * @param source Source string to retrieve data. + * @param format The format represents a word. + * + * @return A word. + */ + function sscanf(source: string, format: "%s"): string; + + /** + *

Read formatted line from string.

+ * + *

Reads a word from source and returns it according to parameter format.

+ * + * @param source Source string to retrieve data. + * @param format The format represents a word. + * + * @return A word. + */ + function sscanf(source: string, format: "%S"): string; + + /** + *

Read formatted integer from string.

+ * + *

Reads an integer from source and returns it according to parameter format.

+ * + * @param source Source string to retrieve data. + * @param format The format represents an integer value. + * + * @return An integer. + */ + function sscanf(source: string, format: "%d"): number; + + /** + *

Read formatted float from string.

+ * + *

Reads a float from source and returns it according to parameter format.

+ * + * @param source Source string to retrieve data. + * @param format The format represents an float value. + * + * @return A float. + */ + function sscanf(source: string, format: "%f"): number; + + /** + *

Read formatted octal from string.

+ * + *

Reads an octal from source and returns it according to parameter format.

+ * + * @param source Source string to retrieve data. + * @param format The format represents an octal value. + * + * @return An octal. + */ + function sscanf(source: string, format: "%o"): number; + + /** + *

Read formatted hex from string.

+ * + *

Reads a hex from source and returns it according to parameter format.

+ * + * @param source Source string to retrieve data. + * @param format The format represents a hex value. + * + * @return A hex. + */ + function sscanf(source: string, format: "%x"): number; + + /** + *

Reads formatted data from string.

+ * + *

Reads data from source and stores them according to the parameter format into an array to be returned.

+ * + * @param source Source string to retrieve data. + * @param format The format contains a sequence of characters that control how characters extracted from the stream are tread. + * + * @return An array containing data constructed from string with the format. + */ + function sscanf(source: string, format: string): Array; + + /** + *

Reads formatted data from string.

+ * + *

Reads data from source and stores them according to the parameter format into a JSON object following sequence of names.

+ * + * @param source Source string to retrieve data. + * @param format The format contains a sequence of characters that control how characters extracted from the stream are tread. + * @param names Names of data constructed from string with the format. + * + * @return A JSON object containing data constructed from string with the format and following names. + */ + function sscanf(source: string, format: string, ...names: string[]): Object; + } +} \ No newline at end of file From e0fdec22052b3d00b7bcfcf2e851731d690fc876 Mon Sep 17 00:00:00 2001 From: Michael McKenzie Date: Tue, 19 Jul 2016 09:57:58 +0100 Subject: [PATCH 0086/1255] Changing hitch signature to match documentation --- dojo/dojo.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index bf3258a14a..687dba4cf7 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -5617,7 +5617,7 @@ declare namespace dojo { * @param scope The scope to use when method executes. If method is a string,scope is also the object containing method. * @param method A function to be hitched to scope, or the name of the method inscope to be hitched. */ - hitch(scope: Object, method: Function): any; + hitch(scope: Object, method: (...args: any[]) => any): any; /** * Returns a function that will only ever execute in the a given scope. * This allows for easy use of object member functions @@ -5631,7 +5631,7 @@ declare namespace dojo { * @param scope The scope to use when method executes. If method is a string,scope is also the object containing method. * @param method A function to be hitched to scope, or the name of the method inscope to be hitched. */ - hitch(scope: Object, method: String[]): any; + hitch(scope: Object, method: string): any; /** * Returns true if it is a built-in function or some other kind of * oddball that should report as a function but doesn't From 5cca8b39b92d6d408205edabd827e80caae73282 Mon Sep 17 00:00:00 2001 From: Michael McKenzie Date: Tue, 19 Jul 2016 11:16:55 +0100 Subject: [PATCH 0087/1255] Changing hitch signature to match documentation --- dojo/dojo.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index 687dba4cf7..8a566a46f5 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -5617,7 +5617,7 @@ declare namespace dojo { * @param scope The scope to use when method executes. If method is a string,scope is also the object containing method. * @param method A function to be hitched to scope, or the name of the method inscope to be hitched. */ - hitch(scope: Object, method: (...args: any[]) => any): any; + hitch(scope: Object, method: (...args: any[]) => any, ...args: any[]): any; /** * Returns a function that will only ever execute in the a given scope. * This allows for easy use of object member functions @@ -5631,7 +5631,7 @@ declare namespace dojo { * @param scope The scope to use when method executes. If method is a string,scope is also the object containing method. * @param method A function to be hitched to scope, or the name of the method inscope to be hitched. */ - hitch(scope: Object, method: string): any; + hitch(scope: Object, method: string, ...args: any[]): any; /** * Returns true if it is a built-in function or some other kind of * oddball that should report as a function but doesn't From cdfb764333a69c177fa59837d92a98b03f564538 Mon Sep 17 00:00:00 2001 From: Michael McKenzie Date: Tue, 19 Jul 2016 11:40:06 +0100 Subject: [PATCH 0088/1255] Changing dojo/_base/lang mixin signature to match documentation --- dojo/dojo.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index 8a566a46f5..cddc6445bb 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -5686,7 +5686,7 @@ declare namespace dojo { * @param dest The object to which to copy/add all properties contained in source. If dest is falsy, thena new object is manufactured before copying/adding properties begins. * @param sources One of more objects from which to draw all properties to copy into dest. sources are processedleft-to-right and if more than one of these objects contain the same property name, the right-mostvalue "wins". */ - mixin(dest: Object, sources: Object[]): Object; + mixin(dest: Object, ...sources: Object[]): Object; /** * similar to hitch() except that the scope object is left to be * whatever the execution context eventually becomes. From 9330e507270fb5e5b70e832bc65821efbf478b7c Mon Sep 17 00:00:00 2001 From: Michael McKenzie Date: Tue, 19 Jul 2016 11:46:37 +0100 Subject: [PATCH 0089/1255] Revert "Changing dojo/_base/lang mixin signature to match documentation" This reverts commit cdfb764333a69c177fa59837d92a98b03f564538. --- dojo/dojo.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dojo/dojo.d.ts b/dojo/dojo.d.ts index cddc6445bb..8a566a46f5 100644 --- a/dojo/dojo.d.ts +++ b/dojo/dojo.d.ts @@ -5686,7 +5686,7 @@ declare namespace dojo { * @param dest The object to which to copy/add all properties contained in source. If dest is falsy, thena new object is manufactured before copying/adding properties begins. * @param sources One of more objects from which to draw all properties to copy into dest. sources are processedleft-to-right and if more than one of these objects contain the same property name, the right-mostvalue "wins". */ - mixin(dest: Object, ...sources: Object[]): Object; + mixin(dest: Object, sources: Object[]): Object; /** * similar to hitch() except that the scope object is left to be * whatever the execution context eventually becomes. From 9bd416090bc58bde254fe43abe27a266b209ce45 Mon Sep 17 00:00:00 2001 From: Pierre Urban Date: Tue, 19 Jul 2016 23:40:31 +0200 Subject: [PATCH 0090/1255] Set the type of language to any. (#10187) * Set the type of language to any. The type of language can be string, array, etc. Sources: https://github.com/select2/select2/blob/6844be777b0fe9af1d2b9a8f6051b7eb7d532247/src/js/select2/defaults.js#L235-L294 * Update the language type. --- select2/select2.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/select2/select2.d.ts b/select2/select2.d.ts index 7699615dee..908fa7a6ae 100644 --- a/select2/select2.d.ts +++ b/select2/select2.d.ts @@ -78,7 +78,7 @@ interface Select2Options { */ templateSelection?: (object: Select2SelectionObject) => any; templateResult?: (object: Select2SelectionObject) => any; - language?: string; + language?: string | string[] | {}; } interface Select2JQueryEventObject extends JQueryEventObject { From ba5f8c1b2f14a6de0be68674da5ec0fc9c00ee14 Mon Sep 17 00:00:00 2001 From: Matthias Date: Tue, 19 Jul 2016 19:22:58 -0400 Subject: [PATCH 0091/1255] Add OpenLayers v3.14.2 (#10119) * Created openlayers v.3.14.2 definitions file by cloning v3.6.0 * fix shadowed references to global types * Added ol.events.Event, ol.events.EventTarget and ol.events.ListenerFunctionType * filled in ol.proj.Projection * completed ol.Observable. Corrected variable names. Added inheritance from ol.events.EventTarget and updated dispatchEvent() to include a possible boolean operator, as per EventTargets impl of dispatchEvent * Filled in ol.interaction.DrawEvent. Added ol.interaction.DrawEventType. * Filled in ol.interaction.Interaction, and added olx.interaction.InteractionOptions. * Filled in ol.interaction.DrawOptions * Corrected ol.DrawGeometryFunctionType * Filled in ol.source.Vector * Updated ol.source.Source . Removed refresh() since it's not in the docs or the code file. * Typo * Added to ol.geom.Polygon * Fix ol.Map beforeRender() * Added PointerOptions, MapBrowserPointerEvent, ModifyEventType, ModifyEvent, pointer && pointer.PointerEvent . * Added to ol.geom.Circle . Added ol.events.Key, though I don't know what it is. * Fixed CollectionEvent * Fix jsdoc problems * DragBoxOptions, InteractionOptions * update VectorOptions * Update VectorOptions * Other things * Lint * Fix duplicates and syntax errors from test. * Filled in ol.interaction. Lint * Added tests file and updated it. Fixed some more definitions. Observable extends. and others --- openlayers/openlayers-3.14.2-tests.ts | 714 ++++ openlayers/openlayers-3.14.2.d.ts | 4873 +++++++++++++++++++++++++ 2 files changed, 5587 insertions(+) create mode 100644 openlayers/openlayers-3.14.2-tests.ts create mode 100644 openlayers/openlayers-3.14.2.d.ts diff --git a/openlayers/openlayers-3.14.2-tests.ts b/openlayers/openlayers-3.14.2-tests.ts new file mode 100644 index 0000000000..1bfdc4bf63 --- /dev/null +++ b/openlayers/openlayers-3.14.2-tests.ts @@ -0,0 +1,714 @@ +/// + +// Basic type variables for test functions +var anyValue: any; +var voidValue: void; +var numberValue: number; +var booleanValue: boolean; +var stringValue: string; +var stringArray: Array; +var jsonValue: JSON; +var voidOrBooleanValue: void | boolean; +var domEventTarget: EventTarget; +var fn: Function; +var object: Object; + +// Callback predefinitions for OpenLayers +var preRenderFunction: ol.PreRenderFunction; +var transformFunction: ol.TransformFunction; +var coordinateFormatType: ol.CoordinateFormatType; +var featureStyleFunction: ol.FeatureStyleFunction; +var featureLoader: ol.FeatureLoader; +var easingFunction: (t: number) => number; +var drawGeometryFunction: ol.interaction.DrawGeometryFunctionType; + +// Type variables for OpenLayers +var attribution: ol.Attribution; +var boundingCoordinates: Array; +var circle: ol.geom.Circle; +var color: ol.Color; +var coordinate: ol.Coordinate; +var coordinatesArray: Array; +var coordinatesArrayDim2: Array>; +var extent: ol.Extent; +var olEvent: ol.events.Event; +var eventKey: ol.events.Key; +var eventKeyArray: Array; +var eventKeyMixed: ol.events.Key | Array; +var eventTarget: ol.events.EventTarget; +var feature: ol.Feature; +var featureArray: Array; +var featureCollection: ol.Collection; +var featureFormat: ol.format.Feature; +var featureUrlFunction: ol.FeatureUrlFunction; +var graticule: ol.Graticule; +var geometriesArray: Array; +var geometry: ol.geom.Geometry; +var geometryCollection: ol.geom.GeometryCollection; +var geometryLayout: ol.geom.GeometryLayout; +var geometryType: ol.geom.GeometryType; +var linearRing: ol.geom.LinearRing; +var lineString: ol.geom.LineString; +var loadingStrategy: ol.LoadingStrategy; +var logoOptions: olx.LogoOptions; +var mapBrowserEvent: ol.MapBrowserEvent; +var multiLineString: ol.geom.MultiLineString; +var multiPoint: ol.geom.MultiPoint; +var multiPolygon: ol.geom.MultiPolygon; +var point: ol.geom.Point; +var polygon: ol.geom.Polygon; +var projection: ol.proj.Projection; +var projectionLike: ol.proj.ProjectionLike; +var simpleGeometry: ol.geom.SimpleGeometry; +var size: ol.Size; +var style: ol.style.Style; +var styleArray: Array; +var styleFunction: ol.style.StyleFunction; +var tilegrid: ol.tilegrid.TileGrid; +var transformFn: ol.TransformFunction; +var vectorSource: ol.source.Vector; +var units: ol.proj.Units; + +// +// ol.Attribution +// + +var attribution: ol.Attribution = new ol.Attribution({ + html: stringValue, +}); + +// +// ol.color +// +color = ol.color.asArray(color); +color = ol.color.asArray(stringValue); +stringValue = ol.color.asString(color); +stringValue = ol.color.asString(stringValue); + +// +// ol.extent +// +transformFunction = function (input: number[]) { + var returnData: number[]; + return returnData; +}; +transformFunction = function (input: number[], output: number[]) { + var returnData: number[]; + return returnData; +}; +transformFunction = function (input: number[], output: number[], dimension: number) { + var returnData: number[]; + return returnData; +} +extent = ol.extent.applyTransform(extent, transformFunction); +ol.extent.applyTransform(extent, transformFunction, extent); +extent = ol.extent.boundingExtent(boundingCoordinates) +extent = ol.extent.buffer(extent, numberValue); +ol.extent.buffer(extent, numberValue, extent); +booleanValue = ol.extent.containsCoordinate(extent, coordinate); +booleanValue = ol.extent.containsExtent(extent, extent); +booleanValue = ol.extent.containsXY(extent, numberValue, numberValue); +extent = ol.extent.createEmpty(); +booleanValue = ol.extent.equals(extent, extent); +extent = ol.extent.extend(extent, extent); +coordinate = ol.extent.getBottomLeft(extent); +coordinate = ol.extent.getBottomRight(extent); +coordinate = ol.extent.getCenter(extent); +numberValue = ol.extent.getHeight(extent); +extent = ol.extent.getIntersection(extent, extent); +ol.extent.getIntersection(extent, extent, extent); +size = ol.extent.getSize(extent); +coordinate = ol.extent.getTopLeft(extent); +coordinate = ol.extent.getTopRight(extent); +numberValue = ol.extent.getWidth(extent); +booleanValue = ol.extent.intersects(extent, extent); +booleanValue = ol.extent.isEmpty(extent); + +// +// ol.featureloader +// +featureLoader = ol.featureloader.xhr(stringValue, featureFormat); + +// +// ol.loadingstrategy +// +loadingStrategy = ol.loadingstrategy.all; +loadingStrategy = ol.loadingstrategy.bbox; +loadingStrategy = ol.loadingstrategy.tile(tilegrid); + +// +// +// ol.geom.Circle +// +booleanValue = circle.intersectsExtent(extent); +circle = circle.transform(projectionLike, projectionLike); + +// +// +// ol.geom.Geometry +// +var geometryResult: ol.geom.Geometry; +coordinate = geometryResult.getClosestPoint(coordinate); +geometryResult.getClosestPoint(coordinate, coordinate); +extent = geometryResult.getExtent(); +geometryResult.getExtent(extent); +geometryResult.transform(projectionLike, projectionLike); + +// +// +// ol.geom.GeometryCollection +// +geometryCollection = new ol.geom.GeometryCollection(geometriesArray) +geometryCollection = new ol.geom.GeometryCollection(); +voidValue = geometryCollection.applyTransform(transformFn); +geometryCollection = geometryCollection.clone(); +geometriesArray = geometryCollection.getGeometries(); +geometryType = geometryCollection.getType(); +booleanValue = geometryCollection.intersectsExtent(extent); +voidValue = geometryCollection.setGeometries(geometriesArray); + +// +// +// ol.geom.LinearRing +// +linearRing = new ol.geom.LinearRing(coordinatesArray); +linearRing = new ol.geom.LinearRing(coordinatesArray, geometryLayout); +linearRing = linearRing.clone(); +numberValue = linearRing.getArea(); +coordinatesArray = linearRing.getCoordinates(); +geometryType = linearRing.getType(); +voidValue = linearRing.setCoordinates(coordinatesArray); +voidValue = linearRing.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.LineString +// +lineString = new ol.geom.LineString(coordinatesArray); +lineString = new ol.geom.LineString(coordinatesArray, geometryLayout); +voidValue = lineString.appendCoordinate(coordinate); +lineString = lineString.clone(); +coordinate = lineString.getCoordinateAtM(numberValue); +coordinate = lineString.getCoordinateAtM(numberValue, booleanValue); +coordinatesArray = lineString.getCoordinates(); +numberValue = lineString.getLength(); +geometryType = lineString.getType(); +booleanValue = lineString.intersectsExtent(extent); +voidValue = lineString.setCoordinates(coordinatesArray); +voidValue = lineString.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.MultiLineString +// +var lineStringsArray: Array; + +multiLineString = new ol.geom.MultiLineString(coordinatesArrayDim2); +multiLineString = new ol.geom.MultiLineString(coordinatesArrayDim2, geometryLayout); +voidValue = multiLineString.appendLineString(lineString); +multiLineString = multiLineString.clone(); +coordinate = multiLineString.getCoordinateAtM(numberValue); +coordinate = multiLineString.getCoordinateAtM(numberValue, booleanValue); +coordinate = multiLineString.getCoordinateAtM(numberValue, booleanValue, booleanValue); +coordinatesArrayDim2 = multiLineString.getCoordinates(); +lineString = multiLineString.getLineString(numberValue); +lineStringsArray = multiLineString.getLineStrings(); +geometryType = multiLineString.getType(); +booleanValue = multiLineString.intersectsExtent(extent); +voidValue = multiLineString.setCoordinates(coordinatesArrayDim2); +voidValue = multiLineString.setCoordinates(coordinatesArrayDim2, geometryLayout); + +// +// +// ol.geom.MultiPoint +// +var pointsArray: Array; + +multiPoint = new ol.geom.MultiPoint(coordinatesArray); +multiPoint = new ol.geom.MultiPoint(coordinatesArray, geometryLayout); +voidValue = multiPoint.appendPoint(point); +multiPoint = multiPoint.clone(); +coordinatesArray = multiPoint.getCoordinates(); +point = multiPoint.getPoint(numberValue); +pointsArray = multiPoint.getPoints(); +geometryType = multiPoint.getType(); +booleanValue = multiPoint.intersectsExtent(extent); +voidValue = multiPoint.setCoordinates(coordinatesArray); +voidValue = multiPoint.setCoordinates(coordinatesArray, geometryLayout); + +// +// +// ol.geom.MultiPolygon +// +var coordinatesArrayDim3: Array>>; +var polygonsArray: Array; + +multiPolygon = new ol.geom.MultiPolygon(coordinatesArrayDim3); +multiPolygon = new ol.geom.MultiPolygon(coordinatesArrayDim3, geometryLayout); +voidValue = multiPolygon.appendPolygon(polygon); +multiPolygon = multiPolygon.clone(); +numberValue = multiPolygon.getArea(); +coordinatesArrayDim3 = multiPolygon.getCoordinates(); +coordinatesArrayDim3 = multiPolygon.getCoordinates(booleanValue); +multiPoint = multiPolygon.getInteriorPoints(); +polygon = multiPolygon.getPolygon(numberValue); +polygonsArray = multiPolygon.getPolygons(); +geometryType = multiPolygon.getType(); +booleanValue = multiPolygon.intersectsExtent(extent); +voidValue = multiPolygon.setCoordinates(coordinatesArrayDim3); +voidValue = multiPolygon.setCoordinates(coordinatesArrayDim3, geometryLayout); + +// +// +// ol.geom.Point +// +point = new ol.geom.Point(coordinate); +point = new ol.geom.Point(coordinate, geometryLayout); +point = point.clone(); +coordinate = point.getCoordinates(); +geometryType = point.getType(); +booleanValue = point.intersectsExtent(extent); +voidValue = point.setCoordinates(coordinate); +voidValue = point.setCoordinates(coordinate, geometryLayout); + +// +// +// ol.geom.Polygon +// +var localSphere: ol.Sphere; +var linearRingsArray: Array; + +polygon = new ol.geom.Polygon(coordinatesArrayDim2); +polygon = new ol.geom.Polygon(coordinatesArrayDim2, geometryLayout); +polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue); +polygon = ol.geom.Polygon.circular(localSphere, coordinate, numberValue, numberValue); +polygon = ol.geom.Polygon.fromCircle(circle); +polygon = ol.geom.Polygon.fromCircle(circle, numberValue); +polygon = ol.geom.Polygon.fromCircle(circle, numberValue, numberValue); +polygon = ol.geom.Polygon.fromExtent(extent); +voidValue = polygon.appendLinearRing(linearRing); +polygon = polygon.clone(); +numberValue = polygon.getArea(); +coordinatesArrayDim2 = polygon.getCoordinates(); +coordinatesArrayDim2 = polygon.getCoordinates(booleanValue); +point = polygon.getInteriorPoint(); +linearRing = polygon.getLinearRing(numberValue); +numberValue = polygon.getLinearRingCount(); +linearRingsArray = polygon.getLinearRings(); +geometryType = polygon.getType(); +booleanValue = polygon.intersectsExtent(extent); +voidValue = polygon.setCoordinates([[coordinate]]); +voidValue = polygon.setCoordinates([[coordinate]], geometryLayout); + +// +// +// ol.geom.SimpleGeometry +// +simpleGeometry.applyTransform(transformFn); +coordinate = simpleGeometry.getFirstCoordinate(); +coordinate = simpleGeometry.getLastCoordinate(); +geometryLayout = simpleGeometry.getLayout(); +voidValue = simpleGeometry.translate(numberValue, numberValue); + +// +// ol.source +// +var featureCallback: (f: ol.Feature) => any; +vectorSource = new ol.source.Vector({ + attributions: [attribution], + features: featureCollection, + format: featureFormat, + loader: featureLoader, + logo: logoOptions, + strategy: loadingStrategy, + url: stringValue, + useSpatialIndex: booleanValue, + wrapX: booleanValue +}); +vectorSource = new ol.source.Vector({ + features: featureArray +}); +vectorSource = new ol.source.Vector({ + url: featureUrlFunction, + loader: featureLoader +}); +voidValue = vectorSource.addFeature(feature); +voidValue = vectorSource.addFeatures(featureArray); +voidValue = vectorSource.clear(); +voidValue = vectorSource.clear(booleanValue); +anyValue = vectorSource.forEachFeature(featureCallback); +anyValue = vectorSource.forEachFeature(featureCallback, object); +anyValue = vectorSource.forEachFeatureInExtent(extent, featureCallback, object); +anyValue = vectorSource.forEachFeatureIntersectingExtent(extent, featureCallback, object); +feature = vectorSource.getClosestFeatureToCoordinate(coordinate); +extent = vectorSource.getExtent(); +feature = vectorSource.getFeatureById(stringValue); +feature = vectorSource.getFeatureById(numberValue); +featureArray = vectorSource.getFeatures(); +featureArray = vectorSource.getFeaturesAtCoordinate(coordinate); +featureCollection = vectorSource.getFeaturesCollection(); +featureArray = vectorSource.getFeaturesInExtent(extent); +voidValue = vectorSource.removeFeature(feature); + +// +// ol.Feature +// +feature = new ol.Feature(); +feature = new ol.Feature(geometry); +feature = new ol.Feature({ + geometry: geometry, + a: numberValue, + b: stringValue, + c: null, + d: object +}); +feature = feature.clone(); +geometry = feature.getGeometry(); +stringValue = feature.getGeometryName(); +var featureGetId: string | number = feature.getId(); +var featureGetStyle: ol.style.Style | Array | ol.FeatureStyleFunction = feature.getStyle(); +featureStyleFunction = feature.getStyleFunction(); +voidValue = feature.setGeometry(geometry); +voidValue = feature.setGeometryName(stringValue); +voidValue = feature.setId(stringValue); +voidValue = feature.setId(numberValue); +voidValue = feature.setStyle(style); +voidValue = feature.setStyle(styleArray); +voidValue = feature.setStyle(featureStyleFunction); +voidValue = feature.setProperties(object); + +// +// ol.View +// + +var view: ol.View = new ol.View({ + center: [0, 0], + zoom: numberValue, +}); + +// +// ol.layer.Tile +// +var tileLayer: ol.layer.Tile = new ol.layer.Tile({ + source: new ol.source.MapQuest({ layer: 'osm' }) +}); + +// +// ol.Object +// +var olObject: ol.Object = new ol.Object({ + a: numberValue, + b: stringValue, + c: booleanValue, + d: voidValue, + e: object, + f: fn +}); +anyValue = olObject.get(stringValue); +stringArray = olObject.getKeys(); +object = olObject.getProperties(); +voidValue = olObject.set(stringValue, anyValue); +voidValue = olObject.set(stringValue, anyValue, booleanValue); +voidValue = olObject.setProperties(object, booleanValue); +voidValue = olObject.unset(stringValue, booleanValue); + +// +// ol.Observable +// +ol.Observable.unByKey(eventKey); +var observable: ol.Observable = new ol.Observable(); +voidValue = observable.changed(); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue}); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue, target: domEventTarget}); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue, target: eventTarget}); +voidOrBooleanValue = observable.dispatchEvent({type: stringValue, a: numberValue, b: stringValue, c: booleanValue, d: null, e: {}}); +voidOrBooleanValue = observable.dispatchEvent(olEvent); +voidOrBooleanValue = observable.dispatchEvent(stringValue); +numberValue = observable.getRevision(); +eventKeyMixed = observable.on(stringValue, fn); +eventKeyMixed = observable.on([stringValue, stringValue], fn, {}); +eventKeyMixed = observable.once(stringValue, fn); +eventKeyMixed = observable.once([stringValue, stringValue], fn, {}); +voidValue = observable.un(stringValue, fn); +voidValue = observable.un([stringValue, stringValue], fn, {}); +voidValue = observable.unByKey(eventKey); +voidValue = observable.unByKey(eventKeyArray); + +// +// ol.proj +// +var getPointResolutionFn: (n: number, c: ol.Coordinate) => number; +projection = new ol.proj.Projection({ + code:stringValue, +}); +stringValue = projection.getCode(); +extent = projection.getExtent(); +numberValue = projection.getMetersPerUnit(); +numberValue = projection.getPointResolution(numberValue, coordinate); +units = projection.getUnits(); +extent = projection.getWorldExtent(); +booleanValue = projection.isGlobal(); +voidValue = projection.setExtent(extent); +voidValue = projection.setGetPointResolution(getPointResolutionFn); +voidValue = projection.setGlobal(booleanValue); +voidValue = projection.setWorldExtent(extent); + +// +// ol.Map +// + +var map: ol.Map = new ol.Map({ + view: view, + layers: [tileLayer], + target: stringValue +}); +voidValue = map.beforeRender(preRenderFunction); + +// +// ol.source.ImageWMS +// +var imageWMS: ol.source.ImageWMS = new ol.source.ImageWMS({ + serverType: stringValue, + url:stringValue +}); + +// +// ol.source.Source +// +const source = imageWMS as ol.source.Source; +projection = source.getProjection(); + +// +// ol.source.TileWMS +// +var tileWMS: ol.source.TileWMS = new ol.source.TileWMS({ + params: {}, + serverType: stringValue, + url:stringValue +}); + +voidValue = tileWMS.updateParams(tileWMS.getParams()); +stringValue = tileWMS.getGetFeatureInfoUrl([0, 0], 1, "EPSG:4326", {}); + +// +// ol.source.WMTS +// +var wmts: ol.source.WMTS = new ol.source.WMTS({ + tileGrid: new ol.tilegrid.WMTS({}), + layer: "", + style: "", + matrixSet: "", + wrapX: true +}); + +// +// ol.animation +// +var bounceOptions: olx.animation.BounceOptions; +bounceOptions.duration = numberValue; +bounceOptions.start = numberValue; +bounceOptions.resolution = numberValue; +bounceOptions.easing = easingFunction; +preRenderFunction = ol.animation.bounce(bounceOptions); + +var panOptions: olx.animation.PanOptions; +panOptions.duration = numberValue; +panOptions.start = numberValue; +panOptions.source = coordinate; +panOptions.easing = easingFunction; +preRenderFunction = ol.animation.pan(panOptions); + +var rotateOptions: olx.animation.RotateOptions; +rotateOptions.duration = numberValue; +rotateOptions.start = numberValue; +rotateOptions.anchor = coordinate; +rotateOptions.rotation = numberValue; +rotateOptions.easing = easingFunction; +preRenderFunction = ol.animation.rotate(rotateOptions); + +var zoomOptions: olx.animation.ZoomOptions; +zoomOptions.duration = numberValue; +zoomOptions.start = numberValue; +zoomOptions.resolution = numberValue; +zoomOptions.easing = easingFunction; +preRenderFunction = ol.animation.zoom(zoomOptions); +voidValue = map.beforeRender(preRenderFunction); + +// +// ol.coordinate +// +coordinate = ol.coordinate.add(coordinate, coordinate); +coordinateFormatType = ol.coordinate.createStringXY(); +coordinateFormatType = ol.coordinate.createStringXY(numberValue); +stringValue = ol.coordinate.format(coordinate, stringValue); +stringValue = ol.coordinate.format(coordinate, stringValue, numberValue); +coordinate = ol.coordinate.rotate(coordinate, numberValue); +stringValue = ol.coordinate.toStringHDMS(); +stringValue = ol.coordinate.toStringHDMS(coordinate); +stringValue = ol.coordinate.toStringXY(); +stringValue = ol.coordinate.toStringXY(coordinate); +stringValue = ol.coordinate.toStringXY(coordinate, numberValue); + +// +// ol.easing +// +easingFunction = ol.easing.easeIn; +easingFunction = ol.easing.easeOut; +easingFunction = ol.easing.inAndOut; +easingFunction = ol.easing.linear; +easingFunction = ol.easing.upAndDown; + +// +// ol.Geolocation +// +var geolocation: ol.Geolocation = new ol.Geolocation({ + projection: projection +}); +coordinate = geolocation.getPosition(); + +// +// ol.Graticule +// + +graticule = new ol.Graticule(); +graticule = new ol.Graticule({ + map: map, +}); +var graticuleMap: ol.Map = graticule.getMap(); +var graticuleMeridians: Array = graticule.getMeridians(); +var graticuleParallels: Array = graticule.getParallels(); +voidValue = graticule.setMap(graticuleMap); + +// +// ol.DeviceOrientation +// + +var deviceOrientation: ol.DeviceOrientation = new ol.DeviceOrientation({ + tracking: true, +}); +numberValue = deviceOrientation.getHeading(); + +// +// ol.Overlay +// + +var popup: ol.Overlay = new ol.Overlay({ + element: document.getElementById('popup') +}); +voidValue = map.addOverlay(popup); +var popupElement: Element = popup.getElement(); +var popupMap: ol.Map = popup.getMap(); +var popupOffset: Array = popup.getOffset(); +coordinate = popup.getPosition(); +var popupPositioning: ol.OverlayPositioning = popup.getPositioning(); +voidValue = popup.setElement(popupElement); +voidValue = popup.setMap(popupMap); +voidValue = popup.setOffset(popupOffset); +voidValue = popup.setPosition(coordinate); +voidValue = popup.setPositioning(popupPositioning); + + +// +// ol.format.GeoJSON +// + +var geojsonOptions: olx.format.GeoJSONOptions; +geojsonOptions.defaultDataProjection = "EPSG"; +geojsonOptions.defaultDataProjection = projection; +geojsonOptions.geometryName = "geom"; + +var geojsonFormat: ol.format.GeoJSON; +geojsonFormat = new ol.format.GeoJSON(); +geojsonFormat = new ol.format.GeoJSON(geojsonOptions); + +// Test options +var readOptions: olx.format.ReadOptions; +readOptions.dataProjection = "EPSG"; +readOptions.dataProjection = projection; +readOptions.featureProjection = "EPSG"; +readOptions.featureProjection = projection; + +var writeOptions: olx.format.WriteOptions; +writeOptions.dataProjection = "EPSG"; +writeOptions.dataProjection = projection; +writeOptions.featureProjection = "EPSG"; +writeOptions.featureProjection = projection; +writeOptions.rightHanded = false; + +// Test functions +feature = geojsonFormat.readFeature("json"); +feature = geojsonFormat.readFeature("json", readOptions); +featureArray = geojsonFormat.readFeatures("json"); +featureArray = geojsonFormat.readFeatures("json", readOptions); +geometry = geojsonFormat.readGeometry("geometry"); +geometry = geojsonFormat.readGeometry("geometry", readOptions); +stringValue = geojsonFormat.writeFeature(feature); +stringValue = geojsonFormat.writeFeature(feature, writeOptions); +stringValue = geojsonFormat.writeFeatures(featureArray); +stringValue = geojsonFormat.writeFeatures(featureArray, writeOptions); +stringValue = geojsonFormat.writeGeometry(geometry); +stringValue = geojsonFormat.writeGeometry(geometry, writeOptions); +jsonValue = geojsonFormat.writeFeatureObject(feature); +jsonValue = geojsonFormat.writeFeatureObject(feature, writeOptions); +jsonValue = geojsonFormat.writeFeaturesObject(featureArray); +jsonValue = geojsonFormat.writeFeaturesObject(featureArray, writeOptions); +jsonValue = geojsonFormat.writeGeometryObject(geometry); +jsonValue = geojsonFormat.writeGeometryObject(geometry, writeOptions); + +// +// ol.interactions +// +var modify: ol.interaction.Modify = new ol.interaction.Modify({ + features: new ol.Collection(featureArray) +}); + +var draw: ol.interaction.Draw = new ol.interaction.Draw({ + type: "Point", + clickTolerance: numberValue, + features: new ol.Collection([]), + source: vectorSource, + snapTolerance: numberValue, + maxPoints: numberValue, + minPoints: numberValue, + style: style, + geometryFunction: drawGeometryFunction, + geometryName: stringValue, + condition: ol.events.condition.never, + freehandCondition: ol.events.condition.never, + wrapX: booleanValue +}); +draw = new ol.interaction.Draw({ + type: "Point", + style: styleArray +}); +draw = new ol.interaction.Draw({ + type: "Point", + style: styleFunction +}); + +var dragbox: ol.interaction.DragBox = new ol.interaction.DragBox({ + className: stringValue, + condition: ol.events.condition.always, + boxEndCondition: function (mapBrowserEvent: ol.MapBrowserEvent, startPixel: ol.Pixel, endPixel: ol.Pixel) { + var width: number = endPixel[0] - startPixel[0]; + var height: number = endPixel[1] - startPixel[1]; + return booleanValue; + } +}); +polygon = dragbox.getGeometry(); + +var interaction: ol.interaction.Interaction = new ol.interaction.Interaction({ + handleEvent: function (e: ol.MapBrowserEvent) { + return booleanValue; + } +}); +booleanValue = interaction.handleEvent(mapBrowserEvent); +booleanValue = interaction.getActive(); +map = interaction.getMap(); +voidValue = interaction.setActive(true); + + + +const select: ol.interaction.Select = new ol.interaction.Select({ + layers: (layer: ol.layer.Layer) => true, +}); diff --git a/openlayers/openlayers-3.14.2.d.ts b/openlayers/openlayers-3.14.2.d.ts new file mode 100644 index 0000000000..f8ca153820 --- /dev/null +++ b/openlayers/openlayers-3.14.2.d.ts @@ -0,0 +1,4873 @@ +// Type definitions for OpenLayers v3.14.2 +// Project: http://openlayers.org/ +// Definitions by: Wouter Goedhart +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// we can't use Object, Event, EventTarget, etc within the namespace because they would refer to OpenLayer's versions. +declare type GlobalObject = Object; +declare type GlobalEvent = Event; +declare type GlobalEventTarget = EventTarget; + +declare namespace olx { + + interface AttributionOptions { + + /** HTML markup for this attribution. */ + html: string; + } + + interface DeviceOrientationOptions { + + /** + * Start tracking. Default is false. + */ + tracking?: boolean; + } + + interface FrameState { + + /** + * + */ + pixelRatio: number; + + /** + * + */ + time: number; + + /** + * + */ + viewState: olx.ViewState; + } + + interface FeatureOverlayOptions { + + /** + * Features + */ + features?: Array | ol.Collection | ol.style.StyleFunction; + + /** + * Map + */ + map: ol.Map; + + /** + * Style + */ + style: ol.style.Style | Array; + } + + interface GeolocationOptions { + + /** + * Start Tracking. Default is false. + */ + tracking?: boolean; + + /** + * Tracking options. See http://www.w3.org/TR/geolocation-API/#position_options_interface. + */ + trackingOptions?: PositionOptions; + + /** + * The projection the position is reported in. + */ + projection?: ol.proj.ProjectionLike | ol.proj.Projection; + } + + interface GraticuleOptions { + + /** Reference to an ol.Map object. */ + map?: ol.Map; + + /** The maximum number of meridians and parallels from the center of the map. The default value is 100, which means that at most 200 meridians and 200 parallels will be displayed. The default value is appropriate for conformal projections like Spherical Mercator. If you increase the value more lines will be drawn and the drawing performance will decrease. */ + maxLines?: number; + + /** The stroke style to use for drawing the graticule. If not provided, the lines will be drawn with rgba(0,0,0,0.2), a not fully opaque black. */ + strokeStyle?: ol.style.Stroke; + + /** The target size of the graticule cells, in pixels. Default value is 100 pixels. */ + targetSize?: number; + } + + interface BaseWMSOptions { + + /** Attributions. */ + attributions?: Array; + + /** WMS request parameters. At least a LAYERS param is required. STYLES is '' by default. VERSION is 1.3.0 by default. WIDTH, HEIGHT, BBOX and CRS (SRS for WMS version < 1.3.0) will be set dynamically. */ + params?: any; + + /** The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail. */ + crossOrigin?: string; + + /** experimental Use the ol.Map#pixelRatio value when requesting the image from the remote server. Default is true. */ + hidpi?: boolean; + + /** experimental The type of the remote WMS server: mapserver, geoserver or qgis. Only needed if hidpi is true. Default is undefined. */ + serverType?: ol.source.wms.ServerType; + + /** WMS service URL. */ + url?: string; + + /** Logo. */ + logo?: olx.LogoOptions; + + /** experimental Projection. */ + projection?: ol.proj.ProjectionLike; + } + + interface ImageWMSOptions extends BaseWMSOptions { + + /** experimental Optional function to load an image given a URL. */ + imageLoadFunction?: ol.ImageLoadFunctionType; + + /** Ratio. 1 means image requests are the size of the map viewport, 2 means twice the width and height of the map viewport, and so on. Must be 1 or higher. Default is 1.5. */ + ratio?: number; + + /** Resolutions. If specified, requests will be made for these resolutions only. */ + resolutions?: Array; + } + + interface TileWMSOptions { + + attributions?: Array; + + /**WMS request parameters. At least a LAYERS param is required. STYLES is '' by default. VERSION is 1.3.0 by default. WIDTH, HEIGHT, BBOX and CRS (SRS for WMS version < 1.3.0) will be set dynamically. Required.*/ + params: GlobalObject; + /**The crossOrigin attribute for loaded images. Note that you must provide a crossOrigin value if you are using the WebGL renderer or if you want to access pixel data with the Canvas renderer. See https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image for more detail.*/ + crossOrigin?: string; + + /** The size in pixels of the gutter around image tiles to ignore. By setting this property to a non-zero value, images will be requested that are wider and taller than the tile size by a value of 2 x gutter. Defaults to zero. Using a non-zero value allows artifacts of rendering at tile edges to be ignored. If you control the WMS service it is recommended to address "artifacts at tile edges" issues by properly configuring the WMS service. For example, MapServer has a tile_map_edge_buffer configuration parameter for this. See http://mapserver.org/output/tile_mode.html. */ + gutter?: number; + + /** Use the ol.Map#pixelRatio value when requesting the image from the remote server. Default is true.*/ + hidpi?: boolean; + + logo?: string | olx.LogoOptions; + + /** Tile grid. Base this on the resolutions, tilesize and extent supported by the server. If this is not defined, a default grid will be used: if there is a projection extent, the grid will be based on that; if not, a grid based on a global extent with origin at 0,0 will be used. */ + tileGrid?: ol.tilegrid.TileGrid; + + /** experimental Maximum zoom. */ + maxZoom?: number; + + projection?: ol.proj.ProjectionLike; + reprojectionErrorThreshold?: number; + + /** experimental Optional function to load a tile given a URL. */ + tileLoadFunction?: ol.TileLoadFunctionType; + + /** WMS service URL. */ + url?: string; + + /** WMS service urls. Use this instead of url when the WMS supports multiple urls for GetMap requests. */ + urls?: Array; + + /** experimental The type of the remote WMS server. Currently only used when hidpi is true. Default is undefined. */ + serverType?: ol.source.wms.ServerType; + + /** experimental Whether to wrap the world horizontally. When set to false, only one world will be rendered. When true, tiles will be requested for one world only, but they will be wrapped horizontally to render multiple worlds. The default is true. */ + wrapX?: boolean; + } + /** + * Object literal with config options for the map logo. + */ + interface LogoOptions { + /** + * Link url for the logo. Will be followed when the logo is clicked. + */ + href: string; + + /** + * Image src for the logo + */ + src: string; + + } + + interface MapOptions { + + /** Controls initially added to the map. If not specified, ol.control.defaults() is used. */ + controls?: any; + + /** The ratio between physical pixels and device-independent pixels (dips) on the device. If undefined then it gets set by using window.devicePixelRatio. */ + pixelRatio?: number; + + /** Interactions that are initially added to the map. If not specified, ol.interaction.defaults() is used. */ + interactions?: any; + + /** The element to listen to keyboard events on. This determines when the KeyboardPan and KeyboardZoom interactions trigger. For example, if this option is set to document the keyboard interactions will always trigger. If this option is not specified, the element the library listens to keyboard events on is the map target (i.e. the user-provided div for the map). If this is not document the target element needs to be focused for key events to be emitted, requiring that the target element has a tabindex attribute. */ + keyboardEventTarget?: any; + + /** Layers. If this is not defined, a map with no layers will be rendered. Note that layers are rendered in the order supplied, so if you want, for example, a vector layer to appear on top of a tile layer, it must come after the tile layer. */ + layers?: Array + + /** When set to true, tiles will be loaded during animations. This may improve the user experience, but can also make animations stutter on devices with slow memory. Default is false. */ + loadTilesWhileAnimating?: boolean; + + /** When set to true, tiles will be loaded while interacting with the map. This may improve the user experience, but can also make map panning and zooming choppy on devices with slow memory. Default is false. */ + loadTilesWhileInteracting?: boolean; + + /** The map logo. A logo to be displayed on the map at all times. If a string is provided, it will be set as the image source of the logo. If an object is provided, the src property should be the URL for an image and the href property should be a URL for creating a link. To disable the map logo, set the option to false. By default, the OpenLayers 3 logo is shown. */ + logo?: any; + + /** Overlays initially added to the map. By default, no overlays are added. */ + overlays?: any; + + /** Renderer. By default, Canvas, DOM and WebGL renderers are tested for support in that order, and the first supported used. Specify a ol.RendererType here to use a specific renderer. Note that at present only the Canvas renderer supports vector data. */ + renderer?: any; + + /** The container for the map, either the element itself or the id of the element. If not specified at construction time, ol.Map#setTarget must be called for the map to be rendered. */ + target?: any; + + /** The map's view. No layer sources will be fetched unless this is specified at construction time or through ol.Map#setView. */ + view?: ViewOptions; + } + + interface OverlayOptions { + + /** + * The overlay element. + */ + element?: Element; + + /** + * Offsets in pixels used when positioning the overlay. The fist element in the array is the horizontal offset. A positive value shifts the overlay right. The second element in the array is the vertical offset. A positive value shifts the overlay down. Default is [0, 0]. + */ + offset?: Array; + + /** + * The overlay position in map projection. + */ + position?: ol.Coordinate; + + /** + * Defines how the overlay is actually positioned with respect to its position property. Possible values are 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', and 'top-right'. Default is 'top-left'. + */ + positioning?: ol.OverlayPositioning; + + /** + * Whether event propagation to the map viewport should be stopped. Default is true. If true the overlay is placed in the same container as that of the controls (CSS class name ol-overlaycontainer-stopevent); if false it is placed in the container with CSS class name ol-overlaycontainer. + */ + stopEvent?: boolean; + + /** + * Whether the overlay is inserted first in the overlay container, or appended. Default is true. If the overlay is placed in the same container as that of the controls (see the stopEvent option) you will probably set insertFirst to true so the overlay is displayed below the controls. + */ + insertFirst?: boolean; + + /** + * If set to true the map is panned when calling setPosition, so that the overlay is entirely visible in the current viewport. The default is false. + */ + autoPan?: boolean; + + /** + * The options used to create a ol.animation.pan animation. This animation is only used when autoPan is enabled. By default the default options for ol.animation.pan are used. If set to null the panning is not animated. + */ + autoPanAnimation?: olx.animation.PanOptions; + + /** + * The margin (in pixels) between the overlay and the borders of the map when autopanning. The default is 20. + */ + autoPanMargin?: number; + } + + interface ViewOptions { + + /** The initial center for the view. The coordinate system for the center is specified with the projection option. Default is undefined, and layer sources will not be fetched if this is not set. */ + center?: ol.Coordinate; + + /** Rotation constraint. false means no constraint. true means no constraint, but snap to zero near zero. A number constrains the rotation to that number of values. For example, 4 will constrain the rotation to 0, 90, 180, and 270 degrees. The default is true. */ + constrainRotation?: boolean; + + /** Enable rotation. Default is true. If false a rotation constraint that always sets the rotation to zero is used. The constrainRotation option has no effect if enableRotation is false. */ + enableRotation?: boolean; + + /**The extent that constrains the center, in other words, center cannot be set outside this extent. Default is undefined. */ + extent?: ol.Extent; + + /** The maximum resolution used to determine the resolution constraint. It is used together with minResolution (or maxZoom) and zoomFactor. If unspecified it is calculated in such a way that the projection's validity extent fits in a 256x256 px tile. If the projection is Spherical Mercator (the default) then maxResolution defaults to 40075016.68557849 / 256 = 156543.03392804097. */ + maxResolution?: number; + + /** The minimum resolution used to determine the resolution constraint. It is used together with maxResolution (or minZoom) and zoomFactor. If unspecified it is calculated assuming 29 zoom levels (with a factor of 2). If the projection is Spherical Mercator (the default) then minResolution defaults to 40075016.68557849 / 256 / Math.pow(2, 28) = 0.0005831682455839253. */ + minResolution?: number; + + /** The maximum zoom level used to determine the resolution constraint. It is used together with minZoom (or maxResolution) and zoomFactor. Default is 28. Note that if minResolution is also provided, it is given precedence over maxZoom. */ + maxZoom?: number; + + /** The minimum zoom level used to determine the resolution constraint. It is used together with maxZoom (or minResolution) and zoomFactor. Default is 0. Note that if maxResolution is also provided, it is given precedence over minZoom. */ + minZoom?: number; + + /** The projection. Default is EPSG:3857 (Spherical Mercator). */ + projection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** The initial resolution for the view. The units are projection units per pixel (e.g. meters per pixel). An alternative to setting this is to set zoom. Default is undefined, and layer sources will not be fetched if neither this nor zoom are defined. */ + resolution?: number; + + /** Resolutions to determine the resolution constraint. If set the maxResolution, minResolution, minZoom, maxZoom, and zoomFactor options are ignored. */ + resolutions?: Array; + + /** The initial rotation for the view in radians (positive rotation clockwise). Default is 0. */ + rotation?: number; + + /** Only used if resolution is not defined. Zoom level used to calculate the initial resolution for the view. The initial resolution is determined using the ol.View#constrainResolution method. */ + zoom?: number; + + /** The zoom factor used to determine the resolution constraint. Default is 2. */ + zoomFactor?: number; + } + + interface ViewState { + + /** + * + */ + center: ol.Coordinate; + + /** + * + */ + projection: ol.proj.Projection; + + /** + * + */ + resolution: number; + + /** + * + */ + rotation: number; + } + + interface Projection { + /** + * The SRS identifier code, e.g. EPSG:4326. + */ + code: string; + + /** + * Units. Required unless a proj4 projection is defined for code. + */ + units?: ol.proj.Units; + + /** + * The validity extent for the SRS. + */ + extent?: Array; + + /** + * The axis orientation as specified in Proj4. The default is enu. + */ + axisOrientation?: string; + + /** + * Whether the projection is valid for the whole globe. Default is false. + */ + global?: boolean; + + /** + * experimental The world extent for the SRS. + */ + worldExtent?: ol.Extent; + + /** + * experimental Function to determine resolution at a point. The function is called with + * a {number} view resolution and an {ol.Coordinate} as arguments, and returns the {number} + * resolution at the passed coordinate. + */ + getPointResolution?: (resolution: number, coordinate: ol.Coordinate) => number; + } + + namespace animation { + + interface BounceOptions { + + /** + * The resolution to start the bounce from, typically map.getView().getResolution(). + */ + resolution: number; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number; + } + + interface PanOptions { + + /** + * The resolution to start the bounce from, typically map.getView().getResolution(). + */ + source: ol.Coordinate; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number; + } + + interface RotateOptions { + + /** + * The rotation value (in radians) to begin rotating from, typically map.getView().getRotation(). If undefined then 0 is assumed. + */ + rotation?: number; + + /** + * The rotation center/anchor. The map rotates around the center of the view if unspecified. + */ + anchor?: ol.Coordinate; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number + } + + interface ZoomOptions { + + /** + * The resolution to begin zooming from, typically map.getView().getResolution(). + */ + resolution: number; + + /** + * The start time of the animation. Default is immediately. + */ + start?: number; + + /** + * The duration of the animation in milliseconds. Default is 1000. + */ + duration?: number; + + /** + * The easing function to use. Can be an ol.easing or a custom function. Default is ol.easing.upAndDown. + */ + easing?: (t: number) => number + } + } + + namespace control { + + interface DefaultsOptions { + + /** + * Attribution. Default is true. + */ + attribution?: boolean; + + /** + * Attribution options. + */ + //TODO: Replace with olx.control.AttributionOptions + attributionOptions?: any; + + /** + * Rotate. Default is true; + */ + rotate?: boolean; + + /** + * Rotate options + */ + //TODO: Replace with olx.control.RotateOptions + rotateOptions?: any; + + /** + * Zoom. Default is true + */ + zoom?: boolean; + + /** + * + */ + //TODO: Replace with olx.control.ZoomOptions + zoomOptions?: any; + } + } + + namespace interaction { + interface DefaultsOptions { + altShiftDragRotate?: boolean; + doubleClickZoom?: boolean; + keyboard?: boolean; + mouseWheelZoom?: boolean; + shiftDragZoom?: boolean; + dragPan?: boolean; + pinchRotate?: boolean; + pinchZoom?: boolean; + zoomDelta?: number; + zoomDuration?: number; + } + interface DragBoxOptions { + className?: string + condition?: ol.events.ConditionType + boxEndCondition?: ol.interaction.DragBoxEndConditionType + } + interface InteractionOptions { + handleEvent (e: ol.MapBrowserEvent): boolean + } + interface ModifyOptions { + deleteCondition?: ol.events.ConditionType; + pixelTolerance?: number; + style?: ol.style.Style | Array | ol.style.StyleFunction; + features: ol.Collection; + wrapX?: boolean; + } + interface DrawOptions { + clickTolerance?: number; + features?: ol.Collection; + source?: ol.source.Vector; + snapTolerance?: number; + type: ol.geom.GeometryType; + maxPoints?: number; + minPoints?: number; + style?: ol.style.Style | Array | ol.style.StyleFunction; + geometryFunction?: ol.interaction.DrawGeometryFunctionType; + geometryName?: string; + condition?: ol.events.ConditionType; + freehandCondition?: ol.events.ConditionType; + wrapX?: boolean; + } + interface PointerOptions { + handleDownEvent?: (e: ol.MapBrowserPointerEvent) => boolean; + handleDragEvent?: (e: ol.MapBrowserPointerEvent) => void; + handleEvent?: (e: ol.MapBrowserEvent) => boolean; + handleMoveEvent?: (e: ol.MapBrowserPointerEvent) => void; + handleUpEvent?: (e: ol.MapBrowserPointerEvent) => boolean; + } + interface SelectOptions { + addCondition?: ol.events.ConditionType; + condition?: ol.events.ConditionType; + layers?: Array | ((layer: ol.layer.Layer) => boolean); + style?: ol.style.Style | Array | ol.style.StyleFunction; + removeCondition?: ol.events.ConditionType; + toggleCondition?: ol.events.ConditionType; + multi?: boolean; + features?: ol.Collection; + filter?: ol.interaction.SelectFilterFunction; + wrapX?: boolean; + } + } + + namespace layer { + + interface BaseOptions { + /** + * Opacity (0, 1). Default is 1. + */ + opacity?: number; + + /** + * Visibility. Default is true. + */ + visible?: boolean; + + /** + * The bounding extent for layer rendering. The layer will not be rendered outside of this extent. + */ + extent?: ol.Extent; + + zIndex?: number; + /** + * The minimum resolution (inclusive) at which this layer will be visible. + */ + minResolution?: number; + + /** + * The maximum resolution (exclusive) below which this layer will be visible. + */ + maxResolution?: number; + } + + interface GroupOptions extends BaseOptions { + + /** + * Child layers + */ + layers?: Array | ol.Collection; + } + + interface HeatmapOptions extends VectorOptions { + + /** + * The color gradient of the heatmap, specified as an array of CSS color strings. Default is ['#00f', '#0ff', '#0f0', '#ff0', '#f00']. + */ + gradient?: Array; + + /** + * Radius size in pixels. Default is 8. + */ + radius?: number; + + /** + * Blur size in pixels. Default is 15. + */ + blur?: number; + + /** + * Shadow size in pixels. Default is 250. + */ + shadow?: number; + } + + interface ImageOptions extends LayerOptions { + } + + interface LayerOptions extends BaseOptions { + + /** + * The layer source (or null if not yet set). + */ + source?: ol.source.Source; + } + + interface TileOptions extends LayerOptions { + + /** + * Preload. Load low-resolution tiles up to preload levels. By default preload is 0, which means no preloading. + */ + preload?: number; + + /** + * Source for this layer. + */ + source?: ol.source.Tile; + + /** + * Use interim tiles on error. Default is true. + */ + useInterimTilesOnError?: boolean; + } + + interface VectorOptions extends LayerOptions { + + /** + * Render order. Function to be used when sorting features before rendering. By default features are drawn in the order that they are created. Use null to avoid the sort, but get an undefined draw order. + */ + renderOrder?: (a: ol.Feature, b: ol.Feature) => number; + + map?: ol.Map; + + extent?: ol.Extent; + + minResolution?: number; + + maxResolution?: number; + + opacity?: number; + + /** + * The buffer around the viewport extent used by the renderer when getting features from the vector source for the rendering or hit-detection. Recommended value: the size of the largest symbol, line width or label. Default is 100 pixels. + */ + renderBuffer?: number; + + /** + * Source. + */ + source: ol.source.Vector; + + /** + * Layer style. See ol.style for default style which will be used if this is not defined. + */ + style?: ol.style.Style | Array | ol.style.StyleFunction; + + /** + * When set to true, feature batches will be recreated during animations. This means that no vectors will be shown clipped, but the setting will have a performance impact for large amounts of vector data. When set to false, batches will be recreated when no animation is active. Default is false. + */ + updateWhileAnimating?: boolean; + + /** + * When set to true, feature batches will be recreated during interactions. See also updateWhileInteracting. Default is false. + */ + updateWhileInteracting?: boolean; + + visible?: boolean; + } + } + + namespace source { + + interface VectorOptions { + /** + * Attributions. + */ + attributions?: Array; + + /** + * Features. If provided as {@link ol.Collection}, the features in the source + * and the collection will stay in sync. + */ + features?: Array | ol.Collection; + + /** + * The feature format used by the XHR feature loader when `url` is set. + * Required if `url` is set, otherwise ignored. Default is `undefined`. + */ + format?: ol.format.Feature; + + /** + * The loader function used to load features, from a remote source for example. + * Note that the source will create and use an XHR feature loader when `url` is + * set. + */ + loader?: ol.FeatureLoader; + + /** + * Logo. + */ + logo?: string | olx.LogoOptions; + + /** + * The loading strategy to use. By default an {@link ol.loadingstrategy.all} + * strategy is used, a one-off strategy which loads all features at once. + */ + strategy?: ol.LoadingStrategy; + + /** + * Setting this option instructs the source to use an XHR loader (see + * {@link ol.featureloader.xhr}) and an {@link ol.loadingstrategy.all} for a + * one-off download of all features from that URL. + * Requires `format` to be set as well. + */ + url?: string | ol.FeatureUrlFunction; + + /** + * By default, an RTree is used as spatial index. When features are removed and + * added frequently, and the total number of features is low, setting this to + * `false` may improve performance. + */ + useSpatialIndex?: boolean; + + /** + * Wrap the world horizontally. Default is `true`. For vector editing across the + * -180° and 180° meridians to work properly, this should be set to `false`. The + * resulting geometry coordinates will then exceed the world bounds. + */ + wrapX?: boolean; + } + interface WMTSOptions { + attributions?: Array; + crossOrigin?: string; + logo?: string | olx.LogoOptions; + tileGrid: ol.tilegrid.WMTS; // REQUIRED ! + projection?: ol.proj.ProjectionLike; + reprojectionErrorThreshold?: number; + requestEncoding?: ol.source.WMTSRequestEncoding; + layer: string; //REQUIRED + style: string; //REQUIRED + tileClass?: Function; + tilePixelRatio?: number; + version?: string; + format?: string; + matrixSet: string; //REQUIRED + dimensions?: GlobalObject; + url?: string; + maxZoom?: number; + tileLoadFunction?: ol.TileLoadFunctionType; + urls?: Array; + wrapX: boolean; + } + } + + namespace style { + + interface FillOptions { + color?: ol.Color | string; + } + + interface StyleOptions { + geometry?: string | ol.geom.Geometry | ol.style.GeometryFunction; + fill?: ol.style.Fill; + image?: ol.style.Image; + stroke?: ol.style.Stroke; + text?: ol.style.Text; + zIndex?: number; + } + + interface TextOptions { + font?: string; + offsetX?: number; + offsetY?: number; + scale?: number; + rotation?: number; + text?: string; + textAlign?: string; + textBaseline?: string; + fill?: ol.style.Fill; + stroke?: ol.style.Stroke; + } + interface StrokeOptions { + color?: ol.Color | string; + lineCap?: string; + lineJoin?: string; + lineDash?: Array; + miterLimit?: number; + width?: number; + } + interface IconOptions { + anchor?: Array; + anchorOrigin?: string; + anchorXUnits?: string; + anchorYUnits?: string; + crossOrigin?: string; + img?: ol.Image | HTMLCanvasElement; + offset?: Array; + offsetOrigin?: string; + opacity?: number; + scale?: number; + snapToPixel?: boolean; + rotateWithView?: boolean; + rotation?: number; + size?: ol.Size; + imgSize?: ol.Size; + src?: string; + } + interface CircleOptions { + fill?: ol.style.Fill; + radius: number; + snapToPixel?: boolean; + stroke?: ol.style.Stroke; + } + } + + namespace tilegrid { + + interface TileGridOptions { + + /** + * Extent for the tile grid. No tiles outside this extent will be requested by ol.source.Tile sources. When no origin or origins are configured, the origin will be set to the bottom-left corner of the extent. When no sizes are configured, they will be calculated from the extent. + */ + extent?: ol.Extent; + + /** + * Minimum zoom. Default is 0. + */ + minZoom?: number; + + /** + * Origin, i.e. the bottom-left corner of the grid. Default is null. + */ + origin?: ol.Coordinate; + + /** + * Origins, i.e. the bottom-left corners of the grid for each zoom level. If given, the array length should match the length of the resolutions array, i.e. each resolution can have a different origin. + */ + origins?: Array; + + /** + * Resolutions. The array index of each resolution needs to match the zoom level. This means that even if a minZoom is configured, the resolutions array will have a length of maxZoom + 1. + */ + resolutions?: Array; + + /** + * Tile size. Default is [256, 256]. + */ + tileSize?: number | ol.Size; + + /** + * Tile sizes. If given, the array length should match the length of the resolutions array, i.e. each resolution can have a different tile size. + */ + tileSizes?: Array; + } + + interface WMTSOptions { + + /** + * Extent for the tile grid. No tiles outside this extent will be requested by ol.source.WMTS sources. When no origin or origins are configured, the origin will be calculated from the extent. When no sizes are configured, they will be calculated from the extent. + */ + extent?: ol.Extent; + + /** + * Origin, i.e. the top-left corner of the grid. + */ + origin?: ol.Coordinate; + + /** + * Origins, i.e. the top-left corners of the grid for each zoom level. The length of this array needs to match the length of the resolutions array. + */ + origins?: Array; + + /** + * Resolutions. The array index of each resolution needs to match the zoom level. This means that even if a minZoom is configured, the resolutions array will have a length of maxZoom + 1 + */ + resolutions?: Array; + + /** + * matrix IDs. The length of this array needs to match the length of the resolutions array. + */ + matrixIds?: Array; + + /** + * Number of tile rows and columns of the grid for each zoom level. The values here are the TileMatrixWidth and TileMatrixHeight advertised in the GetCapabilities response of the WMTS, and define the grid's extent together with the origin. An extent can be configured in addition, and will further limit the extent for which tile requests are made by sources. + */ + sizes?: Array; + + /** + * Tile size. + */ + tileSize?: number | ol.Size; + + /** + * Tile sizes. The length of this array needs to match the length of the resolutions array. + */ + tileSizes?: Array; + + /** + * Number of tile columns that cover the grid's extent for each zoom level. Only required when used with a source that has wrapX set to true, and only when the grid's origin differs from the one of the projection's extent. The array length has to match the length of the resolutions array, i.e. each resolution will have a matching entry here. + */ + widths?: Array; + } + + interface XYZOptions { + + /** + * Extent for the tile grid. The origin for an XYZ tile grid is the top-left corner of the extent. The zero level of the grid is defined by the resolution at which one tile fits in the provided extent. If not provided, the extent of the EPSG:3857 projection is used. + */ + extent?: ol.Extent; + + /** + * Maximum zoom. The default is ol.DEFAULT_MAX_ZOOM. This determines the number of levels in the grid set. For example, a maxZoom of 21 means there are 22 levels in the grid set. + */ + maxZoom?: number; + + /** + * Minimum zoom. Default is 0. + */ + minZoom?: number; + + /** + * Tile size in pixels. Default is [256, 256]. + */ + tileSize?: number | ol.Size; + } + + interface ZoomifyOptions { + + /** + * Resolutions + */ + resolutions: Array; + } + } + + namespace view { + + interface FitGeometryOptions { + + /** + * Padding (in pixels) to be cleared inside the view. Values in the array are top, right, bottom and left padding. Default is [0, 0, 0, 0]. + */ + padding?: Array; + + /** + * Constrain the resolution. Default is true. + */ + constrainResolution?: boolean; + + /** + * Get the nearest extent. Default is false. + */ + nearest?: boolean; + + /** + * Minimum resolution that we zoom to. Default is 0. + */ + minResolution?: number; + + /** + * Maximum zoom level that we zoom to. If minResolution is given, this property is ignored. + */ + maxZoom?: number; + } + } + + namespace format { + interface WKTOptions { + /** + * Whether to split GeometryCollections into multiple features on reading. Default is false. + */ + splitCollection?: boolean; + } + + interface GeoJSONOptions { + + /** + * Default data projection. + */ + defaultDataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Geometry name to use when creating features + */ + geometryName?: string; + } + + interface ReadOptions { + + /** + * Projection of the data we are reading. If not provided, the projection will be derived from the data (where possible) or the defaultDataProjection of the format is assigned (where set). If the projection can not be derived from the data and if no defaultDataProjection is set for a format, the features will not be reprojected. + */ + dataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Projection of the feature geometries created by the format reader. If not provided, features will be returned in the dataProjection. + */ + featureProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + } + + interface WriteOptions { + + /** + * Projection of the data we are writing. If not provided, the defaultDataProjection of the format is assigned (where set). If no defaultDataProjection is set for a format, the features will be returned in the featureProjection. + */ + dataProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * Projection of the feature geometries that will be serialized by the format writer. + */ + featureProjection?: ol.proj.ProjectionLike | ol.proj.Projection; + + /** + * When writing geometries, follow the right-hand rule for linear ring orientation. This means that polygons will have counter-clockwise exterior rings and clockwise interior rings. By default, coordinates are serialized as they are provided at construction. If true, the right-hand rule will be applied. If false, the left-hand rule will be applied (clockwise for exterior and counter-clockwise for interior rings). Note that not all formats support this. The GeoJSON format does use this property when writing geometries. + */ + rightHanded?: boolean; + } + } +} + +/** + * A high-performance, feature-packed library for all your mapping needs. + */ +declare namespace ol { + + interface TileLoadFunctionType { (image: ol.Image, url: string): void } + + interface FeatureUrlFunction { (extent: ol.Extent, resolution: number, projection: ol.proj.Projection): string } + + interface ImageLoadFunctionType { (image: ol.Image, url: string): void } + + /** + * An attribution for a layer source. + */ + class Attribution { + /** + * @constructor + * @param options Attribution options. + */ + constructor(options: olx.AttributionOptions); + + /** + * Get the attribution markup. + * @returns The attribution HTML. + */ + getHTML(): string; + } + + /** + * An expanded version of standard JS Array, adding convenience methods for manipulation. Add and remove changes to the Collection trigger a Collection event. Note that this does not cover changes to the objects within the Collection; they trigger events on the appropriate object, not on the Collection as a whole. + */ + class Collection extends ol.Object { + + /** + * @constructor + * @param opt_array Array. + */ + constructor(opt_array?: Array) + + /** + * Remove all elements from the collection. + */ + clear(): void; + + /** + * Add elements to the collection. This pushes each item in the provided array to the end of the collection. + * @param arr Array. + * @returns This collection. + */ + extend(arr: Array): Collection; + + /** + * Iterate over each element, calling the provided callback. + * @param f The function to call for every element. This function takes 3 arguments (the element, the index and the array). + * @param opt_this The object to use as this in f. + */ + forEach(f: (element: T, index: number, array: Array) => any, opt_this?: any): void; + + /** + * Get a reference to the underlying Array object. Warning: if the array is mutated, no events will be dispatched by the collection, and the collection's "length" property won't be in sync with the actual length of the array. + * @returns Array. + */ + getArray(): Array; + + /** + * Get the length of this collection. + * @returns The length of the array. + */ + getLength(): number; + + /** + * Insert an element at the provided index. + * @param index Index. + * @param elem Element. + */ + insertAt(index: number, elem: T): void; + + /** + * Get the element at the provided index. + * @param index Index. + * @returns Element. + */ + item(index: number): T; + + /** + * Remove the last element of the collection and return it. Return undefined if the collection is empty. + * @returns Element + */ + pop(): T | void; + + /** + * Insert the provided element at the end of the collection. + * @param elem Element. + * @returns Length. + */ + push(elem: T): number; + + /** + * Remove the first occurrence of an element from the collection. + * @param elem Element. + * @returns The removed element or undefined if none found. + */ + remove(elem: T): T | void; + + /** + * Remove the element at the provided index and return it. Return undefined if the collection does not contain this index. + * @param index Index. + * @returns Value. + */ + removeAt(index: number): T | void; + + /** + * Set the element at the provided index. + * @param index Index. + * @param elem Element. + */ + setAt(index: number, elem: T): void; + } + + /** + * Events emitted by ol.Collection instances are instances of this type. + */ + class CollectionEvent extends ol.events.Event { + + /** + * The element that is added to or removed from the collection. + */ + element: T; + } + + /** + * The ol.DeviceOrientation class provides access to information from DeviceOrientation events. + */ + class DeviceOrientation extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.DeviceOrientationOptions); + + /** + * Rotation around the device z-axis (in radians). + * @returns The euler angle in radians of the device from the standard Z axis. + */ + getAlpha(): number; + + /** + * Rotation around the device x-axis (in radians). + * @returns The euler angle in radians of the device from the planar X axis. + */ + getBeta(): number; + + /** + * Rotation around the device y-axis (in radians). + * @returns The euler angle in radians of the device from the planar Y axis. + */ + getGamma(): number; + + /** + * The heading of the device relative to north (in radians). + * @returns The heading of the device relative to north, in radians, normalizing for different browser behavior. + */ + getHeading(): number; + + /** + * Determine if orientation is being tracked. + * @returns Changes in device orientation are being tracked. + */ + getTracking(): boolean; + + /** + * Enable or disable tracking of device orientation events. + * @param tracking The status of tracking changes to alpha, beta and gamma. If true, changes are tracked and reported immediately. + */ + setTracking(tracking: boolean): void; + } + + /** + * Events emitted by ol.interaction.DragBox instances are instances of this type. + */ + class DragBoxEvent extends ol.events.Event { + constructor ( + type: string, + coordinate: ol.Coordinate, + mapBrowserEvent: ol.MapBrowserEvent + ); + /** + * The coordinate of the drag event. + */ + coordinate: ol.Coordinate; + mapBrowserEvent: ol.MapBrowserEvent; + } + + /** + * A vector object for geographic features with a geometry and other attribute properties, similar to the features in vector file formats like GeoJSON. + */ + class Feature extends ol.Object { + + /** + * @constructor + * @param geometryOrProperties Geometry. + */ + // TODO: replace any with Object + constructor(geometryOrProperties?: ol.geom.Geometry | any); + + /** + * Clone this feature. If the original feature has a geometry it is also cloned. The feature id is not set in the clone. + * @returns The clone. + */ + clone(): Feature; + + /** + * Get the feature's default geometry. A feature may have any number of named geometries. The "default" geometry (the one that is rendered by default) is set when calling ol.Feature#setGeometry. + * @returns The default geometry for the feature. + */ + getGeometry(): ol.geom.Geometry; + + /** + * Get the name of the feature's default geometry. By default, the default geometry is named geometry. + * @returns Get the property name associated with the default geometry for this feature. + */ + getGeometryName(): string; + + /** + * @returns Id. + */ + getId(): string | number; + + /** + * Get the feature's style. This return for this method depends on what was provided to the ol.Feature#setStyle method. + * The feature style. + */ + getStyle(): ol.style.Style | Array | ol.FeatureStyleFunction; + + /** + * Get the feature's style function. + * @returns Return a function representing the current style of this feature. + */ + getStyleFunction(): ol.FeatureStyleFunction; + + /** + * Set the default geometry for the feature. This will update the property with the name returned by ol.Feature#getGeometryName. + * @param geometry The new geometry. + */ + setGeometry(geometry: ol.geom.Geometry): void; + + /** + * Set the property name to be used when getting the feature's default geometry. When calling ol.Feature#getGeometry, the value of the property with this name will be returned. + * @param name The property name of the default geometry. + */ + setGeometryName(name: string): void; + + /** + * Set the feature id. The feature id is considered stable and may be used when requesting features or comparing identifiers returned from a remote source. The feature id can be used with the ol.source.Vector#getFeatureById method. + * @param id The feature id. + */ + setId(id: string | number): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: Array): void; + + /** + * Set the style for the feature. This can be a single style object, an array of styles, or a function that takes a resolution and returns an array of styles. If it is null the feature has no style (a null style). + * @param style Style for this feature. + */ + setStyle(style: ol.FeatureStyleFunction): void; + } + + /** + * A mechanism for changing the style of a small number of features on a temporary basis, for example highlighting. + */ + class FeatureOverlay { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.FeatureOverlayOptions); + + /** + * Add a feature to the overlay. + * @param feature Feature. + */ + addFeature(feature: ol.Feature): void; + + /** + * Get the features on the overlay. + * @returns Features collection. + */ + getFeatures: ol.Collection; + + /** + * Get the map associated with the overlay. + * @returns The map with which this feature overlay is associated. + */ + getMap(): ol.Map; + + /** + * Get the style for features. This returns whatever was passed to the style option at construction or to the setStyle method. + * @returns Overlay style. + */ + getStyle(): ol.style.Style | Array | ol.style.StyleFunction; + + /** + * Get the style function + * @returns Style function + */ + getStyleFunction(): ol.style.StyleFunction; + + /** + * Remove a feature from the overlay. + * @param feature The feature to be removed. + */ + removeFeature(feature: ol.Feature): void; + + /** + * Set the features for the overlay. + * @param features Features collection. + */ + setFeatures(features: ol.Collection): void; + + /** + * Set the map for the overlay. + * @param map Map. + */ + setMap(map: ol.Map): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: Array): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. + * @param style Overlay style + */ + setStyle(style: ol.style.StyleFunction): void; + } + + /** + * Helper class for providing HTML5 Geolocation capabilities. The Geolocation API is used to locate a user's position. + */ + class Geolocation extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.GeolocationOptions); + + /** + * Get the accuracy of the position in meters. + * @returns The accuracy of the position measurement in meters. + */ + getAccuracy(): number; + + /** + * Get a geometry of the position accuracy. + * @returns A geometry of the position accuracy. + */ + getAccuracyGeometry(): ol.geom.Geometry; + + /** + * Get the altitude associated with the position. + * @returns The altitude of the position in meters above mean sea level. + */ + getAltitude(): number; + + /** + * Get the altitude accuracy of the position. + * @returns The accuracy of the altitude measurement in meters. + */ + getAltitudeAccuracy(): number; + + /** + * Get the heading as radians clockwise from North. + * @returns The heading of the device in radians from north. + */ + getHeading(): number; + + /** + * Get the position of the device. + * @returns The current position of the device reported in the current projection. + */ + getPosition(): ol.Coordinate; + + /** + * Get the projection associated with the position. + * @returns The projection the position is reported in. + */ + getProjection(): ol.proj.Projection; + + /** + * Get the speed in meters per second. + * @returns The instantaneous speed of the device in meters per second. + */ + getSpeed(): number; + + /** + * Determine if the device location is being tracked. + * @returns The device location is being tracked. + */ + getTracking(): boolean; + + /** + * Get the tracking options. + * @returns PositionOptions as defined by the HTML5 Geolocation spec. + */ + getTrackingOptions(): PositionOptions; + + /** + * Set the projection to use for transforming the coordinates. + * @param projection The projection the position is reported in. + */ + setProjection(projection: ol.proj.Projection): void; + + /** + * Enable or disable tracking. + * @param tracking Enable tracking + */ + setTracking(tracking: boolean): void; + + /** + * Set the tracking options. + * @param options PositionOptions as defined by the HTML5 Geolocation spec. + */ + setTrackingOptions(options: PositionOptions): void; + } + + /** + * Render a grid for a coordinate system on a map. + */ + class Graticule { + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.GraticuleOptions); + + /** + * Get the map associated with this graticule. + * @returns The map. + */ + getMap(): Map; + + /** + * Get the list of meridians. Meridians are lines of equal longitude. + * @returns The meridians. + */ + getMeridians(): Array; + + /** + * Get the list of parallels. Pallels are lines of equal latitude. + * @returns The parallels. + */ + getParallels(): Array; + + /** + * Set the map for this graticule.The graticule will be rendered on the provided map. + * @param map Map + */ + setMap(map: Map): void; + } + + /** + * + */ + class Image extends ol.ImageBase { + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLCanvasElement): Image; + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLImageElement): Image; + + /** + * Get the HTML image element (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLVideoElement): Image; + } + + /** + * + */ + class ImageBase { + } + + /** + * + */ + class ImageTile extends ol.Tile { + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLCanvasElement): Image; + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLImageElement): Image; + + /** + * Get the HTML image element for this tile (may be a Canvas, Image, or Video). + * @param context Object. + * @returns Image. + */ + getImage(context: HTMLVideoElement): Image; + + } + + /** + * Implementation of inertial deceleration for map movement. + */ + class Kinetic { + + /** + * @constructor + * @param decay Rate of decay (must be negative). + * @param minVelocity Minimum velocity (pixels/millisecond). + * @param delay Delay to consider to calculate the kinetic initial values (milliseconds). + */ + constructor(decay: number, minVelocity: number, delay: number); + } + + /** + * The map is the core component of OpenLayers. For a map to render, a view, one or more layers, and a target container are needed. + */ + class Map extends ol.Object { + + /** + * @constructor + * @params options Options. + */ + constructor(options: olx.MapOptions); + + /** + * Add the given control to the map. + * @param control Control. + */ + addControl(control: ol.control.Control): void; + + /** + * Add the given interaction to the map. + * @param interaction Interaction to add. + */ + addInteraction(interaction: ol.interaction.Interaction): void; + + /** + * Adds the given layer to the top of this map. If you want to add a layer elsewhere in the stack, use getLayers() and the methods available on ol.Collection. + * @param layer Layer. + */ + addLayer(layer: ol.layer.Base): void; + + /** + * Add the given overlay to the map. + * @param overlay Overlay. + */ + addOverlay(overlay: ol.Overlay): void; + + /** + * Add functions to be called before rendering. This can be used for attaching animations before updating the map's view. The ol.animation namespace provides several static methods for creating prerender functions. + * @param var_args Any number of pre-render functions. + */ + beforeRender(...var_args: ol.PreRenderFunction[]): void; + + /** + * Detect features that intersect a pixel on the viewport, and execute a callback with each intersecting feature. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param callback Feature callback. The callback will be called with two arguments. The first argument is one feature at the pixel, the second is the layer of the feature. If the detected feature is not on a layer, but on a ol.FeatureOverlay, then the second argument to this function will be null. To stop detection, callback functions can return a truthy value. + * @param ref Value to use as this when executing callback. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref2 Value to use as this when executing layerFilter. + * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. + */ + forEachFeatureAtPixel(pixel: ol.Pixel, callback: (feature: ol.Feature, layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + + /** + * Detect layers that have a color value at a pixel on the viewport, and execute a callback with each matching layer. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param callback Layer callback. Will receive one argument, the layer that contains the color pixel. If the detected color value is not from a layer, but from a ol.FeatureOverlay, then the argument to this function will be null. To stop detection, callback functions can return a truthy value. + * @param ref Value to use as this when executing callback. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref2 Value to use as this when executing layerFilter. + * @returns Callback result, i.e. the return value of last callback execution, or the first truthy callback return value. + */ + forEachLayerAtPixel(pixel: ol.Pixel, callback: (layer: ol.layer.Layer) => any, ref?: any, layerFilter?: (layerCandidate: ol.layer.Layer) => boolean, ref2?: any): void; + + /** + * Get the map controls. Modifying this collection changes the controls associated with the map. + * @returns Controls. + */ + getControls(): ol.Collection; + + /** + * Get the coordinate for a given pixel. This returns a coordinate in the map view projection. + * @param pixel Pixel position in the map viewport. + * @returns The coordinate for the pixel position. + */ + getCoordinateFromPixel(pixel: ol.Pixel): ol.Coordinate; + + /** + * Returns the geographical coordinate for a browser event. + * @param event Event. + * @returns Coordinate. + */ + getEventCoordinate(event: GlobalEvent): ol.Coordinate; + + /** + * Returns the map pixel position for a browser event relative to the viewport. + * @param event Event. + * @returns Pixel. + */ + getEventPixel(event: GlobalEvent): ol.Pixel; + + /** + * Get the map interactions. Modifying this collection changes the interactions associated with the map. + * @returns Interactions + */ + getInteractions(): ol.Collection; + + /** + * Get the layergroup associated with this map. + * @returns A layer group containing the layers in this map. + */ + getLayerGroup(): ol.layer.Group; + + /** + * Get the collection of layers associated with this map. + * @returns Layers. + */ + getLayers(): ol.Collection; + + /** + * Get the map overlays. Modifying this collection changes the overlays associated with the map. + * @returns Overlays. + */ + getOverlays(): ol.Collection; + + /** + * Get the pixel for a coordinate. This takes a coordinate in the map view projection and returns the corresponding pixel. + * @param coordinate A map coordinate. + * @returns A pixel position in the map viewport. + */ + getPixelFromCoordinate(coordinate: ol.Coordinate): ol.Pixel; + + /** + * Get the size of this map. + * @returns The size in pixels of the map in the DOM. + */ + getSize(): ol.Size; + + /** + * Get the target in which this map is rendered. Note that this returns what is entered as an option or in setTarget: if that was an element, it returns an element; if a string, it returns that. + * @returns The Element or id of the Element that the map is rendered in. + */ + getTarget(): Element | string; + + /** + * Get the DOM element into which this map is rendered. In contrast to getTarget this method always return an Element, or null if the map has no target. + * @returns The element that the map is rendered in. + */ + getTargetElement(): Element; + + /** + * Get the view associated with this map. A view manages properties such as center and resolution. + * @returns The view that controls this map. + */ + getView(): View; + + /** + * Get the element that serves as the map viewport. + * @returns Viewport. + */ + getViewport(): Element; + + /** + * Detect if features intersect a pixel on the viewport. Layers included in the detection can be configured through opt_layerFilter. Feature overlays will always be included in the detection. + * @param pixel Pixel. + * @param layerFilter Layer filter function. The filter function will receive one argument, the layer-candidate and it should return a boolean value. Only layers which are visible and for which this function returns true will be tested for features. By default, all visible layers will be tested. Feature overlays will always be tested. + * @param ref Value to use as this when executing layerFilter. + * @returns Is there a feature at the given pixel? + */ + hasFeatureAtPixel(pixel: ol.Pixel, layerFilter?: (layer: ol.layer.Layer) => boolean, ref?: any): boolean; + + /** + * Remove the given control from the map. + * @param control Control. + * @returns The removed control (or undefined if the control was not found). + */ + removeControl(control: ol.control.Control): ol.control.Control; + + /** + * Remove the given interaction from the map. + * @param interaction Interaction to remove. + * @returns The removed interaction (or undefined if the interaction was not found). + */ + removeInteraction(interaction: ol.interaction.Interaction): ol.interaction.Interaction; + + /** + * Removes the given layer from the map. + * @param layer Layer. + * @returns The removed layer (or undefined if the layer was not found). + */ + removeLayer(layer: ol.layer.Base): ol.layer.Base; + + /** + * Remove the given overlay from the map. + * @param overlay Overlay. + * @returns The removed overlay (or undefined if the overlay was not found). + */ + removeOverlay(overlay: ol.Overlay): ol.Overlay; + + /** + * Request a map rendering (at the next animation frame). + */ + render(): void; + + /** + * Requests an immediate render in a synchronous manner. + */ + renderSync(): void; + + /** + * Sets the layergroup of this map. + * @param layerGroup A layer group containing the layers in this map. + */ + setLayerGroup(layerGroup: ol.layer.Group): void; + + /** + * Set the size of this map. + * @param size The size in pixels of the map in the DOM. + */ + setSize(size: ol.Size): void; + + /** + * Set the target element to render this map into. + * @param target The Element that the map is rendered in. + */ + setTarget(target: Element): void; + + /** + * Set the target element to render this map into. + * @param target The id of the element that the map is rendered in. + */ + setTarget(target: string): void; + + /** + * Set the view for this map. + * @param view The view that controls this map. + */ + setView(view: View): void; + + /** + * Force a recalculation of the map viewport size. This should be called when third-party code changes the size of the map viewport. + * */ + updateSize(): void; + } + + /** + * Events emitted as map browser events are instances of this type. See ol.Map for which events trigger a map browser event. + */ + class MapBrowserEvent extends MapEvent { + + /** + * The coordinate of the original browser event + */ + coordinate: Coordinate; + + /** + * Indicates if the map is currently being dragged. Only set for POINTERDRAG and POINTERMOVE events. Default is false. + */ + dragging: boolean; + + /** + * The frame state at the time of the event + */ + frameState: olx.FrameState; + + /** + * The map where the event occured + */ + map: Map; + + /** + * The original browser event + */ + originalEvent: GlobalEvent; + + /** + * The pixel of the original browser event. + */ + pixel: Pixel; + + + // Methods + + /** + * Prevents the default browser action. + */ + preventDefault(): void; + + /** + * Prevents further propagation of the current event. + */ + stopPropagation(): void; + } + + class MapBrowserPointerEvent extends ol.MapBrowserEvent { + constructor (type: string, + map: ol.Map, + pointerEvent: ol.pointer.PointerEvent, + opt_dragging?: boolean, + opt_frameState?: olx.FrameState) + pointerEvent: ol.pointer.PointerEvent; + } + + /** + * Events emitted as map events are instances of this type. See ol.Map for which events trigger a map event. + */ + class MapEvent extends ol.events.Event { + + constructor (type: string, map: ol.Map, opt_frameState?: olx.FrameState) + + /** + * The frame state at the time of the event. + */ + frameState: olx.FrameState; + + /** + * The map where the event occurred. + */ + map: Map; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Most non-trivial classes inherit from this. + */ + class Object extends Observable { + + /** + * @constructor + * @param values An object with key-value pairs. + */ + constructor(values?: GlobalObject); + + /** + * Gets a value. + * @param key Key name. + * @returns Value. + */ + get(key: string): any; + + /** + * Get a list of object property names. + * @returns List of property names. + */ + getKeys(): Array; + + /** + * Get an object of all property names and values. + * @returns Object. + */ + getProperties(): GlobalObject; + + /** + * @returns Revision. + */ + getRevision(): number; + + /** + * Sets a value. + * @param key Key name. + * @param value Value. + * @param opt_silent Update without triggering an event. + */ + set(key: string, value: any, opt_silent?: boolean): void; + + /** + * Sets a collection of key-value pairs. Note that this changes any existing properties and adds new ones (it does not remove any existing properties). + * @param values Values. + * @param opt_silent Update without triggering an event. + */ + setProperties(values: GlobalObject, opt_silent?: boolean): void; + + /** + * Unsets a property. + */ + unset(key: string, opt_silent?: boolean): void; + } + + /** + * Events emitted by ol.Object instances are instances of this type. + */ + class ObjectEvent extends ol.events.Event { + + /** + * The name of the property whose value is changing. + */ + key: string; + + /** + * The old value. To get the new value use e.target.get(e.key) where e is the event object. + */ + oldValue: any; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. An event target providing convenient methods for listener registration and unregistration. A generic change event is always available through ol.Observable#changed. + */ + class Observable extends ol.events.EventTarget { + + /** + * Removes an event listener using the key returned by on() or once(). + */ + static unByKey(key: any): void; + + /** + * Increases the revision counter and dispatches a 'change' event. + */ + changed(): void; + + /** + * @returns Revision. + */ + getRevision(): number; + + /** + * Listen for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param opt_this The object to use as this in listener. + * @returns Unique key for the listener. + */ + on(type: string | Array, listener: Function, opt_this?: GlobalObject): ol.events.Key | Array; + + /** + * Listen once for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param opt_this The object to use as this in listener. + * @returns Unique key for the listener. + */ + once(type: string | Array, listener: Function, opt_this?: GlobalObject): ol.events.Key | Array; + + /** + * Unlisten for a certain type of event. + * @param type The array of event types. + * @param listener The listener function. + * @param opt_this The object to use as this in listener. + * @returns Unique key for the listener. + */ + un(type: string | Array, listener: Function, opt_this?: GlobalObject): void; + + /** + * Removes an event listener using the key returned by on() or once(). Note that using the ol.Observable.unByKey static function is to be preferred. + * @param key The key returned by on() or once() + */ + unByKey(key: ol.events.Key | Array): void; + } + + /** + * An element to be displayed over the map and attached to a single map location. + */ + class Overlay extends ol.Object { + + /** + * @constructor + * @param options Overlay options. + */ + constructor(options: olx.OverlayOptions); + + /** + * Get the DOM element of this overlay. + * @returns The Element containing the overlay. + */ + getElement(): Element; + + /** + * Get the map associated with this overlay. + * @returns The map that the overlay is part of. + */ + getMap(): ol.Map; + + /** + * Get the offset of this overlay. + * @returns The offset. + */ + getOffset(): Array; + + /** + * Get the current position of this overlay. + * @returns The spatial point that the overlay is anchored at. + */ + getPosition(): ol.Coordinate; + + /** + * Get the current positioning of this overlay. + * @returns How the overlay is positioned relative to its point on the map. + */ + getPositioning(): ol.OverlayPositioning; + + /** + * Set the DOM element to be associated with this overlay. + * @param element The element containing the overlay. + */ + setElement(element: Element): void; + + /** + * Set the map to be associated with this overlay. + * @param map The map that the overlay is part of. + */ + setMap(map: Map): void; + + /** + * Set the offset for this overlay. + * @param offset Offset. + */ + setOffset(offset: Array): void; + + /** + * Set the position for this overlay. If the position is undefined the overlay is hidden. + * @param position The spatial point that the overlay is anchored at. + */ + setPosition(position: ol.Coordinate): void; + + /** + * Set the positioning for this overlay. + * @param positioning How the overlay is positioned relative to its point on the map. + */ + setPositioning(positioning: ol.OverlayPositioning): void; + } + + /** + * Events emitted by ol.interaction.Select instances are instances of this type. + */ + class SelectEvent { + + /** + * Deselected features array. + */ + deselected: Array; + + /** + * Associated ol.MapBrowserEvent; + */ + mapBrowserEvent: ol.MapBrowserEvent; + + /** + * Selected features array. + */ + selected: Array + } + + /** + * Class to create objects that can be used with ol.geom.Polygon.circular. + */ + class Sphere { + + /** + * @constructor + * @param radius Radius. + */ + constructor(radius: number); + + /** + * Returns the geodesic area for a list of coordinates. + * @param coordinates List of coordinates of a linear ring. If the ring is oriented clockwise, the area will be positive, otherwise it will be negative. + * @returns Area. + */ + geodesicArea(coordinates: Array): number; + + /** + * Returns the distance from c1 to c2 using the haversine formula. + * @param c1 Coordinate 1. + * @param c2 Coordinate 2. + * @returns Haversine distance. + */ + haversineDistance(c1: ol.Coordinate, c2: ol.Coordinate): number; + } + + /** + * Base class for tiles. + */ + class Tile { + + /** + * Get the tile coordinate for this tile. + * @returns TileCoord. + */ + getTileCoord(): ol.TileCoord; + } + + /** + * An ol.View object represents a simple 2D view of the map. + */ + class View extends ol.Object { + + /** + * @constructor + * @param options Options. + */ + constructor(options?: olx.ViewOptions); + + /** + * Calculate the extent for the current view state and the passed size. The size is the pixel dimensions of the box into which the calculated extent should fit. In most cases you want to get the extent of the entire map, that is map.getSize(). + * @param size Box pixel size + * @returns Extent. + */ + calculateExtent(size: ol.Size): ol.Extent; + + /** + * Center on coordinate and view position. + * @param coordinate Coordinate. + * @param size Box pixel size + * @param position Position on the view to center on + */ + centerOn(coordinate: ol.Coordinate, size: ol.Size, position: ol.Pixel): void; + + /** + * Get the constrained center of this view. + * @param center Center. + * @returns Constrained center. + */ + constrainCenter(center: ol.Coordinate): ol.Coordinate; + + /** + * Get the constrained resolution of this view. + * @param resolution: Resolution. + * @param delta Delta. Default is 0. + * @param direction Direction. Default is 0. + * @returns Constrained resolution + */ + constrainResolution(resolution: number, delta?: number, direction?: number): number; + + /** + * Fit the map view to the passed extent and size. The size is pixel dimensions of the box to fit the extent into. In most cases you will want to use the map size, that is map.getSize(). + * @param geometry Geometry. + * @param size Box pixel size. + * @param opt_options Options + */ + fit(geometry: ol.geom.SimpleGeometry | ol.Extent, size: ol.Size, opt_options?: olx.view.FitGeometryOptions): void; + + /** + * Get the view center. + * @returns The center of the view. + */ + getCenter(): ol.Coordinate; + + /** + * Get the view projection + * @returns The projection of the view. + */ + getProjection(): ol.proj.Projection; + + /** + * Get the view resolution + * @returns The resolution of the view. + */ + getResolution(): number; + + /** + * Get the view rotation + * @returns The rotation of the view in radians + */ + getRotation(): number; + + /** + * Get the current zoom level. Return undefined if the current resolution is undefined or not a "constrained resolution". + * @returns Zoom. + */ + getZoom(): number; + + /** + * Rotate the view around a given coordinate. + * @param rotation New rotation value for the view. + * @param anchor The rotation center. + */ + rotate(rotation: number, anchor: ol.Coordinate): void; + + /** + * Set the center of the current view. + * @param center The center of the view. + */ + setCenter(center: ol.Coordinate): void; + + /** + * Set the resolution for this view. + * @param resolution The resolution of the view. + */ + setResolution(resolution: number): void; + + /** + * Set the rotation for this view. + * @param rotation The rotation of the view in radians. + */ + setRotation(rotation: number): void; + + /** + * Zoom to a specific zoom level. + * @param zoom Zoom level. + */ + setZoom(zoom: number): void; + } + + // NAMESPACES + + /** + * The animation static methods are designed to be used with the ol.Map#beforeRender method. + */ + namespace animation { + + /** + * Generate an animated transition that will "bounce" the resolution as it approaches the final value. + * @param options Bounce options. + */ + function bounce(options: olx.animation.BounceOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view center. + * @param options Pan options. + */ + function pan(options: olx.animation.PanOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view rotation. + * @param options Rotate options. + */ + function rotate(options: olx.animation.RotateOptions): ol.PreRenderFunction; + + /** + * Generate an animated transition while updating the view resolution. + * @param options Zoom options. + */ + function zoom(options: olx.animation.ZoomOptions): ol.PreRenderFunction; + } + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + */ + namespace color { + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + * @param color Color. + */ + function asArray(color: ol.Color): ol.Color; + + /** + * Return the color as an array. This function maintains a cache of calculated arrays which means the result should not be modified. + * @param color Color. + */ + function asArray(color: string): ol.Color; + + /** + * Return the color as an rgba string. + * @param color Color. + */ + function asString(color: ol.Color): string; + + /** + * Return the color as an rgba string. + * @param color Color. + */ + function asString(color: string): string; + } + + namespace control { + + /** + * Set of controls included in maps by default. Unless configured otherwise, this returns a collection containing an instance of each of the following controls: ol.control.Zoom, ol.control.Rotate, ol.control.Attribution + * @param options Defaults options + * @returns Control.s + */ + function defaults(options?: olx.control.DefaultsOptions): ol.Collection; + + /** + * Units for the scale line. Supported values are 'degrees', 'imperial', 'nautical', 'metric', 'us'. + */ + interface ScaleLineUnits extends String { } + + class Attribution { + } + + class Control { + } + + class FullScreen { + } + + class MousePosition { + } + + class OverviewMap { + } + + class Rotate { + } + + class ScaleLine { + } + + class Zoom { + } + + class ZoomSlider { + } + + class ZoomToExtent { + } + } + + namespace coordinate { + + /** + * Add delta to coordinate. coordinate is modified in place and returned by the function. + * @param coordinate Coordinate + * @param delta Delta + * @returns The input coordinate adjusted by the given delta. + */ + function add(coordinate: ol.Coordinate, delta: ol.Coordinate): ol.Coordinate; + + /** + * Returns a ol.CoordinateFormatType function that can be used to format a {ol.Coordinate} to a string. + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns Coordinate format + */ + function createStringXY(fractionDigits?: number): ol.CoordinateFormatType; + + /** + * Transforms the given ol.Coordinate to a string using the given string template. The strings {x} and {y} in the template will be replaced with the first and second coordinate values respectively. + * @param coordinate Coordinate + * @param template A template string with {x} and {y} placeholders that will be replaced by first and second coordinate values. + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns Formatted coordinate + */ + function format(coordinate: ol.Coordinate, template: string, fractionDigits?: number): string; + + /** + * Rotate coordinate by angle. coordinate is modified in place and returned by the function. + * @param coordinate Coordinate + * @param angle Angle in radian + * @returns Coordinatee + */ + function rotate(coordinate: ol.Coordinate, angle: number): ol.Coordinate; + + /** + * Format a geographic coordinate with the hemisphere, degrees, minutes, and seconds. + * @param coordinate COordinate + * @returns Hemisphere, degrees, minutes and seconds. + */ + function toStringHDMS(coordinate?: ol.Coordinate): string; + + /** + * Format a coordinate as a comma delimited string. + * @param coordinate Coordinate + * @param fractionDigits The number of digits to include after the decimal point. Default is 0. + * @returns XY + */ + function toStringXY(coordinate?: ol.Coordinate, fractionDigits?: number): string; + } + + /** + * Easing functions for ol.animation. + */ + namespace easing { + + /** + * Start slow and speed up. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function easeIn(t: number): number; + + /** + * Start fast and slow down. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function easeOut(t: number): number; + + /** + * Start slow, speed up, and then slow down again. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function inAndOut(t: number): number; + + /** + * Maintain a constant speed over time. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function linear(t: number): number; + + /** + * Start slow, speed up, and at the very end slow down again. This has the same general behavior as ol.easing.inAndOut, but the final slowdown is delayed. + * @param t Input between 0 and 1 + * @returns Output between 0 and 1 + */ + function upAndDown(t: number): number; + } + + interface ModifyEventType extends String { + MODIFYSTART: any; + MODIFYEND: any; + } + + namespace events { + namespace condition { + function altKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function altShiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function always(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function click(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function doubleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function mouseOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function never(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function noModifierKeys(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function platformModifierKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function pointerMove(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function shiftKeyOnly(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function singleClick(mapBrowserEvent: ol.MapBrowserEvent): boolean; + function targetNotEditable(mapBrowserEvent: ol.MapBrowserEvent): boolean; + } + interface ConditionType { (mapBrowseEvent: ol.MapBrowserEvent): boolean; } + + class Event { + constructor(type: string, opt_target?: GlobalObject); + propagationStopped: boolean; + type: string; + target: Object; + preventDefault(): void; + stopPropagation(): void; + static preventDefault(evt: GlobalEvent | ol.events.Event): void; + static stopPropagation(evt: GlobalEvent | ol.events.Event): void; + } + + class EventTarget { + addEventListener(type: string, listener: ol.events.ListenerFunctionType): void; + dispatchEvent(event: {type: string, target?: GlobalEventTarget | ol.events.EventTarget, [x: string]: any}): void | boolean; + dispatchEvent(event: ol.events.Event): void | boolean; + dispatchEvent(event: string): void | boolean; + //getListeners(type: string): ol.events.ListenerFunctionType[]; + //hasListener(opt_type?: string): boolean; + removeEventListener(type: string, listener: ol.events.ListenerFunctionType): void; + } + + interface ListenerFunctionType { + (evt: ol.events.Event): boolean | void; + } + + interface Key extends GlobalObject {} + } + + namespace extent { + + /** + * Apply a transform function to the extent. + * @param extent Extent + * @param transformFn Transform function. Called with [minX, minY, maxX, maxY] extent coordinates. + * @param destinationExtent Destination Extent + * @returns Extent + */ + function applyTransform(extent: ol.Extent, transformFn: ol.TransformFunction, destinationExtent?: ol.Extent): ol.Extent; + + /** + * Build an extent that includes all given coordinates. + * @param coordinates Coordinates + * @returns Bounding extent + */ + function boundingExtent(coordinates: Array): ol.Extent; + + /** + * Return extent increased by the provided value. + * @param extent Extent + * @param value The amount by which the extent should be buffered. + * @param destinationExtent Destination Extent + * @returns Extent + */ + function buffer(extent: ol.Extent, value: number, destinationExtent?: ol.Extent): ol.Extent; + + /** + * Check if the passed coordinate is contained or on the edge of the extent. + * @param extent Extent + * @param coordinate Coordinate + * @returns The coordinate is contained in the extent + */ + function containsCoordinate(extent: ol.Extent, coordinate: ol.Coordinate): boolean; + + /** + * Check if one extent contains another. An extent is deemed contained if it lies completely within the other extent, including if they share one or more edges. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The second extent is contained by or on the edge of the first + */ + function containsExtent(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Check if the passed coordinate is contained or on the edge of the extent. + * @param extent Extent + * @param x X coordinate + * @param y Y coordinate + * @returns The x, y values are contained in the extent. + */ + function containsXY(extent: ol.Extent, x: number, y: number): boolean; + + /** + * Create an empty extent. + * @returns Empty extent + */ + function createEmpty(): ol.Extent; + + /** + * Determine if two extents are equivalent. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The two extents are equivalent + */ + function equals(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Modify an extent to include another extent. + * @param extent1 The extent to be modified. + * @param extent2 The extent that will be included in the first. + * @returns A reference to the first (extended) extent. + */ + function extend(extent1: ol.Extent, extent2: ol.Extent): ol.Extent; + + /** + * Get the bottom left coordinate of an extent. + * @param extent Extent + * @returns Bottom left coordinate + */ + function getBottomLeft(extent: ol.Extent): ol.Coordinate; + + /** + * Get the bottom right coordinate of an extent. + * @param extent Extent + * @returns Bottom right coordinate + */ + function getBottomRight(extent: ol.Extent): ol.Coordinate; + + /** + * Get the center coordinate of an extent. + * @param extent Extent + * @returns Center + */ + function getCenter(extent: ol.Extent): ol.Coordinate; + + /** + * Get the height of an extent. + * @param extent Extent + * @returns Height + */ + function getHeight(extent: ol.Extent): number; + + /** + * Get the intersection of two extents. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @param extent Optional extent to populate with intersection. + * @returns Intersecting extent + */ + function getIntersection(extent1: ol.Extent, extent2: ol.Extent, extent?: ol.Extent): ol.Extent; + + /** + * Get the size (width, height) of an extent. + * @param extent Extent + * @returns The extent size + */ + function getSize(extent: ol.Extent): ol.Size; + + /** + * Get the top left coordinate of an extent. + * @param extent Extent + * @returns Top left coordinate + */ + function getTopLeft(extent: ol.Extent): ol.Coordinate; + + /** + * Get the top right coordinate of an extent. + * @param extent Extent + * @returns Top right coordinate + */ + function getTopRight(extent: ol.Extent): ol.Coordinate; + + /** + * Get the width of an extent. + * @param extent Extent + * @returns Width + */ + function getWidth(extent: ol.Extent): number; + + /** + * Determine if one extent intersects another. + * @param extent1 Extent 1 + * @param extent2 Extent 2 + * @returns The two extents intersects + */ + function intersects(extent1: ol.Extent, extent2: ol.Extent): boolean; + + /** + * Determine if an extent is empty. + * @param extent Extent + * @returns Is empty + */ + function isEmpty(extent: ol.Extent): boolean; + } + + /** + * Loading mechanisms for vector data. + */ + namespace featureloader { + + /** + * Create an XHR feature loader for a url and format. The feature loader loads features (with XHR), parses the features, and adds them to the vector source. + * @param url Feature URL Service + * @param format Feature format + * @returns The feature loader + */ + function xhr(url: string, format: ol.format.Feature): ol.FeatureLoader; + } + + namespace format { + + // Type definitions + interface IGCZ extends String { } + + // Classes + class EsriJSON { + } + + class Feature { + } + + /** + * Feature format for reading and writing data in the GeoJSON format. + */ + class GeoJSON extends ol.format.JSONFeature { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.format.GeoJSONOptions); + + /** + * Read a feature from a GeoJSON Feature source. Only works for Feature, use readFeatures to read FeatureCollection source. + * @param source Source + * @param options Read options + * @returns Feature + */ + readFeature(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.Feature; + + /** + * Read all features from a GeoJSON source. Works with both Feature and FeatureCollection sources. + * @param source Source + * @param options Read options + * @returns Features + */ + readFeatures(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): Array; + + /** + * Read a geometry from a GeoJSON source. + * @param source Source + * @param options Read options + * @returns Geometry + */ + readGeometry(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.geom.Geometry; + + /** + * Read the projection from a GeoJSON source. + * @param source Source + * @returns Projection + */ + readProjection(source: Document | Node | JSON | string): ol.proj.Projection; + + /** + * Encode a feature as a GeoJSON Feature string. + * @param feature Feature + * @param options Write options + * @returns GeoJSON + */ + writeFeature(feature: ol.Feature, options?: olx.format.WriteOptions): string; + + /** + * Encode a feature as a GeoJSON Feature object. + * @param feature Feature + * @param options Write options + * @returns GeoJSON object + */ + writeFeatureObject(feature: ol.Feature, options?: olx.format.WriteOptions): JSON; + + /** + * Encode an array of features as GeoJSON. + * @param features Features + * @param options Write options + * @returns GeoJSON + */ + writeFeatures(features: Array, options?: olx.format.WriteOptions): string; + + /** + * Encode an array of features as a GeoJSON object. + * @param features Features + * @param options Write options + * @returns GeoJSON object + */ + writeFeaturesObject(features: Array, options?: olx.format.WriteOptions): JSON; + + /** + * Encode a geometry as a GeoJSON string. + * @param geometry Geometry + * @param options Write options + * @returns GeoJSON + */ + writeGeometry(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): string; + + /** + * Encode a geometry as a GeoJSON object. + * @param geometry Geometry + * @param options Options + * @options Write options + * @returns GeoJSON object + */ + writeGeometryObject(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): JSON; + } + + class GML { + } + + class GML2 { + } + + class GML3 { + } + + class GMLBase { + } + + class GPX { + } + + class IGC { + } + + class JSONFeature { + } + + class KML { + } + + class OSMXML { + } + + class Polyline { + } + + class TextFeature { + } + + class TopoJSON { + } + + class WFS { + readFeatures(source: Document | Node | GlobalObject | string, option?: olx.format.ReadOptions): Array; + } + + class WKT { + constructor(opt_options?: olx.format.WKTOptions); + + /** + * Read a feature from a WKT source. + * @param source Source + * @param opt_options Read options + * @returns Feature + */ + readFeature(source: Document | Node | JSON | string, opt_options?: olx.format.ReadOptions): ol.Feature; + + /** + * Read all features from a WKT source. + * @param source Source + * @param options Read options + * @returns Features + */ + readFeatures(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): Array; + + /** + * Read a geometry from a GeoJSON source. + * @param source Source + * @param options Read options + * @returns Geometry + */ + readGeometry(source: Document | Node | JSON | string, options?: olx.format.ReadOptions): ol.geom.Geometry; + + /** + * Encode a feature as a WKT string. + * @param feature Feature + * @param options Write options + * @returns GeoJSON + */ + writeFeature(feature: ol.Feature, options?: olx.format.WriteOptions): string; + + /** + * Encode an array of features as a WKT string. + * @param features Features + * @param options Write options + * @returns GeoJSON + */ + writeFeatures(features: Array, options?: olx.format.WriteOptions): string; + + /** + * Write a single geometry as a WKT string. + * @param geometry Geometry + * @param options Write options + * @returns GeoJSON + */ + writeGeometry(geometry: ol.geom.Geometry, options?: olx.format.WriteOptions): string; + } + + class WMSCapabilities { + } + + class WMSGetFeatureInfo { + } + + class WMTSCapabilities { + } + + class XML { + } + + class XMLFeature { + } + } + + namespace geom { + + // Type definitions + interface GeometryLayout extends String { } + interface GeometryType extends String { } + + /** + * Abstract base class; only used for creating subclasses; do not instantiate + * in apps, as cannot be rendered. + */ + class Circle extends ol.geom.SimpleGeometry { + + constructor(center: ol.Coordinate, opt_radius?: number, opt_layout?: ol.geom.GeometryLayout); + + clone(): ol.geom.Circle; + + getCenter(): ol.Coordinate; + + getRadius(): number; + + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + setCenter(center: ol.Coordinate): void; + + setCenterAndRadius(center: ol.Coordinate, radius: number, opt_layout?: ol.geom.GeometryLayout): void; + + setFlatCoordinates(layout: ol.geom.GeometryLayout, flatCoordinates: number[]): void; + + setRadius(radius: number): void; + + /** + * Transform each coordinate of the circle from one coordinate reference system + * to another. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and + * then use this function on the clone. + * + * Internally a circle is currently represented by two points: the center of + * the circle `[cx, cy]`, and the point to the right of the circle + * `[cx + r, cy]`. This `transform` function just transforms these two points. + * So the resulting geometry is also a circle, and that circle does not + * correspond to the shape that would be obtained by transforming every point + * of the original circle. + * @param source The current projection. Can be a string identifier or a {@link ol.proj.Projection} object. + * @param destination The desired projection. Can be a string identifier or a {@link ol.proj.Projection} object. + * @returns This geometry. Note that original geometry is modified in place. + */ + transform(source: ol.proj.ProjectionLike, destination: ol.proj.ProjectionLike): ol.geom.Circle; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Base class for vector geometries. + */ + class Geometry extends ol.Object { + + /** + * Return the closest point of the geometry to the passed point as coordinate. + * @param point Point + * @param closestPoint Closest Point + * @returns Closest Point + */ + getClosestPoint(point: ol.Coordinate, closestPoint?: ol.Coordinate): ol.Coordinate; + + /** + * Get the extent of the geometry. + * @param extent Extent + * @returns Extent + */ + getExtent(extent?: ol.Extent): ol.Extent; + + /** + * Transform each coordinate of the geometry from one coordinate reference system to another. + * The geometry is modified in place. For example, a line will be transformed to a line and a + * circle to a circle. If you do not want the geometry modified in place, first clone() it and + * then use this function on the clone. + * @param source The current projection. Can be a string identifier or a ol.proj.Projection object. + * @param destination The desired projection. Can be a string identifier or a ol.proj.Projection object. + * @return This geometry. Note that original geometry is modified in place. + */ + transform(source: ol.proj.ProjectionLike, destination: ol.proj.ProjectionLike): ol.geom.Geometry; + } + + /** + * An array of ol.geom.Geometry objects. + */ + class GeometryCollection extends ol.geom.Geometry { + + /** + * constructor + * @param geometries Geometries. + */ + constructor(geometries?: Array); + + /** + * Apply a transform function to each coordinate of the geometry. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and then use this function on the clone. + * @param transformFn TransformFunction + */ + applyTransform(transformFn: ol.TransformFunction): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.GeometryCollection; + + /** + * Return the geometries that make up this geometry collection. + * @returns Geometries. + */ + getGeometries(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the geometries that make up this geometry collection. + * @param geometries Geometries. + */ + setGeometries(geometries: Array): void; + + translate(deltaX: number, deltaY: number): void; + + } + + /** + * Linear ring geometry. Only used as part of polygon; cannot be rendered + * on its own. + */ + class LinearRing extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.LinearRing; + + /** + * Return the area of the linear ring on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Return the coordinates of the linear ring. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * @Set the coordinates of the linear ring + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: any): void; + + } + + /** + * Linestring geometry. + */ + class LineString extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed coordinate to the coordinates of the linestring. + * @param coordinate Coordinate. + */ + appendCoordinate(coordinate: ol.Coordinate): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.LineString; + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * @param m M. + * @param extrapolate Extrapolate. Default is `false`. + * @returns Coordinate. + */ + getCoordinateAtM(m: number, extrapolate?: boolean): ol.Coordinate; + + /** + * Return the coordinates of the linestring. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Return the length of the linestring on projected plane. + * @returns Length (on projected plane). + */ + getLength(): number; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the linestring. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-linestring geometry. + */ + class MultiLineString extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed linestring to the multilinestring. + * @param lineString LineString. + */ + appendLineString(lineString: ol.geom.LineString): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiLineString; + + /** + * Returns the coordinate at `m` using linear interpolation, or `null` if no + * such coordinate exists. + * + * `extrapolate` controls extrapolation beyond the range of Ms in the + * MultiLineString. If `extrapolate` is `true` then Ms less than the first + * M will return the first coordinate and Ms greater than the last M will + * return the last coordinate. + * + * `interpolate` controls interpolation between consecutive LineStrings + * within the MultiLineString. If `interpolate` is `true` the coordinates + * will be linearly interpolated between the last coordinate of one LineString + * and the first coordinate of the next LineString. If `interpolate` is + * `false` then the function will return `null` for Ms falling between + * LineStrings. + * + * @param m M. + * @param extrapolate Extrapolate. Default is `false`. + * @param interpolate Interpolate. Default is `false`. + * @returns Coordinate. + */ + getCoordinateAtM(m: number, extrapolate?: boolean, interpolate?: boolean): ol.Coordinate; + + /** + * Return the coordinates of the multilinestring. + * @returns Coordinates. + */ + getCoordinates(): Array>; + + /** + * Return the linestring at the specified index. + * @param index Index. + * @returns LineString. + */ + getLineString(index: number): ol.geom.LineString; + + /** + * Return the linestrings of this multilinestring. + * @returns LineStrings. + */ + getLineStrings(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multilinestring. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-point geometry. + */ + class MultiPoint extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed point to this multipoint. + * @param {ol.geom.Point} point Point. + */ + appendPoint(point: ol.geom.Point): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiPoint; + + /** + * Return the coordinates of the multipoint. + * @returns Coordinates. + */ + getCoordinates(): Array; + + /** + * Return the point at the specified index. + * @param index Index. + * @returns Point. + */ + getPoint(index: number): ol.geom.Point; + + /** + * Return the points of this multipoint. + * @returns Points. + */ + getPoints(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multipoint. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Multi-polygon geometry. + */ + class MultiPolygon extends ol.geom.SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: Array>>, layout?: ol.geom.GeometryLayout); + + /** + * Append the passed polygon to this multipolygon. + * @param polygon Polygon. + */ + appendPolygon(polygon: ol.geom.Polygon): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.MultiPolygon; + + /** + * Return the area of the multipolygon on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for multi-polygons. + * + * @param right Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @returns Coordinates. + */ + getCoordinates(right?: boolean): Array>>; + + /** + * Return the interior points as {@link ol.geom.MultiPoint multipoint}. + * @returns Interior points. + */ + getInteriorPoints(): ol.geom.MultiPoint; + + /** + * Return the polygon at the specified index. + * @param index Index. + * @returns Polygon. + */ + getPolygon(index: number): ol.geom.Polygon; + + /** + * Return the polygons of this multipolygon. + * @returns Polygons. + */ + getPolygons(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the multipolygon. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>>, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Point geometry. + */ + class Point extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param layout Layout. + */ + constructor(coordinates: ol.Coordinate, layout?: ol.geom.GeometryLayout); + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.Point; + + /** + * Return the coordinate of the point. + * @returns Coordinates. + */ + getCoordinates(): ol.Coordinate; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinate of the point. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: ol.Coordinate, layout?: ol.geom.GeometryLayout): void; + } + + /** + * Polygon geometry. + */ + class Polygon extends SimpleGeometry { + + /** + * constructor + * @param coordinates Coordinates. + * @param opt_layout Layout. + */ + constructor(coordinates: Array>, opt_layout?: ol.geom.GeometryLayout); + + /** + * Create an approximation of a circle on the surface of a sphere. + * @param sphere The sphere. + * @param center Center (`[lon, lat]` in degrees). + * @param radius The great-circle distance from the center to the polygon vertices. + * @param opt_n Optional number of vertices for the resulting polygon. Default is `32`. + * @returns The "circular" polygon. + */ + static circular(sphere: ol.Sphere, center: ol.Coordinate, radius: number, opt_n?: number): ol.geom.Polygon; + + static fromCircle(circle: ol.geom.Circle, opt_sides?: number, opt_angle?: number): ol.geom.Polygon; + + static fromExtent(extent: ol.Extent): ol.geom.Polygon; + + /** + * Append the passed linear ring to this polygon. + * @param linearRing Linear ring. + */ + appendLinearRing(linearRing: ol.geom.LinearRing): void; + + /** + * Make a complete copy of the geometry. + * @returns Clone. + */ + clone(): ol.geom.Polygon; + + /** + * Return the area of the polygon on projected plane. + * @returns Area (on projected plane). + */ + getArea(): number; + + /** + * Get the coordinate array for this geometry. This array has the structure + * of a GeoJSON coordinate array for polygons. + * + * @param opt_right Orient coordinates according to the right-hand + * rule (counter-clockwise for exterior and clockwise for interior rings). + * If `false`, coordinates will be oriented according to the left-hand rule + * (clockwise for exterior and counter-clockwise for interior rings). + * By default, coordinate orientation will depend on how the geometry was + * constructed. + * @returns Coordinates. + */ + getCoordinates(opt_right?: boolean): Array>; + + /** + * Return an interior point of the polygon. + * @returns Interior point. + */ + getInteriorPoint(): ol.geom.Point; + + /** + * Return the Nth linear ring of the polygon geometry. Return `null` if the + * given index is out of range. + * The exterior linear ring is available at index `0` and the interior rings + * at index `1` and beyond. + * + * @param index Index. + * @returns Linear ring. + */ + getLinearRing(index: number): ol.geom.LinearRing; + + getLinearRingCount(): number; + + /** + * Return the linear rings of the polygon. + * @returns Linear rings. + */ + getLinearRings(): Array; + + /** + * Get the type of this geometry. + * @returns Geometry type + */ + getType(): ol.geom.GeometryType; + + /** + * Test if the geometry and the passed extent intersect. + * @param extent Extent + * @returns true if the geometry and the extent intersect. + */ + intersectsExtent(extent: ol.Extent): boolean; + + /** + * Set the coordinates of the polygon. + * @param coordinates Coordinates. + * @param layout Layout. + */ + setCoordinates(coordinates: Array>, layout?: ol.geom.GeometryLayout): void; + } + /** + * Abstract base class; only used for creating subclasses; do not instantiate + * in apps, as cannot be rendered. + */ + class SimpleGeometry extends ol.geom.Geometry { + + /** + * Apply a transform function to each coordinate of the geometry. The geometry is modified in place. + * If you do not want the geometry modified in place, first clone() it and then use this function on the clone. + * @param transformFn TransformFunction + */ + applyTransform(transformFn: ol.TransformFunction): void; + + /** + * Return the first coordinate of the geometry. + * @returns First coordinate. + */ + getFirstCoordinate(): ol.Coordinate; + + /** + * Return the last coordinate of the geometry. + * @returns Last point. + */ + getLastCoordinate(): ol.Coordinate; + + /** + * Return the {@link ol.geom.GeometryLayout layout} of the geometry. + * @returns Layout. + */ + getLayout(): ol.geom.GeometryLayout; + + /** + * Translate the geometry. This modifies the geometry coordinates in place. + * If instead you want a new geometry, first clone() this geometry. + * @param deltaX Delta X + * @param deltaY Delta Y + */ + translate(deltaX: number, deltaY: number): void; + } + } + + namespace has { + } + + namespace interaction { + + class DoubleClickZoom extends ol.interaction.Interaction { + } + + class DragAndDrop extends ol.interaction.Interaction { + } + + class DragAndDropEvent extends ol.events.Event { + } + + class DragBox extends ol.interaction.Pointer { + constructor (opt_options?: olx.interaction.DragBoxOptions) + getGeometry (): ol.geom.Polygon + } + + class DragPan extends ol.interaction.Pointer { + } + + class DragRotate extends ol.interaction.Pointer { + } + + class DragRotateAndZoom extends ol.interaction.Pointer { + } + + class DragZoom extends ol.interaction.DragBox { + } + + class Draw extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.DrawOptions) + } + + class DrawEvent extends ol.events.Event { + constructor (type: ol.interaction.DrawEventType, feature: ol.Feature) + feature: ol.Feature + } + + class Interaction extends ol.Object { + constructor (options: olx.interaction.InteractionOptions) + handleEvent (e: ol.MapBrowserEvent): boolean + getActive (): boolean; + getMap (): ol.Map; + setActive (active: boolean): void; + } + + class KeyboardPan extends ol.interaction.Interaction { + } + + class KeyboardZoom extends ol.interaction.Interaction { + } + + class Modify extends ol.interaction.Pointer { + constructor(opt_options?: olx.interaction.ModifyOptions) + } + + class ModifyEvent extends ol.events.Event { + constructor ( + type: ol.ModifyEventType, + features: ol.Collection, + mapBrowserPointerEvent: ol.MapBrowserPointerEvent + ) + features: ol.Collection; + mapBrowserPointerEvent: ol.MapBrowserPointerEvent; + } + + class MouseWheelZoom extends ol.interaction.Interaction { + } + + class PinchRotate extends ol.interaction.Pointer { + } + + class PinchZoom extends ol.interaction.Pointer { + } + + class Pointer extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.PointerOptions) + handleEvent(mapBrowserEvent: ol.MapBrowserEvent): boolean + } + + class Select extends ol.interaction.Interaction { + constructor(opt_options?: olx.interaction.SelectOptions); + getLayer(): ol.layer.Layer; + getFeatures(): ol.Collection; + } + + class Snap extends ol.interaction.Pointer { + } + + class Translate extends ol.interaction.Pointer { + } + + class TranslateEvent extends ol.events.Event { + } + + function defaults(opts: olx.interaction.DefaultsOptions): ol.Collection; + + interface DragBoxEndConditionType { + (evt: ol.MapBrowserEvent, startPixel: ol.Pixel, endPixel: ol.Pixel): boolean + } + + interface DrawGeometryFunctionType { + (coordinates: ol.Coordinate | Array | Array>, geom?: ol.geom.SimpleGeometry): ol.geom.SimpleGeometry; + } + + interface SelectFilterFunction { (feature: ol.Feature | ol.render.Feature, layer: ol.layer.Layer): boolean; } + + interface DrawEventType extends String { + DRAWSTART: any; + DRAWEND: any; + } + } + + namespace layer { + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. Note that with ol.layer.Base and all its subclasses, any property set in the options is set as a ol.Object property on the layer object, so is observable, and has get/set accessors. + */ + class Base extends ol.Object { + + /** + * @constructor + * @param options Layer options. + */ + constructor(options?: olx.layer.BaseOptions); + + /** + * Return the brightness of the layer. + * @returns The brightness of the layer. + */ + getBrightness(): number; + + /** + * Return the contrast of the layer. + * @returns The contrast of the layer. + */ + getContrast(): number; + + /** + * Return the extent of the layer or undefined if it will be visible regardless of extent. + * @returns The layer extent. + */ + getExtent(): ol.Extent; + + /** + * Return the hue of the layer. + * @returns The hue of the layer + */ + getHue(): number; + + /** + * Return the maximum resolution of the layer. + * @returns The maximum resolution of the layer + */ + getMaxResolution(): number; + + /** + * Return the minimum resolution of the layer. + * @returns The minimum resolution of the layer. + */ + getMinResolution(): number; + + /** + * Return the opacity of the layer (between 0 and 1). + * @returns The opacity of the layer. + */ + getOpacity(): number; + + /** + * Return the saturation of the layer. + * @returns The saturation of the layer. + */ + getSaturation(): number; + + /** + * Return the visibility of the layer (true or false). + * The visibility of the layer + */ + getVisible(): boolean; + + /** + * Adjust the layer brightness. A value of -1 will render the layer completely black. A value of 0 will leave the brightness unchanged. A value of 1 will render the layer completely white. Other values are linear multipliers on the effect (values are clamped between -1 and 1). + * @param brightness The brightness of the layer + */ + setBrightness(brightness: number): void; + + /** + * Adjust the layer contrast. A value of 0 will render the layer completely grey. A value of 1 will leave the contrast unchanged. Other values are linear multipliers on the effect (and values over 1 are permitted). + * @param contrast The contrast of the layer + */ + setContrast(contrast: number): void; + + /** + * Set the extent at which the layer is visible. If undefined, the layer will be visible at all extents. + * @param extent The extent of the layer + */ + setExtent(extent?: ol.Extent): void; + + /** + * Apply a hue-rotation to the layer. A value of 0 will leave the hue unchanged. Other values are radians around the color circle. + * @param hue The hue of the layer + */ + setHue(hue: number): void; + + /** + * Set the maximum resolution at which the layer is visible. + * @param maxResolution The maximum resolution of the layer. + */ + setMaxResolution(maxResolution: number): void; + + /** + * Set the minimum resolution at which the layer is visible. + * @param minResolution The minimum resolution of the layer. + */ + setMinResolution(minResolution: number): void; + + /** + * Set the opacity of the layer, allowed values range from 0 to 1. + * @param opacity The opacity of the layer. + */ + setOpacity(opacity: number): void; + + /** + * Adjust layer saturation. A value of 0 will render the layer completely unsaturated. A value of 1 will leave the saturation unchanged. Other values are linear multipliers of the effect (and values over 1 are permitted). + * @param saturation The saturation of the layer. + */ + setSaturation(saturation: number): void; + + /** + * Set the visibility of the layer (true or false). + * @param visible The visibility of the layer. + */ + setVisible(visible: boolean): void; + } + + /** + * A ol.Collection of layers that are handled together. + */ + class Group extends ol.layer.Base { + + /** + * @constructor + * @param options Layer options. + */ + constructor(options?: olx.layer.GroupOptions); + + /** + * Returns the collection of layers in this group. + * @returns Collection of layers that are part of this group. + */ + getLayers(): ol.Collection; + + /** + * Set the collection of layers in this group. + * @param layers Collection of layers that are part of this group. + */ + setLayers(layers: ol.Collection): void; + } + + /** + * Layer for rendering vector data as a heatmap. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Heatmap extends ol.layer.Vector { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.layer.HeatmapOptions); + + /** + * Return the blur size in pixels. + * @returns Blur size in pixels + */ + getBlur(): number; + + /** + * Return the gradient colors as array of strings. + * @returns Colors + */ + getGradient(): Array; + + /** + * Return the size of the radius in pixels. + * @returns Radius size in pixel + */ + getRadius(): number; + + /** + * Set the blur size in pixels. + * @param blur Blur size in pixels + */ + setBlur(blur: number): void; + + /** + * Set the gradient colors as array of strings. + * @param colors Gradient + */ + setGradient(colors: Array): void; + + /** + * Set the size of the radius in pixels. + * @param radius Radius size in pixels + */ + setRadius(radius: number): void; + } + + /** + * Server-rendered images that are available for arbitrary extents and resolutions. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Image extends ol.layer.Layer { + + /** + * @constructor + * @param options Layer options + */ + constructor(options?: olx.layer.ImageOptions); + + /** + * Return the associated source of the image layer. + * @returns Source. + */ + getSource(): ol.source.Image; + } + + /** + * Abstract base class; normally only used for creating subclasses and not instantiated in apps. A visual representation of raster or vector map data. Layers group together those properties that pertain to how the data is to be displayed, irrespective of the source of that data. + */ + class Layer extends ol.layer.Base { + + /** + * @constructor + * @param options Layer options + */ + constructor(options?: olx.layer.LayerOptions); + + /** + * Get the layer source. + * @returns The layer source (or null if not yet set) + */ + getSource(): ol.source.Source; + + /** + * Set the layer source. + * @param source The layer source. + */ + setSource(source: ol.source.Source): void; + } + + /** + * For layer sources that provide pre-rendered, tiled images in grids that are organized by zoom levels for specific resolutions. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Tile extends ol.layer.Layer { + + /** + * @constructor + * @param options Tile layer options. + */ + constructor(options?: olx.layer.TileOptions); + + /** + * Return the level as number to which we will preload tiles up to. + * @retruns The level to preload tiled up to. + */ + getPreload(): number; + + /** + * Return the associated tilesource of the layer. + * @returns Source + */ + getSource(): ol.source.Tile; + + /** + * Whether we use interim tiles on error. + * @returns Use interim tiles on error. + */ + getUseInterimTilesOnError(): boolean; + + /** + * Set the level as number to which we will preload tiles up to. + * @param preload The level to preload tiled up to + */ + setPreload(preload: number): void; + + /** + * Set whether we use interim tiles on error. + * @param useInterimTilesOnError Use interim tiles on error. + */ + setUseInterimTilesOnError(useInterimTilesOnError: boolean): void; + } + + /** + * Vector data that is rendered client-side. Note that any property set in the options is set as a ol.Object property on the layer object; for example, setting title: 'My Title' in the options means that title is observable, and has get/set accessors. + */ + class Vector extends ol.layer.Layer { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.layer.VectorOptions); + + /** + * Return the associated vectorsource of the layer. + * @returns Source. + */ + getSource(): ol.source.Vector; + + /** + * Get the style for features. This returns whatever was passed to the style option at construction or to the setStyle method. + */ + getStyle(): ol.style.Style | Array | ol.style.StyleFunction; + + /** + * Get the style function. + * @returns Layer style function + */ + getStyleFunction(): ol.style.StyleFunction; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + */ + setStyle(): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param style Layer style + */ + setStyle(style: ol.style.Style): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param style Layer style + */ + setStyle(style: Array): void; + + /** + * Set the style for features. This can be a single style object, an array of styles, or a function that takes a feature and resolution and returns an array of styles. If it is undefined the default style is used. If it is null the layer has no style (a null style), so only features that have their own styles will be rendered in the layer. See ol.style for information on the default style. + * @param style Layer style + */ + setStyle(style: ol.style.StyleFunction): void; + + /** + * Sets the layer to be rendered on top of other layers on a map. The map will not manage this layer + * in its layers collection, and the callback in ol.Map#forEachLayerAtPixel will receive null as + * layer. This is useful for temporary layers. To remove an unmanaged layer from the map, use #setMap(null). + * To add the layer to a map and have it managed by the map, use ol.Map#addLayer instead. + * @argument map. + */ + setMap(map: ol.Map): void; + } + } + + namespace loadingstrategy { + + /** + * Strategy function for loading all features with a single request. + * @param extent Extent + * @param resolution Resolution + * @returns Extents + */ + function all(extent: ol.Extent, resolution: number): Array; + + /** + * Strategy function for loading features based on the view's extent and resolution. + * @param extent Extent + * @param resolution Resolution + * @returns Extents + */ + function bbox(extent: ol.Extent, resolution: number): Array; + + /** + * Creates a strategy function for loading features based on a tile grid. + * @param tileGrid Tile grid + * @returns Loading strategy + */ + function tile(tileGrid: ol.tilegrid.TileGrid): ol.LoadingStrategy; + } + + namespace pointer { + + class PointerEvent { + constructor (type: string, + originalEvent: Event, + opt_eventDict?: {[x: string]: any}) + originalEvent: Event; + buttons: number; + pressure: number; + bubbles: boolean; + cancelable: boolean; + view: Object; + detail: number; + screenX: number; + screenY: number; + clientX: number; + clientY: number; + ctrlKey: boolean; + altKey: boolean; + shiftKey: boolean; + metaKey: boolean; + button: number; + relatedTarget: Node; + pointerId: number; + width: number; + height: number; + tiltX: number; + tiltY: number; + pointerType: string; + hwTimestamp: number; + isPrimary: boolean; + preventDefault: () => void; + } + + } + + namespace proj { + + // Type definitions + interface ProjectionLike extends String { } + interface Units extends String { } + + // Methods + + /** + * Meters per unit lookup table. + */ + //TODO: validate! + var METERS_PER_UNIT: GlobalObject; + + /** + * Registers coordinate transform functions to convert coordinates between the source projection and the destination projection. The forward and inverse functions convert coordinate pairs; this function converts these into the functions used internally which also handle extents and coordinate arrays. + * @param source Source projection + * @param destination Destination projection + * @param forward The forward transform function (that is, from the source projection to the destination projection) that takes a ol.Coordinate as argument and returns the transformed ol.Coordinate. + * @param inverse The inverse transform function (that is, from the destination projection to the source projection) that takes a ol.Coordinate as argument and returns the transformed ol.Coordinate. + */ + function addCoordinateTransforms(source: ProjectionLike, destination: ProjectionLike, forward: (coordinate: Coordinate) => Coordinate, inverse: (coordinate: Coordinate) => Coordinate): void; + + /** + * Registers transformation functions that don't alter coordinates. Those allow to transform between projections with equal meaning. + * @param projections Projections. + */ + function addEquivalentProjections(projections: Array): void; + + /** + * Add a Projection object to the list of supported projections that can be looked up by their code. + * @param projection Projection instance. + */ + function addProjection(projection: Projection): void; + + /** + * Transforms a coordinate from longitude/latitude to a different projection. + * @param coordinate Coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. + * @param opt_projection Target projection. The default is Web Mercator, i.e. 'EPSG:3857'. + */ + function fromLonLat(coordinate: Coordinate, opt_projection: ProjectionLike): Coordinate; + + /** + * Fetches a Projection object for the code specified. + * @param projectionLike Either a code string which is a combination of authority and identifier such as "EPSG:4326", or an existing projection object, or undefined. + * @returns Projection object, or null if not in list. + */ + function get(projectionLike: ProjectionLike): Projection; + + /** + * Given the projection-like objects, searches for a transformation function to convert a coordinates array from the source projection to the destination projection. + * @param source Source. + * @param destination Destination. + * @returns Transform function. + */ + function getTransform(source: ProjectionLike, destination: ProjectionLike): ol.TransformFunction; + + /** + * Transforms a coordinate to longitude/latitude. + * @param coordinate Projected coordinate. + * @param projection Projection of the coordinate. The default is Web Mercator, i.e. 'EPSG:3857'. + * @returns Coordinate as longitude and latitude, i.e. an array with longitude as 1st and latitude as 2nd element. + */ + function toLonLat(coordinate: Coordinate, projection: ProjectionLike): Coordinate; + + /** + * Transforms a coordinate from source projection to destination projection. This returns a new coordinate (and does not modify the original). + * @param coordinate Coordinate. + * @param source Source projection-like. + * @param destination Destination projection-like. + * @returns Coordinate. + */ + function transform(coordinate: Coordinate, source: ProjectionLike, destination: ProjectionLike): Coordinate; + + /** + * Transforms an extent from source projection to destination projection. This returns a new extent (and does not modify the original). + * @param extent The extent to transform. + * @param source Source projection-like. + * @param destination Destination projection-like. + * @returns The transformed extent. + */ + function transformExtent(extent: Extent, source: ProjectionLike, destination: ProjectionLike): Extent; + + class Projection { + constructor(options: olx.Projection); + + getExtent(): Extent; + + /** + * Set the validity extent for this projection. + * @param extent The new extent of the projection. + */ + setExtent(extent: Extent): void; + + getCode(): string; + + getMetersPerUnit(): number; + + getPointResolution(resolution: number, point: ol.Coordinate): number; + + getUnits(): ol.proj.Units; + + getWorldExtent(): ol.Extent; + + isGlobal(): boolean; + + setGetPointResolution(func: (n: number, c: ol.Coordinate) => number): void; + + setGlobal(global: boolean): void; + + setWorldExtent(worldExtent: ol.Extent): void; + } + } + + namespace render { + + class Event { + } + + class VectorContext { + } + class Feature { + get(key: string): any; + getExtent(): ol.Extent; + getGeometry(): ol.geom.Geometry; + getProperties: GlobalObject[]; + getType(): ol.geom.GeometryType; + } + namespace canvas { + class Immediate { + } + } + } + + namespace source { + + class BingMaps extends TileImage { + } + + class CartoDB extends XYZ { + } + + class Cluster extends Vector { + } + + class Image extends Source { + } + + class ImageArcGISRest extends Image { + } + + class ImageCanvas extends Image { + } + + class ImageEvent { + } + + class ImageMapGuide extends Image { + } + + class ImageStatic extends Image { + } + + class ImageVector extends ImageCanvas { + } + + class ImageWMS extends Image { + constructor(options: olx.ImageWMSOptions); + } + + class MapQuest extends XYZ { + constructor(options: any); + } + + class OSM extends XYZ { + } + + class Source extends ol.Object { + getAttributions(): Array; + + getLogo(): string | olx.LogoOptions | void; + + /** + * Get the projection of the source. + * @return Projection. + */ + getProjection(): ol.proj.Projection; + + getState(): ol.source.State; + + setAttributions(attributions: Array): void; + } + + class Stamen extends XYZ { + } + + class Tile extends Source { + } + + class TileArcGISRest extends TileImage { + } + + class TileDebug extends Tile { + } + + class TileEvent { + } + + class TileImage extends UrlTile { + } + + class TileJSON extends TileImage { + } + + class TileUTFGrid extends Tile { + } + + class TileWMS extends TileImage { + constructor(options: olx.TileWMSOptions); + + /** + * Update the user-provided (WMS request) parameters. + */ + updateParams(params: any): void; + + /** + * Get the user-provided (WMS request) params, i.e. those passed to the constructor through the "params" option, and possibly updated using the updateParams method. + */ + getParams(): any; + + /** + * Return the GetFeatureInfo URL for the passed coordinate, resolution, and + * projection. Return `undefined` if the GetFeatureInfo URL cannot be + * constructed. + * @param coordinate Coordinate. + * @param resolution Resolution. + * @param projection Projection. + * @param params GetFeatureInfo params. `INFO_FORMAT` at least should + * be provided. If `QUERY_LAYERS` is not provided then the layers specified + * in the `LAYERS` parameter will be used. `VERSION` should not be + * specified here. + * @return GetFeatureInfo URL. + */ + getGetFeatureInfoUrl(coordinate: ol.Coordinate, resolution: number, projection: ol.proj.ProjectionLike, params: {}): string; + } + + class UrlTile extends Tile { + } + + class Vector extends Source { + constructor(opts?: olx.source.VectorOptions) + /** + * Add a single feature to the source. If you want to add a batch of features at once, + * call source.addFeatures() instead. + */ + addFeature(feature: ol.Feature): void; + + /** + * Add a batch of features to the source. + */ + addFeatures(features: ol.Feature[]): void; + + /** + * Remove all features from the source. + * @param opt_fast Skip dispatching of removefeature events. + */ + clear(opt_fast?: boolean): void; + + forEachFeature(callback: (f: ol.Feature) => any, opt_this?: any): any; + + forEachFeatureInExtent(extent: ol.Extent, callback: (f: ol.Feature) => any, opt_this?: any): any; + + forEachFeatureIntersectingExtent(extent: ol.Extent, callback: (f: ol.Feature) => any, opt_this?: any): any; + + getClosestFeatureToCoordinate(coordinate: ol.Coordinate): ol.Feature; + + /** + * Get the extent of the features currently in the source. + */ + getExtent(): ol.Extent; + + getFeatureById(id: string | number): ol.Feature; + + /** + * Get all features on the source + */ + getFeatures(): ol.Feature[]; + + /** + * Get all features whose geometry intersects the provided coordinate. + */ + getFeaturesAtCoordinate(coordinate: ol.Coordinate): ol.Feature[]; + + getFeaturesCollection(): ol.Collection; + + /** + * Get all features in the provided extent. Note that this returns all features whose bounding boxes + * intersect the given extent (so it may include features whose geometries do not intersect the extent). + * This method is not available when the source is configured with useSpatialIndex set to false. + */ + getFeaturesInExtent(extent: ol.Extent): ol.Feature[]; + + removeFeature(feature: ol.Feature): void; + } + + class VectorEvent { + } + + class VectorTile extends UrlTile { + } + + class WMTS extends TileImage { + constructor(options: olx.source.WMTSOptions); + } + + class XYZ extends TileImage { + } + + class Zoomify extends TileImage { + } + + // Namespaces + namespace wms { + interface ServerType extends String { } + } + + // Type definitions + interface State extends String { } + interface WMTSRequestEncoding extends String { } + } + + namespace style { + + class AtlasManager { + } + + class Circle extends Image { + constructor(opt_options?: olx.style.CircleOptions); + } + + /** + * Set fill style for vector features. + */ + class Fill { + + constructor(opt_options?: olx.style.FillOptions); + + getColor(): ol.Color | string; + + /** + * Set the color. + */ + setColor(color: ol.Color | string): void; + + getChecksum(): string; + } + + class Icon extends Image { + constructor(option: olx.style.IconOptions) + } + + class Image { + getOpacity(): number; + getRotateWithView(): boolean; + getRotation(): number; + getScale(): number; + getSnapToPiexl(): boolean; + + setOpacity(opacity: number): void; + setRotation(rotation: number): void; + setScale(scale: number): void; + } + + interface GeometryFunction { + (feature: Feature): ol.geom.Geometry + } + + class RegularShape { + } + + class Stroke { + constructor(opts?: olx.style.StrokeOptions); + getColor(): ol.Color | string; + getLineCap(): string; + getLineDash(): number[]; + getLineJoin(): string; + getMitterLimit(): number; + getWidth(): number; + setColor(color: ol.Color | string): void; + setLineCap(lineCap: string): void; + setLineDash(lineDash: number[]): void; + setLineJoin(lineJoin: string): void; + setMiterLimit(miterLimit: number): void; + setWidth(width: number): void; + } + + /** + * Container for vector feature rendering styles. Any changes made to the style + * or its children through `set*()` methods will not take effect until the + * feature, layer or FeatureOverlay that uses the style is re-rendered. + */ + class Style { + constructor(opts: olx.style.StyleOptions); + + getFill(): ol.style.Fill; + /*** + * Get the geometry to be rendered. + * @return Feature property or geometry or function that returns the geometry that will + * be rendered with this style. + */ + getGeometry(): string | ol.geom.Geometry | ol.style.GeometryFunction; + getGeometryFunction(): ol.style.GeometryFunction; + getImage(): ol.style.Image; + getStroke(): ol.style.Stroke; + getText(): ol.style.Text; + getZIndex(): number; + + setGeometry(geometry: string | ol.geom.Geometry | ol.style.GeometryFunction): void; + setZIndex(zIndex: number): void; + } + + /** + * Set text style for vector features. + */ + class Text { + constructor(opt?: olx.style.TextOptions); + + getFont(): string; + getOffsetX(): number; + getOffsetY(): number; + getFill(): Fill; + getRotation(): number; + getScale(): number; + getStroke(): Stroke; + getText(): string; + getTextAlign(): string; + getTextBaseline(): string; + + /** + * Set the font. + */ + setFont(font: string): void; + + /** + * Set the x offset. + */ + setOffsetX(offsetX: number): void; + + /** + * Set the y offset. + */ + setOffsetY(offsetY: number): void; + + /** + * Set the fill. + */ + setFill(fill: Fill): void; + + /** + * Set the rotation. + */ + setRotation(rotation: number): void; + + /** + * Set the scale. + */ + setScale(scale: number): void; + + /** + * Set the stroke. + * + */ + setStroke(stroke: Stroke): void; + + /** + * Set the text. + */ + setText(text: string): void; + + /** + * Set the text alignment. + */ + setTextAlign(textAlign: string): void; + + /** + * Set the text baseline. + */ + setTextBaseline(textBaseline: string): void; + } + + /** + * A function that takes an ol.Feature and a {number} representing the view's resolution. The function should return an array of ol.style.Style. This way e.g. a vector layer can be styled. + */ + interface StyleFunction { (feature: ol.Feature, resolution: number): ol.style.Style } + } + + namespace tilegrid { + + /** + * Base class for setting the grid pattern for sources accessing tiled-image servers. + */ + class TileGrid { + + /** + * @constructor + * @param options Tile grid options + */ + constructor(options: olx.tilegrid.TileGridOptions); + + /** + * Creates a TileCoord transform function for use with this tile grid. Transforms the internal tile coordinates with bottom-left origin to the tile coordinates used by the ol.TileUrlFunction. The returned function expects an ol.TileCoord as first and an ol.proj.Projection as second argument and returns a transformed ol.TileCoord. + */ + createTileCoordTransform(): { (tilecoord: ol.TileCoord, projection: ol.proj.Projection): ol.TileCoord }; + + /** + * Get the maximum zoom level for the grid. + * @returns Max zoom + */ + getMaxZoom(): number; + + /** + * Get the minimum zoom level for the grid. + * @returns Min zoom + */ + getMinZoom(): number; + + /** + * Get the origin for the grid at the given zoom level. + * @param z Z + * @returns Origin + */ + getOrigin(z: number): ol.Coordinate; + + /** + * Get the list of resolutions for the tile grid. + * @param z Z + * @returns Resolution + */ + getResolution(z: number): number; + + /** + * Get the list of resolutions for the tile grid. + * @returns Resolutions + */ + getResolutions(): Array; + + /** + * Get the tile coordinate for the given map coordinate and resolution. This method considers that coordinates that intersect tile boundaries should be assigned the higher tile coordinate. + * @param coordinate Coordinate + * @param resolution Resolution + * @param tileCoord Destination ol.TileCoord object. + * @returns Tile coordinate + */ + getTileCoordForCoordAndResolution(coordinate: ol.Coordinate, resolution: number, tileCoord?: ol.TileCoord): ol.TileCoord; + + /** + * Get a tile coordinate given a map coordinate and zoom level. + * @param coordinate Coordinate + * @param z Zoom level + * @param tileCoord Destination ol.TileCoord object + * @returns Tile coordinate + */ + getTileCoordForCoordAndZ(coordinate: ol.Coordinate, z: number, tileCoord?: ol.TileCoord): ol.TileCoord; + + /** + * Get the tile size for a zoom level. The type of the return value matches the tileSize or tileSizes that the tile grid was configured with. To always get an ol.Size, run the result through ol.size.toSize(). + * @param z Z + * @returns Tile size + */ + getTileSize(z: number): number | ol.Size; + } + + /** + * Set the grid pattern for sources accessing WMTS tiled-image servers. + */ + class WMTS extends TileGrid { + + /** + * @constructor + * @param options WMTS options + */ + constructor(options: olx.tilegrid.WMTSOptions); + + /** + * Create a tile grid from a WMTS capabilities matrix set. + * @param matrixSet An object representing a matrixSet in the capabilities document. + * @param extent An optional extent to restrict the tile ranges the server provides. + * @returns WMTS tilegrid instance + */ + createFromCapabilitiesMatrixSet(matrixSet: any, extent: ol.Extent): ol.tilegrid.WMTS; + + /** + * Get the list of matrix identifiers. + * @returns MatrixIds + */ + getMatrixIds(): Array; + } + + /** + * Set the grid pattern for sources accessing Zoomify tiled-image servers. + */ + class Zoomify extends TileGrid { + + /** + * @constructor + * @param options Options + */ + constructor(options?: olx.tilegrid.ZoomifyOptions); + } + + /** + * Creates a tile grid with a standard XYZ tiling scheme. + * @param options Tile grid options. + * @returns The grid instance + */ + function createXYZ(options?: olx.tilegrid.XYZOptions): ol.tilegrid.TileGrid; + } + + namespace webgl { + + class Context { + + /** + * @constructor + * @param canvas HTML Canvas Element + * @param gl WebGL Rendering context + */ + constructor(canvas: HTMLCanvasElement, gl: WebGLRenderingContext); + + /** + Get the WebGL rendering context + @returns The rendering context. + */ + getGL(): WebGLRenderingContext; + + /** + * Get the frame buffer for hit detection. + * @returns The hit detection frame buffer. + */ + getHitDetectionFramebuffer(): WebGLFramebuffer; + + /** + * Use a program. If the program is already in use, this will return false. + * @param program Program. + * @returns Changed. + */ + useProgram(program: WebGLProgram): boolean; + } + } + + // Type definitions + + /** + * A function returning the canvas element ({HTMLCanvasElement}) used by the source as an image. The arguments passed to the function are: ol.Extent the image extent, {number} the image resolution, {number} the device pixel ratio, ol.Size the image size, and ol.proj.Projection the image projection. The canvas returned by this function is cached by the source. The this keyword inside the function references the ol.source.ImageCanvas. + */ + function CanvasFunctionType(extent: Extent, resolution: number, pixelRatio: number, size: Size, projection: proj.Projection): HTMLCanvasElement; + + /** + * A color represented as a short array [red, green, blue, alpha]. red, green, and blue should be integers in the range 0..255 inclusive. alpha should be a float in the range 0..1 inclusive. + */ + interface Color extends Array { } + + /** + * An array of numbers representing an xy coordinate. Example: [16, 48]. + */ + interface Coordinate extends Array { } + + /** + * An array of numbers representing an extent: [minx, miny, maxx, maxy]. + */ + interface Extent extends Array { } + + /** + * Overlay position: 'bottom-left', 'bottom-center', 'bottom-right', 'center-left', 'center-center', 'center-right', 'top-left', 'top-center', 'top-right' + */ + interface OverlayPositioning extends String { } + + /** + * An array with two elements, representing a pixel. The first element is the x-coordinate, the second the y-coordinate of the pixel. + */ + interface Pixel extends Array { } + + /** + * Available renderers: 'canvas', 'dom' or 'webgl'. + */ + interface RendererType extends String { } + + /** + * An array of numbers representing a size: [width, height]. + */ + interface Size extends Array { } + + /** + * An array of three numbers representing the location of a tile in a tile grid. The order is z, x, and y. z is the zoom level. + */ + interface TileCoord extends Array { } + + // Functions + + /** + * A function that takes a ol.Coordinate and transforms it into a {string}. + */ + interface CoordinateFormatType { (coordinate?: Coordinate): string; } + + /** + * Implementation based on the code of OpenLayers, no documentation available (yet). If it is incorrect, please create an issue and I will change it. + */ + interface FeatureLoader { (extent: ol.Extent, number: number, projection: ol.proj.Projection): string } + + /** + * A function that returns a style given a resolution. The this keyword inside the function references the ol.Feature to be styled. + */ + interface FeatureStyleFunction { (resolution: number): ol.style.Style } + + /** + * Loading strategy + */ + interface LoadingStrategy { (extent: ol.Extent, resolution: number): Array } + + /** + * Function to perform manipulations before rendering. This function is called with the ol.Map as first and an optional olx.FrameState as second argument. Return true to keep this function for the next frame, false to remove it. + */ + interface PreRenderFunction { (map: ol.Map, frameState?: olx.FrameState): boolean } + + /** + * A transform function accepts an array of input coordinate values, an optional output array, and an optional dimension (default should be 2). The function transforms the input coordinate values, populates the output array, and returns the output array. + */ + interface TransformFunction { (input: Array, output?: Array, dimension?: number): Array } +} + +declare module "openlayers" { + export = ol; +} From fc595bd854e0f619b538277f165e7537aa44255e Mon Sep 17 00:00:00 2001 From: Shant Marouti Date: Wed, 20 Jul 2016 03:53:27 +0430 Subject: [PATCH 0092/1255] Add definitions for app-root-path and gulp-insert (#10118) * add app-root-path type difinitions * Add defenitions for gulp-insert --- app-root-path/app-root-path-tests.ts | 10 ++++++ app-root-path/app-root-path.d.ts | 39 +++++++++++++++++++++ gulp-insert/gulp-insert-tests.ts | 21 +++++++++++ gulp-insert/gulp-insert.d.ts | 52 ++++++++++++++++++++++++++++ 4 files changed, 122 insertions(+) create mode 100644 app-root-path/app-root-path-tests.ts create mode 100644 app-root-path/app-root-path.d.ts create mode 100644 gulp-insert/gulp-insert-tests.ts create mode 100644 gulp-insert/gulp-insert.d.ts diff --git a/app-root-path/app-root-path-tests.ts b/app-root-path/app-root-path-tests.ts new file mode 100644 index 0000000000..64d8cdab6b --- /dev/null +++ b/app-root-path/app-root-path-tests.ts @@ -0,0 +1,10 @@ +/// +import * as root from 'app-root-path'; + +let resolvedPath: string; +resolvedPath = root.resolve('../dir'); +resolvedPath = root.path; +resolvedPath = root.toString(); +let resolvedModule: any = root.require('app-root-path'); +root.setPath('C:\\app-root'); + diff --git a/app-root-path/app-root-path.d.ts b/app-root-path/app-root-path.d.ts new file mode 100644 index 0000000000..7cccc59e01 --- /dev/null +++ b/app-root-path/app-root-path.d.ts @@ -0,0 +1,39 @@ +// Type definitions for app-root-path 1.2.1 +// Project: https://github.com/inxilpro/node-app-root-path +// Definitions by: Shant Marouti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'app-root-path' { + interface RootPath { + + /** + * Application root directory absolute path + * @type {string} + */ + path: string; + + /** + * Resolves relative path from root to absolute path + * @param {string} pathToModule + * @returns {string} + */ + resolve(pathToModule: string): string; + + /** + * Resolve module by relative addressing from root + * @param {string} pathToModule + * @returns {*} + */ + require(pathToModule: string): any; + + /** + * Explicitly set root path + * @param {string} explicitlySetPath + */ + setPath(explicitlySetPath: string): void; + + toString(): string; + } + var RootPath: RootPath; + export = RootPath; +} \ No newline at end of file diff --git a/gulp-insert/gulp-insert-tests.ts b/gulp-insert/gulp-insert-tests.ts new file mode 100644 index 0000000000..e420cf5e4a --- /dev/null +++ b/gulp-insert/gulp-insert-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import * as gulp from 'gulp'; +import * as insert from 'gulp-insert'; + +gulp.task('gulp-insert-tests', () => { + return gulp.src('*.js') + .pipe(insert.prepend('/* Inserted using gulp-insert prepend method */\n')) + .pipe(insert.prepend('\n/* Inserted using gulp-insert append method */')) + .pipe(insert.wrap( + '/* Inserted using gulp-insert wrap method */\n', + '\n/* Inserted using gulp-insert wrap method */' + )) + .pipe(insert.transform((contents, file) => { + var comment = '/* Local file: ' + file.path + ' */\n'; + return comment + contents; + })) + .pipe(gulp.dest('gulp-insert')); +}); + diff --git a/gulp-insert/gulp-insert.d.ts b/gulp-insert/gulp-insert.d.ts new file mode 100644 index 0000000000..9777280d5b --- /dev/null +++ b/gulp-insert/gulp-insert.d.ts @@ -0,0 +1,52 @@ +// Type definitions for gulp-insert 0.5.0 +// Project: https://github.com/rschmukler/gulp-insert +// Definitions by: Shant Marouti +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare module 'gulp-insert' { + + import File = require('vinyl'); + + interface Transformer { + (contents: string, file: File): string + } + + namespace Insert { + + /** + * Prepends a string onto the contents + * @param {string} content + * @returns {NodeJS.ReadWriteStream} + */ + function prepend(content: string): NodeJS.ReadWriteStream; + + /** + * Appends a string onto the contents + * @param {string} content + * @returns {NodeJS.ReadWriteStream} + */ + function append(content: string): NodeJS.ReadWriteStream; + + /** + * Wraps the contents with two strings + * @param {string} prepend + * @param {string} append + * @returns {NodeJS.ReadWriteStream} + */ + function wrap(prepend: string, append: string): NodeJS.ReadWriteStream; + + /** + * Calls a function with the contents of the file + * @param {Transformer} transformer + * @returns {NodeJS.ReadWriteStream} + */ + function transform(transformer: Transformer): NodeJS.ReadWriteStream; + + } + + module Insert { } + export = Insert; +} \ No newline at end of file From 1074806a34bffcbedf3a4fb9556a8c3c8ccc5e9d Mon Sep 17 00:00:00 2001 From: Mitchell Wills Date: Tue, 19 Jul 2016 16:25:14 -0700 Subject: [PATCH 0093/1255] Rename Pako namespace to pako to allow use with browserifyed library (#10124) --- pako/pako.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pako/pako.d.ts b/pako/pako.d.ts index 9f7d84df39..816c1a5ad3 100644 --- a/pako/pako.d.ts +++ b/pako/pako.d.ts @@ -3,7 +3,7 @@ // Definitions by: Denis Cappellin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace Pako { +declare namespace pako { /** * Compress data with deflate algorithm and options. @@ -59,5 +59,5 @@ declare namespace Pako { } declare module 'pako' { - export = Pako; + export = pako; } From 4c7d03b088d4e71cd9fe9c66ab7bd363049077c3 Mon Sep 17 00:00:00 2001 From: Ruben Slabbert Date: Wed, 20 Jul 2016 09:25:34 +1000 Subject: [PATCH 0094/1255] React-Native: Added ActivityIndicator (#10122) * React-Native: Added ActivityIndicator * React Native: Added @Deprecated to ActivityIndicatorIOS and changed string type to enum type on ActivityIndicator size --- react-native/react-native.d.ts | 42 +++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/react-native/react-native.d.ts b/react-native/react-native.d.ts index ad8b3553fb..74a86e27b7 100644 --- a/react-native/react-native.d.ts +++ b/react-native/react-native.d.ts @@ -1741,6 +1741,41 @@ declare namespace __React { } + /** + * @see https://facebook.github.io/react-native/docs/activityindicator.html#props + */ + export interface ActivityIndicatorProperties extends React.Props { + + /** + * Whether to show the indicator (true, the default) or hide it (false). + */ + animating?: boolean + + /** + * The foreground color of the spinner (default is gray). + */ + color?: string + + /** + * Whether the indicator should hide when not animating (true by default). + */ + hidesWhenStopped?: boolean + + /** + * Size of the indicator. + * Small has a height of 20, large has a height of 36. + * + * enum('small', 'large') + */ + size?: 'small' | 'large' + + style?: ViewStyle + } + + export interface ActivityIndicatorStatic extends React.ComponentClass { + } + + /** * @see https://facebook.github.io/react-native/docs/activityindicatorios.html#props */ @@ -1772,11 +1807,14 @@ declare namespace __React { * * enum('small', 'large') */ - size?: string + size?: 'small' | 'large' style?: ViewStyle } + /** + * @Deprecated since version 0.28.0 + */ export interface ActivityIndicatorIOSStatic extends React.ComponentClass { } @@ -5585,6 +5623,8 @@ declare namespace __React { // export var AppRegistry: AppRegistryStatic; + export var ActivityIndicator: ActivityIndicatorStatic + export type ActivityIndicator = ActivityIndicatorStatic export var ActivityIndicatorIOS: ActivityIndicatorIOSStatic export type ActivityIndicatorIOS = ActivityIndicatorIOSStatic From 47b9697e0de05e57806bc25b52c01d4b3d183dce Mon Sep 17 00:00:00 2001 From: lincoln <359972883@qq.com> Date: Wed, 20 Jul 2016 07:33:12 +0800 Subject: [PATCH 0095/1255] filename argument of fs.watch callback will be type of Buffer, if encoding (#10112) option is set to 'buffer' --- node/node.d.ts | 252 +++++++++++++++++++++++++------------------------ 1 file changed, 127 insertions(+), 125 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index ad764938a0..0a85883357 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -21,10 +21,10 @@ interface ErrorConstructor { // compat for TypeScript 1.8 // if you use with --target es3 or --target es5 and use below definitions, // use the lib.es6.d.ts that is bundled with TypeScript 1.8. -interface MapConstructor {} -interface WeakMapConstructor {} -interface SetConstructor {} -interface WeakSetConstructor {} +interface MapConstructor { } +interface WeakMapConstructor { } +interface SetConstructor { } +interface WeakSetConstructor { } /************************************************ * * @@ -49,7 +49,7 @@ interface NodeRequireFunction { } interface NodeRequire extends NodeRequireFunction { - resolve(id:string): string; + resolve(id: string): string; cache: any; extensions: any; main: any; @@ -85,7 +85,7 @@ declare var SlowBuffer: { // Buffer class type BufferEncoding = "ascii" | "utf8" | "utf16le" | "ucs2" | "binary" | "hex"; -interface Buffer extends NodeBuffer {} +interface Buffer extends NodeBuffer { } /** * Raw data is stored in instances of the Buffer class. @@ -149,7 +149,7 @@ declare var Buffer: { * @param byteOffset * @param length */ - from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?:number): Buffer; + from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. * @@ -209,20 +209,20 @@ declare var Buffer: { * If parameter is omitted, buffer will be filled with zeros. * @param encoding encoding used for call to buf.fill while initalizing */ - alloc(size: number, fill?: string|Buffer|number, encoding?: string): Buffer; - /** - * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ + alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ allocUnsafe(size: number): Buffer; - /** - * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents - * of the newly created Buffer are unknown and may contain sensitive data. - * - * @param size count of octets to allocate - */ + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ allocUnsafeSlow(size: number): Buffer; }; @@ -255,7 +255,7 @@ declare namespace NodeJS { export interface ReadableStream extends EventEmitter { readable: boolean; - read(size?: number): string|Buffer; + read(size?: number): string | Buffer; setEncoding(encoding: string): void; pause(): void; resume(): void; @@ -268,7 +268,7 @@ declare namespace NodeJS { export interface WritableStream extends EventEmitter { writable: boolean; - write(buffer: Buffer|string, cb?: Function): boolean; + write(buffer: Buffer | string, cb?: Function): boolean; write(str: string, encoding?: string, cb?: Function): boolean; end(): void; end(buffer: Buffer, cb?: Function): void; @@ -276,7 +276,7 @@ declare namespace NodeJS { end(str: string, encoding?: string, cb?: Function): void; } - export interface ReadWriteStream extends ReadableStream, WritableStream {} + export interface ReadWriteStream extends ReadableStream, WritableStream { } export interface Events extends EventEmitter { } @@ -356,7 +356,7 @@ declare namespace NodeJS { visibility: string; }; }; - kill(pid:number, signal?: string|number): void; + kill(pid: number, signal?: string | number): void; pid: number; title: string; arch: string; @@ -365,7 +365,7 @@ declare namespace NodeJS { nextTick(callback: Function): void; umask(mask?: number): number; uptime(): number; - hrtime(time?:number[]): number[]; + hrtime(time?: number[]): number[]; domain: Domain; // Worker @@ -441,8 +441,8 @@ declare namespace NodeJS { } export interface Timer { - ref() : void; - unref() : void; + ref(): void; + unref(): void; } } @@ -570,7 +570,7 @@ declare module "http" { path?: string; headers?: { [key: string]: any }; auth?: string; - agent?: Agent|boolean; + agent?: Agent | boolean; } export interface Server extends events.EventEmitter, net.Server { @@ -710,7 +710,7 @@ declare module "http" { [errorCode: number]: string; [errorCode: string]: string; }; - export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) =>void ): Server; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; export function createClient(port?: number, host?: string): any; export function request(options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: any, callback?: (res: IncomingMessage) => void): ClientRequest; @@ -794,19 +794,19 @@ declare module "zlib" { export function createInflateRaw(options?: ZlibOptions): InflateRaw; export function createUnzip(options?: ZlibOptions): Unzip; - export function deflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflate(buf: Buffer, callback: (error: Error, result: any) => void): void; export function deflateSync(buf: Buffer, options?: ZlibOptions): any; - export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function deflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; export function deflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function gzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gzip(buf: Buffer, callback: (error: Error, result: any) => void): void; export function gzipSync(buf: Buffer, options?: ZlibOptions): any; - export function gunzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function gunzip(buf: Buffer, callback: (error: Error, result: any) => void): void; export function gunzipSync(buf: Buffer, options?: ZlibOptions): any; - export function inflate(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflate(buf: Buffer, callback: (error: Error, result: any) => void): void; export function inflateSync(buf: Buffer, options?: ZlibOptions): any; - export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function inflateRaw(buf: Buffer, callback: (error: Error, result: any) => void): void; export function inflateRawSync(buf: Buffer, options?: ZlibOptions): any; - export function unzip(buf: Buffer, callback: (error: Error, result: any) =>void ): void; + export function unzip(buf: Buffer, callback: (error: Error, result: any) => void): void; export function unzipSync(buf: Buffer, options?: ZlibOptions): any; // Constants @@ -877,7 +877,7 @@ declare module "os" { export function totalmem(): number; export function freemem(): number; export function cpus(): CpuInfo[]; - export function networkInterfaces(): {[index: string]: NetworkInterfaceInfo[]}; + export function networkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; export var EOL: string; } @@ -923,8 +923,8 @@ declare module "https" { }; export interface Server extends tls.Server { } export function createServer(options: ServerOptions, requestListener?: Function): Server; - export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; - export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) =>void ): http.ClientRequest; + export function request(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; + export function get(options: RequestOptions, callback?: (res: http.IncomingMessage) => void): http.ClientRequest; export var globalAgent: Agent; } @@ -978,7 +978,7 @@ declare module "readline" { pause(): ReadLine; resume(): ReadLine; close(): void; - write(data: string|Buffer, key?: Key): void; + write(data: string | Buffer, key?: Key): void; } export interface Completer { @@ -1003,7 +1003,7 @@ declare module "readline" { export function createInterface(options: ReadLineOptions): ReadLine; export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number|string, dy: number|string): void; + export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; export function clearLine(stream: NodeJS.WritableStream, dir: number): void; export function clearScreenDown(stream: NodeJS.WritableStream): void; } @@ -1045,7 +1045,7 @@ declare module "child_process" { import * as stream from "stream"; export interface ChildProcess extends events.EventEmitter { - stdin: stream.Writable; + stdin: stream.Writable; stdout: stream.Readable; stderr: stream.Readable; stdio: [stream.Writable, stream.Readable, stream.Readable]; @@ -1084,11 +1084,11 @@ declare module "child_process" { export interface ExecOptionsWithBufferEncoding extends ExecOptions { encoding: string; // specify `null`. } - export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); - export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; export interface ExecFileOptions { cwd?: string; @@ -1105,16 +1105,16 @@ declare module "child_process" { export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { encoding: string; // specify `null`. } - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) =>void ): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) =>void ): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; export interface ForkOptions { cwd?: string; @@ -1230,24 +1230,24 @@ declare module "url" { path?: string; } - export function parse(urlStr: string, parseQueryString?: boolean , slashesDenoteHost?: boolean ): Url; + export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url; export function format(url: Url): string; export function resolve(from: string, to: string): string; } declare module "dns" { - export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) =>void ): string; - export function lookup(domain: string, callback: (err: Error, address: string, family: number) =>void ): string; - export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve4(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolve6(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) =>void ): string[]; - export function reverse(ip: string, callback: (err: Error, domains: string[]) =>void ): string[]; + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; + export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; + export function resolve(domain: string, rrtype: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve4(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolve6(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveMx(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveTxt(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveSrv(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveNs(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function resolveCname(domain: string, callback: (err: Error, addresses: string[]) => void): string[]; + export function reverse(ip: string, callback: (err: Error, domains: string[]) => void): string[]; } declare module "net" { @@ -1322,12 +1322,12 @@ declare module "net" { maxConnections: number; connections: number; } - export function createServer(connectionListener?: (socket: Socket) =>void ): Server; - export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) =>void ): Server; - export function connect(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createServer(connectionListener?: (socket: Socket) => void): Server; + export function createServer(options?: { allowHalfOpen?: boolean; }, connectionListener?: (socket: Socket) => void): Server; + export function connect(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function connect(port: number, host?: string, connectionListener?: Function): Socket; export function connect(path: string, connectionListener?: Function): Socket; - export function createConnection(options: { port: number, host?: string, localAddress? : string, localPort? : string, family? : number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; + export function createConnection(options: { port: number, host?: string, localAddress?: string, localPort?: string, family?: number, allowHalfOpen?: boolean; }, connectionListener?: Function): Socket; export function createConnection(port: number, host?: string, connectionListener?: Function): Socket; export function createConnection(path: string, connectionListener?: Function): Socket; export function isIP(input: string): number; @@ -1456,7 +1456,7 @@ declare module "fs" { export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; export function readlinkSync(path: string | Buffer): string; export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string | Buffer, cache: {[path: string]: string}, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; + export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; /* * Asynchronous unlink - deletes the file specified in {path} @@ -1629,8 +1629,8 @@ declare module "fs" { export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, encoding: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string) => any): FSWatcher; + export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; + export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; export function existsSync(path: string | Buffer): boolean; /** Constant for fs.access(). File is visible to the calling process. */ @@ -1645,7 +1645,7 @@ declare module "fs" { export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ - export function accessSync(path: string | Buffer, mode ?: number): void; + export function accessSync(path: string | Buffer, mode?: number): void; export function createReadStream(path: string | Buffer, options?: { flags?: string; encoding?: string; @@ -1779,33 +1779,33 @@ declare module "path" { export function format(pathObject: ParsedPath): string; export module posix { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; } export module win32 { - export function normalize(p: string): string; - export function join(...paths: any[]): string; - export function resolve(...pathSegments: any[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export var sep: string; - export var delimiter: string; - export function parse(p: string): ParsedPath; - export function format(pP: ParsedPath): string; + export function normalize(p: string): string; + export function join(...paths: any[]): string; + export function resolve(...pathSegments: any[]): string; + export function isAbsolute(p: string): boolean; + export function relative(from: string, to: string): string; + export function dirname(p: string): string; + export function basename(p: string, ext?: string): string; + export function extname(p: string): string; + export var sep: string; + export var delimiter: string; + export function parse(p: string): ParsedPath; + export function format(pP: ParsedPath): string; } } @@ -1826,7 +1826,7 @@ declare module "tls" { var CLIENT_RENEG_LIMIT: number; var CLIENT_RENEG_WINDOW: number; - + export interface Certificate { /** * Country code. @@ -1966,7 +1966,7 @@ declare module "tls" { */ setMaxSendFragment(size: number): boolean; } - + export interface TlsOptions { host?: string; port?: number; @@ -2047,10 +2047,10 @@ declare module "tls" { context: any; } - export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) =>void ): Server; - export function connect(options: TlsOptions, secureConnectionListener?: () =>void ): ClearTextStream; - export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; - export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () =>void ): ClearTextStream; + export function createServer(options: TlsOptions, secureConnectionListener?: (cleartextStream: ClearTextStream) => void): Server; + export function connect(options: TlsOptions, secureConnectionListener?: () => void): ClearTextStream; + export function connect(port: number, host?: string, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; + export function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): ClearTextStream; export function createSecurePair(credentials?: crypto.Credentials, isServer?: boolean, requestCert?: boolean, rejectUnauthorized?: boolean): SecurePair; export function createSecureContext(details: SecureContextOptions): SecureContext; } @@ -2086,9 +2086,9 @@ declare module "crypto" { export function createCipheriv(algorithm: string, key: any, iv: any): Cipher; export interface Cipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding: "utf8"|"ascii"|"binary"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "binary"|"base64"|"hex"): string; - update(data: string, input_encoding: "utf8"|"ascii"|"binary", output_encoding: "binary"|"base64"|"hex"): string; + update(data: string, input_encoding: "utf8" | "ascii" | "binary"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "binary" | "base64" | "hex"): string; + update(data: string, input_encoding: "utf8" | "ascii" | "binary", output_encoding: "binary" | "base64" | "hex"): string; final(): Buffer; final(output_encoding: string): string; setAutoPadding(auto_padding: boolean): void; @@ -2098,9 +2098,9 @@ declare module "crypto" { export function createDecipheriv(algorithm: string, key: any, iv: any): Decipher; export interface Decipher extends NodeJS.ReadWriteStream { update(data: Buffer): Buffer; - update(data: string, input_encoding: "binary"|"base64"|"hex"): Buffer; - update(data: Buffer, input_encoding: any, output_encoding: "utf8"|"ascii"|"binary"): string; - update(data: string, input_encoding: "binary"|"base64"|"hex", output_encoding: "utf8"|"ascii"|"binary"): string; + update(data: string, input_encoding: "binary" | "base64" | "hex"): Buffer; + update(data: Buffer, input_encoding: any, output_encoding: "utf8" | "ascii" | "binary"): string; + update(data: string, input_encoding: "binary" | "base64" | "hex", output_encoding: "utf8" | "ascii" | "binary"): string; final(): Buffer; final(output_encoding: string): string; setAutoPadding(auto_padding: boolean): void; @@ -2129,14 +2129,14 @@ declare module "crypto" { setPrivateKey(public_key: string, encoding?: string): void; } export function getDiffieHellman(group_name: string): DiffieHellman; - export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; - export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number) : Buffer; - export function pbkdf2Sync(password: string|Buffer, salt: string|Buffer, iterations: number, keylen: number, digest: string) : Buffer; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string, callback: (err: Error, derivedKey: Buffer) => any): void; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number): Buffer; + export function pbkdf2Sync(password: string | Buffer, salt: string | Buffer, iterations: number, keylen: number, digest: string): Buffer; export function randomBytes(size: number): Buffer; - export function randomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function randomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; export function pseudoRandomBytes(size: number): Buffer; - export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) =>void ): void; + export function pseudoRandomBytes(size: number, callback: (err: Error, buf: Buffer) => void): void; export interface RsaPublicKey { key: string; padding?: any; @@ -2146,8 +2146,8 @@ declare module "crypto" { passphrase?: string, padding?: any; } - export function publicEncrypt(public_key: string|RsaPublicKey, buffer: Buffer): Buffer - export function privateDecrypt(private_key: string|RsaPrivateKey, buffer: Buffer): Buffer + export function publicEncrypt(public_key: string | RsaPublicKey, buffer: Buffer): Buffer + export function privateDecrypt(private_key: string | RsaPrivateKey, buffer: Buffer): Buffer } declare module "stream" { @@ -2211,7 +2211,7 @@ declare module "stream" { end(chunk: any, encoding?: string, cb?: Function): void; } - export interface TransformOptions extends ReadableOptions, WritableOptions {} + export interface TransformOptions extends ReadableOptions, WritableOptions { } // Note: Transform lacks the _read and _write methods of Readable/Writable. export class Transform extends events.EventEmitter implements NodeJS.ReadWriteStream { @@ -2236,7 +2236,7 @@ declare module "stream" { end(chunk: any, encoding?: string, cb?: Function): void; } - export class PassThrough extends Transform {} + export class PassThrough extends Transform { } } declare module "util" { @@ -2260,11 +2260,11 @@ declare module "util" { export function isDate(object: any): boolean; export function isError(object: any): boolean; export function inherits(constructor: any, superConstructor: any): void; - export function debuglog(key:string): (msg:string,...param: any[])=>void; + export function debuglog(key: string): (msg: string, ...param: any[]) => void; } declare module "assert" { - function internal (value: any, message?: string): void; + function internal(value: any, message?: string): void; namespace internal { export class AssertionError implements Error { name: string; @@ -2274,8 +2274,10 @@ declare module "assert" { operator: string; generatedMessage: boolean; - constructor(options?: {message?: string; actual?: any; expected?: any; - operator?: string; stackStartFunction?: Function}); + constructor(options?: { + message?: string; actual?: any; expected?: any; + operator?: string; stackStartFunction?: Function + }); } export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; From c820a48f5e91b29c30660253ecc82f17ed9642dd Mon Sep 17 00:00:00 2001 From: Danilo Bargen Date: Wed, 20 Jul 2016 01:59:50 +0200 Subject: [PATCH 0096/1255] webrtc: Fix type of ondatachannel event (#10094) --- webrtc/RTCPeerConnection-tests.ts | 2 +- webrtc/RTCPeerConnection.d.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/webrtc/RTCPeerConnection-tests.ts b/webrtc/RTCPeerConnection-tests.ts index 9cd8087947..4a9e558ac7 100644 --- a/webrtc/RTCPeerConnection-tests.ts +++ b/webrtc/RTCPeerConnection-tests.ts @@ -41,7 +41,7 @@ navigator.getUserMedia({ audio: true, video: true }, }); peerConnection.onaddstream = ev => console.log(ev.type); -peerConnection.ondatachannel = ev => console.log(ev.type); +peerConnection.ondatachannel = ev => console.log(ev.channel); peerConnection.oniceconnectionstatechange = ev => console.log(ev.type); peerConnection.onnegotiationneeded = ev => console.log(ev.type); peerConnection.onopen = ev => console.log(ev.type); diff --git a/webrtc/RTCPeerConnection.d.ts b/webrtc/RTCPeerConnection.d.ts index 66b92c2416..c985cf2855 100644 --- a/webrtc/RTCPeerConnection.d.ts +++ b/webrtc/RTCPeerConnection.d.ts @@ -191,6 +191,7 @@ declare var RTCDataChannel: { new (): RTCDataChannel; }; +// https://www.w3.org/TR/webrtc/#rtcdatachannelevent interface RTCDataChannelEvent extends Event { channel: RTCDataChannel; } @@ -309,7 +310,7 @@ interface RTCPeerConnection { getRemoteStreams(): MediaStream[]; createDataChannel(label?: string, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; - ondatachannel: (event: Event) => void; + ondatachannel: (event: RTCDataChannelEvent) => void; addStream(stream: MediaStream, constraints?: RTCMediaConstraints): void; removeStream(stream: MediaStream): void; close(): void; From d726a1348e98d76558b1101801075f1a670bcbfd Mon Sep 17 00:00:00 2001 From: osechet Date: Wed, 20 Jul 2016 02:03:27 +0200 Subject: [PATCH 0097/1255] Add the options argument to openlayers custom control (#10099) * Add arguments to ol.control.Control's constructor * Define the olx.control.ControlOptions interface --- openlayers/openlayers.d.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 270876f440..243087c7b4 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -1079,6 +1079,25 @@ declare namespace olx { rightHanded?: boolean; } } + + namespace control { + interface ControlOptions { + /** + * The element is the control's container element. This only needs to be specified if you're developing a custom control. + */ + element?: Element; + + /** + * Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback. + */ + render?: any; + + /** + * Specify a target if you want the control to be rendered outside of the map's viewport. + */ + target?: Element | string; + } + } } /** @@ -2395,6 +2414,7 @@ declare namespace ol { } class Control { + constructor(options: olx.control.ControlOptions); } class FullScreen { From b54fdb65953a0f7c7847da4470513be9a3f3063f Mon Sep 17 00:00:00 2001 From: Vincent Rouille Date: Wed, 20 Jul 2016 02:05:08 +0200 Subject: [PATCH 0098/1255] Fix nodejs StringDecoder definition (#10100) --- node/node-0.10.d.ts | 4 ++-- node/node-0.11-tests.ts | 13 +++++++++++++ node/node-0.11.d.ts | 4 ++-- node/node-0.12-tests.ts | 13 +++++++++++++ node/node-0.12.d.ts | 4 ++-- node/node-4-tests.ts | 14 ++++++++++++++ node/node-4.d.ts | 4 ++-- node/node-tests.ts | 17 +++++++++++++++++ node/node.d.ts | 8 ++++---- 9 files changed, 69 insertions(+), 12 deletions(-) diff --git a/node/node-0.10.d.ts b/node/node-0.10.d.ts index ddfb58eca1..80b46a475c 100644 --- a/node/node-0.10.d.ts +++ b/node/node-0.10.d.ts @@ -1032,10 +1032,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } diff --git a/node/node-0.11-tests.ts b/node/node-0.11-tests.ts index 66c0c9ec7c..761a023668 100644 --- a/node/node-0.11-tests.ts +++ b/node/node-0.11-tests.ts @@ -12,6 +12,7 @@ import net = require("net"); import dgram = require("dgram"); import querystring = require('querystring'); import readline = require('readline'); +import string_decoder = require('string_decoder'); assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -122,6 +123,18 @@ namespace http_tests { var codeMessage = http.STATUS_CODES[400]; } +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +namespace string_decoder_tests { + var StringDecoder = string_decoder.StringDecoder; + var buffer = new Buffer('test'); + var decoder = new StringDecoder('utf8'); + var part: string = decoder.write(new Buffer('test')); + var end: string = decoder.end(); +} + //////////////////////////////////////////////////// /// Dgram tests : http://nodejs.org/api/dgram.html //////////////////////////////////////////////////// diff --git a/node/node-0.11.d.ts b/node/node-0.11.d.ts index 21f8bdca4e..212768c21a 100644 --- a/node/node-0.11.d.ts +++ b/node/node-0.11.d.ts @@ -943,10 +943,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } diff --git a/node/node-0.12-tests.ts b/node/node-0.12-tests.ts index 989b69dab0..cee6c8dc2d 100644 --- a/node/node-0.12-tests.ts +++ b/node/node-0.12-tests.ts @@ -14,6 +14,7 @@ import * as querystring from "querystring"; import * as path from "path"; import * as readline from "readline"; import * as childProcess from "child_process"; +import * as string_decoder from "string_decoder"; assert(1 + 1 - 2 === 0, "The universe isn't how it should."); @@ -404,6 +405,18 @@ rl.question("do you like typescript?", function(answer: string) { rl.close(); }); +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +namespace string_decoder_tests { + var StringDecoder = string_decoder.StringDecoder; + var buffer = new Buffer('test'); + var decoder = new StringDecoder('utf8'); + var part: string = decoder.write(new Buffer('test')); + var end: string = decoder.end(); +} + ////////////////////////////////////////////////////////////////////// /// Child Process tests: https://nodejs.org/api/child_process.html /// ////////////////////////////////////////////////////////////////////// diff --git a/node/node-0.12.d.ts b/node/node-0.12.d.ts index 3818b364d7..49091419a8 100644 --- a/node/node-0.12.d.ts +++ b/node/node-0.12.d.ts @@ -1480,10 +1480,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 8ead0224a2..8cddf66987 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -19,6 +19,8 @@ import * as childProcess from "child_process"; import * as cluster from "cluster"; import * as os from "os"; import * as vm from "vm"; +import * as string_decoder from "string_decoder"; + // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -699,6 +701,18 @@ namespace readline_tests { } } +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +namespace string_decoder_tests { + const StringDecoder = string_decoder.StringDecoder; + const buffer = new Buffer('test'); + const decoder = new StringDecoder('utf8'); + const part: string = decoder.write(new Buffer('test')); + const end: string = decoder.end(); +} + ////////////////////////////////////////////////////////////////////// /// Child Process tests: https://nodejs.org/api/child_process.html /// ////////////////////////////////////////////////////////////////////// diff --git a/node/node-4.d.ts b/node/node-4.d.ts index b70bb4d1c9..e0847bb5bc 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -1779,10 +1779,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } diff --git a/node/node-tests.ts b/node/node-tests.ts index 10a51dc01e..3967c09c6a 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -19,6 +19,8 @@ import * as childProcess from "child_process"; import * as cluster from "cluster"; import * as os from "os"; import * as vm from "vm"; +import * as string_decoder from "string_decoder"; + // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -723,6 +725,21 @@ namespace readline_tests { } } +//////////////////////////////////////////////////// +/// string_decoder tests : https://nodejs.org/api/string_decoder.html +//////////////////////////////////////////////////// + +namespace string_decoder_tests { + const StringDecoder = string_decoder.StringDecoder; + const buffer = new Buffer('test'); + const decoder1 = new StringDecoder(); + const decoder2 = new StringDecoder('utf8'); + const part1: string = decoder1.write(new Buffer('test')); + const end1: string = decoder1.end(); + const part2: string = decoder2.write(new Buffer('test')); + const end2: string = decoder1.end(new Buffer('test')); +} + ////////////////////////////////////////////////////////////////////// /// Child Process tests: https://nodejs.org/api/child_process.html /// ////////////////////////////////////////////////////////////////////// diff --git a/node/node.d.ts b/node/node.d.ts index 0a85883357..0934d1ebfb 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1812,10 +1812,10 @@ declare module "path" { declare module "string_decoder" { export interface NodeStringDecoder { write(buffer: Buffer): string; - detectIncompleteChar(buffer: Buffer): number; + end(buffer?: Buffer): string; } export var StringDecoder: { - new (encoding: string): NodeStringDecoder; + new (encoding?: string): NodeStringDecoder; }; } @@ -1868,7 +1868,7 @@ declare module "tls" { export class TLSSocket extends stream.Duplex { /** * Returns the bound address, the address family name and port of the underlying socket as reported by - * the operating system. + * the operating system. * @returns {any} - An object with three properties, e.g. { port: 12346, family: 'IPv4', address: '127.0.0.1' }. */ address(): { port: number; family: string; address: string }; @@ -1945,7 +1945,7 @@ declare module "tls" { remotePort: number; /** * Initiate TLS renegotiation process. - * + * * NOTE: Can be used to request peer's certificate after the secure connection has been established. * ANOTHER NOTE: When running as the server, socket will be destroyed with an error after handshakeTimeout timeout. * @param {TlsOptions} options - The options may contain the following fields: rejectUnauthorized, From b1426f561dde78d0e40f191be672546fca61d57a Mon Sep 17 00:00:00 2001 From: Carson Full Date: Tue, 19 Jul 2016 19:09:41 -0500 Subject: [PATCH 0099/1255] [Material UI] Changed button labels from strings to ReactNodes. (#10102) --- material-ui/material-ui-tests.tsx | 4 ++-- material-ui/material-ui.d.ts | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/material-ui/material-ui-tests.tsx b/material-ui/material-ui-tests.tsx index d1188ac3fb..c47f82858b 100644 --- a/material-ui/material-ui-tests.tsx +++ b/material-ui/material-ui-tests.tsx @@ -680,7 +680,7 @@ const FlatButtonExampleComplex = () => ( Label before} labelPosition="before" primary={true} style={styles.button} @@ -741,7 +741,7 @@ const RaisedButtonExampleComplex = () => ( Label before} labelPosition="before" primary={true} icon={} diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 984f57e987..58a36f9cf9 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -662,7 +662,7 @@ declare namespace __MaterialUI { hoverColor?: string; href?: string; icon?: React.ReactNode; - label?: string; + label?: React.ReactNode; labelPosition?: "before" | "after"; labelStyle?: React.CSSProperties; linkButton?: boolean; @@ -688,7 +688,7 @@ declare namespace __MaterialUI { fullWidth?: boolean; href?: string; icon?: React.ReactNode; - label?: string; + label?: React.ReactNode; labelColor?: string; labelPosition?: "before" | "after"; labelStyle?: React.CSSProperties; From 83f954972eea14a29161a0d9b9e602c4f8f824d1 Mon Sep 17 00:00:00 2001 From: Tim Perry Date: Wed, 20 Jul 2016 02:13:09 +0200 Subject: [PATCH 0100/1255] Fix signature for _.sum/sumBy when summing properties from object arrays in Lodash (#10101) * Fix lodash _.sumBy signature Main fix here is to ensure that summing plucked keys from objects is allowed. * Fix lodash 3.10 _.sumBy signature to allow summing plucked keys too --- lodash/lodash-3.10-tests.ts | 23 ++++++++++++-------- lodash/lodash-3.10.d.ts | 4 ++-- lodash/lodash-tests.ts | 42 +++++++++++++++---------------------- lodash/lodash.d.ts | 42 +++++++++++++++++++------------------ 4 files changed, 55 insertions(+), 56 deletions(-) diff --git a/lodash/lodash-3.10-tests.ts b/lodash/lodash-3.10-tests.ts index 0a2debfa00..2616822f6e 100644 --- a/lodash/lodash-3.10-tests.ts +++ b/lodash/lodash-3.10-tests.ts @@ -7700,8 +7700,13 @@ namespace TestRound { // _.sum namespace TestSum { let array: number[]; + let objectArray: { 'age': number }[]; + let list: _.List; + let objectList: _.List<{ 'age': number }>; + let dictionary: _.Dictionary; + let objectDictionary: _.Dictionary<{ 'age': number }>; let listIterator: (value: number, index: number, collection: _.List) => number; let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => number; @@ -7713,36 +7718,36 @@ namespace TestSum { result = _.sum(array); result = _.sum(array, listIterator); result = _.sum(array, listIterator, any); - result = _.sum(array, ''); + result = _.sum(objectArray, 'age'); result = _.sum(list); result = _.sum(list); result = _.sum(list, listIterator); result = _.sum(list, listIterator, any); - result = _.sum(list, ''); + result = _.sum(objectList, 'age'); result = _.sum(dictionary); result = _.sum(dictionary); result = _.sum(dictionary, dictionaryIterator); result = _.sum(dictionary, dictionaryIterator, any); - result = _.sum(dictionary, ''); + result = _.sum(objectDictionary, 'age'); result = _(array).sum(); result = _(array).sum(listIterator); result = _(array).sum(listIterator, any); - result = _(array).sum(''); + result = _(objectArray).sum('age'); result = _(list).sum(); result = _(list).sum(listIterator); result = _(list).sum(listIterator, any); - result = _(list).sum(''); + result = _(objectList).sum('age'); result = _(dictionary).sum(); result = _(dictionary).sum(dictionaryIterator); result = _(dictionary).sum(dictionaryIterator, any); - result = _(dictionary).sum(''); + result = _(objectDictionary).sum('age'); } { @@ -7751,18 +7756,18 @@ namespace TestSum { result = _(array).chain().sum(); result = _(array).chain().sum(listIterator); result = _(array).chain().sum(listIterator, any); - result = _(array).chain().sum(''); + result = _(objectArray).chain().sum(''); result = _(list).chain().sum(); result = _(list).chain().sum(listIterator); result = _(list).chain().sum(listIterator, any); - result = _(list).chain().sum(''); + result = _(objectList).chain().sum('age'); result = _(dictionary).chain().sum(); result = _(dictionary).chain().sum(dictionaryIterator); result = _(dictionary).chain().sum(dictionaryIterator, any); - result = _(dictionary).chain().sum(''); + result = _(objectDictionary).chain().sum('age'); } } diff --git a/lodash/lodash-3.10.d.ts b/lodash/lodash-3.10.d.ts index 3948215468..eca84d937f 100644 --- a/lodash/lodash-3.10.d.ts +++ b/lodash/lodash-3.10.d.ts @@ -12065,8 +12065,8 @@ declare module _ { /** * @see _.sum */ - sum( - collection: List|Dictionary, + sum( + collection: List<{}>|Dictionary<{}>, iteratee: string ): number; diff --git a/lodash/lodash-tests.ts b/lodash/lodash-tests.ts index ec20e06b1f..8ec22e98de 100644 --- a/lodash/lodash-tests.ts +++ b/lodash/lodash-tests.ts @@ -7896,49 +7896,41 @@ namespace TestSum { // _.sumBy namespace TestSumBy { let array: number[]; + let objectArray: { 'age': number }[]; + let list: _.List; - let dictionary: _.Dictionary; + let objectList: _.List<{ 'age': number }>; let listIterator: (value: number, index: number, collection: _.List) => number; - let dictionaryIterator: (value: number, key: string, collection: _.Dictionary) => number; { let result: number; - result = _.sumBy(array); - result = _.sumBy(array, listIterator); - result = _.sumBy(array, ''); + result = _.sumBy(array); + result = _.sumBy(array, listIterator); + result = _.sumBy(objectArray, 'age'); + result = _.sumBy(objectArray, { 'age': 30 }); - - result = _.sumBy(list); - result = _.sumBy(list, listIterator); - result = _.sumBy(list, ''); - - result = _.sumBy(dictionary); - result = _.sumBy(dictionary, dictionaryIterator); - result = _.sumBy(dictionary, ''); + result = _.sumBy(list); + result = _.sumBy(list, listIterator); + result = _.sumBy(objectList, 'age'); + result = _.sumBy(objectList, { 'age': 30 }); result = _(array).sumBy(listIterator); - result = _(array).sumBy(''); + result = _(objectArray).sumBy('age'); - result = _(list).sumBy(listIterator); - result = _(list).sumBy(''); - - result = _(dictionary).sumBy(dictionaryIterator); - result = _(dictionary).sumBy(''); + result = _(list).sumBy(listIterator); + result = _(objectList).sumBy('age'); } { let result: _.LoDashExplicitWrapper; result = _(array).chain().sumBy(listIterator); - result = _(array).chain().sumBy(''); + result = _(objectArray).chain().sumBy('age'); - result = _(list).chain().sumBy(listIterator); - result = _(list).chain().sumBy(''); - - result = _(dictionary).chain().sumBy(dictionaryIterator); - result = _(dictionary).chain().sumBy(''); + result = _(list).chain().sumBy(listIterator); + result = _(objectList).chain().sumBy('age'); } } diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index 3396ea447a..35c6611596 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -13475,31 +13475,28 @@ declare module _ { iteratee: ListIterator ): number; - /** - * @see _.sumBy - **/ - sumBy( - collection: Dictionary, - iteratee: DictionaryIterator - ): number; - /** * @see _.sumBy */ - sumBy( - collection: List|Dictionary, + sumBy( + collection: List<{}>, iteratee: string ): number; /** * @see _.sumBy */ - sumBy(collection: List|Dictionary): number; + sumBy( + collection: List + ): number; /** * @see _.sumBy */ - sumBy(collection: List|Dictionary): number; + sumBy( + collection: List<{}>, + iteratee: Dictionary<{}> + ): number; } interface LoDashImplicitArrayWrapper { @@ -13518,15 +13515,15 @@ declare module _ { /** * @see _.sumBy */ - sumBy(): number; + sumBy(iteratee: Dictionary<{}>): number; } interface LoDashImplicitObjectWrapper { /** * @see _.sumBy - **/ - sumBy( - iteratee: ListIterator|DictionaryIterator + */ + sumBy( + iteratee: ListIterator<{}, number> ): number; /** @@ -13537,7 +13534,7 @@ declare module _ { /** * @see _.sumBy */ - sumBy(): number; + sumBy(iteratee: Dictionary<{}>): number; } interface LoDashExplicitArrayWrapper { @@ -13557,14 +13554,19 @@ declare module _ { * @see _.sumBy */ sumBy(): LoDashExplicitWrapper; + + /** + * @see _.sumBy + */ + sumBy(iteratee: Dictionary<{}>): LoDashExplicitWrapper; } interface LoDashExplicitObjectWrapper { /** * @see _.sumBy */ - sumBy( - iteratee: ListIterator|DictionaryIterator + sumBy( + iteratee: ListIterator<{}, number> ): LoDashExplicitWrapper; /** @@ -13575,7 +13577,7 @@ declare module _ { /** * @see _.sumBy */ - sumBy(): LoDashExplicitWrapper; + sumBy(iteratee: Dictionary<{}>): LoDashExplicitWrapper; } /********** From 3a5b669575196d6231c69d283c03dcfbe46eca94 Mon Sep 17 00:00:00 2001 From: benoit74 Date: Wed, 20 Jul 2016 02:14:25 +0200 Subject: [PATCH 0101/1255] MailParser: Added missing "stream" attribute on Attachment (#10089) --- mailparser/mailparser-tests.ts | 4 ++-- mailparser/mailparser.d.ts | 3 +++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/mailparser/mailparser-tests.ts b/mailparser/mailparser-tests.ts index b7df9adb44..d52c011fe1 100644 --- a/mailparser/mailparser-tests.ts +++ b/mailparser/mailparser-tests.ts @@ -3,7 +3,7 @@ import mailparser_mod = require("mailparser"); import MailParser = mailparser_mod.MailParser; import ParsedMail = mailparser_mod.ParsedMail; - +import Attachment = mailparser_mod.Attachment; var mailparser = new MailParser(); @@ -61,7 +61,7 @@ var mp = new MailParser({ streamAttachments: true }) -mp.on("attachment", function(attachment, mail){ +mp.on("attachment", function(attachment : Attachment, mail : ParsedMail){ var output = fs.createWriteStream(attachment.generatedFileName); attachment.stream.pipe(output); }); diff --git a/mailparser/mailparser.d.ts b/mailparser/mailparser.d.ts index 94e99308d9..bc50dcc509 100644 --- a/mailparser/mailparser.d.ts +++ b/mailparser/mailparser.d.ts @@ -8,6 +8,8 @@ declare module 'mailparser' { + import StreamModule = require("stream"); + import Stream = StreamModule.Stream; import WritableStream = NodeJS.WritableStream; import EventEmitter = NodeJS.EventEmitter; @@ -36,6 +38,7 @@ declare module 'mailparser' { generatedFileName: string; // e.g. 'image.png' checksum: string; // the md5 hash of the file, e.g. 'e4cef4c6e26037bcf8166905207ea09b' content: Buffer; // possibly a SlowBuffer + stream: Stream; // a stream to read the attachment if streamAttachments is set to true } // emitted with the 'end' event From 2f16c8ae7e781c890fa7f52206babda099a581c3 Mon Sep 17 00:00:00 2001 From: velveret Date: Tue, 19 Jul 2016 17:16:17 -0700 Subject: [PATCH 0102/1255] Fix react-select definition for filterOptions (#10109) --- react-select/react-select-tests.tsx | 27 +++++++++++++++++++++++++++ react-select/react-select.d.ts | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/react-select/react-select-tests.tsx b/react-select/react-select-tests.tsx index acd84badba..880aacae42 100644 --- a/react-select/react-select-tests.tsx +++ b/react-select/react-select-tests.tsx @@ -1,7 +1,9 @@ +/// /// /// /// +import * as _ from "lodash"; import * as React from "react"; import * as ReactDOM from "react-dom"; @@ -61,6 +63,30 @@ const CustomValue = React.createClass({ } }); +const filterOptions = (options: Array