From 08f9659a3b4a2d2cad90cc50639279ec1372fcb5 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 15 Aug 2016 17:45:45 +0200 Subject: [PATCH 001/212] clean: remove glMatrix definition (it is only used internally) and add space after every colon --- gl-matrix/gl-matrix-typed-tests.ts | 3 +- gl-matrix/gl-matrix-typed.d.ts | 296 ++++++++++++++--------------- 2 files changed, 144 insertions(+), 155 deletions(-) diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts index 7364ec0a83..361690b5e7 100644 --- a/gl-matrix/gl-matrix-typed-tests.ts +++ b/gl-matrix/gl-matrix-typed-tests.ts @@ -1,8 +1,7 @@ /// // common -import {vec2, mat2, mat3, mat4, vec3, vec4, glMatrix, mat2d, quat} from "./gl-matrix-typed"; -var result: number = glMatrix.toRadian(180); +import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix-typed"; var outVal: number; var outBool: boolean; diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts index e172074fec..1309e994c8 100644 --- a/gl-matrix/gl-matrix-typed.d.ts +++ b/gl-matrix/gl-matrix-typed.d.ts @@ -3,16 +3,6 @@ // Definitions by: Mattijs Kneppers , based on definitions by Tat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Common -export class glMatrix { - /** - * Convert Degree To Radian - * - * @param a Angle in Degrees - */ - public static toRadian(a: number): number; -} - // vec2 export class vec2 extends Float32Array { private typeVec2:number; @@ -137,7 +127,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to ceil * @returns {vec2} out */ - public static ceil(out:vec2, a:vec2):vec2; + public static ceil(out: vec2, a: vec2): vec2; /** * Math.floor the components of a vec2 @@ -146,7 +136,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to floor * @returns {vec2} out */ - public static floor (out:vec2, a:vec2):vec2; + public static floor (out: vec2, a: vec2): vec2; /** * Returns the minimum of two vec2's @@ -175,7 +165,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to round * @returns {vec2} out */ - public static round(out:vec2, a:vec2):vec2; + public static round(out: vec2, a: vec2): vec2; /** @@ -427,7 +417,7 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a:vec2, b:vec2): boolean; + public static exactEquals (a: vec2, b: vec2): boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -436,7 +426,7 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a:vec2, b:vec2) : boolean; + public static equals (a: vec2, b: vec2) : boolean; } // vec3 @@ -565,7 +555,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to ceil * @returns {vec3} out */ - public static ceil (out:vec3, a:vec3) : vec3; + public static ceil (out: vec3, a: vec3) : vec3; /** * Math.floor the components of a vec3 @@ -574,7 +564,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to floor * @returns {vec3} out */ - public static floor (out:vec3, a:vec3) :vec3; + public static floor (out: vec3, a: vec3) : vec3; /** * Returns the minimum of two vec3's @@ -603,7 +593,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to round * @returns {vec3} out */ - public static round (out:vec3, a:vec3) : vec3 + public static round (out: vec3, a: vec3) : vec3 /** * Scales a vec3 by a scalar number @@ -762,7 +752,7 @@ export class vec3 extends Float32Array { * @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; + public static hermite (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; /** * Performs a bezier interpolation with two control points @@ -775,7 +765,7 @@ export class vec3 extends Float32Array { * @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; + public static bezier (out: vec3, a: vec3, b: vec3, c: vec3, d: vec3, t:number) : vec3; /** * Generates a random unit vector @@ -908,7 +898,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:vec3, b:vec3): 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 +907,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:vec3, b:vec3) : boolean + public static equals (a: vec3, b: vec3) : boolean } // vec4 @@ -1048,7 +1038,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to ceil * @returns {vec4} out */ - public static ceil (out:vec4, a:vec4) : vec4; + public static ceil (out: vec4, a: vec4) : vec4; /** * Math.floor the components of a vec4 @@ -1057,7 +1047,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to floor * @returns {vec4} out */ - public static floor (out:vec4, a:vec4) : vec4; + public static floor (out: vec4, a: vec4) : vec4; /** * Returns the minimum of two vec4's @@ -1086,7 +1076,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to round * @returns {vec4} out */ - public static round (out:vec4, a:vec4): vec4; + public static round (out: vec4, a: vec4): vec4; /** * Scales a vec4 by a scalar number @@ -1306,7 +1296,7 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a:vec4, b:vec4) : boolean; + public static exactEquals (a: vec4, b: vec4) : boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -1315,7 +1305,7 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a:vec4, b:vec4) : boolean; + public static equals (a: vec4, b: vec4) : boolean; } // mat2 @@ -1327,7 +1317,7 @@ export class mat2 extends Float32Array { * * @returns a new 2x2 matrix */ - public static create():mat2; + public static create(): mat2; /** * Creates a new mat2 initialized with values from an existing matrix @@ -1335,7 +1325,7 @@ export class mat2 extends Float32Array { * @param a matrix to clone * @returns a new 2x2 matrix */ - public static clone(a:mat2):mat2; + public static clone(a: mat2): mat2; /** * Copy the values from one mat2 to another @@ -1344,7 +1334,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static copy(out:mat2, a:mat2):mat2; + public static copy(out: mat2, a: mat2): mat2; /** * Set a mat2 to the identity matrix @@ -1352,7 +1342,7 @@ export class mat2 extends Float32Array { * @param out the receiving matrix * @returns out */ - public static identity(out:mat2):mat2; + public static identity(out: mat2): mat2; /** * Create a new mat2 with the given values @@ -1363,7 +1353,7 @@ export class mat2 extends Float32Array { * @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; + public static fromValues(m00:number, m01:number, m10:number, m11:number): mat2; /** * Set the components of a mat2 to the given values @@ -1375,7 +1365,7 @@ export class mat2 extends Float32Array { * @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; + public static set(out: mat2, m00:number, m01:number, m10:number, m11:number): mat2; /** * Transpose the values of a mat2 @@ -1384,7 +1374,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static transpose(out:mat2, a:mat2):mat2; + public static transpose(out: mat2, a: mat2): mat2; /** * Inverts a mat2 @@ -1393,7 +1383,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static invert(out:mat2, a:mat2):mat2; + public static invert(out: mat2, a: mat2): mat2; /** * Calculates the adjugate of a mat2 @@ -1402,7 +1392,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns out */ - public static adjoint(out:mat2, a:mat2):mat2; + public static adjoint(out: mat2, a: mat2): mat2; /** * Calculates the determinant of a mat2 @@ -1410,7 +1400,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a:mat2):number; + public static determinant(a: mat2):number; /** * Multiplies two mat2's @@ -1420,7 +1410,7 @@ export class mat2 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out:mat2, a:mat2, b:mat2):mat2; + public static multiply(out: mat2, a: mat2, b: mat2): mat2; /** * Multiplies two mat2's @@ -1430,7 +1420,7 @@ export class mat2 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out:mat2, a:mat2, b:mat2):mat2; + public static mul(out: mat2, a: mat2, b: mat2): mat2; /** * Rotates a mat2 by the given angle @@ -1440,7 +1430,7 @@ export class mat2 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out:mat2, a:mat2, rad:number):mat2; + public static rotate(out: mat2, a: mat2, rad:number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1450,7 +1440,7 @@ export class mat2 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out:mat2, a:mat2, v:vec2):mat2; + public static scale(out: mat2, a: mat2, v: vec2): mat2; /** * Creates a matrix from a given angle @@ -1463,7 +1453,7 @@ export class mat2 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2} out */ - public static fromRotation(out:mat2, rad:number):mat2; + public static fromRotation(out: mat2, rad:number): mat2; /** * Creates a matrix from a vector scaling @@ -1476,7 +1466,7 @@ export class mat2 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2} out */ - public static fromScaling(out:mat2, v:vec2):mat2; + public static fromScaling(out: mat2, v: vec2): mat2; /** * Returns a string representation of a mat2 @@ -1484,7 +1474,7 @@ export class mat2 extends Float32Array { * @param a matrix to represent as a string * @returns string representation of the matrix */ - public static str(a:mat2):string; + public static str(a: mat2):string; /** * Returns Frobenius norm of a mat2 @@ -1492,7 +1482,7 @@ export class mat2 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a:mat2):number; + public static frob(a: mat2):number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1501,7 +1491,7 @@ export class mat2 extends Float32Array { * @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; + public static LDU(L: mat2, D: mat2, U: mat2, a: mat2): mat2; /** * Adds two mat2's @@ -1511,7 +1501,7 @@ export class mat2 extends Float32Array { * @param {mat2} b the second operand * @returns {mat2} out */ - public static add(out:mat2, a:mat2, b:mat2):mat2; + public static add(out: mat2, a: mat2, b: mat2): mat2; /** * Subtracts matrix b from matrix a @@ -1521,7 +1511,7 @@ export class mat2 extends Float32Array { * @param {mat2} b the second operand * @returns {mat2} out */ - public static subtract (out:mat2, a:mat2, b:mat2):mat2; + public static subtract (out: mat2, a: mat2, b: mat2): mat2; /** * Subtracts matrix b from matrix a @@ -1531,7 +1521,7 @@ export class mat2 extends Float32Array { * @param {mat2} b the second operand * @returns {mat2} out */ - public static sub (out:mat2, a:mat2, b:mat2):mat2; + 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 ===) @@ -1540,7 +1530,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a:mat2, b:mat2):boolean; + public static exactEquals (a: mat2, b: mat2):boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -1549,7 +1539,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals (a:mat2, b:mat2) :boolean; + public static equals (a: mat2, b: mat2) :boolean; /** * Multiply each element of the matrix by a scalar. @@ -1559,7 +1549,7 @@ export class mat2 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat2} out */ - public static multiplyScalar (out:mat2, a:mat2, b:number) :mat2 + 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. @@ -1570,7 +1560,7 @@ export class mat2 extends Float32Array { * @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 + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale:number): mat2 @@ -1638,7 +1628,7 @@ export class mat2d extends Float32Array { * @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 + public static set (out: mat2d, a:number, b:number, c:number, d:number, tx:number, ty:number) : mat2d /** * Inverts a mat2d @@ -1718,7 +1708,7 @@ export class mat2d extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2d} out */ - public static fromRotation (out:mat2d, rad:number): mat2d; + public static fromRotation (out: mat2d, rad:number): mat2d; /** * Creates a matrix from a vector scaling @@ -1731,7 +1721,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2d} out */ - public static fromScaling (out:mat2d, v:vec2):mat2d; + public static fromScaling (out: mat2d, v: vec2): mat2d; /** * Creates a matrix from a vector translation @@ -1744,7 +1734,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Translation vector * @returns {mat2d} out */ - public static fromTranslation (out:mat2d, v:vec2):mat2d + public static fromTranslation (out: mat2d, v: vec2): mat2d /** * Returns a string representation of a mat2d @@ -1841,7 +1831,7 @@ export class mat3 extends Float32Array { * * @returns a new 3x3 matrix */ - public static create():mat3; + public static create(): mat3; /** * Copies the upper-left 3x3 values into the given mat3. @@ -1850,7 +1840,7 @@ export class mat3 extends Float32Array { * @param {mat4} a the source 4x4 matrix * @returns {mat3} out */ - public static fromMat4(out:mat3, a:mat4):mat3 + public static fromMat4(out: mat3, a: mat4): mat3 /** * Creates a new mat3 initialized with values from an existing matrix @@ -1858,7 +1848,7 @@ export class mat3 extends Float32Array { * @param a matrix to clone * @returns a new 3x3 matrix */ - public static clone(a:mat3):mat3; + public static clone(a: mat3): mat3; /** * Copy the values from one mat3 to another @@ -1867,7 +1857,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static copy(out:mat3, a:mat3):mat3; + public static copy(out: mat3, a: mat3): mat3; /** * Create a new mat3 with the given values @@ -1883,7 +1873,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:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number):mat3; + public static fromValues(m00:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3; /** @@ -1901,7 +1891,7 @@ export class mat3 extends Float32Array { * @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 + 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 @@ -1909,7 +1899,7 @@ export class mat3 extends Float32Array { * @param out the receiving matrix * @returns out */ - public static identity(out:mat3):mat3; + public static identity(out: mat3): mat3; /** * Transpose the values of a mat3 @@ -1918,7 +1908,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static transpose(out:mat3, a:mat3):mat3; + public static transpose(out: mat3, a: mat3): mat3; /** * Inverts a mat3 @@ -1927,7 +1917,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static invert(out:mat3, a:mat3):mat3; + public static invert(out: mat3, a: mat3): mat3; /** * Calculates the adjugate of a mat3 @@ -1936,7 +1926,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns out */ - public static adjoint(out:mat3, a:mat3):mat3; + public static adjoint(out: mat3, a: mat3): mat3; /** * Calculates the determinant of a mat3 @@ -1944,7 +1934,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a:mat3):number; + public static determinant(a: mat3):number; /** * Multiplies two mat3's @@ -1954,7 +1944,7 @@ export class mat3 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out:mat3, a:mat3, b:mat3):mat3; + public static multiply(out: mat3, a: mat3, b: mat3): mat3; /** * Multiplies two mat3's @@ -1964,7 +1954,7 @@ export class mat3 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out:mat3, a:mat3, b:mat3):mat3; + public static mul(out: mat3, a: mat3, b: mat3): mat3; /** @@ -1975,7 +1965,7 @@ export class mat3 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out:mat3, a:mat3, v:vec3):mat3; + public static translate(out: mat3, a: mat3, v: vec3): mat3; /** * Rotates a mat3 by the given angle @@ -1985,7 +1975,7 @@ export class mat3 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out:mat3, a:mat3, rad:number):mat3; + public static rotate(out: mat3, a: mat3, rad:number): mat3; /** * Scales the mat3 by the dimensions in the given vec2 @@ -1995,7 +1985,7 @@ export class mat3 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out:mat3, a:mat3, v:vec2):mat3; + public static scale(out: mat3, a: mat3, v: vec2): mat3; /** * Creates a matrix from a vector translation @@ -2008,7 +1998,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Translation vector * @returns {mat3} out */ - public static fromTranslation(out:mat3, v:vec2):mat3 + public static fromTranslation(out: mat3, v: vec2): mat3 /** * Creates a matrix from a given angle @@ -2021,7 +2011,7 @@ export class mat3 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat3} out */ - public static fromRotation(out:mat3, rad:number):mat3 + public static fromRotation(out: mat3, rad:number): mat3 /** * Creates a matrix from a vector scaling @@ -2034,7 +2024,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat3} out */ - public static fromScaling(out:mat3, v:vec2):mat3 + public static fromScaling(out: mat3, v: vec2): mat3 /** * Copies the values from a mat2d into a mat3 @@ -2043,7 +2033,7 @@ export class mat3 extends Float32Array { * @param {mat2d} a the matrix to copy * @returns out **/ - public static fromMat2d(out:mat3, a:mat2d):mat3; + public static fromMat2d(out: mat3, a: mat2d): mat3; /** * Calculates a 3x3 matrix from the given quaternion @@ -2053,7 +2043,7 @@ export class mat3 extends Float32Array { * * @returns out */ - public static fromQuat(out:mat3, q:quat):mat3; + public static fromQuat(out: mat3, q: quat): mat3; /** * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix @@ -2063,7 +2053,7 @@ export class mat3 extends Float32Array { * * @returns out */ - public static normalFromMat4(out:mat3, a:mat4):mat3; + public static normalFromMat4(out: mat3, a: mat4): mat3; /** * Returns a string representation of a mat3 @@ -2071,7 +2061,7 @@ export class mat3 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat:mat3):string; + public static str(mat: mat3):string; /** * Returns Frobenius norm of a mat3 @@ -2079,7 +2069,7 @@ export class mat3 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a:mat3):number; + public static frob(a: mat3):number; /** * Adds two mat3's @@ -2089,7 +2079,7 @@ export class mat3 extends Float32Array { * @param {mat3} b the second operand * @returns {mat3} out */ - public static add(out:mat3, a:mat3, b:mat3):mat3 + public static add(out: mat3, a: mat3, b: mat3): mat3 /** * Subtracts matrix b from matrix a @@ -2099,7 +2089,7 @@ export class mat3 extends Float32Array { * @param {mat3} b the second operand * @returns {mat3} out */ - public static subtract(out:mat3, a:mat3, b:mat3):mat3 + public static subtract(out: mat3, a: mat3, b: mat3): mat3 /** * Subtracts matrix b from matrix a @@ -2109,7 +2099,7 @@ export class mat3 extends Float32Array { * @param {mat3} b the second operand * @returns {mat3} out */ - public static sub(out:mat3, a:mat3, b:mat3):mat3 + public static sub(out: mat3, a: mat3, b: mat3): mat3 /** * Multiply each element of the matrix by a scalar. @@ -2119,7 +2109,7 @@ export class mat3 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat3} out */ - public static multiplyScalar(out:mat3, a:mat3, b:number):mat3 + 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. @@ -2130,7 +2120,7 @@ export class mat3 extends Float32Array { * @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 + 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 ===) @@ -2139,7 +2129,7 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals(a:mat3, b:mat3):boolean; + public static exactEquals(a: mat3, b: mat3):boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2148,7 +2138,7 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals(a:mat3, b:mat3):boolean + public static equals(a: mat3, b: mat3):boolean } // mat4 @@ -2160,7 +2150,7 @@ export class mat4 extends Float32Array { * * @returns a new 4x4 matrix */ - public static create():mat4; + public static create(): mat4; /** * Creates a new mat4 initialized with values from an existing matrix @@ -2168,7 +2158,7 @@ export class mat4 extends Float32Array { * @param a matrix to clone * @returns a new 4x4 matrix */ - public static clone(a:mat4):mat4; + public static clone(a: mat4): mat4; /** * Copy the values from one mat4 to another @@ -2177,7 +2167,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static copy(out:mat4, a:mat4):mat4; + public static copy(out: mat4, a: mat4): mat4; /** @@ -2201,7 +2191,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: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; + 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 @@ -2225,7 +2215,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: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; + 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 @@ -2233,7 +2223,7 @@ export class mat4 extends Float32Array { * @param out the receiving matrix * @returns out */ - public static identity(out:mat4):mat4; + public static identity(out: mat4): mat4; /** * Transpose the values of a mat4 @@ -2242,7 +2232,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static transpose(out:mat4, a:mat4):mat4; + public static transpose(out: mat4, a: mat4): mat4; /** * Inverts a mat4 @@ -2251,7 +2241,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static invert(out:mat4, a:mat4):mat4; + public static invert(out: mat4, a: mat4): mat4; /** * Calculates the adjugate of a mat4 @@ -2260,7 +2250,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns out */ - public static adjoint(out:mat4, a:mat4):mat4; + public static adjoint(out: mat4, a: mat4): mat4; /** * Calculates the determinant of a mat4 @@ -2268,7 +2258,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a:mat4):number; + public static determinant(a: mat4):number; /** * Multiplies two mat4's @@ -2278,7 +2268,7 @@ export class mat4 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out:mat4, a:mat4, b:mat4):mat4; + public static multiply(out: mat4, a: mat4, b: mat4): mat4; /** * Multiplies two mat4's @@ -2288,7 +2278,7 @@ export class mat4 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out:mat4, a:mat4, b:mat4):mat4; + public static mul(out: mat4, a: mat4, b: mat4): mat4; /** * Translate a mat4 by the given vector @@ -2298,7 +2288,7 @@ export class mat4 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out:mat4, a:mat4, v:vec3):mat4; + public static translate(out: mat4, a: mat4, v: vec3): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -2308,7 +2298,7 @@ export class mat4 extends Float32Array { * @param v the vec3 to scale the matrix by * @returns out **/ - public static scale(out:mat4, a:mat4, v:vec3):mat4; + public static scale(out: mat4, a: mat4, v: vec3): mat4; /** * Rotates a mat4 by the given angle @@ -2319,7 +2309,7 @@ export class mat4 extends Float32Array { * @param axis the axis to rotate around * @returns out */ - public static rotate(out:mat4, a:mat4, rad:number, axis:vec3):mat4; + public static rotate(out: mat4, a: mat4, rad:number, axis: vec3): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -2329,7 +2319,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateX(out:mat4, a:mat4, rad:number):mat4; + public static rotateX(out: mat4, a: mat4, rad:number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -2339,7 +2329,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateY(out:mat4, a:mat4, rad:number):mat4; + public static rotateY(out: mat4, a: mat4, rad:number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -2349,7 +2339,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateZ(out:mat4, a:mat4, rad:number):mat4; + public static rotateZ(out: mat4, a: mat4, rad:number): mat4; /** * Creates a matrix from a vector translation @@ -2362,7 +2352,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Translation vector * @returns {mat4} out */ - public static fromTranslation(out:mat4, v:vec3):mat4 + public static fromTranslation(out: mat4, v: vec3): mat4 /** * Creates a matrix from a vector scaling @@ -2375,7 +2365,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Scaling vector * @returns {mat4} out */ - public static fromScaling(out:mat4, v:vec3):mat4 + public static fromScaling(out: mat4, v: vec3): mat4 /** * Creates a matrix from a given angle around a given axis @@ -2389,7 +2379,7 @@ export class mat4 extends Float32Array { * @param {vec3} axis the axis to rotate around * @returns {mat4} out */ - public static fromRotation(out:mat4, rad:number, axis:vec3):mat4 + public static fromRotation(out: mat4, rad:number, axis: vec3): mat4 /** * Creates a matrix from the given angle around the X axis @@ -2402,7 +2392,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromXRotation(out:mat4, rad:number):mat4 + public static fromXRotation(out: mat4, rad:number): mat4 /** * Creates a matrix from the given angle around the Y axis @@ -2415,7 +2405,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromYRotation(out:mat4, rad:number):mat4 + public static fromYRotation(out: mat4, rad:number): mat4 /** @@ -2429,7 +2419,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromZRotation(out:mat4, rad:number):mat4 + public static fromZRotation(out: mat4, rad:number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -2446,7 +2436,7 @@ export class mat4 extends Float32Array { * @param v Translation vector * @returns out */ - public static fromRotationTranslation(out:mat4, q:quat, v:vec3):mat4; + public static fromRotationTranslation(out: mat4, q: quat, v: vec3): mat4; /** * Returns the translation vector component of a transformation @@ -2457,7 +2447,7 @@ export class mat4 extends Float32Array { * @param {mat4} mat Matrix to be decomposed (input) * @return {vec3} out */ - public static getTranslation(out:vec3, mat:mat4):vec3; + public static getTranslation(out: vec3, mat: mat4): vec3; /** * Returns a quaternion representing the rotational component @@ -2468,7 +2458,7 @@ export class mat4 extends Float32Array { * @param {mat4} mat Matrix to be decomposed (input) * @return {quat} out */ - public static getRotation(out:quat, mat:mat4):quat; + public static getRotation(out: quat, mat: mat4): quat; /** * Creates a matrix from a quaternion rotation, vector translation and vector scale @@ -2487,7 +2477,7 @@ export class mat4 extends Float32Array { * @param s Scaling vector * @returns out */ - public static fromRotationTranslationScale(out:mat4, q:quat, v:vec3, s:vec3):mat4; + 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 @@ -2509,7 +2499,7 @@ export class mat4 extends Float32Array { * @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 + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3, s: vec3, o: vec3): mat4 /** * Calculates a 4x4 matrix from the given quaternion @@ -2519,7 +2509,7 @@ export class mat4 extends Float32Array { * * @returns {mat4} out */ - public static fromQuat(out:mat4, q:quat):mat4 + public static fromQuat(out: mat4, q: quat): mat4 /** * Generates a frustum matrix with the given bounds @@ -2533,8 +2523,8 @@ export class mat4 extends Float32Array { * @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; + 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 @@ -2546,8 +2536,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static perspective(out:mat4, fovy:number, aspect:number, - near:number, far:number):mat4; + 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. @@ -2560,9 +2550,9 @@ export class mat4 extends Float32Array { * @param {number} far Far bound of the frustum * @returns {mat4} out */ - public static perspectiveFromFieldOfView(out:mat4, + public static perspectiveFromFieldOfView(out: mat4, fov:{upDegrees:number, downDegrees:number, leftDegrees:number, rightDegrees:number}, - near:number, far:number):mat4 + near:number, far:number): mat4 /** * Generates a orthogonal projection matrix with the given bounds @@ -2576,8 +2566,8 @@ export class mat4 extends Float32Array { * @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; + 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 @@ -2588,7 +2578,7 @@ export class mat4 extends Float32Array { * @param up vec3 pointing up * @returns out */ - public static lookAt(out:mat4, eye:vec3, center:vec3, up:vec3):mat4; + public static lookAt(out: mat4, eye: vec3, center: vec3, up: vec3): mat4; /** * Returns a string representation of a mat4 @@ -2596,7 +2586,7 @@ export class mat4 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat:mat4):string; + public static str(mat: mat4):string; /** * Returns Frobenius norm of a mat4 @@ -2604,7 +2594,7 @@ export class mat4 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a:mat4):number; + public static frob(a: mat4):number; /** * Adds two mat4's @@ -2614,7 +2604,7 @@ export class mat4 extends Float32Array { * @param {mat4} b the second operand * @returns {mat4} out */ - public static add(out:mat4, a:mat4, b:mat4):mat4 + public static add(out: mat4, a: mat4, b: mat4): mat4 /** * Subtracts matrix b from matrix a @@ -2624,7 +2614,7 @@ export class mat4 extends Float32Array { * @param {mat4} b the second operand * @returns {mat4} out */ - public static subtract(out:mat4, a:mat4, b:mat4):mat4 + public static subtract(out: mat4, a: mat4, b: mat4): mat4 /** * Subtracts matrix b from matrix a @@ -2634,7 +2624,7 @@ export class mat4 extends Float32Array { * @param {mat4} b the second operand * @returns {mat4} out */ - public static sub(out:mat4, a:mat4, b:mat4):mat4 + public static sub(out: mat4, a: mat4, b: mat4): mat4 /** * Multiply each element of the matrix by a scalar. @@ -2644,7 +2634,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:number):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. @@ -2655,7 +2645,7 @@ export class mat4 extends Float32Array { * @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 + 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 ===) @@ -2664,7 +2654,7 @@ export class mat4 extends Float32Array { * @param {mat4} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a:mat4, b:mat4) :boolean + public static exactEquals (a: mat4, b: mat4) :boolean /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2673,7 +2663,7 @@ export class mat4 extends Float32Array { * @param {mat4} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals (a:mat4, b:mat4): boolean + public static equals (a: mat4, b: mat4): boolean } @@ -2740,6 +2730,18 @@ export class quat extends Float32Array { */ public static identity(out: quat): 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 quaternion to represent the shortest rotation from one * vector to another. @@ -2751,19 +2753,7 @@ export class quat extends Float32Array { * @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 + public static rotationTo (out: quat, a: vec3, b: vec3): quat; @@ -2791,7 +2781,7 @@ export class quat extends Float32Array { * @param {quat} q Quaternion to be decomposed * @return {number} Angle, in radians, of the rotation */ - public static getAxisAngle (out_axis:vec3, q:quat) :number + public static getAxisAngle (out_axis: vec3, q: quat) :number /** * Adds two quat's @@ -2912,7 +2902,7 @@ export class quat extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static slerp(out:quat, a:quat, b:quat, t:number): quat; + public static slerp(out: quat, a: quat, b: quat, t:number): quat; /** * Performs a spherical linear interpolation with two control points @@ -3041,7 +3031,7 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static exactEquals (a:quat, b:quat) : boolean; + public static exactEquals (a: quat, b: quat) : boolean; /** * Returns whether or not the quaternions have approximately the same elements in the same position. @@ -3050,5 +3040,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 568c64aa047cf20d2ff4a7e2128ccfa7bf326483 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 15 Aug 2016 17:47:26 +0200 Subject: [PATCH 002/212] feature: add option of number array input for all vector arguments --- gl-matrix/gl-matrix-typed-tests.ts | 4 +- gl-matrix/gl-matrix-typed.d.ts | 430 ++++++++++++++--------------- 2 files changed, 218 insertions(+), 216 deletions(-) diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts index 361690b5e7..64f6beb7a4 100644 --- a/gl-matrix/gl-matrix-typed-tests.ts +++ b/gl-matrix/gl-matrix-typed-tests.ts @@ -79,6 +79,7 @@ vecArray = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); outStr = vec2.str(vec2A); outBool = vec2.exactEquals(vec2A, vec2B); outBool = vec2.equals(vec2A, vec2B); +outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input // vec3 outVec3 = vec3.create(); @@ -129,6 +130,7 @@ outVal = vec3.angle(vec3A, vec3B); outStr = vec3.str(vec3A); outBool = vec3.exactEquals(vec3A, vec3B); outBool = vec3.equals(vec3A, vec3B); +outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input // vec4 outVec4 = vec4.create(); @@ -170,6 +172,7 @@ vecArray = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); outStr = vec4.str(vec4A); outBool = vec4.exactEquals(vec4A, vec4B); outBool = vec4.equals(vec4A, vec4B); +outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input // mat2 outMat2 = mat2.create(); @@ -229,7 +232,6 @@ 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); diff --git a/gl-matrix/gl-matrix-typed.d.ts b/gl-matrix/gl-matrix-typed.d.ts index 1309e994c8..2edbbd8bb5 100644 --- a/gl-matrix/gl-matrix-typed.d.ts +++ b/gl-matrix/gl-matrix-typed.d.ts @@ -5,7 +5,7 @@ // vec2 export class vec2 extends Float32Array { - private typeVec2:number; + private typeVec2: number; /** * Creates a new, empty vec2 @@ -20,7 +20,7 @@ export class vec2 extends Float32Array { * @param a a vector to clone * @returns a new 2D vector */ - public static clone(a: vec2): vec2; + public static clone(a: vec2 | number[]): vec2; /** * Creates a new vec2 initialized with the given values @@ -38,7 +38,7 @@ export class vec2 extends Float32Array { * @param a the source vector * @returns out */ - public static copy(out: vec2, a: vec2): vec2; + public static copy(out: vec2, a: vec2 | number[]): vec2; /** * Set the components of a vec2 to the given values @@ -58,7 +58,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static add(out: vec2, a: vec2, b: vec2): vec2; + public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -68,7 +68,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static subtract(out: vec2, a: vec2, b: vec2): vec2; + public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -78,7 +78,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static sub(out: vec2, a: vec2, b: vec2): vec2; + public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -88,7 +88,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out: vec2, a: vec2, b: vec2): vec2; + public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -98,7 +98,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out: vec2, a: vec2, b: vec2): vec2; + public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -108,7 +108,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static divide(out: vec2, a: vec2, b: vec2): vec2; + public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -118,7 +118,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static div(out: vec2, a: vec2, b: vec2): vec2; + public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Math.ceil the components of a vec2 @@ -127,7 +127,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to ceil * @returns {vec2} out */ - public static ceil(out: vec2, a: vec2): vec2; + public static ceil(out: vec2, a: vec2 | number[]): vec2; /** * Math.floor the components of a vec2 @@ -136,7 +136,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to floor * @returns {vec2} out */ - public static floor (out: vec2, a: vec2): vec2; + public static floor (out: vec2, a: vec2 | number[]): vec2; /** * Returns the minimum of two vec2's @@ -146,7 +146,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static min(out: vec2, a: vec2, b: vec2): vec2; + public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Returns the maximum of two vec2's @@ -156,7 +156,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static max(out: vec2, a: vec2, b: vec2): vec2; + public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Math.round the components of a vec2 @@ -165,7 +165,7 @@ export class vec2 extends Float32Array { * @param {vec2} a vector to round * @returns {vec2} out */ - public static round(out: vec2, a: vec2): vec2; + public static round(out: vec2, a: vec2 | number[]): vec2; /** @@ -176,7 +176,7 @@ export class vec2 extends Float32Array { * @param b amount to scale the vector by * @returns out */ - public static scale(out: vec2, a: vec2, b: number): vec2; + public static scale(out: vec2, a: vec2 | number[], b: number): vec2; /** * Adds two vec2's after scaling the second operand by a scalar value @@ -187,7 +187,7 @@ export class vec2 extends Float32Array { * @param scale the amount to scale b by before adding * @returns out */ - public static scaleAndAdd(out: vec2, a: vec2, b: vec2, scale: number): vec2; + public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; /** * Calculates the euclidian distance between two vec2's @@ -196,7 +196,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static distance(a: vec2, b: vec2): number; + public static distance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the euclidian distance between two vec2's @@ -205,7 +205,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static dist(a: vec2, b: vec2): number; + public static dist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -214,7 +214,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static squaredDistance(a: vec2, b: vec2): number; + public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -223,7 +223,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static sqrDist(a: vec2, b: vec2): number; + public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -231,7 +231,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static length(a: vec2): number; + public static length(a: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -239,7 +239,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static len(a: vec2): number; + public static len(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -247,7 +247,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static squaredLength(a: vec2): number; + public static squaredLength(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -255,7 +255,7 @@ export class vec2 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static sqrLen(a: vec2): number; + public static sqrLen(a: vec2 | number[]): number; /** * Negates the components of a vec2 @@ -264,7 +264,7 @@ export class vec2 extends Float32Array { * @param a vector to negate * @returns out */ - public static negate(out: vec2, a: vec2): vec2; + public static negate(out: vec2, a: vec2 | number[]): vec2; /** * Returns the inverse of the components of a vec2 @@ -273,7 +273,7 @@ export class vec2 extends Float32Array { * @param a vector to invert * @returns out */ - public static inverse(out: vec2, a: vec2): vec2; + public static inverse(out: vec2, a: vec2 | number[]): vec2; /** * Normalize a vec2 @@ -282,7 +282,7 @@ export class vec2 extends Float32Array { * @param a vector to normalize * @returns out */ - public static normalize(out: vec2, a: vec2): vec2; + public static normalize(out: vec2, a: vec2 | number[]): vec2; /** * Calculates the dot product of two vec2's @@ -291,7 +291,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns dot product of a and b */ - public static dot(a: vec2, b: vec2): number; + public static dot(a: vec2 | number[], b: vec2 | number[]): number; /** * Computes the cross product of two vec2's @@ -302,7 +302,7 @@ export class vec2 extends Float32Array { * @param b the second operand * @returns out */ - public static cross(out: vec2, a: vec2, b: vec2): vec2; + public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Performs a linear interpolation between two vec2's @@ -313,7 +313,7 @@ export class vec2 extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static lerp(out: vec2, a: vec2, b: vec2, t: number): vec2; + public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; /** * Generates a random unit vector @@ -340,7 +340,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat2(out: vec2, a: vec2, m: mat2): vec2; + public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; /** * Transforms the vec2 with a mat2d @@ -350,7 +350,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat2d(out: vec2, a: vec2, m: mat2d): vec2; + public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; /** * Transforms the vec2 with a mat3 @@ -361,7 +361,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat3(out: vec2, a: vec2, m: mat3): vec2; + public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; /** * Transforms the vec2 with a mat4 @@ -373,7 +373,7 @@ export class vec2 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat4(out: vec2, a: vec2, m: mat4): vec2; + public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; /** * Perform some operation over an array of vec2s. @@ -387,7 +387,7 @@ export class vec2 extends Float32Array { * @returns a */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2, b: vec2, arg: any) => void, arg: any): Float32Array; + fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec2s. @@ -400,7 +400,7 @@ export class vec2 extends Float32Array { * @returns a */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2, b: vec2) => void): Float32Array; + fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; /** * Returns a string representation of a vector @@ -408,7 +408,7 @@ export class vec2 extends Float32Array { * @param a vector to represent as a string * @returns string representation of the vector */ - public static str(a: vec2): string; + public static str(a: vec2 | number[]): string; /** * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) @@ -417,7 +417,7 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a: vec2, b: vec2): boolean; + public static exactEquals (a: vec2 | number[], b: vec2 | number[]): boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -426,12 +426,12 @@ export class vec2 extends Float32Array { * @param {vec2} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a: vec2, b: vec2) : boolean; + public static equals (a: vec2 | number[], b: vec2 | number[]): boolean; } // vec3 export class vec3 extends Float32Array { - private typeVec3:number; + private typeVec3: number; /** * Creates a new, empty vec3 @@ -446,7 +446,7 @@ export class vec3 extends Float32Array { * @param a vector to clone * @returns a new 3D vector */ - public static clone(a: vec3): vec3; + public static clone(a: vec3 | number[]): vec3; /** * Creates a new vec3 initialized with the given values @@ -465,7 +465,7 @@ export class vec3 extends Float32Array { * @param a the source vector * @returns out */ - public static copy(out: vec3, a: vec3): vec3; + public static copy(out: vec3, a: vec3 | number[]): vec3; /** * Set the components of a vec3 to the given values @@ -486,7 +486,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static add(out: vec3, a: vec3, b: vec3): vec3; + public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -496,7 +496,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static subtract(out: vec3, a: vec3, b: vec3): vec3; + public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -506,7 +506,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static sub(out: vec3, a: vec3, b: vec3): vec3 + public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 /** * Multiplies two vec3's @@ -516,7 +516,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out: vec3, a: vec3, b: vec3): vec3; + public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Multiplies two vec3's @@ -526,7 +526,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out: vec3, a: vec3, b: vec3): vec3; + public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -536,7 +536,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static divide(out: vec3, a: vec3, b: vec3): vec3; + public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -546,7 +546,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static div(out: vec3, a: vec3, b: vec3): vec3; + public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Math.ceil the components of a vec3 @@ -555,7 +555,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to ceil * @returns {vec3} out */ - public static ceil (out: vec3, a: vec3) : vec3; + public static ceil (out: vec3, a: vec3 | number[]): vec3; /** * Math.floor the components of a vec3 @@ -564,7 +564,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to floor * @returns {vec3} out */ - public static floor (out: vec3, a: vec3) : vec3; + public static floor (out: vec3, a: vec3 | number[]): vec3; /** * Returns the minimum of two vec3's @@ -574,7 +574,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static min(out: vec3, a: vec3, b: vec3): vec3; + public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Returns the maximum of two vec3's @@ -584,7 +584,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static max(out: vec3, a: vec3, b: vec3): vec3; + public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Math.round the components of a vec3 @@ -593,7 +593,7 @@ export class vec3 extends Float32Array { * @param {vec3} a vector to round * @returns {vec3} out */ - public static round (out: vec3, a: vec3) : vec3 + public static round (out: vec3, a: vec3 | number[]): vec3 /** * Scales a vec3 by a scalar number @@ -603,7 +603,7 @@ export class vec3 extends Float32Array { * @param b amount to scale the vector by * @returns out */ - public static scale(out: vec3, a: vec3, b: number): vec3; + public static scale(out: vec3, a: vec3 | number[], b: number): vec3; /** * Adds two vec3's after scaling the second operand by a scalar value @@ -614,7 +614,7 @@ export class vec3 extends Float32Array { * @param scale the amount to scale b by before adding * @returns out */ - public static scaleAndAdd(out: vec3, a: vec3, b: vec3, scale: number): vec3; + public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; /** * Calculates the euclidian distance between two vec3's @@ -623,7 +623,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static distance(a: vec3, b: vec3): number; + public static distance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the euclidian distance between two vec3's @@ -632,7 +632,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static dist(a: vec3, b: vec3): number; + public static dist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -641,7 +641,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static squaredDistance(a: vec3, b: vec3): number; + public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -650,7 +650,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static sqrDist(a: vec3, b: vec3): number; + public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -658,7 +658,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static length(a: vec3): number; + public static length(a: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -666,7 +666,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static len(a: vec3): number; + public static len(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -674,7 +674,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static squaredLength(a: vec3): number; + public static squaredLength(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -682,7 +682,7 @@ export class vec3 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static sqrLen(a: vec3): number; + public static sqrLen(a: vec3 | number[]): number; /** * Negates the components of a vec3 @@ -691,7 +691,7 @@ export class vec3 extends Float32Array { * @param a vector to negate * @returns out */ - public static negate(out: vec3, a: vec3): vec3; + public static negate(out: vec3, a: vec3 | number[]): vec3; /** * Returns the inverse of the components of a vec3 @@ -700,7 +700,7 @@ export class vec3 extends Float32Array { * @param a vector to invert * @returns out */ - public static inverse(out: vec3, a: vec3): vec3; + public static inverse(out: vec3, a: vec3 | number[]): vec3; /** * Normalize a vec3 @@ -709,7 +709,7 @@ export class vec3 extends Float32Array { * @param a vector to normalize * @returns out */ - public static normalize(out: vec3, a: vec3): vec3; + public static normalize(out: vec3, a: vec3 | number[]): vec3; /** * Calculates the dot product of two vec3's @@ -718,7 +718,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns dot product of a and b */ - public static dot(a: vec3, b: vec3): number; + public static dot(a: vec3 | number[], b: vec3 | number[]): number; /** * Computes the cross product of two vec3's @@ -728,7 +728,7 @@ export class vec3 extends Float32Array { * @param b the second operand * @returns out */ - public static cross(out: vec3, a: vec3, b: vec3): vec3; + public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Performs a linear interpolation between two vec3's @@ -739,7 +739,7 @@ export class vec3 extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static lerp(out: vec3, a: vec3, b: vec3, t: number): vec3; + public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], t: number): vec3; /** * Performs a hermite interpolation with two control points @@ -752,7 +752,7 @@ export class vec3 extends Float32Array { * @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; + public static hermite (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Performs a bezier interpolation with two control points @@ -765,7 +765,7 @@ export class vec3 extends Float32Array { * @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; + public static bezier (out: vec3, a: vec3 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Generates a random unit vector @@ -792,7 +792,7 @@ export class vec3 extends Float32Array { * @param m the 3x3 matrix to transform with * @returns out */ - public static transformMat3(out: vec3, a: vec3, m: mat3): vec3; + public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; /** * Transforms the vec3 with a mat4. @@ -803,7 +803,7 @@ export class vec3 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat4(out: vec3, a: vec3, m: mat4): vec3; + public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; /** * Transforms the vec3 with a quat @@ -813,7 +813,7 @@ export class vec3 extends Float32Array { * @param q quaternion to transform with * @returns out */ - public static transformQuat(out: vec3, a: vec3, q: quat): vec3; + public static transformQuat(out: vec3, a: vec3 | number[], q: quat): vec3; /** @@ -824,7 +824,7 @@ export class vec3 extends Float32Array { * @param c The angle of rotation * @returns out */ - public static rotateX(out: vec3, a: vec3, b: vec3, c: number): vec3; + public static rotateX(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; /** * Rotate a 3D vector around the y-axis @@ -834,7 +834,7 @@ export class vec3 extends Float32Array { * @param c The angle of rotation * @returns out */ - public static rotateY(out: vec3, a: vec3, b: vec3, c: number): vec3; + public static rotateY(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; /** * Rotate a 3D vector around the z-axis @@ -844,7 +844,7 @@ export class vec3 extends Float32Array { * @param c The angle of rotation * @returns out */ - public static rotateZ(out: vec3, a: vec3, b: vec3, c: number): vec3; + public static rotateZ(out: vec3, a: vec3 | number[], b: vec3 | number[], c: number): vec3; /** * Perform some operation over an array of vec3s. @@ -859,7 +859,7 @@ export class vec3 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3, b: vec3, arg: any) => void, arg: any): Float32Array; + fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec3s. @@ -873,7 +873,7 @@ export class vec3 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3, b: vec3) => void): Float32Array; + fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; /** * Get the angle between two 3D vectors @@ -881,7 +881,7 @@ export class vec3 extends Float32Array { * @param b The second operand * @returns The angle in radians */ - public static angle(a: vec3, b: vec3): number; + public static angle(a: vec3 | number[], b: vec3 | number[]): number; /** * Returns a string representation of a vector @@ -889,7 +889,7 @@ export class vec3 extends Float32Array { * @param a vector to represent as a string * @returns string representation of the vector */ - public static str(a: vec3): string; + public static str(a: vec3 | number[]): string; /** * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) @@ -898,7 +898,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: vec3, b: vec3): boolean + public static exactEquals (a: vec3 | number[], b: vec3 | number[]): boolean /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -907,12 +907,12 @@ 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: vec3, b: vec3) : boolean + public static equals (a: vec3 | number[], b: vec3 | number[]): boolean } // vec4 export class vec4 extends Float32Array { - private typeVec3:number; + private typeVec3: number; /** * Creates a new, empty vec4 @@ -927,7 +927,7 @@ export class vec4 extends Float32Array { * @param a vector to clone * @returns a new 4D vector */ - public static clone(a: vec4): vec4; + public static clone(a: vec4 | number[]): vec4; /** * Creates a new vec4 initialized with the given values @@ -947,7 +947,7 @@ export class vec4 extends Float32Array { * @param a the source vector * @returns out */ - public static copy(out: vec4, a: vec4): vec4; + public static copy(out: vec4, a: vec4 | number[]): vec4; /** * Set the components of a vec4 to the given values @@ -969,7 +969,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static add(out: vec4, a: vec4, b: vec4): vec4; + public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -979,7 +979,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static subtract(out: vec4, a: vec4, b: vec4): vec4; + public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -989,7 +989,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static sub(out: vec4, a: vec4, b: vec4): vec4; + public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -999,7 +999,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static multiply(out: vec4, a: vec4, b: vec4): vec4; + public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -1009,7 +1009,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static mul(out: vec4, a: vec4, b: vec4): vec4; + public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -1019,7 +1019,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static divide(out: vec4, a: vec4, b: vec4): vec4; + public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -1029,7 +1029,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static div(out: vec4, a: vec4, b: vec4): vec4; + public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Math.ceil the components of a vec4 @@ -1038,7 +1038,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to ceil * @returns {vec4} out */ - public static ceil (out: vec4, a: vec4) : vec4; + public static ceil (out: vec4, a: vec4 | number[]): vec4; /** * Math.floor the components of a vec4 @@ -1047,7 +1047,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to floor * @returns {vec4} out */ - public static floor (out: vec4, a: vec4) : vec4; + public static floor (out: vec4, a: vec4 | number[]): vec4; /** * Returns the minimum of two vec4's @@ -1057,7 +1057,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static min(out: vec4, a: vec4, b: vec4): vec4; + public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Returns the maximum of two vec4's @@ -1067,7 +1067,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns out */ - public static max(out: vec4, a: vec4, b: vec4): vec4; + public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Math.round the components of a vec4 @@ -1076,7 +1076,7 @@ export class vec4 extends Float32Array { * @param {vec4} a vector to round * @returns {vec4} out */ - public static round (out: vec4, a: vec4): vec4; + public static round (out: vec4, a: vec4 | number[]): vec4; /** * Scales a vec4 by a scalar number @@ -1086,7 +1086,7 @@ export class vec4 extends Float32Array { * @param b amount to scale the vector by * @returns out */ - public static scale(out: vec4, a: vec4, b: number): vec4; + public static scale(out: vec4, a: vec4 | number[], b: number): vec4; /** * Adds two vec4's after scaling the second operand by a scalar value @@ -1097,7 +1097,7 @@ export class vec4 extends Float32Array { * @param scale the amount to scale b by before adding * @returns out */ - public static scaleAndAdd(out: vec4, a: vec4, b: vec4, scale: number): vec4; + public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; /** * Calculates the euclidian distance between two vec4's @@ -1106,7 +1106,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static distance(a: vec4, b: vec4): number; + public static distance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the euclidian distance between two vec4's @@ -1115,7 +1115,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns distance between a and b */ - public static dist(a: vec4, b: vec4): number; + public static dist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1124,7 +1124,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static squaredDistance(a: vec4, b: vec4): number; + public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1133,7 +1133,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns squared distance between a and b */ - public static sqrDist(a: vec4, b: vec4): number; + public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1141,7 +1141,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static length(a: vec4): number; + public static length(a: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1149,7 +1149,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate length of * @returns length of a */ - public static len(a: vec4): number; + public static len(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1157,7 +1157,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static squaredLength(a: vec4): number; + public static squaredLength(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1165,7 +1165,7 @@ export class vec4 extends Float32Array { * @param a vector to calculate squared length of * @returns squared length of a */ - public static sqrLen(a: vec4): number; + public static sqrLen(a: vec4 | number[]): number; /** * Negates the components of a vec4 @@ -1174,7 +1174,7 @@ export class vec4 extends Float32Array { * @param a vector to negate * @returns out */ - public static negate(out: vec4, a: vec4): vec4; + public static negate(out: vec4, a: vec4 | number[]): vec4; /** * Returns the inverse of the components of a vec4 @@ -1183,7 +1183,7 @@ export class vec4 extends Float32Array { * @param a vector to invert * @returns out */ - public static inverse(out: vec4, a: vec4): vec4; + public static inverse(out: vec4, a: vec4 | number[]): vec4; /** * Normalize a vec4 @@ -1192,7 +1192,7 @@ export class vec4 extends Float32Array { * @param a vector to normalize * @returns out */ - public static normalize(out: vec4, a: vec4): vec4; + public static normalize(out: vec4, a: vec4 | number[]): vec4; /** * Calculates the dot product of two vec4's @@ -1201,7 +1201,7 @@ export class vec4 extends Float32Array { * @param b the second operand * @returns dot product of a and b */ - public static dot(a: vec4, b: vec4): number; + public static dot(a: vec4 | number[], b: vec4 | number[]): number; /** * Performs a linear interpolation between two vec4's @@ -1212,7 +1212,7 @@ export class vec4 extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static lerp(out: vec4, a: vec4, b: vec4, t: number): vec4; + public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; /** * Generates a random unit vector @@ -1239,7 +1239,7 @@ export class vec4 extends Float32Array { * @param m matrix to transform with * @returns out */ - public static transformMat4(out: vec4, a: vec4, m: mat4): vec4; + public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; /** * Transforms the vec4 with a quat @@ -1250,7 +1250,7 @@ export class vec4 extends Float32Array { * @returns out */ - public static transformQuat(out: vec4, a: vec4, q: quat): vec4; + public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; /** * Perform some operation over an array of vec4s. @@ -1265,7 +1265,7 @@ export class vec4 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4, b: vec4, arg: any) => void, arg: any): Float32Array; + fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec4s. @@ -1279,7 +1279,7 @@ export class vec4 extends Float32Array { * @function */ public static forEach(a: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4, b: vec4) => void): Float32Array; + fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; /** * Returns a string representation of a vector @@ -1287,7 +1287,7 @@ export class vec4 extends Float32Array { * @param a vector to represent as a string * @returns string representation of the vector */ - public static str(a: vec4): string; + public static str(a: vec4 | number[]): string; /** * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) @@ -1296,7 +1296,7 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static exactEquals (a: vec4, b: vec4) : boolean; + public static exactEquals (a: vec4 | number[], b: vec4 | number[]): boolean; /** * Returns whether or not the vectors have approximately the same elements in the same position. @@ -1305,12 +1305,12 @@ export class vec4 extends Float32Array { * @param {vec4} b The second vector. * @returns {boolean} True if the vectors are equal, false otherwise. */ - public static equals (a: vec4, b: vec4) : boolean; + public static equals (a: vec4 | number[], b: vec4 | number[]): boolean; } // mat2 export class mat2 extends Float32Array { - private typeMat2:number; + private typeMat2: number; /** * Creates a new identity mat2 @@ -1353,7 +1353,7 @@ export class mat2 extends Float32Array { * @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; + public static fromValues(m00: number, m01: number, m10: number, m11: number): mat2; /** * Set the components of a mat2 to the given values @@ -1365,7 +1365,7 @@ export class mat2 extends Float32Array { * @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; + public static set(out: mat2, m00: number, m01: number, m10: number, m11: number): mat2; /** * Transpose the values of a mat2 @@ -1400,7 +1400,7 @@ export class mat2 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a: mat2):number; + public static determinant(a: mat2): number; /** * Multiplies two mat2's @@ -1430,7 +1430,7 @@ export class mat2 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out: mat2, a: mat2, rad:number): mat2; + public static rotate(out: mat2, a: mat2, rad: number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1440,7 +1440,7 @@ export class mat2 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out: mat2, a: mat2, v: vec2): mat2; + public static scale(out: mat2, a: mat2, v: vec2 | number[]): mat2; /** * Creates a matrix from a given angle @@ -1453,7 +1453,7 @@ export class mat2 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2} out */ - public static fromRotation(out: mat2, rad:number): mat2; + public static fromRotation(out: mat2, rad: number): mat2; /** * Creates a matrix from a vector scaling @@ -1466,7 +1466,7 @@ export class mat2 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2} out */ - public static fromScaling(out: mat2, v: vec2): mat2; + public static fromScaling(out: mat2, v: vec2 | number[]): mat2; /** * Returns a string representation of a mat2 @@ -1474,7 +1474,7 @@ export class mat2 extends Float32Array { * @param a matrix to represent as a string * @returns string representation of the matrix */ - public static str(a: mat2):string; + public static str(a: mat2): string; /** * Returns Frobenius norm of a mat2 @@ -1482,7 +1482,7 @@ export class mat2 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a: mat2):number; + public static frob(a: mat2): number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1530,7 +1530,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a: mat2, b: mat2):boolean; + public static exactEquals (a: mat2, b: mat2): boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -1539,7 +1539,7 @@ export class mat2 extends Float32Array { * @param {mat2} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals (a: mat2, b: mat2) :boolean; + public static equals (a: mat2, b: mat2): boolean; /** * Multiply each element of the matrix by a scalar. @@ -1549,7 +1549,7 @@ export class mat2 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat2} out */ - public static multiplyScalar (out: mat2, a: mat2, b:number) : mat2 + 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. @@ -1560,7 +1560,7 @@ export class mat2 extends Float32Array { * @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 + public static multiplyScalarAndAdd (out: mat2, a: mat2, b: mat2, scale: number): mat2 @@ -1568,7 +1568,7 @@ export class mat2 extends Float32Array { // mat2d export class mat2d extends Float32Array { - private typeMat2d:number; + private typeMat2d: number; /** * Creates a new identity mat2d @@ -1613,7 +1613,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 /** @@ -1628,7 +1628,7 @@ export class mat2d extends Float32Array { * @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 + public static set (out: mat2d, a: number, b: number, c: number, d: number, tx: number, ty: number): mat2d /** * Inverts a mat2d @@ -1685,7 +1685,7 @@ export class mat2d extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out: mat2d, a: mat2d, v: vec2): mat2d; + public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Translates the mat2d by the dimensions in the given vec2 @@ -1695,7 +1695,7 @@ export class mat2d extends Float32Array { * @param v the vec2 to translate the matrix by * @returns out **/ - public static translate(out: mat2d, a: mat2d, v: vec2): mat2d; + public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Creates a matrix from a given angle @@ -1708,7 +1708,7 @@ export class mat2d extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat2d} out */ - public static fromRotation (out: mat2d, rad:number): mat2d; + public static fromRotation (out: mat2d, rad: number): mat2d; /** * Creates a matrix from a vector scaling @@ -1721,7 +1721,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat2d} out */ - public static fromScaling (out: mat2d, v: vec2): mat2d; + public static fromScaling (out: mat2d, v: vec2 | number[]): mat2d; /** * Creates a matrix from a vector translation @@ -1734,7 +1734,7 @@ export class mat2d extends Float32Array { * @param {vec2} v Translation vector * @returns {mat2d} out */ - public static fromTranslation (out: mat2d, v: vec2): mat2d + public static fromTranslation (out: mat2d, v: vec2 | number[]): mat2d /** * Returns a string representation of a mat2d @@ -1801,7 +1801,7 @@ export class mat2d extends Float32Array { * @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 + 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 ===) @@ -1824,7 +1824,7 @@ export class mat2d extends Float32Array { // mat3 export class mat3 extends Float32Array { - private typeMat3:number; + private typeMat3: number; /** * Creates a new identity mat3 @@ -1873,7 +1873,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:number, m01:number, m02:number, m10:number, m11:number, m12:number, m20:number, m21:number, m22:number): mat3; + public static fromValues(m00: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): mat3; /** @@ -1891,7 +1891,7 @@ export class mat3 extends Float32Array { * @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 + 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 @@ -1934,7 +1934,7 @@ export class mat3 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a: mat3):number; + public static determinant(a: mat3): number; /** * Multiplies two mat3's @@ -1965,7 +1965,7 @@ export class mat3 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out: mat3, a: mat3, v: vec3): mat3; + public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; /** * Rotates a mat3 by the given angle @@ -1975,7 +1975,7 @@ export class mat3 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotate(out: mat3, a: mat3, rad:number): mat3; + public static rotate(out: mat3, a: mat3, rad: number): mat3; /** * Scales the mat3 by the dimensions in the given vec2 @@ -1985,7 +1985,7 @@ export class mat3 extends Float32Array { * @param v the vec2 to scale the matrix by * @returns out **/ - public static scale(out: mat3, a: mat3, v: vec2): mat3; + public static scale(out: mat3, a: mat3, v: vec2 | number[]): mat3; /** * Creates a matrix from a vector translation @@ -1998,7 +1998,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Translation vector * @returns {mat3} out */ - public static fromTranslation(out: mat3, v: vec2): mat3 + public static fromTranslation(out: mat3, v: vec2 | number[]): mat3 /** * Creates a matrix from a given angle @@ -2011,7 +2011,7 @@ export class mat3 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat3} out */ - public static fromRotation(out: mat3, rad:number): mat3 + public static fromRotation(out: mat3, rad: number): mat3 /** * Creates a matrix from a vector scaling @@ -2024,7 +2024,7 @@ export class mat3 extends Float32Array { * @param {vec2} v Scaling vector * @returns {mat3} out */ - public static fromScaling(out: mat3, v: vec2): mat3 + public static fromScaling(out: mat3, v: vec2 | number[]): mat3 /** * Copies the values from a mat2d into a mat3 @@ -2061,7 +2061,7 @@ export class mat3 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat: mat3):string; + public static str(mat: mat3): string; /** * Returns Frobenius norm of a mat3 @@ -2069,7 +2069,7 @@ export class mat3 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a: mat3):number; + public static frob(a: mat3): number; /** * Adds two mat3's @@ -2109,7 +2109,7 @@ export class mat3 extends Float32Array { * @param {number} b amount to scale the matrix's elements by * @returns {mat3} out */ - public static multiplyScalar(out: mat3, a: mat3, b:number): mat3 + 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. @@ -2120,7 +2120,7 @@ export class mat3 extends Float32Array { * @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 + 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 ===) @@ -2129,7 +2129,7 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals(a: mat3, b: mat3):boolean; + public static exactEquals(a: mat3, b: mat3): boolean; /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2138,12 +2138,12 @@ export class mat3 extends Float32Array { * @param {mat3} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static equals(a: mat3, b: mat3):boolean + public static equals(a: mat3, b: mat3): boolean } // mat4 export class mat4 extends Float32Array { - private typeMat4:number; + private typeMat4: number; /** * Creates a new identity mat4 @@ -2191,7 +2191,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: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; + 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 @@ -2215,7 +2215,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: 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; + 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 @@ -2258,7 +2258,7 @@ export class mat4 extends Float32Array { * @param a the source matrix * @returns determinant of a */ - public static determinant(a: mat4):number; + public static determinant(a: mat4): number; /** * Multiplies two mat4's @@ -2288,7 +2288,7 @@ export class mat4 extends Float32Array { * @param v vector to translate by * @returns out */ - public static translate(out: mat4, a: mat4, v: vec3): mat4; + public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -2298,7 +2298,7 @@ export class mat4 extends Float32Array { * @param v the vec3 to scale the matrix by * @returns out **/ - public static scale(out: mat4, a: mat4, v: vec3): mat4; + public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Rotates a mat4 by the given angle @@ -2309,7 +2309,7 @@ export class mat4 extends Float32Array { * @param axis the axis to rotate around * @returns out */ - public static rotate(out: mat4, a: mat4, rad:number, axis: vec3): mat4; + public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -2319,7 +2319,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateX(out: mat4, a: mat4, rad:number): mat4; + public static rotateX(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -2329,7 +2329,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateY(out: mat4, a: mat4, rad:number): mat4; + public static rotateY(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -2339,7 +2339,7 @@ export class mat4 extends Float32Array { * @param rad the angle to rotate the matrix by * @returns out */ - public static rotateZ(out: mat4, a: mat4, rad:number): mat4; + public static rotateZ(out: mat4, a: mat4, rad: number): mat4; /** * Creates a matrix from a vector translation @@ -2352,7 +2352,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Translation vector * @returns {mat4} out */ - public static fromTranslation(out: mat4, v: vec3): mat4 + public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 /** * Creates a matrix from a vector scaling @@ -2365,7 +2365,7 @@ export class mat4 extends Float32Array { * @param {vec3} v Scaling vector * @returns {mat4} out */ - public static fromScaling(out: mat4, v: vec3): mat4 + public static fromScaling(out: mat4, v: vec3 | number[]): mat4 /** * Creates a matrix from a given angle around a given axis @@ -2379,7 +2379,7 @@ export class mat4 extends Float32Array { * @param {vec3} axis the axis to rotate around * @returns {mat4} out */ - public static fromRotation(out: mat4, rad:number, axis: vec3): mat4 + public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 /** * Creates a matrix from the given angle around the X axis @@ -2392,7 +2392,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromXRotation(out: mat4, rad:number): mat4 + public static fromXRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from the given angle around the Y axis @@ -2405,7 +2405,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromYRotation(out: mat4, rad:number): mat4 + public static fromYRotation(out: mat4, rad: number): mat4 /** @@ -2419,7 +2419,7 @@ export class mat4 extends Float32Array { * @param {number} rad the angle to rotate the matrix by * @returns {mat4} out */ - public static fromZRotation(out: mat4, rad:number): mat4 + public static fromZRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -2436,7 +2436,7 @@ export class mat4 extends Float32Array { * @param v Translation vector * @returns out */ - public static fromRotationTranslation(out: mat4, q: quat, v: vec3): mat4; + public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; /** * Returns the translation vector component of a transformation @@ -2477,7 +2477,7 @@ export class mat4 extends Float32Array { * @param s Scaling vector * @returns out */ - public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3, s: vec3): mat4; + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): mat4; /** * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin @@ -2499,7 +2499,7 @@ export class mat4 extends Float32Array { * @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 + public static fromRotationTranslationScaleOrigin(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[], o: vec3 | number[]): mat4 /** * Calculates a 4x4 matrix from the given quaternion @@ -2523,8 +2523,8 @@ export class mat4 extends Float32Array { * @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; + 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 @@ -2536,8 +2536,8 @@ export class mat4 extends Float32Array { * @param far Far bound of the frustum * @returns out */ - public static perspective(out: mat4, fovy:number, aspect:number, - near:number, far:number): mat4; + 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. @@ -2551,8 +2551,8 @@ export class mat4 extends Float32Array { * @returns {mat4} out */ public static perspectiveFromFieldOfView(out: mat4, - fov:{upDegrees:number, downDegrees:number, leftDegrees:number, rightDegrees:number}, - near:number, far:number): mat4 + fov:{upDegrees: number, downDegrees: number, leftDegrees: number, rightDegrees: number}, + near: number, far: number): mat4 /** * Generates a orthogonal projection matrix with the given bounds @@ -2566,8 +2566,8 @@ export class mat4 extends Float32Array { * @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; + 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 @@ -2578,7 +2578,7 @@ export class mat4 extends Float32Array { * @param up vec3 pointing up * @returns out */ - public static lookAt(out: mat4, eye: vec3, center: vec3, up: vec3): mat4; + public static lookAt(out: mat4, eye: vec3 | number[], center: vec3 | number[], up: vec3 | number[]): mat4; /** * Returns a string representation of a mat4 @@ -2586,7 +2586,7 @@ export class mat4 extends Float32Array { * @param mat matrix to represent as a string * @returns string representation of the matrix */ - public static str(mat: mat4):string; + public static str(mat: mat4): string; /** * Returns Frobenius norm of a mat4 @@ -2594,7 +2594,7 @@ export class mat4 extends Float32Array { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - public static frob(a: mat4):number; + public static frob(a: mat4): number; /** * Adds two mat4's @@ -2634,7 +2634,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:number): 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. @@ -2645,7 +2645,7 @@ export class mat4 extends Float32Array { * @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 + 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 ===) @@ -2654,7 +2654,7 @@ export class mat4 extends Float32Array { * @param {mat4} b The second matrix. * @returns {boolean} True if the matrices are equal, false otherwise. */ - public static exactEquals (a: mat4, b: mat4) :boolean + public static exactEquals (a: mat4, b: mat4): boolean /** * Returns whether or not the matrices have approximately the same elements in the same position. @@ -2669,7 +2669,7 @@ export class mat4 extends Float32Array { // quat export class quat extends Float32Array { - private typeQuat:number; + private typeQuat: number; /** * Creates a new identity quat @@ -2730,18 +2730,6 @@ export class quat extends Float32Array { */ public static identity(out: quat): 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 quaternion to represent the shortest rotation from one * vector to another. @@ -2753,7 +2741,19 @@ export class quat extends Float32Array { * @param {vec3} b the destination vector * @returns {quat} out */ - public static rotationTo (out: quat, a: vec3, b: vec3): quat; + public static rotationTo (out: quat, a: vec3 | number[], b: vec3 | number[]): 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 | number[], right: vec3 | number[], up: vec3 | number[]): quat @@ -2766,7 +2766,7 @@ export class quat extends Float32Array { * @param rad the angle in radians * @returns out **/ - public static setAxisAngle(out: quat, axis: vec3, rad: number): quat; + public static setAxisAngle(out: quat, axis: vec3 | number[], rad: number): quat; /** * Gets the rotation axis and angle for a given @@ -2781,7 +2781,7 @@ export class quat extends Float32Array { * @param {quat} q Quaternion to be decomposed * @return {number} Angle, in radians, of the rotation */ - public static getAxisAngle (out_axis: vec3, q: quat) :number + public static getAxisAngle (out_axis: vec3 | number[], q: quat): number /** * Adds two quat's @@ -2902,7 +2902,7 @@ export class quat extends Float32Array { * @param t interpolation amount between the two inputs * @returns out */ - public static slerp(out: quat, a: quat, b: quat, t:number): quat; + public static slerp(out: quat, a: quat, b: quat, t: number): quat; /** * Performs a spherical linear interpolation with two control points @@ -2998,7 +2998,7 @@ export class quat extends Float32Array { * @param up the vector representing the local "up" direction * @returns out */ - public static setAxes(out: quat, view: vec3, right: vec3, up: vec3): quat; + public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; /** * Sets a quaternion to represent the shortest rotation from one @@ -3011,7 +3011,7 @@ export class quat extends Float32Array { * @param b the destination vector * @returns out */ - public static rotationTo(out: quat, a: vec3, b: vec3): quat; + public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; /** * Calculates the W component of a quat from the X, Y, and Z components. @@ -3031,7 +3031,7 @@ export class quat extends Float32Array { * @param {quat} b The second vector. * @returns {boolean} True if the quaternions are equal, false otherwise. */ - public static exactEquals (a: quat, b: quat) : boolean; + public static exactEquals (a: quat, b: quat): boolean; /** * Returns whether or not the quaternions have approximately the same elements in the same position. @@ -3040,5 +3040,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 3fbffb91e3837db19fa35ee4617317f9ed3e9370 Mon Sep 17 00:00:00 2001 From: Mattijs Kneppers Date: Mon, 15 Aug 2016 18:13:26 +0200 Subject: [PATCH 003/212] rename old implementation to legacy and new to standard --- gl-matrix/gl-matrix-legacy-tests.ts | 362 ++++ gl-matrix/gl-matrix-legacy.d.ts | 2163 +++++++++++++++++++ gl-matrix/gl-matrix-tests.ts | 653 +++--- gl-matrix/gl-matrix-typed-tests.ts | 347 --- gl-matrix/gl-matrix-typed.d.ts | 3044 --------------------------- gl-matrix/gl-matrix.d.ts | 1697 +++++++++++---- 6 files changed, 4133 insertions(+), 4133 deletions(-) create mode 100644 gl-matrix/gl-matrix-legacy-tests.ts create mode 100644 gl-matrix/gl-matrix-legacy.d.ts delete mode 100644 gl-matrix/gl-matrix-typed-tests.ts delete mode 100644 gl-matrix/gl-matrix-typed.d.ts diff --git a/gl-matrix/gl-matrix-legacy-tests.ts b/gl-matrix/gl-matrix-legacy-tests.ts new file mode 100644 index 0000000000..5cfa9a1c3a --- /dev/null +++ b/gl-matrix/gl-matrix-legacy-tests.ts @@ -0,0 +1,362 @@ +/// + +// common +var result: number = glMatrix.toRadian(180); + +var out: GLM.IArray; +var outVal: number; +var outStr: string; + +// vec2 +var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray; +var vecArray: GLM.IArray; + +vecA = [1, 2]; +vecB = new Float32Array([3, 4]); +out = [0, 0]; +matA = [1, 2, 3, 4, 5, 6]; +vecArray = [1, 2, 3, 4, 0, 0]; + +out = vec2.create(); +out = vec2.clone(vecA); +out = vec2.fromValues(1, 2); +out = vec2.copy(out, vecA); +out = vec2.set(out, 1, 2); +out = vec2.add(out, vecA, vecB); +out = vec2.subtract(out, vecA, vecB); +out = vec2.sub(out, vecA, vecB); +out = vec2.multiply(out, vecA, vecB); +out = vec2.mul(out, vecA, vecB); +out = vec2.divide(out, vecA, vecB); +out = vec2.div(out, vecA, vecB); +out = vec2.min(out, vecA, vecB); +out = vec2.max(out, vecA, vecB); +out = vec2.scale(out, vecA, 2); +out = vec2.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec2.distance(vecA, vecB); +outVal = vec2.dist(vecA, vecB); +outVal = vec2.squaredDistance(vecA, vecB); +outVal = vec2.sqrDist(vecA, vecB); +outVal = vec2.length(vecA); +outVal = vec2.len(vecA); +outVal = vec2.squaredLength(vecA); +outVal = vec2.sqrLen(vecA); +out = vec2.negate(out, vecA); +out = vec2.inverse(out, vecA); +out = vec2.normalize(out, vecA); +outVal = vec2.dot(vecA, vecB); +out = vec2.cross(out, vecA, vecB); +out = vec2.lerp(out, vecA, vecB, 0.5); +out = vec2.random(out); +out = vec2.random(out, 5.0); +out = vec2.transformMat2(out, vecA, matA); +out = vec2.transformMat2d(out, vecA, matA); +out = vec2.transformMat3(out, vecA, matA); +out = vec2.transformMat4(out, vecA, matA); +out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); +outStr = vec2.str(vecA); + +// vec3 +var matr: GLM.IArray; +var q: GLM.IArray; + +vecA = [1, 2, 3]; +vecB = new Float32Array([4, 5, 6]); +out = [0, 0, 0]; +vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0]; +matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ]; + +out = vec3.create(); +out = vec3.clone(vecA); +out = vec3.fromValues(1, 2, 3); +out = vec3.copy(out, vecA); +out = vec3.set(out, 1, 2, 3); +out = vec3.add(out, vecA, vecB); +out = vec3.subtract(out, vecA, vecB); +out = vec3.sub(out, vecA, vecB); +out = vec3.multiply(out, vecA, vecB); +out = vec3.mul(out, vecA, vecB); +out = vec3.divide(out, vecA, vecB); +out = vec3.div(out, vecA, vecB); +out = vec3.min(out, vecA, vecB); +out = vec3.max(out, vecA, vecB); +out = vec3.scale(out, vecA, 2); +out = vec3.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec3.distance(vecA, vecB); +outVal = vec3.dist(vecA, vecB); +outVal = vec3.squaredDistance(vecA, vecB); +outVal = vec3.sqrDist(vecA, vecB); +outVal = vec3.length(vecA); +outVal = vec3.len(vecA); +outVal = vec3.squaredLength(vecA); +outVal = vec3.sqrLen(vecA); +out = vec3.negate(out, vecA); +out = vec3.inverse(out, vecA); +out = vec3.normalize(out, vecA); +outVal = vec3.dot(vecA, vecB); +out = vec3.cross(out, vecA, vecB); +out = vec3.lerp(out, vecA, vecB, 0.5); +out = vec3.random(out); +out = vec3.random(out, 5.0); +out = vec3.rotateX(out, vecA, vecB, Math.PI); +out = vec3.rotateY(out, vecA, vecB, Math.PI); +out = vec3.rotateZ(out, vecA, vecB, Math.PI); +out = vec3.transformMat3(out, vecA, matr); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; +out = vec3.transformMat4(out, vecA, matr); + +q = [1, 2, 3, 4]; +out = vec3.transformQuat(out, vecA, matr); + +out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); +outVal = vec3.angle(vecA, vecB); +outStr = vec3.str(vecA); + +// vec4 +var q: GLM.IArray; + +vecA = [1, 2, 3, 4]; +vecB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +q = [1, 2, 3, 4]; + +out = vec4.create(); +out = vec4.clone(vecA); +out = vec4.fromValues(1, 2, 3, 4); +out = vec4.copy(out, vecA); +out = vec4.set(out, 1, 2, 3, 4); +out = vec4.add(out, vecA, vecB); +out = vec4.subtract(out, vecA, vecB); +out = vec4.sub(out, vecA, vecB); +out = vec4.multiply(out, vecA, vecB); +out = vec4.mul(out, vecA, vecB); +out = vec4.divide(out, vecA, vecB); +out = vec4.div(out, vecA, vecB); +out = vec4.min(out, vecA, vecB); +out = vec4.max(out, vecA, vecB); +out = vec4.scale(out, vecA, 2); +out = vec4.scaleAndAdd(out, vecA, vecB, 0.5); +outVal = vec4.distance(vecA, vecB); +outVal = vec4.dist(vecA, vecB); +outVal = vec4.squaredDistance(vecA, vecB); +outVal = vec4.sqrDist(vecA, vecB); +outVal = vec4.length(vecA); +outVal = vec4.len(vecA); +outVal = vec4.squaredLength(vecA); +outVal = vec4.sqrLen(vecA); +out = vec4.negate(out, vecA); +out = vec4.inverse(out, vecA); +out = vec4.normalize(out, vecA); +outVal = vec4.dot(vecA, vecB); +out = vec4.lerp(out, vecA, vecB, 0.5); +out = vec4.random(out); +out = vec4.random(out, 5.0); + +matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] +out = vec4.transformMat4(out, vecA, matr); +out = vec4.transformQuat(out, vecA, q); + +vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]; +out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); +outStr = vec4.str(vecA); + +// mat2 +var matB: GLM.IArray, identity: GLM.IArray; + +matA = [1, 2, 3, 4]; +matB = new Float32Array([5, 6, 7, 8]); +out = [0, 0, 0, 0]; +identity = [1, 0, 0, 1]; + +out = mat2.create(); +out = mat2.clone(matA); +out = mat2.copy(out, matA); +out = mat2.identity(out); +out = mat2.transpose(out, matA); +out = mat2.invert(out, matA); +out = mat2.adjoint(out, matA); +outVal = mat2.determinant(matA); +out = mat2.multiply(out, matA, matB); +out = mat2.mul(out, matA, matB); +out = mat2.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2.scale(out, matA, vecA); +outStr = mat2.str(matA); +outVal = mat2.frob(matA); + +var L = mat2.create(); +var D = mat2.create(); +var U = mat2.create(); +out = mat2.LDU(L, D, U, [4,3,6,3]); + +// mat2d +matA = [1, 2, 3, 4, 5, 6]; +matB = [7, 8, 9, 10, 11, 12]; +out = [0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 1, 0, 0]; + +out = mat2d.create(); +out = mat2d.clone(matA); +out = mat2d.copy(out, matA); +out = mat2d.identity(out); +out = mat2d.invert(out, matA); +outVal = mat2d.determinant(matA); +out = mat2d.multiply(out, matA, matB); +out = mat2d.mul(out, matA, matB); +out = mat2d.rotate(out, matA, Math.PI * 0.5); + +vecA = [2, 3]; +out = mat2d.scale(out, matA, vecA); +out = mat2d.translate(out, matA, vecA); +outStr = mat2d.str(matA); +outVal = mat2d.frob(matA); + +// mat3 +matA = [1, 0, 0, 0, 1, 0, 1, 2, 1]; +matB = [1, 0, 0, 0, 1, 0, 3, 4, 1]; +out = [0, 0, 0, 0, 0, 0, 0, 0, 0]; +identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; + +out = mat3.create(); +out = mat3.clone(matA); +out = mat3.copy(out, matA); +out = mat3.identity(out); +out = mat3.transpose(out, matA); +out = mat3.invert(out, matA); +out = mat3.adjoint(out, matA); +outVal = mat3.determinant(matA); +out = mat3.multiply(out, matA, matB); +out = mat3.mul(out, matA, matB); +outStr = mat3.str(matA); +outVal = mat3.frob(matA); + +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; +out = mat3.normalFromMat4(out, matA); + +q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ]; +out = mat3.fromQuat(out, q); + +out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); +out = mat3.scale(out, matA, [2,2]); +out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]); + +out = mat3.translate(out, matA, [1, 2, 3]); +out = mat3.rotate(out, matA, Math.PI/2); + +// mat4 +matA = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 1, 2, 3, 1]; + +matB = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 4, 5, 6, 1]; + +out = [0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0]; + +identity = [1, 0, 0, 0, + 0, 1, 0, 0, + 0, 0, 1, 0, + 0, 0, 0, 1]; + +out = mat4.create(); +out = mat4.clone(matA); +out = mat4.copy(out, matA); +out = mat4.identity(out); +out = mat4.transpose(out, matA); +out = mat4.invert(out, matA); +out = mat4.adjoint(out, matA); +outVal = mat4.determinant(matA); +out = mat4.multiply(out, matA, matB); +out = mat4.mul(out, matA, matB); +out = mat4.translate(out, matA, [4, 5, 6]); +out = mat4.scale(out, matA, [4, 5, 6]); + +var rad = Math.PI * 0.5; +var axis = [1, 0, 0]; +out = mat4.rotate(out, matA, rad, axis); +out = mat4.rotateX(out, matA, rad); +out = mat4.rotateY(out, matA, rad); +out = mat4.rotateZ(out, matA, rad); + +out = mat4.frustum(out, -1, 1, -1, 1, -1, 1); + +var fovy = Math.PI * 0.5; +out = mat4.perspective(out, fovy, 1, 0, 1); +out = mat4.ortho(out, -1, 1, -1, 1, -1, 1); + +var eye = [0, 0, 1]; +var center = [0, 0, -1]; +var up = [0, 1, 0]; +out = mat4.lookAt(out, eye, center, up); + +outStr = mat4.str(matA); +outVal = mat4.frob(matA); + +q = [0, 0, 0, 1]; +out = mat4.fromRotationTranslation(out, q, [1, 2, 3]); +out = mat4.fromQuat(out, q); + +q = [0, 0, 0, 1]; +out = mat4.fromRotationTranslationScale(out, q, [1, 2, 3], [1, 2, 3]); +out = mat4.fromQuat(out, q); + + +// quat +var quatA = [1, 2, 3, 4]; +var quatB = [5, 6, 7, 8]; +out = [0, 0, 0, 0]; +var vec = [1, 1, -1]; +var id = [0, 0, 0, 1]; +var deg90 = Math.PI / 2; + +out = quat.create(); +out = quat.clone(quatA); +out = quat.fromValues(1, 2, 3, 4); +out = quat.copy(out, quatA); +out = quat.set(out, 1, 2, 3, 4); +out = quat.identity(out); +out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5); +out = quat.add(out, quatA, quatB); +out = quat.multiply(out, quatA, quatB); +out = quat.mul(out, quatA, quatB); +out = quat.scale(out, quatA, 2); +outVal = quat.length(quatA); +outVal = quat.len(quatA); +outVal = quat.squaredLength(quatA); +outVal = quat.sqrLen(quatA); +out = quat.normalize(out, quatA); +outVal = quat.dot(out, quatA, quatB); +out = quat.lerp(out, quatA, quatB, 0.5); +out = quat.slerp(out, quatA, quatB, 0.5); +out = quat.invert(out, quatA); +out = quat.conjugate(out, quatA); +outStr = quat.str(quatA); +out = quat.rotateX(out, id, deg90); +out = quat.rotateY(out, id, deg90); +out = quat.rotateZ(out, id, deg90); + +matr = [ 1, 0, 0, + 0, 0, -1, + 0, 1, 0 ]; +out = quat.fromMat3(out, matr); + +var view = [-1, 0, 0]; +up = [ 0, 1, 0]; +var right= [ 0, 0,-1]; +out = quat.setAxes([], view, right, up); + +out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]); +out = quat.calculateW(out, quatA); + diff --git a/gl-matrix/gl-matrix-legacy.d.ts b/gl-matrix/gl-matrix-legacy.d.ts new file mode 100644 index 0000000000..16366f263a --- /dev/null +++ b/gl-matrix/gl-matrix-legacy.d.ts @@ -0,0 +1,2163 @@ +// Type definitions for gl-matrix 2.2.2 +// Project: https://github.com/toji/gl-matrix +// Definitions by: Tat +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace GLM { + interface IArray + { + /** + * Must be indexable like an array + */ + [index: number]: number; + } +} + +// Common +declare namespace glMatrix { + /** + * Convert Degree To Radian + * + * @param a Angle in Degrees + */ + export function toRadian(a: number): number; +} + +// vec2 +declare namespace vec2 { + /** + * Creates a new, empty vec2 + * + * @returns a new 2D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec2 initialized with values from an existing vector + * + * @param a a vector to clone + * @returns a new 2D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Creates a new vec2 initialized with the given values + * + * @param x X component + * @param y Y component + * @returns a new 2D vector + */ + export function fromValues(x: number, y: number): GLM.IArray; + + /** + * Copy the values from one vec2 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function set(out: GLM.IArray, x: number, y: number): GLM.IArray; + + /** + * Adds two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec2's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * 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 + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec2's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function dist(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec2 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec2 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec2 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec2 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec2 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function dot(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * 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 + */ + export function transformMat2(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function transformMat2d(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * 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 + */ + export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec3 +declare namespace vec3 { + + /** + * Creates a new, empty vec3 + * + * @returns a new 3D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec3 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 3D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function fromValues(x: number, y: number, z: number): GLM.IArray; + + /** + * Copy the values from one vec3 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function set(out: GLM.IArray, x: number, y: number, z: number): GLM.IArray; + + /** + * Adds two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec3's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * 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 + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec3's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function dist(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec3 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec3 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec3 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec3 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec3 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function dot(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * 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 + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * 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 + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * 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 + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + + /** + * 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 + */ + export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, q: GLM.IArray): GLM.IArray; + + + /** + * 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 + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * 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 + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Get the angle between two 3D vectors + * @param a The first operand + * @param b The second operand + * @returns The angle in radians + */ + export function angle(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// vec4 +declare namespace vec4 { + + /** + * Creates a new, empty vec4 + * + * @returns a new 4D vector + */ + export function create(): GLM.IArray; + + /** + * Creates a new vec4 initialized with values from an existing vector + * + * @param a vector to clone + * @returns a new 4D vector + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one vec4 to another + * + * @param out the receiving vector + * @param a the source vector + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Adds two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Subtracts vector b from vector a + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Divides two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the minimum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns the maximum of two vec4's + * + * @param out the receiving vector + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * 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 + */ + export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + + /** + * Calculates the euclidian distance between two vec4's + * + * @param a the first operand + * @param b the second operand + * @returns distance between a and b + */ + export function distance(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function dist(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function squaredDistance(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a vec4 + * + * @param a vector to calculate length of + * @returns length of a + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a vec4 + * + * @param a vector to calculate squared length of + * @returns squared length of a + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Negates the components of a vec4 + * + * @param out the receiving vector + * @param a vector to negate + * @returns out + */ + export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns the inverse of the components of a vec4 + * + * @param out the receiving vector + * @param a vector to invert + * @returns out + */ + export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Normalize a vec4 + * + * @param out the receiving vector + * @param a vector to normalize + * @returns out + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function dot(a: GLM.IArray, b: GLM.IArray): 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 + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Generates a random unit vector + * + * @param out the receiving vector + * @returns out + */ + export function random(out: GLM.IArray): GLM.IArray; + + /** + * Generates a random vector with the given scale + * + * @param out the receiving vector + * @param Length of the resulting vector. If ommitted, a unit vector will be returned + * @returns out + */ + export function random(out: GLM.IArray, scale: number): GLM.IArray; + + /** + * 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 + */ + export function transformMat4(out: GLM.IArray, a: GLM.IArray, mat: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function transformQuat(out: GLM.IArray, a: GLM.IArray, quat: GLM.IArray): GLM.IArray; + + /** + * 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 additional argument to pass to fn + * @returns a + * @function + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + + /** + * 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 + */ + export function forEach(out: GLM.IArray, string: number, offset: number, count: number, + callback: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + + /** + * Returns a string representation of a vector + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): string; +} + +// mat2 +declare namespace mat2 { + + /** + * Creates a new identity mat2 + * + * @returns a new 2x2 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x2 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat2 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * 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 + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2 + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): 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 + */ + export function LDU(L: GLM.IArray, D: GLM.IArray, U: GLM.IArray, a: GLM.IArray): GLM.IArray; +} + +// mat2d +declare namespace mat2d { + + /** + * Creates a new identity mat2d + * + * @returns a new 2x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat2d initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 2x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat2d to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat2d to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat2d + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat2d + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat2d's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * 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 + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * 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 + **/ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat2d + * + * @param a matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(a: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat2d + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; +} + +// mat3 +declare namespace mat3 { + + /** + * Creates a new identity mat3 + * + * @returns a new 3x3 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat3 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 3x3 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat3 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat3 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat3 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat3 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat3's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat3 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat3 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * 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 + */ + export function normalFromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates a 3x3 matrix from the given quaternion + * + * @param out mat3 receiving operation result + * @param q Quaternion to create matrix from + * + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; + + /** + * Copies the upper-left 3x3 values into the given mat3. + * + * @param out the receiving 3x3 matrix + * @param a the source 4x4 matrix + * @returns out + */ + export function fromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * Copies the values from a mat2d into a mat3 + * + * @param out the receiving matrix + * @param {mat2d} a the matrix to copy + * @returns out + **/ + export function fromMat2d(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; +} + +// mat4 +declare namespace mat4 { + + /** + * Creates a new identity mat4 + * + * @returns a new 4x4 matrix + */ + export function create(): GLM.IArray; + + /** + * Creates a new mat4 initialized with values from an existing matrix + * + * @param a matrix to clone + * @returns a new 4x4 matrix + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * Copy the values from one mat4 to another + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Set a mat4 to the identity matrix + * + * @param out the receiving matrix + * @returns out + */ + export function identity(a: GLM.IArray): GLM.IArray; + + /** + * Transpose the values of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Inverts a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the adjugate of a mat4 + * + * @param out the receiving matrix + * @param a the source matrix + * @returns out + */ + export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Calculates the determinant of a mat4 + * + * @param a the source matrix + * @returns determinant of a + */ + export function determinant(a: GLM.IArray): number; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two mat4's + * + * @param out the receiving matrix + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * 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 + **/ + export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number, axis: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * 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 + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * 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 + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * 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 + */ + export function frustum(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * 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 + */ + export function perspective(out: GLM.IArray, fovy: number, aspect: number, + near: number, far: number): GLM.IArray; + + /** + * 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 + */ + export function ortho(out: GLM.IArray, left: number, right: number, + bottom: number, top: number, near: number, far: number): GLM.IArray; + + /** + * 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 + */ + export function lookAt(out: GLM.IArray, eye: GLM.IArray, + center: GLM.IArray, up: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a mat4 + * + * @param mat matrix to represent as a string + * @returns string representation of the matrix + */ + export function str(mat: GLM.IArray): string; + + /** + * Returns Frobenius norm of a mat4 + * + * @param a the matrix to calculate Frobenius norm of + * @returns Frobenius norm + */ + export function frob(a: GLM.IArray): number; + + /** + * 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 + */ + export function fromRotationTranslation(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray): GLM.IArray; + + /** + * 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 Scale vector + * @returns out + */ + export function fromRotationTranslationScale(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray, s: GLM.IArray): GLM.IArray + + /** + * Creates a matrix from a quaternion + * + * @param out mat4 receiving operation result + * @param q Rotation quaternion + * @returns out + */ + export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; +} + +// quat +declare namespace quat { + + /** + * Creates a new identity quat + * + * @returns a new quaternion + */ + export function create(): GLM.IArray; + + /** + * Creates a new quat initialized with values from an existing quaternion + * + * @param a quaternion to clone + * @returns a new quaternion + * @function + */ + export function clone(a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Copy the values from one quat to another + * + * @param out the receiving quaternion + * @param a the source quaternion + * @returns out + * @function + */ + export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + + /** + * Set a quat to the identity quaternion + * + * @param out the receiving quaternion + * @returns out + */ + export function identity(out: GLM.IArray): GLM.IArray; + + /** + * 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 + **/ + export function setAxisAngle(out: GLM.IArray, axis: GLM.IArray, rad: number): GLM.IArray; + + /** + * Adds two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + * @function + */ + export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * Multiplies two quat's + * + * @param out the receiving quaternion + * @param a the first operand + * @param b the second operand + * @returns out + */ + export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function length(a: GLM.IArray): number; + + /** + * Calculates the length of a quat + * + * @param a vector to calculate length of + * @returns length of a + * @function + */ + export function len(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function squaredLength(a: GLM.IArray): number; + + /** + * Calculates the squared length of a quat + * + * @param a vector to calculate squared length of + * @returns squared length of a + * @function + */ + export function sqrLen(a: GLM.IArray): number; + + /** + * Normalize a quat + * + * @param out the receiving quaternion + * @param a quaternion to normalize + * @returns out + * @function + */ + export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function dot(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): 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 + */ + export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * 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 + */ + export function slerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + + /** + * Calculates the inverse of a quat + * + * @param out the receiving quaternion + * @param a quat to calculate inverse of + * @returns out + */ + export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function conjugate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + + /** + * Returns a string representation of a quatenion + * + * @param vec vector to represent as a string + * @returns string representation of the vector + */ + export function str(a: GLM.IArray): 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 + */ + export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * 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 + */ + export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * 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 + */ + export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + + /** + * 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 + */ + export function fromMat3(out: GLM.IArray, m: GLM.IArray): GLM.IArray; + + /** + * 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 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 + */ + export function setAxes(out: GLM.IArray, view: GLM.IArray, right: GLM.IArray, + up: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function rotationTo(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + + /** + * 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 + */ + export function calculateW(out: GLM.IArray, a: GLM.IArray): GLM.IArray; +} diff --git a/gl-matrix/gl-matrix-tests.ts b/gl-matrix/gl-matrix-tests.ts index 682bca7b8b..984ca3d1c3 100644 --- a/gl-matrix/gl-matrix-tests.ts +++ b/gl-matrix/gl-matrix-tests.ts @@ -1,362 +1,347 @@ /// // common -var result: number = glMatrix.toRadian(180); +import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix"; -var out: GLM.IArray; 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 -var vecA: GLM.IArray, vecB: GLM.IArray, matA: GLM.IArray; -var vecArray: GLM.IArray; - -vecA = [1, 2]; -vecB = new Float32Array([3, 4]); -out = [0, 0]; -matA = [1, 2, 3, 4, 5, 6]; -vecArray = [1, 2, 3, 4, 0, 0]; - -out = vec2.create(); -out = vec2.clone(vecA); -out = vec2.fromValues(1, 2); -out = vec2.copy(out, vecA); -out = vec2.set(out, 1, 2); -out = vec2.add(out, vecA, vecB); -out = vec2.subtract(out, vecA, vecB); -out = vec2.sub(out, vecA, vecB); -out = vec2.multiply(out, vecA, vecB); -out = vec2.mul(out, vecA, vecB); -out = vec2.divide(out, vecA, vecB); -out = vec2.div(out, vecA, vecB); -out = vec2.min(out, vecA, vecB); -out = vec2.max(out, vecA, vecB); -out = vec2.scale(out, vecA, 2); -out = vec2.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec2.distance(vecA, vecB); -outVal = vec2.dist(vecA, vecB); -outVal = vec2.squaredDistance(vecA, vecB); -outVal = vec2.sqrDist(vecA, vecB); -outVal = vec2.length(vecA); -outVal = vec2.len(vecA); -outVal = vec2.squaredLength(vecA); -outVal = vec2.sqrLen(vecA); -out = vec2.negate(out, vecA); -out = vec2.inverse(out, vecA); -out = vec2.normalize(out, vecA); -outVal = vec2.dot(vecA, vecB); -out = vec2.cross(out, vecA, vecB); -out = vec2.lerp(out, vecA, vecB, 0.5); -out = vec2.random(out); -out = vec2.random(out, 5.0); -out = vec2.transformMat2(out, vecA, matA); -out = vec2.transformMat2d(out, vecA, matA); -out = vec2.transformMat3(out, vecA, matA); -out = vec2.transformMat4(out, vecA, matA); -out = vec2.forEach(vecArray, 0, 0, 0, vec2.normalize); -outStr = vec2.str(vecA); +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); +outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input // vec3 -var matr: GLM.IArray; -var q: GLM.IArray; - -vecA = [1, 2, 3]; -vecB = new Float32Array([4, 5, 6]); -out = [0, 0, 0]; -vecArray = [1, 2, 3, 4, 5, 6, 0, 0, 0]; -matr = [1, 0, 0, 0, 1, 0, 0, 0, 1 ]; - -out = vec3.create(); -out = vec3.clone(vecA); -out = vec3.fromValues(1, 2, 3); -out = vec3.copy(out, vecA); -out = vec3.set(out, 1, 2, 3); -out = vec3.add(out, vecA, vecB); -out = vec3.subtract(out, vecA, vecB); -out = vec3.sub(out, vecA, vecB); -out = vec3.multiply(out, vecA, vecB); -out = vec3.mul(out, vecA, vecB); -out = vec3.divide(out, vecA, vecB); -out = vec3.div(out, vecA, vecB); -out = vec3.min(out, vecA, vecB); -out = vec3.max(out, vecA, vecB); -out = vec3.scale(out, vecA, 2); -out = vec3.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec3.distance(vecA, vecB); -outVal = vec3.dist(vecA, vecB); -outVal = vec3.squaredDistance(vecA, vecB); -outVal = vec3.sqrDist(vecA, vecB); -outVal = vec3.length(vecA); -outVal = vec3.len(vecA); -outVal = vec3.squaredLength(vecA); -outVal = vec3.sqrLen(vecA); -out = vec3.negate(out, vecA); -out = vec3.inverse(out, vecA); -out = vec3.normalize(out, vecA); -outVal = vec3.dot(vecA, vecB); -out = vec3.cross(out, vecA, vecB); -out = vec3.lerp(out, vecA, vecB, 0.5); -out = vec3.random(out); -out = vec3.random(out, 5.0); -out = vec3.rotateX(out, vecA, vecB, Math.PI); -out = vec3.rotateY(out, vecA, vecB, Math.PI); -out = vec3.rotateZ(out, vecA, vecB, Math.PI); -out = vec3.transformMat3(out, vecA, matr); - -matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; -out = vec3.transformMat4(out, vecA, matr); - -q = [1, 2, 3, 4]; -out = vec3.transformQuat(out, vecA, matr); - -out = vec3.forEach(vecArray, 0, 0, 0, vec3.normalize); -outVal = vec3.angle(vecA, vecB); -outStr = vec3.str(vecA); +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); +outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input // vec4 -var q: GLM.IArray; - -vecA = [1, 2, 3, 4]; -vecB = new Float32Array([5, 6, 7, 8]); -out = [0, 0, 0, 0]; -q = [1, 2, 3, 4]; - -out = vec4.create(); -out = vec4.clone(vecA); -out = vec4.fromValues(1, 2, 3, 4); -out = vec4.copy(out, vecA); -out = vec4.set(out, 1, 2, 3, 4); -out = vec4.add(out, vecA, vecB); -out = vec4.subtract(out, vecA, vecB); -out = vec4.sub(out, vecA, vecB); -out = vec4.multiply(out, vecA, vecB); -out = vec4.mul(out, vecA, vecB); -out = vec4.divide(out, vecA, vecB); -out = vec4.div(out, vecA, vecB); -out = vec4.min(out, vecA, vecB); -out = vec4.max(out, vecA, vecB); -out = vec4.scale(out, vecA, 2); -out = vec4.scaleAndAdd(out, vecA, vecB, 0.5); -outVal = vec4.distance(vecA, vecB); -outVal = vec4.dist(vecA, vecB); -outVal = vec4.squaredDistance(vecA, vecB); -outVal = vec4.sqrDist(vecA, vecB); -outVal = vec4.length(vecA); -outVal = vec4.len(vecA); -outVal = vec4.squaredLength(vecA); -outVal = vec4.sqrLen(vecA); -out = vec4.negate(out, vecA); -out = vec4.inverse(out, vecA); -out = vec4.normalize(out, vecA); -outVal = vec4.dot(vecA, vecB); -out = vec4.lerp(out, vecA, vecB, 0.5); -out = vec4.random(out); -out = vec4.random(out, 5.0); - -matr = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ] -out = vec4.transformMat4(out, vecA, matr); -out = vec4.transformQuat(out, vecA, q); - -vecArray = [1, 2, 3, 4, 5, 6, 7, 8, 0, 0, 0, 0]; -out = vec4.forEach(vecArray, 0, 0, 0, vec4.normalize); -outStr = vec4.str(vecA); +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); +outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input // mat2 -var matB: GLM.IArray, identity: GLM.IArray; - -matA = [1, 2, 3, 4]; -matB = new Float32Array([5, 6, 7, 8]); -out = [0, 0, 0, 0]; -identity = [1, 0, 0, 1]; - -out = mat2.create(); -out = mat2.clone(matA); -out = mat2.copy(out, matA); -out = mat2.identity(out); -out = mat2.transpose(out, matA); -out = mat2.invert(out, matA); -out = mat2.adjoint(out, matA); -outVal = mat2.determinant(matA); -out = mat2.multiply(out, matA, matB); -out = mat2.mul(out, matA, matB); -out = mat2.rotate(out, matA, Math.PI * 0.5); - -vecA = [2, 3]; -out = mat2.scale(out, matA, vecA); -outStr = mat2.str(matA); -outVal = mat2.frob(matA); - -var L = mat2.create(); -var D = mat2.create(); +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(); -out = mat2.LDU(L, D, U, [4,3,6,3]); +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 -matA = [1, 2, 3, 4, 5, 6]; -matB = [7, 8, 9, 10, 11, 12]; -out = [0, 0, 0, 0, 0, 0]; -identity = [1, 0, 0, 1, 0, 0]; - -out = mat2d.create(); -out = mat2d.clone(matA); -out = mat2d.copy(out, matA); -out = mat2d.identity(out); -out = mat2d.invert(out, matA); -outVal = mat2d.determinant(matA); -out = mat2d.multiply(out, matA, matB); -out = mat2d.mul(out, matA, matB); -out = mat2d.rotate(out, matA, Math.PI * 0.5); - -vecA = [2, 3]; -out = mat2d.scale(out, matA, vecA); -out = mat2d.translate(out, matA, vecA); -outStr = mat2d.str(matA); -outVal = mat2d.frob(matA); +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 -matA = [1, 0, 0, 0, 1, 0, 1, 2, 1]; -matB = [1, 0, 0, 0, 1, 0, 3, 4, 1]; -out = [0, 0, 0, 0, 0, 0, 0, 0, 0]; -identity = [1, 0, 0, 0, 1, 0, 0, 0, 1]; - -out = mat3.create(); -out = mat3.clone(matA); -out = mat3.copy(out, matA); -out = mat3.identity(out); -out = mat3.transpose(out, matA); -out = mat3.invert(out, matA); -out = mat3.adjoint(out, matA); -outVal = mat3.determinant(matA); -out = mat3.multiply(out, matA, matB); -out = mat3.mul(out, matA, matB); -outStr = mat3.str(matA); -outVal = mat3.frob(matA); - -matA = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]; -out = mat3.normalFromMat4(out, matA); - -q = [ 0, -0.7071067811865475, 0, 0.7071067811865475 ]; -out = mat3.fromQuat(out, q); - -out = mat3.normalFromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); -out = mat3.fromMat4(out, [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12, 13,14,15,16]); -out = mat3.scale(out, matA, [2,2]); -out = mat3.fromMat2d(out, [1, 2, 3, 4, 5, 6]); - -out = mat3.translate(out, matA, [1, 2, 3]); -out = mat3.rotate(out, matA, Math.PI/2); - -// mat4 -matA = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 1, 2, 3, 1]; - -matB = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 4, 5, 6, 1]; - -out = [0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0, - 0, 0, 0, 0]; - -identity = [1, 0, 0, 0, - 0, 1, 0, 0, - 0, 0, 1, 0, - 0, 0, 0, 1]; - -out = mat4.create(); -out = mat4.clone(matA); -out = mat4.copy(out, matA); -out = mat4.identity(out); -out = mat4.transpose(out, matA); -out = mat4.invert(out, matA); -out = mat4.adjoint(out, matA); -outVal = mat4.determinant(matA); -out = mat4.multiply(out, matA, matB); -out = mat4.mul(out, matA, matB); -out = mat4.translate(out, matA, [4, 5, 6]); -out = mat4.scale(out, matA, [4, 5, 6]); - -var rad = Math.PI * 0.5; -var axis = [1, 0, 0]; -out = mat4.rotate(out, matA, rad, axis); -out = mat4.rotateX(out, matA, rad); -out = mat4.rotateY(out, matA, rad); -out = mat4.rotateZ(out, matA, rad); - -out = mat4.frustum(out, -1, 1, -1, 1, -1, 1); - -var fovy = Math.PI * 0.5; -out = mat4.perspective(out, fovy, 1, 0, 1); -out = mat4.ortho(out, -1, 1, -1, 1, -1, 1); - -var eye = [0, 0, 1]; -var center = [0, 0, -1]; -var up = [0, 1, 0]; -out = mat4.lookAt(out, eye, center, up); - -outStr = mat4.str(matA); -outVal = mat4.frob(matA); - -q = [0, 0, 0, 1]; -out = mat4.fromRotationTranslation(out, q, [1, 2, 3]); -out = mat4.fromQuat(out, q); - -q = [0, 0, 0, 1]; -out = mat4.fromRotationTranslationScale(out, q, [1, 2, 3], [1, 2, 3]); -out = mat4.fromQuat(out, q); +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 quatA = [1, 2, 3, 4]; -var quatB = [5, 6, 7, 8]; -out = [0, 0, 0, 0]; -var vec = [1, 1, -1]; -var id = [0, 0, 0, 1]; var deg90 = Math.PI / 2; - -out = quat.create(); -out = quat.clone(quatA); -out = quat.fromValues(1, 2, 3, 4); -out = quat.copy(out, quatA); -out = quat.set(out, 1, 2, 3, 4); -out = quat.identity(out); -out = quat.setAxisAngle(out, [1, 0, 0], Math.PI * 0.5); -out = quat.add(out, quatA, quatB); -out = quat.multiply(out, quatA, quatB); -out = quat.mul(out, quatA, quatB); -out = quat.scale(out, quatA, 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); -out = quat.normalize(out, quatA); -outVal = quat.dot(out, quatA, quatB); -out = quat.lerp(out, quatA, quatB, 0.5); -out = quat.slerp(out, quatA, quatB, 0.5); -out = quat.invert(out, quatA); -out = quat.conjugate(out, 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); -out = quat.rotateX(out, id, deg90); -out = quat.rotateY(out, id, deg90); -out = quat.rotateZ(out, id, deg90); - -matr = [ 1, 0, 0, - 0, 0, -1, - 0, 1, 0 ]; -out = quat.fromMat3(out, matr); - -var view = [-1, 0, 0]; -up = [ 0, 1, 0]; -var right= [ 0, 0,-1]; -out = quat.setAxes([], view, right, up); - -out = quat.rotationTo(out, [0, 1, 0], [1, 0, 0]); -out = quat.calculateW(out, 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); diff --git a/gl-matrix/gl-matrix-typed-tests.ts b/gl-matrix/gl-matrix-typed-tests.ts deleted file mode 100644 index 64f6beb7a4..0000000000 --- a/gl-matrix/gl-matrix-typed-tests.ts +++ /dev/null @@ -1,347 +0,0 @@ -/// - -// common -import {vec2, mat2, mat3, mat4, vec3, vec4, mat2d, quat} from "./gl-matrix-typed"; - -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); -outVec2 = vec2.add(outVec2, [0, 1], [2, 3]); // test one method with number array input - -// 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); -outVec3 = vec3.add(outVec3, [0, 1, 2], [3, 4, 5]); // test one method with number array input - -// 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); -outVec4 = vec4.add(outVec4, [0, 1, 2, 3], [4, 5, 6, 7]); // test one method with number array input - -// 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 deleted file mode 100644 index 2edbbd8bb5..0000000000 --- a/gl-matrix/gl-matrix-typed.d.ts +++ /dev/null @@ -1,3044 +0,0 @@ -// Type definitions for gl-matrix 2.2.2 -// Project: https://github.com/toji/gl-matrix -// Definitions by: Mattijs Kneppers , based on definitions by Tat -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -// 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 | number[]): 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 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[]): 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 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[]): 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 | number[], 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 | number[], b: vec2 | number[], 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): number; - - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec2 | number[]): number; - - /** - * Calculates the length of a vec2 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec2 | number[]): 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[]): 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[]): 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 | number[]): 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 | number[]): vec2; - - /** - * Normalize a vec2 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec2, a: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[], 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 | number[], 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 | number[], 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 | number[], 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 | number[], 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: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * 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: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; - - /** - * 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 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[]): 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 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[]): 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 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[]): 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 | number[], 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 | number[], b: vec3 | number[], 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec3 | number[]): number; - - /** - * Calculates the length of a vec3 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec3 | number[]): 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[]): 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[]): 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 | number[]): 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 | number[]): vec3; - - /** - * Normalize a vec3 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec3, a: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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 | number[], b: vec3 | number[], 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 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], 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 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], 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 | number[], 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 | number[], 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 | number[], 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 | number[], b: vec3 | number[], 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 | number[], b: vec3 | number[], 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 | number[], b: vec3 | number[], 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: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * 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: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; - - /** - * 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 | number[], b: vec3 | number[]): 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 | number[]): 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: vec3 | number[], b: vec3 | number[]): 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: vec3 | number[], b: vec3 | number[]): 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 | number[]): 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 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[]): 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 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[]): 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 | number[], 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 | number[], b: vec4 | number[], 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static length(a: vec4 | number[]): number; - - /** - * Calculates the length of a vec4 - * - * @param a vector to calculate length of - * @returns length of a - */ - public static len(a: vec4 | number[]): 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[]): 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[]): 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 | number[]): 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 | number[]): vec4; - - /** - * Normalize a vec4 - * - * @param out the receiving vector - * @param a vector to normalize - * @returns out - */ - public static normalize(out: vec4, a: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[], 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 | number[], 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 | number[], 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: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; - - /** - * 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: Float32Array, stride: number, offset: number, count: number, - fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; - - /** - * 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 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[]): 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 | number[]): mat2; - - /** - * 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 | number[]): 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 | number[]): 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 | number[]): 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 | number[]): 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: number): 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: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): 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 | number[]): 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 | number[]): 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 | number[]): 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 | number[]): 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; - - /** - * 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: mat4): 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: 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 - * - * @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: 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 - * - * @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 | number[]): 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 | number[]): 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 | number[]): 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 | number[]): 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 | number[]): 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 | number[]): 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 | number[]): 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 | number[], s: vec3 | number[]): 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 | number[], s: vec3 | number[], o: vec3 | number[]): 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: number, far: number): 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 | number[], center: vec3 | number[], up: vec3 | number[]): 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: number): 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 | number[], b: vec3 | number[]): 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 | number[], right: vec3 | number[], up: vec3 | number[]): 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 | number[], 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 | number[], 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 | number[], right: vec3 | number[], up: vec3 | number[]): 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 | number[], b: vec3 | number[]): 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; -} diff --git a/gl-matrix/gl-matrix.d.ts b/gl-matrix/gl-matrix.d.ts index 16366f263a..2edbbd8bb5 100644 --- a/gl-matrix/gl-matrix.d.ts +++ b/gl-matrix/gl-matrix.d.ts @@ -1,36 +1,18 @@ // 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 -declare namespace GLM { - interface IArray - { - /** - * Must be indexable like an array - */ - [index: number]: number; - } -} - -// Common -declare namespace glMatrix { - /** - * Convert Degree To Radian - * - * @param a Angle in Degrees - */ - export function toRadian(a: number): number; -} - // vec2 -declare namespace vec2 { +export class vec2 extends Float32Array { + private typeVec2: number; + /** * Creates a new, empty vec2 * * @returns a new 2D vector */ - export function create(): GLM.IArray; + public static create(): vec2; /** * Creates a new vec2 initialized with values from an existing vector @@ -38,7 +20,7 @@ declare namespace vec2 { * @param a a vector to clone * @returns a new 2D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec2 | number[]): vec2; /** * Creates a new vec2 initialized with the given values @@ -47,7 +29,7 @@ declare namespace vec2 { * @param y Y component * @returns a new 2D vector */ - export function fromValues(x: number, y: number): GLM.IArray; + public static fromValues(x: number, y: number): vec2; /** * Copy the values from one vec2 to another @@ -56,7 +38,7 @@ declare namespace vec2 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec2, a: vec2 | number[]): vec2; /** * Set the components of a vec2 to the given values @@ -66,7 +48,7 @@ declare namespace vec2 { * @param y Y component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number): GLM.IArray; + public static set(out: vec2, x: number, y: number): vec2; /** * Adds two vec2's @@ -76,7 +58,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -86,7 +68,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Subtracts vector b from vector a @@ -96,7 +78,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static sub(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -106,7 +88,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Multiplies two vec2's @@ -116,7 +98,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -126,7 +108,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Divides two vec2's @@ -136,7 +118,25 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec2, a: vec2 | number[], b: vec2 | number[]): 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 | number[]): 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 | number[]): vec2; /** * Returns the minimum of two vec2's @@ -146,7 +146,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Returns the maximum of two vec2's @@ -156,7 +156,17 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec2, a: vec2 | number[], b: vec2 | number[]): 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 | number[]): vec2; + /** * Scales a vec2 by a scalar number @@ -166,7 +176,7 @@ declare namespace vec2 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec2, a: vec2 | number[], b: number): vec2; /** * Adds two vec2's after scaling the second operand by a scalar value @@ -177,7 +187,7 @@ declare namespace vec2 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec2, a: vec2 | number[], b: vec2 | number[], scale: number): vec2; /** * Calculates the euclidian distance between two vec2's @@ -186,7 +196,7 @@ declare namespace vec2 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the euclidian distance between two vec2's @@ -195,7 +205,7 @@ declare namespace vec2 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -204,7 +214,7 @@ declare namespace vec2 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the squared euclidian distance between two vec2's @@ -213,7 +223,7 @@ declare namespace vec2 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec2 | number[], b: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -221,7 +231,7 @@ declare namespace vec2 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec2 | number[]): number; /** * Calculates the length of a vec2 @@ -229,7 +239,7 @@ declare namespace vec2 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -237,7 +247,7 @@ declare namespace vec2 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec2 | number[]): number; /** * Calculates the squared length of a vec2 @@ -245,7 +255,7 @@ declare namespace vec2 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec2 | number[]): number; /** * Negates the components of a vec2 @@ -254,7 +264,7 @@ declare namespace vec2 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec2, a: vec2 | number[]): vec2; /** * Returns the inverse of the components of a vec2 @@ -263,7 +273,7 @@ declare namespace vec2 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec2, a: vec2 | number[]): vec2; /** * Normalize a vec2 @@ -272,7 +282,7 @@ declare namespace vec2 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec2, a: vec2 | number[]): vec2; /** * Calculates the dot product of two vec2's @@ -281,7 +291,7 @@ declare namespace vec2 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec2 | number[], b: vec2 | number[]): number; /** * Computes the cross product of two vec2's @@ -292,7 +302,7 @@ declare namespace vec2 { * @param b the second operand * @returns out */ - export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static cross(out: vec2, a: vec2 | number[], b: vec2 | number[]): vec2; /** * Performs a linear interpolation between two vec2's @@ -303,7 +313,7 @@ declare namespace vec2 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec2, a: vec2 | number[], b: vec2 | number[], t: number): vec2; /** * Generates a random unit vector @@ -311,7 +321,7 @@ declare namespace vec2 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec2): vec2; /** * Generates a random vector with the given scale @@ -320,7 +330,7 @@ declare namespace vec2 { * @param scale Length of the resulting vector. If ommitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; + public static random(out: vec2, scale: number): vec2; /** * Transforms the vec2 with a mat2 @@ -330,7 +340,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat2(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat2(out: vec2, a: vec2 | number[], m: mat2): vec2; /** * Transforms the vec2 with a mat2d @@ -340,7 +350,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat2d(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat2d(out: vec2, a: vec2 | number[], m: mat2d): vec2; /** * Transforms the vec2 with a mat3 @@ -351,7 +361,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat3(out: vec2, a: vec2 | number[], m: mat3): vec2; /** * Transforms the vec2 with a mat4 @@ -363,7 +373,7 @@ declare namespace vec2 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec2, a: vec2 | number[], m: mat4): vec2; /** * Perform some operation over an array of vec2s. @@ -376,8 +386,8 @@ declare namespace vec2 { * @param arg additional argument to pass to fn * @returns a */ - export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec2s. @@ -389,27 +399,46 @@ declare namespace vec2 { * @param fn Function to call for each vector in the array * @returns a */ - export function forEach(a: GLM.IArray, stride: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec2 | number[], b: vec2 | number[]) => void): Float32Array; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec2 | number[]): 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 | number[], b: vec2 | number[]): 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 | number[], b: vec2 | number[]): boolean; } // vec3 -declare namespace vec3 { +export class vec3 extends Float32Array { + private typeVec3: number; /** * Creates a new, empty vec3 * * @returns a new 3D vector */ - export function create(): GLM.IArray; + public static create(): vec3; /** * Creates a new vec3 initialized with values from an existing vector @@ -417,7 +446,7 @@ declare namespace vec3 { * @param a vector to clone * @returns a new 3D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec3 | number[]): vec3; /** * Creates a new vec3 initialized with the given values @@ -427,7 +456,7 @@ declare namespace vec3 { * @param z Z component * @returns a new 3D vector */ - export function fromValues(x: number, y: number, z: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number): vec3; /** * Copy the values from one vec3 to another @@ -436,7 +465,7 @@ declare namespace vec3 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec3, a: vec3 | number[]): vec3; /** * Set the components of a vec3 to the given values @@ -447,7 +476,7 @@ declare namespace vec3 { * @param z Z component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number, z: number): GLM.IArray; + public static set(out: vec3, x: number, y: number, z: number): vec3; /** * Adds two vec3's @@ -457,7 +486,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -467,7 +496,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Subtracts vector b from vector a @@ -477,7 +506,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray + public static sub(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3 /** * Multiplies two vec3's @@ -487,7 +516,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Multiplies two vec3's @@ -497,7 +526,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -507,7 +536,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Divides two vec3's @@ -517,7 +546,25 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec3, a: vec3 | number[], b: vec3 | number[]): 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 | number[]): 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 | number[]): vec3; /** * Returns the minimum of two vec3's @@ -527,7 +574,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Returns the maximum of two vec3's @@ -537,7 +584,16 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec3, a: vec3 | number[], b: vec3 | number[]): 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 | number[]): vec3 /** * Scales a vec3 by a scalar number @@ -547,7 +603,7 @@ declare namespace vec3 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec3, a: vec3 | number[], b: number): vec3; /** * Adds two vec3's after scaling the second operand by a scalar value @@ -558,7 +614,7 @@ declare namespace vec3 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec3, a: vec3 | number[], b: vec3 | number[], scale: number): vec3; /** * Calculates the euclidian distance between two vec3's @@ -567,7 +623,7 @@ declare namespace vec3 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the euclidian distance between two vec3's @@ -576,7 +632,7 @@ declare namespace vec3 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -585,7 +641,7 @@ declare namespace vec3 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the squared euclidian distance between two vec3's @@ -594,7 +650,7 @@ declare namespace vec3 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec3 | number[], b: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -602,7 +658,7 @@ declare namespace vec3 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec3 | number[]): number; /** * Calculates the length of a vec3 @@ -610,7 +666,7 @@ declare namespace vec3 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -618,7 +674,7 @@ declare namespace vec3 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec3 | number[]): number; /** * Calculates the squared length of a vec3 @@ -626,7 +682,7 @@ declare namespace vec3 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec3 | number[]): number; /** * Negates the components of a vec3 @@ -635,7 +691,7 @@ declare namespace vec3 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec3, a: vec3 | number[]): vec3; /** * Returns the inverse of the components of a vec3 @@ -644,7 +700,7 @@ declare namespace vec3 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec3, a: vec3 | number[]): vec3; /** * Normalize a vec3 @@ -653,7 +709,7 @@ declare namespace vec3 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec3, a: vec3 | number[]): vec3; /** * Calculates the dot product of two vec3's @@ -662,7 +718,7 @@ declare namespace vec3 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec3 | number[], b: vec3 | number[]): number; /** * Computes the cross product of two vec3's @@ -672,7 +728,7 @@ declare namespace vec3 { * @param b the second operand * @returns out */ - export function cross(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static cross(out: vec3, a: vec3 | number[], b: vec3 | number[]): vec3; /** * Performs a linear interpolation between two vec3's @@ -683,7 +739,33 @@ declare namespace vec3 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec3, a: vec3 | number[], b: vec3 | number[], 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 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], 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 | number[], b: vec3 | number[], c: vec3 | number[], d: vec3 | number[], t: number): vec3; /** * Generates a random unit vector @@ -691,46 +773,16 @@ declare namespace vec3 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + 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 ommitted, a unit vector will be returned + * @param [scale] Length of the resulting vector. If omitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; - - /** - * 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 - */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; - - /** - * 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 - */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; - - /** - * 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 - */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, c: number): GLM.IArray; + public static random(out: vec3, scale: number): vec3; /** * Transforms the vec3 with a mat3. @@ -740,7 +792,7 @@ declare namespace vec3 { * @param m the 3x3 matrix to transform with * @returns out */ - export function transformMat3(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat3(out: vec3, a: vec3 | number[], m: mat3): vec3; /** * Transforms the vec3 with a mat4. @@ -751,9 +803,9 @@ declare namespace vec3 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, m: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec3, a: vec3 | number[], m: mat4): vec3; - /** + /** * Transforms the vec3 with a quat * * @param out the receiving vector @@ -761,9 +813,39 @@ declare namespace vec3 { * @param q quaternion to transform with * @returns out */ - export function transformQuat(out: GLM.IArray, a: GLM.IArray, q: GLM.IArray): GLM.IArray; + public static transformQuat(out: vec3, a: vec3 | number[], 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 | number[], b: vec3 | number[], 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 | number[], b: vec3 | number[], 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 | number[], b: vec3 | number[], c: number): vec3; + /** * Perform some operation over an array of vec3s. * @@ -776,8 +858,8 @@ declare namespace vec3 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec3s. @@ -790,8 +872,8 @@ declare namespace vec3 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - fn: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec3 | number[], b: vec3 | number[]) => void): Float32Array; /** * Get the angle between two 3D vectors @@ -799,26 +881,45 @@ declare namespace vec3 { * @param b The second operand * @returns The angle in radians */ - export function angle(a: GLM.IArray, b: GLM.IArray): number; + public static angle(a: vec3 | number[], b: vec3 | number[]): number; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec3 | number[]): 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: vec3 | number[], b: vec3 | number[]): 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: vec3 | number[], b: vec3 | number[]): boolean } // vec4 -declare namespace vec4 { +export class vec4 extends Float32Array { + private typeVec3: number; /** * Creates a new, empty vec4 * * @returns a new 4D vector */ - export function create(): GLM.IArray; + public static create(): vec4; /** * Creates a new vec4 initialized with values from an existing vector @@ -826,7 +927,7 @@ declare namespace vec4 { * @param a vector to clone * @returns a new 4D vector */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: vec4 | number[]): vec4; /** * Creates a new vec4 initialized with the given values @@ -837,7 +938,7 @@ declare namespace vec4 { * @param w W component * @returns a new 4D vector */ - export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number, w: number): vec4; /** * Copy the values from one vec4 to another @@ -846,7 +947,7 @@ declare namespace vec4 { * @param a the source vector * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: vec4, a: vec4 | number[]): vec4; /** * Set the components of a vec4 to the given values @@ -858,7 +959,7 @@ declare namespace vec4 { * @param w W component * @returns out */ - export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + public static set(out: vec4, x: number, y: number, z: number, w: number): vec4; /** * Adds two vec4's @@ -868,7 +969,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -878,7 +979,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function subtract(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static subtract(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Subtracts vector b from vector a @@ -888,7 +989,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function sub(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static sub(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -898,7 +999,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Multiplies two vec4's @@ -908,7 +1009,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -918,7 +1019,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function divide(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static divide(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Divides two vec4's @@ -928,7 +1029,25 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function div(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static div(out: vec4, a: vec4 | number[], b: vec4 | number[]): 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 | number[]): 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 | number[]): vec4; /** * Returns the minimum of two vec4's @@ -938,7 +1057,7 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function min(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static min(out: vec4, a: vec4 | number[], b: vec4 | number[]): vec4; /** * Returns the maximum of two vec4's @@ -948,7 +1067,16 @@ declare namespace vec4 { * @param b the second operand * @returns out */ - export function max(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static max(out: vec4, a: vec4 | number[], b: vec4 | number[]): 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 | number[]): vec4; /** * Scales a vec4 by a scalar number @@ -958,7 +1086,7 @@ declare namespace vec4 { * @param b amount to scale the vector by * @returns out */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: vec4, a: vec4 | number[], b: number): vec4; /** * Adds two vec4's after scaling the second operand by a scalar value @@ -969,7 +1097,7 @@ declare namespace vec4 { * @param scale the amount to scale b by before adding * @returns out */ - export function scaleAndAdd(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, scale: number): GLM.IArray; + public static scaleAndAdd(out: vec4, a: vec4 | number[], b: vec4 | number[], scale: number): vec4; /** * Calculates the euclidian distance between two vec4's @@ -978,7 +1106,7 @@ declare namespace vec4 { * @param b the second operand * @returns distance between a and b */ - export function distance(a: GLM.IArray, b: GLM.IArray): number; + public static distance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the euclidian distance between two vec4's @@ -987,7 +1115,7 @@ declare namespace vec4 { * @param b the second operand * @returns distance between a and b */ - export function dist(a: GLM.IArray, b: GLM.IArray): number; + public static dist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -996,7 +1124,7 @@ declare namespace vec4 { * @param b the second operand * @returns squared distance between a and b */ - export function squaredDistance(a: GLM.IArray, b: GLM.IArray): number; + public static squaredDistance(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the squared euclidian distance between two vec4's @@ -1005,7 +1133,7 @@ declare namespace vec4 { * @param b the second operand * @returns squared distance between a and b */ - export function sqrDist(a: GLM.IArray, b: GLM.IArray): number; + public static sqrDist(a: vec4 | number[], b: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1013,7 +1141,7 @@ declare namespace vec4 { * @param a vector to calculate length of * @returns length of a */ - export function length(a: GLM.IArray): number; + public static length(a: vec4 | number[]): number; /** * Calculates the length of a vec4 @@ -1021,7 +1149,7 @@ declare namespace vec4 { * @param a vector to calculate length of * @returns length of a */ - export function len(a: GLM.IArray): number; + public static len(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1029,7 +1157,7 @@ declare namespace vec4 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: vec4 | number[]): number; /** * Calculates the squared length of a vec4 @@ -1037,7 +1165,7 @@ declare namespace vec4 { * @param a vector to calculate squared length of * @returns squared length of a */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: vec4 | number[]): number; /** * Negates the components of a vec4 @@ -1046,7 +1174,7 @@ declare namespace vec4 { * @param a vector to negate * @returns out */ - export function negate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static negate(out: vec4, a: vec4 | number[]): vec4; /** * Returns the inverse of the components of a vec4 @@ -1055,7 +1183,7 @@ declare namespace vec4 { * @param a vector to invert * @returns out */ - export function inverse(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static inverse(out: vec4, a: vec4 | number[]): vec4; /** * Normalize a vec4 @@ -1064,7 +1192,7 @@ declare namespace vec4 { * @param a vector to normalize * @returns out */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: vec4, a: vec4 | number[]): vec4; /** * Calculates the dot product of two vec4's @@ -1073,7 +1201,7 @@ declare namespace vec4 { * @param b the second operand * @returns dot product of a and b */ - export function dot(a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: vec4 | number[], b: vec4 | number[]): number; /** * Performs a linear interpolation between two vec4's @@ -1084,7 +1212,7 @@ declare namespace vec4 { * @param t interpolation amount between the two inputs * @returns out */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: vec4, a: vec4 | number[], b: vec4 | number[], t: number): vec4; /** * Generates a random unit vector @@ -1092,16 +1220,16 @@ declare namespace vec4 { * @param out the receiving vector * @returns out */ - export function random(out: GLM.IArray): GLM.IArray; + public static random(out: vec4): vec4; /** * Generates a random vector with the given scale * * @param out the receiving vector - * @param Length of the resulting vector. If ommitted, a unit vector will be returned + * @param scale length of the resulting vector. If ommitted, a unit vector will be returned * @returns out */ - export function random(out: GLM.IArray, scale: number): GLM.IArray; + public static random(out: vec4, scale: number): vec4; /** * Transforms the vec4 with a mat4. @@ -1111,7 +1239,7 @@ declare namespace vec4 { * @param m matrix to transform with * @returns out */ - export function transformMat4(out: GLM.IArray, a: GLM.IArray, mat: GLM.IArray): GLM.IArray; + public static transformMat4(out: vec4, a: vec4 | number[], m: mat4): vec4; /** * Transforms the vec4 with a quat @@ -1121,7 +1249,8 @@ declare namespace vec4 { * @param q quaternion to transform with * @returns out */ - export function transformQuat(out: GLM.IArray, a: GLM.IArray, quat: GLM.IArray): GLM.IArray; + + public static transformQuat(out: vec4, a: vec4 | number[], q: quat): vec4; /** * Perform some operation over an array of vec4s. @@ -1131,12 +1260,12 @@ declare namespace vec4 { * @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 additional argument to pass to fn + * @param arg additional argument to pass to fn * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - callback: (a: GLM.IArray, b: GLM.IArray, arg: any) => void, arg: any): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[], arg: any) => void, arg: any): Float32Array; /** * Perform some operation over an array of vec4s. @@ -1149,27 +1278,46 @@ declare namespace vec4 { * @returns a * @function */ - export function forEach(out: GLM.IArray, string: number, offset: number, count: number, - callback: (a: GLM.IArray, b: GLM.IArray) => void): GLM.IArray; + public static forEach(a: Float32Array, stride: number, offset: number, count: number, + fn: (a: vec4 | number[], b: vec4 | number[]) => void): Float32Array; /** * Returns a string representation of a vector * - * @param vec vector to represent as a string + * @param a vector to represent as a string * @returns string representation of the vector */ - export function str(a: GLM.IArray): string; + public static str(a: vec4 | number[]): 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 | number[], b: vec4 | number[]): 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 | number[], b: vec4 | number[]): boolean; } // mat2 -declare namespace mat2 { +export class mat2 extends Float32Array { + private typeMat2: number; /** * Creates a new identity mat2 * * @returns a new 2x2 matrix */ - export function create(): GLM.IArray; + public static create(): mat2; /** * Creates a new mat2 initialized with values from an existing matrix @@ -1177,7 +1325,7 @@ declare namespace mat2 { * @param a matrix to clone * @returns a new 2x2 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat2): mat2; /** * Copy the values from one mat2 to another @@ -1186,7 +1334,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat2, a: mat2): mat2; /** * Set a mat2 to the identity matrix @@ -1194,7 +1342,30 @@ declare namespace mat2 { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + 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 @@ -1203,7 +1374,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat2, a: mat2): mat2; /** * Inverts a mat2 @@ -1212,7 +1383,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat2, a: mat2): mat2; /** * Calculates the adjugate of a mat2 @@ -1221,7 +1392,7 @@ declare namespace mat2 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat2, a: mat2): mat2; /** * Calculates the determinant of a mat2 @@ -1229,7 +1400,7 @@ declare namespace mat2 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat2): number; /** * Multiplies two mat2's @@ -1239,7 +1410,7 @@ declare namespace mat2 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat2, a: mat2, b: mat2): mat2; /** * Multiplies two mat2's @@ -1249,7 +1420,7 @@ declare namespace mat2 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat2, a: mat2, b: mat2): mat2; /** * Rotates a mat2 by the given angle @@ -1259,7 +1430,7 @@ declare namespace mat2 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat2, a: mat2, rad: number): mat2; /** * Scales the mat2 by the dimensions in the given vec2 @@ -1269,7 +1440,33 @@ declare namespace mat2 { * @param v the vec2 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat2, a: mat2, v: vec2 | number[]): 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 | number[]): mat2; /** * Returns a string representation of a mat2 @@ -1277,7 +1474,7 @@ declare namespace mat2 { * @param a matrix to represent as a string * @returns string representation of the matrix */ - export function str(a: GLM.IArray): string; + public static str(a: mat2): string; /** * Returns Frobenius norm of a mat2 @@ -1285,7 +1482,7 @@ declare namespace mat2 { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - export function frob(a: GLM.IArray): number; + public static frob(a: mat2): number; /** * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix @@ -1294,18 +1491,91 @@ declare namespace mat2 { * @param U the upper triangular matrix * @param a the input matrix to factorize */ - export function LDU(L: GLM.IArray, D: GLM.IArray, U: GLM.IArray, a: GLM.IArray): GLM.IArray; + 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 -declare namespace mat2d { +export class mat2d extends Float32Array { + private typeMat2d: number; /** * Creates a new identity mat2d * * @returns a new 2x3 matrix */ - export function create(): GLM.IArray; + public static create(): mat2d; /** * Creates a new mat2d initialized with values from an existing matrix @@ -1313,7 +1583,7 @@ declare namespace mat2d { * @param a matrix to clone * @returns a new 2x3 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat2d): mat2d; /** * Copy the values from one mat2d to another @@ -1322,7 +1592,7 @@ declare namespace mat2d { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: mat2d, a: mat2d): mat2d; /** * Set a mat2d to the identity matrix @@ -1330,7 +1600,35 @@ declare namespace mat2d { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + 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 @@ -1339,7 +1637,7 @@ declare namespace mat2d { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat2d, a: mat2d): mat2d; /** * Calculates the determinant of a mat2d @@ -1347,7 +1645,7 @@ declare namespace mat2d { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat2d): number; /** * Multiplies two mat2d's @@ -1357,7 +1655,7 @@ declare namespace mat2d { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat2d, a: mat2d, b: mat2d): mat2d; /** * Multiplies two mat2d's @@ -1367,7 +1665,7 @@ declare namespace mat2d { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat2d, a: mat2d, b: mat2d): mat2d; /** * Rotates a mat2d by the given angle @@ -1377,7 +1675,7 @@ declare namespace mat2d { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotate(out: mat2d, a: mat2d, rad: number): mat2d; /** * Scales the mat2d by the dimensions in the given vec2 @@ -1387,7 +1685,7 @@ declare namespace mat2d { * @param v the vec2 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat2d, a: mat2d, v: vec2 | number[]): mat2d; /** * Translates the mat2d by the dimensions in the given vec2 @@ -1397,7 +1695,46 @@ declare namespace mat2d { * @param v the vec2 to translate the matrix by * @returns out **/ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat2d, a: mat2d, v: vec2 | number[]): 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 | number[]): 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 | number[]): mat2d /** * Returns a string representation of a mat2d @@ -1405,7 +1742,7 @@ declare namespace mat2d { * @param a matrix to represent as a string * @returns string representation of the matrix */ - export function str(a: GLM.IArray): string; + public static str(a: mat2d): string; /** * Returns Frobenius norm of a mat2d @@ -1413,18 +1750,97 @@ declare namespace mat2d { * @param a the matrix to calculate Frobenius norm of * @returns Frobenius norm */ - export function frob(a: GLM.IArray): number; + 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: number): 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 -declare namespace mat3 { +export class mat3 extends Float32Array { + private typeMat3: number; /** * Creates a new identity mat3 * * @returns a new 3x3 matrix */ - export function create(): GLM.IArray; + 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 @@ -1432,7 +1848,7 @@ declare namespace mat3 { * @param a matrix to clone * @returns a new 3x3 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat3): mat3; /** * Copy the values from one mat3 to another @@ -1441,7 +1857,41 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + 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: number, m01: number, m02: number, m10: number, m11: number, m12: number, m20: number, m21: number, m22: number): 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 @@ -1449,7 +1899,7 @@ declare namespace mat3 { * @param out the receiving matrix * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + public static identity(out: mat3): mat3; /** * Transpose the values of a mat3 @@ -1458,7 +1908,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat3, a: mat3): mat3; /** * Inverts a mat3 @@ -1467,7 +1917,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat3, a: mat3): mat3; /** * Calculates the adjugate of a mat3 @@ -1476,7 +1926,7 @@ declare namespace mat3 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat3, a: mat3): mat3; /** * Calculates the determinant of a mat3 @@ -1484,7 +1934,7 @@ declare namespace mat3 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat3): number; /** * Multiplies two mat3's @@ -1494,7 +1944,7 @@ declare namespace mat3 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat3, a: mat3, b: mat3): mat3; /** * Multiplies two mat3's @@ -1504,71 +1954,8 @@ declare namespace mat3 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat3, a: mat3, b: mat3): mat3; - /** - * Returns a string representation of a mat3 - * - * @param mat matrix to represent as a string - * @returns string representation of the matrix - */ - export function str(mat: GLM.IArray): string; - - /** - * Returns Frobenius norm of a mat3 - * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm - */ - export function frob(a: GLM.IArray): number; - - /** - * 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 - */ - export function normalFromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; - - /** - * Calculates a 3x3 matrix from the given quaternion - * - * @param out mat3 receiving operation result - * @param q Quaternion to create matrix from - * - * @returns out - */ - export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; - - /** - * Copies the upper-left 3x3 values into the given mat3. - * - * @param out the receiving 3x3 matrix - * @param a the source 4x4 matrix - * @returns out - */ - export function fromMat4(out: GLM.IArray, a: GLM.IArray): GLM.IArray; - - /** - * 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 - **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; - - /** - * Copies the values from a mat2d into a mat3 - * - * @param out the receiving matrix - * @param {mat2d} a the matrix to copy - * @returns out - **/ - export function fromMat2d(out: GLM.IArray, a: GLM.IArray): GLM.IArray; /** * Translate a mat3 by the given vector @@ -1578,7 +1965,7 @@ declare namespace mat3 { * @param v vector to translate by * @returns out */ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat3, a: mat3, v: vec3 | number[]): mat3; /** * Rotates a mat3 by the given angle @@ -1588,18 +1975,182 @@ declare namespace mat3 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + 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 | number[]): 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 | number[]): 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 | number[]): 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; + + /** + * 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: mat4): 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 -declare namespace mat4 { +export class mat4 extends Float32Array { + private typeMat4: number; /** * Creates a new identity mat4 * * @returns a new 4x4 matrix */ - export function create(): GLM.IArray; + public static create(): mat4; /** * Creates a new mat4 initialized with values from an existing matrix @@ -1607,7 +2158,7 @@ declare namespace mat4 { * @param a matrix to clone * @returns a new 4x4 matrix */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: mat4): mat4; /** * Copy the values from one mat4 to another @@ -1616,7 +2167,55 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + 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: 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 + * + * @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: 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 @@ -1624,7 +2223,7 @@ declare namespace mat4 { * @param out the receiving matrix * @returns out */ - export function identity(a: GLM.IArray): GLM.IArray; + public static identity(out: mat4): mat4; /** * Transpose the values of a mat4 @@ -1633,7 +2232,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function transpose(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static transpose(out: mat4, a: mat4): mat4; /** * Inverts a mat4 @@ -1642,7 +2241,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: mat4, a: mat4): mat4; /** * Calculates the adjugate of a mat4 @@ -1651,7 +2250,7 @@ declare namespace mat4 { * @param a the source matrix * @returns out */ - export function adjoint(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static adjoint(out: mat4, a: mat4): mat4; /** * Calculates the determinant of a mat4 @@ -1659,7 +2258,7 @@ declare namespace mat4 { * @param a the source matrix * @returns determinant of a */ - export function determinant(a: GLM.IArray): number; + public static determinant(a: mat4): number; /** * Multiplies two mat4's @@ -1669,7 +2268,7 @@ declare namespace mat4 { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: mat4, a: mat4, b: mat4): mat4; /** * Multiplies two mat4's @@ -1679,7 +2278,7 @@ declare namespace mat4 { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: mat4, a: mat4, b: mat4): mat4; /** * Translate a mat4 by the given vector @@ -1689,7 +2288,7 @@ declare namespace mat4 { * @param v vector to translate by * @returns out */ - export function translate(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static translate(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Scales the mat4 by the dimensions in the given vec3 @@ -1699,7 +2298,7 @@ declare namespace mat4 { * @param v the vec3 to scale the matrix by * @returns out **/ - export function scale(out: GLM.IArray, a: GLM.IArray, v: GLM.IArray): GLM.IArray; + public static scale(out: mat4, a: mat4, v: vec3 | number[]): mat4; /** * Rotates a mat4 by the given angle @@ -1710,7 +2309,7 @@ declare namespace mat4 { * @param axis the axis to rotate around * @returns out */ - export function rotate(out: GLM.IArray, a: GLM.IArray, rad: number, axis: GLM.IArray): GLM.IArray; + public static rotate(out: mat4, a: mat4, rad: number, axis: vec3 | number[]): mat4; /** * Rotates a matrix by the given angle around the X axis @@ -1720,7 +2319,7 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateX(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Y axis @@ -1730,7 +2329,7 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateY(out: mat4, a: mat4, rad: number): mat4; /** * Rotates a matrix by the given angle around the Z axis @@ -1740,78 +2339,87 @@ declare namespace mat4 { * @param rad the angle to rotate the matrix by * @returns out */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateZ(out: mat4, a: mat4, rad: number): mat4; /** - * Generates a frustum matrix with the given bounds + * Creates a matrix from a vector translation + * This is equivalent to (but much faster than): * - * @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 + * mat4.identity(dest); + * mat4.translate(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Translation vector + * @returns {mat4} out */ - export function frustum(out: GLM.IArray, left: number, right: number, - bottom: number, top: number, near: number, far: number): GLM.IArray; + public static fromTranslation(out: mat4, v: vec3 | number[]): mat4 /** - * Generates a perspective projection matrix with the given bounds + * Creates a matrix from a vector scaling + * This is equivalent to (but much faster than): * - * @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 + * mat4.identity(dest); + * mat4.scale(dest, dest, vec); + * + * @param {mat4} out mat4 receiving operation result + * @param {vec3} v Scaling vector + * @returns {mat4} out */ - export function perspective(out: GLM.IArray, fovy: number, aspect: number, - near: number, far: number): GLM.IArray; + public static fromScaling(out: mat4, v: vec3 | number[]): mat4 /** - * Generates a orthogonal projection matrix with the given bounds + * Creates a matrix from a given angle around a given axis + * This is equivalent to (but much faster than): * - * @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 + * 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 */ - export function ortho(out: GLM.IArray, left: number, right: number, - bottom: number, top: number, near: number, far: number): GLM.IArray; + public static fromRotation(out: mat4, rad: number, axis: vec3 | number[]): mat4 /** - * Generates a look-at matrix with the given eye position, focal point, and up axis + * Creates a matrix from the given angle around the X axis + * This is equivalent to (but much faster than): * - * @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 + * 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 */ - export function lookAt(out: GLM.IArray, eye: GLM.IArray, - center: GLM.IArray, up: GLM.IArray): GLM.IArray; + public static fromXRotation(out: mat4, rad: number): mat4 /** - * Returns a string representation of a mat4 + * Creates a matrix from the given angle around the Y axis + * This is equivalent to (but much faster than): * - * @param mat matrix to represent as a string - * @returns string representation of the matrix + * 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 */ - export function str(mat: GLM.IArray): string; + public static fromYRotation(out: mat4, rad: number): mat4 + /** - * Returns Frobenius norm of a mat4 + * Creates a matrix from the given angle around the Z axis + * This is equivalent to (but much faster than): * - * @param a the matrix to calculate Frobenius norm of - * @returns Frobenius norm + * 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 */ - export function frob(a: GLM.IArray): number; + public static fromZRotation(out: mat4, rad: number): mat4 /** * Creates a matrix from a quaternion rotation and vector translation @@ -1828,47 +2436,247 @@ declare namespace mat4 { * @param v Translation vector * @returns out */ - export function fromRotationTranslation(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray): GLM.IArray; - - /** - * 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 Scale vector - * @returns out - */ - export function fromRotationTranslationScale(out: GLM.IArray, q: GLM.IArray, v: GLM.IArray, s: GLM.IArray): GLM.IArray + public static fromRotationTranslation(out: mat4, q: quat, v: vec3 | number[]): mat4; /** - * Creates a matrix from a quaternion + * 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 */ - export function fromQuat(out: GLM.IArray, q: GLM.IArray): GLM.IArray; + public static fromRotationTranslationScale(out: mat4, q: quat, v: vec3 | number[], s: vec3 | number[]): 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 | number[], s: vec3 | number[], o: vec3 | number[]): 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: number, far: number): 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 | number[], center: vec3 | number[], up: vec3 | number[]): 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: number): 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 -declare namespace quat { +export class quat extends Float32Array { + private typeQuat: number; /** * Creates a new identity quat * * @returns a new quaternion */ - export function create(): GLM.IArray; + public static create(): quat; /** * Creates a new quat initialized with values from an existing quaternion @@ -1877,7 +2685,7 @@ declare namespace quat { * @returns a new quaternion * @function */ - export function clone(a: GLM.IArray): GLM.IArray; + public static clone(a: quat): quat; /** * Creates a new quat initialized with the given values @@ -1889,7 +2697,7 @@ declare namespace quat { * @returns a new quaternion * @function */ - export function fromValues(x: number, y: number, z: number, w: number): GLM.IArray; + public static fromValues(x: number, y: number, z: number, w: number): quat; /** * Copy the values from one quat to another @@ -1899,7 +2707,7 @@ declare namespace quat { * @returns out * @function */ - export function copy(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static copy(out: quat, a: quat): quat; /** * Set the components of a quat to the given values @@ -1912,7 +2720,7 @@ declare namespace quat { * @returns out * @function */ - export function set(out: GLM.IArray, x: number, y: number, z: number, w: number): GLM.IArray; + public static set(out: quat, x: number, y: number, z: number, w: number): quat; /** * Set a quat to the identity quaternion @@ -1920,7 +2728,34 @@ declare namespace quat { * @param out the receiving quaternion * @returns out */ - export function identity(out: GLM.IArray): GLM.IArray; + 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 | number[], b: vec3 | number[]): 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 | number[], right: vec3 | number[], up: vec3 | number[]): quat + + /** * Sets a quat from the given angle and rotation axis, @@ -1931,7 +2766,22 @@ declare namespace quat { * @param rad the angle in radians * @returns out **/ - export function setAxisAngle(out: GLM.IArray, axis: GLM.IArray, rad: number): GLM.IArray; + public static setAxisAngle(out: quat, axis: vec3 | number[], 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 | number[], q: quat): number /** * Adds two quat's @@ -1942,7 +2792,7 @@ declare namespace quat { * @returns out * @function */ - export function add(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static add(out: quat, a: quat, b: quat): quat; /** * Multiplies two quat's @@ -1952,7 +2802,7 @@ declare namespace quat { * @param b the second operand * @returns out */ - export function multiply(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static multiply(out: quat, a: quat, b: quat): quat; /** * Multiplies two quat's @@ -1962,7 +2812,7 @@ declare namespace quat { * @param b the second operand * @returns out */ - export function mul(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static mul(out: quat, a: quat, b: quat): quat; /** * Scales a quat by a scalar number @@ -1973,7 +2823,7 @@ declare namespace quat { * @returns out * @function */ - export function scale(out: GLM.IArray, a: GLM.IArray, b: number): GLM.IArray; + public static scale(out: quat, a: quat, b: number): quat; /** * Calculates the length of a quat @@ -1982,7 +2832,7 @@ declare namespace quat { * @returns length of a * @function */ - export function length(a: GLM.IArray): number; + public static length(a: quat): number; /** * Calculates the length of a quat @@ -1991,7 +2841,7 @@ declare namespace quat { * @returns length of a * @function */ - export function len(a: GLM.IArray): number; + public static len(a: quat): number; /** * Calculates the squared length of a quat @@ -2000,7 +2850,7 @@ declare namespace quat { * @returns squared length of a * @function */ - export function squaredLength(a: GLM.IArray): number; + public static squaredLength(a: quat): number; /** * Calculates the squared length of a quat @@ -2009,7 +2859,7 @@ declare namespace quat { * @returns squared length of a * @function */ - export function sqrLen(a: GLM.IArray): number; + public static sqrLen(a: quat): number; /** * Normalize a quat @@ -2019,7 +2869,7 @@ declare namespace quat { * @returns out * @function */ - export function normalize(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static normalize(out: quat, a: quat): quat; /** * Calculates the dot product of two quat's @@ -2029,7 +2879,7 @@ declare namespace quat { * @returns dot product of a and b * @function */ - export function dot(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): number; + public static dot(a: quat, b: quat): number; /** * Performs a linear interpolation between two quat's @@ -2041,7 +2891,7 @@ declare namespace quat { * @returns out * @function */ - export function lerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + public static lerp(out: quat, a: quat, b: quat, t: number): quat; /** * Performs a spherical linear interpolation between two quat @@ -2052,7 +2902,20 @@ declare namespace quat { * @param t interpolation amount between the two inputs * @returns out */ - export function slerp(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray, t: number): GLM.IArray; + 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 @@ -2061,7 +2924,7 @@ declare namespace quat { * @param a quat to calculate inverse of * @returns out */ - export function invert(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static invert(out: quat, a: quat): quat; /** * Calculates the conjugate of a quat @@ -2071,15 +2934,15 @@ declare namespace quat { * @param a quat to calculate conjugate of * @returns out */ - export function conjugate(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + public static conjugate(out: quat, a: quat): quat; /** - * Returns a string representation of a quatenion + * Returns a string representation of a quaternion * - * @param vec vector to represent as a string - * @returns string representation of the vector + * @param a quat to represent as a string + * @returns string representation of the quat */ - export function str(a: GLM.IArray): string; + public static str(a: quat): string; /** * Rotates a quaternion by the given angle about the X axis @@ -2089,7 +2952,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateX(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateX(out: quat, a: quat, rad: number): quat; /** * Rotates a quaternion by the given angle about the Y axis @@ -2099,7 +2962,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateY(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateY(out: quat, a: quat, rad: number): quat; /** * Rotates a quaternion by the given angle about the Z axis @@ -2109,7 +2972,7 @@ declare namespace quat { * @param rad angle (in radians) to rotate * @returns out */ - export function rotateZ(out: GLM.IArray, a: GLM.IArray, rad: number): GLM.IArray; + public static rotateZ(out: quat, a: quat, rad: number): quat; /** * Creates a quaternion from the given 3x3 rotation matrix. @@ -2122,20 +2985,20 @@ declare namespace quat { * @returns out * @function */ - export function fromMat3(out: GLM.IArray, m: GLM.IArray): GLM.IArray; + 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 */ - export function setAxes(out: GLM.IArray, view: GLM.IArray, right: GLM.IArray, - up: GLM.IArray): GLM.IArray; + public static setAxes(out: quat, view: vec3 | number[], right: vec3 | number[], up: vec3 | number[]): quat; /** * Sets a quaternion to represent the shortest rotation from one @@ -2148,7 +3011,7 @@ declare namespace quat { * @param b the destination vector * @returns out */ - export function rotationTo(out: GLM.IArray, a: GLM.IArray, b: GLM.IArray): GLM.IArray; + public static rotationTo(out: quat, a: vec3 | number[], b: vec3 | number[]): quat; /** * Calculates the W component of a quat from the X, Y, and Z components. @@ -2159,5 +3022,23 @@ declare namespace quat { * @param a quat to calculate W component of * @returns out */ - export function calculateW(out: GLM.IArray, a: GLM.IArray): GLM.IArray; + 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 6d9768b337310fa80e348ed5da12d0547f5a5a52 Mon Sep 17 00:00:00 2001 From: Stephen Feest Date: Wed, 17 Aug 2016 10:03:38 +0100 Subject: [PATCH 004/212] Add additional $transclude function parameters A couple of additional optional parameters were added to the `$transclude` function when support for multi-slot transclusion was added in Angular 1.5 [1]. This commit updates the `ITranscludeFunction` type definition to reflect those changes. [1] https://docs.angularjs.org/api/ng/service/$compile#-controller- --- angularjs/angular.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index 3c13fd6cf3..a6a130a66d 100644 --- a/angularjs/angular.d.ts +++ b/angularjs/angular.d.ts @@ -1258,7 +1258,7 @@ declare namespace angular { // This corresponds to $transclude (and also the transclude function passed to link). interface ITranscludeFunction { // If the scope is provided, then the cloneAttachFn must be as well. - (scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery; + (scope: IScope, cloneAttachFn: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery; // If one argument is provided, then it's assumed to be the cloneAttachFn. (cloneAttachFn?: ICloneAttachFunction): JQuery; } From ed50b4775d7d49a44d3d39d103aa4f50d3442174 Mon Sep 17 00:00:00 2001 From: Stephen Feest Date: Wed, 17 Aug 2016 21:35:36 +0100 Subject: [PATCH 005/212] Add $transclude function tests These tests try to exercise the different ways that the $transclude can be called including: + With and without specifying the scope explicitly + With and without a clone attach function + With and without specifying the future parent + Using the default and named transclude slots --- angularjs/angular-tests.ts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index ef3e29b4c8..07f67a7375 100644 --- a/angularjs/angular-tests.ts +++ b/angularjs/angular-tests.ts @@ -867,6 +867,26 @@ angular.module('docsTabsExample', []) }; }); +angular.module('multiSlotTranscludeExample', []) + .directive('dropDownMenu', function() { + return { + transclude: { + button: 'button', + list: 'ul', + }, + link: function(scope, element, attrs, ctrl, transclude) { + // without scope + transclude().appendTo(element); + transclude(clone => clone.appendTo(element)); + + // with scope + transclude(scope, clone => clone.appendTo(element)); + transclude(scope, clone => clone.appendTo(element), element, 'button'); + transclude(scope, null, element, 'list').addClass('drop-down-list').appendTo(element); + } + }; + }); + angular.module('componentExample', []) .component('counter', { require: {'ctrl': '^ctrl'}, From 7a7510a12d5b1c3c14f45313807c7c1e6092571e Mon Sep 17 00:00:00 2001 From: minodisk Date: Tue, 16 Aug 2016 20:09:18 +0900 Subject: [PATCH 006/212] Format react-router.d.ts --- react-router/react-router.d.ts | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 3fe2538048..41eb1b53ed 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -236,15 +236,15 @@ declare namespace ReactRouter { // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md interface InjectedRouter { - push: (pathOrLoc: H.LocationDescriptor) => void - replace: (pathOrLoc: H.LocationDescriptor) => void - go: (n: number) => void - goBack: () => void - goForward: () => void - setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void - createPath(path: H.Path, query?: H.Query): H.Path - createHref(path: H.Path, query?: H.Query): H.Href - isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean + push: (pathOrLoc: H.LocationDescriptor) => void + replace: (pathOrLoc: H.LocationDescriptor) => void + go: (n: number) => void + goBack: () => void + goForward: () => void + setRouteLeaveHook(route: PlainRoute, callback: RouteHook): void + createPath(path: H.Path, query?: H.Query): H.Path + createHref(path: H.Path, query?: H.Query): H.Href + isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean } function withRouter>(component: C): C @@ -359,7 +359,7 @@ declare module "react-router/lib/useRoutes" { declare module "react-router/lib/PatternUtils" { - export function formatPattern(pattern: string, params: {}): string; + export function formatPattern(pattern: string, params: {}): string; } @@ -419,16 +419,16 @@ declare module "react-router/lib/PropTypes" { } declare module "react-router/lib/browserHistory" { - export default ReactRouter.browserHistory; + export default ReactRouter.browserHistory; } declare module "react-router/lib/hashHistory" { - export default ReactRouter.hashHistory; + export default ReactRouter.hashHistory; } declare module "react-router/lib/match" { - export default ReactRouter.match + export default ReactRouter.match; } @@ -441,11 +441,11 @@ declare module "react-router/lib/useRouterHistory" { } declare module "react-router/lib/createMemoryHistory" { - export default ReactRouter.createMemoryHistory; + export default ReactRouter.createMemoryHistory; } declare module "react-router/lib/withRouter" { - export default ReactRouter.withRouter; + export default ReactRouter.withRouter; } declare module "react-router" { @@ -504,7 +504,7 @@ declare module "react-router" { export type LeaveHook = ReactRouter.LeaveHook export type ParseQueryString = ReactRouter.ParseQueryString export type RedirectFunction = ReactRouter.RedirectFunction - export type RouteComponentProps = ReactRouter.RouteComponentProps; + export type RouteComponentProps = ReactRouter.RouteComponentProps; export type RouteHook = ReactRouter.RouteHook export type StringifyQuery = ReactRouter.StringifyQuery export type RouterListener = ReactRouter.RouterListener From 35324f1700d0658e194785633f9bf95c9d8764e3 Mon Sep 17 00:00:00 2001 From: minodisk Date: Fri, 19 Aug 2016 09:45:19 +0900 Subject: [PATCH 007/212] Add applyRouterMiddleware to react-router --- react-router/react-router.d.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index 41eb1b53ed..6d5051f61b 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -88,6 +88,13 @@ declare namespace ReactRouter { function createMemoryHistory(options?: H.HistoryOptions): H.History + interface Middleware { + renderRouterContext: (previous: React.Props<{}>[], props: React.Props<{}>) => React.Props<{}>[] + renderRouteComponent: (previous: React.Props<{}>[], props: React.Props<{}>) => React.Props<{}>[] + } + + function applyRouterMiddleware(...middlewares: Middleware[]): (renderProps: React.Props<{}>) => React.Props<{}>[] + /* components */ interface RouterProps extends React.Props { @@ -97,6 +104,7 @@ declare namespace ReactRouter { onError?: (error: any) => any onUpdate?: () => any parseQueryString?: ParseQueryString + render?: (renderProps: React.Props<{}>) => React.Props<{}>[] stringifyQuery?: StringifyQuery } interface Router extends React.ComponentClass {} @@ -448,6 +456,10 @@ declare module "react-router/lib/withRouter" { export default ReactRouter.withRouter; } +declare module "react-router/lib/applyRouterMiddleware" { + export default ReactRouter.applyRouterMiddleware; +} + declare module "react-router" { import Router from "react-router/lib/Router" @@ -492,6 +504,8 @@ declare module "react-router" { import withRouter from "react-router/lib/withRouter"; + import applyRouterMiddleware from "react-router/lib/applyRouterMiddleware"; + // PlainRoute is defined in the API documented at: // https://github.com/rackt/react-router/blob/master/docs/API.md // but not included in any of the .../lib modules above. @@ -534,7 +548,8 @@ declare module "react-router" { match, useRouterHistory, createMemoryHistory, - withRouter + withRouter, + applyRouterMiddleware } export default Router From fedccb1e7ad7e2aad3fad61e7de6ef536a8967c5 Mon Sep 17 00:00:00 2001 From: Oliver Joseph Ash Date: Sat, 20 Aug 2016 10:31:54 +0100 Subject: [PATCH 008/212] RxJS DOM: ajax doesn't return Error, throws instead RxJS DOM does not return AjaxErrorResponse, it throws it. Observable errors are currently not modelled in the typings. --- rx-dom/rx-dom.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/rx-dom/rx-dom.d.ts b/rx-dom/rx-dom.d.ts index 5a42810600..e0d4369c60 100644 --- a/rx-dom/rx-dom.d.ts +++ b/rx-dom/rx-dom.d.ts @@ -110,13 +110,13 @@ declare module Rx.DOM { function touchstart(element: Element, selector?:Function, useCapture?:boolean):Rx.Observable; // Ajax - function ajax(url:string):Rx.Observable; - function ajax(settings:AjaxSettings):Rx.Observable; - function get(url:string):Rx.Observable; + function ajax(url:string):Rx.Observable; + function ajax(settings:AjaxSettings):Rx.Observable; + function get(url:string):Rx.Observable; function getJSON(url:string):Rx.Observable; - function post(url:string, body:any):Rx.Observable; + function post(url:string, body:any):Rx.Observable; function jsonpRequest(url:string):Rx.Observable; - function jsonpRequest(settings:JsonpSettings):Rx.Observable; + function jsonpRequest(settings:JsonpSettings):Rx.Observable; // Server-Sent Events function fromEventSource(url:string, openObservable?:Rx.Observer):Rx.Observable; @@ -139,4 +139,4 @@ declare module Rx.DOM { declare module "rx.DOM" { export default Rx.DOM; -} \ No newline at end of file +} From e9fc032fe8a9cf754f2c9b06ab855bfbf837d4e6 Mon Sep 17 00:00:00 2001 From: Massimo Hamilton Date: Tue, 23 Aug 2016 08:52:49 +0100 Subject: [PATCH 009/212] Durandal - Fixes to DialogContext. See below: - Add blockoutOpacity to DialogContext - Mark name of getContext as optional All as per docs here: http://durandaljs.com/documentation/Showing-Message-Boxes-And-Modals.html#dialog-contexts --- durandal/durandal.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/durandal/durandal.d.ts b/durandal/durandal.d.ts index 97e1307a0b..1b28ca7bc3 100644 --- a/durandal/durandal.d.ts +++ b/durandal/durandal.d.ts @@ -690,6 +690,11 @@ declare module 'plugins/dialog' { * @param {object} context The composition context. */ compositionComplete(child: HTMLElement, parent: HTMLElement, context: composition.CompositionContext): void; + + /** + * Opacity of the blockout. The default is 0.6. + */ + blockoutOpacity?: number; } interface Dialog { @@ -728,7 +733,7 @@ declare module 'plugins/dialog' { * @param {string} [name] The name of the context to retrieve. * @returns {DialogContext} True context. */ - export function getContext(name: string): DialogContext; + export function getContext(name?: string): DialogContext; /** * Adds (or replaces) a dialog context. From 103788b39d55dcf3f78705f8acbef789159edd38 Mon Sep 17 00:00:00 2001 From: Ville Saarinen Date: Wed, 24 Aug 2016 13:08:40 +0300 Subject: [PATCH 010/212] Add support for passing in undefined or null This is needed if strictNullChecks are enabled --- classnames/classnames-tests.ts | 8 +++++--- classnames/index.d.ts | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/classnames/classnames-tests.ts b/classnames/classnames-tests.ts index e296001ed8..5c99df82eb 100644 --- a/classnames/classnames-tests.ts +++ b/classnames/classnames-tests.ts @@ -17,6 +17,8 @@ classNames([{ foo: true, bar: false }, { baz: true }]); // => 'foo baz' classNames(["foo", ["bar", {baz: true}]]); // => 'foo bar baz' -// other falsy values are just ignored -// NOTE: We don't really want to allow this kind of thing with Typescript (otherwise what's the point!) -//classNames(null, false, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1' \ No newline at end of file +// falsey values are just ignored +classNames(null, 'bar', undefined, 0, 1, { baz: null }, ''); // => 'bar 1' + +// Supporting booleans is tricky since we should only support passing in false, which is ignored +//classNames(false, 'bar', 0, 1, { baz: null }, ''); // => 'bar 1' diff --git a/classnames/index.d.ts b/classnames/index.d.ts index f9993f3c11..e6b645c5b0 100644 --- a/classnames/index.d.ts +++ b/classnames/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Dave Keen , Adi Dahiya , Jason Killian // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare type ClassValue = string | number | ClassDictionary | ClassArray; +declare type ClassValue = string | number | ClassDictionary | ClassArray | undefined | null; interface ClassDictionary { [id: string]: boolean; From ab65bec50eba26e1f3039e44a5007dbb52b117da Mon Sep 17 00:00:00 2001 From: Daniele Frasca Date: Thu, 25 Aug 2016 10:13:39 +0100 Subject: [PATCH 011/212] added AutoScaling --- aws-sdk/aws-sdk.d.ts | 452 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 452 insertions(+) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index cb35f34e97..652365e156 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -49,6 +49,51 @@ declare module "aws-sdk" { stack: string; } + export interface RetryDelayOption { + base?: number; + customBackoff?: (retryCount: number) => number; + } + + export interface Ebs { + snapshotId?: string; + volumeSize?: number; + volumeType?: string; + deleteOnTermination?: boolean; + iops?: number; + encrypted?: boolean; + } + + export interface BlockDeviceMapping { + virtualName?: string; + deviceName: string; + ebs?: Ebs; + noDevice?: boolean; + } + + export interface InstanceMonitoring { + spotPrice?: string; + enabled?: boolean; + } + + export interface Filter { + Name?: string; + Values?: boolean; + } + + export interface StepAdjustment { + scalingAdjustment: number; + metricIntervalLowerBound?: number; + metricIntervalUpperBound?: number; + } + + export interface Tags { + resourceId?: string; + resourceType?: string; + key: string; + value?: string; + propagateAtLaunch?: boolean; + } + export interface Services { autoscaling?: any; cloudformation?: any; @@ -147,6 +192,64 @@ declare module "aws-sdk" { updateFunctionConfiguration(params: Lambda.UpdateFunctionConfigurationParams, callback: (err: AwsError, data: any) => void): void; } + export class AutoScaling { + constructor(options?: any); + endpoint: Endpoint; + + attachInstances(params: AutoScaling.AttachInstancesParams, callback: (err: AwsError, data: any) => void): void; + attachLoadBalancers(params: AutoScaling.AttachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + attachLoadBalancerTargetGroups(param: AutoScaling.AttachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + completeLifecycleAction(param: AutoScaling.CompleteLifecycleActionParams, callback: (err: AwsError, data: any) => void): void; + createAutoScalingGroup(param: AutoScaling.CreateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + createLaunchConfiguration(param: AutoScaling.CreateLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void; + createOrUpdateTags(param: AutoScaling.CreateOrUpdateTagsParams, callback: (err: AwsError, data: any) => void): void; + deleteAutoScalingGroup(param: AutoScaling.DeleteAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + deleteLaunchConfiguration(param: AutoScaling.DeleteLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void; + deleteLifecycleHook(param: AutoScaling.DeleteLifecycleHookParams, callback: (err: AwsError, data: any) => void): void; + deleteNotificationConfiguration(param: AutoScaling.DeleteNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void; + deletePolicy(param: AutoScaling.DeletePolicyParams, callback: (err: AwsError, data: any) => void): void; + deleteScheduledAction(param: AutoScaling.DeleteScheduledActionParams, callback: (err: AwsError, data: any) => void): void; + deleteTags(param: AutoScaling.DeleteTagsParams, callback: (err: AwsError, data: any) => void): void; + describeAccountLimits(callback: (err: AwsError, data: any) => void): void; + describeAdjustmentTypes(callback: (err: AwsError, data: any) => void): void; + describeAutoScalingGroups(param: AutoScaling.DescribeAutoScalingGroupsParams, callback: (err: AwsError, data: any) => void): void; + describeAutoScalingInstances(param: AutoScaling.DescribeAutoScalingInstancesParams, callback: (err: AwsError, data: any) => void): void; + describeAutoScalingNotificationTypes(callback: (err: AwsError, data: any) => void): void; + describeLaunchConfigurations(param: AutoScaling.DescribeLaunchConfigurationsParams, callback: (err: AwsError, data: any) => void): void; + describeLifecycleHooks(param: AutoScaling.DescribeLifecycleHooksParams, callback: (err: AwsError, data: any) => void): void; + describeLifecycleHookTypes(callback: (err: AwsError, data: any) => void): void; + describeLoadBalancers(param: AutoScaling.DescribeLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + describeLoadBalancerTargetGroups(param: AutoScaling.DescribeLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + describeMetricCollectionTypes(callback: (err: AwsError, data: any) => void): void; + describeNotificationConfigurations(param: AutoScaling.DescribeNotificationConfigurationsParams, callback: (err: AwsError, data: any) => void): void; + describePolicies(param: AutoScaling.DescribePoliciesParams, callback: (err: AwsError, data: any) => void): void; + describeScalingActivities(param: AutoScaling.DescribeScalingActivitiesParams, callback: (err: AwsError, data: any) => void): void; + describeScalingProcessTypes(callback: (err: AwsError, data: any) => void): void; + describeScheduledActions(param: AutoScaling.DescribeScheduledActionsParams, callback: (err: AwsError, data: any) => void): void; + describeTags(param: AutoScaling.DescribeTagsParams, callback: (err: AwsError, data: any) => void): void; + describeTerminationPolicyTypes(callback: (err: AwsError, data: any) => void): void; + detachInstances(param: AutoScaling.DetachInstancesParams, callback: (err: AwsError, data: any) => void): void; + detachLoadBalancers(param: AutoScaling.DetachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void; + detachLoadBalancerTargetGroups(param: AutoScaling.DetachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void; + disableMetricsCollection(param: AutoScaling.DisableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void; + enableMetricsCollection(param: AutoScaling.EnableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void; + enterStandby(param: AutoScaling.EnterStandbyParams, callback: (err: AwsError, data: any) => void): void; + executePolicy(param: AutoScaling.ExecutePolicyParams, callback: (err: AwsError, data: any) => void): void; + exitStandby(param: AutoScaling.ExitStandbyParams, callback: (err: AwsError, data: any) => void): void; + putLifecycleHook(param: AutoScaling.PutLifecycleHookParams, callback: (err: AwsError, data: any) => void): void; + putNotificationConfiguration(param: AutoScaling.PutNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void; + putScalingPolicy(param: AutoScaling.PutScalingPolicyParams, callback: (err: AwsError, data: any) => void): void; + putScheduledUpdateGroupAction(param: AutoScaling.PutScheduledUpdateGroupActionParams, callback: (err: AwsError, data: any) => void): void; + recordLifecycleActionHeartbeat(params: AutoScaling.RecordLifecycleActionHeartbeatParams, callback: (err: AwsError, data: any) => void): void; + resumeProcesses(params: AutoScaling.ResumeProcessesParams, callback: (err: AwsError, data: any) => void): void; + setDesiredCapacity(params: AutoScaling.SetDesiredCapacityParams, callback: (err: AwsError, data: any) => void): void; + setInstanceHealth(params: AutoScaling.SetInstanceHealthParams, callback: (err: AwsError, data: any) => void): void; + setInstanceProtection(params: AutoScaling.SetInstanceProtectionParams, callback: (err: AwsError, data: any) => void): void; + suspendProcesses(params: AutoScaling.SuspendProcessesParams, callback: (err: AwsError, data: any) => void): void; + terminateInstanceInAutoScalingGroup(params: AutoScaling.TerminateInstanceInAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + updateAutoScalingGroup(params: AutoScaling.UpdateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void; + } + export class SQS { constructor(options?: any); endpoint: Endpoint; @@ -592,6 +695,355 @@ declare module "aws-sdk" { } } + export module AutoScaling { + export interface AutoScalingOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + s3DisableBodySigning?: boolean; + retryDelayOptions?: RetryDelayOption; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; + } + + export interface AttachInstancesParams { + autoScalingGroupName: string; + instanceIds: string[]; + } + + export interface AttachLoadBalancersParams { + autoScalingGroupName: string; + loadBalancerNames: string[]; + } + + export interface AttachLoadBalancerTargetGroupsParams { + autoScalingGroupName: string; + targetGroupARNs: string[]; + } + + export interface CompleteLifecycleActionParams { + autoScalingGroupName: string; + lifecycleActionResult: string; + lifecycleHookName: string; + lifecycleActionToken?: string; + instanceId?: string; + } + + export interface CreateAutoScalingGroupParams { + autoScalingGroupName: string; + minSize: number; + maxSize: number; + launchConfigurationName?: string; + instanceId?: string; + desiredCapacity?: number; + defaultCooldown?: number; + availabilityZones?: string[]; + loadBalancerNames?: string[]; + targetGroupARNs?: string[]; + healthCheckType?: string; + healthCheckGracePeriod?: number; + placementGroup?: string; + vPCZoneIdentifier?: string; + terminationPolicies?: string; + newInstancesProtectedFromScaleIn?: boolean; + tags?: Tags; + } + + export interface CreateLaunchConfigurationParams { + launchConfigurationName: string; + associatePublicIpAddress?: boolean; + imageId?: string; + keyName?: string; + securityGroups?: string[]; + classicLinkVPCId?: string; + classicLinkVPCSecurityGroups?: string[]; + userData?: string; + instanceId?: string; + instanceType?: string; + kernelId?: string; + ramdiskId?: string; + blockDeviceMappings?: BlockDeviceMapping[]; + instanceMonitoring?: InstanceMonitoring; + spotPrice?: string; + iamInstanceProfile?: string; + ebsOptimized?: boolean; + placementTenancy?: string; + } + + export interface CreateOrUpdateTagsParams { + tags: Tags[]; + } + + export interface DeleteAutoScalingGroupParams { + autoScalingGroupName: string; + forceDelete?: boolean; + } + + export interface DeleteLaunchConfigurationParams { + launchConfigurationName: string; + } + + export interface DeleteLifecycleHookParams { + autoScalingGroupName: string; + lifecycleHookName: string; + } + + export interface DeleteNotificationConfigurationParams { + autoScalingGroupName: string; + topicARN: string; + } + + export interface DeletePolicyParams { + policyName: string; + autoScalingGroupName?: string; + } + + export interface DeleteScheduledActionParams { + autoScalingGroupName: string; + scheduledActionName: string; + } + + export interface DeleteTagsParams { + tags: Tags[]; + } + + export interface DescribeAutoScalingGroupsParams { + autoScalingGroupName?: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeAutoScalingInstancesParams { + instanceIds?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeLaunchConfigurationsParams { + launchConfigurationNames?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeLifecycleHooksParams { + autoScalingGroupName: string; + lifecycleHookNames?: string[]; + } + + export interface DescribeLoadBalancersParams { + autoScalingGroupName: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeLoadBalancerTargetGroupsParams { + autoScalingGroupName: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeNotificationConfigurationsParams { + autoScalingGroupName?: string; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribePoliciesParams { + autoScalingGroupName?: string; + policyNames?: string[]; + policyTypes?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeScalingActivitiesParams { + autoScalingGroupName?: string; + activityIds?: string[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeScheduledActionsParams { + autoScalingGroupName?: string; + scheduledActionNames?: string[]; + startTime?: Date; + endTime?: Date; + nextToken?: string; + maxRecords?: number; + } + + export interface DescribeTagsParams { + filters?: Filter[]; + nextToken?: string; + maxRecords?: number; + } + + export interface DetachInstancesParams { + autoScalingGroupName: string; + shouldDecrementDesiredCapacity: boolean; + instanceIds?: string[]; + } + + export interface DetachLoadBalancersParams { + autoScalingGroupName: string; + loadBalancerNames: string; + } + + export interface DetachLoadBalancerTargetGroupsParams { + autoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface DisableMetricsCollectionParams { + autoScalingGroupName: string; + metrics?: string[]; + } + + export interface EnableMetricsCollectionParams { + autoScalingGroupName: string; + granularity: string; + metrics?: string[]; + } + + export interface EnterStandbyParams { + autoScalingGroupName: string; + shouldDecrementDesiredCapacity: boolean; + instanceIds?: string[]; + } + + export interface ExecutePolicyParams { + policyName: string; + autoScalingGroupName?: string; + honorCooldown?: boolean; + metricValue?: number; + breachThreshold?: number; + } + + export interface ExitStandbyParams { + autoScalingGroupName: string; + instanceIds?: string[]; + } + + export interface PutLifecycleHookParams { + autoScalingGroupName: string; + lifecycleHookName: string; + lifecycleTransition?: string; + roleARN?: string; + notificationTargetARN?: string; + notificationMetadata?: string; + heartbeatTimeout?: number; + defaultResult?: string; + } + + export interface PutNotificationConfigurationParams { + autoScalingGroupName: string; + notificationTypes: string[]; + topicARN: string; + } + + export interface PutScalingPolicyParams { + autoScalingGroupName: string; + adjustmentType: string; + policyName: string; + policyType?: string; + minAdjustmentStep?: number; + minAdjustmentMagnitude?: number; + scalingAdjustment?: number; + cooldown?: number; + metricAggregationType?: string; + stepAdjustments?: StepAdjustment[]; + estimatedInstanceWarmup: number; + } + + export interface PutScheduledUpdateGroupActionParams { + autoScalingGroupName: string; + scheduledActionName: string; + time?: Date; + startTime?: Date; + endTime?: Date; + recurrence?: string; + minSize?: number; + maxSize?: number; + desiredCapacity?: number; + } + + export interface RecordLifecycleActionHeartbeatParams { + autoScalingGroupName: string; + lifecycleHookName: string; + LifecycleActionToken?: string; + InstanceId?: string; + } + + export interface ResumeProcessesParams { + autoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface SetDesiredCapacityParams { + autoScalingGroupName: string; + desiredCapacity: number; + honorCooldown?: boolean; + } + + export interface SetInstanceHealthParams { + healthStatus: string; + instanceId: string; + shouldRespectGracePeriod?: boolean; + } + + export interface SetInstanceProtectionParams { + autoScalingGroupName: string; + instanceIds: string[]; + protectedFromScaleIn: boolean; + } + + export interface SuspendProcessesParams { + autoScalingGroupName: string; + scalingProcesses?: string[]; + } + + export interface TerminateInstanceInAutoScalingGroupParams { + instanceId: string; + shouldDecrementDesiredCapacity: boolean; + } + + export interface UpdateAutoScalingGroupParams { + autoScalingGroupName: string; + launchConfigurationName: string; + minSize: number; + maxSize: number; + desiredCapacity: number; + defaultCooldown: number; + availabilityZones: string[]; + healthCheckType: string; + healthCheckGracePeriod: number; + placementGroup: string; + vPCZoneIdentifier: string; + terminationPolicies: string[]; + newInstancesProtectedFromScaleIn?: boolean; + } + } + + export module SQS { export interface SqsOptions { From 6d4653c7c4029d286eff04cd98c883e5adea220d Mon Sep 17 00:00:00 2001 From: Jason Killian Date: Thu, 25 Aug 2016 14:09:15 -0400 Subject: [PATCH 012/212] fuzzaldrin-plus typings --- fuzzaldrin-plus/fuzzaldrin-plus-tests.ts | 20 ++++++++++++++++ fuzzaldrin-plus/index.d.ts | 29 ++++++++++++++++++++++++ fuzzaldrin-plus/tsconfig.json | 19 ++++++++++++++++ 3 files changed, 68 insertions(+) create mode 100644 fuzzaldrin-plus/fuzzaldrin-plus-tests.ts create mode 100644 fuzzaldrin-plus/index.d.ts create mode 100644 fuzzaldrin-plus/tsconfig.json diff --git a/fuzzaldrin-plus/fuzzaldrin-plus-tests.ts b/fuzzaldrin-plus/fuzzaldrin-plus-tests.ts new file mode 100644 index 0000000000..97730fe2e5 --- /dev/null +++ b/fuzzaldrin-plus/fuzzaldrin-plus-tests.ts @@ -0,0 +1,20 @@ +import * as fz from "fuzzaldrin-plus"; + +const candidates = [ + 'Find And Replace: Select All', + 'Settings View: Uninstall Packages', + 'Settings View: View Installed Themes', + 'Application: Install Update', + 'Install' +] +const objectCandidates = candidates.map(s => ({ foo: s })); + +fz.filter(candidates, 'install'); +fz.filter(objectCandidates, 'install', { key: 'foo' }); + +const prepQuery = fz.prepQuery('install'); +fz.score('Application: Install Update', 'install'); +fz.score('Application: Install Update', 'install', prepQuery); + +fz.match('Application: Install Update', 'install'); +fz.match('Application: Install Update', 'install', prepQuery); diff --git a/fuzzaldrin-plus/index.d.ts b/fuzzaldrin-plus/index.d.ts new file mode 100644 index 0000000000..34d6949ace --- /dev/null +++ b/fuzzaldrin-plus/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for fuzzaldrin-plus +// Project: https://github.com/jeancroy/fuzzaldrin-plus/ +// Definitions by: Jean Christophe Roy , Jason Killian +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export as namespace fuzzaldrin; + +export interface IQueryOptions { + pathSeparator?: string; + optCharRegEx?: RegExp; +} + +export interface IScoringOptions extends IQueryOptions { + allowErrors?: boolean; + isPath?: boolean; + useExtensionBonus?: boolean; +} + +export interface IFilterOptions extends IScoringOptions { + key?: string; + maxResults?: number; +} + +export type PreparedQuery = { __internalAPIBrand: string; }; + +export function filter(data: T[], query: string, options?: IFilterOptions): T[]; +export function score(str: string, query: string, preparedQuery?: PreparedQuery, options?: IScoringOptions): number; +export function match(str: string, query: string, preparedQuery?: PreparedQuery, options?: IScoringOptions): number[]; +export function prepQuery(query: string, options?: IQueryOptions): PreparedQuery; diff --git a/fuzzaldrin-plus/tsconfig.json b/fuzzaldrin-plus/tsconfig.json new file mode 100644 index 0000000000..ce458c2f00 --- /dev/null +++ b/fuzzaldrin-plus/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fuzzaldrin-plus-tests.ts" + ] +} From aa7fb007db039fb20f2db6cf104d1c8c27e59ae7 Mon Sep 17 00:00:00 2001 From: Daniele Frasca Date: Fri, 26 Aug 2016 16:27:49 +0100 Subject: [PATCH 013/212] fixed the property name with upper case letter --- aws-sdk/aws-sdk.d.ts | 354 +++++++++++++++++++++---------------------- 1 file changed, 177 insertions(+), 177 deletions(-) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 652365e156..6f5ced6cd3 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -726,320 +726,320 @@ declare module "aws-sdk" { } export interface AttachInstancesParams { - autoScalingGroupName: string; - instanceIds: string[]; + AutoScalingGroupName: string; + InstanceIds: string[]; } export interface AttachLoadBalancersParams { - autoScalingGroupName: string; - loadBalancerNames: string[]; + AutoScalingGroupName: string; + LoadBalancerNames: string[]; } export interface AttachLoadBalancerTargetGroupsParams { - autoScalingGroupName: string; - targetGroupARNs: string[]; + AutoScalingGroupName: string; + TargetGroupARNs: string[]; } export interface CompleteLifecycleActionParams { - autoScalingGroupName: string; - lifecycleActionResult: string; - lifecycleHookName: string; + AutoScalingGroupName: string; + LifecycleActionResult: string; + LifecycleHookName: string; lifecycleActionToken?: string; - instanceId?: string; + InstanceId?: string; } export interface CreateAutoScalingGroupParams { - autoScalingGroupName: string; - minSize: number; - maxSize: number; - launchConfigurationName?: string; - instanceId?: string; - desiredCapacity?: number; - defaultCooldown?: number; - availabilityZones?: string[]; - loadBalancerNames?: string[]; - targetGroupARNs?: string[]; - healthCheckType?: string; - healthCheckGracePeriod?: number; - placementGroup?: string; - vPCZoneIdentifier?: string; - terminationPolicies?: string; - newInstancesProtectedFromScaleIn?: boolean; - tags?: Tags; + AutoScalingGroupName: string; + MinSize: number; + MaxSize: number; + LaunchConfigurationName?: string; + InstanceId?: string; + DesiredCapacity?: number; + DefaultCooldown?: number; + AvailabilityZones?: string[]; + LoadBalancerNames?: string[]; + TargetGroupARNs?: string[]; + HealthCheckType?: string; + HealthCheckGracePeriod?: number; + PlacementGroup?: string; + VPCZoneIdentifier?: string; + TerminationPolicies?: string; + NewInstancesProtectedFromScaleIn?: boolean; + Tags?: Tags; } export interface CreateLaunchConfigurationParams { - launchConfigurationName: string; - associatePublicIpAddress?: boolean; - imageId?: string; - keyName?: string; - securityGroups?: string[]; - classicLinkVPCId?: string; - classicLinkVPCSecurityGroups?: string[]; - userData?: string; - instanceId?: string; - instanceType?: string; - kernelId?: string; - ramdiskId?: string; - blockDeviceMappings?: BlockDeviceMapping[]; - instanceMonitoring?: InstanceMonitoring; - spotPrice?: string; - iamInstanceProfile?: string; - ebsOptimized?: boolean; - placementTenancy?: string; + LaunchConfigurationName: string; + AssociatePublicIpAddress?: boolean; + ImageId?: string; + KeyName?: string; + SecurityGroups?: string[]; + ClassicLinkVPCId?: string; + ClassicLinkVPCSecurityGroups?: string[]; + UserData?: string; + InstanceId?: string; + InstanceType?: string; + KernelId?: string; + RamdiskId?: string; + BlockDeviceMappings?: BlockDeviceMapping[]; + InstanceMonitoring?: InstanceMonitoring; + SpotPrice?: string; + IamInstanceProfile?: string; + EbsOptimized?: boolean; + PlacementTenancy?: string; } export interface CreateOrUpdateTagsParams { - tags: Tags[]; + Tags: Tags[]; } export interface DeleteAutoScalingGroupParams { - autoScalingGroupName: string; - forceDelete?: boolean; + AutoScalingGroupName: string; + ForceDelete?: boolean; } export interface DeleteLaunchConfigurationParams { - launchConfigurationName: string; + LaunchConfigurationName: string; } export interface DeleteLifecycleHookParams { - autoScalingGroupName: string; - lifecycleHookName: string; + AutoScalingGroupName: string; + LifecycleHookName: string; } export interface DeleteNotificationConfigurationParams { - autoScalingGroupName: string; - topicARN: string; + AutoScalingGroupName: string; + TopicARN: string; } export interface DeletePolicyParams { - policyName: string; - autoScalingGroupName?: string; + PolicyName: string; + AutoScalingGroupName?: string; } export interface DeleteScheduledActionParams { - autoScalingGroupName: string; - scheduledActionName: string; + AutoScalingGroupName: string; + ScheduledActionName: string; } export interface DeleteTagsParams { - tags: Tags[]; + Tags: Tags[]; } export interface DescribeAutoScalingGroupsParams { - autoScalingGroupName?: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribeAutoScalingInstancesParams { - instanceIds?: string[]; - nextToken?: string; - maxRecords?: number; + InstanceIds?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeLaunchConfigurationsParams { - launchConfigurationNames?: string[]; - nextToken?: string; - maxRecords?: number; + LaunchConfigurationNames?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeLifecycleHooksParams { - autoScalingGroupName: string; - lifecycleHookNames?: string[]; + AutoScalingGroupName: string; + LifecycleHookNames?: string[]; } export interface DescribeLoadBalancersParams { - autoScalingGroupName: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribeLoadBalancerTargetGroupsParams { - autoScalingGroupName: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribeNotificationConfigurationsParams { - autoScalingGroupName?: string; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; } export interface DescribePoliciesParams { - autoScalingGroupName?: string; - policyNames?: string[]; - policyTypes?: string[]; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + PolicyNames?: string[]; + PolicyTypes?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeScalingActivitiesParams { - autoScalingGroupName?: string; - activityIds?: string[]; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + ActivityIds?: string[]; + NextToken?: string; + MaxRecords?: number; } export interface DescribeScheduledActionsParams { - autoScalingGroupName?: string; - scheduledActionNames?: string[]; - startTime?: Date; - endTime?: Date; - nextToken?: string; - maxRecords?: number; + AutoScalingGroupName?: string; + ScheduledActionNames?: string[]; + StartTime?: Date; + EndTime?: Date; + NextToken?: string; + MaxRecords?: number; } export interface DescribeTagsParams { - filters?: Filter[]; - nextToken?: string; - maxRecords?: number; + Filters?: Filter[]; + NextToken?: string; + MaxRecords?: number; } export interface DetachInstancesParams { - autoScalingGroupName: string; - shouldDecrementDesiredCapacity: boolean; - instanceIds?: string[]; + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; } export interface DetachLoadBalancersParams { - autoScalingGroupName: string; - loadBalancerNames: string; + AutoScalingGroupName: string; + LoadBalancerNames: string; } export interface DetachLoadBalancerTargetGroupsParams { - autoScalingGroupName: string; + AutoScalingGroupName: string; TargetGroupARNs: string[]; } export interface DisableMetricsCollectionParams { - autoScalingGroupName: string; - metrics?: string[]; + AutoScalingGroupName: string; + Metrics?: string[]; } export interface EnableMetricsCollectionParams { - autoScalingGroupName: string; - granularity: string; - metrics?: string[]; + AutoScalingGroupName: string; + Granularity: string; + Metrics?: string[]; } export interface EnterStandbyParams { - autoScalingGroupName: string; - shouldDecrementDesiredCapacity: boolean; - instanceIds?: string[]; + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; } export interface ExecutePolicyParams { - policyName: string; - autoScalingGroupName?: string; - honorCooldown?: boolean; - metricValue?: number; - breachThreshold?: number; + PolicyName: string; + AutoScalingGroupName?: string; + HonorCooldown?: boolean; + MetricValue?: number; + BreachThreshold?: number; } export interface ExitStandbyParams { - autoScalingGroupName: string; - instanceIds?: string[]; + AutoScalingGroupName: string; + InstanceIds?: string[]; } export interface PutLifecycleHookParams { - autoScalingGroupName: string; - lifecycleHookName: string; - lifecycleTransition?: string; - roleARN?: string; - notificationTargetARN?: string; - notificationMetadata?: string; - heartbeatTimeout?: number; - defaultResult?: string; + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleTransition?: string; + RoleARN?: string; + NotificationTargetARN?: string; + NotificationMetadata?: string; + HeartbeatTimeout?: number; + DefaultResult?: string; } export interface PutNotificationConfigurationParams { - autoScalingGroupName: string; - notificationTypes: string[]; - topicARN: string; + AutoScalingGroupName: string; + NotificationTypes: string[]; + TopicARN: string; } export interface PutScalingPolicyParams { - autoScalingGroupName: string; - adjustmentType: string; - policyName: string; - policyType?: string; - minAdjustmentStep?: number; - minAdjustmentMagnitude?: number; - scalingAdjustment?: number; - cooldown?: number; - metricAggregationType?: string; - stepAdjustments?: StepAdjustment[]; - estimatedInstanceWarmup: number; + AutoScalingGroupName: string; + AdjustmentType: string; + PolicyName: string; + PolicyType?: string; + MinAdjustmentStep?: number; + MinAdjustmentMagnitude?: number; + ScalingAdjustment?: number; + Cooldown?: number; + MetricAggregationType?: string; + StepAdjustments?: StepAdjustment[]; + EstimatedInstanceWarmup: number; } export interface PutScheduledUpdateGroupActionParams { - autoScalingGroupName: string; - scheduledActionName: string; - time?: Date; - startTime?: Date; - endTime?: Date; - recurrence?: string; - minSize?: number; - maxSize?: number; - desiredCapacity?: number; + AutoScalingGroupName: string; + ScheduledActionName: string; + Time?: Date; + StartTime?: Date; + EndTime?: Date; + Recurrence?: string; + MinSize?: number; + MaxSize?: number; + DesiredCapacity?: number; } export interface RecordLifecycleActionHeartbeatParams { - autoScalingGroupName: string; - lifecycleHookName: string; + AutoScalingGroupName: string; + LifecycleHookName: string; LifecycleActionToken?: string; InstanceId?: string; } export interface ResumeProcessesParams { - autoScalingGroupName: string; + AutoScalingGroupName: string; ScalingProcesses?: string[]; } export interface SetDesiredCapacityParams { - autoScalingGroupName: string; - desiredCapacity: number; - honorCooldown?: boolean; + AutoScalingGroupName: string; + DesiredCapacity: number; + HonorCooldown?: boolean; } export interface SetInstanceHealthParams { - healthStatus: string; - instanceId: string; - shouldRespectGracePeriod?: boolean; + HealthStatus: string; + InstanceId: string; + ShouldRespectGracePeriod?: boolean; } export interface SetInstanceProtectionParams { - autoScalingGroupName: string; - instanceIds: string[]; - protectedFromScaleIn: boolean; + AutoScalingGroupName: string; + InstanceIds: string[]; + ProtectedFromScaleIn: boolean; } export interface SuspendProcessesParams { - autoScalingGroupName: string; - scalingProcesses?: string[]; + AutoScalingGroupName: string; + ScalingProcesses?: string[]; } export interface TerminateInstanceInAutoScalingGroupParams { - instanceId: string; - shouldDecrementDesiredCapacity: boolean; + InstanceId: string; + ShouldDecrementDesiredCapacity: boolean; } export interface UpdateAutoScalingGroupParams { - autoScalingGroupName: string; - launchConfigurationName: string; - minSize: number; - maxSize: number; - desiredCapacity: number; - defaultCooldown: number; - availabilityZones: string[]; - healthCheckType: string; - healthCheckGracePeriod: number; - placementGroup: string; - vPCZoneIdentifier: string; - terminationPolicies: string[]; - newInstancesProtectedFromScaleIn?: boolean; + AutoScalingGroupName: string; + LaunchConfigurationName: string; + MinSize: number; + MaxSize: number; + DesiredCapacity: number; + DefaultCooldown: number; + AvailabilityZones: string[]; + HealthCheckType: string; + HealthCheckGracePeriod: number; + PlacementGroup: string; + VPCZoneIdentifier: string; + TerminationPolicies: string[]; + NewInstancesProtectedFromScaleIn?: boolean; } } From df2e17b0a951123fa1ba1e8b673073c4aaef25ed Mon Sep 17 00:00:00 2001 From: Daniele Frasca Date: Fri, 26 Aug 2016 16:31:19 +0100 Subject: [PATCH 014/212] fixed the first letter of the property to be uppecase --- aws-sdk/aws-sdk.d.ts | 714 +++++++++++++++++++++---------------------- 1 file changed, 357 insertions(+), 357 deletions(-) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 6f5ced6cd3..4ed550251b 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -55,24 +55,24 @@ declare module "aws-sdk" { } export interface Ebs { - snapshotId?: string; - volumeSize?: number; - volumeType?: string; - deleteOnTermination?: boolean; - iops?: number; - encrypted?: boolean; + SnapshotId?: string; + VolumeSize?: number; + VolumeType?: string; + DeleteOnTermination?: boolean; + Iops?: number; + Encrypted?: boolean; } export interface BlockDeviceMapping { - virtualName?: string; - deviceName: string; - ebs?: Ebs; - noDevice?: boolean; + VirtualName?: string; + DeviceName: string; + Ebs?: Ebs; + NoDevice?: boolean; } export interface InstanceMonitoring { - spotPrice?: string; - enabled?: boolean; + SpotPrice?: string; + Enabled?: boolean; } export interface Filter { @@ -696,353 +696,353 @@ declare module "aws-sdk" { } export module AutoScaling { - export interface AutoScalingOptions { - params?: any; - endpoint?: string; - accessKeyId?: string; - secretAccessKey?: string; - sessionToken?: Credentials; - credentials?: Credentials; - credentialProvider?: any; - region?: string; - maxRetries?: number; - maxRedirects?: number; - sslEnabled?: boolean; - paramValidation?: boolean; - computeChecksums?: boolean; - convertResponseTypes?: boolean; - correctClockSkew?: boolean; - s3ForcePathStyle?: boolean; - s3BucketEndpoint?: boolean; - s3DisableBodySigning?: boolean; - retryDelayOptions?: RetryDelayOption; - httpOptions?: HttpOptions; - apiVersion?: string; - apiVersions?: { [serviceName: string]: string }; - logger?: Logger; - systemClockOffset?: number; - signatureVersion?: string; - signatureCache?: boolean; - } - - export interface AttachInstancesParams { - AutoScalingGroupName: string; - InstanceIds: string[]; - } - - export interface AttachLoadBalancersParams { - AutoScalingGroupName: string; - LoadBalancerNames: string[]; - } - - export interface AttachLoadBalancerTargetGroupsParams { - AutoScalingGroupName: string; - TargetGroupARNs: string[]; - } - - export interface CompleteLifecycleActionParams { - AutoScalingGroupName: string; - LifecycleActionResult: string; - LifecycleHookName: string; - lifecycleActionToken?: string; - InstanceId?: string; - } - - export interface CreateAutoScalingGroupParams { - AutoScalingGroupName: string; - MinSize: number; - MaxSize: number; - LaunchConfigurationName?: string; - InstanceId?: string; - DesiredCapacity?: number; - DefaultCooldown?: number; - AvailabilityZones?: string[]; - LoadBalancerNames?: string[]; - TargetGroupARNs?: string[]; - HealthCheckType?: string; - HealthCheckGracePeriod?: number; - PlacementGroup?: string; - VPCZoneIdentifier?: string; - TerminationPolicies?: string; - NewInstancesProtectedFromScaleIn?: boolean; - Tags?: Tags; - } - - export interface CreateLaunchConfigurationParams { - LaunchConfigurationName: string; - AssociatePublicIpAddress?: boolean; - ImageId?: string; - KeyName?: string; - SecurityGroups?: string[]; - ClassicLinkVPCId?: string; - ClassicLinkVPCSecurityGroups?: string[]; - UserData?: string; - InstanceId?: string; - InstanceType?: string; - KernelId?: string; - RamdiskId?: string; - BlockDeviceMappings?: BlockDeviceMapping[]; - InstanceMonitoring?: InstanceMonitoring; - SpotPrice?: string; - IamInstanceProfile?: string; - EbsOptimized?: boolean; - PlacementTenancy?: string; - } - - export interface CreateOrUpdateTagsParams { - Tags: Tags[]; - } - - export interface DeleteAutoScalingGroupParams { - AutoScalingGroupName: string; - ForceDelete?: boolean; - } - - export interface DeleteLaunchConfigurationParams { - LaunchConfigurationName: string; - } - - export interface DeleteLifecycleHookParams { - AutoScalingGroupName: string; - LifecycleHookName: string; - } - - export interface DeleteNotificationConfigurationParams { - AutoScalingGroupName: string; - TopicARN: string; - } - - export interface DeletePolicyParams { - PolicyName: string; - AutoScalingGroupName?: string; - } - - export interface DeleteScheduledActionParams { - AutoScalingGroupName: string; - ScheduledActionName: string; - } - - export interface DeleteTagsParams { - Tags: Tags[]; - } - - export interface DescribeAutoScalingGroupsParams { - AutoScalingGroupName?: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeAutoScalingInstancesParams { - InstanceIds?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeLaunchConfigurationsParams { - LaunchConfigurationNames?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeLifecycleHooksParams { - AutoScalingGroupName: string; - LifecycleHookNames?: string[]; - } - - export interface DescribeLoadBalancersParams { - AutoScalingGroupName: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeLoadBalancerTargetGroupsParams { - AutoScalingGroupName: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeNotificationConfigurationsParams { - AutoScalingGroupName?: string; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribePoliciesParams { - AutoScalingGroupName?: string; - PolicyNames?: string[]; - PolicyTypes?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeScalingActivitiesParams { - AutoScalingGroupName?: string; - ActivityIds?: string[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeScheduledActionsParams { - AutoScalingGroupName?: string; - ScheduledActionNames?: string[]; - StartTime?: Date; - EndTime?: Date; - NextToken?: string; - MaxRecords?: number; - } - - export interface DescribeTagsParams { - Filters?: Filter[]; - NextToken?: string; - MaxRecords?: number; - } - - export interface DetachInstancesParams { - AutoScalingGroupName: string; - ShouldDecrementDesiredCapacity: boolean; - InstanceIds?: string[]; - } - - export interface DetachLoadBalancersParams { - AutoScalingGroupName: string; - LoadBalancerNames: string; - } - - export interface DetachLoadBalancerTargetGroupsParams { - AutoScalingGroupName: string; - TargetGroupARNs: string[]; - } - - export interface DisableMetricsCollectionParams { - AutoScalingGroupName: string; - Metrics?: string[]; - } - - export interface EnableMetricsCollectionParams { - AutoScalingGroupName: string; - Granularity: string; - Metrics?: string[]; - } - - export interface EnterStandbyParams { - AutoScalingGroupName: string; - ShouldDecrementDesiredCapacity: boolean; - InstanceIds?: string[]; - } - - export interface ExecutePolicyParams { - PolicyName: string; - AutoScalingGroupName?: string; - HonorCooldown?: boolean; - MetricValue?: number; - BreachThreshold?: number; - } - - export interface ExitStandbyParams { - AutoScalingGroupName: string; - InstanceIds?: string[]; - } - - export interface PutLifecycleHookParams { - AutoScalingGroupName: string; - LifecycleHookName: string; - LifecycleTransition?: string; - RoleARN?: string; - NotificationTargetARN?: string; - NotificationMetadata?: string; - HeartbeatTimeout?: number; - DefaultResult?: string; - } - - export interface PutNotificationConfigurationParams { - AutoScalingGroupName: string; - NotificationTypes: string[]; - TopicARN: string; - } - - export interface PutScalingPolicyParams { - AutoScalingGroupName: string; - AdjustmentType: string; - PolicyName: string; - PolicyType?: string; - MinAdjustmentStep?: number; - MinAdjustmentMagnitude?: number; - ScalingAdjustment?: number; - Cooldown?: number; - MetricAggregationType?: string; - StepAdjustments?: StepAdjustment[]; - EstimatedInstanceWarmup: number; - } - - export interface PutScheduledUpdateGroupActionParams { - AutoScalingGroupName: string; - ScheduledActionName: string; - Time?: Date; - StartTime?: Date; - EndTime?: Date; - Recurrence?: string; - MinSize?: number; - MaxSize?: number; - DesiredCapacity?: number; - } - - export interface RecordLifecycleActionHeartbeatParams { - AutoScalingGroupName: string; - LifecycleHookName: string; - LifecycleActionToken?: string; - InstanceId?: string; - } - - export interface ResumeProcessesParams { - AutoScalingGroupName: string; - ScalingProcesses?: string[]; - } - - export interface SetDesiredCapacityParams { - AutoScalingGroupName: string; - DesiredCapacity: number; - HonorCooldown?: boolean; - } - - export interface SetInstanceHealthParams { - HealthStatus: string; - InstanceId: string; - ShouldRespectGracePeriod?: boolean; - } - - export interface SetInstanceProtectionParams { - AutoScalingGroupName: string; - InstanceIds: string[]; - ProtectedFromScaleIn: boolean; - } - - export interface SuspendProcessesParams { - AutoScalingGroupName: string; - ScalingProcesses?: string[]; - } - - export interface TerminateInstanceInAutoScalingGroupParams { - InstanceId: string; - ShouldDecrementDesiredCapacity: boolean; - } - - export interface UpdateAutoScalingGroupParams { - AutoScalingGroupName: string; - LaunchConfigurationName: string; - MinSize: number; - MaxSize: number; - DesiredCapacity: number; - DefaultCooldown: number; - AvailabilityZones: string[]; - HealthCheckType: string; - HealthCheckGracePeriod: number; - PlacementGroup: string; - VPCZoneIdentifier: string; - TerminationPolicies: string[]; - NewInstancesProtectedFromScaleIn?: boolean; - } + export interface AutoScalingOptions { + params?: any; + endpoint?: string; + accessKeyId?: string; + secretAccessKey?: string; + sessionToken?: Credentials; + credentials?: Credentials; + credentialProvider?: any; + region?: string; + maxRetries?: number; + maxRedirects?: number; + sslEnabled?: boolean; + paramValidation?: boolean; + computeChecksums?: boolean; + convertResponseTypes?: boolean; + correctClockSkew?: boolean; + s3ForcePathStyle?: boolean; + s3BucketEndpoint?: boolean; + s3DisableBodySigning?: boolean; + retryDelayOptions?: RetryDelayOption; + httpOptions?: HttpOptions; + apiVersion?: string; + apiVersions?: { [serviceName: string]: string }; + logger?: Logger; + systemClockOffset?: number; + signatureVersion?: string; + signatureCache?: boolean; } + export interface AttachInstancesParams { + AutoScalingGroupName: string; + InstanceIds: string[]; + } + + export interface AttachLoadBalancersParams { + AutoScalingGroupName: string; + LoadBalancerNames: string[]; + } + + export interface AttachLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface CompleteLifecycleActionParams { + AutoScalingGroupName: string; + LifecycleActionResult: string; + LifecycleHookName: string; + lifecycleActionToken?: string; + InstanceId?: string; + } + + export interface CreateAutoScalingGroupParams { + AutoScalingGroupName: string; + MinSize: number; + MaxSize: number; + LaunchConfigurationName?: string; + InstanceId?: string; + DesiredCapacity?: number; + DefaultCooldown?: number; + AvailabilityZones?: string[]; + LoadBalancerNames?: string[]; + TargetGroupARNs?: string[]; + HealthCheckType?: string; + HealthCheckGracePeriod?: number; + PlacementGroup?: string; + VPCZoneIdentifier?: string; + TerminationPolicies?: string; + NewInstancesProtectedFromScaleIn?: boolean; + Tags?: Tags; + } + + export interface CreateLaunchConfigurationParams { + LaunchConfigurationName: string; + AssociatePublicIpAddress?: boolean; + ImageId?: string; + KeyName?: string; + SecurityGroups?: string[]; + ClassicLinkVPCId?: string; + ClassicLinkVPCSecurityGroups?: string[]; + UserData?: string; + InstanceId?: string; + InstanceType?: string; + KernelId?: string; + RamdiskId?: string; + BlockDeviceMappings?: BlockDeviceMapping[]; + InstanceMonitoring?: InstanceMonitoring; + SpotPrice?: string; + IamInstanceProfile?: string; + EbsOptimized?: boolean; + PlacementTenancy?: string; + } + + export interface CreateOrUpdateTagsParams { + Tags: Tags[]; + } + + export interface DeleteAutoScalingGroupParams { + AutoScalingGroupName: string; + ForceDelete?: boolean; + } + + export interface DeleteLaunchConfigurationParams { + LaunchConfigurationName: string; + } + + export interface DeleteLifecycleHookParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + } + + export interface DeleteNotificationConfigurationParams { + AutoScalingGroupName: string; + TopicARN: string; + } + + export interface DeletePolicyParams { + PolicyName: string; + AutoScalingGroupName?: string; + } + + export interface DeleteScheduledActionParams { + AutoScalingGroupName: string; + ScheduledActionName: string; + } + + export interface DeleteTagsParams { + Tags: Tags[]; + } + + export interface DescribeAutoScalingGroupsParams { + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeAutoScalingInstancesParams { + InstanceIds?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLaunchConfigurationsParams { + LaunchConfigurationNames?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLifecycleHooksParams { + AutoScalingGroupName: string; + LifecycleHookNames?: string[]; + } + + export interface DescribeLoadBalancersParams { + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeNotificationConfigurationsParams { + AutoScalingGroupName?: string; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribePoliciesParams { + AutoScalingGroupName?: string; + PolicyNames?: string[]; + PolicyTypes?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeScalingActivitiesParams { + AutoScalingGroupName?: string; + ActivityIds?: string[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeScheduledActionsParams { + AutoScalingGroupName?: string; + ScheduledActionNames?: string[]; + StartTime?: Date; + EndTime?: Date; + NextToken?: string; + MaxRecords?: number; + } + + export interface DescribeTagsParams { + Filters?: Filter[]; + NextToken?: string; + MaxRecords?: number; + } + + export interface DetachInstancesParams { + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; + } + + export interface DetachLoadBalancersParams { + AutoScalingGroupName: string; + LoadBalancerNames: string; + } + + export interface DetachLoadBalancerTargetGroupsParams { + AutoScalingGroupName: string; + TargetGroupARNs: string[]; + } + + export interface DisableMetricsCollectionParams { + AutoScalingGroupName: string; + Metrics?: string[]; + } + + export interface EnableMetricsCollectionParams { + AutoScalingGroupName: string; + Granularity: string; + Metrics?: string[]; + } + + export interface EnterStandbyParams { + AutoScalingGroupName: string; + ShouldDecrementDesiredCapacity: boolean; + InstanceIds?: string[]; + } + + export interface ExecutePolicyParams { + PolicyName: string; + AutoScalingGroupName?: string; + HonorCooldown?: boolean; + MetricValue?: number; + BreachThreshold?: number; + } + + export interface ExitStandbyParams { + AutoScalingGroupName: string; + InstanceIds?: string[]; + } + + export interface PutLifecycleHookParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleTransition?: string; + RoleARN?: string; + NotificationTargetARN?: string; + NotificationMetadata?: string; + HeartbeatTimeout?: number; + DefaultResult?: string; + } + + export interface PutNotificationConfigurationParams { + AutoScalingGroupName: string; + NotificationTypes: string[]; + TopicARN: string; + } + + export interface PutScalingPolicyParams { + AutoScalingGroupName: string; + AdjustmentType: string; + PolicyName: string; + PolicyType?: string; + MinAdjustmentStep?: number; + MinAdjustmentMagnitude?: number; + ScalingAdjustment?: number; + Cooldown?: number; + MetricAggregationType?: string; + StepAdjustments?: StepAdjustment[]; + EstimatedInstanceWarmup: number; + } + + export interface PutScheduledUpdateGroupActionParams { + AutoScalingGroupName: string; + ScheduledActionName: string; + Time?: Date; + StartTime?: Date; + EndTime?: Date; + Recurrence?: string; + MinSize?: number; + MaxSize?: number; + DesiredCapacity?: number; + } + + export interface RecordLifecycleActionHeartbeatParams { + AutoScalingGroupName: string; + LifecycleHookName: string; + LifecycleActionToken?: string; + InstanceId?: string; + } + + export interface ResumeProcessesParams { + AutoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface SetDesiredCapacityParams { + AutoScalingGroupName: string; + DesiredCapacity: number; + HonorCooldown?: boolean; + } + + export interface SetInstanceHealthParams { + HealthStatus: string; + InstanceId: string; + ShouldRespectGracePeriod?: boolean; + } + + export interface SetInstanceProtectionParams { + AutoScalingGroupName: string; + InstanceIds: string[]; + ProtectedFromScaleIn: boolean; + } + + export interface SuspendProcessesParams { + AutoScalingGroupName: string; + ScalingProcesses?: string[]; + } + + export interface TerminateInstanceInAutoScalingGroupParams { + InstanceId: string; + ShouldDecrementDesiredCapacity: boolean; + } + + export interface UpdateAutoScalingGroupParams { + AutoScalingGroupName: string; + LaunchConfigurationName: string; + MinSize: number; + MaxSize: number; + DesiredCapacity: number; + DefaultCooldown: number; + AvailabilityZones: string[]; + HealthCheckType: string; + HealthCheckGracePeriod: number; + PlacementGroup: string; + VPCZoneIdentifier: string; + TerminationPolicies: string[]; + NewInstancesProtectedFromScaleIn?: boolean; + } + } + export module SQS { From ca7ee532cee7e1ecac135c36cd719bbb6efefaa1 Mon Sep 17 00:00:00 2001 From: DzmitryDulko Date: Fri, 26 Aug 2016 14:37:43 -0700 Subject: [PATCH 015/212] Add page dimensions to jspdf/addPage --- jspdf/jspdf.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jspdf/jspdf.d.ts b/jspdf/jspdf.d.ts index 60246f04a1..e393e5fba1 100644 --- a/jspdf/jspdf.d.ts +++ b/jspdf/jspdf.d.ts @@ -42,7 +42,7 @@ declare module 'jspdf' { 'getPageInfo'(pageNumberOneBased:number):any; 'getCurrentPageInfo'():any; }; - addPage():jsPDF; + addPage(sizes?: number[]):jsPDF; setPage(n:number):jsPDF; insertPage(beforePage:number):jsPDF; movePage(targetPage:number, beforePage:number):jsPDF; From 811874f47a7667bfe912387f39a39eeb58e1c55b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Mon, 29 Aug 2016 00:12:34 -0700 Subject: [PATCH 016/212] Added declaration and tests for 'rc'. --- rc/index.d.ts | 12 ++++++++++++ rc/rc-tests.ts | 16 ++++++++++++++++ rc/tsconfig.json | 19 +++++++++++++++++++ 3 files changed, 47 insertions(+) create mode 100644 rc/index.d.ts create mode 100644 rc/rc-tests.ts create mode 100644 rc/tsconfig.json diff --git a/rc/index.d.ts b/rc/index.d.ts new file mode 100644 index 0000000000..113f9cdda2 --- /dev/null +++ b/rc/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for rc +// Project: https://github.com/dominictarr/rc +// Definitions by: Daniel Rosenwasser +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function rc( + name: string, + defaults?: any, + argv?: string[] | null, + parse?: ((content: string) => any) | null): any; + +export = rc; \ No newline at end of file diff --git a/rc/rc-tests.ts b/rc/rc-tests.ts new file mode 100644 index 0000000000..9b47bb18d4 --- /dev/null +++ b/rc/rc-tests.ts @@ -0,0 +1,16 @@ +import rc = require("rc") + +let confA = rc("appname", { + port: 2468, + + views: { + engine: "jade" + } +}); + +let appCfg = rc("appname", {}, null, function parse(s) { + return JSON.parse(s.toLowerCase()); +}); +appCfg.configs[0]; +appCfg.configs[1]; +appCfg.config; \ No newline at end of file diff --git a/rc/tsconfig.json b/rc/tsconfig.json new file mode 100644 index 0000000000..331d3bf362 --- /dev/null +++ b/rc/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rc-tests.ts" + ] +} \ No newline at end of file From acdb7b6f5e633e8b361fdc4cac94d904d19c7e2e Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Wed, 31 Aug 2016 17:07:42 +0300 Subject: [PATCH 017/212] node-dir: added types for callback params --- node-dir/node-dir.d.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index 857cdf7bdf..9f45441d4f 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -37,11 +37,11 @@ declare module "node-dir" { } export interface FileCallback { - (error: any, content: any, next: () => void): void; + (error: any, content: string, next: () => void): void; } export interface FileNamedCallback { - (error: any, content: any, filename: string, next: () => void): void; + (error: any, content: string, filename: string, next: () => void): void; } export interface StreamCallback { @@ -49,7 +49,11 @@ declare module "node-dir" { } export interface FinishedCallback { - (error: any, files: any): void; + (error: any, files: string[]): void; + } + export interface PathsResult { + files: string[]; + dirs: string[]; } export function readFiles(dir: string, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; @@ -58,8 +62,9 @@ declare module "node-dir" { export function readFiles(dir: string, options: Options, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; export function readFilesStream(dir: string, options: Options, streamCallback: StreamCallback, finishedCallback?: FinishedCallback): void; - export function files(dir: string, callback: (error: any, files: any) => void): void; - export function subdirs(dir: string, callback: (error: any, subdirs: any) => void): void; - export function paths(dir: string, callback: (error: any, paths: any) => void): void; - export function paths(dir: string, combine: boolean, callback: (error: any, paths: any) => void): void; + export function files(dir: string, callback: (error: any, files: string[]) => void): void; + export function subdirs(dir: string, callback: (error: any, subdirs: string[]) => void): void; + export function paths(dir: string, callback: (error: any, paths: PathsResult) => void): void; + export function paths(dir: string, combine: true, callback: (error: any, paths: string[]) => void): void; + export function paths(dir: string, combine: false, callback: (error: any, paths: PathsResult) => void): void; } From 9fbbb355351e32e7727ca35b885b62f3af50ec57 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 14:31:14 +0300 Subject: [PATCH 018/212] Buffer and ReadStream types --- node-dir/node-dir.d.ts | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index 9f45441d4f..4ffaf0e093 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module "node-dir" { + import { ReadStream } from "fs"; + export interface Options { // file encoding (defaults to 'utf8') encoding?: string; @@ -37,31 +39,28 @@ declare module "node-dir" { } export interface FileCallback { - (error: any, content: string, next: () => void): void; + (error: any, content: string | Buffer, next: () => void): void; } export interface FileNamedCallback { - (error: any, content: string, filename: string, next: () => void): void; + (error: any, content: string | Buffer, filename: string, next: () => void): void; } export interface StreamCallback { - (error: any, stream: any, next: () => void): void; + (error: any, stream: ReadStream, next: () => void): void; } export interface FinishedCallback { (error: any, files: string[]): void; } export interface PathsResult { - files: string[]; - dirs: string[]; + files: string[]; + dirs: string[]; } - export function readFiles(dir: string, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; - export function readFiles(dir: string, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; - export function readFiles(dir: string, options: Options, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; - export function readFiles(dir: string, options: Options, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; - export function readFilesStream(dir: string, options: Options, streamCallback: StreamCallback, - finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, fileCallback: FileCallback | FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, options: Options, fileCallback: FileCallback | FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFilesStream(dir: string, options: Options, streamCallback: StreamCallback, finishedCallback?: FinishedCallback): void; export function files(dir: string, callback: (error: any, files: string[]) => void): void; export function subdirs(dir: string, callback: (error: any, subdirs: string[]) => void): void; export function paths(dir: string, callback: (error: any, paths: PathsResult) => void): void; From dc316de06d44bdbc23ccf22d0b9869bdc36dc4fc Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 14:34:03 +0300 Subject: [PATCH 019/212] removed literal boolean types to pass Travis CI test --- node-dir/node-dir.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index 4ffaf0e093..c1450cf172 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -64,6 +64,5 @@ declare module "node-dir" { export function files(dir: string, callback: (error: any, files: string[]) => void): void; export function subdirs(dir: string, callback: (error: any, subdirs: string[]) => void): void; export function paths(dir: string, callback: (error: any, paths: PathsResult) => void): void; - export function paths(dir: string, combine: true, callback: (error: any, paths: string[]) => void): void; - export function paths(dir: string, combine: false, callback: (error: any, paths: PathsResult) => void): void; + export function paths(dir: string, combine: boolean, callback: (error: any, paths: string[] | PathsResult) => void): void; } From 9d32bda3023b89b75fb1c8289cbc96d9c89cd1a9 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 14:38:35 +0300 Subject: [PATCH 020/212] reference node in node-dir tests --- node-dir/node-dir-tests.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node-dir/node-dir-tests.ts b/node-dir/node-dir-tests.ts index 6cc03ec538..c6442de20f 100644 --- a/node-dir/node-dir-tests.ts +++ b/node-dir/node-dir-tests.ts @@ -1,3 +1,4 @@ +/// /// import * as dir from "node-dir"; From eaebc356556dd02a3a530ae03b50b27b8bfd7017 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 14:51:40 +0300 Subject: [PATCH 021/212] reference node in node-dir --- node-dir/node-dir.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index c1450cf172..40843d3226 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/fshost/node-dir // Definitions by: Panu Horsmalahti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// declare module "node-dir" { import { ReadStream } from "fs"; From 69abf23874bad9cf8dbaa1650cdc6e4cba8c7582 Mon Sep 17 00:00:00 2001 From: Dmitry Radkovskiy Date: Fri, 2 Sep 2016 15:03:32 +0300 Subject: [PATCH 022/212] revert accidental changes --- node-dir/node-dir.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/node-dir/node-dir.d.ts b/node-dir/node-dir.d.ts index 40843d3226..3b2c91dea2 100644 --- a/node-dir/node-dir.d.ts +++ b/node-dir/node-dir.d.ts @@ -59,8 +59,10 @@ declare module "node-dir" { dirs: string[]; } - export function readFiles(dir: string, fileCallback: FileCallback | FileNamedCallback, finishedCallback?: FinishedCallback): void; - export function readFiles(dir: string, options: Options, fileCallback: FileCallback | FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, options: Options, fileCallback: FileCallback, finishedCallback?: FinishedCallback): void; + export function readFiles(dir: string, options: Options, fileCallback: FileNamedCallback, finishedCallback?: FinishedCallback): void; export function readFilesStream(dir: string, options: Options, streamCallback: StreamCallback, finishedCallback?: FinishedCallback): void; export function files(dir: string, callback: (error: any, files: string[]) => void): void; export function subdirs(dir: string, callback: (error: any, subdirs: string[]) => void): void; From 2867a19221cd5e2449135aeed9f13f760b65f458 Mon Sep 17 00:00:00 2001 From: Alec Hill Date: Fri, 2 Sep 2016 13:57:19 +0100 Subject: [PATCH 023/212] Updated redux dock monitor and log monitor to include new optional props, and added typing to custom themes by adding base16 colour scheme typings --- base16/base16-tests.ts | 24 +++++++ base16/base16.d.ts | 70 +++++++++++++++++++ .../redux-devtools-dock-monitor-tests.tsx | 10 ++- .../redux-devtools-dock-monitor.d.ts | 31 +++++--- .../redux-devtools-log-monitor-tests.tsx | 32 ++++++++- .../redux-devtools-log-monitor.d.ts | 34 ++++++--- 6 files changed, 180 insertions(+), 21 deletions(-) create mode 100644 base16/base16-tests.ts create mode 100644 base16/base16.d.ts diff --git a/base16/base16-tests.ts b/base16/base16-tests.ts new file mode 100644 index 0000000000..e4cf78d559 --- /dev/null +++ b/base16/base16-tests.ts @@ -0,0 +1,24 @@ +/// + +import * as base16 from 'base16'; + +const colorScheme: base16.ColorScheme = base16.solarized + +const scheme: string = colorScheme.scheme +const author: string = colorScheme.author +const base00: string = colorScheme.base00 +const base01: string = colorScheme.base01 +const base02: string = colorScheme.base02 +const base03: string = colorScheme.base03 +const base04: string = colorScheme.base04 +const base05: string = colorScheme.base05 +const base06: string = colorScheme.base06 +const base07: string = colorScheme.base07 +const base08: string = colorScheme.base08 +const base09: string = colorScheme.base09 +const base0A: string = colorScheme.base0A +const base0B: string = colorScheme.base0B +const base0C: string = colorScheme.base0C +const base0D: string = colorScheme.base0D +const base0E: string = colorScheme.base0E +const base0F: string = colorScheme.base0F diff --git a/base16/base16.d.ts b/base16/base16.d.ts new file mode 100644 index 0000000000..32717e99f2 --- /dev/null +++ b/base16/base16.d.ts @@ -0,0 +1,70 @@ +// Type definitions for base16-js 1.0.0 +// Project: https://github.com/gaearon/base16-js +// Definitions by: Alec Hill +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'base16' { + + /** + * Type describing a syntax highlighting scheme as a JS object, as used in redux dev tools + * Based on https://github.com/chriskempson/base16 + */ + export interface ColorScheme { + scheme: string + author: string + base00: string + base01: string + base02: string + base03: string + base04: string + base05: string + base06: string + base07: string + base08: string + base09: string + base0A: string + base0B: string + base0C: string + base0D: string + base0E: string + base0F: string + } + + // predefined schemes... + export var threezerotwofour: ColorScheme + export var apathy: ColorScheme + export var ashes: ColorScheme + export var atelierDune: ColorScheme + export var atelierForest: ColorScheme + export var atelierHeath: ColorScheme + export var atelierLakeside: ColorScheme + export var atelierSeaside: ColorScheme + export var bespin: ColorScheme + export var brewer: ColorScheme + export var bright: ColorScheme + export var chalk: ColorScheme + export var codeschool: ColorScheme + export var colors: ColorScheme + export var eighties: ColorScheme + export var embers: ColorScheme + export var flat: ColorScheme + export var google: ColorScheme + export var grayscale: ColorScheme + export var greenscreen: ColorScheme + export var harmonic: ColorScheme + export var hopscotch: ColorScheme + export var isotope: ColorScheme + export var marrakesh: ColorScheme + export var monokai: ColorScheme + export var ocean: ColorScheme + export var paraiso: ColorScheme + export var pop: ColorScheme + export var railscasts: ColorScheme + export var shapeshifter: ColorScheme + export var solarized: ColorScheme + export var summerfruit: ColorScheme + export var tomorrow: ColorScheme + export var tube: ColorScheme + export var twilight: ColorScheme + +} diff --git a/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx b/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx index 00845bdc0a..deeb876fbc 100644 --- a/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx +++ b/redux-devtools-dock-monitor/redux-devtools-dock-monitor-tests.tsx @@ -4,4 +4,12 @@ import * as React from 'react' import DockMonitor from 'redux-devtools-dock-monitor' -let dockMonitor = \ No newline at end of file +let dockMonitor = + +let dockMonitorOptionalProps = diff --git a/redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts b/redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts index 09e3d96036..a3cb861c54 100644 --- a/redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts +++ b/redux-devtools-dock-monitor/redux-devtools-dock-monitor.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-devtools-dock-monitor 1.0.1 +// Type definitions for redux-devtools-dock-monitor 1.1.1 // Project: https://github.com/gaearon/redux-devtools-dock-monitor // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,6 +8,8 @@ declare module "redux-devtools-dock-monitor" { import * as React from 'react' + type DockPosition = 'left' | 'top' | 'right' | 'bottom' + interface IDockMonitorProps { /** * Any valid Redux DevTools monitor. @@ -15,39 +17,48 @@ declare module "redux-devtools-dock-monitor" { children?: React.ReactNode /** - * A key or a key combination that toggles the dock visibility. + * A key or a key combination that toggles the dock visibility. * Must be recognizable by parse-key (for example, 'ctrl-h') */ toggleVisibilityKey: string /** - * A key or a key combination that toggles the dock position. + * A key or a key combination that toggles the dock position. * Must be recognizable by parse-key (for example, 'ctrl-w') */ changePositionKey: string + /** + * A key or a key combination that switches the currently visible monitor. + * Must be recognizable by parse-key (for example, 'ctrl-m') + * Required if you use more than one monitor. + * + * @default undefined + */ + changeMonitorKey?: string + /** * When true, the dock size is a fraction of the window size, fixed otherwise. - * + * * @default true */ fluid?: boolean /** - * Size of the dock. When fluid is true, a float (0.5 means half the window size). + * Size of the dock. When fluid is true, a float (0.5 means half the window size). * When fluid is false, a width in pixels - * + * * @default 0.3 (3/10th of the window size) */ defaultSize?: number /** - * Where the dock appears on the screen. + * Where the dock appears on the screen. * Valid values: 'left', 'top', 'right', 'bottom' - * + * * @default 'right' */ - defaultPosition?: string + defaultPosition?: DockPosition /** * @default true @@ -56,4 +67,4 @@ declare module "redux-devtools-dock-monitor" { } export default class DockMonitor extends React.Component {} -} \ No newline at end of file +} diff --git a/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx b/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx index dbcdbcf7a2..837bc17923 100644 --- a/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx +++ b/redux-devtools-log-monitor/redux-devtools-log-monitor-tests.tsx @@ -4,4 +4,34 @@ import * as React from 'react' import LogMonitor from 'redux-devtools-log-monitor' -let logMonitor = \ No newline at end of file +let logMonitor = + +let logMonitorWithStringTheme = + +const customTheme = { + scheme: 'Oscar Award Winner', + author: 'Nic Cage', + base00: '#000000', + base01: '#000000', + base02: '#000000', + base03: '#000000', + base04: '#000000', + base05: '#000000', + base06: '#000000', + base07: '#000000', + base08: '#000000', + base09: '#000000', + base0A: '#000000', + base0B: '#000000', + base0C: '#000000', + base0D: '#000000', + base0E: '#000000', + base0F: '#000000' +} + +let logMonitorWithCustomTheme = + +let logMonitorWithOtherOptProps = state} + preserveScrollTop={true} + expandActionRoot={true} + expandStateRoot={true} /> diff --git a/redux-devtools-log-monitor/redux-devtools-log-monitor.d.ts b/redux-devtools-log-monitor/redux-devtools-log-monitor.d.ts index 8c96c804da..bb558d5fdc 100644 --- a/redux-devtools-log-monitor/redux-devtools-log-monitor.d.ts +++ b/redux-devtools-log-monitor/redux-devtools-log-monitor.d.ts @@ -1,39 +1,55 @@ -// Type definitions for redux-devtools-log-monitor 1.0.1 +// Type definitions for redux-devtools-log-monitor 1.0.11 // Project: https://github.com/gaearon/redux-devtools-log-monitor // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// declare module "redux-devtools-log-monitor" { import * as React from 'react' + import {ColorScheme} from 'base16' interface ILogMonitorProps { /** - * Either a string referring to one of the themes provided by + * Either a string referring to one of the themes provided by * redux-devtools-themes or a custom object of the same format. - * + * * @see https://github.com/gaearon/redux-devtools-themes */ - theme?: string + theme?: string | ColorScheme /** * A function that selects the slice of the state for DevTools to show. - * + * * @example state => state.thePart.iCare.about. * @default state => state. */ select?: (state: any) => any /** - * When true, records the current scroll top every second so it - * can be restored on refresh. This only has effect when used together + * When true, records the current scroll top every second so it + * can be restored on refresh. This only has effect when used together * with persistState() enhancer from Redux DevTools. - * + * * @default true */ preserveScrollTop?: boolean + + /** + * When true, displays the action object expanded rather than collapsed. + * + * @default true + */ + expandActionRoot?: boolean + + /** + * When true, displays the state object expanded rather than collapsed. + * + * @default true + */ + expandStateRoot?: boolean } export default class LogMonitor extends React.Component {} -} \ No newline at end of file +} From 305bef7e2d9940e4cc40dd157afbabccbc3ef9d7 Mon Sep 17 00:00:00 2001 From: Bez Reyhan Date: Fri, 2 Sep 2016 12:38:19 -0700 Subject: [PATCH 024/212] allow tooltip prop of IconButton to be a ReactNode | string --- material-ui/material-ui.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 2913c0bd57..3f2894a9b6 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -536,7 +536,7 @@ declare namespace __MaterialUI { type horizontal = 'left' | 'middle' | 'right'; type vertical = 'top' | 'center' | 'bottom'; type direction = 'left' | 'right' | 'up' | 'down'; - + interface origin { horizontal: horizontal; vertical: vertical; @@ -745,7 +745,7 @@ declare namespace __MaterialUI { onMouseLeave?: React.MouseEventHandler; onMouseOut?: React.MouseEventHandler; style?: React.CSSProperties; - tooltip?: string; + tooltip?: React.ReactNode | string; tooltipPosition?: propTypes.cornersAndCenter; tooltipStyles?: React.CSSProperties; touch?: boolean; From 0b50dada2ba5585f32aa56b6ba1a80089de3bacc Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Sun, 4 Sep 2016 16:56:47 -0500 Subject: [PATCH 025/212] Add possible null response from find one style functions for TS 2.0 --- sequelize/index.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/sequelize/index.d.ts b/sequelize/index.d.ts index d78abaa2e7..368cecb009 100644 --- a/sequelize/index.d.ts +++ b/sequelize/index.d.ts @@ -56,7 +56,7 @@ declare namespace sequelize { * Get the associated instance. * @param options The options to use when getting the association. */ - (options?: BelongsToGetAssociationMixinOptions): Promise; + (options?: BelongsToGetAssociationMixinOptions): Promise; } /** @@ -170,7 +170,7 @@ declare namespace sequelize { * Get the associated instance. * @param options The options to use when getting the association. */ - (options?: HasOneGetAssociationMixinOptions): Promise; + (options?: HasOneGetAssociationMixinOptions): Promise; } /** @@ -3718,15 +3718,15 @@ declare namespace sequelize { * Search for a single instance by its primary key. This applies LIMIT 1, so the listener will * always be called with a single instance. */ - findById(identifier?: number | string, options?: FindOptions): Promise; - findByPrimary(identifier?: number | string, options?: FindOptions): Promise; + findById(identifier?: number | string, options?: FindOptions): Promise; + findByPrimary(identifier?: number | string, options?: FindOptions): Promise; /** * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single * instance. */ - findOne(options?: FindOptions): Promise; - find(options?: FindOptions): Promise; + findOne(options?: FindOptions): Promise; + find(options?: FindOptions): Promise; /** * Run an aggregation method on the specified field From 29fb8c50c7714582d0c7d912703f81909825b674 Mon Sep 17 00:00:00 2001 From: Joel Spadin Date: Sun, 4 Sep 2016 20:52:33 -0500 Subject: [PATCH 026/212] Fix strict null checking in chrome Fixed everywhere the Chrome API documentation said something could be null but the types didn't allow it under strict null checking. --- chrome/chrome-tests.ts | 47 +++++++++++++++++++++++++++++++++++------ chrome/index.d.ts | 48 ++++++++++++------------------------------ 2 files changed, 54 insertions(+), 41 deletions(-) diff --git a/chrome/chrome-tests.ts b/chrome/chrome-tests.ts index 02273f4385..e7efd0b604 100644 --- a/chrome/chrome-tests.ts +++ b/chrome/chrome-tests.ts @@ -254,11 +254,44 @@ function testOptionsPage() { }); } -chrome.storage.sync.get("myKey", function (loadedData) { - var myValue: { x: number } = loadedData["myKey"]; -}); +// https://developer.chrome.com/extensions/storage#type-StorageArea +function testStorage() { + function getCallback(loadedData: { [key: string]: any; }) { + var myValue: { x: number } = loadedData["myKey"]; + } -chrome.storage.onChanged.addListener(function (changes) { - var myNewValue: { x: number } = changes["myKey"].newValue; - var myOldValue: { x: number } = changes["myKey"].oldValue; -}); + chrome.storage.sync.get(getCallback); + chrome.storage.sync.get("myKey", getCallback); + chrome.storage.sync.get(["myKey", "myKey2"], getCallback); + chrome.storage.sync.get({ foo: 1, bar: 2 }, getCallback); + chrome.storage.sync.get(null, getCallback); + + function getBytesInUseCallback(bytesInUse: number) { + console.log(bytesInUse); + } + + chrome.storage.sync.getBytesInUse(getBytesInUseCallback); + chrome.storage.sync.getBytesInUse("myKey", getBytesInUseCallback); + chrome.storage.sync.getBytesInUse(["myKey", "myKey2"], getBytesInUseCallback); + chrome.storage.sync.getBytesInUse(null, getBytesInUseCallback); + + function doneCallback() { + console.log("done"); + } + + chrome.storage.sync.set({ foo: 1, bar: 2}); + chrome.storage.sync.set({ foo: 1, bar: 2}, doneCallback); + + chrome.storage.sync.remove("myKey"); + chrome.storage.sync.remove("myKey", doneCallback); + chrome.storage.sync.remove(["myKey", "myKey2"]); + chrome.storage.sync.remove(["myKey", "myKey2"], doneCallback); + + chrome.storage.sync.clear(); + chrome.storage.sync.clear(doneCallback); + + chrome.storage.onChanged.addListener(function (changes) { + var myNewValue: { x: number } = changes["myKey"].newValue; + var myOldValue: { x: number } = changes["myKey"].oldValue; + }); +} diff --git a/chrome/index.d.ts b/chrome/index.d.ts index 936616e118..af3dbdc15d 100644 --- a/chrome/index.d.ts +++ b/chrome/index.d.ts @@ -1242,7 +1242,7 @@ declare namespace chrome.cookies { * function( Cookie cookie) {...}; * Optional parameter cookie: Contains details about the cookie that's been set. If setting failed for any reason, this will be "null", and "chrome.runtime.lastError" will be set. */ - export function set(details: SetDetails, callback?: (cookie?: Cookie) => void): void; + export function set(details: SetDetails, callback?: (cookie: Cookie | null) => void): void; /** * Deletes a cookie by name. * @param details Information to identify the cookie to remove. @@ -1257,7 +1257,7 @@ declare namespace chrome.cookies { * function( Cookie cookie) {...}; * Parameter cookie: Contains details about the cookie. This parameter is null if no such cookie was found. */ - export function get(details: Details, callback: (cookie?: Cookie) => void): void; + export function get(details: Details, callback: (cookie: Cookie | null) => void): void; /** Fired when a cookie is set or removed. As a special case, note that updating a cookie's properties is implemented as a two step process: the cookie to be updated is first removed entirely, generating a notification with "cause" of "overwrite" . Afterwards, a new cookie is written with the updated values, generating a second notification with "cause" "explicit". */ var onChanged: CookieChangedEvent; @@ -1755,7 +1755,7 @@ declare namespace chrome.devtools.panels { * @param tooltipText Text shown as a tooltip when user hovers the mouse over the button. * @param disabled Whether the button is disabled. */ - update(iconPath?: string, tooltipText?: string, disabled?: boolean): void; + update(iconPath?: string | null, tooltipText?: string | null, disabled?: boolean | null): void; /** Fired when the button is clicked. */ onClicked: ButtonClickedEvent; } @@ -2458,7 +2458,7 @@ declare namespace chrome.extension { var lastError: LastError; /** Returns the JavaScript 'window' object for the background page running inside the current extension. Returns null if the extension has no background page. */ - export function getBackgroundPage(): Window; + export function getBackgroundPage(): Window | null; /** * Converts a relative path within an extension install directory to a fully-qualified URL. * @param path A path to a resource within an extension expressed relative to its install directory. @@ -2545,7 +2545,7 @@ declare namespace chrome.fileBrowserHandler { interface SelectionResult { /** Optional. Selected file entry. It will be null if a file hasn't been selected. */ - entry?: Object; + entry?: Object | null; /** Whether the file has been selected. */ success: boolean; } @@ -4633,7 +4633,7 @@ declare namespace chrome.platformKeys { * function(object publicKey, object privateKey) {...}; * Optional parameter privateKey: Might be null if this extension does not have access to it. */ - export function getKeyPair(certificate: ArrayBuffer, parameters: Object, callback: (publicKey: CryptoKey, privateKey?: CryptoKey) => void): void; + export function getKeyPair(certificate: ArrayBuffer, parameters: Object, callback: (publicKey: CryptoKey, privateKey: CryptoKey | null) => void): void; /** An implementation of WebCrypto's SubtleCrypto that allows crypto operations on keys of client certificates that are available to this extension. */ export function subtleCrypto(): SubtleCrypto; /** @@ -5476,18 +5476,11 @@ declare namespace chrome.storage { getBytesInUse(callback: (bytesInUse: number) => void): void; /** * Gets the amount of space (in bytes) being used by one or more items. - * @param key A single key to get the total usage for. Pass in null to get the total usage of all of storage. + * @param keys A single key or list of keys to get the total usage for. An empty list will return 0. Pass in null to get the total usage of all of storage. * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). * Parameter bytesInUse: Amount of space being used in storage, in bytes. */ - getBytesInUse(key: string, callback: (bytesInUse: number) => void): void; - /** - * Gets the amount of space (in bytes) being used by one or more items. - * @param keys A list of keys to get the total usage for. An empty list will return 0. Pass in null to get the total usage of all of storage. - * @param callback Callback with the amount of space being used by storage, or on failure (in which case runtime.lastError will be set). - * Parameter bytesInUse: Amount of space being used in storage, in bytes. - */ - getBytesInUse(keys: string[], callback: (bytesInUse: number) => void): void; + getBytesInUse(keys: string | string[] | null, callback: (bytesInUse: number) => void): void; /** * Removes all items from storage. * @param callback Optional. @@ -5524,25 +5517,12 @@ declare namespace chrome.storage { get(callback: (items: { [key: string]: any }) => void): void; /** * Gets one or more items from storage. - * @param key A single key to get. Pass in null to get the entire contents of storage. + * @param keys A single key to get, list of keys to get, or a dictionary specifying default values. + * An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). * Parameter items: Object with items in their key-value mappings. */ - get(key: string, callback: (items: { [key: string]: any }) => void): void; - /** - * Gets one or more items from storage. - * @param keys A list of keys to get. An empty list or object will return an empty result object. Pass in null to get the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get(keys: string[], callback: (items: { [key: string]: any }) => void): void; - /** - * Gets one or more items from storage. - * @param keys A dictionary specifying default values. Pass in null to get the entire contents of storage. - * @param callback Callback with storage items, or on failure (in which case runtime.lastError will be set). - * Parameter items: Object with items in their key-value mappings. - */ - get(keys: Object, callback: (items: { [key: string]: any }) => void): void; + get(keys: string | string[] | Object | null, callback: (items: { [key: string]: any }) => void): void; } interface StorageChange { @@ -5816,7 +5796,7 @@ declare namespace chrome.tabCapture { * @param options Configures the returned media stream. * @param callback Callback with either the tab capture stream or null. */ - export function capture(options: CaptureOptions, callback: (stream: MediaStream) => void): void; + export function capture(options: CaptureOptions, callback: (stream: MediaStream | null) => void): void; /** * Returns a list of tabs that have requested capture or are being captured, i.e. status != stopped and status != error. This allows extensions to inform the user that there is an existing tab capture that would prevent a new tab capture from succeeding (or to prevent redundant requests for the same tab). * @param callback Callback invoked with CaptureInfo[] for captured tabs. @@ -7107,14 +7087,14 @@ declare namespace chrome.webNavigation { * @param callback * Optional parameter details: Information about the requested frame, null if the specified frame ID and/or tab ID are invalid. */ - export function getFrame(details: GetFrameDetails, callback: (details?: GetFrameResultDetails) => void): void; + export function getFrame(details: GetFrameDetails, callback: (details: GetFrameResultDetails | null) => void): void; /** * Retrieves information about all frames of a given tab. * @param details Information about the tab to retrieve all frames from. * @param callback * Optional parameter details: A list of frames in the given tab, null if the specified tab ID is invalid. */ - export function getAllFrames(details: GetAllFrameDetails, callback: (details?: GetAllFrameResultDetails[]) => void): void; + export function getAllFrames(details: GetAllFrameDetails, callback: (details: GetAllFrameResultDetails[] | null) => void): void; /** Fired when the reference fragment of a frame was updated. All future events for that frame will use the updated URL. */ var onReferenceFragmentUpdated: WebNavigationTransitionalEvent; From 989cbc1b80fb2cd5e15994c2d8ffa92f81985684 Mon Sep 17 00:00:00 2001 From: Joel Spadin Date: Sun, 4 Sep 2016 21:07:33 -0500 Subject: [PATCH 027/212] Fix Chrome tests with strict null checking enabled Enabled strict null checking for Chrome tests and fixed some issues with the existing tests. The example code at https://developer.chrome.com/extensions/examples/api/bookmarks/basic/popup.js would use an uninitialized 'span' variable if bookmarkNode.title was empty. Since I have no idea what it was supposed to do in that case, I just moved the declaration of span up a block. --- chrome/chrome-tests.ts | 8 ++++---- chrome/tsconfig.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/chrome/chrome-tests.ts b/chrome/chrome-tests.ts index e7efd0b604..7788397a4c 100644 --- a/chrome/chrome-tests.ts +++ b/chrome/chrome-tests.ts @@ -26,6 +26,7 @@ function bookmarksExample() { return list; } function dumpNode(bookmarkNode, query) { + var span = $(''); if (bookmarkNode.title) { if (query && !bookmarkNode.children) { if (String(bookmarkNode.title).indexOf(query) == -1) { @@ -42,7 +43,6 @@ function bookmarksExample() { anchor.click(function () { chrome.tabs.create({ url: bookmarkNode.url }); }); - var span = $(''); var options = bookmarkNode.children ? $('[Add]') : $('[Edit { + chrome.proxy.settings.get({ incognito: true }, (details) => { var val = details.value; var level: string = details.levelOfControl; - var incognito: boolean = details.incognitoSpecific; + var incognito: boolean = details.incognitoSpecific!; }); // bare minimum set call diff --git a/chrome/tsconfig.json b/chrome/tsconfig.json index f40142d6ae..120b5d78dc 100644 --- a/chrome/tsconfig.json +++ b/chrome/tsconfig.json @@ -3,7 +3,7 @@ "module": "commonjs", "target": "es6", "noImplicitAny": false, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" From 7cfc95d09aee4600d6201d7a937eaa269d184c02 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Sun, 4 Sep 2016 21:06:54 -0500 Subject: [PATCH 028/212] s3-upload-stream typing --- s3-upload-stream/index.d.ts | 26 ++++++++++++++++++++++ s3-upload-stream/s3-upload-stream-tests.ts | 21 +++++++++++++++++ s3-upload-stream/tsconfig.json | 19 ++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 s3-upload-stream/index.d.ts create mode 100644 s3-upload-stream/s3-upload-stream-tests.ts create mode 100644 s3-upload-stream/tsconfig.json diff --git a/s3-upload-stream/index.d.ts b/s3-upload-stream/index.d.ts new file mode 100644 index 0000000000..530fff9674 --- /dev/null +++ b/s3-upload-stream/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for s3-upload-stream +// Project: https://github.com/nathanpeck/s3-upload-stream +// Definitions by: Joshua DeVinney +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +import * as stream from 'stream'; +import * as AWS from 'aws-sdk'; + +interface IS3Stream { + (client: AWS.S3): IS3StreamUploader +} + +interface IS3StreamUploader { + upload(destinationDetails: AWS.s3.PutObjectRequest, sessionDetails?: any): IS3WriteStream; +} + +interface IS3WriteStream extends stream.Writable { + maxPartSize(sizeInBytes: number): void; + concurrentParts(numberOfParts: number): void; +} + +declare var s3Stream: IS3Stream; +export = s3Stream; diff --git a/s3-upload-stream/s3-upload-stream-tests.ts b/s3-upload-stream/s3-upload-stream-tests.ts new file mode 100644 index 0000000000..fefae6782e --- /dev/null +++ b/s3-upload-stream/s3-upload-stream-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import * as fs from 'fs'; +import * as S3Stream from 's3-upload-stream'; +import * as AWS from 'aws-sdk'; + +var s3Stream = S3Stream(new AWS.S3()); + +var read = fs.createReadStream('/path/to/a/file'); +var upload = s3Stream.upload({ + Bucket: "bucket-name", + Key: "key-name", + ACL: "public-read", + StorageClass: "REDUCED_REDUNDANCY", + ContentType: "binary/octet-stream" +}); + +upload.concurrentParts(5); + +read.pipe(upload); diff --git a/s3-upload-stream/tsconfig.json b/s3-upload-stream/tsconfig.json new file mode 100644 index 0000000000..01c892ab5c --- /dev/null +++ b/s3-upload-stream/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "s3-upload-stream-tests.ts" + ] +} \ No newline at end of file From 9320f2c3d65c203ab84876471c62901aa615e6f9 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Mon, 5 Sep 2016 19:36:05 -0500 Subject: [PATCH 029/212] Allow where clauses to have null values submitted to them in strict null checks --- sequelize/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sequelize/index.d.ts b/sequelize/index.d.ts index 368cecb009..032abb064e 100644 --- a/sequelize/index.d.ts +++ b/sequelize/index.d.ts @@ -3052,7 +3052,7 @@ declare namespace sequelize { * typesafety, but there is no way to pass the tests if we just remove it. */ interface WhereOptions { - [field: string]: string | number | WhereLogic | WhereOptions | col | and | or | WhereGeometryOptions | Array | Object; + [field: string]: string | number | WhereLogic | WhereOptions | col | and | or | WhereGeometryOptions | Array | Object | null; } /** From 041d2d4dd5a07a087f03caa534ca99ec324ce779 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Tue, 6 Sep 2016 01:18:46 -0700 Subject: [PATCH 030/212] Fix 'argv' (which is not a simple array). --- rc/index.d.ts | 5 +++-- rc/rc-tests.ts | 25 +++++++++++++++++++++---- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/rc/index.d.ts b/rc/index.d.ts index 113f9cdda2..9a2c6783f6 100644 --- a/rc/index.d.ts +++ b/rc/index.d.ts @@ -6,7 +6,8 @@ declare function rc( name: string, defaults?: any, - argv?: string[] | null, - parse?: ((content: string) => any) | null): any; + argv?: {} | null, + parse?: ((content: string) => any) | null +): any; export = rc; \ No newline at end of file diff --git a/rc/rc-tests.ts b/rc/rc-tests.ts index 9b47bb18d4..9574bec339 100644 --- a/rc/rc-tests.ts +++ b/rc/rc-tests.ts @@ -1,16 +1,33 @@ import rc = require("rc") -let confA = rc("appname", { +let confA = rc("appname1", { port: 2468, - views: { engine: "jade" } }); -let appCfg = rc("appname", {}, null, function parse(s) { +//////////////////// + +let appCfg = rc("appname2", {}, null, function parse(s) { return JSON.parse(s.toLowerCase()); }); + appCfg.configs[0]; appCfg.configs[1]; -appCfg.config; \ No newline at end of file +appCfg.config; + +//////////////////// + +let customArgv = rc("appname3", { + option: true +}, +{ + option: false, + envOption: 24, + argv: { + remain: [], + cooked: ['--no-option', '--envOption', '24'], + original: ['--no-option', '--envOption=24'] + } +}); From 6a01265ff68b3d57b2baef1325be188239ad7d77 Mon Sep 17 00:00:00 2001 From: Ben Mosher Date: Tue, 6 Sep 2016 10:34:08 -0400 Subject: [PATCH 031/212] superagent: req.responseType, res.xhr --- superagent/superagent-tests.ts | 12 +++++++++++- superagent/superagent.d.ts | 2 ++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/superagent/superagent-tests.ts b/superagent/superagent-tests.ts index 237cbdeda1..a91914eaae 100644 --- a/superagent/superagent-tests.ts +++ b/superagent/superagent-tests.ts @@ -5,6 +5,7 @@ import * as request from 'superagent'; import * as fs from 'fs'; +import * as assert from 'assert'; // Examples taken from https://github.com/visionmedia/superagent/blob/gh-pages/docs/index.md // and https://github.com/visionmedia/superagent/blob/master/Readme.md @@ -302,4 +303,13 @@ request request .get('/search') .then((response) => {}) - .catch((error) => {}); \ No newline at end of file + .catch((error) => {}); + +// Requesting binary data. +// adapted from: https://github.com/visionmedia/superagent/blob/v2.0.0/test/client/request.js#L110 +request + .get('/blob') + .responseType('blob') + .end(function(err, res){ + assert.deepEqual(res.xhr.response instanceof Blob, true); + }); diff --git a/superagent/superagent.d.ts b/superagent/superagent.d.ts index 1d89adeb6b..c41847775c 100644 --- a/superagent/superagent.d.ts +++ b/superagent/superagent.d.ts @@ -77,6 +77,7 @@ declare module "superagent" { notAcceptable: boolean; notFound: boolean; forbidden: boolean; + xhr: XMLHttpRequest; get(header: string): string; } @@ -96,6 +97,7 @@ declare module "superagent" { pipe(stream: NodeJS.WritableStream, options?: Object): stream.Writable; query(val: Object): this; redirects(n: number): this; + responseType(type: string): this; send(data: string): this; send(data: Object): this; send(): this; From ad87335d69c98e3cc1888755d55ddd4ed82d9c35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Kov=C3=A1cs?= Date: Wed, 7 Sep 2016 10:04:36 +0200 Subject: [PATCH 032/212] [tether-drop] Rename 'element' property name to 'drop' --- tether-drop/tether-drop.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tether-drop/tether-drop.d.ts b/tether-drop/tether-drop.d.ts index 19c48ec7a1..c908ba399e 100644 --- a/tether-drop/tether-drop.d.ts +++ b/tether-drop/tether-drop.d.ts @@ -10,7 +10,7 @@ declare class Drop { constructor(options: Drop.IDropOptions); public content: HTMLElement; - public element: HTMLElement; + public drop: HTMLElement; public tether: Tether; public open(): void; public close(): void; From ce96198da7f8e66a811f4daf286a37dc3d84c11c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Kov=C3=A1cs?= Date: Wed, 7 Sep 2016 12:42:40 +0200 Subject: [PATCH 033/212] [tether-drop] Rename 'element' property in test --- tether-drop/tether-drop-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tether-drop/tether-drop-tests.ts b/tether-drop/tether-drop-tests.ts index f67f746a7c..403f8d7421 100644 --- a/tether-drop/tether-drop-tests.ts +++ b/tether-drop/tether-drop-tests.ts @@ -24,7 +24,7 @@ d.remove(); d.toggle(); d.position(); d.destroy(); -d.element.appendChild(document.createElement("div")); +d.drop.appendChild(document.createElement("div")); d.tether.position(); d.on("open", () => false); From 34a70dfb0bb7f983b97cec0de94e18dd9940e8b3 Mon Sep 17 00:00:00 2001 From: Peter Burns Date: Tue, 23 Aug 2016 13:51:27 -0700 Subject: [PATCH 034/212] Add async/await to ESTree's declarations. Async/await has landed as stage 4 and the ESTree spec has been updated accordingly: https://github.com/estree/estree/pull/131 --- estree/estree-tests.ts | 12 ++++++++++++ estree/index.d.ts | 12 ++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/estree/estree-tests.ts b/estree/estree-tests.ts index be9587f3c9..ebfb4efe57 100644 --- a/estree/estree-tests.ts +++ b/estree/estree-tests.ts @@ -84,6 +84,7 @@ declare var exportNamedDeclaration: ESTree.ExportNamedDeclaration; declare var exportSpecifier: ESTree.ExportSpecifier; declare var exportDefaultDeclaration: ESTree.ExportDefaultDeclaration; declare var exportAllDeclaration: ESTree.ExportAllDeclaration; +declare var awaitExpression: ESTree.AwaitExpression; declare var toplevelStatement: ESTree.Statement | ESTree.ModuleDeclaration; declare var expressionOrPattern: ESTree.Expression | ESTree.Pattern; @@ -181,6 +182,7 @@ pattern = assignmentPattern.left; expression = assignmentPattern.right; blockStatement = functionExpression.body; var booleanMaybe: boolean | undefined = functionExpression.generator; +booleanMaybe = functionExpression.async; // SequenceExpression var sequenceExpression: ESTree.SequenceExpression; @@ -224,6 +226,7 @@ identifier = functionDeclaration.id; var params: Array = functionDeclaration.params; blockStatement = functionDeclaration.body; booleanMaybe = functionDeclaration.generator; +booleanMaybe = functionDeclaration.async; var variableDeclaration: ESTree.VariableDeclaration; var declarations: Array = variableDeclaration.declarations; @@ -253,6 +256,9 @@ string = identifier.name; string = literal.type; any = literal.value; +// Await Expression +var awaitExpression: ESTree.AwaitExpression; +expression = awaitExpression.argument; // Test narrowing @@ -417,6 +423,9 @@ switch (node.type) { case 'Identifier': identifier = node; break; + case 'AwaitExpression': + awaitExpression = node; + break; // end narrowing of Expression case 'Property': @@ -637,6 +646,9 @@ switch (expression.type) { case 'Identifier': identifier = expression; break; + case 'AwaitExpression': + awaitExpression = expression; + break; default: never = expression; } diff --git a/estree/index.d.ts b/estree/index.d.ts index d086a6455d..26bccf1731 100644 --- a/estree/index.d.ts +++ b/estree/index.d.ts @@ -63,11 +63,13 @@ export interface Program extends BaseNode { interface BaseFunction extends BaseNode { params: Array; generator?: boolean; + async?: boolean; // The body is either BlockStatement or Expression because arrow functions // can have a body that's either. FunctionDeclarations and - // FunctionExpressions nave only BlockStatement bodies. + // FunctionExpressions have only BlockStatement bodies. body: BlockStatement | Expression; } + export type Function = FunctionDeclaration | FunctionExpression | ArrowFunctionExpression; @@ -208,7 +210,8 @@ type Expression = UpdateExpression | BinaryExpression | AssignmentExpression | LogicalExpression | MemberExpression | ConditionalExpression | CallExpression | NewExpression | SequenceExpression | TemplateLiteral | - TaggedTemplateExpression | ClassExpression | MetaProperty | Identifier; + TaggedTemplateExpression | ClassExpression | MetaProperty | Identifier | + AwaitExpression; export interface BaseExpression extends BaseNode { } export interface ThisExpression extends BaseExpression { @@ -526,3 +529,8 @@ export interface ExportAllDeclaration extends BaseModuleDeclaration { type: "ExportAllDeclaration"; source: Literal; } + +export interface AwaitExpression extends BaseExpression { + type: "AwaitExpression"; + argument: Expression; +} From 31b4db7233e018c9c74c7da2de96ec429501f8e2 Mon Sep 17 00:00:00 2001 From: Horiuchi_H Date: Fri, 9 Sep 2016 17:33:04 +0900 Subject: [PATCH 035/212] rewrite nock type definition --- nock/nock-tests.ts | 696 +++++++++++++++++++++++++++++++++++++++++---- nock/nock.d.ts | 237 ++++++++------- 2 files changed, 772 insertions(+), 161 deletions(-) diff --git a/nock/nock-tests.ts b/nock/nock-tests.ts index ffb456b420..20dbf6d04e 100644 --- a/nock/nock-tests.ts +++ b/nock/nock-tests.ts @@ -1,113 +1,118 @@ /// -import nock = require('nock'); +import * as nock from 'nock'; +import * as fs from 'fs'; -var inst: nock.Scope; +var scope: nock.Scope; +var inst: nock.Interceptor; var str: string; var strings: string[]; var bool: boolean; var data: string; var num: number; var obj: {}; -var objects: Object[]; +var defs: nock.NockDefinition[]; var value: any; var regex: RegExp; var options: nock.Options; -var headers: Object; +var headers: { [key: string]: string; }; -inst = inst.head(str); +inst = scope.head(str); -inst = inst.get(str); -inst = inst.get(str, data); +inst = scope.get(str); +inst = scope.get(str, data); -inst = inst.patch(str); -inst = inst.patch(str, str); -inst = inst.patch(str, obj); -inst = inst.patch(str, regex); +inst = scope.patch(str); +inst = scope.patch(str, str); +inst = scope.patch(str, obj); +inst = scope.patch(str, regex); -inst = inst.post(str); -inst = inst.post(str, data); -inst = inst.post(str, obj); -inst = inst.post(str, regex); +inst = scope.post(str); +inst = scope.post(str, data); +inst = scope.post(str, obj); +inst = scope.post(str, regex); -inst = inst.put(str); -inst = inst.put(str, data); -inst = inst.put(str, obj); -inst = inst.put(str, regex); +inst = scope.put(str); +inst = scope.put(str, data); +inst = scope.put(str, obj); +inst = scope.put(str, regex); -inst = inst.delete(str); -inst = inst.delete(str, data); -inst = inst.delete(str, obj); -inst = inst.delete(str, regex); +inst = scope.delete(str); +inst = scope.delete(str, data); +inst = scope.delete(str, obj); +inst = scope.delete(str, regex); -inst = inst.merge(str); -inst = inst.merge(str, data); -inst = inst.merge(str, obj); -inst = inst.merge(str, regex); +inst = scope.merge(str); +inst = scope.merge(str, data); +inst = scope.merge(str, obj); +inst = scope.merge(str, regex); inst = inst.query(obj); inst = inst.query(bool); -inst = inst.intercept(str, str); -inst = inst.intercept(str, str, str); -inst = inst.intercept(str, str, obj); -inst = inst.intercept(str, str, regex); -inst = inst.intercept(str, str, str, value); -inst = inst.intercept(str, str, obj, value); -inst = inst.intercept(str, str, regex, value); +inst = scope.intercept(str, str); +inst = scope.intercept(str, str, str); +inst = scope.intercept(str, str, obj); +inst = scope.intercept(str, str, regex); +inst = scope.intercept(str, str, str, value); +inst = scope.intercept(str, str, obj, value); +inst = scope.intercept(str, str, regex, value); -inst = inst.reply(num); -inst = inst.reply(num, str); +scope = inst.reply(num); +scope = inst.reply(num, str); -inst = inst.reply(num, str, headers); -inst = inst.reply(num, obj, headers); -inst = inst.reply(num, (uri: string, body: string) => { +scope = inst.reply(num, str, headers); +scope = inst.reply(num, obj, headers); +scope = inst.reply(num, (uri: string, body: string) => { return str; }); -inst = inst.reply(num, (uri: string, body: string) => { +scope = inst.reply(num, (uri: string, body: string) => { return str; }, headers); -inst = inst.replyWithFile(num, str); +scope = inst.replyWithFile(num, str); inst = inst.times(4); inst = inst.once(); inst = inst.twice(); inst = inst.thrice(); -inst = inst.defaultReplyHeaders(value); +scope = scope.defaultReplyHeaders(value); -inst = inst.matchHeader(str, str); -inst = inst.matchHeader(str, regex); -inst = inst.matchHeader(str, (val: string) => true); +scope = scope.matchHeader(str, str); +scope = scope.matchHeader(str, regex); +scope = scope.matchHeader(str, (val: string) => true); inst = inst.delay(num); inst = inst.delayConnection(num); -inst = inst.filteringPath(regex, str); -inst = inst.filteringPath((path: string) => { +scope = scope.filteringPath(regex, str); +scope = scope.filteringPath((path: string) => { return str; }); -inst = inst.filteringRequestBody(regex, str); -inst = inst.filteringRequestBody((path: string) => { +scope = scope.filteringRequestBody(regex, str); +scope = scope.filteringRequestBody((path: string) => { return str; }); -inst = inst.persist(); -inst = inst.log(() => { - -}); +scope = scope.log(() => { }); +scope = scope.persist(); +bool = scope.shouldPersist(); +scope = scope.replyContentLength(); +scope = scope.replyDate(); +scope = scope.replyDate(new Date()); inst = inst.delay(2000); +inst = inst.delay({ head: 1000, body: 1000 }); inst = inst.delayBody(2000); inst = inst.delayConnection(2000); inst.getTotalDelay(); inst = inst.socketDelay(2000); -inst.done(); -bool = inst.isDone(); -inst.restore(); +scope.done(); +bool = scope.isDone(); +scope.restore(); -objects = inst.pendingMocks(); +strings = scope.pendingMocks(); nock.recorder.rec(); nock.recorder.rec(true); @@ -115,6 +120,579 @@ nock.recorder.rec({ dont_print: true, output_objects: true }); +nock.recorder.clear(); +strings = nock.recorder.play() as string[]; +defs = nock.recorder.play() as nock.NockDefinition[]; + + +// Usage +var couchdb = nock('http://myapp.iriscouch.com') + .get('/users/1') + .reply(200, { + _id: '123ABC', + _rev: '946B7D1C', + username: 'pgte', + email: 'pedro.teixeira@gmail.com' + }); + +// Specifying hostname +var scope = nock('http://www.example.com') + .get('/resource') + .reply(200, 'domain matched'); +var scope = nock(/example\.com/) + .get('/resource') + .reply(200, 'domain regex matched'); + +// Specifying path +var scope = nock('http://www.example.com') + .get('/resource') + .reply(200, 'path matched'); + +var scope = nock('http://www.example.com') + .get(/source$/) + .reply(200, 'path using regex matched'); + +var scope = nock('http://www.example.com') + .get((uri) => { + return uri.indexOf('cats') >= 0; + }) + .reply(200, 'path using function matched'); + +// Specifying request body +var scope = nock('http://myapp.iriscouch.com') + .post('/users', { + username: 'pgte', + email: 'pedro.teixeira@gmail.com' + }) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }); + +var scope = nock('http://myapp.iriscouch.com') + .post('/users', /email=.?@gmail.com/gi) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }); + +var scope = nock('http://myapp.iriscouch.com') + .post('/users', { + username: 'pgte', + password: /a.+/, + email: 'pedro.teixeira@gmail.com' + }) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }); + +var scope = nock('http://myapp.iriscouch.com') + .post('/users', (body: any) => { + return body.id === '123ABC'; + }) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }); + +// Specifying request query string +nock('http://example.com') + .get('/users') + .query({name: 'pedro', surname: 'teixeira'}) + .reply(200, {results: [{id: 'pgte'}]}); + +nock('http://example.com') + .get('/users') + .query({ + names: ['alice', 'bob'], + tags: { + alice: ['admin', 'tester'], + bob: ['tester'] + } + }) + .reply(200, {results: [{id: 'pgte'}]}); + +nock('http://example.com') + .get('/users') + .query((actualQueryObject: any) => { + // do some compare with the actual Query Object + // return true for matched + // return false for not matched + return true; + }) + .reply(200, {results: [{id: 'pgte'}]}); + +nock('http://example.com') + .get('/users') + .query(true) + .reply(200, {results: [{id: 'pgte'}]}); + +// Specifying replies +var scope = nock('http://myapp.iriscouch.com') + .get('/users/1') + .reply(404); + +var scope = nock('http://www.google.com') + .get('/') + .reply(200, 'Hello from Google!'); + +var scope = nock('http://myapp.iriscouch.com') + .get('/') + .reply(200, { + username: 'pgte', + email: 'pedro.teixeira@gmail.com', + _id: '4324243fsd' + }); + +var scope = nock('http://myapp.iriscouch.com') + .get('/') + .replyWithFile(200, __dirname + '/replies/user.json'); + +var scope = nock('http://www.google.com') + .filteringRequestBody(/.*/, '*') + .post('/echo', '*') + .reply(201, (uri: string, requestBody: string) => { + return requestBody; + }); + +var scope = nock('http://www.google.com') + .filteringRequestBody(/.*/, '*') + .post('/echo', '*') + .reply(201, (uri: string, requestBody: string, cb: nock.ReplyCallback) => { + fs.readFile('cat-poems.txt' , cb); // Error-first callback + }); + +var scope = nock('http://www.google.com') + .filteringRequestBody(/.*/, '*') + .post('/echo', '*') + .reply((uri, requestBody) => { + return [ + 201, + 'THIS IS THE REPLY BODY', + {'header': 'value'} // optional headers + ]; + }); + +var scope = nock('http://www.google.com') + .filteringRequestBody(/.*/, '*') + .post('/echo', '*') + .reply((uri, requestBody, cb) => { + setTimeout(() => { + cb(null, [201, 'THIS IS THE REPLY BODY']) + }, 1e3); + }); + +var scope = nock('http://www.google.com') + .get('/cat-poems') + .reply(200, (uri: string, requestBody: string) => { + return fs.createReadStream('cat-poems.txt'); + }); + +/// Access original request and headers +var scope = nock('http://www.google.com') + .get('/cat-poems') + .reply((uri, requestBody) => { + console.log('path:', this.req.path); + console.log('headers:', this.req.headers); + // ... + }); + +// Replying with errors +nock('http://www.google.com') + .get('/cat-poems') + .replyWithError('something awful happened'); + +nock('http://www.google.com') + .get('/cat-poems') + .replyWithError({'message': 'something awful happened', 'code': 'AWFUL_ERROR'}); + +// Specifying headers + +/// Specifying Request Headers +var scope = nock('http://www.example.com', { + reqheaders: { + 'authorization': 'Basic Auth' + } + }) + .get('/') + .reply(200); + +var scope = nock('http://www.example.com', { + reqheaders: { + 'X-My-Headers': (headerValue) => { + if (headerValue) { + return true; + } + return false; + }, + 'X-My-Awesome-Header': /Awesome/i + } + }) + .get('/') + .reply(200); + +var scope = nock('http://www.example.com', { + badheaders: ['cookie', 'x-forwarded-for'] + }) + .get('/') + .reply(200); + +var scope = nock('http://www.example.com') + .get('/') + .basicAuth({ + user: 'john', + pass: 'doe' + }) + .reply(200); + +/// Specifying Reply Headers +var scope = nock('http://www.headdy.com') + .get('/') + .reply(200, 'Hello World!', { + 'X-My-Headers': 'My Header value' + }); + +var scope = nock('http://www.headdy.com') + .get('/') + .reply(200, 'Hello World!', { + 'X-My-Headers': (req, res, body) => { + return body.toString(); + } + }); + +// Default Reply Headers +var scope = nock('http://www.headdy.com') + .defaultReplyHeaders({ + 'X-Powered-By': 'Rails', + 'Content-Type': 'application/json' + }) + .get('/') + .reply(200, 'The default headers should come too'); + +var scope = nock('http://www.headdy.com') + .defaultReplyHeaders({ + 'Content-Length': (req, res, body) => { + return body.length; + } + }) + .get('/') + .reply(200, 'The default headers should come too'); + +// Including Content-Length Header Automatically +var scope = nock('http://www.headdy.com') + .replyContentLength() + .get('/') + .reply(200, { hello: 'world' }); + +// Including Date Header Automatically +var scope = nock('http://www.headdy.com') + .replyDate(new Date(2015, 0, 1)) // defaults to now, must use a Date object + .get('/') + .reply(200, { hello: 'world' }); + +// HTTP Verbs +nock('http://my.domain.com') + .intercept('/path', 'PATCH') + .reply(304); + +// Support for HTTP and HTTPS +var scope = nock('https://secure.my.server.com'); + +// Non-standard ports +var scope = nock('http://my.server.com:8081'); + +// Repeat response n times +nock('http://zombo.com').get('/').times(4).reply(200, 'Ok'); +nock('http://zombo.com').get('/').once().reply(200, 'Ok'); +nock('http://zombo.com').get('/').twice().reply(200, 'Ok'); +nock('http://zombo.com').get('/').thrice().reply(200, 'Ok'); + +// Delay the response body +nock('http://my.server.com') + .get('/') + .delayBody(2000) // 2 seconds + .reply(200, '') + +// Delay the response +nock('http://my.server.com') + .get('/') + .delay(2000) // 2 seconds delay will be applied to the response header. + .reply(200, '') + +nock('http://my.server.com') + .get('/') + .delay({ + head: 2000, // header will be delayed for 2 seconds, i.e. the whole response will be delayed for 2 seconds. + body: 3000 // body will be delayed for another 3 seconds after header is sent out. + }) + .reply(200, '') + +// Delay the connection +nock('http://my.server.com') + .get('/') + .socketDelay(2000) // 2 seconds + .delayConnection(1000) + .reply(200, '') + +// Chaining +var scope = nock('http://myapp.iriscouch.com') + .get('/users/1') + .reply(404) + .post('/users', { + username: 'pgte', + email: 'pedro.teixeira@gmail.com' + }) + .reply(201, { + ok: true, + id: '123ABC', + rev: '946B7D1C' + }) + .get('/users/123ABC') + .reply(200, { + _id: '123ABC', + _rev: '946B7D1C', + username: 'pgte', + email: 'pedro.teixeira@gmail.com' + }); + +// Scope filtering +var scope = nock('https://api.dropbox.com', { +filteringScope: (scope: string) => { + return /^https:\/\/api[0-9]*.dropbox.com/.test(scope); + } + }) + .get('/1/metadata/auto/Photos?include_deleted=false&list=true') + .reply(200); + +// Path filtering +var scope = nock('http://api.myservice.com') + .filteringPath(/password=[^&]*/g, 'password=XXX') + .get('/users/1?password=XXX') + .reply(200, 'user'); + +var scope = nock('http://api.myservice.com') + .filteringPath((path) => { + return '/ABC'; + }) + .get('/ABC') + .reply(200, 'user'); + +// Request Body filtering +var scope = nock('http://api.myservice.com') + .filteringRequestBody(/password=[^&]*/g, 'password=XXX') + .post('/users/1', 'data=ABC&password=XXX') + .reply(201, 'OK'); + +var scope = nock('http://api.myservice.com') + .filteringRequestBody((body) => { + return 'ABC'; + }) + .post('/', 'ABC') + .reply(201, 'OK'); + +// Request Headers Matching +var scope = nock('http://api.myservice.com') + .matchHeader('accept', 'application/json') + .get('/') + .reply(200, { + data: 'hello world' + }) + +var scope = nock('http://api.myservice.com') + .matchHeader('User-Agent', /Mozilla\/.*/) + .get('/') + .reply(200, { + data: 'hello world' + }) + +var scope = nock('http://api.myservice.com') + .matchHeader('content-length', (val) => { + return Number(val) >= 1000; + }) + .get('/') + .reply(200, { + data: 'hello world' + }) + +// Allow unmocked requests on a mocked hostname +options = {allowUnmocked: true}; +var scope = nock('http://my.existing.service.com', options) + .get('/my/url') + .reply(200, 'OK!'); + +// Expectations +var google = nock('http://google.com') + .get('/') + .reply(200, 'Hello from Google!'); +setTimeout(() => { + google.done(); // will throw an assertion error if meanwhile a "GET http://google.com" was not performed. +}, 5000); + +/// .isDone() +var scope = nock('http://google.com') + .get('/') + .reply(200); +scope.isDone(); // will return false + +nock.isDone(); + +/// .cleanAll() +nock.cleanAll(); + +/// .persist() +var scope = nock('http://persisssists.con') + .persist() + .get('/') + .reply(200, 'Persisting all the way'); + +/// .pendingMocks() +if (!scope.isDone()) { + console.error('pending mocks: %j', scope.pendingMocks()); +} +console.error('pending mocks: %j', nock.pendingMocks()); + +// Logging +var google = nock('http://google.com') + .log(console.log); + +// Restoring +nock.restore(); + +// Enable/Disable real HTTP request +nock.disableNetConnect(); +nock.enableNetConnect(); + +// using a string +nock.enableNetConnect('amazon.com'); + +// or a RegExp +nock.enableNetConnect(/(amazon|github).com/); + +nock.disableNetConnect(); +nock.enableNetConnect('127.0.0.1'); //Allow localhost connections so we can test local routes and mock servers. + +nock.cleanAll(); +nock.enableNetConnect(); + + +// Recording +nock.recorder.rec(); + +/// dont_print option +nock.recorder.rec({ + dont_print: true +}); +// ... some HTTP calls +var nockCalls = nock.recorder.play(); + +/// output_objects option +nock.recorder.rec({ + output_objects: true +}); +// ... some HTTP calls +var nockCallObjects = nock.recorder.play(); + +var pathToJson: string; +var nocks = nock.load(pathToJson); +nocks.forEach((nock) => { + nock = nock.filteringRequestBody((body: string) => { + return body; + }); +}); + +// Pre-process the nock definitions as scope filtering has to be defined before the nocks are defined (due to its very hacky nature). +var nockDefs = nock.loadDefs(pathToJson); +nockDefs.forEach((def) => { + // Do something with the definition object e.g. scope filtering. + def.options = def.options || {}; + def.options.filteringScope = (scope: string) => { + return /^https:\/\/api[0-9]*.dropbox.com/.test(scope); + }; +}); +// Load the nocks from pre-processed definitions. +var nocks = nock.define(nockDefs); + +/// enable_reqheaders_recording option +nock.recorder.rec({ + dont_print: true, + output_objects: true, + enable_reqheaders_recording: true +}); + +/// logging option +var nullAppender = (content: string) => { }; +nock.recorder.rec({ + logging: nullAppender +}); + +/// use_separator option +nock.recorder.rec({ + use_separator: false +}); + + +// .removeInterceptor() +nock.removeInterceptor({ + hostname : 'localhost', + path : '/mockedResource' +}); +nock.removeInterceptor({ + hostname : 'localhost', + path : '/login', + method: 'POST', + proto : 'https' +}); + +var interceptor = nock('http://example.org') + .get('somePath'); +nock.removeInterceptor(interceptor); + + +// Events +/// Global no match event +nock.emitter.on('no match', (req: any) => { }); + + +// Nock Back +/// Setup +import { back as nockBack } from 'nock'; + +nockBack.fixtures = '/path/to/fixtures/'; +nockBack.setMode('record'); + +/// Usage +nockBack.setMode('record'); +nockBack.fixtures = './nockFixtures'; //this only needs to be set once in your test helper + +var before = (def: nock.NockDefinition) => { + def.options = def.options || {}; + def.options.filteringScope = (scope: string) => { + return /^https:\/\/api[0-9]*.dropbox.com/.test(scope); + }; +}; +var after = (scope: nock.Scope) => { + scope = scope.filteringRequestBody((body: string): string => { + return body; + }); +}; + +// recording of the fixture +declare var request: any; +nockBack('zomboFixture.json', { before, after }, (nockDone: () => void) => { + request.get('http://zombo.com', (err: any, res: any, body: string) => { + nockDone(); + // usage of the created fixture + nockBack('zomboFixture.json', (nockDone: () => void) => { + nockDone(); //never gets here + }); + }); +}); + + + -strings = nock.recorder.play(); -objects = nock.recorder.play(); diff --git a/nock/nock.d.ts b/nock/nock.d.ts index 615ec0d3ca..d98d390b10 100644 --- a/nock/nock.d.ts +++ b/nock/nock.d.ts @@ -1,131 +1,164 @@ -// Type definitions for nock v0.54.0 -// Project: https://github.com/pgte/nock -// Definitions by: bonnici +// Type definitions for nock v8.0.0 +// Project: https://github.com/node-nock/nock +// Definitions by: bonnici , Horiuchi_H // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Imported from: https://github.com/soywiz/typescript-node-definitions/nock.d.ts +/// declare module "nock" { - export = nock; + export = nock; - function nock (host: string, options?: nock.Options): nock.Scope; + function nock(basePath: string | RegExp, options?: nock.Options): nock.Scope; - namespace nock { - export function cleanAll(): void; + namespace nock { + export function cleanAll(): void; - export function disableNetConnect(): void; - export function enableNetConnect(): void; - export function enableNetConnect(regex: RegExp): void; - export function enableNetConnect(domain: string): void; - - export function load(path: string): Object[]; - export function restore(): void; + export function activate(): void; + export function isActive(): boolean; + export function isDone(): boolean; + export function pendingMocks(): void; + export function removeInterceptor(interceptor: Interceptor | RequestOptions): boolean; + export function disableNetConnect(): void; + export function enableNetConnect(matcher?: string | RegExp): void; - export var recorder: Recorder; + export function load(path: string): Scope[]; + export function loadDefs(path: string): NockDefinition[]; + export function define(defs: NockDefinition[]): Scope[]; - export interface Scope { - get(path: string, data?: string): Scope; - get(path: RegExp, data?: string): Scope; + export var emitter: NodeJS.EventEmitter; - 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; + export var recorder: Recorder; + export function restore(): void; - 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; + export var back: NockBack; - 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; + type HttpHeaders = { [key: string]: string | { (req: any, res: any, body: string): any; }; }; + type InterceptFunction = ( + uri: string | RegExp | { (uri: string): boolean; }, + requestBody?: string | RegExp | { (body: any): boolean; } | any + ) => Interceptor; + export type ReplyCallback = (err: any, result: ReplyCallbackResult) => void; + type ReplyCallbackResult = string | [number, string | any] | [number, string | any, HttpHeaders] | any; - 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; + export interface Scope extends NodeJS.EventEmitter { + get: InterceptFunction; + post: InterceptFunction; + put: InterceptFunction; + head: InterceptFunction; + patch: InterceptFunction; + merge: InterceptFunction; + delete: InterceptFunction; - 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; + intercept: ( + uri: string | RegExp | { (uri: string): boolean; }, + method: string, + requestBody?: string | RegExp | { (body: any): boolean; } | any, + options?: Options + ) => Interceptor; - query(params: any): Scope; - query(acceptAnyParams: boolean): Scope; - 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; + defaultReplyHeaders(headers: HttpHeaders): this; + matchHeader(name: string, value: string | RegExp | { (value: string): boolean; }): this; + filteringPath(regex: RegExp, replace: string): this; + filteringPath(fn: (path: string) => string): this; + filteringRequestBody(regex: RegExp, replace: string): this; + filteringRequestBody(fn: (body: string) => string): this; - reply(responseCode: number, body?: string, headers?: Object): Scope; - reply(responseCode: number, body?: Object, headers?: Object): Scope; - reply(responseCode: number, callback: (uri: string, body: string) => string, headers?: Object): Scope; - replyWithFile(responseCode: number, fileName: string): Scope; - replyWithError(errorMessage: string): Scope; + log(out: () => void): this; + persist(): this; + shouldPersist(): boolean; + replyContentLength(): this; + replyDate(d?: Date): this; - defaultReplyHeaders(headers: Object): Scope; + done(): void; + isDone(): boolean; + restore(): void; + pendingMocks(): string[]; + } - matchHeader(name: string, value: string): Scope; - matchHeader(name: string, regex: RegExp): Scope; - matchHeader(name: string, fn: (value: string) => boolean): Scope; + export interface Interceptor { + query(params: boolean | { (querObject: any): boolean; } | any): this; - filteringPath(regex: RegExp, replace: string): Scope; - filteringPath(fn: (path: string) => string): Scope; - filteringRequestBody(regex: RegExp, replace: string): Scope; - filteringRequestBody(fn: (path: string) => string): Scope; + reply(responseCode: number, body?: string | any, headers?: HttpHeaders): Scope; + reply(responseCode: number, callback: (uri: string, body: string, cb?: ReplyCallback) => ReplyCallbackResult, headers?: HttpHeaders): Scope; + reply(callback: (uri: string, body: string, cb?: ReplyCallback) => ReplyCallbackResult, headers?: HttpHeaders): Scope; + replyWithError(errorMessage: string | any): Scope; + replyWithFile(responseCode: number, fileName: string, headers?: HttpHeaders): Scope; - persist(): Scope; - log(out: () => void): Scope; + basicAuth(options: { user: string; pass?: string; }): this; - delay(timeMs: number): Scope; - delayBody(timeMs: number): Scope; - delayConnection(timeMs: number): Scope; - getTotalDelay(): number; - socketDelay(timeMs: number): Scope; + times(newCounter: number): this; + once(): this; + twice(): this; + thrice(): this; - times(repeats: number): Scope; - once(): Scope; - twice(): Scope; - thrice(): Scope; + delay(opts: number | { head?: number; body?: number; }): this; + delayBody(timeMs: number): this; + delayConnection(timeMs: number): this; + getTotalDelay(): number; + socketDelay(timeMs: number): this; + } - done(): void; - isDone(): boolean; - restore(): void; - pendingMocks(): Object[]; - } + export interface Options { + allowUnmocked?: boolean; + reqheaders?: { [key: string]: string | RegExp | { (headerValue: string): boolean; }; }; + badheaders?: string[]; + filteringScope?: { (scope: string): boolean; }; + } - export interface Recorder { - rec(capture?: boolean): void; - rec(options?: RecorderOptions): void; - play(): any[]; - } + export interface RequestOptions { + proto?: string; + _https_?: boolean; + hostname?: string; + host?: string; + port?: number; + method?: string; + path?: string; + } - export interface Options { - allowUnmocked?: boolean; - } + export interface Recorder { + rec(options?: boolean | RecorderOptions): void; + clear(): void; + play(): string[] | NockDefinition[]; + } - export interface RecorderOptions { - dont_print?: boolean; - output_objects?: boolean; - enable_reqheaders_recording?: boolean; - } - } + export interface RecorderOptions { + dont_print?: boolean; + output_objects?: boolean; + enable_reqheaders_recording?: boolean; + logging?: (content: string) => void; + use_separator?: boolean; + } + + export interface NockDefinition { + scope: string; + port?: number | string; + method?: string; + path: string; + body?: string | any; + status?: number; + response?: string | any; + headers?: HttpHeaders; + reqheaders?: { [key: string]: string | RegExp | { (headerValue: string): boolean; }; }; + options?: Options; + } + + export type NockBackMode = "wild" | "dryrun" | "record" | "lockdown"; + + export interface NockBack { + fixtures: string; + setMode(mode: NockBackMode): void; + + (fixtureName: string, nockedFn: (nockDone: () => void) => void): void; + (fixtureName: string, options: NockBackOptions, nockedFn: (nockDone: () => void) => void): void; + } + + export interface NockBackOptions { + before?: (def: NockDefinition) => void; + after?: (scope: Scope) => void; + afterRecord?: (defs: NockDefinition[]) => NockDefinition[]; + recorder?: RecorderOptions; + } + } } From f51a1e3750158d1890bad5bc71434e5a2275b51c Mon Sep 17 00:00:00 2001 From: Nico Jansen Date: Mon, 12 Sep 2016 08:15:58 +0200 Subject: [PATCH 036/212] esprima: Allow for type narrowing * Make Syntax constants have specialized sting types. --- esprima/esprima-tests.ts | 6 ++ esprima/index.d.ts | 130 +++++++++++++++++++-------------------- 2 files changed, 71 insertions(+), 65 deletions(-) diff --git a/esprima/esprima-tests.ts b/esprima/esprima-tests.ts index 4e808a1225..6be8ec9e50 100644 --- a/esprima/esprima-tests.ts +++ b/esprima/esprima-tests.ts @@ -22,3 +22,9 @@ string = token.value; // Comment string = comment.value; + +// Type narrowing +var node: ESTree.Node; +if(node.type === esprima.Syntax.IfStatement){ + node.consequent = node; +} diff --git a/esprima/index.d.ts b/esprima/index.d.ts index ccc0c177a9..c19b4e4d21 100644 --- a/esprima/index.d.ts +++ b/esprima/index.d.ts @@ -37,71 +37,71 @@ declare namespace esprima { } const Syntax: { - AssignmentExpression: string, - AssignmentPattern: string, - ArrayExpression: string, - ArrayPattern: string, - ArrowFunctionExpression: string, - BlockStatement: string, - BinaryExpression: string, - BreakStatement: string, - CallExpression: string, - CatchClause: string, - ClassBody: string, - ClassDeclaration: string, - ClassExpression: string, - ConditionalExpression: string, - ContinueStatement: string, - DoWhileStatement: string, - DebuggerStatement: string, - EmptyStatement: string, - ExportAllDeclaration: string, - ExportDefaultDeclaration: string, - ExportNamedDeclaration: string, - ExportSpecifier: string, - ExpressionStatement: string, - ForStatement: string, - ForOfStatement: string, - ForInStatement: string, - FunctionDeclaration: string, - FunctionExpression: string, - Identifier: string, - IfStatement: string, - ImportDeclaration: string, - ImportDefaultSpecifier: string, - ImportNamespaceSpecifier: string, - ImportSpecifier: string, - Literal: string, - LabeledStatement: string, - LogicalExpression: string, - MemberExpression: string, - MetaProperty: string, - MethodDefinition: string, - NewExpression: string, - ObjectExpression: string, - ObjectPattern: string, - Program: string, - Property: string, - RestElement: string, - ReturnStatement: string, - SequenceExpression: string, - SpreadElement: string, - Super: string, - SwitchCase: string, - SwitchStatement: string, - TaggedTemplateExpression: string, - TemplateElement: string, - TemplateLiteral: string, - ThisExpression: string, - ThrowStatement: string, - TryStatement: string, - UnaryExpression: string, - UpdateExpression: string, - VariableDeclaration: string, - VariableDeclarator: string, - WhileStatement: string, - WithStatement: string, - YieldExpression: string + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForOfStatement: 'ForOfStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchCase: 'SwitchCase', + SwitchStatement: 'SwitchStatement', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' }; } From f105740dced564894ee5a12c36fce6a82af9a849 Mon Sep 17 00:00:00 2001 From: Ben Mosher Date: Mon, 12 Sep 2016 08:45:01 -0400 Subject: [PATCH 037/212] superagent: updates for feedback on #11055 --- superagent/superagent-tests.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/superagent/superagent-tests.ts b/superagent/superagent-tests.ts index a91914eaae..283244ac85 100644 --- a/superagent/superagent-tests.ts +++ b/superagent/superagent-tests.ts @@ -310,6 +310,7 @@ request request .get('/blob') .responseType('blob') - .end(function(err, res){ - assert.deepEqual(res.xhr.response instanceof Blob, true); + .end(function (err, res) { + assert(res.xhr instanceof XMLHttpRequest) + assert(res.xhr.response instanceof Blob); }); From a99a95390e5bfc09078fcd0597c395b2ccae370f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Kov=C3=A1cs?= Date: Tue, 13 Sep 2016 10:50:15 +0200 Subject: [PATCH 038/212] [tether-drop] Remove 'drop' property since it is undocumented --- tether-drop/tether-drop.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/tether-drop/tether-drop.d.ts b/tether-drop/tether-drop.d.ts index c908ba399e..8ee8ca1c02 100644 --- a/tether-drop/tether-drop.d.ts +++ b/tether-drop/tether-drop.d.ts @@ -10,7 +10,6 @@ declare class Drop { constructor(options: Drop.IDropOptions); public content: HTMLElement; - public drop: HTMLElement; public tether: Tether; public open(): void; public close(): void; From 605baa5cb44469c9bd6d2caa70b6b9812d500224 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C3=A9ter=20Kov=C3=A1cs?= Date: Tue, 13 Sep 2016 10:51:45 +0200 Subject: [PATCH 039/212] [tether-drop] Fix test containing 'drop' property --- tether-drop/tether-drop-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tether-drop/tether-drop-tests.ts b/tether-drop/tether-drop-tests.ts index 403f8d7421..8976f0344c 100644 --- a/tether-drop/tether-drop-tests.ts +++ b/tether-drop/tether-drop-tests.ts @@ -24,7 +24,7 @@ d.remove(); d.toggle(); d.position(); d.destroy(); -d.drop.appendChild(document.createElement("div")); +d.content.appendChild(document.createElement("div")); d.tether.position(); d.on("open", () => false); From 33377a68598194d155764feb4a4ef33f606b220a Mon Sep 17 00:00:00 2001 From: Tomas Date: Tue, 13 Sep 2016 11:37:10 +0100 Subject: [PATCH 040/212] Fixing removeAllListeners definition - argument optional --- wolfy87-eventemitter/wolfy87-eventemitter.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts index 8291c50c11..d9af289d1a 100644 --- a/wolfy87-eventemitter/wolfy87-eventemitter.d.ts +++ b/wolfy87-eventemitter/wolfy87-eventemitter.d.ts @@ -405,14 +405,14 @@ declare namespace Wolfy87EventEmitter { * * Added to mirror the node API. */ - removeAllListeners(event: string): EventEmitter; + removeAllListeners(event?: string): EventEmitter; /** * Alias of removeEvent. * * Added to mirror the node API. */ - removeAllListeners(event: RegExp): EventEmitter; + removeAllListeners(event?: RegExp): EventEmitter; /** * Emits an event of your choice. From d34c7a7cdd8b58b40eabc3fcc0ac90d799fca4ba Mon Sep 17 00:00:00 2001 From: Marc Date: Tue, 13 Sep 2016 10:35:48 -0400 Subject: [PATCH 041/212] requirejs.RequireConfig Add a missing signature for urlArgs property of the RequireConfig object. --- requirejs/require.d.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/requirejs/require.d.ts b/requirejs/require.d.ts index 3905945187..1c5b4088c1 100644 --- a/requirejs/require.d.ts +++ b/requirejs/require.d.ts @@ -185,8 +185,28 @@ interface RequireConfig { * * @example * urlArgs: "bust= + (new Date()).getTime() + * + * As of RequireJS 2.2.0, urlArgs can be a function. If a + * function, it will receive the module ID and the URL as + * parameters, and it should return a string that will be added + * to the end of the URL. Return an empty string if no args. + * Be sure to take care of adding the '?' or '&' depending on + * the existing state of the URL. + * + * @example + + * requirejs.config({ + * urlArgs: function(id, url) { + * var args = 'v=1'; + * if (url.indexOf('view.html') !== -1) { + * args = 'v=2' + * } + * + * return (url.indexOf('?') === -1 ? '?' : '&') + args; + * } + * }); **/ - urlArgs?: string; + urlArgs?: string | { (id: string, url: string): string; }; /** * Specify the value for the type="" attribute used for script From feae95f169c4892f7e525cbe9d7f677785c99210 Mon Sep 17 00:00:00 2001 From: Gary Roberts Date: Wed, 14 Sep 2016 09:03:34 +0100 Subject: [PATCH 042/212] Update react-router.d.ts Changed react-router RouteComponentProps comment to properly reflect routeParams resolving to type string (not number). As per documentation here: https://github.com/ReactTraining/react-router/blob/master/docs/API.md#routeparams --- react-router/react-router.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index fb19dca42d..767cca1e2f 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -39,10 +39,10 @@ declare namespace ReactRouter { type RouteComponent = Component // use the following interface in an app code to get access to route param values, history, location... - // interface MyComponentProps extends ReactRouter.RouteComponentProps<{}, { id: number }> {} + // interface MyComponentProps extends ReactRouter.RouteComponentProps<{}, { id: string }> {} // somewhere in MyComponent // ... - // let id = this.props.routeParams.id + // let id = parseInt(this.props.routeParams.id, 10); // ... // this.props.history. ... // ... From 874a60bc6803c2ce7eb1103be41be5a203e5a323 Mon Sep 17 00:00:00 2001 From: Marcin Kral Date: Wed, 14 Sep 2016 13:39:53 +0200 Subject: [PATCH 043/212] Add Pure and Stateless components to withRouter definition (#10959) * Add Pure and Stateless components to withRouter definition * Add missing type parameter --- react-router/react-router.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-router/react-router.d.ts b/react-router/react-router.d.ts index fb19dca42d..5df21529e6 100644 --- a/react-router/react-router.d.ts +++ b/react-router/react-router.d.ts @@ -247,7 +247,7 @@ declare namespace ReactRouter { isActive: (pathOrLoc: H.LocationDescriptor, indexOnly?: boolean) => boolean } - function withRouter>(component: C): C + function withRouter | React.StatelessComponent | React.PureComponent>(component: C): C /* utils */ From b1546040789c7f2da20ac97067837e63182f6e16 Mon Sep 17 00:00:00 2001 From: Bastien Caudan Date: Wed, 14 Sep 2016 13:40:39 +0200 Subject: [PATCH 044/212] Add colors strip and stripColors methods (#11160) --- colors/colors-tests.ts | 2 ++ colors/colors.d.ts | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/colors/colors-tests.ts b/colors/colors-tests.ts index 1b9b12834e..ff838da995 100644 --- a/colors/colors-tests.ts +++ b/colors/colors-tests.ts @@ -8,9 +8,11 @@ colors.enabled = true; console.log(colors.black.underline('test')); console.log(colors.rainbow.black.blue.gray('test')); console.log(colors.random.reset.bgWhite.dim('test')); +console.log(colors.random.reset.bgWhite.strip('test')); console.log('test'.black.underline); console.log('test'.rainbow.black.blue.gray); console.log('test'.random.reset.bgWhite.dim); +console.log('test'.random.reset.bgWhite.dim.stripColors); colors.enabled = false; diff --git a/colors/colors.d.ts b/colors/colors.d.ts index 8ce8cca8b7..50e960c416 100644 --- a/colors/colors.d.ts +++ b/colors/colors.d.ts @@ -7,6 +7,9 @@ declare module "colors" { interface Color { (text: string): string; + strip: Color; + stripColors: Color; + black: Color; red: Color; green: Color; @@ -49,6 +52,9 @@ declare module "colors" { export var enabled: boolean; + export var strip: Color; + export var stripColors: Color; + export var black: Color; export var red: Color; export var green: Color; @@ -90,6 +96,9 @@ declare module "colors" { } interface String { + strip: string; + stripColors: string; + black: string; red: string; green: string; From c393c1f1f75bfc8e57df5eb6b70c11eebc28d742 Mon Sep 17 00:00:00 2001 From: ersimont Date: Wed, 14 Sep 2016 07:41:24 -0400 Subject: [PATCH 045/212] support `$injector.get('$resource')` (#11161) --- angularjs/angular-resource.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 441a7e1d3d..3deed5d2fa 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -186,6 +186,12 @@ declare namespace angular { /** creating a resource service factory */ factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction): IModule; } + + namespace auto { + interface IInjectorService { + get(name: '$resource'): ng.resource.IResourceService; + } + } } interface Array From 202e18feddce6512b2e7a89262c13c0f703f859b Mon Sep 17 00:00:00 2001 From: Dominik Palo Date: Wed, 14 Sep 2016 13:41:52 +0200 Subject: [PATCH 046/212] Add typings for node-rio (#11162) --- rpio/rpio-tests.ts | 105 +++++++++++++ rpio/rpio.d.ts | 372 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 477 insertions(+) create mode 100644 rpio/rpio-tests.ts create mode 100644 rpio/rpio.d.ts diff --git a/rpio/rpio-tests.ts b/rpio/rpio-tests.ts new file mode 100644 index 0000000000..fc0d79a71f --- /dev/null +++ b/rpio/rpio-tests.ts @@ -0,0 +1,105 @@ +/// + +rpio.init({gpiomem: false}); /* Use /dev/mem for i²c/PWM/SPI */ +rpio.init({mapping: 'gpio'}); /* Use the GPIOxx numbering */ + +/* Configure P11 as input with the internal pulldown resistor enabled */ +rpio.open(11, rpio.INPUT, rpio.PULL_DOWN); + +/* Configure P12 as output with the initiate state set high */ +rpio.open(12, rpio.OUTPUT, rpio.HIGH); + +/* Configure P13 as output, but leave it in its initial undefined state */ +rpio.open(13, rpio.OUTPUT); + +rpio.mode(12, rpio.INPUT); /* Switch P12 back to input mode */ + +console.log('Pin 12 = %d', rpio.read(12)); + +var buf = new Buffer(10000); + +/* Read the value of Pin 12 10,000 times in a row, storing the values in buf */ +rpio.readbuf(12, buf); + +rpio.write(13, rpio.HIGH); + +/* Write 1 0 1 0 1 0 1 0 to Pin 13 */ +var buf = new Buffer(8).fill(rpio.LOW); +buf[0] = buf[2] = buf[4] = buf[6] = rpio.HIGH; +rpio.writebuf(13, buf); + +var curpad = rpio.readpad(rpio.PAD_GROUP_0_27); + +var slew = ((curpad & rpio.PAD_SLEW_UNLIMITED) == rpio.PAD_SLEW_UNLIMITED); +var hysteresis = ((curpad & rpio.PAD_HYSTERESIS) == rpio.PAD_HYSTERESIS); +var drive = (curpad & 0x7); + +/* Disable input hysteresis but retain other current settings. */ +var control = rpio.readpad(rpio.PAD_GROUP_0_27); +control &= ~rpio.PAD_HYSTERESIS; +rpio.writepad(rpio.PAD_GROUP_0_27, control); + +rpio.pud(11, rpio.PULL_UP); +rpio.pud(12, rpio.PULL_DOWN); + +function nuke_button(pin: number) +{ + console.log('Nuke button on pin %d pressed', pin); + + /* No need to nuke more than once. */ + rpio.poll(pin, null); +} + +function regular_button(pin: number) +{ + /* Watch pin 11 forever. */ + console.log('Button event on pin %d, is now %d', pin, rpio.read(pin)); +} + +/* + * Pin 11 watches for both high and low transitions. Pin 12 only watches for + * high transitions (e.g. the nuke button is pushed). + */ +rpio.poll(11, regular_button); +rpio.poll(12, nuke_button, rpio.POLL_HIGH); + +rpio.close(11); + +rpio.i2cBegin(); + +rpio.i2cSetSlaveAddress(0x20); + +rpio.i2cSetBaudRate(100000); /* 100kHz */ +rpio.i2cSetClockDivider(2500); /* 250MHz / 2500 = 100kHz */ + +var txbuf = new Buffer([0x0b, 0x0e, 0x0e, 0x0f]); +var rxbuf = new Buffer(32); + +rpio.i2cWrite(txbuf); /* Sends 4 bytes */ +rpio.i2cRead(rxbuf, 16); /* Reads 16 bytes */ + +rpio.i2cEnd(); + +rpio.open(12, rpio.PWM); /* Use pin 12 */ + +rpio.pwmSetClockDivider(64); /* Set PWM refresh rate to 300kHz */ + +rpio.pwmSetRange(12, 1024); + +rpio.pwmSetData(12, 512); + +rpio.spiBegin(); /* Switch GPIO7-GPIO11 to SPI mode */ + +rpio.spiSetCSPolarity(0, rpio.HIGH); /* Set CE0 high to activate */ + +rpio.spiSetClockDivider(128); /* Set SPI speed to 1.95MHz */ + +rpio.spiTransfer(txbuf, rxbuf, txbuf.length); + +rpio.spiWrite(txbuf, txbuf.length); + +rpio.spiEnd(); + +rpio.sleep(1); /* Sleep for n seconds */ +rpio.msleep(1); /* Sleep for n milliseconds */ +rpio.usleep(1); /* Sleep for n microseconds */ diff --git a/rpio/rpio.d.ts b/rpio/rpio.d.ts new file mode 100644 index 0000000000..0bba37b918 --- /dev/null +++ b/rpio/rpio.d.ts @@ -0,0 +1,372 @@ +// Type definitions for node-rpio +// Project: https://github.com/jperkin/node-rpio +// Definitions by: Dominik Palo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare var rpio: Rpio; + +declare module 'rpio' { + export = rpio; +} + +interface Rpio { + /** + * Initialise the bcm2835 library. This will be called automatically by .open() using the default option values if not called explicitly. + * @param options + */ + init(options: RPIO.Options): void; + + /** + * Open a pin for input or output. Valid modes are: + * INPUT: pin is input (read-only). + * OUTPUT: pin is output (read-write). + * PWM: configure pin for hardware PWM. + * + * For input pins, option can be used to configure the internal pullup or pulldown resistors using options as described in the .pud() documentation below. + * + * For output pins, option defines the initial isMotionDetected of the pin, rather than having to issue a separate .write() call. This can be critical for devices which must have a stable value, rather than relying on the initial floating value when a pin is enabled for output but hasn't yet been configured with a value. + * @param pin + * @param mode + * @param options + */ + open(pin: number, mode: number, options?: number): void; + + /** + * Switch a pin that has already been opened in one mode to a different mode. + * This is provided primarily for performance reasons, as it avoids some of the setup work done by .open(). + * @param pin + * @param mode + */ + mode(pin: number, mode: number): void; + + /** + * Read the current value of pin, returning either 1 (high) or 0 (low). + * @param pin + */ + read(pin: number): number; + + /** + * Read length bits from pin into buffer as fast as possible. If length isn't specified it defaults to buffer.length. + * @param pin + * @param buffer + * @param length + */ + readbuf(pin: number, buffer: Buffer, length?: number): void; + + /** + * Set the specified pin either high or low, using either the HIGH/LOW constants, or simply 1 or 0. + * @param pin + * @param value + */ + write(pin: number, value: number): void; + + /** + * Write length bits to pin from buffer as fast as possible. If length isn't specified it defaults to buffer.length. + + * @param pin + * @param buffer + * @param length + */ + writebuf(pin: number, buffer: Buffer, length?: number): void; + + /** + * Read the current isMotionDetected of the GPIO pad control for the specified GPIO group. On current models of Raspberry Pi there are three groups with corresponding defines: + * PAD_GROUP_0_27: GPIO0 - GPIO27. Use this for the main GPIO header. + * PAD_GROUP_28_45: GPIO28 - GPIO45. Use this to configure the P5 header. + * PAD_GROUP_46_53: GPIO46 - GPIO53. Internal, you probably won't need this. + * + * The value returned will be a bit mask of the following defines: + * PAD_SLEW_UNLIMITED: 0x10. Slew rate unlimited if set. + * PAD_HYSTERESIS: 0x08. Hysteresis is enabled if set. + * + * The bottom three bits determine the drive current: + * PAD_DRIVE_2mA: 0b000 + * PAD_DRIVE_4mA: 0b001 + * PAD_DRIVE_6mA: 0b010 + * PAD_DRIVE_8mA: 0b011 + * PAD_DRIVE_10mA: 0b100 + * PAD_DRIVE_12mA: 0b101 + * PAD_DRIVE_14mA: 0b110 + * PAD_DRIVE_16mA: 0b111 + * + * @note Note that the pad control registers are not available via /dev/gpiomem, so you will need to use .init({gpiomem: false}) and run as root. + * @param group + */ + readpad(group: number): number; + + /** + * Write control settings to the pad control for group. Uses the same defines as above for .readpad(). + * @param group + * @param control + */ + writepad(group: number, control: number): void; + + /** + * Configure the pin's internal pullup or pulldown resistors, using the following isMotionDetected constants: + * PULL_OFF: disable configured resistors. + * PULL_DOWN: enable the pulldown resistor. + * PULL_UP: enable the pullup resistor. + * + * @param pin + * @param state + */ + pud(pin: number, state: number): void; + + /** + * Watch pin for changes and execute the callback cb() on events. cb() takes a single argument, the pin which triggered the callback. + * + * The optional direction argument can be used to watch for specific events: + * POLL_LOW: poll for falling edge transitions to low. + * POLL_HIGH: poll for rising edge transitions to high. + * POLL_BOTH: poll for both transitions (the default). + * + * Due to hardware/kernel limitations we can only poll for changes, and the event detection only says that an event occurred, not which one. The poll interval is a 1ms setInterval() and transitions could come in between detecting the event and reading the value. Therefore this interface is only useful for events which transition slower than approximately 1kHz. + * + * To stop watching for pin changes, call .poll() again, setting the callback to null. + * @param pin + * @param cb + * @param direction + */ + poll(pin: number, cb: RPIO.CallbackFunction, direction?: number): void; + + /** + * Reset pin to INPUT and clear any pullup/pulldown resistors and poll events. + * @param pin + */ + close(pin: number): void; + + // I²C + + /** + * Assign pins 3 and 5 to i²c use. Until .i2cEnd() is called they won't be available for GPIO use. + * + * The pin assignments are: + * Pin 3: SDA (Serial Data) + * Pin 5: SCL (Serial Clock) + */ + i2cBegin(): void; + + /** + * Configure the slave address. This is between 0 - 0x7f, and it can be helpful to + * run the i2cdetect program to figure out where your devices are if you are unsure. + * @param address + */ + i2cSetSlaveAddress(address: number): void; + + /** + * Set the baud rate - directly set the speed in hertz. + * @param baudRate + */ + i2cSetBaudRate(baudRate: number): void; + + /** + * Read from the i²c slave. + * Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified. + * @param buffer + * @param length + */ + i2cRead(buffer: Buffer, length?: number): void; + + /** + * Write to the i²c slave. + * Function takes a buffer and optional length argument, defaulting to the length of the buffer if not specified. + * @param biffer + * @param length + */ + i2cWrite(biffer: Buffer, length?: number): void; + + /** + * Set the baud rate - based on a divisor of the base 250MHz rate. + * @param clockDivider + */ + i2cSetClockDivider(clockDivider: number): void; + + + + + /** + * Turn off the i²c interface and return the pins to GPIO. + */ + i2cEnd(): void; + + // PWM + + /** + * Set the PWM refresh rate. + * @param clockDivider: power-of-two divisor of the base 19.2MHz rate, with a maximum value of 4096 (4.6875kHz). + */ + pwmSetClockDivider(clockDivider: number): void; + + /** + * Set the PWM range for a pin. This determines the maximum pulse width. + * @param pin + * @param range + */ + pwmSetRange(pin: number, range: number): void; + + /** + * Set the PWM width for a pin. + * @param pin + * @param data + */ + pwmSetData(pin: number, data: number): void; + + // SPI + + /** + * Switch pins 119, 21, 23, 24 and 25 (GPIO7-GPIO11) to SPI mode + * + * Pin | Function + * -----|---------- + * 19 | MOSI + * 21 | MISO + * 23 | SCLK + * 24 | CE0 + * 25 | CE1 + */ + spiBegin(): void; + + /** + * Choose which of the chip select / chip enable pins to control. + * + * Value | Pin + * ------|--------------------- + * 0 | SPI_CE0 (24 / GPIO8) + * 1 | SPI_CE1 (25 / GPIO7) + * 2 | Both + * + * @param chip + */ + spiChipSelect(cePin: number): void; + + /** + * Commonly chip enable (CE) pins are active low, and this is the default. + * If your device's CE pin is active high, use spiSetCSPolarity() to change the polarity. + * @param cePin + * @param polarity + */ + spiSetCSPolarity(cePin: number, polarity: number): void; + + /** + * Set the SPI clock speed with. + * @param clockDivider: an even divisor of the base 250MHz rate ranging between 0 and 65536. + */ + spiSetClockDivider(clockDivider: number): void; + + /** + * Transfer data. Data is sent and received in 8-bit chunks via buffers which should be the same size. + * @param txBuffer + * @param rxBuffer + * @param txLength + */ + spiTransfer(txBuffer: Buffer, rxBuffer: Buffer, txLength: number): void; + + /** + * Send data and do not care about the data coming back. + * @param txBuffer + * @param txLength + */ + spiWrite(txBuffer: Buffer, txLength: number): void; + + /** + * Release the pins back to general purpose use. + */ + spiEnd(): void; + + // Misc + + /** + * Sleep for n seconds. + * @param n: number of seconds to sleep + */ + sleep(n: number): void; + + /** + * Sleep for n milliseconds. + * @param n: number of milliseconds to sleep + */ + msleep(n: number): void; + + /** + * Sleep for n microseconds. + * @param n: number of microseconds to sleep + */ + usleep(n: number): void; + + + // Constants: + + HIGH: number; + LOW: number; + + INPUT: number; + OUTPUT: number; + PWM: number; + + PULL_OFF: number; + PULL_DOWN: number; + PULL_UP: number; + + PAD_GROUP_0_27: number; + PAD_GROUP_28_45: number; + PAD_GROUP_46_53: number; + + PAD_SLEW_UNLIMITED: number; + PAD_HYSTERESIS: number; + + PAD_DRIVE_2mA: number; + PAD_DRIVE_4mA: number; + PAD_DRIVE_6mA: number; + PAD_DRIVE_8mA: number; + PAD_DRIVE_10mA: number; + PAD_DRIVE_12mA: number; + PAD_DRIVE_14mA: number; + PAD_DRIVE_16mA: number; + + POLL_LOW: number; + POLL_HIGH: number; + POLL_BOTH: number; + +} + +declare namespace RPIO { + + interface Options { + + /** + * There are two device nodes for GPIO access. The default is /dev/gpiomem which, when configured with gpio group access, allows users in that group to read/write directly to that device. This removes the need to run as root, but is limited to GPIO functions. + * For non-GPIO functions (i²c, PWM, SPI) the /dev/mem device is required for full access to the Broadcom peripheral address range and the program needs to be executed as the root user (e.g. via sudo). If you do not explicitly call .init() when using those functions, the library will do it for you with gpiomem: false. + * You may also need to use gpiomem: false if you are running on an older Linux kernel which does not support the gpiomem module. + * rpio will throw an exception if you try to use one of the non-GPIO functions after already opening with /dev/gpiomem, as well as checking to see if you have the necessary permissions. + * + * Valid options: + * true: use /dev/gpiomem for non-root but GPIO-only access + * false: use /dev/mem for full access but requires root + */ + gpiomem?: boolean; + + /** + * There are two naming schemes when referring to GPIO pins: + * By their physical header location: Pins 1 to 26 (A/B) or Pins 1 to 40 (A+/B+) + * Using the Broadcom hardware map: GPIO 0-25 (B rev1), GPIO 2-27 (A/B rev2, A+/B+) + * + * Confusingly however, the Broadcom GPIO map changes between revisions, so for example P3 maps to GPIO0 on Model B Revision 1 models, but maps to GPIO2 on all later models. + * This means the only sane default mapping is the physical layout, so that the same code will work on all models regardless of the underlying GPIO mapping. + * If you prefer to use the Broadcom GPIO scheme for whatever reason (e.g. to use the P5 header pins on the Raspberry Pi 1 revision 2.0 model which aren't currently mapped to the physical layout), you can set mapping to gpio to switch to the GPIOxx naming. + * + * Valid options: + * gpio: use the Broadcom GPIOxx naming + * physical: use the physical P01-P40 header layou + */ + mapping?: "gpio" | "physical"; + } + + interface CallbackFunction { + /** + * @param pin: The pin which triggered the callback. + */ + (pin: number): void; + } +} From f237a9af8e7a59dc2fa1ce78f9b84e328d985364 Mon Sep 17 00:00:00 2001 From: Matt Lewis Date: Wed, 14 Sep 2016 12:42:34 +0100 Subject: [PATCH 047/212] Add types for the date-fns library (#11163) --- date-fns/date-fns-tests.ts | 16 + date-fns/date-fns.d.ts | 1195 ++++++++++++++++++++++++++++++++++++ 2 files changed, 1211 insertions(+) create mode 100644 date-fns/date-fns-tests.ts create mode 100644 date-fns/date-fns.d.ts diff --git a/date-fns/date-fns-tests.ts b/date-fns/date-fns-tests.ts new file mode 100644 index 0000000000..4c1dfc2476 --- /dev/null +++ b/date-fns/date-fns-tests.ts @@ -0,0 +1,16 @@ +/// + +import {addDays, closestIndexTo, differenceInCalendarWeeks, max, isDate} from 'date-fns'; +import * as addHours from 'date-fns/add_hours'; + +function test() { + + addDays(new Date(), 5); + closestIndexTo(new Date(), [new Date(), new Date()]); + addHours(new Date(), 5); + differenceInCalendarWeeks(new Date(), new Date()); + differenceInCalendarWeeks(new Date(), new Date(), {weekStartsOn: 1}); + max(new Date(), new Date()); + isDate({}); + +} \ No newline at end of file diff --git a/date-fns/date-fns.d.ts b/date-fns/date-fns.d.ts new file mode 100644 index 0000000000..d0582c2571 --- /dev/null +++ b/date-fns/date-fns.d.ts @@ -0,0 +1,1195 @@ +// Type definitions for date-fns +// Project: https://date-fns.org/ +// Definitions by: Matt Lewis +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type DateOrStringOrNumber = Date | string | number; + +declare module 'date-fns' { + + function addDays(date: DateOrStringOrNumber, amount: number): Date; + namespace addDays {} + + function addHours(date: DateOrStringOrNumber, amount: number): Date; + namespace addHours {} + + function addISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addISOYears {} + + function addMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addMilliseconds {} + + function addMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace addMinutes {} + + function addMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace addMonths {} + + function addQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace addQuarters {} + + function addSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace addSeconds {} + + function addWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace addWeeks {} + + function addYears(date: DateOrStringOrNumber, amount: number): Date; + namespace addYears {} + + function closestIndexTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): number; + namespace closestIndexTo {} + + function closestTo(dateToCompare: DateOrStringOrNumber, datesArray: DateOrStringOrNumber[]): Date; + namespace closestTo {} + + function compareAsc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareAsc {} + + function compareDesc(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace compareDesc {} + + function differenceInCalendarDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarDays {} + + function differenceInCalendarISOWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOWeeks {} + + function differenceInCalendarISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarISOYears {} + + function differenceInCalendarMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarMonths {} + + function differenceInCalendarQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarQuarters {} + + function differenceInCalendarWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): number; + namespace differenceInCalendarWeeks {} + + function differenceInCalendarYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInCalendarYears {} + + function differenceInDays(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInDays {} + + function differenceInHours(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInHours {} + + function differenceInISOYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInISOYears {} + + function differenceInMilliseconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMilliseconds {} + + function differenceInMinutes(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMinutes {} + + function differenceInMonths(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInMonths {} + + function differenceInQuarters(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInQuarters {} + + function differenceInSeconds(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInSeconds {} + + function differenceInWeeks(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInWeeks {} + + function differenceInYears(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): number; + namespace differenceInYears {} + + function distanceInWords(dateFrom: DateOrStringOrNumber, dateTo: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWords {} + + function distanceInWordsToNow(date: DateOrStringOrNumber, options?: {includeSeconds: boolean}): string; + namespace distanceInWordsToNow {} + + function eachDay(startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): Date[]; + namespace eachDay {} + + function endOfDay(date: DateOrStringOrNumber): Date; + namespace endOfDay {} + + function endOfHour(date: DateOrStringOrNumber): Date; + namespace endOfHour {} + + function endOfISOWeek(date: DateOrStringOrNumber): Date; + namespace endOfISOWeek {} + + function endOfISOYear(date: DateOrStringOrNumber): Date; + namespace endOfISOYear {} + + function endOfMinute(date: DateOrStringOrNumber): Date; + namespace endOfMinute {} + + function endOfMonth(date: DateOrStringOrNumber): Date; + namespace endOfMonth {} + + function endOfQuarter(date: DateOrStringOrNumber): Date; + namespace endOfQuarter {} + + function endOfSecond(date: DateOrStringOrNumber): Date; + namespace endOfSecond {} + + function endOfToday(): Date; + namespace endOfToday {} + + function endOfTomorrow(): Date; + namespace endOfTomorrow {} + + function endOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace endOfWeek {} + + function endOfYear(date: DateOrStringOrNumber): Date; + namespace endOfYear {} + + function endOfYesterday(): Date; + namespace endOfYesterday {} + + function format(date: DateOrStringOrNumber, format?: string): string; + namespace format {} + + function getDate(date: DateOrStringOrNumber): number; + namespace getDate {} + + function getDay(date: DateOrStringOrNumber): number; + namespace getDay {} + + function getDayOfYear(date: DateOrStringOrNumber): number; + namespace getDayOfYear {} + + function getDaysInMonth(date: DateOrStringOrNumber): number; + namespace getDaysInMonth {} + + function getDaysInYear(date: DateOrStringOrNumber): number; + namespace getDaysInYear {} + + function getHours(date: DateOrStringOrNumber): number; + namespace getHours {} + + function getISOWeek(date: DateOrStringOrNumber): number; + namespace getISOWeek {} + + function getISOWeeksInYear(date: DateOrStringOrNumber): number; + namespace getISOWeeksInYear {} + + function getISOYear(date: DateOrStringOrNumber): number; + namespace getISOYear {} + + function getMilliseconds(date: DateOrStringOrNumber): number; + namespace getMilliseconds {} + + function getMinutes(date: DateOrStringOrNumber): number; + namespace getMinutes {} + + function getMonth(date: DateOrStringOrNumber): number; + namespace getMonth {} + + function getQuarter(date: DateOrStringOrNumber): number; + namespace getQuarter {} + + function getSeconds(date: DateOrStringOrNumber): number; + namespace getSeconds {} + + function getYear(date: DateOrStringOrNumber): number; + namespace getYear {} + + function isAfter(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isAfter {} + + function isBefore(dateToCompare: DateOrStringOrNumber, date: DateOrStringOrNumber): boolean; + namespace isBefore {} + + function isDate(argument: any): boolean; + namespace isDate {} + + function isEqual(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isEqual {} + + function isFirstDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isFirstDayOfMonth {} + + function isFriday(date: DateOrStringOrNumber): boolean; + namespace isFriday {} + + function isFuture(date: DateOrStringOrNumber): boolean; + namespace isFuture {} + + function isLastDayOfMonth(date: DateOrStringOrNumber): boolean; + namespace isLastDayOfMonth {} + + function isLeapYear(date: DateOrStringOrNumber): boolean; + namespace isLeapYear {} + + function isMonday(date: DateOrStringOrNumber): boolean; + namespace isMonday {} + + function isPast(date: DateOrStringOrNumber): boolean; + namespace isPast {} + + function isSameDay(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameDay {} + + function isSameHour(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameHour {} + + function isSameISOWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOWeek {} + + function isSameISOYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameISOYear {} + + function isSameMinute(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMinute {} + + function isSameMonth(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameMonth {} + + function isSameQuarter(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameQuarter {} + + function isSameSecond(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameSecond {} + + function isSameWeek(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isSameWeek {} + + function isSameYear(dateLeft: DateOrStringOrNumber, dateRight: DateOrStringOrNumber): boolean; + namespace isSameYear {} + + function isSaturday(date: DateOrStringOrNumber): boolean; + namespace isSaturday {} + + function isSunday(date: DateOrStringOrNumber): boolean; + namespace isSunday {} + + function isThisHour(date: DateOrStringOrNumber): boolean; + namespace isThisHour {} + + function isThisISOWeek(date: DateOrStringOrNumber): boolean; + namespace isThisISOWeek {} + + function isThisISOYear(date: DateOrStringOrNumber): boolean; + namespace isThisISOYear {} + + function isThisMinute(date: DateOrStringOrNumber): boolean; + namespace isThisMinute {} + + function isThisMonth(date: DateOrStringOrNumber): boolean; + namespace isThisMonth {} + + function isThisQuarter(date: DateOrStringOrNumber): boolean; + namespace isThisQuarter {} + + function isThisSecond(date: DateOrStringOrNumber): boolean; + namespace isThisSecond {} + + function isThisWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): boolean; + namespace isThisWeek {} + + function isThisYear(date: DateOrStringOrNumber): boolean; + namespace isThisYear {} + + function isThursday(date: DateOrStringOrNumber): boolean; + namespace isThursday {} + + function isToday(date: DateOrStringOrNumber): boolean; + namespace isToday {} + + function isTomorrow(date: DateOrStringOrNumber): boolean; + namespace isTomorrow {} + + function isTuesday(date: DateOrStringOrNumber): boolean; + namespace isTuesday {} + + function isValid(date: DateOrStringOrNumber): boolean; + namespace isValid {} + + function isWednesday(date: DateOrStringOrNumber): boolean; + namespace isWednesday {} + + function isWeekend(date: DateOrStringOrNumber): boolean; + namespace isWeekend {} + + function isWithinRange(date: DateOrStringOrNumber, startDate: DateOrStringOrNumber, endDate: DateOrStringOrNumber): boolean; + namespace isWithinRange {} + + function isYesterday(date: DateOrStringOrNumber): boolean; + namespace isYesterday {} + + function lastDayOfISOWeek(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOWeek {} + + function lastDayOfISOYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfISOYear {} + + function lastDayOfMonth(date: DateOrStringOrNumber): Date; + namespace lastDayOfMonth {} + + function lastDayOfQuarter(date: DateOrStringOrNumber): Date; + namespace lastDayOfQuarter {} + + function lastDayOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace lastDayOfWeek {} + + function lastDayOfYear(date: DateOrStringOrNumber): Date; + namespace lastDayOfYear {} + + function max(...dates: DateOrStringOrNumber[]): Date; + namespace max {} + + function min(...dates: DateOrStringOrNumber[]): Date; + namespace min {} + + function parse(dateString: string): Date; + namespace parse {} + + function setDate(date: DateOrStringOrNumber, dayOfMonth: number): Date; + namespace setDate {} + + function setDay(date: DateOrStringOrNumber, day: number, options?: {weekStartsOn: number}): Date; + namespace setDay {} + + function setDayOfYear(date: DateOrStringOrNumber, dayOfYear: number): Date; + namespace setDayOfYear {} + + function setHours(date: DateOrStringOrNumber, hours: number): Date; + namespace setHours {} + + function setISOWeek(date: DateOrStringOrNumber, isoWeek: number): Date; + namespace setISOWeek {} + + function setISOYear(date: DateOrStringOrNumber, isoYear: number): Date; + namespace setISOYear {} + + function setMilliseconds(date: DateOrStringOrNumber, milliseconds: number): Date; + namespace setMilliseconds {} + + function setMinutes(date: DateOrStringOrNumber, minutes: number): Date; + namespace setMinutes {} + + function setMonth(date: DateOrStringOrNumber, month: number): Date; + namespace setMonth {} + + function setQuarter(date: DateOrStringOrNumber, quarter: number): Date; + namespace setQuarter {} + + function setSeconds(date: DateOrStringOrNumber, seconds: number): Date; + namespace setSeconds {} + + function setYear(date: DateOrStringOrNumber, year: number): Date; + namespace setYear {} + + function startOfDay(date: DateOrStringOrNumber): Date; + namespace startOfDay {} + + function startOfHour(date: DateOrStringOrNumber): Date; + namespace startOfHour {} + + function startOfISOWeek(date: DateOrStringOrNumber): Date; + namespace startOfISOWeek {} + + function startOfISOYear(date: DateOrStringOrNumber): Date; + namespace startOfISOYear {} + + function startOfMinute(date: DateOrStringOrNumber): Date; + namespace startOfMinute {} + + function startOfMonth(date: DateOrStringOrNumber): Date; + namespace startOfMonth {} + + function startOfQuarter(date: DateOrStringOrNumber): Date; + namespace startOfQuarter {} + + function startOfSecond(date: DateOrStringOrNumber): Date; + namespace startOfSecond {} + + function startOfToday(): Date; + namespace startOfToday {} + + function startOfTomorrow(): Date; + namespace startOfTomorrow {} + + function startOfWeek(date: DateOrStringOrNumber, options?: {weekStartsOn: number}): Date; + namespace startOfWeek {} + + function startOfYear(date: DateOrStringOrNumber): Date; + namespace startOfYear {} + + function startOfYesterday(): Date; + namespace startOfYesterday {} + + function subDays(date: DateOrStringOrNumber, amount: number): Date; + namespace subDays {} + + function subHours(date: DateOrStringOrNumber, amount: number): Date; + namespace subHours {} + + function subISOYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subISOYears {} + + function subMilliseconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subMilliseconds {} + + function subMinutes(date: DateOrStringOrNumber, amount: number): Date; + namespace subMinutes {} + + function subMonths(date: DateOrStringOrNumber, amount: number): Date; + namespace subMonths {} + + function subQuarters(date: DateOrStringOrNumber, amount: number): Date; + namespace subQuarters {} + + function subSeconds(date: DateOrStringOrNumber, amount: number): Date; + namespace subSeconds {} + + function subWeeks(date: DateOrStringOrNumber, amount: number): Date; + namespace subWeeks {} + + function subYears(date: DateOrStringOrNumber, amount: number): Date; + namespace subYears {} + +} + +declare module 'date-fns/add_days' { + import {addDays} from 'date-fns'; + export = addDays; +} + +declare module 'date-fns/add_hours' { + import {addHours} from 'date-fns'; + export = addHours; +} + +declare module 'date-fns/add_iso_years' { + import {addISOYears} from 'date-fns'; + export = addISOYears; +} + +declare module 'date-fns/add_milliseconds' { + import {addMilliseconds} from 'date-fns'; + export = addMilliseconds; +} + +declare module 'date-fns/add_minutes' { + import {addMinutes} from 'date-fns'; + export = addMinutes; +} + +declare module 'date-fns/add_months' { + import {addMonths} from 'date-fns'; + export = addMonths; +} + +declare module 'date-fns/add_quarters' { + import {addQuarters} from 'date-fns'; + export = addQuarters; +} + +declare module 'date-fns/add_seconds' { + import {addSeconds} from 'date-fns'; + export = addSeconds; +} + +declare module 'date-fns/add_weeks' { + import {addWeeks} from 'date-fns'; + export = addWeeks; +} + +declare module 'date-fns/add_years' { + import {addYears} from 'date-fns'; + export = addYears; +} + +declare module 'date-fns/closest_index_to' { + import {closestIndexTo} from 'date-fns'; + export = closestIndexTo; +} + +declare module 'date-fns/closest_to' { + import {closestTo} from 'date-fns'; + export = closestTo; +} + +declare module 'date-fns/compare_asc' { + import {compareAsc} from 'date-fns'; + export = compareAsc; +} + +declare module 'date-fns/compare_desc' { + import {compareDesc} from 'date-fns'; + export = compareDesc; +} + +declare module 'date-fns/difference_in_calendar_days' { + import {differenceInCalendarDays} from 'date-fns'; + export = differenceInCalendarDays; +} + +declare module 'date-fns/difference_in_calendar_iso_weeks' { + import {differenceInCalendarISOWeeks} from 'date-fns'; + export = differenceInCalendarISOWeeks; +} + +declare module 'date-fns/difference_in_calendar_iso_years' { + import {differenceInCalendarISOYears} from 'date-fns'; + export = differenceInCalendarISOYears; +} + +declare module 'date-fns/difference_in_calendar_months' { + import {differenceInCalendarMonths} from 'date-fns'; + export = differenceInCalendarMonths; +} + +declare module 'date-fns/difference_in_calendar_quarters' { + import {differenceInCalendarQuarters} from 'date-fns'; + export = differenceInCalendarQuarters; +} + +declare module 'date-fns/difference_in_calendar_weeks' { + import {differenceInCalendarWeeks} from 'date-fns'; + export = differenceInCalendarWeeks; +} + +declare module 'date-fns/difference_in_calendar_years' { + import {differenceInCalendarYears} from 'date-fns'; + export = differenceInCalendarYears; +} + +declare module 'date-fns/difference_in_days' { + import {differenceInDays} from 'date-fns'; + export = differenceInDays; +} + +declare module 'date-fns/difference_in_hours' { + import {differenceInHours} from 'date-fns'; + export = differenceInHours; +} + +declare module 'date-fns/difference_in_iso_years' { + import {differenceInISOYears} from 'date-fns'; + export = differenceInISOYears; +} + +declare module 'date-fns/difference_in_milliseconds' { + import {differenceInMilliseconds} from 'date-fns'; + export = differenceInMilliseconds; +} + +declare module 'date-fns/difference_in_minutes' { + import {differenceInMinutes} from 'date-fns'; + export = differenceInMinutes; +} + +declare module 'date-fns/difference_in_months' { + import {differenceInMonths} from 'date-fns'; + export = differenceInMonths; +} + +declare module 'date-fns/difference_in_quarters' { + import {differenceInQuarters} from 'date-fns'; + export = differenceInQuarters; +} + +declare module 'date-fns/difference_in_seconds' { + import {differenceInSeconds} from 'date-fns'; + export = differenceInSeconds; +} + +declare module 'date-fns/difference_in_weeks' { + import {differenceInWeeks} from 'date-fns'; + export = differenceInWeeks; +} + +declare module 'date-fns/difference_in_years' { + import {differenceInYears} from 'date-fns'; + export = differenceInYears; +} + +declare module 'date-fns/distance_in_words' { + import {distanceInWords} from 'date-fns'; + export = distanceInWords; +} + +declare module 'date-fns/distance_in_words_to_now' { + import {distanceInWordsToNow} from 'date-fns'; + export = distanceInWordsToNow; +} + +declare module 'date-fns/each_day' { + import {eachDay} from 'date-fns'; + export = eachDay; +} + +declare module 'date-fns/end_of_day' { + import {endOfDay} from 'date-fns'; + export = endOfDay; +} + +declare module 'date-fns/end_of_hour' { + import {endOfHour} from 'date-fns'; + export = endOfHour; +} + +declare module 'date-fns/end_of_iso_week' { + import {endOfISOWeek} from 'date-fns'; + export = endOfISOWeek; +} + +declare module 'date-fns/end_of_iso_year' { + import {endOfISOYear} from 'date-fns'; + export = endOfISOYear; +} + +declare module 'date-fns/end_of_minute' { + import {endOfMinute} from 'date-fns'; + export = endOfMinute; +} + +declare module 'date-fns/end_of_month' { + import {endOfMonth} from 'date-fns'; + export = endOfMonth; +} + +declare module 'date-fns/end_of_quarter' { + import {endOfQuarter} from 'date-fns'; + export = endOfQuarter; +} + +declare module 'date-fns/end_of_second' { + import {endOfSecond} from 'date-fns'; + export = endOfSecond; +} + +declare module 'date-fns/end_of_today' { + import {endOfToday} from 'date-fns'; + export = endOfToday; +} + +declare module 'date-fns/end_of_tomorrow' { + import {endOfTomorrow} from 'date-fns'; + export = endOfTomorrow; +} + +declare module 'date-fns/end_of_week' { + import {endOfWeek} from 'date-fns'; + export = endOfWeek; +} + +declare module 'date-fns/end_of_year' { + import {endOfYear} from 'date-fns'; + export = endOfYear; +} + +declare module 'date-fns/end_of_yesterday' { + import {endOfYesterday} from 'date-fns'; + export = endOfYesterday; +} + +declare module 'date-fns/format' { + import {format} from 'date-fns'; + export = format; +} + +declare module 'date-fns/get_date' { + import {getDate} from 'date-fns'; + export = getDate; +} + +declare module 'date-fns/get_day' { + import {getDay} from 'date-fns'; + export = getDay; +} + +declare module 'date-fns/get_day_of_year' { + import {getDayOfYear} from 'date-fns'; + export = getDayOfYear; +} + +declare module 'date-fns/get_days_in_month' { + import {getDaysInMonth} from 'date-fns'; + export = getDaysInMonth; +} + +declare module 'date-fns/get_days_in_year' { + import {getDaysInYear} from 'date-fns'; + export = getDaysInYear; +} + +declare module 'date-fns/get_hours' { + import {getHours} from 'date-fns'; + export = getHours; +} + +declare module 'date-fns/get_iso_week' { + import {getISOWeek} from 'date-fns'; + export = getISOWeek; +} + +declare module 'date-fns/get_iso_weeks_in_year' { + import {getISOWeeksInYear} from 'date-fns'; + export = getISOWeeksInYear; +} + +declare module 'date-fns/get_iso_year' { + import {getISOYear} from 'date-fns'; + export = getISOYear; +} + +declare module 'date-fns/get_milliseconds' { + import {getMilliseconds} from 'date-fns'; + export = getMilliseconds; +} + +declare module 'date-fns/get_minutes' { + import {getMinutes} from 'date-fns'; + export = getMinutes; +} + +declare module 'date-fns/get_month' { + import {getMonth} from 'date-fns'; + export = getMonth; +} + +declare module 'date-fns/get_quarter' { + import {getQuarter} from 'date-fns'; + export = getQuarter; +} + +declare module 'date-fns/get_seconds' { + import {getSeconds} from 'date-fns'; + export = getSeconds; +} + +declare module 'date-fns/get_year' { + import {getYear} from 'date-fns'; + export = getYear; +} + +declare module 'date-fns/is_after' { + import {isAfter} from 'date-fns'; + export = isAfter; +} + +declare module 'date-fns/is_before' { + import {isBefore} from 'date-fns'; + export = isBefore; +} + +declare module 'date-fns/is_date' { + import {isDate} from 'date-fns'; + export = isDate; +} + +declare module 'date-fns/is_equal' { + import {isEqual} from 'date-fns'; + export = isEqual; +} + +declare module 'date-fns/is_first_day_of_month' { + import {isFirstDayOfMonth} from 'date-fns'; + export = isFirstDayOfMonth; +} + +declare module 'date-fns/is_friday' { + import {isFriday} from 'date-fns'; + export = isFriday; +} + +declare module 'date-fns/is_future' { + import {isFuture} from 'date-fns'; + export = isFuture; +} + +declare module 'date-fns/is_last_day_of_month' { + import {isLastDayOfMonth} from 'date-fns'; + export = isLastDayOfMonth; +} + +declare module 'date-fns/is_leap_year' { + import {isLeapYear} from 'date-fns'; + export = isLeapYear; +} + +declare module 'date-fns/is_monday' { + import {isMonday} from 'date-fns'; + export = isMonday; +} + +declare module 'date-fns/is_past' { + import {isPast} from 'date-fns'; + export = isPast; +} + +declare module 'date-fns/is_same_day' { + import {isSameDay} from 'date-fns'; + export = isSameDay; +} + +declare module 'date-fns/is_same_hour' { + import {isSameHour} from 'date-fns'; + export = isSameHour; +} + +declare module 'date-fns/is_same_iso_week' { + import {isSameISOWeek} from 'date-fns'; + export = isSameISOWeek; +} + +declare module 'date-fns/is_same_iso_year' { + import {isSameISOYear} from 'date-fns'; + export = isSameISOYear; +} + +declare module 'date-fns/is_same_minute' { + import {isSameMinute} from 'date-fns'; + export = isSameMinute; +} + +declare module 'date-fns/is_same_month' { + import {isSameMonth} from 'date-fns'; + export = isSameMonth; +} + +declare module 'date-fns/is_same_quarter' { + import {isSameQuarter} from 'date-fns'; + export = isSameQuarter; +} + +declare module 'date-fns/is_same_second' { + import {isSameSecond} from 'date-fns'; + export = isSameSecond; +} + +declare module 'date-fns/is_same_week' { + import {isSameWeek} from 'date-fns'; + export = isSameWeek; +} + +declare module 'date-fns/is_same_year' { + import {isSameYear} from 'date-fns'; + export = isSameYear; +} + +declare module 'date-fns/is_saturday' { + import {isSaturday} from 'date-fns'; + export = isSaturday; +} + +declare module 'date-fns/is_sunday' { + import {isSunday} from 'date-fns'; + export = isSunday; +} + +declare module 'date-fns/is_this_hour' { + import {isThisHour} from 'date-fns'; + export = isThisHour; +} + +declare module 'date-fns/is_this_iso_week' { + import {isThisISOWeek} from 'date-fns'; + export = isThisISOWeek; +} + +declare module 'date-fns/is_this_iso_year' { + import {isThisISOYear} from 'date-fns'; + export = isThisISOYear; +} + +declare module 'date-fns/is_this_minute' { + import {isThisMinute} from 'date-fns'; + export = isThisMinute; +} + +declare module 'date-fns/is_this_month' { + import {isThisMonth} from 'date-fns'; + export = isThisMonth; +} + +declare module 'date-fns/is_this_quarter' { + import {isThisQuarter} from 'date-fns'; + export = isThisQuarter; +} + +declare module 'date-fns/is_this_second' { + import {isThisSecond} from 'date-fns'; + export = isThisSecond; +} + +declare module 'date-fns/is_this_week' { + import {isThisWeek} from 'date-fns'; + export = isThisWeek; +} + +declare module 'date-fns/is_this_year' { + import {isThisYear} from 'date-fns'; + export = isThisYear; +} + +declare module 'date-fns/is_thursday' { + import {isThursday} from 'date-fns'; + export = isThursday; +} + +declare module 'date-fns/is_today' { + import {isToday} from 'date-fns'; + export = isToday; +} + +declare module 'date-fns/is_tomorrow' { + import {isTomorrow} from 'date-fns'; + export = isTomorrow; +} + +declare module 'date-fns/is_tuesday' { + import {isTuesday} from 'date-fns'; + export = isTuesday; +} + +declare module 'date-fns/is_valid' { + import {isValid} from 'date-fns'; + export = isValid; +} + +declare module 'date-fns/is_wednesday' { + import {isWednesday} from 'date-fns'; + export = isWednesday; +} + +declare module 'date-fns/is_weekend' { + import {isWeekend} from 'date-fns'; + export = isWeekend; +} + +declare module 'date-fns/is_within_range' { + import {isWithinRange} from 'date-fns'; + export = isWithinRange; +} + +declare module 'date-fns/is_yesterday' { + import {isYesterday} from 'date-fns'; + export = isYesterday; +} + +declare module 'date-fns/last_day_of_iso_week' { + import {lastDayOfISOWeek} from 'date-fns'; + export = lastDayOfISOWeek; +} + +declare module 'date-fns/last_day_of_iso_year' { + import {lastDayOfISOYear} from 'date-fns'; + export = lastDayOfISOYear; +} + +declare module 'date-fns/last_day_of_month' { + import {lastDayOfMonth} from 'date-fns'; + export = lastDayOfMonth; +} + +declare module 'date-fns/last_day_of_quarter' { + import {lastDayOfQuarter} from 'date-fns'; + export = lastDayOfQuarter; +} + +declare module 'date-fns/last_day_of_week' { + import {lastDayOfWeek} from 'date-fns'; + export = lastDayOfWeek; +} + +declare module 'date-fns/last_day_of_year' { + import {lastDayOfYear} from 'date-fns'; + export = lastDayOfYear; +} + +declare module 'date-fns/max' { + import {max} from 'date-fns'; + export = max; +} + +declare module 'date-fns/min' { + import {min} from 'date-fns'; + export = min; +} + +declare module 'date-fns/parse' { + import {parse} from 'date-fns'; + export = parse; +} + +declare module 'date-fns/set_date' { + import {setDate} from 'date-fns'; + export = setDate; +} + +declare module 'date-fns/set_day' { + import {setDay} from 'date-fns'; + export = setDay; +} + +declare module 'date-fns/set_day_of_year' { + import {setDayOfYear} from 'date-fns'; + export = setDayOfYear; +} + +declare module 'date-fns/set_hours' { + import {setHours} from 'date-fns'; + export = setHours; +} + +declare module 'date-fns/set_iso_week' { + import {setISOWeek} from 'date-fns'; + export = setISOWeek; +} + +declare module 'date-fns/set_iso_year' { + import {setISOYear} from 'date-fns'; + export = setISOYear; +} + +declare module 'date-fns/set_milliseconds' { + import {setMilliseconds} from 'date-fns'; + export = setMilliseconds; +} + +declare module 'date-fns/set_minutes' { + import {setMinutes} from 'date-fns'; + export = setMinutes; +} + +declare module 'date-fns/set_month' { + import {setMonth} from 'date-fns'; + export = setMonth; +} + +declare module 'date-fns/set_quarter' { + import {setQuarter} from 'date-fns'; + export = setQuarter; +} + +declare module 'date-fns/set_seconds' { + import {setSeconds} from 'date-fns'; + export = setSeconds; +} + +declare module 'date-fns/set_year' { + import {setYear} from 'date-fns'; + export = setYear; +} + +declare module 'date-fns/start_of_day' { + import {startOfDay} from 'date-fns'; + export = startOfDay; +} + +declare module 'date-fns/start_of_hour' { + import {startOfHour} from 'date-fns'; + export = startOfHour; +} + +declare module 'date-fns/start_of_iso_week' { + import {startOfISOWeek} from 'date-fns'; + export = startOfISOWeek; +} + +declare module 'date-fns/start_of_iso_year' { + import {startOfISOYear} from 'date-fns'; + export = startOfISOYear; +} + +declare module 'date-fns/start_of_minute' { + import {startOfMinute} from 'date-fns'; + export = startOfMinute; +} + +declare module 'date-fns/start_of_month' { + import {startOfMonth} from 'date-fns'; + export = startOfMonth; +} + +declare module 'date-fns/start_of_quarter' { + import {startOfQuarter} from 'date-fns'; + export = startOfQuarter; +} + +declare module 'date-fns/start_of_second' { + import {startOfSecond} from 'date-fns'; + export = startOfSecond; +} + +declare module 'date-fns/start_of_today' { + import {startOfToday} from 'date-fns'; + export = startOfToday; +} + +declare module 'date-fns/start_of_tomorrow' { + import {startOfTomorrow} from 'date-fns'; + export = startOfTomorrow; +} + +declare module 'date-fns/start_of_week' { + import {startOfWeek} from 'date-fns'; + export = startOfWeek; +} + +declare module 'date-fns/start_of_year' { + import {startOfYear} from 'date-fns'; + export = startOfYear; +} + +declare module 'date-fns/start_of_yesterday' { + import {startOfYesterday} from 'date-fns'; + export = startOfYesterday; +} + +declare module 'date-fns/sub_days' { + import {subDays} from 'date-fns'; + export = subDays; +} + +declare module 'date-fns/sub_hours' { + import {subHours} from 'date-fns'; + export = subHours; +} + +declare module 'date-fns/sub_iso_years' { + import {subISOYears} from 'date-fns'; + export = subISOYears; +} + +declare module 'date-fns/sub_milliseconds' { + import {subMilliseconds} from 'date-fns'; + export = subMilliseconds; +} + +declare module 'date-fns/sub_minutes' { + import {subMinutes} from 'date-fns'; + export = subMinutes; +} + +declare module 'date-fns/sub_months' { + import {subMonths} from 'date-fns'; + export = subMonths; +} + +declare module 'date-fns/sub_quarters' { + import {subQuarters} from 'date-fns'; + export = subQuarters; +} + +declare module 'date-fns/sub_seconds' { + import {subSeconds} from 'date-fns'; + export = subSeconds; +} + +declare module 'date-fns/sub_weeks' { + import {subWeeks} from 'date-fns'; + export = subWeeks; +} + +declare module 'date-fns/sub_years' { + import {subYears} from 'date-fns'; + export = subYears; +} + From 20e557ecad41d9a9e4af7fbab58f90366c72aa94 Mon Sep 17 00:00:00 2001 From: David Pires Date: Wed, 14 Sep 2016 12:44:54 +0100 Subject: [PATCH 048/212] Added type definitions for scrollreveal (#10855) * Added type definitions for scrollreveal * fixed implicit any * remove IScrollReveal --- scrollreveal/scrollreveal-tests.ts | 74 ++++++++++++++++++++++++++++++ scrollreveal/scrollreveal.d.ts | 68 +++++++++++++++++++++++++++ 2 files changed, 142 insertions(+) create mode 100644 scrollreveal/scrollreveal-tests.ts create mode 100644 scrollreveal/scrollreveal.d.ts diff --git a/scrollreveal/scrollreveal-tests.ts b/scrollreveal/scrollreveal-tests.ts new file mode 100644 index 0000000000..f0b205763d --- /dev/null +++ b/scrollreveal/scrollreveal-tests.ts @@ -0,0 +1,74 @@ +/// + +//Tests from https://github.com/jlmakes/scrollreveal.js + +//1.2 +var sr = ScrollReveal(); +sr.reveal('.foo'); +sr.reveal('.bar'); + +//1.3 +sr = ScrollReveal().reveal('.foo, .bar'); + +//2.1 +sr = ScrollReveal({ reset: true }); +sr.reveal('.foo', { duration: 200 }); + +//3.1 +sr = ScrollReveal({ duration: 2000 }); +sr.reveal('.box', 50); + +sr = ScrollReveal(); +sr.reveal('.box', { duration: 2000 }, 50); + +//3.2 +var fooReveal = { + delay : 200, + distance : '90px', + easing : 'ease-in-out', + rotate : { z: 10 }, + scale : 1.1 +}; + +sr = ScrollReveal(); +sr.reveal('.foo', fooReveal); +sr.reveal('#chocolate', { delay: 500, scale: 0.9 }); + +//3.3 +sr.reveal(document.getElementById('foo')); +sr.reveal(document.querySelectorAll('.bar')); + +//3.4 +sr = ScrollReveal(); +var fooContainer = document.getElementById('fooContainer'); +sr.reveal('.foo', { container: fooContainer }); +sr.reveal('.bar', { container: '#barContainer' }); + +//3.5 + +fooContainer = document.getElementById('fooContainer'); + +sr = ScrollReveal(); +sr.reveal('.foo', { container: fooContainer }); +var xmlhttp = new XMLHttpRequest(); +xmlhttp.onreadystatechange = function() { + if (xmlhttp.readyState == XMLHttpRequest.DONE) { + if (xmlhttp.status == 200) { + + // Turn our response into HTML... + var content = document.createElement('div'); + content.innerHTML = xmlhttp.responseText; + + // Add each element to the DOM... + for (var i = 0; i < content.childNodes.length; i++) { + fooContainer.appendChild(content.childNodes[ i ]); + }; + + // Finally! + sr.sync(); + } + } +} + +xmlhttp.open('GET', 'ajax.html', true); +xmlhttp.send(); \ No newline at end of file diff --git a/scrollreveal/scrollreveal.d.ts b/scrollreveal/scrollreveal.d.ts new file mode 100644 index 0000000000..d1478c8243 --- /dev/null +++ b/scrollreveal/scrollreveal.d.ts @@ -0,0 +1,68 @@ +// Type definitions for ScrollReveal +// Project: https://github.com/jlmakes/scrollreveal.js +// Definitions by: David Pires +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace scrollReveal { + interface ScrollRevealRotateObject { + x?: number; + y?: number; + z?: number; + } + + interface ScrollRevealPositionObject { + top?: number; + right?: number; + bottom?: number; + left?: number; + } + + interface ScrollRevealObjectOptions { + origin ? : string; + distance ? : string; + duration ? : number; + delay ? : number; + rotate ? : ScrollRevealRotateObject; + opacity ? : number; + scale ? : number; + easing ? : string; + container ? : any; + mobile ? : boolean; + reset ? : boolean; + useDelay ? : string; + viewFactor ? : number; + viewOffset ? : ScrollRevealPositionObject; + beforeReveal ? (domEl: HTMLElement): void; + afterReveal ? (domEl: HTMLElement): void; + beforeReset ? (domEl: HTMLElement): void; + afterReset ? (domEl: HTMLElement): void; + beforeReveal ? (domEl: NodeListOf): void; + afterReveal ? (domEl: NodeListOf): void; + beforeReset ? (domEl: NodeListOf): void; + afterReset ? (domEl: NodeListOf): void; + } + + + interface ScrollRevealObject { + (): ScrollRevealObject; + (options: ScrollRevealObjectOptions): ScrollRevealObject; + reveal(selector: string): ScrollRevealObject; + reveal(selector: string, interval: number): ScrollRevealObject; + reveal(selector: string, options: ScrollRevealObjectOptions): ScrollRevealObject; + reveal(selector: string, options: ScrollRevealObjectOptions, interval: number): ScrollRevealObject; + + reveal(selector: HTMLElement): ScrollRevealObject; + reveal(selector: HTMLElement, interval: number): ScrollRevealObject; + reveal(selector: HTMLElement, options: ScrollRevealObjectOptions): ScrollRevealObject; + reveal(selector: HTMLElement, options: ScrollRevealObjectOptions, interval: number): ScrollRevealObject; + + reveal(selector: NodeListOf): ScrollRevealObject; + reveal(selector: NodeListOf, interval: number): ScrollRevealObject; + reveal(selector: NodeListOf, options: ScrollRevealObjectOptions): ScrollRevealObject; + reveal(selector: NodeListOf, options: ScrollRevealObjectOptions, interval: number): ScrollRevealObject; + + sync(): void; + } +} + +declare var ScrollReveal: scrollReveal.ScrollRevealObject; \ No newline at end of file From be0ba281b67575b3b626a6bbb15b152add97244e Mon Sep 17 00:00:00 2001 From: Stefan Thomas Date: Wed, 14 Sep 2016 04:45:59 -0700 Subject: [PATCH 049/212] Fix typo for core-js/.../min-safe-integer (#11166) Fix a typo in the `core-js/(library/)fn/number/min-safe-integer` module name. --- core-js/core-js.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts index c633dc4ef6..1ad88ff41a 100644 --- a/core-js/core-js.d.ts +++ b/core-js/core-js.d.ts @@ -1889,7 +1889,7 @@ declare module "core-js/fn/number/max-safe-integer" { var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; export = MAX_SAFE_INTEGER; } -declare module "core-js/fn/number/min-safe-interger" { +declare module "core-js/fn/number/min-safe-integer" { var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; export = MIN_SAFE_INTEGER; } @@ -2668,7 +2668,7 @@ declare module "core-js/library/fn/number/max-safe-integer" { var MAX_SAFE_INTEGER: typeof core.Number.MAX_SAFE_INTEGER; export = MAX_SAFE_INTEGER; } -declare module "core-js/library/fn/number/min-safe-interger" { +declare module "core-js/library/fn/number/min-safe-integer" { var MIN_SAFE_INTEGER: typeof core.Number.MIN_SAFE_INTEGER; export = MIN_SAFE_INTEGER; } From 66d2cc80d8bb5ccfcf37b40e6197205f04182a15 Mon Sep 17 00:00:00 2001 From: "shinichi.kogai" Date: Wed, 14 Sep 2016 20:47:43 +0900 Subject: [PATCH 050/212] add point-in-polygon/point-in-polygon.d.ts (#11169) --- point-in-polygon/point-in-polygon-tests.ts | 6 ++++++ point-in-polygon/point-in-polygon.d.ts | 8 ++++++++ 2 files changed, 14 insertions(+) create mode 100644 point-in-polygon/point-in-polygon-tests.ts create mode 100644 point-in-polygon/point-in-polygon.d.ts diff --git a/point-in-polygon/point-in-polygon-tests.ts b/point-in-polygon/point-in-polygon-tests.ts new file mode 100644 index 0000000000..39851bd00e --- /dev/null +++ b/point-in-polygon/point-in-polygon-tests.ts @@ -0,0 +1,6 @@ +/// + +import inside from 'point-in-polygon'; + +const polygon = [ [ 1, 1 ], [ 1, 2 ], [ 2, 2 ], [ 2, 1 ] ]; +const inPolygon: boolean = inside([ 1.5, 1.5 ], polygon); diff --git a/point-in-polygon/point-in-polygon.d.ts b/point-in-polygon/point-in-polygon.d.ts new file mode 100644 index 0000000000..ceb85ecdec --- /dev/null +++ b/point-in-polygon/point-in-polygon.d.ts @@ -0,0 +1,8 @@ +// Type definitions for point-in-polygon +// Project: https://github.com/substack/point-in-polygon +// Definitions by: kogai +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'point-in-polygon' { + export default function inside(point: number[], polygon: number[][]): boolean; +} From 6f4b149a52e3b894b68c7181aada547e23beb58b Mon Sep 17 00:00:00 2001 From: Humberto Machado Date: Wed, 14 Sep 2016 09:04:16 -0300 Subject: [PATCH 051/212] Add _router definition in Application. Using to get all registred routes (#11006) --- express-serve-static-core/express-serve-static-core.d.ts | 5 +++++ 1 file changed, 5 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 93551ffece..e80ffa85a9 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -1046,6 +1046,11 @@ declare module "express-serve-static-core" { * simply by removing them from this object. */ routes: any; + + /** + * Using to all registered routes in Express Application + */ + _router: any; } interface Express extends Application { From 0a51f69a36bb73214cdadfacc06def3cb4ba762f Mon Sep 17 00:00:00 2001 From: ShMcK Date: Wed, 14 Sep 2016 05:13:51 -0700 Subject: [PATCH 052/212] Add `toThrowError` test matcher (#11171) Add `toThrowError` test docs. See Jest Docs [toThrowError](https://facebook.github.io/jest/docs/api.html#tothrowerror-error). --- jest/jest.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/jest/jest.d.ts b/jest/jest.d.ts index 10949a6691..b2484dfcc5 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -44,6 +44,7 @@ declare namespace jest { interface Matchers { not: Matchers; toThrow(expected?: any): boolean; + toThrowError(expected?: any): boolean; toBe(expected: any): boolean; toEqual(expected: any): boolean; toBeFalsy(): boolean; From 2affe4c63bc3f2a667804ffee4b8b00d74cadbc8 Mon Sep 17 00:00:00 2001 From: Jeongho Nam Date: Wed, 14 Sep 2016 21:14:17 +0900 Subject: [PATCH 053/212] TypeScript-STL v1.0.8 & Samchon-Framework v2.0 beta-8 (#11172) --- samchon-framework/samchon-framework.d.ts | 1466 +++++++++++++--------- typescript-stl/typescript-stl.d.ts | 1074 +++++++++------- 2 files changed, 1484 insertions(+), 1056 deletions(-) diff --git a/samchon-framework/samchon-framework.d.ts b/samchon-framework/samchon-framework.d.ts index a6d03758dd..70d9dda38f 100644 --- a/samchon-framework/samchon-framework.d.ts +++ b/samchon-framework/samchon-framework.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Samchon Framework v2.0.0-beta.1 +// Type definitions for Samchon Framework v2.0.0-beta.8 // Project: https://github.com/samchon/framework // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -82,19 +82,15 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.VectorIterator, n: number, val: T): std.VectorIterator; + protected _Insert_by_repeating_val(position: std.VectorIterator, n: number, val: T): std.VectorIterator; /** * @hidden */ - protected insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; - /** - * @inheritdoc - */ - pop_back(): void; + protected _Insert_by_range>(position: std.VectorIterator, begin: InputIterator, end: InputIterator): std.VectorIterator; /** * @hidden */ - protected erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; + protected _Erase_by_range(first: std.VectorIterator, last: std.VectorIterator): std.VectorIterator; /** * @hidden */ @@ -110,7 +106,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -126,28 +122,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -176,13 +172,9 @@ declare namespace samchon.library { * @reference https://developer.mozilla.org/en-US/docs/Web/API/Event * @author Jeongho Nam */ - class BasicEvent implements Event { - NONE: number; - CAPTURING_PHASE: number; - AT_TARGET: number; - BUBBLING_PHASE: number; - private type_; - private target_; + class BasicEvent { + protected type_: string; + protected target_: IEventDispatcher; private currentTarget_; protected trusted_: boolean; protected bubbles_: boolean; @@ -198,7 +190,6 @@ declare namespace samchon.library { /** * @inheritdoc */ - preventDefault(): void; /** * @inheritdoc */ @@ -256,22 +247,12 @@ declare namespace samchon.library { */ returnValue: boolean; } - class ProgressEvent extends library.BasicEvent { - static PROGRESS: string; - protected numerator_: number; - protected denominator_: number; - constructor(type: string, numerator: number, denominator: number); - numerator: number; - denominator: number; - } } declare namespace samchon.collection { /** * Type of function pointer for listener of {@link CollectionEvent CollectionEvents}. */ - interface CollectionEventListener extends EventListener { - (event: CollectionEvent): void; - } + type CollectionEventListener = (event: CollectionEvent) => void; } declare namespace samchon.collection { /** @@ -281,11 +262,13 @@ declare namespace samchon.collection { /** * @hidden */ - private first_; + protected first_: std.Iterator; /** * @hidden */ - private last_; + protected last_: std.Iterator; + private temporary_container_; + private origin_first_; /** * Initialization Constructor. * @@ -298,9 +281,9 @@ declare namespace samchon.collection { constructor(type: "erase", first: std.Iterator, last: std.Iterator); constructor(type: "refresh", first: std.Iterator, last: std.Iterator); /** - * Get associative container. + * Get associative target, the container. */ - container: ICollection; + target: ICollection; /** * Get range of the first. */ @@ -309,12 +292,19 @@ declare namespace samchon.collection { * Get range of the last. */ last: std.Iterator; + /** + * @inheritdoc + */ + preventDefault(): void; } } +/** + * @hidden + */ declare namespace samchon.collection.CollectionEvent { - const INSERT: string; - const ERASE: string; - const REFRESH: string; + const INSERT: "insert"; + const ERASE: "erase"; + const REFRESH: "refresh"; } declare namespace samchon.collection { /** @@ -357,11 +347,11 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.DequeIterator, n: number, val: T): std.DequeIterator; + protected _Insert_by_repeating_val(position: std.DequeIterator, n: number, val: T): std.DequeIterator; /** * @hidden */ - protected insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; + protected _Insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; /** * @inheritdoc */ @@ -369,7 +359,7 @@ declare namespace samchon.collection { /** * @hidden */ - protected erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; + protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; /** * @hidden */ @@ -385,7 +375,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -401,28 +391,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -462,11 +452,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ @@ -474,7 +464,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -490,31 +480,31 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener>): void; - addEventListener(type: "erase", listener: CollectionEventListener>): void; - addEventListener(type: "refresh", listener: CollectionEventListener>): void; + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener>): void; - removeEventListener(type: "erase", listener: CollectionEventListener>): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { @@ -544,11 +534,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ @@ -556,7 +546,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -572,31 +562,31 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener>): void; - addEventListener(type: "erase", listener: CollectionEventListener>): void; - addEventListener(type: "refresh", listener: CollectionEventListener>): void; + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener>): void; - removeEventListener(type: "erase", listener: CollectionEventListener>): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { @@ -623,6 +613,14 @@ declare namespace samchon.collection { * A chain object taking responsibility of dispatching events. */ private event_dispatcher_; + /** + * @inheritdoc + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ @@ -630,7 +628,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -646,28 +644,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -701,11 +699,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.SetIterator, last: std.SetIterator): void; + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.SetIterator, last: std.SetIterator): void; + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ @@ -713,7 +711,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -729,28 +727,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -830,32 +828,39 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } + /** + * @hidden + */ + namespace ICollection { + function _Dispatch_CollectionEvent(collection: ICollection, type: string, first: std.Iterator, last: std.Iterator): void; + function _Dispatch_MapCollectionEvent(collection: ICollection>, type: string, first: std.MapIterator, last: std.MapIterator): void; + } } declare namespace samchon.collection { /** @@ -908,11 +913,11 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.ListIterator, n: number, val: T): std.ListIterator; + protected _Insert_by_repeating_val(position: std.ListIterator, n: number, val: T): std.ListIterator; /** * @hidden */ - protected insert_by_range>(position: std.ListIterator, begin: InputIterator, end: InputIterator): std.ListIterator; + protected _Insert_by_range>(position: std.ListIterator, begin: InputIterator, end: InputIterator): std.ListIterator; /** * @inheritdoc */ @@ -924,7 +929,7 @@ declare namespace samchon.collection { /** * @hidden */ - protected erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; + protected _Erase_by_range(first: std.ListIterator, last: std.ListIterator): std.ListIterator; /** * @hidden */ @@ -940,7 +945,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -956,33 +961,46 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; } } +declare namespace samchon.collection { + type MapCollectionEventListener = (event: MapCollectionEvent) => void; + class MapCollectionEvent extends CollectionEvent> { + /** + * @inheritdoc + */ + first: std.MapIterator; + /** + * @inheritdoc + */ + last: std.MapIterator; + } +} declare namespace samchon.collection { /** * A {@link TreeMap} who can detect element I/O events. @@ -1017,11 +1035,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ @@ -1029,7 +1047,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1045,31 +1063,31 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener>): void; - addEventListener(type: "erase", listener: CollectionEventListener>): void; - addEventListener(type: "refresh", listener: CollectionEventListener>): void; + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener>): void; - removeEventListener(type: "erase", listener: CollectionEventListener>): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { @@ -1099,11 +1117,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_insert(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.MapIterator, last: std.MapIterator): void; + protected _Handle_erase(first: std.MapIterator, last: std.MapIterator): void; /** * @inheritdoc */ @@ -1111,7 +1129,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1127,31 +1145,31 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; - addEventListener(type: "insert", listener: CollectionEventListener>): void; - addEventListener(type: "erase", listener: CollectionEventListener>): void; - addEventListener(type: "refresh", listener: CollectionEventListener>): void; + addEventListener(type: string, listener: library.BasicEventListener): void; + addEventListener(type: "insert", listener: MapCollectionEventListener): void; + addEventListener(type: "erase", listener: MapCollectionEventListener): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; - addEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - addEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + addEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + addEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; - removeEventListener(type: "insert", listener: CollectionEventListener>): void; - removeEventListener(type: "erase", listener: CollectionEventListener>): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; - removeEventListener(type: "insert", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "erase", listener: CollectionEventListener>, thisArg: Object): void; - removeEventListener(type: "refresh", listener: CollectionEventListener>, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; + removeEventListener(type: "insert", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "erase", listener: MapCollectionEventListener, thisArg: Object): void; + removeEventListener(type: "refresh", listener: MapCollectionEventListener, thisArg: Object): void; } } declare namespace samchon.collection { @@ -1181,11 +1199,11 @@ declare namespace samchon.collection { /** * @inheritdoc */ - protected handle_insert(first: std.SetIterator, last: std.SetIterator): void; + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: std.SetIterator, last: std.SetIterator): void; + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ @@ -1193,7 +1211,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1209,28 +1227,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -1261,6 +1279,14 @@ declare namespace samchon.collection { * A chain object taking responsibility of dispatching events. */ private event_dispatcher_; + /** + * @inheritdoc + */ + protected _Handle_insert(first: std.SetIterator, last: std.SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: std.SetIterator, last: std.SetIterator): void; /** * @inheritdoc */ @@ -1268,7 +1294,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1284,28 +1310,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -1323,8 +1349,8 @@ declare namespace samchon.library { * *

Relationships between XML and XMLList

*
    - *
  • XML contains XMLList from dictionary of XMLList.
  • - *
  • XMLList contains XML from vector of XML.
  • + *
  • XML is std.HashMap
  • + *
  • XMLList is std.Deque
  • *
* *

Note

@@ -1337,17 +1363,28 @@ declare namespace samchon.library { * * * - * <memberList>
- *      <member id='jhnam88' name='Jeongho+Nam' birthdate='1988-03-11' />
- *      <member id='master' name='Administartor' birthdate='2011-07-28' />
- * </memberList> + * + * + * + * + * + * * * - * <member>
- *      <id>jhnam88</id>
- *      <name>Jeongho+Nam</name>
- *      <birthdate>1988-03-11</birthdate>
- * </member> + * + * + * + * jhnam88 + * Jeongho Nam + * 1988-03-11 + * + * + * master + * Administartor + * 2011-07-28 + * + * + * * * * @@ -1363,7 +1400,7 @@ declare namespace samchon.library { *
  • \<price high='1500' low='1300' open='1450' close='1320' /\>: tag => \"price\"
  • * */ - private tag; + private tag_; /** *

    Value of the XML.

    * @@ -1372,7 +1409,7 @@ declare namespace samchon.library { *
  • \: value => null
  • * */ - private value; + private value_; /** *

    Properties belongs to the XML.

    *

    A Dictionary of properties accessing each property by its key.

    @@ -1385,7 +1422,7 @@ declare namespace samchon.library { * {\"comment\", \"Hello. My name is Jeongho Nam \"}} * */ - private properties; + private property_map_; /** *

    Default Constructor.

    * @@ -1703,11 +1740,11 @@ declare namespace samchon.collection { /** * @hidden */ - protected insert_by_repeating_val(position: std.DequeIterator, n: number, val: library.XML): std.DequeIterator; + protected _Insert_by_repeating_val(position: std.DequeIterator, n: number, val: library.XML): std.DequeIterator; /** * @hidden */ - protected insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; + protected _Insert_by_range>(position: std.DequeIterator, begin: InputIterator, end: InputIterator): std.DequeIterator; /** * @inheritdoc */ @@ -1715,7 +1752,7 @@ declare namespace samchon.collection { /** * @hidden */ - protected erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; + protected _Erase_by_range(first: std.DequeIterator, last: std.DequeIterator): std.DequeIterator; /** * @hidden */ @@ -1731,7 +1768,7 @@ declare namespace samchon.collection { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ @@ -1747,28 +1784,28 @@ declare namespace samchon.collection { /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; addEventListener(type: "insert", listener: CollectionEventListener): void; addEventListener(type: "erase", listener: CollectionEventListener): void; addEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; addEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; addEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; removeEventListener(type: "insert", listener: CollectionEventListener): void; removeEventListener(type: "erase", listener: CollectionEventListener): void; removeEventListener(type: "refresh", listener: CollectionEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; removeEventListener(type: "insert", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "erase", listener: CollectionEventListener, thisArg: Object): void; removeEventListener(type: "refresh", listener: CollectionEventListener, thisArg: Object): void; @@ -1887,6 +1924,7 @@ declare namespace samchon.library { } } declare namespace samchon.library { + type BasicEventListener = (event: BasicEvent) => void; /** *

    The IEventDispatcher interface defines methods for adding or removing event listeners, checks * whether specific types of event listeners are registered, and dispatches events.

    @@ -1975,7 +2013,7 @@ declare namespace samchon.library { * This function must accept an Event object as its only parameter and must return * nothing. */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; /** *

    Registers an event listener object with an EventDispatcher object so that the listener * receives notification of an event. You can register event listeners on all nodes in the display @@ -2020,7 +2058,7 @@ declare namespace samchon.library { * nothing. * @param thisArg The object to be used as the this object. */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; /** * Removes a listener from the EventDispatcher object. If there is no matching listener registered * with the EventDispatcher object, a call to this method has no effect. @@ -2028,7 +2066,7 @@ declare namespace samchon.library { * @param type The type of event. * @param listener The listener object to remove. */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; /** * Removes a listener from the EventDispatcher object. If there is no matching listener registered * with the EventDispatcher object, a call to this method has no effect. @@ -2037,7 +2075,7 @@ declare namespace samchon.library { * @param listener The listener object to remove. * @param thisArg The object to be used as the this object. */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; } /** *

    Registers an event listener object with an EventDispatcher object so that the listener @@ -2091,7 +2129,7 @@ declare namespace samchon.library { /** * Container of listeners. */ - protected event_listeners_: std.HashMap>>; + protected event_listeners_: std.HashMap>>; /** * Default Constructor. */ @@ -2109,23 +2147,23 @@ declare namespace samchon.library { /** * @inheritdoc */ - dispatchEvent(event: Event): boolean; + dispatchEvent(event: library.BasicEvent): boolean; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener): void; + addEventListener(type: string, listener: library.BasicEventListener): void; /** * @inheritdoc */ - addEventListener(type: string, listener: EventListener, thisArg: Object): void; + addEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: library.BasicEventListener): void; /** * @inheritdoc */ - removeEventListener(type: string, listener: EventListener, thisArg: Object): void; + removeEventListener(type: string, listener: library.BasicEventListener, thisArg: Object): void; } } declare namespace samchon.library { @@ -2247,6 +2285,10 @@ declare namespace samchon.library { *

    */ modificationDate: Date; + /** + * @hidden + */ + _Set_file(val: File): void; /** *

    Displays a file-browsing dialog box that lets the user select a file to upload. The dialog box is native * to the user's browser system. The user can select a file on the local computer or from other systems, for @@ -2418,7 +2460,7 @@ declare namespace samchon.library { /** * Whether each element (Gene) is unique in their GeneArray. */ - private unique; + private unique_; /** * Rate of mutation. * @@ -2432,11 +2474,11 @@ declare namespace samchon.library { * * */ - private mutation_rate; + private mutation_rate_; /** * Number of tournaments in selection. */ - private tournament; + private tournament_; /** * Initialization Constructor. * @@ -2567,7 +2609,7 @@ declare namespace samchon.library { /** * Genes representing the population. */ - private children; + private children_; /** *

    A comparison function returns whether left gene is more optimal, greater.

    * @@ -2586,7 +2628,7 @@ declare namespace samchon.library { *

    If you don't want to follow the rule or want a custom comparison function, you have to realize a * comparison function.

    */ - private compare; + private compare_; /** *

    Private constructor with population.

    * @@ -2622,6 +2664,7 @@ declare namespace samchon.library { * @param compare A comparison function returns whether left gene is more optimal. */ constructor(geneArray: GeneArray, size: number, compare: (left: GeneArray, right: GeneArray) => boolean); + _Get_children(): std.Vector; /** * Test fitness of each GeneArray in the {@link population}. * @@ -2924,6 +2967,13 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } + /** + * @hidden + */ + namespace IEntity { + function construct(entity: IEntity, xml: library.XML, ...prohibited_names: string[]): void; + function toXML(entity: IEntity, ...prohibited_names: string[]): library.XML; + } /** *

    An entity, a standard data class.

    * @@ -3104,7 +3154,8 @@ declare namespace samchon.protocol { /** * Close connection. */ - close(): any; + close(): void; + isConnected(): boolean; sendData(invoke: protocol.Invoke): void; replyData(invoke: protocol.Invoke): void; } @@ -3114,19 +3165,20 @@ declare namespace samchon.protocol { /** * @hidden */ - protected listener: IProtocol; + protected listener_: IProtocol; /** * @inheritdoc */ onClose: Function; + protected connected_: boolean; /** * @hidden */ - private binary_invoke; + private binary_invoke_; /** * @hidden */ - private binary_parameters; + private binary_parameters_; /** * @hidden */ @@ -3135,11 +3187,20 @@ declare namespace samchon.protocol { * Default Constructor. */ constructor(); + /** + * Construct from listener. + * + * @param listener An {@link IProtocol} object to listen {@link Invoke} messages. + */ constructor(listener: IProtocol); /** * @inheritdoc */ abstract close(): void; + /** + * @inheritdoc + */ + isConnected(): boolean; protected is_binary_invoke(): boolean; abstract sendData(invoke: Invoke): void; replyData(invoke: Invoke): void; @@ -3148,27 +3209,27 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { - class Communicator extends CommunicatorBase { + abstract class Communicator extends CommunicatorBase { /** * @hidden */ - protected socket: socket.socket; + protected socket_: socket.socket; /** * @hidden */ - private header_bytes; + private header_bytes_; /** * @hidden */ - private data; + private data_; /** * @hidden */ - private data_index; + private data_index_; /** * @hidden */ - private listening; + private listening_; /** * @inheritdoc */ @@ -3223,11 +3284,11 @@ declare namespace samchon.protocol { * * @author Jeongho Nam */ - class WebCommunicator extends CommunicatorBase { + abstract class WebCommunicator extends CommunicatorBase { /** * Connection driver, a socket for web-socket. */ - protected connection: websocket.connection; + protected connection_: websocket.connection; /** * Close the connection. */ @@ -3249,8 +3310,8 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { - class SharedWorkerCommunicator extends CommunicatorBase { - protected port: MessagePort; + abstract class SharedWorkerCommunicator extends CommunicatorBase { + protected port_: MessagePort; close(): void; /** * @inheritdoc @@ -3481,12 +3542,12 @@ declare namespace samchon.protocol { /** * Requested path. */ - private path; + private path_; /** * Session ID, an identifier of the remote client. */ - private session_id; - private listening; + private session_id_; + private listening_; /** * Initialization Constructor. * @@ -3556,6 +3617,11 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { + /** + * A container of entity, and it's a type of entity, too. + * + * @author Jeongho Nam + */ interface IEntityGroup extends IEntity, std.base.IContainer { /** *

    Construct data of the Entity from an XML object.

    @@ -3578,6 +3644,7 @@ declare namespace samchon.protocol { * * @return A new child Entity belongs to EntityArray. */ + createChild(xml: library.XML): T; /** *

    Get iterator to element.

    * @@ -3644,6 +3711,24 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } + /** + * @hidden + */ + namespace IEntityGroup { + /** + * @hidden + */ + function construct(entityGroup: IEntityGroup, xml: library.XML, ...prohibited_names: string[]): void; + /** + * @hidden + */ + function toXML(entityGroup: IEntityGroup, ...prohibited_names: string[]): library.XML; + function has(entityGroup: IEntityGroup, key: any): boolean; + function count(entityGroup: IEntityGroup, key: any): number; + function get(entityGroup: IEntityGroup, key: any): T; + } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3653,22 +3738,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3694,6 +3770,8 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3703,22 +3781,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3744,6 +3813,8 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3753,22 +3824,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3801,6 +3863,8 @@ declare namespace samchon.protocol { */ interface IEntityCollection extends IEntityGroup, collection.ICollection { } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3810,22 +3874,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3851,6 +3906,8 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3860,22 +3917,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -3901,6 +3949,8 @@ declare namespace samchon.protocol { */ toXML(): library.XML; } +} +declare namespace samchon.protocol { /** * @inheritdoc */ @@ -3910,22 +3960,13 @@ declare namespace samchon.protocol { */ construct(xml: library.XML): void; /** - *

    Factory method of a child Entity.

    - * - *

    EntityArray::createChild() is a factory method creating a new child Entity which is belonged - * to the EntityArray. This method is called by EntityArray::construct(). The children construction - * methods Entity::construct() will be called by abstract method of the EntityArray::construct().

    - * - * @return A new child Entity belongs to EntityArray. + * @inheritdoc */ - protected abstract createChild(xml: library.XML): T; + abstract createChild(xml: library.XML): T; /** * @inheritdoc */ key(): any; - /** - * @inheritdoc - */ /** * @inheritdoc */ @@ -4232,7 +4273,7 @@ declare namespace samchon.protocol { /** *

    Listener, represent function's name.

    */ - protected listener: string; + private listener; /** * Default Constructor. */ @@ -4254,7 +4295,7 @@ declare namespace samchon.protocol { /** * @inheritdoc */ - protected createChild(xml: library.XML): InvokeParameter; + createChild(xml: library.XML): InvokeParameter; /** * Get listener. */ @@ -4322,10 +4363,10 @@ declare namespace samchon.protocol { * @inheritdoc */ construct(xml: library.XML): void; - setValue(value: number): any; - setValue(value: string): any; - setValue(value: library.XML): any; - setValue(value: Uint8Array): any; + setValue(value: number): void; + setValue(value: string): void; + setValue(value: library.XML): void; + setValue(value: Uint8Array): void; /** * @inheritdoc */ @@ -4365,25 +4406,31 @@ declare namespace samchon.protocol { /** * */ - private startTime; + private start_time_; /** * */ - private endTime; + private end_time_; /** * Default Constructor. */ constructor(); constructor(invoke: Invoke); construct(xml: library.XML): void; - notifyEnd(): void; + complete(): void; key(): number; getUID(): number; getListener(): string; getStartTime(): Date; getEndTime(): Date; computeElapsedTime(): number; + /** + * @inheritdoc + */ TAG(): string; + /** + * @inheritdoc + */ toXML(): library.XML; toInvoke(): Invoke; } @@ -4525,15 +4572,15 @@ declare namespace samchon.protocol { /** * A server handler. */ - private http_server; + private http_server_; /** * Sequence number for issuing session id. */ - private sequence; + private sequence_; /** * @hidden */ - private my_port; + private my_port_; /** * Default Constructor. */ @@ -4685,7 +4732,7 @@ declare namespace samchon.protocol { * @author Jeongho Nam */ class ServerBase extends Server implements IServerBase { - private target; + private target_; constructor(target: IServer); addClient(driver: IClientDriver): void; } @@ -4730,7 +4777,7 @@ declare namespace samchon.protocol { * @author Jeongho Nam */ class WebServerBase extends WebServer implements IServerBase { - private target; + private target_; constructor(target: IServer); addClient(driver: IClientDriver): void; } @@ -4776,7 +4823,7 @@ declare namespace samchon.protocol { * @author Jeongho Nam */ class SharedWorkerServerBase extends SharedWorkerServer implements IServerBase { - private target; + private target_; constructor(target: IServer); addClient(driver: IClientDriver): void; } @@ -4849,13 +4896,13 @@ declare namespace samchon.protocol { * *

    Note that, {@link socket} is only used in web-browser environment.

    */ - private browser_socket; + private browser_socket_; /** *

    A driver for server connection.

    * *

    Note that, {@link node_client} is only used in NodeJS environment.

    */ - private node_client; + private node_client_; /** * @inheritdoc */ @@ -4889,11 +4936,17 @@ declare namespace samchon.protocol { } } declare namespace samchon.protocol { + /** + * @hidden + */ namespace socket { type socket = any; type server = any; type http_server = any; } + /** + * @hidden + */ namespace websocket { type connection = any; type request = any; @@ -4902,14 +4955,42 @@ declare namespace samchon.protocol { type client = any; } } +declare namespace samchon.protocol.distributed { + class DSInvokeHistory extends InvokeHistory { + private system_; + private role_; + /** + * Construct from a DistributedSystem. + * + * @param system + */ + constructor(system: DistributedSystem); + /** + * Initilizer Constructor. + * + * @param system + * @param role + * @param invoke + */ + constructor(system: DistributedSystem, role: DistributedSystemRole, invoke: Invoke); + /** + * @inheritdoc + */ + construct(xml: library.XML): void; + getSystem(): DistributedSystem; + getRole(): DistributedSystemRole; + /** + * @inheritdoc + */ + toXML(): library.XML; + } +} declare namespace samchon.protocol.external { /** - *

    An external system driver.

    + *

    A role of an external system.

    * - *

    The {@link ExternalSystem} class represents an external system, connected and interact with this system. - * {@link ExternalSystem} takes full charge of network communication with external system have connected. - * Replied {@link Invoke messages} from the external system is shifted to and processed in, children elements of this - * class, {@link ExternalSystemRole} objects.

    + *

    The {@link ExternalSystemRole} class represents a role, what to do in an {@link ExternalSystem}. + * Extends this class and writes some methods related to the role.

    * *
    * - *

    Bridge & Proxy Pattern

    - *

    The {@link ExternalSystem} class can be a bridge for logical proxy. In framework within user, - * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + *

    Proxy Pattern

    + *

    The {@link ExternalSystemRole} class can be an logical proxy. In framework within user, which + * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not * important. Only interested in user's perspective is which can be done.

    * *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged @@ -4936,197 +5017,81 @@ declare namespace samchon.protocol.external { * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the * external system. * - *

  • Those strategy is called Bridge Pattern and Proxy Pattern.
  • + *
  • Those strategy is called Proxy Pattern.
  • * * * @author Jeongho Nam */ - abstract class ExternalSystem extends EntityDequeCollection implements IProtocol { + abstract class ExternalSystemRole extends Entity implements IProtocol { /** - * A network communicator with external system. + * An {@link ExternalSystem external system} containing this {@link ExternalSystemRole role}. */ + private system; /** - * A network communicator with external system. - */ - protected communicator: ICommunicator; - /** - * The name represents external system have connected. + *

    A name, represents and identifies this {@link ExternalSystemRole role}.

    + * + *

    This {@link name} is an identifier represents this {@link ExternalSystemRole role}. This {@link name} is + * used in {@link ExternalSystemArray.getRole} and {@link ExternalSystem.get}, as a key elements. Thus, this + * {@link name} should be unique in an {@link ExternalSystemArray}. */ protected name: string; /** - * Default Constructor. - */ - constructor(); - /** - * Construct from an IClientDriver object. + * Constructor from a system. * - * @param driver + * @param system An external system containing this role. */ - constructor(driver: IClientDriver); + constructor(system: ExternalSystem); /** - * Default Destructor. - */ - destructor(): void; - /** - * Identifier of {@link ExternalSystem} is its {@link name}. + * Identifier of {@link ExternalSystemRole} is its {@link name}. */ key(): string; /** - * Get {@link name}. + * Get external system, this role is belonged to. + */ + getSystem(): ExternalSystem; + /** + * Get name, who represents and identifies this role. */ getName(): string; - close(): void; /** - * Send {@link Invoke} message to external system. + * Send an {@link Invoke} message to the external system via {@link system}. * - * @param invoke An {@link Invoke} message to send. + * @param invoke An {@link Invoke} message to send to the external system. */ sendData(invoke: Invoke): void; /** - * Handle an {@Invoke} message have received. + *

    Handle replied {@link Invoke message} from the {@link system external system} belonged to.

    * - * @param invoke An {@link Invoke} message have received. + *

    This {@link replyData replyData()} will call a member method named following {@link Invoke.listener}. + * in the invoke.

    + * + * @param invoke An {@link Invoke} message received from the {@link system external system}. */ replyData(invoke: Invoke): void; /** - * Tag name of the {@link ExternalSytem} in {@link XML}. - * - * @return system. - */ - TAG(): string; - /** - * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSytem} in {@link XML}. + * Tag name of the {@link ExternalSytemRole} in {@link XML}. * * @return role. */ - CHILD_TAG(): string; - /** - * @inheritdoc - */ - toXML(): library.XML; - /** - * @hidden - */ - private communicator_; - /** - * @hidden - */ - private external_system_array_; - /** - * @hidden - */ - private erasing_; - /** - * @hidden - */ - private external_system_array; - /** - * @hidden - */ - private handle_close(); - } -} -declare namespace samchon.protocol.parallel { - /** - *

    An external parallel system driver.

    - * - * - * - * @author Jeongho Nam - */ - abstract class ParallelSystem extends external.ExternalSystem { - /** - * A manager containing this {@link ParallelSystem} object. - */ - private systemArray; - /** - * A list of {@link Invoke} messages on process. - * - * @see {@link performance} - */ - private progress_list; - /** - * A list of {@link Invoke} messages had processed. - * - * @see {@link performance} - */ - private history_list; - /** - *

    Performance index.

    - * - *

    A performance index that indicates how much fast the connected parallel system is.

    - * - *

    If this {@link ParallelSystem parallel system} hasn't any {@link Invoke} message - * {@link history_list had handled}, then the {@link performance performance index} will be 1, which means - * default and average value between all {@link ParallelSystem} instances (belonged to a same - * {@link ParallelSystemArray} object).

    - * - *

    You can specify this {@link performance} by yourself, but notice that, if the - * {@link performance performance index} is higher then other {@link ParallelSystem} objects, then this - * {@link ParallelSystem parallel system} will ordered to handle more processes than other {@link ParallelSystem} - * objects. Otherwise, the {@link performance performance index) is lower than others, of course, less processes - * will be delivered.

    - * - *

    This {@link performance index} is always re-calculated whenever {@link ParallelSystemArray} calls one of - * them below.

    - * - *
      - *
    • {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()}
    • - *
    • {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()}
    • - *
    - * - *

    If this class is a type of {@link DistributedSystem}, a derived class from the {@link ParallelSystem}, - * then {@link DistributedSystemRole.sendData DistributedSystem.sendData()} also cause the re-calculation.

    - * - * @see {@link progress_list}, {@link history_list} - */ - protected performance: number; - /** - * Construct from a {@link ParallelSystemArray}. - * - * @param systemArray A manager containing this {@link ParallelSystem} object. - * @param communicator A communicator who takes full charge of network communication with the external - * parallel system. - */ - constructor(systemArray: ParallelSystemArray, communicator?: ICommunicator); - /** - * Get manager of this object, {@link systemArray}. - * - * @return A manager containing this {@link ParallelSystem} object. - */ - getSystemArray(): ParallelSystemArray; - /** - * Get {@link performant performance index}. - * - * A performance index that indicates how much fast the connected parallel system is. - */ - getPerformance(): number; - /** - * Send an {@link Invoke} message with index of segmentation. - * - * @param invoke An invoke message requesting parallel process. - * @param first Initial piece's index in a section. - * @param last Final piece's index in a section. The ranged used is [first, last), which contains - * all the pieces' indices between first and last, including the piece pointed by index - * first, but not the piece pointed by the index last. - * - * @see {@link ParallelSystemArray.sendPieceData} - */ - private send_piece_data(invoke, first, last); - /** - * - * - * @param xml - * - * @see {@link ParallelSystemArray.notify_end} - */ - private report_invoke_history(xml); + TAG(): string; } } declare namespace samchon.protocol.distributed { - abstract class DistributedSystem extends parallel.ParallelSystem { + abstract class DistributedSystemRole extends external.ExternalSystemRole { + private system_array_; + private progress_list_; + private history_list_; + protected performance: number; + constructor(systemArray: DistributedSystemArray); + getSystemArray(): DistributedSystemArray; + getPerformance(): number; + sendData(invoke: protocol.Invoke): void; + _Report_history(history: DSInvokeHistory): void; } } +/** + * [[include: https://raw.githubusercontent.com/samchon/framework/master/handbook/TypeScript-Protocol-External_System.md]] + */ declare namespace samchon.protocol.external { /** *

    An array and manager of {@link ExternalSystem external systems}.

    @@ -5175,23 +5140,15 @@ declare namespace samchon.protocol.external { * * @author Jeongho Nam */ - abstract class ExternalSystemArray extends EntityArrayCollection implements IProtocol { + abstract class ExternalSystemArray extends EntityDequeCollection implements IProtocol { /** * Default Constructor. */ constructor(); - /** - * @hidden - */ - private handle_system_insert(event); /** * @hidden */ private handle_system_erase(event); - /** - * @hidden - */ - protected handle_system_close(system: ExternalSystem): void; /** * Test whether this system array has the role. * @@ -5244,13 +5201,25 @@ declare namespace samchon.protocol.parallel { */ abstract class ParallelSystemArray extends external.ExternalSystemArray { /** - * @see {@link ParallelSystem.progress_list}, {@link ParallelSystem.history_list} + * @hidden */ - private history_sequence; + private history_sequence_; /** * Default Constructor. */ constructor(); + /** + * @inheritdoc + */ + at(index: number): ParallelSystem; + /** + * @hidden + */ + _Fetch_history_sequence(): number; + /** + * @hidden + */ + _Set_history_sequence(val: number): void; /** * * @param invoke An invoke message requesting parallel process. @@ -5272,27 +5241,145 @@ declare namespace samchon.protocol.parallel { * @param history * * @return Whether the processes with same uid are all fininsed. - * - * @see {@link ParallelSystem.report_invoke_history}, {@link normalize_performance} */ - protected notify_end(history: PRInvokeHistory): boolean; + _Complete_history(history: InvokeHistory): boolean; /** - * @see {@link ParallelSystem.performance} + * @hidden */ private normalize_performance(); } } declare namespace samchon.protocol.distributed { abstract class DistributedSystemArray extends parallel.ParallelSystemArray { - protected roles: std.HashMap; + /** + * @hidden + */ + private role_map_; + /** + * Default Constructor. + */ + constructor(); + construct(xml: library.XML): void; + abstract createRole(xml: library.XML): DistributedSystemRole; + /** + * @inheritdoc + */ + at(index: number): DistributedSystem; + getRoleMap(): std.HashMap; + /** + * @inheritdoc + */ + hasRole(name: string): boolean; + /** + * @inheritdoc + */ + getRole(name: string): DistributedSystemRole; + insertRole(role: DistributedSystemRole): void; + eraseRole(name: string): void; + toXML(): library.XML; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedClientArray extends DistributedSystemArray implements external.IExternalClientArray { + /** + * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + *

    Factory method creating {@link IServerBase} object.

    + * + *

    This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol.

    + * + *

    Creates and returns one of them:

    + *
      + *
    • {@link ServerBase}
    • + *
    • {@link WebServerBase}
    • + *
    • {@link SharedWorkerServerBase}
    • + *
    + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + createChild(xml: library.XML): DistributedSystem; + protected abstract createExternalClient(driver: IClientDriver): DistributedSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedSystemArrayMediator extends DistributedSystemArray { + private mediator_; + /** + * Default Constructor. + */ + constructor(); + protected abstract createMediator(): parallel.MediatorSystem; + protected startMediator(): void; + getMediator(): parallel.MediatorSystem; + _Complete_history(history: parallel.PRInvokeHistory): boolean; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedClientArrayMediator extends DistributedSystemArrayMediator implements external.IExternalClientArray { + /** + * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. + */ + private server_base_; + /** + * Default Constructor. + */ + constructor(); + /** + *

    Factory method creating {@link IServerBase} object.

    + * + *

    This method {@link createServerBase createServerBase()} determines which protocol is used in this server, + * {@link ExternalClientArray}. If the protocol is determined, then {@link ExternalSystem external clients} who + * may connect to {@link ExternalClientArray this server} must follow the specified protocol.

    + * + *

    Creates and returns one of them:

    + *
      + *
    • {@link ServerBase}
    • + *
    • {@link WebServerBase}
    • + *
    • {@link SharedWorkerServerBase}
    • + *
    + * + * @return A new {@link IServerBase} object. + */ + protected abstract createServerBase(): IServerBase; + addClient(driver: IClientDriver): void; + createChild(xml: library.XML): DistributedSystem; + protected abstract createExternalClient(driver: IClientDriver): DistributedSystem; + /** + * @inheritdoc + */ + open(port: number): void; + /** + * @inheritdoc + */ + close(): void; } } declare namespace samchon.protocol.external { /** - *

    A role of an external system.

    + *

    An external system driver.

    * - *

    The {@link ExternalSystemRole} class represents a role, what to do in an {@link ExternalSystem}. - * Extends this class and writes some methods related to the role.

    + *

    The {@link ExternalSystem} class represents an external system, connected and interact with this system. + * {@link ExternalSystem} takes full charge of network communication with external system have connected. + * Replied {@link Invoke messages} from the external system is shifted to and processed in, children elements of this + * class, {@link ExternalSystemRole} objects.

    * *

    @@ -5300,9 +5387,9 @@ declare namespace samchon.protocol.external { * style="max-width: 100%" /> *

    * - *

    Proxy Pattern

    - *

    The {@link ExternalSystemRole} class can be an logical proxy. In framework within user, which - * {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not + *

    Bridge & Proxy Pattern

    + *

    The {@link ExternalSystem} class can be a bridge for logical proxy. In framework within user, + * which {@link ExternalSystem external system} is connected with {@link ExternalSystemArray this system}, it's not * important. Only interested in user's perspective is which can be done.

    * *

    By using the logical proxy, user dont't need to know which {@link ExternalSystemRole role} is belonged @@ -5319,68 +5406,249 @@ declare namespace samchon.protocol.external { * {@link ExternalSystemRole.sendData ExternalSystemRole.sendData()}. Then, the message will be sent to the * external system. * - *

  • Those strategy is called Proxy Pattern.
  • + *
  • Those strategy is called Bridge Pattern and Proxy Pattern.
  • * * * @author Jeongho Nam */ - abstract class ExternalSystemRole extends Entity implements IProtocol { + abstract class ExternalSystem extends EntityDequeCollection implements IProtocol { /** - * An {@link ExternalSystem external system} containing this {@link ExternalSystemRole role}. + * The name represents external system have connected. */ - private system; + protected name: string; /** - *

    A name, represents and identifies this {@link ExternalSystemRole role}.

    - * - *

    This {@link name} is an identifier represents this {@link ExternalSystemRole role}. This {@link name} is - * used in {@link ExternalSystemArray.getRole} and {@link ExternalSystem.get}, as a key elements. Thus, this - * {@link name} should be unique in an {@link ExternalSystemArray}. + * @hidden */ - private name; + private system_array_; /** - * Constructor from a system. - * - * @param system An external system containing this role. + * @hidden */ - constructor(system: ExternalSystem); + private communicator_; + constructor(systemArray: ExternalSystemArray); + constructor(systemArray: ExternalSystemArray, communicator: IClientDriver); /** - * Identifier of {@link ExternalSystemRole} is its {@link name}. + * Default Destructor. + */ + destructor(): void; + /** + * @hidden + */ + private handle_close(); + getSystemArray(): ExternalSystemArray; + /** + * Identifier of {@link ExternalSystem} is its {@link name}. */ key(): string; /** - * Get external system, this role is belonged to. - */ - getSystem(): ExternalSystem; - /** - * Get name, who represents and identifies this role. + * Get {@link name}. */ getName(): string; + protected communicator: protocol.ICommunicator; + close(): void; /** - * Send an {@link Invoke} message to the external system via {@link system}. + * Send {@link Invoke} message to external system. * - * @param invoke An {@link Invoke} message to send to the external system. + * @param invoke An {@link Invoke} message to send. */ sendData(invoke: Invoke): void; /** - *

    Handle replied {@link Invoke message} from the {@link system external system} belonged to.

    + * Handle an {@Invoke} message has received. * - *

    This {@link replyData replyData()} will call a member method named following {@link Invoke.listener}. - * in the invoke.

    - * - * @param invoke An {@link Invoke} message received from the {@link system external system}. + * @param invoke An {@link Invoke} message have received. */ replyData(invoke: Invoke): void; /** - * Tag name of the {@link ExternalSytemRole} in {@link XML}. + * Tag name of the {@link ExternalSytem} in {@link XML}. + * + * @return system. + */ + TAG(): string; + /** + * Tag name of {@link ExternalSystemRole children elements} belonged to the {@link ExternalSytem} in {@link XML}. * * @return role. */ - TAG(): string; + CHILD_TAG(): string; + } +} +declare namespace samchon.protocol.parallel { + /** + *

    An external parallel system driver.

    + * + * + * + * @author Jeongho Nam + */ + abstract class ParallelSystem extends external.ExternalSystem { + /** + * @hidden + */ + private progress_list_; + /** + * @hidden + */ + private history_list_; + /** + *

    Performance index.

    + * + *

    A performance index that indicates how much fast the connected parallel system is.

    + * + *

    If this {@link ParallelSystem parallel system} hasn't any {@link Invoke} message had handled, then the + * {@link performance performance index} will be 1, which means default and average value between all + * {@link ParallelSystem} instances (belonged to a same {@link ParallelSystemArray} object).

    + * + *

    You can specify this {@link performance} by yourself, but notice that, if the + * {@link performance performance index} is higher then other {@link ParallelSystem} objects, then this + * {@link ParallelSystem parallel system} will ordered to handle more processes than other + * {@link ParallelSystem} objects. Otherwise, the {@link performance performance index) is lower than others, + * of course, less processes will be delivered.

    + * + *

    This {@link performance index} is always re-calculated whenever {@link ParallelSystemArray} calls one of + * them below.

    + * + *
      + *
    • {@link ParallelSystemArray.sendSegmentData ParallelSystemArray.sendSegmentData()}
    • + *
    • {@link ParallelSystemArray.sendPieceData ParallelSystemArray.sendPieceData()}
    • + *
    + * + *

    If this class is a type of {@link DistributedSystem} derived class from the {@link ParallelSystem}, + * then {@link DistributedSystemRole.sendData DistributedSystemRole.sendData()} also cause the re-calculation. + *

    + */ + protected performance: number; + constructor(systemArray: ParallelSystemArray); + constructor(systemArray: ParallelSystemArray, communicator: IClientDriver); + destructor(): void; + /** + * Get manager of this object, {@link systemArray}. + * + * @return A manager containing this {@link ParallelSystem} object. + */ + getSystemArray(): ParallelSystemArray; + /** + * Get {@link performant performance index}. + * + * A performance index that indicates how much fast the connected parallel system is. + */ + getPerformance(): number; + _Get_progress_list(): std.HashMap>; + _Get_history_list(): std.HashMap; + _Set_performance(val: number): void; + /** + * @hidden + */ + _Send_piece_data(invoke: Invoke, first: number, last: number): void; + /** + * @hidden + */ + private _replyData(invoke); + /** + * + * + * @param xml + * + * @see {@link ParallelSystemArray.notify_complete} + */ + protected _Report_history(xml: library.XML): void; } } declare namespace samchon.protocol.distributed { - abstract class DistributedSystemRole extends external.ExternalSystemRole { - private systems; + abstract class DistributedSystem extends parallel.ParallelSystem { + destructor(): void; + createChild(xml: library.XML): external.ExternalSystemRole; + /** + * Get manager of this object. + * + * @return A manager containing this {@link DistributedSystem} objects. + */ + getSystemArray(): DistributedSystemArray; + /** + * @inheritdoc + */ + has(key: string): boolean; + /** + * @inheritdoc + */ + get(key: string): DistributedSystemRole; + replyData(invoke: protocol.Invoke): void; + protected _Report_history(xml: library.XML): void; + } +} +declare namespace samchon.protocol.distributed { + interface IDistributedServer extends DistributedSystem, external.IExternalServer { + /** + * @inheritdoc + */ + getSystemArray(): DistributedSystemArray; + /** + * @inheritdoc + */ + has(key: string): boolean; + /** + * @inheritdoc + */ + get(key: string): DistributedSystemRole; + } + abstract class DistributedServer extends DistributedSystem implements external.IExternalServer { + protected ip: string; + protected port: number; + constructor(systemArray: DistributedSystemArray); + protected abstract createServerConnector(): IServerConnector; + connect(): void; + getIP(): string; + getPort(): number; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedServerArray extends DistributedSystemArray implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedServerArrayMediator extends DistributedSystemArrayMediator implements external.IExternalServerArray { + /** + * Default Constructor. + */ + constructor(); + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedServerClientArray extends DistributedClientArray implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + createChild(xml: library.XML): DistributedSystem; + protected abstract createExternalServer(xml: library.XML): IDistributedServer; + /** + * @inheritdoc + */ + connect(): void; + } +} +declare namespace samchon.protocol.distributed { + abstract class DistributedServerClientArrayMediator extends DistributedClientArrayMediator implements external.IExternalServerClientArray { + /** + * Default Constructor. + */ + constructor(); + createChild(xml: library.XML): DistributedSystem; + protected abstract createExternalServer(xml: library.XML): IDistributedServer; + /** + * @inheritdoc + */ + connect(): void; } } declare namespace samchon.protocol.external { @@ -5454,7 +5722,7 @@ declare namespace samchon.protocol.external { /** * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. */ - private server_base; + private server_base_; /** * Default Constructor. */ @@ -5482,7 +5750,7 @@ declare namespace samchon.protocol.external { * * @return null. */ - protected createChild(xml: library.XML): ExternalSystem; + createChild(xml: library.XML): ExternalSystem; /** * Factory method creating {@link ExternalSystem} object. * @@ -5528,18 +5796,7 @@ declare namespace samchon.protocol.external { * @author Jeongho Nam */ interface IExternalServer extends ExternalSystem { - /** - * Connect to the external system. - */ connect(): void; - /** - * Get ip address. - */ - getIP(): string; - /** - * Get port number. - */ - getPort(): number; } /** *

    An external server driver.

    @@ -5591,7 +5848,7 @@ declare namespace samchon.protocol.external { /** * Default Constructor. */ - constructor(); + constructor(systemArray: ExternalSystemArray); /** * Factory method creating server connector. */ @@ -5779,7 +6036,7 @@ declare namespace samchon.protocol.external { * * @return A new child Entity via {@link createExternalServer createExternalServer()}. */ - protected createChild(xml: library.XML): ExternalSystem; + createChild(xml: library.XML): ExternalSystem; /** * Factory method creating an {@link IExternalServer} object. * @@ -5795,33 +6052,34 @@ declare namespace samchon.protocol.external { } } declare namespace samchon.protocol.slave { - abstract class SlaveSystem extends external.ExternalSystem { + abstract class SlaveSystem implements protocol.IProtocol { + protected communicator_: ICommunicator; /** * Default Constructor. */ constructor(); + sendData(invoke: Invoke): void; + protected _replyData(invoke: Invoke): void; replyData(invoke: Invoke): void; } } -declare namespace samchon.protocol.external { +declare namespace samchon.protocol.parallel { abstract class MediatorSystem extends slave.SlaveSystem { - private system_array; - private progress_list; - constructor(systemArray: ExternalSystemArray); + private mediator_; + private progress_list_; + constructor(systemArray: ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator); abstract start(): void; - /** - * @hidden - */ - protected createChild(xml: library.XML): ExternalSystemRole; - private notify_end(uid); + getMediator(): ParallelSystemArrayMediator | distributed.DistributedSystemArrayMediator; + _Complete_history(uid: number): void; + protected _replyData(invoke: Invoke): void; replyData(invoke: protocol.Invoke): void; } } -declare namespace samchon.protocol.external { - class MediatorServer extends MediatorSystem implements IServer { - private server_base; +declare namespace samchon.protocol.parallel { + class MediatorServer extends MediatorSystem implements slave.ISlaveServer { + private server_base_; private port; - constructor(systemArray: ExternalSystemArray, port: number); + constructor(systemArray: ParallelSystemArrayMediator, port: number); protected createServerBase(): IServerBase; addClient(driver: IClientDriver): void; start(): void; @@ -5829,17 +6087,23 @@ declare namespace samchon.protocol.external { close(): void; } class MediatorWebServer extends MediatorServer { + /** + * @inheritdoc + */ protected createServerBase(): IServerBase; } class MediatorSharedWorkerServer extends MediatorServer { + /** + * @inheritdoc + */ protected createServerBase(): IServerBase; } } -declare namespace samchon.protocol.external { - class MediatorClient extends MediatorSystem implements IExternalServer { +declare namespace samchon.protocol.parallel { + class MediatorClient extends MediatorSystem implements slave.ISlaveClient { protected ip: string; protected port: number; - constructor(systemArray: ExternalSystemArray, ip: string, port: number); + constructor(systemArray: ParallelSystemArrayMediator, ip: string, port: number); protected createServerConnector(): IServerConnector; getIP(): string; getPort(): number; @@ -5881,6 +6145,8 @@ declare namespace samchon.protocol.parallel { constructor(invoke: Invoke); getFirst(): number; getLast(): number; + _Set_first(val: number): void; + _Set_last(val: number): void; /** * Compute number of allocated pieces. */ @@ -5892,7 +6158,7 @@ declare namespace samchon.protocol.parallel { /** * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. */ - private server_base; + private server_base_; /** * Default Constructor. */ @@ -5915,7 +6181,7 @@ declare namespace samchon.protocol.parallel { */ protected abstract createServerBase(): IServerBase; addClient(driver: IClientDriver): void; - protected createChild(xml: library.XML): ParallelSystem; + createChild(xml: library.XML): ParallelSystem; protected abstract createExternalClient(driver: IClientDriver): ParallelSystem; /** * @inheritdoc @@ -5929,16 +6195,15 @@ declare namespace samchon.protocol.parallel { } declare namespace samchon.protocol.parallel { abstract class ParallelSystemArrayMediator extends ParallelSystemArray { - protected mediator: external.MediatorSystem; + private mediator_; /** * Default Constructor. */ constructor(); - protected abstract createMediator(): external.MediatorSystem; + protected abstract createMediator(): MediatorSystem; protected start_mediator(): void; - sendData(invoke: protocol.Invoke): void; - sendPieceData(invoke: protocol.Invoke, first: number, last: number): void; - protected notify_end(history: PRInvokeHistory): boolean; + getMediator(): MediatorSystem; + _Complete_history(history: PRInvokeHistory): boolean; } } declare namespace samchon.protocol.parallel { @@ -5946,7 +6211,7 @@ declare namespace samchon.protocol.parallel { /** * A subrogator of {@link IServer server}'s role instead of this {@link ExternalClientArray}. */ - private server_base; + private server_base_; /** * Default Constructor. */ @@ -5969,7 +6234,7 @@ declare namespace samchon.protocol.parallel { */ protected abstract createServerBase(): IServerBase; addClient(driver: IClientDriver): void; - protected createChild(xml: library.XML): ParallelSystem; + createChild(xml: library.XML): ParallelSystem; protected abstract createExternalClient(driver: IClientDriver): ParallelSystem; /** * @inheritdoc @@ -5982,9 +6247,13 @@ declare namespace samchon.protocol.parallel { } } declare namespace samchon.protocol.parallel { - interface IParallelServer extends ParallelSystem, external.IExternalServer { + interface IParallelServer extends external.IExternalServer, ParallelSystem { + /** + * @inheritdoc + */ + getSystemArray(): ParallelSystemArray; } - abstract class ParallelServer extends ParallelSystem implements IParallelServer { + abstract class ParallelServer extends ParallelSystem implements external.IExternalServer { protected ip: string; protected port: number; constructor(systemArray: ParallelSystemArray); @@ -6003,6 +6272,9 @@ declare namespace samchon.protocol.parallel { declare namespace samchon.protocol.parallel { abstract class ParallelServerArrayMediator extends ParallelSystemArrayMediator implements external.IExternalServerArray { constructor(); + /** + * @inheritdoc + */ connect(): void; } } @@ -6012,7 +6284,7 @@ declare namespace samchon.protocol.parallel { * Default Constructor. */ constructor(); - protected createChild(xml: library.XML): ParallelSystem; + createChild(xml: library.XML): ParallelSystem; protected abstract createExternalServer(xml: library.XML): IParallelServer; connect(): void; } @@ -6023,7 +6295,7 @@ declare namespace samchon.protocol.parallel { * Default Constructor. */ constructor(); - protected createChild(xml: library.XML): ParallelSystem; + createChild(xml: library.XML): ParallelSystem; protected abstract createExternalServer(xml: library.XML): IParallelServer; /** * @inheritdoc @@ -6033,10 +6305,10 @@ declare namespace samchon.protocol.parallel { } declare namespace samchon.protocol.service { abstract class Client implements protocol.IProtocol { - private user; - private service; - private driver; - private no; + private user_; + private service_; + private communicator_; + private no_; /** * Construct from an User and WebClientDriver. */ @@ -6045,6 +6317,8 @@ declare namespace samchon.protocol.service { close(): void; getUser(): User; getService(): Service; + getNo(): number; + _Set_no(val: number): void; sendData(invoke: protocol.Invoke): void; replyData(invoke: protocol.Invoke): void; protected changeService(path: string): void; @@ -6052,8 +6326,8 @@ declare namespace samchon.protocol.service { } declare namespace samchon.protocol.service { abstract class Server extends protocol.WebServer implements IProtocol { - private session_map; - private account_map; + private session_map_; + private account_map_; /** * Default Constructor. */ @@ -6066,16 +6340,20 @@ declare namespace samchon.protocol.service { protected abstract createUser(): User; has(account: string): boolean; get(account: string): User; + /** + * @hidden + */ + _Get_account_map(): std.HashMap; sendData(invoke: protocol.Invoke): void; replyData(invoke: protocol.Invoke): void; addClient(driver: WebClientDriver): void; - private erase_user(user); + _Erase_user(user: User): void; } } declare namespace samchon.protocol.service { abstract class Service implements protocol.IProtocol { - private client; - private path; + private client_; + private path_; /** * Default Constructor. */ @@ -6095,39 +6373,75 @@ declare namespace samchon.protocol.service { } declare namespace samchon.protocol.service { abstract class User extends collection.HashMapCollection implements protocol.IProtocol { - private server; - private session_id; - private sequence; - private account_id; - private authority; + private server_; + private session_id_; + private sequence_; + private account_id_; + private authority_; /** * Construct from a Server. */ constructor(server: Server); protected abstract createClient(driver: WebClientDriver): Client; + /** + * @hidden + */ + _Create_child(driver: WebClientDriver): Client; + /** + * @hidden + */ private handle_erase_client(event); getServer(): Server; getAccountID(): string; getAuthority(): number; setAccount(id: string, authority: number): void; + /** + * @hidden + */ + _Get_session_id(): string; + /** + * @hidden + */ + _Fetch_sequence(): number; + /** + * @hidden + */ + _Set_session_id(val: string): void; sendData(invoke: protocol.Invoke): void; replyData(invoke: protocol.Invoke): void; } } declare namespace samchon.protocol.slave { - abstract class SlaveClient extends SlaveSystem { + interface ISlaveClient extends SlaveSystem { + connect(ip: string, port: number): void; + } + abstract class SlaveClient extends SlaveSystem implements ISlaveClient { + /** + * Default Constructor. + */ constructor(); + /** + * @inheritdoc + */ protected abstract createServerConnector(): IServerConnector; + /** + * @inheritdoc + */ connect(ip: string, port: number): void; } } declare namespace samchon.protocol.slave { - abstract class SlaveServer extends SlaveSystem implements IServer { - private server_base; + interface ISlaveServer extends SlaveSystem, IServer { + } + abstract class SlaveServer extends SlaveSystem implements ISlaveServer { + private server_base_; constructor(); protected abstract createServerBase(): IServerBase; - addClient(driver: IClientDriver): void; open(port: number): void; close(): void; + addClient(driver: IClientDriver): void; } } +declare namespace samchon.test { + function test_collection(): void; +} diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/typescript-stl.d.ts index 96d22ceb8f..36ad79e4a1 100644 --- a/typescript-stl/typescript-stl.d.ts +++ b/typescript-stl/typescript-stl.d.ts @@ -1,4 +1,4 @@ -// Type definitions for TypeScript-STL v1.0.1 +// Type definitions for TypeScript-STL v1.0.8 // Project: https://github.com/samchon/typescript-stl // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -2984,7 +2984,7 @@ declare namespace std { /** * @hidden */ - protected abstract create_neighbor(): This; + protected abstract create_neighbor(base: Base): This; /** *

    Get value of the iterator is pointing.

    * @@ -3292,7 +3292,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: base.IContainer); + constructor(container: Deque); /** *

    Range Constructor.

    * @@ -3339,6 +3339,10 @@ declare namespace std { * @inheritdoc */ size(): number; + /** + * @inheritdoc + */ + empty(): boolean; /** * @inheritdoc */ @@ -3360,11 +3364,9 @@ declare namespace std { */ back(): T; /** - *

    Fetch row and column's index.

    - * - *

    Fetches index of row and column of {@link matrix_} from sequence number.

    - * - * @param index Sequence number + // Fetch row and column's index. + /** + * @hidden */ private fetch_index(index); /** @@ -3418,11 +3420,11 @@ declare namespace std { /** * @hidden */ - protected insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; + protected _Insert_by_repeating_val(position: DequeIterator, n: number, val: T): DequeIterator; /** * @hidden */ - protected insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; + protected _Insert_by_range>(position: DequeIterator, begin: InputIterator, end: InputIterator): DequeIterator; /** * @hidden */ @@ -3446,15 +3448,29 @@ declare namespace std { /** * @hidden */ - protected erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; + protected _Erase_by_range(first: DequeIterator, last: DequeIterator): DequeIterator; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link Deque container} object with same type of elements. Sizes and container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link Deque container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container Deque}. + */ + swap(obj: Deque): void; /** * @inheritdoc */ swap(obj: base.IContainer): void; - /** - * @hidden - */ - private swap_deque(obj); } } declare namespace std { @@ -3556,7 +3572,10 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): DequeReverseIterator; + protected create_neighbor(base: DequeIterator): DequeReverseIterator; + /** + * @inheritdoc + */ /** * Set value of the iterator is pointing to. * @@ -4438,7 +4457,7 @@ declare namespace std.base { * * @author Jeongho Nam */ - abstract class MapContainer extends base.Container> { + abstract class MapContainer extends Container> { /** *

    {@link List} storing elements.

    * @@ -4447,45 +4466,11 @@ declare namespace std.base { * by storing {@link ListIterator iterators} ({@link MapIterator} references {@link ListIterator}) who are * created from {@link data_ here}.

    */ - protected data_: List>; + private data_; /** * Default Constructor. */ constructor(); - /** - * Construct from elements. - */ - constructor(items: Array>); - /** - * Contruct from tuples. - * - * @param array Tuples to be contained. - */ - constructor(array: Array<[Key, T]>); - /** - * Copy Constructor. - */ - constructor(container: IContainer>); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator>, end: Iterator>); - /** - * @hidden - */ - protected init(): void; - /** - * @hidden - */ - protected construct_from_array(items: Array | [Key, T]>): void; - /** - * @hidden - */ - protected construct_from_container(container: IContainer>): void; - /** - * @hidden - */ - protected construct_from_range>>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -4595,6 +4580,7 @@ declare namespace std.base { * Return the number of elements in the map. */ size(): number; + protected _Get_data(): List>; /** * @inheritdoc */ @@ -4670,7 +4656,7 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_pair(pair: Pair): any; + protected abstract _Insert_by_pair(pair: Pair): any; /** * @hidden */ @@ -4678,7 +4664,7 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected abstract _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ @@ -4686,7 +4672,7 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected abstract _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** *

    Erase an elemet by key.

    * @@ -4785,7 +4771,7 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_insert(first: MapIterator, last: MapIterator): void; + protected abstract _Handle_insert(first: MapIterator, last: MapIterator): void; /** *

    Abstract method handling deletions for indexing.

    * @@ -4806,7 +4792,11 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_erase(first: MapIterator, last: MapIterator): void; + protected abstract _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + * @hidden + */ + protected _Swap(obj: MapContainer): void; } } declare namespace std { @@ -4899,7 +4889,7 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): MapReverseIterator; + protected create_neighbor(base: MapIterator): MapReverseIterator; /** * Get first, key element. */ @@ -5160,24 +5150,6 @@ declare namespace std.base { * @hidden */ private insert_or_assign_with_hint(hint, key, value); - /** - *

    Swap content.

    - * - *

    Exchanges the content of the container by the content of obj, which is another - * {@link UniqueMap map} of the same type. Sizes abd container type may differ.

    - * - *

    After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

    - * - *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

    - * - * @param obj Another {@link UniqueMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link UniqueMap container}. - */ - swap(obj: UniqueMap): void; } } declare namespace std.base { @@ -5268,24 +5240,6 @@ declare namespace std.base { * @inheritdoc */ insert>>(first: InputIterator, last: InputIterator): void; - /** - *

    Swap content.

    - * - *

    Exchanges the content of the container by the content of obj, which is another - * {@link UniqueMap map} of the same type. Sizes abd container type may differ.

    - * - *

    After the call to this member function, the elements in this container are those which were - * in obj before the call, and the elements of obj are those which were in this. All - * iterators, references and pointers remain valid for the swapped objects.

    - * - *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that - * algorithm with an optimization that behaves like this member function.

    - * - * @param obj Another {@link MultiMap map container} of the same type of elements as this (i.e., - * with the same template parameters, Key and T) whose content is swapped - * with that of this {@link MultiMap container}. - */ - swap(obj: MultiMap): void; } } declare namespace std.HashMap { @@ -5348,13 +5302,27 @@ declare namespace std { */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array>): void; + constructor(items: Pair[]); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); /** * @inheritdoc */ @@ -5426,31 +5394,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link HashMap map} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link HashMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMap container}. + */ + swap(obj: HashMap): void; /** * @inheritdoc */ - swap(obj: base.UniqueMap): void; - /** - * @hidden - */ - private swap_hash_map(obj); + swap(obj: base.IContainer>): void; } } declare namespace std.HashMultiMap { @@ -5461,15 +5443,15 @@ declare namespace std { /** *

    Hashed, unordered Multimap.

    * - *

    {@link HashMap}s are associative containers that store elements formed by the combination of - * a key value and a mapped value, much like {@link HashMap} containers, but allowing + *

    {@link HashMultiMap}s are associative containers that store elements formed by the combination of + * a key value and a mapped value, much like {@link HashMultiMap} containers, but allowing * different elements to have equivalent keys.

    * - *

    In an {@link HashMap}, the key value is generally used to uniquely identify the + *

    In an {@link HashMultiMap}, the key value is generally used to uniquely identify the * element, while the mapped value is an object with the content associated to this key. * Types of key and mapped value may differ.

    * - *

    Internally, the elements in the {@link HashMap} are not sorted in any particular order with + *

    Internally, the elements in the {@link HashMultiMap} are not sorted in any particular order with * respect to either their key or mapped values, but organized into buckets depending on * their hash values to allow for fast access to individual elements directly by their key values * (with a constant average time complexity on average).

    @@ -5500,9 +5482,9 @@ declare namespace std { * * * @param Type of the key values. - * Each element in an {@link HashMap} is identified by a key value. + * Each element in an {@link HashMultiMap} is identified by a key value. * @param Type of the mapped value. - * Each element in an {@link HashMap} is used to store some data as its mapped value. + * Each element in an {@link HashMultiMap} is used to store some data as its mapped value. * * @reference http://www.cplusplus.com/reference/unordered_map/unordered_multimap * @author Jeongho Nam @@ -5513,13 +5495,27 @@ declare namespace std { */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array>): void; + constructor(items: Pair[]); + /** + * Contruct from tuples. + * + * @param array Tuples to be contained. + */ + constructor(array: [Key, T][]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiMap); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator>, end: Iterator>); /** * @inheritdoc */ @@ -5595,31 +5591,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiMap map} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link HashMultiMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiMap container}. + */ + swap(obj: HashMultiMap): void; /** * @inheritdoc */ - swap(obj: base.MultiMap): void; - /** - * @hidden - */ - private swap_hash_multimap(obj); + swap(obj: base.IContainer>): void; } } declare namespace std.base { @@ -5666,39 +5676,11 @@ declare namespace std.base { * by storing {@link ListIterator iterators} ({@link SetIterator} references {@link ListIterator}) who are * created from {@link data_ here}.

    */ - protected data_: List; + private data_; /** * Default Constructor. */ constructor(); - /** - * Construct from elements. - */ - constructor(items: Array); - /** - * Copy Constructor. - */ - constructor(container: IContainer); - /** - * Construct from range iterators. - */ - constructor(begin: Iterator, end: Iterator); - /** - * @hidden - */ - protected init(): void; - /** - * @hidden - */ - protected construct_from_array(items: Array): void; - /** - * @hidden - */ - protected construct_from_container(container: IContainer): void; - /** - * @hidden - */ - protected construct_from_range>(begin: InputIterator, end: InputIterator): void; /** * @inheritdoc */ @@ -5762,6 +5744,10 @@ declare namespace std.base { * @inheritdoc */ size(): number; + /** + * @hidden + */ + _Get_data(): List; /** * @inheritdoc */ @@ -5805,15 +5791,15 @@ declare namespace std.base { /** * @hidden */ - protected abstract insert_by_val(val: T): any; + protected abstract _Insert_by_val(val: T): any; /** * @hidden */ - protected abstract insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected abstract _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected abstract insert_by_range>(begin: InputIterator, end: InputIterator): void; + protected abstract _Insert_by_range>(begin: InputIterator, end: InputIterator): void; /** *

    Erase an element.

    *

    Removes from the set container the elements whose value is key.

    @@ -5886,7 +5872,7 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_insert(first: SetIterator, last: SetIterator): void; + protected abstract _Handle_insert(first: SetIterator, last: SetIterator): void; /** *

    Abstract method handling deletions for indexing.

    * @@ -5907,7 +5893,11 @@ declare namespace std.base { * [first, last), which contains all the elements between first and last, * including the element pointed by first but not the element pointed by last. */ - protected abstract handle_erase(first: SetIterator, last: SetIterator): void; + protected abstract _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + * @hidden + */ + protected _Swap(obj: SetContainer): void; } } declare namespace std { @@ -5990,7 +5980,7 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): SetReverseIterator; + protected create_neighbor(base: SetIterator): SetReverseIterator; } } declare namespace std.base { @@ -6055,10 +6045,6 @@ declare namespace std.base { * @inheritdoc */ insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - swap(obj: MultiSet): void; } } declare namespace std.HashMultiSet { @@ -6070,7 +6056,7 @@ declare namespace std { *

    Hashed, unordered Multiset.

    * *

    {@link HashMultiSet HashMultiSets} are containers that store elements in no particular order, allowing fast - * retrieval of individual elements based on their value, much like {@link HashSet} containers, + * retrieval of individual elements based on their value, much like {@link HashMultiSet} containers, * but allowing different elements to have equivalent values.

    * *

    In an {@link HashMultiSet}, the value of an element is at the same time its key, used to @@ -6116,13 +6102,21 @@ declare namespace std { */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array): void; + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashMultiSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ @@ -6198,31 +6192,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; + protected _Insert_by_val(val: T): any; /** * @hidden */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: SetIterator, last: SetIterator): void; + protected _Handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: SetIterator, last: SetIterator): void; + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link HashMultiSet set} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link HashMultiSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashMultiSet container}. + */ + swap(obj: HashMultiSet): void; /** * @inheritdoc */ - swap(obj: base.MultiSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); + swap(obj: base.IContainer): void; } } declare namespace std.base { @@ -6344,10 +6352,6 @@ declare namespace std.base { * @inheritdoc */ insert>(begin: InputIterator, end: InputIterator): void; - /** - * @inheritdoc - */ - swap(obj: UniqueSet): void; } } declare namespace std.HashSet { @@ -6399,19 +6403,27 @@ declare namespace std { * @reference http://www.cplusplus.com/reference/unordered_set/unordered_set * @author Jeongho Nam */ - class HashSet extends base.UniqueSet { + class HashSet extends base.UniqueSet implements base.IHashSet { /** * @hidden */ private hash_buckets_; /** - * @hidden + * Default Constructor. */ - protected init(): void; + constructor(); /** - * @hidden + * Construct from elements. */ - protected construct_from_array(items: Array): void; + constructor(items: T[]); + /** + * Copy Constructor. + */ + constructor(container: HashSet); + /** + * Construct from range iterators. + */ + constructor(begin: Iterator, end: Iterator); /** * @inheritdoc */ @@ -6483,31 +6495,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; + protected _Insert_by_val(val: T): any; /** * @hidden */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: SetIterator, last: SetIterator): void; + protected _Handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: SetIterator, last: SetIterator): void; + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link HashSet set} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link HashSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link HashSet container}. + */ + swap(obj: HashSet): void; /** * @inheritdoc */ - swap(obj: base.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); + swap(obj: base.IContainer): void; } } declare namespace std.List { @@ -6563,15 +6589,15 @@ declare namespace std { /** * @hidden */ - protected begin_: ListIterator; + private begin_; /** * @hidden */ - protected end_: ListIterator; + private end_; /** * @hidden */ - protected size_: number; + private size_; /** *

    Default Constructor.

    * @@ -6604,7 +6630,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: base.IContainer); + constructor(container: List); /** *

    Range Constructor.

    * @@ -6794,11 +6820,11 @@ declare namespace std { /** * @hidden */ - protected insert_by_repeating_val(position: ListIterator, size: number, val: T): ListIterator; + protected _Insert_by_repeating_val(position: ListIterator, size: number, val: T): ListIterator; /** * @hidden */ - protected insert_by_range>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; + protected _Insert_by_range>(position: ListIterator, begin: InputIterator, end: InputIterator): ListIterator; /** *

    Erase an element.

    * @@ -6868,7 +6894,7 @@ declare namespace std { /** * @hidden */ - protected erase_by_range(first: ListIterator, last: ListIterator): ListIterator; + protected _Erase_by_range(first: ListIterator, last: ListIterator): ListIterator; /** *

    Remove duplicate values.

    * @@ -7105,14 +7131,28 @@ declare namespace std { * @hidden */ private partition(first, last, compare); + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link List container} object with same type of elements. Sizes and container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link List container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container List}. + */ + swap(obj: List): void; /** * @inheritdoc */ swap(obj: base.IContainer): void; - /** - * @hidden - */ - private swap_list(obj); } } declare namespace std { @@ -7142,14 +7182,6 @@ declare namespace std { * @param value Value to be stored in the node (iterator). */ constructor(source: List, prev: ListIterator, next: ListIterator, value: T); - /** - * @inheritdoc - */ - set_prev(it: ListIterator): void; - /** - * @inheritdoc - */ - set_next(next: ListIterator): void; private list(); /** * @inheritdoc @@ -7172,6 +7204,14 @@ declare namespace std { * @param val Value to set. */ value: T; + /** + * @hidden + */ + _Set_prev(it: ListIterator): void; + /** + * @hidden + */ + _Set_next(it: ListIterator): void; /** * @inheritdoc */ @@ -7204,7 +7244,10 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): ListReverseIterator; + protected create_neighbor(base: ListIterator): ListReverseIterator; + /** + * @inheritdoc + */ /** * Set value of the iterator is pointing to. * @@ -7213,6 +7256,192 @@ declare namespace std { value: T; } } +declare namespace std { + /** + *

    Priority queue.

    + * + *

    {@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its + * first element is always the greatest of the elements it contains, according to some strict weak ordering + * criterion.

    + * + *

    This context is similar to a heap, where elements can be inserted at any moment, and only the + * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

    + * + *

    {@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that + * use an encapsulated object of a specific container class as its {@link container_ underlying container}, + * providing a specific set of member functions to access its elements. Elements are popped from the "back" + * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

    + * + *

    The {@link container_ underlying container} may be any of the standard container class templates or some + * other specifically designed container class. The container shall be accessible through + * {@link IArrayIterator random access iterators} and support the following operations:

    + * + *
      + *
    • empty()
    • + *
    • size()
    • + *
    • front()
    • + *
    • push_back()
    • + *
    • pop_back()
    • + *
    + * + *

    The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if + * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard + * container {@link Vector} is used.

    + * + *

    Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally + * at all times. This is done automatically by the container adaptor by automatically calling the algorithm + * functions make_heap, push_heap and pop_heap when needed.

    + * + * @param Type of the elements. + * + * @reference http://www.cplusplus.com/reference/queue/priority_queue/ + * @author Jeongho Nam + */ + class PriorityQueue { + /** + *

    The underlying container for implementing the priority queue.

    + * + *

    Following standard definition from the C++ committee, the underlying container should be one of + * {@link Vector} or {@link Deque}, however, I've adopted {@link TreeMultiSet} instead of them. Of course, + * there are proper reasons for adapting the {@link TreeMultiSet} even violating standard advice.

    + * + *

    Underlying container of {@link PriorityQueue} must keep a condition; the highest (or lowest) + * element must be placed on the terminal node for fast retrieval and deletion. To keep the condition with + * {@link Vector} or {@link Deque}, lots of times will only be spent for re-arranging elements. It calls + * rearrangement functions like make_heap, push_heap and pop_head for rearrangement.

    + * + *

    However, the {@link TreeMultiSet} container always keeps arrangment automatically without additional + * operations and it even meets full criteria of {@link PriorityQueue}. Those are the reason why I've adopted + * {@link TreeMultiSet} as the underlying container of {@link PriorityQueue}.

    + */ + private container_; + /** + * Default Constructor. + */ + constructor(); + /** + * Construct from compare. + * + * @param compare A binary predicate determines order of elements. + */ + constructor(compare: (left: T, right: T) => boolean); + /** + * Contruct from elements. + * + * @param array Elements to be contained. + */ + constructor(array: Array); + /** + * Contruct from elements with compare. + * + * @param array Elements to be contained. + * @param compare A binary predicate determines order of elements. + */ + constructor(array: Array, compare: (left: T, right: T) => boolean); + /** + * Copy Constructor. + */ + constructor(container: base.IContainer); + /** + * Copy Constructor with compare. + * + * @param container A container to be copied. + * @param compare A binary predicate determines order of elements. + */ + constructor(container: base.IContainer, compare: (left: T, right: T) => boolean); + /** + * Range Constructor. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + */ + constructor(begin: Iterator, end: Iterator); + /** + * Range Constructor with compare. + * + * @param begin Input interator of the initial position in a sequence. + * @param end Input interator of the final position in a sequence. + * @param compare A binary predicate determines order of elements. + */ + constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); + /** + *

    Return size.

    + * + *

    Returns the number of elements in the {@link PriorityQueue}.

    + * + *

    This member function effectively calls member {@link IArray.size size} of the + * {@link container_ underlying container} object.

    + * + * @return The number of elements in the underlying + */ + size(): number; + /** + *

    Test whether container is empty.

    + * + *

    Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

    + * + *

    This member function effectively calls member {@link IARray.empty empty} of the + * {@link container_ underlying container} object.

    + */ + empty(): boolean; + /** + *

    Access top element.

    + * + *

    Returns a constant reference to the top element in the {@link PriorityQueue}.

    + * + *

    The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is + * removed from the container when {@link PriorityQueue.pop} is called.

    + * + *

    This member function effectively calls member {@link IArray.front front} of the + * {@link container_ underlying container} object.

    + * + * @return A reference to the top element in the {@link PriorityQueue}. + */ + top(): T; + /** + *

    Insert element.

    + * + *

    Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to + * val. + * + *

    This member function effectively calls the member function {@link IArray.push_back push_back} of the + * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling + * the push_heap algorithm on the range that includes all the elements of the

    + * + * @param val Value to which the inserted element is initialized. + */ + push(val: T): void; + /** + *

    Remove top element.

    + * + *

    Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. + * The element removed is the one with the highest (or lowest) value.

    + * + *

    The value of this element can be retrieved before being popped by calling member + * {@link PriorityQueue.top}.

    + * + *

    This member function effectively calls the pop_heap algorithm to keep the heap property of + * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of + * the {@link container_ underlying container} object to remove the element.

    + */ + pop(): void; + /** + *

    Swap contents.

    + * + *

    Exchanges the contents of the container adaptor by those of obj, swapping both the + * {@link container_ underlying container} value and their comparison function using the corresponding + * {@link std.swap swap} non-member functions (unqualified).

    + * + *

    This member function has a noexcept specifier that matches the combined noexcept of the + * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison + * functions.

    + * + * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same + * template parameters, T). Sizes may differ. + */ + swap(obj: PriorityQueue): void; + } +} declare namespace std { /** *

    FIFO queue.

    @@ -7349,204 +7578,6 @@ declare namespace std { swap(obj: Queue): void; } } -declare namespace std { - /** - *

    Priority queue.

    - * - *

    {@link PriorityQueue Priority queues} are a type of container adaptors, specifically designed such that its - * first element is always the greatest of the elements it contains, according to some strict weak ordering - * criterion.

    - * - *

    This context is similar to a heap, where elements can be inserted at any moment, and only the - * max heap element can be retrieved (the one at the top in the {@link PriorityQueue priority queue}).

    - * - *

    {@link PriorityQueue Priority queues} are implemented as container adaptors, which are classes that - * use an encapsulated object of a specific container class as its {@link container_ underlying container}, - * providing a specific set of member functions to access its elements. Elements are popped from the "back" - * of the specific container, which is known as the top of the {@link PriorityQueue Priority queue}.

    - * - *

    The {@link container_ underlying container} may be any of the standard container class templates or some - * other specifically designed container class. The container shall be accessible through - * {@link IArrayIterator random access iterators} and support the following operations:

    - * - *
      - *
    • empty()
    • - *
    • size()
    • - *
    • front()
    • - *
    • push_back()
    • - *
    • pop_back()
    • - *
    - * - *

    The standard container classes {@link Vector} and {@link Deque} fulfill these requirements. By default, if - * no container class is specified for a particular {@link PriorityQueue} class instantiation, the standard - * container {@link Vector} is used.

    - * - *

    Support of {@link IArrayIterator random access iterators} is required to keep a heap structure internally - * at all times. This is done automatically by the container adaptor by automatically calling the algorithm - * functions make_heap, push_heap and pop_heap when needed.

    - * - * @param Type of the elements. - * - * @reference http://www.cplusplus.com/reference/queue/priority_queue/ - * @author Jeongho Nam - */ - class PriorityQueue { - /** - *

    The underlying container for implementing the priority queue.

    - * - *

    Following standard definition from the C++ committee, the underlying container should be one of - * {@link Vector} or {@link Deque}, however, I've adopted {@link TreeMultiSet} instead of them. Of course, - * there are proper reasons for adapting the {@link TreeMultiSet} even violating standard advice.

    - * - *

    Underlying container of {@link PriorityQueue} must keep a condition; the highest (or lowest) - * element must be placed on the terminal node for fast retrieval and deletion. To keep the condition with - * {@link Vector} or {@link Deque}, lots of times will only be spent for re-arranging elements. It calls - * rearrangement functions like make_heap, push_heap and pop_head for rearrangement.

    - * - *

    However, the {@link TreeMultiSet} container always keeps arrangment automatically without additional - * operations and it even meets full criteria of {@link PriorityQueue}. Those are the reason why I've adopted - * {@link TreeMultiSet} as the underlying container of {@link PriorityQueue}.

    - */ - private container_; - /** - * Default Constructor. - */ - constructor(); - /** - * Construct from compare. - * - * @param compare A binary predicate determines order of elements. - */ - constructor(compare: (left: T, right: T) => boolean); - /** - * Contruct from elements. - * - * @param array Elements to be contained. - */ - constructor(array: Array); - /** - * Contruct from elements with compare. - * - * @param array Elements to be contained. - * @param compare A binary predicate determines order of elements. - */ - constructor(array: Array, compare: (left: T, right: T) => boolean); - /** - * Copy Constructor. - */ - constructor(container: base.Container); - /** - * Copy Constructor with compare. - * - * @param container A container to be copied. - * @param compare A binary predicate determines order of elements. - */ - constructor(container: base.Container, compare: (left: T, right: T) => boolean); - /** - * Range Constructor. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - */ - constructor(begin: Iterator, end: Iterator); - /** - * Range Constructor with compare. - * - * @param begin Input interator of the initial position in a sequence. - * @param end Input interator of the final position in a sequence. - * @param compare A binary predicate determines order of elements. - */ - constructor(begin: Iterator, end: Iterator, compare: (left: T, right: T) => boolean); - /** - * @hidden - */ - protected construct_from_array(items: Array): void; - /** - * @hidden - */ - protected construct_from_container(container: base.IContainer): void; - /** - * @hidden - */ - protected construct_from_range(begin: Iterator, end: Iterator): void; - /** - *

    Return size.

    - * - *

    Returns the number of elements in the {@link PriorityQueue}.

    - * - *

    This member function effectively calls member {@link IArray.size size} of the - * {@link container_ underlying container} object.

    - * - * @return The number of elements in the underlying - */ - size(): number; - /** - *

    Test whether container is empty.

    - * - *

    Returns whether the {@link PriorityQueue} is empty: i.e. whether its {@link size} is zero.

    - * - *

    This member function effectively calls member {@link IARray.empty empty} of the - * {@link container_ underlying container} object.

    - */ - empty(): boolean; - /** - *

    Access top element.

    - * - *

    Returns a constant reference to the top element in the {@link PriorityQueue}.

    - * - *

    The top element is the element that compares higher in the {@link PriorityQueue}, and the next that is - * removed from the container when {@link PriorityQueue.pop} is called.

    - * - *

    This member function effectively calls member {@link IArray.front front} of the - * {@link container_ underlying container} object.

    - * - * @return A reference to the top element in the {@link PriorityQueue}. - */ - top(): T; - /** - *

    Insert element.

    - * - *

    Inserts a new element in the {@link PriorityQueue}. The content of this new element is initialized to - * val. - * - *

    This member function effectively calls the member function {@link IArray.push_back push_back} of the - * {@link container_ underlying container} object, and then reorders it to its location in the heap by calling - * the push_heap algorithm on the range that includes all the elements of the

    - * - * @param val Value to which the inserted element is initialized. - */ - push(val: T): void; - /** - *

    Remove top element.

    - * - *

    Removes the element on top of the {@link PriorityQueue}, effectively reducing its {@link size} by one. - * The element removed is the one with the highest (or lowest) value.

    - * - *

    The value of this element can be retrieved before being popped by calling member - * {@link PriorityQueue.top}.

    - * - *

    This member function effectively calls the pop_heap algorithm to keep the heap property of - * {@link PriorityQueue PriorityQueues} and then calls the member function {@link IArray.pop_back pop_back} of - * the {@link container_ underlying container} object to remove the element.

    - */ - pop(): void; - /** - *

    Swap contents.

    - * - *

    Exchanges the contents of the container adaptor by those of obj, swapping both the - * {@link container_ underlying container} value and their comparison function using the corresponding - * {@link std.swap swap} non-member functions (unqualified).

    - * - *

    This member function has a noexcept specifier that matches the combined noexcept of the - * {@link IArray.swap swap} operations on the {@link container_ underlying container} and the comparison - * functions.

    - * - * @param obj {@link PriorityQueue} container adaptor of the same type (i.e., instantiated with the same - * template parameters, T). Sizes may differ. - */ - swap(obj: PriorityQueue): void; - } -} declare namespace std { /** *

    LIFO stack.

    @@ -8142,14 +8173,14 @@ declare namespace std { * * @param container Another map to copy. */ - constructor(container: base.MapContainer); + constructor(container: TreeMap); /** * Copy Constructor. * * @param container Another map to copy. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.MapContainer, compare: (x: Key, y: Key) => boolean); + constructor(container: TreeMap, compare: (x: Key, y: Key) => boolean); /** * Range Constructor. * @@ -8196,31 +8227,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link TreeMap map} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link TreeMap map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMap container}. + */ + swap(obj: TreeMap): void; /** * @inheritdoc */ - swap(obj: base.UniqueMap): void; - /** - * @hidden - */ - private swap_tree_map(obj); + swap(obj: base.IContainer>): void; } } declare namespace std.TreeMultiMap { @@ -8330,14 +8375,14 @@ declare namespace std { * * @param container Another map to copy. */ - constructor(container: base.MapContainer); + constructor(container: TreeMultiMap); /** * Copy Constructor. * * @param container Another map to copy. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.MapContainer, compare: (x: Key, y: Key) => boolean); + constructor(container: TreeMultiMap, compare: (x: Key, y: Key) => boolean); /** * Range Constructor. * @@ -8388,31 +8433,45 @@ declare namespace std { /** * @hidden */ - protected insert_by_pair(pair: Pair): any; + protected _Insert_by_pair(pair: Pair): any; /** * @hidden */ - protected insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; + protected _Insert_by_hint(hint: MapIterator, pair: Pair): MapIterator; /** * @hidden */ - protected insert_by_range>>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: MapIterator, last: MapIterator): void; + protected _Handle_insert(first: MapIterator, last: MapIterator): void; /** * @inheritdoc */ - protected handle_erase(first: MapIterator, last: MapIterator): void; + protected _Handle_erase(first: MapIterator, last: MapIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link TreeMapMulti map} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link TreeMapMulti map container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMapMulti container}. + */ + swap(obj: TreeMultiMap): void; /** * @inheritdoc */ - swap(obj: base.MultiMap): void; - /** - * @hidden - */ - private swap_tree_multimap(obj); + swap(obj: base.IContainer>): void; } } declare namespace std.TreeMultiSet { @@ -8501,14 +8560,14 @@ declare namespace std { /** * Copy Constructor. */ - constructor(container: base.Container); + constructor(container: TreeMultiSet); /** * Copy Constructor with compare. * * @param container A container to be copied. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.Container, compare: (x: T, y: T) => boolean); + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); /** * Range Constructor. * @@ -8559,31 +8618,49 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; + _Get_tree(): base.AtomicTree; /** * @hidden */ - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_val(val: T): any; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; - /** - * @inheritdoc - */ - protected handle_insert(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - protected handle_erase(first: SetIterator, last: SetIterator): void; - /** - * @inheritdoc - */ - swap(obj: base.MultiSet): void; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - private swap_tree_set(obj); + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; + /** + * @inheritdoc + */ + protected _Handle_insert(first: SetIterator, last: SetIterator): void; + /** + * @inheritdoc + */ + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link TreeMultiSet set} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link TreeMultiSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeMultiSet container}. + */ + swap(obj: TreeMultiSet): void; + /** + * @inheritdoc + */ + swap(obj: base.IContainer): void; } } declare namespace std.TreeSet { @@ -8671,14 +8748,14 @@ declare namespace std { /** * Copy Constructor. */ - constructor(container: base.IContainer); + constructor(container: TreeMultiSet); /** * Copy Constructor with compare. * * @param container A container to be copied. * @param compare A binary predicate determines order of elements. */ - constructor(container: base.IContainer, compare: (x: T, y: T) => boolean); + constructor(container: TreeMultiSet, compare: (x: T, y: T) => boolean); /** * Range Constructor. * @@ -8687,7 +8764,7 @@ declare namespace std { */ constructor(begin: Iterator, end: Iterator); /** - * Range Constructor with compare. + * Construct from range and compare. * * @param begin Input interator of the initial position in a sequence. * @param end Input interator of the final position in a sequence. @@ -8725,28 +8802,42 @@ declare namespace std { /** * @hidden */ - protected insert_by_val(val: T): any; - protected insert_by_hint(hint: SetIterator, val: T): SetIterator; + protected _Insert_by_val(val: T): any; + protected _Insert_by_hint(hint: SetIterator, val: T): SetIterator; /** * @hidden */ - protected insert_by_range>(first: InputIterator, last: InputIterator): void; + protected _Insert_by_range>(first: InputIterator, last: InputIterator): void; /** * @inheritdoc */ - protected handle_insert(first: SetIterator, last: SetIterator): void; + protected _Handle_insert(first: SetIterator, last: SetIterator): void; /** * @inheritdoc */ - protected handle_erase(first: SetIterator, last: SetIterator): void; + protected _Handle_erase(first: SetIterator, last: SetIterator): void; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link TreeSet set} of the same type. Sizes abd container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were + * in obj before the call, and the elements of obj are those which were in this. All + * iterators, references and pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link TreeSet set container} of the same type of elements as this (i.e., + * with the same template parameters, Key and T) whose content is swapped + * with that of this {@link TreeSet container}. + */ + swap(obj: TreeSet): void; /** * @inheritdoc */ - swap(obj: base.UniqueSet): void; - /** - * @hidden - */ - private swap_tree_set(obj); + swap(obj: base.IContainer): void; } } declare namespace std { @@ -8880,7 +8971,7 @@ declare namespace std { * @reference http://www.cplusplus.com/reference/vector/vector * @author Jeongho Nam */ - class Vector extends Array implements base.IArrayContainer { + class Vector extends Array implements base.IContainer, base.IArrayContainer { /** *

    Default Constructor.

    * @@ -8917,7 +9008,7 @@ declare namespace std { * @param container Another container object of the same type (with the same class template * arguments T), whose contents are either copied or acquired. */ - constructor(container: base.IContainer); + constructor(container: Vector); /** *

    Range Constructor.

    * @@ -9137,11 +9228,11 @@ declare namespace std { /** * @hidden */ - protected insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; + protected _Insert_by_repeating_val(position: VectorIterator, n: number, val: T): VectorIterator; /** * @hidden */ - protected insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; + protected _Insert_by_range>(position: VectorIterator, first: InputIterator, last: InputIterator): VectorIterator; /** * @inheritdoc */ @@ -9227,7 +9318,25 @@ declare namespace std { /** * @hidden */ - protected erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; + protected _Erase_by_range(first: VectorIterator, last: VectorIterator): VectorIterator; + /** + *

    Swap content.

    + * + *

    Exchanges the content of the container by the content of obj, which is another + * {@link Vector container} object with same type of elements. Sizes and container type may differ.

    + * + *

    After the call to this member function, the elements in this container are those which were in obj + * before the call, and the elements of obj are those which were in this. All iterators, references and + * pointers remain valid for the swapped objects.

    + * + *

    Notice that a non-member function exists with the same name, {@link std.swap swap}, overloading that + * algorithm with an optimization that behaves like this member function.

    + * + * @param obj Another {@link Vector container} of the same type of elements (i.e., instantiated + * with the same template parameter, T) whose content is swapped with that of this + * {@link container Vector}. + */ + obj(obj: Vector): void; /** * @inheritdoc */ @@ -9335,7 +9444,10 @@ declare namespace std { /** * @hidden */ - protected create_neighbor(): VectorReverseIterator; + protected create_neighbor(base: VectorIterator): VectorReverseIterator; + /** + * @inheritdoc + */ /** * Set value of the iterator is pointing to. * @@ -11328,6 +11440,7 @@ declare namespace std.base { * Default Constructor. */ constructor(map: TreeMap | TreeMultiMap, compare?: (x: Key, y: Key) => boolean); + _Set_compare(val: (x: Key, y: Key) => boolean): void; find(key: Key): XTreeNode>; find(it: MapIterator): XTreeNode>; /** @@ -11628,6 +11741,7 @@ declare namespace std.base { * Default Constructor. */ constructor(set: TreeSet | TreeMultiSet, compare?: (x: T, y: T) => boolean); + _Set_compare(val: (x: T, y: T) => boolean): void; find(val: T): XTreeNode>; find(it: SetIterator): XTreeNode>; /** From d9ed548addd8d5eae953e28e4dfe98c2d6a03568 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 20:15:15 +0800 Subject: [PATCH 054/212] Delete deprecated functions (#11173) --- node/node.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 820521e43c..c2a8f71239 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1019,8 +1019,6 @@ declare module "os" { export function arch(): string; export function platform(): string; export function tmpdir(): string; - export function tmpDir(): string; - export function getNetworkInterfaces(): { [index: string]: NetworkInterfaceInfo[] }; export var EOL: string; export function endianness(): "BE" | "LE"; } From f7b0b1c8a030760ff4e87bbb6fa4b28393da33fe Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 20:20:09 +0800 Subject: [PATCH 055/212] Correct assert.fail parameters (#11176) --- node/node.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node/node.d.ts b/node/node.d.ts index c2a8f71239..a9112d47a4 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2596,7 +2596,7 @@ declare module "assert" { }); } - export function fail(actual?: any, expected?: any, message?: string, operator?: string): void; + export function fail(actual: any, expected: any, message: string, operator: string): void; export function ok(value: any, message?: string): void; export function equal(actual: any, expected: any, message?: string): void; export function notEqual(actual: any, expected: any, message?: string): void; From d1171f6895907d555e0a78bca773c9fba3be14f4 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 20:20:31 +0800 Subject: [PATCH 056/212] [node.d.ts] Implement function tests for assert (#11175) * Implement function tests for assert * Implement function tests for assert - Node v4.x --- node/node-4-tests.ts | 17 ++++++++--------- node/node-tests.ts | 17 ++++++++--------- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 0162951454..35fe3553a6 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -34,7 +34,7 @@ namespace assert_tests{ assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - // TODO: assert.deepStrictEqual + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); assert.doesNotThrow(() => { const b = false; @@ -43,21 +43,20 @@ namespace assert_tests{ assert.equal(3, "3", "uses == comparator"); - // TODO: assert.fail + assert.fail(1, 2, undefined, '>'); - // TODO: assert.ifError + assert.ifError(0); - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - // TODO: assert.notDeepStrictEqual - - // TODO: assert.notEqual + assert.notEqual(1, 2, "uses != comparator"); assert.notStrictEqual(2, "2", "uses === comparator"); - // TODO: assert.ok + assert.ok(true); + assert.ok(1); - // TODO: assert.strictEqual + assert.strictEqual(1, 1, "uses === comparator"); assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } diff --git a/node/node-tests.ts b/node/node-tests.ts index 651df8ca09..7e010bc9a3 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -36,7 +36,7 @@ namespace assert_tests{ assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - // TODO: assert.deepStrictEqual + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); assert.doesNotThrow(() => { const b = false; @@ -45,21 +45,20 @@ namespace assert_tests{ assert.equal(3, "3", "uses == comparator"); - // TODO: assert.fail + assert.fail(1, 2, undefined, '>'); - // TODO: assert.ifError + assert.ifError(0); - assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses === comparator"); + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - // TODO: assert.notDeepStrictEqual - - // TODO: assert.notEqual + assert.notEqual(1, 2, "uses != comparator"); assert.notStrictEqual(2, "2", "uses === comparator"); - // TODO: assert.ok + assert.ok(true); + assert.ok(1); - // TODO: assert.strictEqual + assert.strictEqual(1, 1, "uses === comparator"); assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } From 684fa0d89400dff7497ce9fec7ab3f7376cd27bc Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 20:21:03 +0800 Subject: [PATCH 057/212] [node.d.ts] Correct NodeBuffer.toJSON type (#11177) * Correct NodeBuffer.toJSON type * Correct NodeBuffer.toJSON type in Node v4.x --- node/node-4.d.ts | 2 +- node/node.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/node/node-4.d.ts b/node/node-4.d.ts index daebb4585e..f05444336d 100644 --- a/node/node-4.d.ts +++ b/node/node-4.d.ts @@ -430,7 +430,7 @@ declare namespace NodeJS { interface NodeBuffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; + toJSON(): {type: 'Buffer', data: any[]}; equals(otherBuffer: Buffer): boolean; compare(otherBuffer: Buffer): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; diff --git a/node/node.d.ts b/node/node.d.ts index a9112d47a4..8c4123f283 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -464,7 +464,7 @@ interface IterableIterator {} interface NodeBuffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; - toJSON(): any; + toJSON(): {type: 'Buffer', data: any[]}; equals(otherBuffer: Buffer): boolean; compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; From 1b2c971798ad303824af74973de1a2b5b9acaf79 Mon Sep 17 00:00:00 2001 From: Joshua Efiong Date: Wed, 14 Sep 2016 13:23:06 +0100 Subject: [PATCH 058/212] Added GeoShape classes to typedefs (#11178) * Added GeoShape classes to typedefs * Circle style can be SpatialStyle.Options --- heremaps/heremaps.d.ts | 315 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 312 insertions(+), 3 deletions(-) diff --git a/heremaps/heremaps.d.ts b/heremaps/heremaps.d.ts index fe79e55ecf..8d730f3ae5 100644 --- a/heremaps/heremaps.d.ts +++ b/heremaps/heremaps.d.ts @@ -1073,6 +1073,125 @@ declare namespace H { */ resizeToCenter(center: H.geo.IPoint, opt_out?: H.geo.Rect): H.geo.Rect; } + + /** + * A strip is a flat list of latitude, longitude, altitude tuples in a fixed order. + */ + export class Strip { + /** + * Constructor + * @param opt_latLngAlts {Array=} - An optional array of latitude, longitude and altitude triples to initialize the strip with. + * @param opt_ctx {H.geo.AltitudeContext=} - An optional altitude context for all altitudes contained in this strip. + */ + constructor(opt_latLngAlts?: Array, opt_ctx?: H.geo.AltitudeContext); + + /** + * This method pushes a lat, lng, alt to the end of this strip. + * @param lat {H.geo.Latitude} + * @param lng {H.geo.Longitude} + * @param alt {H.geo.Altitude} + */ + pushLatLngAlt(lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method splices the strip at the provided index, removing the specified number of items at that index and inserting the lat, lng, alt array. + * @param index {number} - The index at which to splice + * @param opt_nRemove {number=} - The number of lat, lng, alt values to remove + * @param opt_latLngAlts {Array=} - The lat, lng, alt values to add + * @returns {Array} - an array of removed elements + */ + spliceLatLngAlts(index: number, opt_nRemove?: number, opt_latLngAlts?: Array): Array; + + /** + * This method inserts one set of lat, lng, alt values into the strip at the specified index. + * @param index {number} - the index at which to add the element + * @param lat {H.geo.Latitude} - the latitude to insert + * @param lng {H.geo.Longitude} - the longitude to insert + * @param alt {H.geo.Altitude} - the altitude to insert + */ + insertLatLngAlt(index: number, lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude): void; + + /** + * This method removes one set of lat, lng, alt values from the strip at the specified index. + * @param index {number} + */ + removeLatLngAlt(index: number): void; + + /** + * This method pushes the lat, lng, alt values of a H.geo.Point to the end of this strip. + * @param geoPoint {H.geo.IPoint} + */ + pushPoint(geoPoint: H.geo.IPoint): void; + + /** + * This method inserts the lat, lng, alt values of a H.geo.Point into the list at the specified index. + * @param pointIndex {number} + * @param geoPoint {H.geo.IPoint} + */ + insertPoint(pointIndex: number, geoPoint: H.geo.IPoint): void; + + /** + * This method removes one set of lat, lng, alt values from this strip at the virtual point index specified. + * @param pointIndex {number} - the virtual point index + */ + removePoint(pointIndex: number): void; + + /** + * This method extracts a H.geo.Point from this strip at the virtual point index. If the extracted point has an alt value, the strip's altitude context will be supplied to the point. + * @param pointIndex {number} - the virtual point index in the strip + * @param opt_out {H.geo.Point=} - an optional point object to store the lat, lng, alt values + * @returns {H.geo.Point} - returns either the 'opt_out' point object or a new point object. + */ + extractPoint(pointIndex: number, opt_out?: H.geo.Point): H.geo.Point; + + /** + * This method is a utility method that iterates over the lat, lng, alt array and calls the provided function for each 3 elements passing lat, lng and alt and the virtual point index as arguments. + * @param eachFn {function(H.geo.Latitude, H.geo.Longitude, H.geo.Altitude, number)} - the function to be called for each 3 elements + * @param opt_start {number=} - an optional start index to iterate from + * @param opt_end {number=} - an optional end index to iterate to + */ + eachLatLngAlt(eachFn: (lat: H.geo.Latitude, lng: H.geo.Longitude, alt: H.geo.Altitude, n: number) => void, opt_start?: number, opt_end?: number): void; + + /** + * This method returns the number of times that legs in this strip cross the date border. + * @param opt_closed {boolean=} - indicates whether the strip is closed (i.e. whether the strip's last and first coordinates form the closing leg of a polygon) + * @returns {number} - the amount of times this strip crosses the date border. + */ + getDBCs(opt_closed?: boolean): number; + + /** + * This method return the number of points stored in this strip. + * @returns {number} - the number of points in this strip + */ + getPointCount(): number; + + /** + * This method returns the internal array keeping the lat, lng, alt values. Modifying this array directly can destroy the integrity of this strip. Use it only for read access. + * @returns {Array} - returns the raw lat, lng, alt values of this strip + */ + getLatLngAltArray(): Array; + + /** + * This method returns the bounding box of this strip. + * @returns {?H.geo.Rect} - this strip's bounding rectangle + */ + getBounds(): H.geo.Rect; + + /** + * This method checks whether two longitudes form a leg which crosses the date border. + * @param lng1 {H.geo.Longitude} - the start longitude of the leg + * @param lng2 {H.geo.Longitude} - the end longitude of the leg + * @returns {boolean} - true if the leg crosses the date border, otherwise false + */ + static isDBC(lng1: H.geo.Longitude, lng2: H.geo.Longitude): boolean; + + /** + * This method initializes a new strip with an array of lat, lng values. Arrays are expected to have an even length with the format [lat, lng, lat, lng, ...]. + * @param latLngs {Array} - the array of lat, lng value. + * @returns {H.geo.Strip} - the strip containing the lat, lng values + */ + static fromLatLngArray(latLngs: Array): H.geo.Strip; + } } /***** lang *****/ @@ -1173,6 +1292,78 @@ declare namespace H { } } + /** + * A Polygon with a circular shape. + */ + export class Circle extends H.map.Polygon { + /** + * Constructor + * @param center {H.geo.IPoint} - The geographical coordinates of the circle's center + * @param radius {number} - The radius of the circle in meters + * @param opt_options {H.map.Circle.Options=} - An object that specifies circle options and their initial values (among these, precision has a significant impact on the shape of the circle - please see + */ + constructor(center: H.geo.IPoint, radius: number, opt_options?: H.map.Circle.Options); + + /** + * To set the geographical center point of this circle. If the specified center is an instance of H.geo.Point you must not modify this Point instance without calling setCenter immediately afterwards. + * @param center {H.geo.IPoint} + */ + setCenter(center: H.geo.IPoint): void; + + /** + * To get the center point of this circle You must not modify the returned Point instance without calling setCenter immediately afterwards. + * @returns {H.geo.Point} + */ + getCenter(): H.geo.Point; + + /** + * To set the length of the radius of the circle in meters. The value is clamped to the of {@code[0 ... 20015089.27787877]} (half WGS84 mean circumference) + * @param radius {number} + */ + setRadius(radius: number): void; + + /** + * To get the length of the radius of the circle in meters. + * @returns {number} + */ + getRadius(): number; + + /** + * To set the precision of this circle {@see H.map.Circle.Options#precision} + * @param precision {number} + */ + setPrecision(precision: number): void; + + /** + * To get the precision value of this circle + * @returns {number} + */ + getPrecision(): number; + } + + export module Circle { + /** + * @property style {H.map.SpatialStyle=} - the style to be used when tracing the polyline + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property precision {number=} - The precision of a circle as a number of segments to be used when rendering the circle. The value is clamped to the range between [4 ... 360], where 60 is the default. Note that the lower the value the more angular and the less circle-like the shape appears and, conversely, the higher the value the smoother and more rounded the result. Thus, starting at the extreme low end of the possible values, 4 produces a square, 6 a hexagon, while 30 results in a circle-like shape, although it appears increasingly angular as the zoom level increases (as you zoom in), and finally 360 produces a smooth circle. + * @property zIndex {number=} - The z-index value of the circle, default is 0 + * @property min {number=} - The minimum zoom level for which the circle is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the circle is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: H.map.SpatialStyle | H.map.SpatialStyle.Options; + visibility?: boolean; + precision?: number; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + /** * The class represents data model of the map. It holds list of layers that are rendered by map's RenderEngine. The class listens to 'update' events from layers and dispatches them to the RenderEngine. */ @@ -1242,6 +1433,38 @@ declare namespace H { } } + /** + * This class represents a spatial shape in geographic space. It is defined by a path containing the vertices of the shape (lat, lng, alt values). + */ + export class GeoShape extends H.map.Spatial { + /** + * Constructor + * @param isClosed {boolean} - Indicates whether this geographical shape is closed (a polygon) + * @param strip {H.geo.Strip} - The strip describing the shape of the spatial object + * @param options {H.map.Spatial.Options} - The options to apply + */ + constructor(isClosed: boolean, strip: H.geo.Strip, options: H.map.Spatial.Options); + + /** + * This method returns the strip which represents the shape of the spatial object. + * @returns {H.geo.Strip} - the strip + */ + getStrip(): H.geo.Strip; + + /** + * This method sets the geo-information for the spatial object + * @param strip {?H.geo.Strip} - The strip which represents the shape of the spatial object. + * @returns {H.map.GeoShape} - the Spatial instance itself + */ + setStrip(strip: H.geo.Strip): H.map.GeoShape; + + /** + * This method returns the bounding rectangle for this object. The rectangle is the smallest rectangle which encloses all points of the spatial object. + * @returns {H.geo.Rect} + */ + getBounds(): H.geo.Rect; + } + /** * This class represents a map object which can contain other map objects. It's visibility, zIndex and object-order influences the contained map objects */ @@ -1855,6 +2078,92 @@ declare namespace H { } } + /** + * This class represents a polygon in geo-space. It is defined by a strip containing the vertices of a geo shape object (lat, lng, alt values) and a pen to use when rendering the polyline. Polygon represents a closed plane defined by the list of verticies, projected on the map display. List of vericies which define the polygon are is a list of geo coordinates encapsulated by the strip object H.geo.Strip + */ + export class Polygon extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Spatial.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Spatial.Options); + + /** + * To set the indicator whether this polygon covers the north pole. It's needed for Polygons whose strip is defined as lines arround the world on longitude axis (for example a circle whose center is one of the poles). In this case a additional information is needed to know if the southern or northern part of the world should be covered by the poygon. + * @param flag {boolean} - A value of true means it covers the north pole, false means south pole + * @returns {H.map.Polygon} - the Polygon instance itself + */ + setNorthPoleCovering(flag: boolean): H.map.Polygon; + + /** + * See H.map.Polygon#setNorthPoleCovering + * @returns {boolean} + */ + getNorthPoleCovering(): boolean; + } + + /** + * This class represents a polyline in geo-space. It is defined by a path containing the vertices of a polyline (lat, lng, alt values) and a pen to use when tracing the path on the map. + */ + export class Polyline extends H.map.GeoShape { + /** + * Constructor + * @param strip {H.geo.Strip} - the strip describing this polygon's vertices + * @param opt_options {H.map.Polyline.Options=} - optional initialization parameters + */ + constructor(strip: H.geo.Strip, opt_options?: H.map.Polyline.Options); + + /** + * This method clips this polyline against a rectangular area and returns the intersecting sub-lines. + * @param geoRect {H.geo.Rect} + * @returns {Array>} + */ + clip(geoRect: H.geo.Rect): Array>; + } + + export module Polyline { + /** + * Options which are used to initialize a polyline + * @property style {(H.map.SpatialStyle | H.map.SpatialStyle.Options)=} - the style to be used when tracing the polyline + * @property arrows {(H.map.ArrowStyle | H.map.ArrowStyle.Options)=} - The arrows style to be used when rendering the polyline. + * @property visibility {boolean=} - An optional boolean value indicating whether this map object is visible, default is true + * @property zIndex {number=} - The z-index value of the map object, default is 0 + * @property min {number=} - The minimum zoom level for which the object is visible, default is -Infinity + * @property max {number=} - The maximum zoom level for which the object is visible, default is Infinity + * @property provider {(H.map.provider.Provider | null)=} - The provider of this object. This property is only needed if a customized Implementation of ObjectProvider wants to instantiate an object. + * @property data {*} - Optional arbitrary data to be stored with this map object. This data can be retrieved by calling getData + */ + export interface Options { + style?: (H.map.SpatialStyle | H.map.SpatialStyle.Options); + arrows?: (H.map.ArrowStyle | H.map.ArrowStyle.Options); + visibility?: boolean; + zIndex?: number; + min?: number; + max?: number; + provider?: H.map.provider.Provider; + data?: any; + } + } + + /** + * A Polygon with a rectangular shape. + */ + export class Rect extends H.map.Polygon { + /** + * Constructor + * @param bounds {H.geo.Rect} - The geographical bounding box for this rectangle + * @param opt_options {H.map.Spatial.Options=} + */ + constructor(bounds: H.geo.Rect, opt_options?: H.map.Spatial.Options); + + /** + * To set the bounds of this rectangle. + * @param bounds {H.geo.Rect} + */ + setBounds(bounds: H.geo.Rect): void; + } + /** * This class represents a spatial map object which provides its projected geometry. */ @@ -1985,8 +2294,8 @@ declare namespace H { miterLimit: number; lineDash: Array; lineDashOffset: number; - MAX_LINE_WIDTH: number; - DEFAULT_STYLE: H.map.SpatialStyle; + static MAX_LINE_WIDTH: number; + static DEFAULT_STYLE: H.map.SpatialStyle; } export module SpatialStyle { @@ -2018,7 +2327,7 @@ declare namespace H { lineCap?: H.map.SpatialStyle.LineCap; lineJoin?: H.map.SpatialStyle.LineJoin; miterLimit?: number; - lineDash: Array; + lineDash?: Array; lineDashOffset?: number; } } From 5ee054ac95f68355c05b8d168b9a2f1eb4a581f8 Mon Sep 17 00:00:00 2001 From: hriss95 Date: Wed, 14 Sep 2016 13:26:40 +0100 Subject: [PATCH 059/212] [Node.d.ts]: Update definitions for module "crypto" (#11186) --- node/node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node.d.ts b/node/node.d.ts index 8c4123f283..76a42f4013 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -2434,6 +2434,7 @@ declare module "crypto" { setPrivateKey(private_key: string, encoding: HexBase64Latin1Encoding): void; } export function createECDH(curve_name: string): ECDH; + export var DEFAULT_ENCODING: string; } declare module "stream" { From 2e7debf76d12149b4eee2c2e26ce9a1065b31369 Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Wed, 14 Sep 2016 05:41:56 -0700 Subject: [PATCH 060/212] Update to Electron 1.3.5 (#11096) --- github-electron/github-electron-main-tests.ts | 57 +++++++++ github-electron/github-electron.d.ts | 117 +++++++++++++++++- 2 files changed, 171 insertions(+), 3 deletions(-) diff --git a/github-electron/github-electron-main-tests.ts b/github-electron/github-electron-main-tests.ts index bebf0b99c8..966465ed3a 100644 --- a/github-electron/github-electron-main-tests.ts +++ b/github-electron/github-electron-main-tests.ts @@ -240,6 +240,63 @@ app.setUserTasks([ } ]); app.setUserTasks([]); + +app.setJumpList([ + { + type: 'custom', + name: 'Recent Projects', + items: [ + { type: 'file', path: 'C:\\Projects\\project1.proj' }, + { type: 'file', path: 'C:\\Projects\\project2.proj' } + ] + }, + { // has a name so type is assumed to be "custom" + name: 'Tools', + items: [ + { + type: 'task', + title: 'Tool A', + program: process.execPath, + args: '--run-tool-a', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool A' + }, + { + type: 'task', + title: 'Tool B', + program: process.execPath, + args: '--run-tool-b', + iconPath: process.execPath, + iconIndex: 0, + description: 'Runs Tool B' + }] + }, + { + type: 'frequent' + }, + { // has no name and no type so type is assumed to be "tasks" + items: [ + { + type: 'task', + title: 'New Project', + program: process.execPath, + args: '--new-project', + description: 'Create a new project.' + }, + { + type: 'separator' + }, + { + type: 'task', + title: 'Recover Project', + program: process.execPath, + args: '--recover-project', + description: 'Recover Project' + }] + } +]); + if (app.isUnityRunning()) { } if (app.isAccessibilitySupportEnabled()) { diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 7d10fce465..3dc72d7075 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.4 +// Type definitions for Electron v1.3.5 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -199,7 +199,7 @@ declare namespace Electron { * All windows will be closed immediately without asking user * and the before-quit and will-quit events will not be emitted. */ - exit(exitCode: number): void; + exit(exitCode?: number): void; /** * Relaunches the app when current instance exits. * @@ -333,6 +333,19 @@ declare namespace Electron { * Note: This API is only available on Windows. */ setUserTasks(tasks: Task[]): boolean; + /** + * Note: This API is only available on Windows. + */ + getJumpListSettings(): JumpListSettings; + /** + * Sets or removes a custom Jump List for the application. + * + * If categories is null the previously set custom Jump List (if any) will be replaced + * by the standard Jump List for the app (managed by Windows). + * + * Note: This API is only available on Windows. + */ + setJumpList(categories: JumpListCategory[]): SetJumpListResult; /** * This method makes your application a Single Instance Application instead of allowing * multiple instances of your app to run, this will ensure that only a single instance @@ -560,6 +573,89 @@ declare namespace Electron { iconIndex?: number; } + /** + * ok - Nothing went wrong. + * error - One or more errors occured, enable runtime logging to figure out the likely cause. + * invalidSeparatorError - An attempt was made to add a separator to a custom category in the Jump List. + * Separators are only allowed in the standard Tasks category. + * fileTypeRegistrationError - An attempt was made to add a file link to the Jump List + * for a file type the app isn't registered to handle. + * customCategoryAccessDeniedError - Custom categories can't be added to the Jump List + * due to user privacy or group policy settings. + */ + type SetJumpListResult = 'ok' | 'error' | 'invalidSeparatorError' | 'fileTypeRegistrationError' | 'customCategoryAccessDeniedError'; + + interface JumpListSettings { + /** + * The minimum number of items that will be shown in the Jump List. + */ + minItems: number; + /** + * Items that the user has explicitly removed from custom categories in the Jump List. + */ + removedItems: JumpListItem[]; + } + + interface JumpListCategory { + /** + * tasks - Items in this category will be placed into the standard Tasks category. + * frequent - Displays a list of files frequently opened by the app, the name of the category and its items are set by Windows. + * recent - Displays a list of files recently opened by the app, the name of the category and its items are set by Windows. + * custom - Displays tasks or file links, name must be set by the app. + */ + type?: 'tasks' | 'frequent' | 'recent' | 'custom'; + /** + * Must be set if type is custom, otherwise it should be omitted. + */ + name?: string; + /** + * Array of JumpListItem objects if type is tasks or custom, otherwise it should be omitted. + */ + items?: JumpListItem[]; + } + + interface JumpListItem { + /** + * task - A task will launch an app with specific arguments. + * separator - Can be used to separate items in the standard Tasks category. + * file - A file link will open a file using the app that created the Jump List. + */ + type: 'task' | 'separator' | 'file'; + /** + * Path of the file to open, should only be set if type is file. + */ + path?: string; + /** + * Path of the program to execute, usually you should specify process.execPath which opens the current program. + * Should only be set if type is task. + */ + program?: string; + /** + * The command line arguments when program is executed. Should only be set if type is task. + */ + args?: string; + /** + * The text to be displayed for the item in the Jump List. Should only be set if type is task. + */ + title?: string; + /** + * Description of the task (displayed in a tooltip). Should only be set if type is task. + */ + description?: string; + /** + * The absolute path to an icon to be displayed in a Jump List, which can be an arbitrary + * resource file that contains an icon (e.g. .ico, .exe, .dll). + * You can usually specify process.execPath to show the program icon. + */ + iconPath?: string; + /** + * The index of the icon in the resource file. If a resource file contains multiple icons + * this value can be used to specify the zero-based index of the icon that should be displayed + * for this task. If a resource file contains only one icon, this property should be set to zero. + */ + iconIndex?: number; + } + interface LoginItemSettings { /** * True if the app is set to open at login. @@ -3595,7 +3691,7 @@ declare namespace Electron { interface WebContentsStatic { /** - * @returns An array of all web contents. This will contain web contents for all windows, + * @returns An array of all WebContents instances. This will contain web contents for all windows, * webviews, opened devtools, and devtools extension background pages. */ getAllWebContents(): WebContents[]; @@ -3603,6 +3699,10 @@ declare namespace Electron { * @returns The web contents that is focused in this application, otherwise returns null. */ getFocusedWebContents(): WebContents; + /** + * Find a WebContents instance according to its ID. + */ + fromId(id: number): WebContents; } /** @@ -4971,6 +5071,17 @@ declare namespace Electron { * See webContents.sendInputEvent for detailed description of event object. */ sendInputEvent(event: SendInputEvent): void + /** + * Changes the zoom factor to the specified factor. + * Zoom factor is zoom percent divided by 100, so 300% = 3.0. + */ + setZoomFactor(factor: number): void; + /** + * Changes the zoom level to the specified level. + * The original size is 0 and each increment above or below represents + * zooming 20% larger or smaller to default limits of 300% and 50% of original size, respectively. + */ + setZoomLevel(level: number): void; /** * Shows pop-up dictionary that searches the selected word on the page. * Note: This API is available only on macOS. From c4186178260604b5b45f7cbc10d7525640e24460 Mon Sep 17 00:00:00 2001 From: Riad Loukili Date: Wed, 14 Sep 2016 13:44:48 +0100 Subject: [PATCH 061/212] AppBar type fix (#11192) Styles should be CSS properties not string. ;) --- material-ui/material-ui.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index f9dcbcfb38..2430923d9d 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -513,8 +513,8 @@ declare namespace __MaterialUI { iconClassNameRight?: string; iconElementLeft?: React.ReactElement; iconElementRight?: React.ReactElement; - iconStyleRight?: string; - iconStyleLeft?: string; + iconStyleRight?: React.CSSProperties; + iconStyleLeft?: React.CSSProperties; onLeftIconButtonTouchTap?: TouchTapEventHandler; onRightIconButtonTouchTap?: TouchTapEventHandler; onTitleTouchTap?: TouchTapEventHandler; From 007f8af1dcb7a849a9fe9f8c60fdde5fd594cb7c Mon Sep 17 00:00:00 2001 From: ShMcK Date: Wed, 14 Sep 2016 05:45:16 -0700 Subject: [PATCH 062/212] Add Atom Grammars (#11194) See [Atom Grammar Registry Docs](https://atom.io/docs/api/v1.10.2/GrammarRegistry). Atom grammars can be found by typings `atom.grammars` into the console. --- atom/atom.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/atom/atom.d.ts b/atom/atom.d.ts index 389d6ef16e..ac899ba5ac 100644 --- a/atom/atom.d.ts +++ b/atom/atom.d.ts @@ -946,9 +946,14 @@ declare namespace AtomCore { registry: any; repository: Object; scopeName: string; + tokenizeLines: (text: string) => any; // TBD } + + interface IGrammars { + grammarForScopeName(scope: string): IGrammar; + } interface IPane /* extends Theorist.Model */ { itemForURI: (uri:string)=>IEditor; @@ -1302,6 +1307,7 @@ declare namespace AtomCore { deserializers:IDeserializerManager; config: IConfig; commands: ICommandRegistry; + grammars: IGrammars; keymaps: IKeymapManager; keymap: IKeymapManager; packages: IPackageManager; From ef12b9812631c89256a70e9269ea8021e008c738 Mon Sep 17 00:00:00 2001 From: Marcy Sutton Date: Wed, 14 Sep 2016 05:45:38 -0700 Subject: [PATCH 063/212] add axe-core definition (#11195) --- axe-core/axe-core-tests.ts | 91 +++++++++++++++++++++ axe-core/axe-core.d.ts | 159 +++++++++++++++++++++++++++++++++++++ 2 files changed, 250 insertions(+) create mode 100644 axe-core/axe-core-tests.ts create mode 100644 axe-core/axe-core.d.ts diff --git a/axe-core/axe-core-tests.ts b/axe-core/axe-core-tests.ts new file mode 100644 index 0000000000..7decb865c2 --- /dev/null +++ b/axe-core/axe-core-tests.ts @@ -0,0 +1,91 @@ +/// + +var context:any = document +var $fixture:any = {} + +// axe.a11yCheck config +axe.a11yCheck(context, {}, (results) => { + // axe's results object + console.log(results.passes.length) + console.log(results.violations.length) +}); +// axe.a11yCheck include/exclude +axe.a11yCheck({include: [['#id1'], ['#id2']]}, {}, (results) => { + console.log(results) +}) +axe.a11yCheck({exclude: [$fixture[0]]}, {}, (results) => { + console.log(results) +}) +var tagConfigRunOnly: axe.RunOnly = { + type: 'tag', + values: ['wcag2a'] +} +var tagConfig = { + runOnly: tagConfigRunOnly +} +axe.a11yCheck(context, tagConfig, (results) => { + console.log(results) +}) +var includeExcludeTagsRunOnly: axe.RunOnly = { + type: 'tags', + value: { + include: ['wcag2a', 'wcag2aa'], + exclude: ['experimental'] + } +} +var includeExcludeTagsConfig = { + runOnly: includeExcludeTagsRunOnly +} +axe.a11yCheck(context, includeExcludeTagsConfig, (results) => { + console.log(results) +}) +var someRulesConfig = { + rules: { + "color-contrast": {enabled: 'false'}, + "heading-order": {enabled: 'true'} + } +} +axe.a11yCheck(context, someRulesConfig, (results) => { + console.log(results) +}) + +// axe.configure +var spec: axe.Spec = { + branding: { + brand: 'foo', + application: 'bar' + }, + reporter: 'v1', + checks: [{ + id: 'custom-check', + evaluate: function() { + return true + } + }], + rules: [{ + id: 'custom-rule', + any: ['custom-check'] + }] +} +axe.configure(spec) + +axe.reset() + +axe.getRules(['wcag2aa']) +typeof axe.getRules() === 'object' + +// Plugins +var pluginSrc: axe.AxePlugin = { + id: 'doStuff', + run: (data:any, callback:Function) => { + callback() + }, + commands: [{ + id: 'run-doStuff', + callback: (data:any, callback:Function) => { + axe.plugins['doStuff'].run(data, callback) + } + }] +} +axe.registerPlugin(pluginSrc) +axe.cleanup() diff --git a/axe-core/axe-core.d.ts b/axe-core/axe-core.d.ts new file mode 100644 index 0000000000..98818e75cc --- /dev/null +++ b/axe-core/axe-core.d.ts @@ -0,0 +1,159 @@ +// Type definitions for axe-core 2.0.5 +// Project: https://github.com/dequelabs/axe-core +// Definitions by: Marcy Sutton +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace axe { + + export type ImpactValue = "minor" | "moderate" | "serious" | "critical"; + + export type TagValue = "wcag2a" | "wcag2aa" | "section508" | "best-practice"; + + export type ReporterVersion = "v1" | "v2"; + + export type RunOnlyType = "rule" | "rules" | "tag" | "tags"; + + export interface ElementContext { + node?: Object, + selector?: string, + include?: any[], + exclude?: any[] + } + export interface RunOnly { + type: RunOnlyType, + value?: { + include?: string[], + exclude?: string[] + } + values?: TagValue[] + } + export interface AxeResults { + url: string, + timestamp: string, + passes: Pass[], + violations: Violation[] + } + export interface Pass { + description: string, + help: string, + helpUrl: string, + id: string, + impact: ImpactValue, + tags: TagValue[], + nodes: NodeResult[] + } + export interface Violation { + description: string, + help: string, + helpUrl: string, + id: string, + impact: ImpactValue, + tags: TagValue[], + nodes: NodeResult[] + } + export interface NodeResult { + html: string, + impact: ImpactValue, + target: string[], + any: CheckResult[], + all: CheckResult[], + none: CheckResult[] + } + export interface CheckResult { + id: string, + impact: string, + message: string, + data: any, + relatedNodes?: RelatedNode[] + } + export interface RelatedNode { + target: string[], + html: string + } + export interface Spec { + branding?: { + brand: string, + application: string + }, + reporter?: ReporterVersion, + checks?: Check[], + rules?: Rule[] + } + export interface Check { + id: string, + evaluate: Function, + after?: Function, + options?: any, + matches?: string, + enabled?: boolean + } + export interface Rule { + id: string, + selector?: string, + excludeHidden?: boolean, + enabled?: boolean, + pageLevel?: boolean, + any?: string[], + all?: string[], + none?: string[], + tags?: string[], + matches?: string + } + export interface AxePlugin { + id: string, + run(...args:any[]): any, + commands: { + id: string, + callback(...args:any[]): void + }[], + cleanup?(callback:Function): void + } + + export let plugins: any + + /** + * Starts analysis on the current document and its subframes + * + * @param {Object} context The `Context` specification object @see Context + * @param {Array} options Options passed into rules or checks, temporarily modifyint them. + * @param {Function} callback The function to invoke when analysis is complete. + * @returns {Object} results The aXe results object + */ + export function a11yCheck(context: ElementContext, options: {runOnly?: RunOnly, rules?: Object}, callback: (results:AxeResults) => void): AxeResults + + /** + * Method for configuring the data format used by aXe. Helpful for adding new + * rules, which must be registered with the library to execute. + * @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data + */ + export function configure(spec: Spec): void + + /** + * Searches and returns rules that contain a tag in the list of tags. + * @param {Array} tags Optional array of tags + * @return {Array} Array of rules + */ + export function getRules(tags?: string[]): Object[] + + /** + * Restores the default axe configuration + */ + export function reset(): void + + /** + * Function to register a plugin configuration in document and its subframes + * @param {Object} plugin A plugin configuration object + */ + export function registerPlugin(plugin: AxePlugin): void + + /** + * Function to clean up plugin configuration in document and its subframes + */ + export function cleanup(): void + +} + +// axe is also available as a module +declare module "axe-core" { + export = axe; +} From 4280cc2e71bb8211727116b5a442f7317b5e816c Mon Sep 17 00:00:00 2001 From: Graham Mendick Date: Wed, 14 Sep 2016 13:45:59 +0100 Subject: [PATCH 064/212] Updated typings and tests for Navigation 3.0.0 (#11196) --- navigation/navigation-tests.ts | 5 +++-- navigation/navigation.d.ts | 22 ++++++++++++---------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/navigation/navigation-tests.ts b/navigation/navigation-tests.ts index c1b6e45ff9..52e6bfded4 100644 --- a/navigation/navigation-tests.ts +++ b/navigation/navigation-tests.ts @@ -37,10 +37,11 @@ namespace NavigationTests { person.navigated = (data) => {}; person.urlEncode = function urlEncode(state: Navigation.State, key: string, val: string, queryString: boolean): string { return queryString ? val.replace(/\s/g, '+') : encodeURIComponent(val); - } + }; person.urlDecode = function urlDecode(state: Navigation.State, key: string, val: string, queryString: boolean): string { return queryString ? val.replace(/\+/g, ' ') : decodeURIComponent(val); - } + }; + person.validate = (data: any) => data.id > 0; // Navigation Event var navigationListener = (oldState: Navigation.State, state: Navigation.State, data: any, asyncData: any) => { diff --git a/navigation/navigation.d.ts b/navigation/navigation.d.ts index ad3c1c8e23..1ae460a9f3 100644 --- a/navigation/navigation.d.ts +++ b/navigation/navigation.d.ts @@ -138,6 +138,12 @@ declare namespace Navigation { * @param queryString A value indicating the Url value's location */ urlDecode(state: State, key: string, val: string, queryString: boolean): string; + /** + * Validates the NavigationData before navigating to the new State + * @param data The new NavigationData + * @returns Validation success indicator + */ + validate(data: any): boolean; /** * Truncates the crumb trail whenever a repeated or initial State is * encountered @@ -178,9 +184,9 @@ declare namespace Navigation { */ getHref(url: string): string; /** - * Gets a Url from the anchor + * Gets a Url from the anchor or location */ - getUrl(anchor: HTMLAnchorElement): string; + getUrl(hrefElement: HTMLAnchorElement | Location): string; /** * Removes browser history event listeners */ @@ -230,9 +236,9 @@ declare namespace Navigation { */ getHref(url: string): string; /** - * Gets a Url from the anchor + * Gets a Url from the anchor or location */ - getUrl(anchor: HTMLAnchorElement): string; + getUrl(hrefElement: HTMLAnchorElement | Location): string; /** * Removes a listener for the hashchange event */ @@ -281,9 +287,9 @@ declare namespace Navigation { */ getHref(url: string): string; /** - * Gets a Url from the anchor + * Gets a Url from the anchor or location */ - getUrl(anchor: HTMLAnchorElement): string; + getUrl(hrefElement: HTMLAnchorElement | Location): string; /** * Removes a listener for the popstate event */ @@ -381,10 +387,6 @@ declare namespace Navigation { * Crumb first */ crumbs: Crumb[]; - /** - * Gets the crumb trail - */ - crumbTrail: string[]; /** * Gets the next crumb */ From c404aa6f7bb825b5385b554b66a3e2c861bd7175 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Wed, 14 Sep 2016 14:46:59 +0200 Subject: [PATCH 065/212] Added typings for the mongoose-sequence plugin (#11201) --- mongoose-sequence/mongoose-sequence-tests.ts | 52 ++++++++++++++++++++ mongoose-sequence/mongoose-sequence.d.ts | 36 ++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 mongoose-sequence/mongoose-sequence-tests.ts create mode 100644 mongoose-sequence/mongoose-sequence.d.ts diff --git a/mongoose-sequence/mongoose-sequence-tests.ts b/mongoose-sequence/mongoose-sequence-tests.ts new file mode 100644 index 0000000000..7962afeeb4 --- /dev/null +++ b/mongoose-sequence/mongoose-sequence-tests.ts @@ -0,0 +1,52 @@ +/// +/// +/// + +/** + * Based on the examples on: https://github.com/ramiel/mongoose-sequence + * Created by Linus Brolin . + */ + +import { SequenceDocument, SequenceOptions, SequenceSchema, Document, Schema, Model, model } from 'mongoose'; +import * as mongooseSequence from 'mongoose-sequence'; + +//#region Test Models +interface User extends SequenceDocument { + name: string; + country: string; + city: string; + inhabitant_number: number; +} + +const UserSchema: SequenceSchema = new Schema({ + name: String, + country: String, + city: String, + inhabitant_number: Number +}); + +let seqOpts: SequenceOptions = { id: 'inhabitant_seq', inc_field: 'inhabitant_number', reference_fields: ['country', 'city'] }; +UserSchema.plugin(mongooseSequence, seqOpts); + +let UserModel: Model = model('User', UserSchema); +//#endregion + +//#region Test Sequence +let user: User = new UserModel({ + name: 'Patrice', + country: 'France', + city: 'Paris' +}); +user.save(); +console.log(user.inhabitant_number); + +user.setNext('inhabitant_seq', function(err: any, user: User) { + if (err) { + console.log(err); + return; + } + if (user) { + console.log(user.inhabitant_number); + } +}); +//#endregion diff --git a/mongoose-sequence/mongoose-sequence.d.ts b/mongoose-sequence/mongoose-sequence.d.ts new file mode 100644 index 0000000000..b0dec033bd --- /dev/null +++ b/mongoose-sequence/mongoose-sequence.d.ts @@ -0,0 +1,36 @@ +// Type definitions for mongoose-sequence 3.0.2 +// Project: https://github.com/ramiel/mongoose-sequence +// Definitions by: Linus Brolin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module 'mongoose' { + export interface SequenceOptions { + inc_field: string; // The name of the field to increment. Mandatory, default is _id + id?: string; // Id of the sequence. Is mandatory only for scoped sequences but its use is strongly encouraged. + reference_fields?: Array; // The field to reference for a scoped counter. Optional + disable_hooks?: boolean; // If true, the counter will not be incremented on saving a new document. Default to false + collection_name?: string; // By default the collection name to mantain the status of the counters is counters. You can override it using this option + } + + export interface SequenceDocument extends Document { + setNext(sequenceId: string, callback: (err: any, res: SequenceDocument) => void): void; + } + + export interface SequenceSchema extends Schema { + plugin( + plugin: (schema: SequenceSchema, options: SequenceOptions) => void, + options: SequenceOptions + ): this; + + // overload for the default mongoose plugin function + plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; + } +} + +declare module 'mongoose-sequence' { + import mongoose = require('mongoose'); + var _: (schema: mongoose.Schema, options?: Object) => void; + export = _; +} From 73e5a5026641eda668d1c787bfa25b065645e539 Mon Sep 17 00:00:00 2001 From: linusbrolin Date: Wed, 14 Sep 2016 14:47:12 +0200 Subject: [PATCH 066/212] Added an overload for the default mongoose plugin function (#11202) This fixes typing errors when other plugins (with different types of options) are used on the same model as this one. --- passport-local-mongoose/passport-local-mongoose.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index ab2539a709..a3b5414c84 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -74,6 +74,9 @@ declare module 'mongoose' { plugin: (schema: PassportLocalSchema, options?: PassportLocalOptions) => void, options?: PassportLocalOptions ): this; + + // overload for the default mongoose plugin function + plugin(plugin: (schema: Schema, options?: Object) => void, opts?: Object): this; } export function model( From 3a0684743e9443b8693a980ff3353d20066de0c7 Mon Sep 17 00:00:00 2001 From: Thomas Champagne Date: Wed, 14 Sep 2016 14:49:27 +0200 Subject: [PATCH 067/212] Must be "tooltips" (plurar) instead of "tooltip" (#11180) ...must be "tooltips" (plurar) instead of "tooltip" in ChartOptions My custom callback given in "ChartTooltipOptions.custom" was never called... :/ "tooltips" (plurar) is OK Take a look @ http://www.chartjs.org/docs/#advanced-usage-external-tooltips --- chart.js/chart.js.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chart.js/chart.js.d.ts b/chart.js/chart.js.d.ts index e05d930d4e..57389ee4ea 100644 --- a/chart.js/chart.js.d.ts +++ b/chart.js/chart.js.d.ts @@ -73,7 +73,7 @@ interface ChartOptions { onClick?: (any?: any) => any; title?: ChartTitleOptions; legend?: ChartLegendOptions; - tooltip?: ChartTooltipOptions; + tooltips?: ChartTooltipOptions; hover?: ChartHoverOptions; animation?: ChartAnimationOptions; elements?: ChartElementsOptions; From 5262c27b6ec4786e543c32ac83ef0b5b687987b5 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Wed, 14 Sep 2016 15:51:20 +0300 Subject: [PATCH 068/212] Fix `redux-promise` export (#11200) `redux-promise` is using an old version of Babel which transpiles `default` export to: ```js exports['default'] = promiseMiddleware; module.exports = promiseMiddleware; ``` Fix the declaration file to respect this. --- redux-promise/redux-promise-tests.ts | 2 +- redux-promise/redux-promise.d.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/redux-promise/redux-promise-tests.ts b/redux-promise/redux-promise-tests.ts index 724f695261..92a672488b 100644 --- a/redux-promise/redux-promise-tests.ts +++ b/redux-promise/redux-promise-tests.ts @@ -4,7 +4,7 @@ import {createAction} from 'redux-actions'; import { createStore, applyMiddleware, PromiseAction } from 'redux'; -import promise from 'redux-promise'; +import promise = require('redux-promise'); declare var userReducer: any; diff --git a/redux-promise/redux-promise.d.ts b/redux-promise/redux-promise.d.ts index f3fbea7240..7656def908 100644 --- a/redux-promise/redux-promise.d.ts +++ b/redux-promise/redux-promise.d.ts @@ -19,5 +19,5 @@ declare namespace ReduxPromise { declare module "redux-promise" { var promise: ReduxPromise.Promise; - export default promise; -} \ No newline at end of file + export = promise; +} From 5f23898c6fbc0b08b918b37030dedbda660a5907 Mon Sep 17 00:00:00 2001 From: sguest Date: Wed, 14 Sep 2016 07:56:56 -0500 Subject: [PATCH 069/212] videojs corrections (#11193) ready() is chainable, on() will provide event object to callback, off() can be called without callback and without event name --- videojs/videojs.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/videojs/videojs.d.ts b/videojs/videojs.d.ts index 7fb5005092..3ac6007daf 100644 --- a/videojs/videojs.d.ts +++ b/videojs/videojs.d.ts @@ -44,9 +44,11 @@ interface VideoJSPlayer { size(width: number, height: number): VideoJSPlayer; requestFullScreen(): VideoJSPlayer; cancelFullScreen(): VideoJSPlayer; - ready(callback: () => void ): void; - on(eventName: string, callback: () => void ): void; + ready(callback: () => void ): VideoJSPlayer; + on(eventName: string, callback: (eventObject: Event) => void ): void; off(eventName: string, callback: () => void ): void; + off(eventName: string): void; + off(): void; dispose(): void; addRemoteTextTrack(options : {}) : HTMLTrackElement; removeRemoteTextTrack(track : HTMLTrackElement) : void; From 3cbdc08f81f5d1b5d188fda0893936dc89cb4742 Mon Sep 17 00:00:00 2001 From: Ian Ker-Seymer Date: Wed, 14 Sep 2016 08:57:21 -0400 Subject: [PATCH 070/212] Add typings for react-virtualized (#11148) --- react-virtualized/react-virtualized-tests.tsx | 309 ++++++++++++++++++ react-virtualized/react-virtualized.d.ts | 123 +++++++ 2 files changed, 432 insertions(+) create mode 100644 react-virtualized/react-virtualized-tests.tsx create mode 100644 react-virtualized/react-virtualized.d.ts diff --git a/react-virtualized/react-virtualized-tests.tsx b/react-virtualized/react-virtualized-tests.tsx new file mode 100644 index 0000000000..d3ee9c3590 --- /dev/null +++ b/react-virtualized/react-virtualized-tests.tsx @@ -0,0 +1,309 @@ +/// +/// +/// + +import * as React from "react"; +import * as ReactDOM from "react-dom"; + +import { + Collection, + FlexTable, + FlexColumn, + SortDirection, + Grid, + VirtualScroll, + ArrowKeyStepper, + AutoSizer, + CellMeasurer, + ColumnSizer, + InfiniteLoader, + ScrollSync, + WindowScroller, +} from "react-virtualized"; + +/* + * Collection + */ + +function CollectionTest() { + const list = [ + { name: "Brian Vaughn", x: 13, y: 34, width: 123, size: 234, height: 123 } + ]; + + // Render your grid + ReactDOM.render( + list[index].name} + cellSizeAndPositionGetter={({ index }) => { + const datum = list[index]; + return { + height: datum.height, + width: datum.width, + x: datum.x, + y: datum.y + }; + } } + height={300} + width={300} + />, + document.getElementById("example") + ); +} + + +function FlexTableTest() { + const list = [ + { name: 'Brian Vaughn', description: 'Software engineer' } + // And so on... + ]; + + // Render your table + ReactDOM.render( + list[index] + } + > + + + , + document.getElementById("example") + ); +} + +function GridTest() { + // Grid data as an array of arrays + const list = [ + ['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */] + // And so on... + ]; + + // Render your grid + ReactDOM.render( + list[rowIndex][columnIndex]} + />, + document.getElementById('example') + ); +} + +function VirtualScrollTest() { + // List data as an array of strings + const list = [ + 'Brian Vaughn' + // And so on... + ]; + + // Render your list + ReactDOM.render( + list[index]} + />, + document.getElementById('example') + ); +} + +function ArrowKeyStepperTest() { + const columnCount = 12; + const rowCount = 3; + + ReactDOM.render( + + {({ onSectionRendered, scrollToColumn, scrollToRow }) => ( + + ) } + , + document.getElementById('example') + ); +} + +function AutoSizerTest() { + // List data as an array of strings + const list = [ + 'Brian Vaughn' + // And so on... + ]; + + // Render your list + ReactDOM.render( + + {({ height, width }) => ( + list[index] // Could also be a DOM element + } + /> + ) } + , + document.getElementById('example') + ); +} + +function CellMeasurerTest() { + const columnCount = 12; + const rowCount = 3; + const cellRenderer = ({ columnIndex, rowIndex }) => `${rowIndex}, ${columnIndex}`; + const fixedRowHeight = 42; + const height = 12; + const width = 12; + + ReactDOM.render( + + {({ getColumnWidth }) => ( + + ) } + , + document.getElementById('example') + ); +} + +function ColumnSizerTest() { + ReactDOM.render( + + {({ adjustedWidth, getColumnWidth, registerChild }) => ( + "test"} + rowHeight={50} + rowCount={12} + width={adjustedWidth} + /> + ) } + , + document.getElementById('example') + ); +} + +function InfiniteLoaderTest() { + const list: string[] = []; + + function isRowLoaded({ index }) { + return !!list[index]; + } + + function loadMoreRows({ startIndex, stopIndex }) { + return list.push('test'); + } + + // Render your list + ReactDOM.render( + + {({ onRowsRendered, registerChild }) => ( + list[index] // Could also be a DOM element + } + /> + ) } + , + document.getElementById('example') + ); +} + +function ScrollSyncTest() { + return ( + + {({ clientHeight, clientWidth, onScroll, scrollHeight, scrollLeft, scrollTop, scrollWidth }) => ( +
    +
    + "test"} + rowCount={42} + height={12} + width={12} + rowHeight={120} + scrollTop={scrollTop}/> + /> +
    +
    + +
    +
    + ) } +
    + ); +} + +function WindowScrollerTest() { + ReactDOM.render( + + {({ height, isScrolling, scrollTop }) => ( + 'test'} + scrollTop={scrollTop} + width={120}/> + ) } + , + document.getElementById('example') + ); +} diff --git a/react-virtualized/react-virtualized.d.ts b/react-virtualized/react-virtualized.d.ts new file mode 100644 index 0000000000..aad19c44a3 --- /dev/null +++ b/react-virtualized/react-virtualized.d.ts @@ -0,0 +1,123 @@ +// Type definitions for react-virtualized +// Project: https://github.com/bvaughn/react-virtualized +// Definitions by: Ian Ker-Seymer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module "react-virtualized" { + import * as React from "react"; + + /* + * Components + */ + + interface VirtualScrollProps { + className?: string; + autoHeight?: boolean; + estimatedRowSize?: number; + height: number; + noRowsRenderer?: Function; + onRowsRendered?: (info: { overscanStartIndex: number, overscanStopIndex: number, startIndex: number, stopIndex: number }) => void; + onScroll?: (info: { clientHeight: number, scrollHeight: number, scrollTop: number }) => void; + overscanRowCount?: number; + rowHeight: number | ((info: { index: number }) => number); + rowRenderer: (info: { index: number, isScrolling: boolean }) => React.ReactNode; + rowClassName?: string | ((info: { index: number }) => string); + rowCount: number; + rowStyle?: React.CSSProperties | ((info: { index: number }) => React.CSSProperties); + scrollToAlignment?: string; + scrollToIndex?: number; + scrollTop?: number; + style?: React.CSSProperties; + tabIndex?: number; + width: number; + } + export class VirtualScroll extends React.Component { } + + type CollectionProps = any; + export class Collection extends React.Component { } + + type FlexTableProps = any; + export class FlexTable extends React.Component { } + + type FlexColumnProps = any; + export class FlexColumn extends React.Component { } + + type SortDirectionProps = any; + export class SortDirection extends React.Component { } + + type GridProps = any; + export class Grid extends React.Component { } + + + /* + * Higher-Order Components + */ + + interface AutoSizerProps { + disableHeight?: boolean; + disableWidth?: boolean; + onResize?: (info: { height: number, width: number }) => any; + } + export class AutoSizer extends React.Component { } + + interface ArrowKeyStepperProps { + children?: React.StatelessComponent<{ + onSectionRendered: Function, + scrollToColumn: number, + scrollToRow: number + }>; + className?: string; + columnCount: number; + rowCount: number; + } + export class ArrowKeyStepper extends React.Component { } + + interface CellMeasurerProps { + cellRenderer: (info: { columnIndex: number, rowIndex: number }) => React.ReactNode; + cellSizeCache?: { + clearAllColumnWidths(): void; + clearAllRowHeights(): void; + clearColumnWidth(index: number): void; + clearRowHeight(index: number): void; + getColumnWidth(index: number): number; + getRowHeight(index: number): number; + hasColumnWidth(index: number): boolean; + hasRowHeight(index: number): boolean; + setColumnWidth(index: number, width: number): void; + setRowHeight(index: number, height: number): void; + }; + children?: React.StatelessComponent<{ + getColumnWidth: () => number, + getRowHeight: () => number, + resetMeasurements: () => any, + resetMeasurementsForColumn: (index: number) => any, + resetMeasurementsForRow: (index: number) => any, + }>; + columnCount: number; + container?: React.ReactType; + height?: number; + rowCount: number; + width?: number; + } + export class CellMeasurer extends React.Component { } + + interface ColumnSizerProps { + children?: React.StatelessComponent<{ adjustedWidth: number, getColumnWidth: () => number, registerChild: any }>; + columnMaxWidth?: number; + columnMinWidth?: number; + columnCount?: number; + width: number; + } + export class ColumnSizer extends React.Component { } + + type InfiniteLoaderProps = any; + export class InfiniteLoader extends React.Component { } + + type ScrollSyncProps = any; + export class ScrollSync extends React.Component { } + + type WindowScrollerProps = any; + export class WindowScroller extends React.Component { } +} From e9bd268321e6e3cfcebcd633054b3a4b2c4db578 Mon Sep 17 00:00:00 2001 From: Cyril Schumacher Date: Wed, 14 Sep 2016 14:58:56 +0200 Subject: [PATCH 071/212] Add definition for "bunnymq" and "strftime". (#11188) * Add definition for "bunnymq". * Add definition for "strftime". --- bunnymq/bunnymq-tests.ts | 36 +++++++++++ bunnymq/bunnymq.d.ts | 120 +++++++++++++++++++++++++++++++++++++ strftime/strftime-tests.ts | 37 ++++++++++++ strftime/strftime.d.ts | 72 ++++++++++++++++++++++ 4 files changed, 265 insertions(+) create mode 100644 bunnymq/bunnymq-tests.ts create mode 100644 bunnymq/bunnymq.d.ts create mode 100644 strftime/strftime-tests.ts create mode 100644 strftime/strftime.d.ts diff --git a/bunnymq/bunnymq-tests.ts b/bunnymq/bunnymq-tests.ts new file mode 100644 index 0000000000..208eb7e992 --- /dev/null +++ b/bunnymq/bunnymq-tests.ts @@ -0,0 +1,36 @@ +/// + +import * as bunnymq from "bunnymq"; + +// Basic usage +var instance = bunnymq({ host: 'amqp://localhost' }); + +// Publisher +instance.producer.produce('queue:name', 'Hello World!'); +// Subscriber +instance.consumer.consume('queue:name', message => { }); + +// RPC Support +instance.producer.produce('queue:name', { message: 'content' }, { rpc: true }) + .then(function (consumerResponse) { + console.log(consumerResponse); + }); + +// Routing keys +instance.producer.produce('queue:name', { message: 'content' }, { routingKey: 'my-routing-key' }); + +// Config +var custom = bunnymq({ + host: 'amqp://localhost', + //number of fetched messages at once on the channel + prefetch: 5, + //requeue put back message into the broker if consumer crashes/trigger exception + requeue: true, + //time between two reconnect (ms) + timeout: 1000, + consumerSuffix: '', + //generate a hostname so we can track this connection on the broker (rabbitmq management plugin) + hostname: "", + //the transport to use to debug. if provided, bunnymq will show some logs + transport: new Object() +}); \ No newline at end of file diff --git a/bunnymq/bunnymq.d.ts b/bunnymq/bunnymq.d.ts new file mode 100644 index 0000000000..1167db21ed --- /dev/null +++ b/bunnymq/bunnymq.d.ts @@ -0,0 +1,120 @@ +// Type definitions for node-bunnymq 2.2.1 +// Project: https://github.com/dial-once/node-bunnymq +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "bunnymq" { + namespace bunnymq { + export type ConsumerCallback = (message: Object) => void; + + /** + * Consumer. + * @interface + */ + export interface Consumer { + /** + * Handle messages from a named queue. + * @param {string} queue A named queue. + * @param {ConsumerCallback} callback A callback. + */ + consume(queue: string, callback: ConsumerCallback): void; + } + + /** + * bunnymq instance. + * @interface + */ + export interface Instance { + /** + * Consumer. + * @type {Consumer} + */ + consumer: Consumer; + + /** + * Producer. + * @type {Producer} + */ + producer: Producer; + } + + /** + * Options. + * @interface + */ + export interface Options { + /** + * Consumer suffix. + * @type {string} + */ + consumerSuffix?: string; + + /** + * Host. + * @type {string} + */ + host?: string; + + /** + * Hostname. + * @type {string} + */ + hostname?: string; + + /** + * Number of fetched messages at once on the channel. + * @type {number} + */ + prefetch?: number; + + /** + * Requeue put back message into the broker if consumer crashes/trigger exception. + * @type {boolean} + */ + requeue?: boolean; + + /** + * Time between two reconnect (in milliseconds). + * @type {number} + */ + timeout?: number; + + /** + * Transport. + * @type {any} + */ + transport?: any; + } + + /** + * Producer. + * @inteface + */ + export interface Producer { + /** + * Send messages to a named queue. + * @param {string} queue A named queue. + * @param {Object} message A message. + * @return {Object} The consumer response. + */ + produce(queue: string, message: Object, options?: ProducerOptions): PromiseLike; + } + + /** + * Options for producer. + * @interface + */ + export interface ProducerOptions { + routingKey?: string; + rpc?: boolean; + } + } + + /** + * Constructor. + * @param {Options} [options] Options. + * @return {Instance} A instance of bunnymq. + */ + function bunnymq(options?: bunnymq.Options): bunnymq.Instance; + export = bunnymq; +} diff --git a/strftime/strftime-tests.ts b/strftime/strftime-tests.ts new file mode 100644 index 0000000000..3f24a53c48 --- /dev/null +++ b/strftime/strftime-tests.ts @@ -0,0 +1,37 @@ +/// + +import * as strftime from "strftime"; + +strftime('%B %d, %Y %H:%M:%S'); +strftime('%F %T', new Date(1307472705067)); + +var it_IT = { + days: ['domenica', 'lunedi', 'martedi', 'mercoledi', 'giovedi', 'venerdi', 'sabato'], + shortDays: ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'], + months: ['gennaio', 'febbraio', 'marzo', 'aprile', 'maggio', 'giugno', 'luglio', 'agosto', 'settembre', 'ottobre', 'novembre', 'dicembre'], + shortMonths: ['gen', 'feb', 'mar', 'apr', 'mag', 'giu', 'lug', 'ago', 'set', 'ott', 'nov', 'dic'], + AM: 'AM', + PM: 'PM', + am: 'am', + pm: 'pm', + formats: { + D: '%m/%d/%y', + F: '%Y-%m-%d', + R: '%H:%M', + X: '%T', + c: '%a %b %d %X %Y', + r: '%I:%M:%S %p', + T: '%H:%M:%S', + v: '%e-%b-%Y', + x: '%D' + } +}; + +var strftimeIT = strftime.localize(it_IT); +strftimeIT('%B %d, %Y %H:%M:%S'); +strftimeIT('%B %d, %Y %H:%M:%S', new Date(1307472705067)); + +var strftimePDT = strftime.timezone(-420); +var strftimeCEST = strftime.timezone(120); +strftimePDT('%B %d, %y %H:%M:%S', new Date(1307472705067)); +strftimeCEST('%F %T', new Date(1307472705067)); \ No newline at end of file diff --git a/strftime/strftime.d.ts b/strftime/strftime.d.ts new file mode 100644 index 0000000000..4c4b8ad835 --- /dev/null +++ b/strftime/strftime.d.ts @@ -0,0 +1,72 @@ +// Type definitions for strftime 0.9.2 +// Project: https://github.com/samsonjs/strftime +// Definitions by: Cyril Schumacher +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "strftime" { + type strftimeFunction = (format: string, date?: Date) => string; + + namespace strftime { + /** + * Sets locale. + * @param {Locale} locale A locale. + * @return {strftimeFunction} A strftime function. + */ + export function localize(locale: Locale): strftimeFunction; + + /** + * Sets timezone. + * @param {number|string} offset A offset. + * @return {strftimeFunction} A strftime function. + */ + export function timezone(offset: number | string): strftimeFunction; + + /** + * Locale formats. + * @interface + */ + export interface LocaleFormats { + D?: string; + F?: string; + R?: string; + T?: string; + X?: string; + c?: string; + r?: string; + v?: string; + x?: string; + } + + /** + * Locale. + * @interface + */ + export interface Locale { + days?: Array; + shortDays?: Array; + months?: Array; + shortMonths?: Array; + AM?: string; + PM?: string; + am?: string; + pm?: string; + formats: LocaleFormats + } + } + + /** + * Format a local time/date according to locale settings + * @param {string} format A format. + * @return {string} Returns a string formatted. + */ + function strftime(format: string): string; + + /** + * Format a local time/date according to locale settings + * @param {string} format A format. + * @param {Date} date A date. + * @return {string} Returns a string formatted according format using the given date or the current local time. + */ + function strftime(format: string, date: Date): string; + export = strftime; +} From 2b69abecc831e4da5d360044efb74e13396bf7a9 Mon Sep 17 00:00:00 2001 From: Ayman Nedjmeddine Date: Wed, 14 Sep 2016 15:03:11 +0200 Subject: [PATCH 072/212] Updated Validator API to v5.7.0 (#11209) --- validator/validator-tests.ts | 31 +++++++++++-------- validator/validator.d.ts | 59 +++++++++++++++++++++--------------- 2 files changed, 52 insertions(+), 38 deletions(-) diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index 8afabc2099..96d5bc761a 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -4,9 +4,9 @@ import * as validator from 'validator'; let any: any; -/************** - * Validators * - **************/ +// ************** +// * Validators * +// ************** { let result: boolean; @@ -16,7 +16,7 @@ let any: any; result = validator.equals('sample', 'sample'); result = validator.isAfter('sample'); - result = validator.isAfter('sample', new Date()); + result = validator.isAfter('sample', new Date().toString()); result = validator.isAlpha('sample'); @@ -27,7 +27,7 @@ let any: any; result = validator.isBase64('sample'); result = validator.isBefore('sample'); - result = validator.isBefore('sample', new Date()); + result = validator.isBefore('sample', new Date().toString()); result = validator.isBoolean('sample'); @@ -42,6 +42,8 @@ let any: any; result = validator.isCurrency('sample'); result = validator.isCurrency('sample', isCurrencyOptions); + result = validator.isDataURI('sample'); + result = validator.isDate('sample'); result = validator.isDecimal('sample'); @@ -95,6 +97,8 @@ let any: any; result = validator.isMACAddress('sample'); + result = validator.isMD5('sample'); + result = validator.isMobilePhone('sample', 'en-US'); result = validator.isMongoId('sample'); @@ -113,6 +117,7 @@ let any: any; result = validator.isUUID('sample'); result = validator.isUUID('sample', 5); + result = validator.isUUID('sample', 'all'); result = validator.isUppercase('sample'); @@ -125,9 +130,9 @@ let any: any; result = validator.matches('foobar', 'foo', 'i'); } -/************** - * Sanitizers * - **************/ +// ************** +// * Sanitizers * +// ************** { let result: string; @@ -136,6 +141,8 @@ let any: any; result = validator.escape('sample'); + result = validator.unescape('sample'); + result = validator.ltrim('sample'); result = validator.ltrim('sample', ' '); @@ -175,16 +182,14 @@ let any: any; { let result: string; - result = validator.toString(any); - result = validator.trim('sample'); result = validator.trim('sample', ' '); result = validator.whitelist('sample', 'abc'); } -/************** - * Extensions * - **************/ +// ************** +// * Extensions * +// ************** validator.extend<(str: string, options: {}) => boolean>('isTest', (str: any, options: {}) => !str); diff --git a/validator/validator.d.ts b/validator/validator.d.ts index 0edb5e885b..1ec4711828 100644 --- a/validator/validator.d.ts +++ b/validator/validator.d.ts @@ -1,14 +1,14 @@ -// Type definitions for validator.js v4.5.1 +// Type definitions for validator.js v5.7.0 // Project: https://github.com/chriso/validator.js -// Definitions by: tgfjt , Ilya Mochalov +// Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace ValidatorJS { interface ValidatorStatic { - /************** - * Validators * - **************/ + // ************** + // * Validators * + // ************** // check if the string contains the seed. contains(str: string, elem: any): boolean; @@ -17,7 +17,7 @@ declare namespace ValidatorJS { equals(str: string, comparison: any): boolean; // check if the string is a date that's after the specified date (defaults to now). - isAfter(str: string, date?: Date): boolean; + isAfter(str: string, date?: string): boolean; // check if the string contains only letters (a-zA-Z). isAlpha(str: string): boolean; @@ -32,7 +32,7 @@ declare namespace ValidatorJS { isBase64(str: string): boolean; // check if the string is a date that's before the specified date. - isBefore(str: string, date?: Date): boolean; + isBefore(str: string, date?: string): boolean; // check if a string is a boolean. isBoolean(str: string): boolean; @@ -47,6 +47,9 @@ declare namespace ValidatorJS { // check if the string is a valid currency amount. isCurrency(str: string, options?: IsCurrencyOptions): boolean; + // check if the string is a data uri format (https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs) + isDataURI(str: string): boolean; + // check if the string is a date. isDate(str: string): boolean; @@ -110,8 +113,14 @@ declare namespace ValidatorJS { // check if the string is a MAC address. isMACAddress(str: string): boolean; - // check if the string is a mobile phone number, (locale is one of ['zh-CN', 'zh-TW', 'en-ZA', 'en-AU', 'en-HK', - // 'pt-PT', 'fr-FR', 'el-GR', 'en-GB', 'en-US', 'en-ZM', 'ru-RU', 'nb-NO', 'nn-NO', 'vi-VN', 'en-NZ', 'en-IN']). + // check if the string is a MD5 hash. + isMD5(str: string): boolean; + + // check if the string is a mobile phone number, (locale is one of + // ['ar-DZ', 'ar-SA', 'ar-SY', 'cs-CZ', 'de-DE', 'da-DK', 'el-GR', 'en-AU', 'en-GB', 'en-HK', + // 'en-IN', 'en-NZ', 'en-US', 'en-CA', 'en-ZA', 'en-ZM', 'es-ES', 'fi-FI', 'fr-FR', 'hu-HU', + // 'it-IT', 'ja-JP', 'ms-MY', 'nb-NO', 'nn-NO', 'pl-PL', 'pt-PT', 'ru-RU', 'sr-RS', 'tr-TR', + // 'vi-VN', 'zh-CN', 'zh-TW']). isMobilePhone(str: string, locale: string): boolean; // check if the string is a valid hex-encoded representation of a MongoDB ObjectId @@ -133,8 +142,8 @@ declare namespace ValidatorJS { // check if the string is an URL. isURL(str: string, options?: IsURLOptions): boolean; - // check if the string is a UUID (version 3, 4 or 5). - isUUID(str: string, version?: number): boolean; + // check if the string is a UUID. Must be one of ['3', '4', '5', 'all'], default is all. + isUUID(str: string, version?: string|number): boolean; // check if the string is uppercase. isUppercase(str: string): boolean; @@ -146,11 +155,11 @@ declare namespace ValidatorJS { isWhitelisted(str: string, chars: string|string[]): boolean; // check if string matches the pattern. - matches(str: string, pattern: any, modifiers?: string): boolean; + matches(str: string, pattern: RegExp|string, modifiers?: string): boolean; - /************** - * Sanitizers * - **************/ + // ************** + // * Sanitizers * + // ************** // remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need // to escape some chars, e.g. blacklist(input, '\\[\\]'). @@ -159,6 +168,9 @@ declare namespace ValidatorJS { // replace <, >, &, ', " and / with HTML entities. escape(input: string): string; + // replaces HTML encoded entities with <, >, &, ', " and /. + unescape(input: string): string; + // trim characters from the left-side of the input. ltrim(input: any, chars?: string): string; @@ -185,9 +197,6 @@ declare namespace ValidatorJS { // convert the input to an integer, or NaN if the input is not an integer. toInt(input: any, radix?: number): number; // number or NaN - // convert the input to a string. - toString(input: any): string; - // trim characters (whitespace by default) from both sides of the input. trim(input: any, chars?: string): string; @@ -195,9 +204,9 @@ declare namespace ValidatorJS { // need to escape some chars, e.g. whitelist(input, '\\[\\]'). whitelist(input: string, chars: string): string; - /************** - * Extensions * - **************/ + // ************** + // * Extensions * + // ************** // add your own validators. // Note: that the first argument will be automatically coerced to a string. @@ -263,10 +272,11 @@ declare namespace ValidatorJS { protocols?: string[]; require_tld?: boolean; require_protocol?: boolean; + require_host: boolean; require_valid_protocol?: boolean; allow_underscores?: boolean; - host_whitelist?: boolean; - host_blacklist?: boolean; + host_whitelist?: (string|RegExp)[]; + host_blacklist?: (string|RegExp)[]; allow_trailing_dot?: boolean; allow_protocol_relative_urls?: boolean; } @@ -280,8 +290,7 @@ declare namespace ValidatorJS { } declare module "validator" { - let validator: ValidatorJS.ValidatorStatic; - namespace validator {} + const validator: ValidatorJS.ValidatorStatic; export = validator; } From 489541498b7a896cfa99348afb56c9530a60c85d Mon Sep 17 00:00:00 2001 From: Jonathon T Date: Wed, 14 Sep 2016 23:11:04 +1000 Subject: [PATCH 073/212] [angular-ui-scroll] Include startIndex parameter on adapter reload() method (#11216) As per docs here: https://github.com/angular-ui/ui-scroll `reload()` includes a `startIndex` parameterl; --- angular-ui-scroll/angular-ui-scroll.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts index 168c6ba271..5f24c8ec38 100644 --- a/angular-ui-scroll/angular-ui-scroll.d.ts +++ b/angular-ui-scroll/angular-ui-scroll.d.ts @@ -42,9 +42,10 @@ declare namespace angular.ui { */ topVisibleScope: ng.IRepeatScope; /** - * calling this method reinitializes and reloads the scroller content. + * calling this method reinitializes and reloads the scroller content. + * @param startIndex is an integer indicating what item index the scroller will use to start the load process. */ - reload(): void; + reload(startIndex?: number): void; /** * Replaces the item in the buffer at the given index with the new items. * From ef6b6ef139d11e9fe25fe668e8e5b0fa0ba8a9f7 Mon Sep 17 00:00:00 2001 From: Meno Abels Date: Wed, 14 Sep 2016 15:11:22 +0200 Subject: [PATCH 074/212] Added https type to Websocket.Server (#11213) * Added https type to Websocket.Server Hi, the current typing misses to pass to the Websocket.Server server option a https Server. Cheers meno * * added a test * fix the missing typo of http(s) * improve the test --- ws/ws-tests.ts | 9 ++++++++- ws/ws.d.ts | 3 ++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/ws/ws-tests.ts b/ws/ws-tests.ts index a8afa8cb99..3c85d678cb 100644 --- a/ws/ws-tests.ts +++ b/ws/ws-tests.ts @@ -2,6 +2,7 @@ import * as WebSocket from 'ws'; import * as http from'http'; +import * as https from'https'; var WebSocketServer = WebSocket.Server; @@ -54,6 +55,12 @@ var WebSocketServer = WebSocket.Server; }); } +{ + new WebSocket.Server({ server: https.createServer({}) }); + new WebSocket.Server({ server: http.createServer() }); +} + + { const verifyClient = function( info: { @@ -73,4 +80,4 @@ var WebSocketServer = WebSocket.Server; wsv.on('connection', function connection(ws) { console.log(ws.protocol) }) -} \ No newline at end of file +} diff --git a/ws/ws.d.ts b/ws/ws.d.ts index 2b16bd52ea..b7ce3bd829 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -8,6 +8,7 @@ declare module "ws" { import * as events from 'events'; import * as http from 'http'; + import * as https from 'https'; import * as net from 'net'; class WebSocket extends events.EventEmitter { @@ -99,7 +100,7 @@ declare module "ws" { export interface IServerOptions { host?: string; port?: number; - server?: http.Server; + server?: http.Server | https.Server; verifyClient?: VerifyClientCallbackAsync | VerifyClientCallbackSync; handleProtocols?: any; path?: string; From 8193bc8f6eaf97fc1272c7c503c03d999b379a89 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 21:13:43 +0800 Subject: [PATCH 075/212] [node.d.ts] Add definite events for Readable and Writable (#11217) * Add definite events for Readable and Writable * Delete comments in cluster * Recovery cluster * Remove interface extends events.EventEmitter --- node/node.d.ts | 157 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 141 insertions(+), 16 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index 76a42f4013..76c5c05c94 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -281,8 +281,8 @@ declare namespace NodeJS { } export interface ReadWriteStream extends ReadableStream, WritableStream { - pause(): ReadWriteStream; - resume(): ReadWriteStream; + pause(): ReadWriteStream; + resume(): ReadWriteStream; } export interface Events extends EventEmitter { } @@ -456,7 +456,7 @@ declare namespace NodeJS { } } -interface IterableIterator {} +interface IterableIterator { } /** * @deprecated @@ -588,7 +588,7 @@ declare module "http" { agent?: Agent | boolean; } - export interface Server extends events.EventEmitter, net.Server { + export interface Server extends net.Server { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; timeout: number; @@ -599,7 +599,7 @@ declare module "http" { export interface ServerRequest extends IncomingMessage { connection: net.Socket; } - export interface ServerResponse extends events.EventEmitter, stream.Writable { + export interface ServerResponse extends stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -629,7 +629,7 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface ClientRequest extends events.EventEmitter, stream.Writable { + export interface ClientRequest extends stream.Writable { // Extended base methods write(buffer: Buffer): boolean; write(buffer: Buffer, cb?: Function): boolean; @@ -655,7 +655,7 @@ declare module "http" { end(str: string, encoding?: string, cb?: Function): void; end(data?: any, encoding?: string): void; } - export interface IncomingMessage extends events.EventEmitter, stream.Readable { + export interface IncomingMessage extends stream.Readable { httpVersion: string; httpVersionMajor: string; httpVersionMinor: string; @@ -1040,7 +1040,7 @@ declare module "https" { requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: any; - SNICallback?: (servername: string, cb:(err:Error,ctx:tls.SecureContext)=>any) => any; + SNICallback?: (servername: string, cb: (err: Error, ctx: tls.SecureContext) => any) => any; } export interface RequestOptions extends http.RequestOptions { @@ -1853,7 +1853,7 @@ declare module "fs" { } export const constants: Constants; - + /** Tests a user's permissions for the file specified by path. */ export function access(path: string | Buffer, callback: (err: NodeJS.ErrnoException) => void): void; export function access(path: string | Buffer, mode: number, callback: (err: NodeJS.ErrnoException) => void): void; @@ -2196,7 +2196,7 @@ declare module "tls" { requestCert?: boolean; rejectUnauthorized?: boolean; NPNProtocols?: string[] | Buffer; - SNICallback?: (servername: string, cb:(err:Error,ctx:SecureContext)=>any) => any; + SNICallback?: (servername: string, cb: (err: Error, ctx: SecureContext) => any) => any; ecdhCurve?: string; dhparam?: string | Buffer; handshakeTimeout?: number; @@ -2212,7 +2212,7 @@ declare module "tls" { port?: number; socket?: net.Socket; pfx?: string | Buffer - key?: string |string[] | Buffer | Buffer[]; + key?: string | string[] | Buffer | Buffer[]; passphrase?: string; cert?: string | string[] | Buffer | Buffer[]; ca?: string | Buffer | (string | Buffer)[]; @@ -2445,7 +2445,7 @@ declare module "stream" { } namespace internal { - export class Stream extends internal {} + export class Stream extends internal { } export interface ReadableOptions { highWaterMark?: number; @@ -2467,14 +2467,73 @@ declare module "stream" { unshift(chunk: any): void; wrap(oldStream: NodeJS.ReadableStream): NodeJS.ReadableStream; push(chunk: any, encoding?: string): boolean; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. readable + * 5. error + **/ + addListener(event: string, listener: Function): this; + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; } export interface WritableOptions { highWaterMark?: number; decodeStrings?: boolean; objectMode?: boolean; - write?: (chunk: string|Buffer, encoding: string, callback: Function) => any; - writev?: (chunks: {chunk: string|Buffer, encoding: string}[], callback: Function) => any; + write?: (chunk: string | Buffer, encoding: string, callback: Function) => any; + writev?: (chunks: { chunk: string | Buffer, encoding: string }[], callback: Function) => any; } export class Writable extends events.EventEmitter implements NodeJS.WritableStream { @@ -2486,6 +2545,72 @@ declare module "stream" { end(): void; end(chunk: any, cb?: Function): void; end(chunk: any, encoding?: string, cb?: Function): void; + + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + **/ + addListener(event: string, listener: Function): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "drain", chunk: Buffer | string): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + + on(event: string, listener: Function): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + + once(event: string, listener: Function): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + + removeListener(event: string, listener: Function): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; } export interface DuplexOptions extends ReadableOptions, WritableOptions { @@ -2511,7 +2636,7 @@ declare module "stream" { } export interface TransformOptions extends ReadableOptions, WritableOptions { - transform?: (chunk: string|Buffer, encoding: string, callback: Function) => any; + transform?: (chunk: string | Buffer, encoding: string, callback: Function) => any; flush?: (callback: Function) => any; } @@ -2949,7 +3074,7 @@ declare module "v8" { space_available_size: number; physical_space_size: number; } - export function getHeapStatistics() : {total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number}; + export function getHeapStatistics(): { total_heap_size: number, total_heap_size_executable: number, total_physical_size: number, total_avaialble_size: number, used_heap_size: number, heap_size_limit: number }; export function getHeapSpaceStatistics(): HeapSpaceInfo[]; export function setFlagsFromString(flags: string): void; } From 81197a3926d297f76fc4bb4b77d260100c429843 Mon Sep 17 00:00:00 2001 From: rgozim Date: Wed, 14 Sep 2016 14:16:59 +0100 Subject: [PATCH 076/212] Change #Extend PolyMouseEvent interface from MouseEvent interface (#11218) PolyMouseEvent should inherit from MouseEvent according to google documentation https://developers.google.com/maps/documentation/javascript/3.exp/reference#PolyMouseEvent --- googlemaps/google.maps.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/googlemaps/google.maps.d.ts b/googlemaps/google.maps.d.ts index 0eaa0b9c3d..0aef3b74a6 100644 --- a/googlemaps/google.maps.d.ts +++ b/googlemaps/google.maps.d.ts @@ -756,7 +756,7 @@ declare namespace google.maps { zIndex?: number; } - export interface PolyMouseEvent { + export interface PolyMouseEvent extends MouseEvent { edge?: number; path?: number; vertex?: number; From 3423aa94ffdbe8f4ded33733318e08020a2d6ca8 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Wed, 14 Sep 2016 21:17:36 +0800 Subject: [PATCH 077/212] connection are socket are same in IncomingMessage (#11219) --- node/node.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node/node.d.ts b/node/node.d.ts index 76c5c05c94..2094959e6e 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -659,7 +659,7 @@ declare module "http" { httpVersion: string; httpVersionMajor: string; httpVersionMinor: string; - connection: any; + connection: net.Socket; headers: any; rawHeaders: string[]; trailers: any; From ff71c3d812952fb56c73ae0ff57b0d0cf4b220d8 Mon Sep 17 00:00:00 2001 From: Nick Graef Date: Wed, 14 Sep 2016 08:20:03 -0500 Subject: [PATCH 078/212] enforce action hash type in $resource() (#11212) --- angularjs/angular-resource.d.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts index 3deed5d2fa..f7e803c1c8 100644 --- a/angularjs/angular-resource.d.ts +++ b/angularjs/angular-resource.d.ts @@ -42,15 +42,20 @@ declare namespace angular.resource { (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass>; + actions?: IActionHash, options?: IResourceOptions): IResourceClass>; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): U; + actions?: IActionHash, options?: IResourceOptions): U; (url: string, paramDefaults?: any, /** example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor : IActionDescriptor */ - actions?: any, options?: IResourceOptions): IResourceClass; + actions?: IActionHash, options?: IResourceOptions): IResourceClass; + } + + // Hash of action descriptors allows custom action names + interface IActionHash { + [action: string]: IActionDescriptor } // Just a reference to facilitate describing new actions From b73aaa36d313393d8aaa5411669cf4e0f6b16759 Mon Sep 17 00:00:00 2001 From: Leo Rudberg Date: Wed, 14 Sep 2016 08:20:28 -0500 Subject: [PATCH 079/212] Fixes #10684 (#10751) I kept the deprecated `pick` declarations, but added the proposed (JSDoc-influenced) [deprecation annotation](https://github.com/Microsoft/TypeScript/issues/390) to them. The added `pickone` and `pickset` declarations have identical types to their respective `pick` flavors. --- chance/chance.d.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/chance/chance.d.ts b/chance/chance.d.ts index 290cde8048..6390b57864 100644 --- a/chance/chance.d.ts +++ b/chance/chance.d.ts @@ -114,8 +114,16 @@ declare namespace Chance { capitalize(str: string): string; mixin(desc: MixinDescriptor): any; pad(num: number, width: number, padChar?: string): string; + /** + * @deprecated Use pickone + */ pick(arr: T[]): T; + pickone(arr: T[]): T; + /** + * @deprecated Use pickset + */ pick(arr: T[], count: number): T[]; + pickset(arr: T[], count: number): T[]; set: Setter; shuffle(arr: T[]): T[]; From f46e80640829b7dc43a4030868c1e82889acdabd Mon Sep 17 00:00:00 2001 From: Craig Date: Wed, 14 Sep 2016 06:21:51 -0700 Subject: [PATCH 080/212] types(selenium-webdriver): version 2.53.1 (#10852) - moving selenium-webdriver.d.ts to selenium-webdriver-2.44.0.d.ts - adding in selenium-webdriver.d.ts for version 2.53.1 --- angular-protractor/angular-protractor.d.ts | 2 +- protractor-helpers/protractor-helpers.d.ts | 3 +- .../protractor-http-mock.d.ts | 2 +- .../selenium-webdriver-2.44.0.d.ts | 5393 +++++++++++++++++ .../selenium-webdriver-tests.ts | 249 +- selenium-webdriver/selenium-webdriver.d.ts | 3992 +++++++----- 6 files changed, 7999 insertions(+), 1642 deletions(-) create mode 100644 selenium-webdriver/selenium-webdriver-2.44.0.d.ts diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index d33eeddace..add8264b7e 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bill Armstrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace protractor { //region Wrapped webdriver Items diff --git a/protractor-helpers/protractor-helpers.d.ts b/protractor-helpers/protractor-helpers.d.ts index 20aad94c54..16d67cfbb9 100644 --- a/protractor-helpers/protractor-helpers.d.ts +++ b/protractor-helpers/protractor-helpers.d.ts @@ -5,7 +5,7 @@ /// /// -/// +/// // ElementArrayFinder @@ -108,4 +108,3 @@ declare module "protractor-helpers" { function getFilteredConsoleErrors() : webdriver.promise.IThenable; // TODO - discuss handling in IE } - diff --git a/protractor-http-mock/protractor-http-mock.d.ts b/protractor-http-mock/protractor-http-mock.d.ts index 29d6dfb276..2300246e43 100644 --- a/protractor-http-mock/protractor-http-mock.d.ts +++ b/protractor-http-mock/protractor-http-mock.d.ts @@ -3,7 +3,7 @@ // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace mock { interface ProtractorHttpMock { diff --git a/selenium-webdriver/selenium-webdriver-2.44.0.d.ts b/selenium-webdriver/selenium-webdriver-2.44.0.d.ts new file mode 100644 index 0000000000..548048b695 --- /dev/null +++ b/selenium-webdriver/selenium-webdriver-2.44.0.d.ts @@ -0,0 +1,5393 @@ +// Type definitions for Selenium WebDriverJS 2.44.0 +// Project: https://code.google.com/p/selenium/ +// Definitions by: Bill Armstrong , Yuki Kokubun +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace chrome { + /** + * Creates a new WebDriver client for Chrome. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(webdriver.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + interface IOptionsValues { + args: string[]; + binary?: string; + detach: boolean; + extensions: string[]; + localState?: any; + logFile?: string; + prefs?: any; + } + + interface IPerfLoggingPrefs { + enableNetwork: boolean; + enablePage: boolean; + enableTimeline: boolean; + tracingCategories: string; + bufferUsageReportingInterval: number; + } + + /** + * Class for managing ChromeDriver specific options. + */ + class Options { + /** + * @constructor + */ + constructor(); + + /** + * Extracts the ChromeDriver specific options from the given capabilities + * object. + * @param {!webdriver.Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + + /** + * Add additional command line arguments to use when launching the Chrome + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: string[]): Options; + + + /** + * List of Chrome command line switches to exclude that ChromeDriver by default + * passes when starting Chrome. Do not prefix switches with "--". + * + * @param {...(string|!Array)} var_args The switches to exclude. + * @return {!Options} A self reference. + */ + excludeSwitches(...var_args: string[]): Options; + + + /** + * Add additional extensions to install when launching Chrome. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: any[]): Options; + + + /** + * Sets the path to the Chrome binary to use. On Mac OS X, this path should + * reference the actual Chrome executable, not just the application binary + * (e.g. "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"). + * + * The binary path be absolute or relative to the chromedriver server + * executable, but it must exist on the machine that will launch Chrome. + * + * @param {string} path The path to the Chrome binary to use. + * @return {!Options} A self reference. + */ + setChromeBinaryPath(path: string): Options; + + + /** + * Sets whether to leave the started Chrome browser running if the controlling + * ChromeDriver service is killed before {@link webdriver.WebDriver#quit()} is + * called. + * @param {boolean} detach Whether to leave the browser running if the + * chromedriver service is killed before the session. + * @return {!Options} A self reference. + */ + detachDriver(detach: boolean): Options; + + + /** + * Sets the user preferences for Chrome's user profile. See the "Preferences" + * file in Chrome's user data directory for examples. + * @param {!Object} prefs Dictionary of user preferences to use. + * @return {!Options} A self reference. + */ + setUserPreferences(prefs: any): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {!webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the performance logging preferences. Options include: + * + * - `enableNetwork`: Whether or not to collect events from Network domain. + * - `enablePage`: Whether or not to collect events from Page domain. + * - `enableTimeline`: Whether or not to collect events from Timeline domain. + * Note: when tracing is enabled, Timeline domain is implicitly disabled, + * unless `enableTimeline` is explicitly set to true. + * - `tracingCategories`: A comma-separated string of Chrome tracing categories + * for which trace events should be collected. An unspecified or empty + * string disables tracing. + * - `bufferUsageReportingInterval`: The requested number of milliseconds + * between DevTools trace buffer usage events. For example, if 1000, then + * once per second, DevTools will report how full the trace buffer is. If a + * report indicates the buffer usage is 100%, a warning will be issued. + * + * @param {{enableNetwork: boolean, + * enablePage: boolean, + * enableTimeline: boolean, + * tracingCategories: string, + * bufferUsageReportingInterval: number}} prefs The performance + * logging preferences. + * @return {!Options} A self reference. + */ + setPerfLoggingPrefs(prefs: IPerfLoggingPrefs): Options; + + + /** + * Sets preferences for the "Local State" file in Chrome's user data + * directory. + * @param {!Object} state Dictionary of local state preferences. + * @return {!Options} A self reference. + */ + setLocalState(state: any): Options; + + + /** + * Sets the name of the activity hosting a Chrome-based Android WebView. This + * option must be set to connect to an [Android WebView]( + * https://sites.google.com/a/chromium.org/chromedriver/getting-started/getting-started---android) + * + * @param {string} name The activity name. + * @return {!Options} A self reference. + */ + androidActivity(name: string): Options; + + + /** + * Sets the device serial number to connect to via ADB. If not specified, the + * ChromeDriver will select an unused device at random. An error will be + * returned if all devices already have active sessions. + * + * @param {string} serial The device serial number to connect to. + * @return {!Options} A self reference. + */ + androidDeviceSerial(serial: string): Options; + + + /** + * Configures the ChromeDriver to launch Chrome on Android via adb. This + * function is shorthand for + * {@link #androidPackage options.androidPackage('com.android.chrome')}. + * @return {!Options} A self reference. + */ + androidChrome(): Options; + + + /** + * Sets the package name of the Chrome or WebView app. + * + * @param {?string} pkg The package to connect to, or `null` to disable Android + * and switch back to using desktop Chrome. + * @return {!Options} A self reference. + */ + androidPackage(pkg: string): Options; + + + /** + * Sets the process name of the Activity hosting the WebView (as given by `ps`). + * If not specified, the process name is assumed to be the same as + * {@link #androidPackage}. + * + * @param {string} processName The main activity name. + * @return {!Options} A self reference. + */ + androidProcess(processName: string): Options; + + + /** + * Sets whether to connect to an already-running instead of the specified + * {@linkplain #androidProcess app} instead of launching the app with a clean + * data directory. + * + * @param {boolean} useRunning Whether to connect to a running instance. + * @return {!Options} A self reference. + */ + androidUseRunningApp(useRunning: boolean): Options; + + + /** + * Sets the path to Chrome's log file. This path should exist on the machine + * that will launch Chrome. + * @param {string} path Path to the log file to use. + * @return {!Options} A self reference. + */ + setChromeLogFile(path: string): Options; + + + /** + * Sets the proxy settings for the new session. + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts this options instance to a {@link webdriver.Capabilities} object. + * @param {webdriver.Capabilities=} opt_capabilities The capabilities to merge + * these options into, if any. + * @return {!webdriver.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + + + /** + * Converts this instance to its JSON wire protocol representation. Note this + * function is an implementation not intended for general use. + * @return {{args: !Array., + * binary: (string|undefined), + * detach: boolean, + * extensions: !Array., + * localState: (Object|undefined), + * logFile: (string|undefined), + * prefs: (Object|undefined)}} The JSON wire protocol representation + * of this instance. + */ + toJSON(): IOptionsValues; + } + + /** + * Creates {@link remote.DriverService} instances that manage a ChromeDriver + * server. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the chromedriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the chromedriver + * cannot be found on the PATH. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the ChromeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + + /** + * Sets which port adb is listening to. _The ChromeDriver will connect to adb + * if an {@linkplain Options#androidPackage Android session} is requested, but + * adb **must** be started beforehand._ + * + * @param {number} port Which port adb is running on. + * @return {!ServiceBuilder} A self reference. + */ + setAdbPort(port: number): ServiceBuilder; + + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + + /** + * Sets the number of threads the driver should use to manage HTTP requests. + * By default, the driver will use 4 threads. + * @param {number} n The number of threads to use. + * @return {!ServiceBuilder} A self reference. + */ + setNumHttpThreads(n: number): ServiceBuilder; + + + /** + * Sets the base path for WebDriver REST commands (e.g. "/wd/hub"). + * By default, the driver will accept commands relative to "/". + * @param {string} path The base path to use. + * @return {!ServiceBuilder} A self reference. + */ + setUrlBasePath(path: string): ServiceBuilder; + + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} config The + * configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string): ServiceBuilder; + setStdio(config: any[]): ServiceBuilder; + + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: { [key: string]: string }): ServiceBuilder; + + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): any; + } + + /** + * Returns the default ChromeDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a ChromeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default ChromeDriver service. + */ + function getDefaultService(): any; + + /** + * Sets the default service to use for new ChromeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: any): void; +} + +declare namespace firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; + } + + /** + * A WebDriver client for Firefox. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|webdriver.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash + * object. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * @constructor + */ + constructor(); + + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string): Options; + setProfile(profile: Profile): Options; + + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string): Options; + setBinary(binary: Binary): Options; + + + /** + * Sets the logging preferences for the new session. + * @param {webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets the proxy to use. + * + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts these options to a {@link webdriver.Capabilities} instance. + * + * @return {!webdriver.Capabilities} A new capabilities object. + */ + toCapabilities(opt_remote?: any): webdriver.Capabilities; + } + + /** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; + } +} + +declare namespace executors { + /** + * Creates a command executor that uses WebDriver's JSON wire protocol. + * @param url The server's URL, or a promise that will resolve to that URL. + * @returns {!webdriver.CommandExecutor} The new command executor. + */ + function createExecutor(url: string): webdriver.CommandExecutor; + function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; +} + +declare namespace webdriver { + + namespace error { + interface IErrorCode { + SUCCESS: number; + + NO_SUCH_ELEMENT: number; + NO_SUCH_FRAME: number; + UNKNOWN_COMMAND: number; + UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. + STALE_ELEMENT_REFERENCE: number; + ELEMENT_NOT_VISIBLE: number; + INVALID_ELEMENT_STATE: number; + UNKNOWN_ERROR: number; + ELEMENT_NOT_SELECTABLE: number; + JAVASCRIPT_ERROR: number; + XPATH_LOOKUP_ERROR: number; + TIMEOUT: number; + NO_SUCH_WINDOW: number; + INVALID_COOKIE_DOMAIN: number; + UNABLE_TO_SET_COOKIE: number; + MODAL_DIALOG_OPENED: number; + UNEXPECTED_ALERT_OPEN: number; + NO_SUCH_ALERT: number; + NO_MODAL_DIALOG_OPEN: number; + SCRIPT_TIMEOUT: number; + INVALID_ELEMENT_COORDINATES: number; + IME_NOT_AVAILABLE: number; + IME_ENGINE_ACTIVATION_FAILED: number; + INVALID_SELECTOR_ERROR: number; + SESSION_NOT_CREATED: number; + MOVE_TARGET_OUT_OF_BOUNDS: number; + SQL_DATABASE_ERROR: number; + INVALID_XPATH_SELECTOR: number; + INVALID_XPATH_SELECTOR_RETURN_TYPE: number; + // The following error codes are derived straight from HTTP return codes. + METHOD_NOT_ALLOWED: number; + } + + var ErrorCode: IErrorCode; + + /** + * Error extension that includes error status codes from the WebDriver wire + * protocol: + * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes + * + * @extends {Error} + */ + class Error { + + //region Constructors + + /** + * @param {!bot.ErrorCode} code The error's status code. + * @param {string=} opt_message Optional error message. + * @constructor + */ + constructor(code: number, opt_message?: string); + + //endregion + + //region Static Properties + + /** + * Status strings enumerated in the W3C WebDriver working draft. + * @enum {string} + * @see http://www.w3.org/TR/webdriver/#status-codes + */ + static State: { + ELEMENT_NOT_SELECTABLE: string; + ELEMENT_NOT_VISIBLE: string; + IME_ENGINE_ACTIVATION_FAILED: string; + IME_NOT_AVAILABLE: string; + INVALID_COOKIE_DOMAIN: string; + INVALID_ELEMENT_COORDINATES: string; + INVALID_ELEMENT_STATE: string; + INVALID_SELECTOR: string; + JAVASCRIPT_ERROR: string; + MOVE_TARGET_OUT_OF_BOUNDS: string; + NO_SUCH_ALERT: string; + NO_SUCH_DOM: string; + NO_SUCH_ELEMENT: string; + NO_SUCH_FRAME: string; + NO_SUCH_WINDOW: string; + SCRIPT_TIMEOUT: string; + SESSION_NOT_CREATED: string; + STALE_ELEMENT_REFERENCE: string; + SUCCESS: string; + TIMEOUT: string; + UNABLE_TO_SET_COOKIE: string; + UNEXPECTED_ALERT_OPEN: string; + UNKNOWN_COMMAND: string; + UNKNOWN_ERROR: string; + UNSUPPORTED_OPERATION: string; + }; + + //endregion + + //region Properties + + /** + * This error's status code. + * @type {!bot.ErrorCode} + */ + code: number; + + /** @type {string} */ + state: string; + + /** @override */ + message: string; + + /** @override */ + name: string; + + /** @override */ + stack: string; + + /** + * Flag used for duck-typing when this code is embedded in a Firefox extension. + * This is required since an Error thrown in one component and then reported + * to another will fail instanceof checks in the second component. + * @type {boolean} + */ + isAutomationError: boolean; + + //endregion + + //region Methods + + /** @return {string} The string representation of this error. */ + toString(): string; + + //endregion + } + } + + namespace logging { + + /** + * A hash describing log preferences. + * @typedef {Object.} + */ + class Preferences { + setLevel(type: string, level: ILevel): void; + toJSON(): { [key: string]: string }; + } + + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: string; + } + + /** + * Common log types. + * @enum {string} + */ + var Type: IType; + + /** + * Logging levels. + * @enum {{value: number, name: webdriver.logging.LevelName}} + */ + interface ILevel { + value: number; + name: string; + } + + interface ILevelValues { + ALL: ILevel; + DEBUG: ILevel; + INFO: ILevel; + WARNING: ILevel; + SEVERE: ILevel; + OFF: ILevel; + } + + var Level: ILevelValues; + + /** + * Converts a level name or value to a {@link webdriver.logging.Level} value. + * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} + * will be returned. + * @param {(number|string)} nameOrValue The log level name, or value, to + * convert . + * @return {!webdriver.logging.Level} The converted level. + */ + function getLevel(nameOrValue: string): ILevel; + function getLevel(nameOrValue: number): ILevel; + + interface IEntryJSON { + level: string; + message: string; + timestamp: number; + type: string; + } + + /** + * A single log entry. + */ + class Entry { + + //region Constructors + + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); + constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + + //endregion + + //region Public Properties + + /** @type {!webdriver.logging.Level} */ + level: ILevel; + + /** @type {string} */ + message: string; + + /** @type {number} */ + timestamp: number; + + /** @type {string} */ + type: string; + + //endregion + + //region Static Methods + + /** + * Converts a {@link goog.debug.LogRecord} into a + * {@link webdriver.logging.Entry}. + * @param {!goog.debug.LogRecord} logRecord The record to convert. + * @param {string=} opt_type The log type. + * @return {!webdriver.logging.Entry} The converted entry. + */ + static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + + //endregion + + //region Methods + + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + + //endregion + } + } + + namespace promise { + //region Functions + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * promises to wait on. + * @return {!webdriver.promise.Promise.>} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: Promise[]): Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: Function, opt_errback?: Function): void; + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: ControlFlow) => R): Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + *

    If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + *

    If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ( + * boolean|webdriver.promise.Promise.)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; + function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + + /** + * Creates a new deferred object. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(): Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: T): Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + *

    If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + *

    If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + *

    Example 1: the Fibonacci Sequence. + *

    
    +         * webdriver.promise.consume(function* fibonacci() {
    +         *   var n1 = 1, n2 = 1;
    +         *   for (var i = 0; i < 4; ++i) {
    +         *     var tmp = yield n1 + n2;
    +         *     n1 = n2;
    +         *     n2 = tmp;
    +         *   }
    +         *   return n1 + n2;
    +         * }).then(function(result) {
    +         *   console.log(result);  // 13
    +         * });
    +         * 
    + * + *

    Example 2: a generator that throws. + *

    
    +         * webdriver.promise.consume(function* () {
    +         *   yield webdriver.promise.delayed(250).then(function() {
    +         *     throw Error('boom');
    +         *   });
    +         * }).thenCatch(function(e) {
    +         *   console.log(e.toString());  // Error: boom
    +         * });
    +         * 
    + * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as "this" when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: ControlFlow): void; + + //endregion + + /** + * Error used when the computation of a promise is cancelled. + * + * @extends {goog.debug.Error} + * @final + */ + class CancellationError { + /** + * @param {string=} opt_msg The cancellation message. + * @constructor + */ + constructor(opt_msg?: string); + + name: string; + message: string; + } + + interface IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } catch (ex) {
    +             *     console.error(ex);
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenCatch(function(ex) {
    +             *     console.error(ex);
    +             *   });
    +             * 
    + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } finally {
    +             *     cleanUp();
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenFinally(cleanUp);
    +             * 
    + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
    
    +             *   try {
    +             *     throw Error('one');
    +             *   } finally {
    +             *     throw Error('two');  // Hides Error: one
    +             *   }
    +             *
    +             *   webdriver.promise.rejected(Error('one'))
    +             *       .thenFinally(function() {
    +             *         throw Error('two');  // Hides Error: one
    +             *       });
    +             * 
    + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + } + + /** + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ + class Thenable implements IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } catch (ex) {
    +             *     console.error(ex);
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenCatch(function(ex) {
    +             *     console.error(ex);
    +             *   });
    +             * 
    + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } finally {
    +             *     cleanUp();
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenFinally(cleanUp);
    +             * 
    + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
    
    +             *   try {
    +             *     throw Error('one');
    +             *   } finally {
    +             *     throw Error('two');  // Hides Error: one
    +             *   }
    +             *
    +             *   webdriver.promise.rejected(Error('one'))
    +             *       .thenFinally(function() {
    +             *         throw Error('two');  // Hides Error: one
    +             *       });
    +             * 
    + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + + /** + * Adds a property to a class prototype to allow runtime checks of whether + * instances of that class implement the Thenable interface. This function will + * also ensure the prototype's {@code then} function is exported from compiled + * code. + * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * constructor whose prototype to modify. + */ + static addImplementation(ctor: Function): void; + + + /** + * Checks if an object has been tagged for implementing the Thenable interface + * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + interface IFulfilledCallback { + (value: T|IThenable|Thenable|void): void; + } + + interface IRejectedCallback { + (reason: any): void; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, fulfilled, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or rejected state, at which point the promise is considered + * resolved. + * + * @implements {promise.Thenable} + * @template T + * @see http://promises-aplus.github.io/promises-spec/ + */ + class Promise implements IThenable { + /** + * @param {function( + * function((T|IThenable|Thenable)=), + * function(*=))} resolver + * Function that is invoked immediately to begin computation of this + * promise's value. The function should accept a pair of callback functions, + * one for fulfilling the promise and another for rejecting it. + * @param {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + * @constructor + */ + constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); + constructor(); // For angular-protractor/angular-protractor-tests.ts + + //region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(reason: any): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } catch (ex) {
    +             *     console.error(ex);
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenCatch(function(ex) {
    +             *     console.error(ex);
    +             *   });
    +             * 
    + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } finally {
    +             *     cleanUp();
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenFinally(cleanUp);
    +             * 
    + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
    
    +             *   try {
    +             *     throw Error('one');
    +             *   } finally {
    +             *     throw Error('two');  // Hides Error: one
    +             *   }
    +             *
    +             *   webdriver.promise.rejected(Error('one'))
    +             *       .thenFinally(function() {
    +             *         throw Error('two');  // Hides Error: one
    +             *       });
    +             * 
    + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + + //endregion + } + + /** + * Represents a value that will be resolved at some point in the future. This + * class represents the protected "producer" half of a Promise - each Deferred + * has a {@code promise} property that may be returned to consumers for + * registering callbacks, reserving the ability to resolve the deferred to the + * producer. + * + *

    If this Deferred is rejected and there are no listeners registered before + * the next turn of the event loop, the rejection will be passed to the + * {@link webdriver.promise.ControlFlow} as an unhandled failure. + * + *

    If this Deferred is cancelled, the cancellation reason will be forward to + * the Deferred's canceller function (if provided). The canceller may return a + * truth-y value to override the reason provided for rejection. + * + * @extends {webdriver.promise.Promise} + */ + class Deferred extends Promise { + //region Constructors + + /** + * + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow + * this instance was created under. This should only be provided during + * unit tests. + * @constructor + */ + constructor(opt_flow?: ControlFlow); + + //endregion + + static State_: { + BLOCKED: number; + PENDING: number; + REJECTED: number; + RESOLVED: number; + }; + + //region Properties + + /** + * The consumer promise for this instance. Provides protected access to the + * callback registering functions. + * @type {!webdriver.promise.Promise} + */ + promise: Promise; + + //endregion + + //region Methods + + /** + * Rejects this promise. If the error is itself a promise, this instance will + * be chained to it and be rejected with the error's resolved value. + * @param {*=} opt_error The rejection reason, typically either a + * {@code Error} or a {@code string}. + */ + reject(opt_error?: any): void; + errback(opt_error?: any): void; + + /** + * Resolves this promise with the given value. If the value is itself a + * promise and not a reference to this deferred, this instance will wait for + * it before resolving. + * @param {*=} opt_value The resolved value. + */ + fulfill(opt_value?: T): void; + + /** + * Removes all of the listeners previously registered on this deferred. + * @throws {Error} If this deferred has already been resolved. + */ + removeAll(): void; + + //endregion + } + + interface IControlFlowTimer { + clearInterval: (ms: number) => void; + clearTimeout: (ms: number) => void; + setInterval: (fn: Function, ms: number) => number; + setTimeout: (fn: Function, ms: number) => number; + } + + /** + * Handles the execution of scheduled tasks, each of which may be an + * asynchronous operation. The control flow will ensure tasks are executed in + * the ordered scheduled, starting each task only once those before it have + * completed. + * + * Each task scheduled within this flow may return a + * {@link webdriver.promise.Promise} to indicate it is an asynchronous + * operation. The ControlFlow will wait for such promises to be resolved before + * marking the task as completed. + * + * Tasks and each callback registered on a {@link webdriver.promise.Promise} + * will be run in their own ControlFlow frame. Any tasks scheduled within a + * frame will take priority over previously scheduled tasks. Furthermore, if any + * of the tasks in the frame fail, the remainder of the tasks in that frame will + * be discarded and the failure will be propagated to the user through the + * callback/task's promised result. + * + * Each time a ControlFlow empties its task queue, it will fire an + * {@link webdriver.promise.ControlFlow.EventType.IDLE IDLE} event. Conversely, + * whenever the flow terminates due to an unhandled error, it will remove all + * remaining tasks in its queue and fire an + * {@link webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION + * UNCAUGHT_EXCEPTION} event. If there are no listeners registered with the + * flow, the error will be rethrown to the global error handler. + * + * @extends {EventEmitter} + * @final + */ + class ControlFlow extends EventEmitter { + /** + * @constructor + */ + constructor(); + + /** + * Events that may be emitted by an {@link webdriver.promise.ControlFlow}. + * @enum {string} + */ + static EventType: { + /** Emitted when all tasks have been successfully executed. */ + IDLE: string; + + /** Emitted when a ControlFlow has been reset. */ + RESET: string; + + /** Emitted whenever a new task has been scheduled. */ + SCHEDULE_TASK: string; + + /** + * Emitted whenever a control flow aborts due to an unhandled promise + * rejection. This event will be emitted along with the offending rejection + * reason. Upon emitting this event, the control flow will empty its task + * queue and revert to its initial state. + */ + UNCAUGHT_EXCEPTION: string; + }; + + /** + * Returns a string representation of this control flow, which is its current + * {@link #getSchedule() schedule}, sans task stack traces. + * @return {string} The string representation of this contorl flow. + * @override + */ + toString(): string; + + /** + * Resets this instance, clearing its queue and removing all event listeners. + */ + reset(): void; + + /** + * Generates an annotated string describing the internal state of this control + * flow, including the currently executing as well as pending tasks. If + * {@code opt_includeStackTraces === true}, the string will include the + * stack trace from when each task was scheduled. + * @param {string=} opt_includeStackTraces Whether to include the stack traces + * from when each task was scheduled. Defaults to false. + * @return {string} String representation of this flow's internal state. + */ + getSchedule(opt_includeStackTraces?: boolean): string; + + /** + * Schedules a task for execution. If there is nothing currently in the + * queue, the task will be executed in the next turn of the event loop. If + * the task function is a generator, the task will be executed using + * {@link webdriver.promise.consume}. + * + * @param {function(): (T|promise.Promise)} fn The function to + * call to start the task. If the function returns a + * {@link webdriver.promise.Promise}, this instance will wait for it to be + * resolved before starting the next task. + * @param {string=} opt_description A description of the task. + * @return {!promise.Promise} A promise that will be resolved + * with the result of the action. + * @template T + */ + execute(fn: ()=>(T|Promise), opt_description?: string): Promise; + + /** + * Inserts a {@code setTimeout} into the command queue. This is equivalent to + * a thread sleep in a synchronous programming language. + * + * @param {number} ms The timeout delay, in milliseconds. + * @param {string=} opt_description A description to accompany the timeout. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the result of the action. + */ + timeout(ms: number, opt_description?: string): Promise; + + /** + * Schedules a task that shall wait for a condition to hold. Each condition + * function may return any value, but it will always be evaluated as a boolean. + * + * Condition functions may schedule sub-tasks with this instance, however, + * their execution time will be factored into whether a wait has timed out. + * + * In the event a condition returns a Promise, the polling loop will wait for + * it to be resolved before evaluating whether the condition has been satisfied. + * The resolution time for a promise is factored into whether a wait has timed + * out. + * + * If the condition function throws, or returns a rejected promise, the + * wait task will fail. + * + * If the condition is defined as a promise, the flow will wait for it to + * settle. If the timeout expires before the promise settles, the promise + * returned by this function will be rejected. + * + * If this function is invoked with `timeout === 0`, or the timeout is omitted, + * the flow will wait indefinitely for the condition to be satisfied. + * + * @param {(!promise.Promise|function())} condition The condition to poll, + * or a promise to wait on. + * @param {number=} opt_timeout How long to wait, in milliseconds, for the + * condition to hold before timing out. If omitted, the flow will wait + * indefinitely. + * @param {string=} opt_message An optional error message to include if the + * wait times out; defaults to the empty string. + * @return {!promise.Promise} A promise that will be fulfilled + * when the condition has been satisified. The promise shall be rejected if + * the wait times out waiting for the condition. + * @throws {TypeError} If condition is not a function or promise or if timeout + * is not a number >= 0. + * @template T + */ + wait(condition: Promise|Function, opt_timeout?: number, opt_message?: string): Promise; + } + } + + namespace stacktrace { + /** + * Class representing one stack frame. + */ + class Frame { + /** + * @param {(string|undefined)} context Context object, empty in case of global + * functions or if the browser doesn't provide this information. + * @param {(string|undefined)} name Function name, empty in case of anonymous + * functions. + * @param {(string|undefined)} alias Alias of the function if available. For + * example the function name will be 'c' and the alias will be 'b' if the + * function is defined as a.b = function c() {};. + * @param {(string|undefined)} path File path or URL including line number and + * optionally column number separated by colons. + * @constructor + */ + constructor(context?: string, name?: string, alias?: string, path?: string); + + /** + * @return {string} The function name or empty string if the function is + * anonymous and the object field which it's assigned to is unknown. + */ + getName(): string; + + + /** + * @return {string} The url or empty string if it is unknown. + */ + getUrl(): string; + + + /** + * @return {number} The line number if known or -1 if it is unknown. + */ + getLine(): number; + + + /** + * @return {number} The column number if known and -1 if it is unknown. + */ + getColumn(): number; + + + /** + * @return {boolean} Whether the stack frame contains an anonymous function. + */ + isAnonymous(): boolean; + + + /** + * Converts this frame to its string representation using V8's stack trace + * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + * @return {string} The string representation of this frame. + * @override + */ + toString(): string; + } + + /** + * Stores a snapshot of the stack trace at the time this instance was created. + * The stack trace will always be adjusted to exclude this function call. + */ + class Snapshot { + /** + * @param {number=} opt_slice The number of frames to remove from the top of + * the generated stack trace. + * @constructor + */ + constructor(opt_slice?: number); + + /** + * @return {!Array.} The parsed stack trace. + */ + getStacktrace(): Frame[]; + } + + /** + * Formats an error's stack trace. + * @param {!(Error|goog.testing.JsUnitException)} error The error to format. + * @return {!(Error|goog.testing.JsUnitException)} The formatted error. + */ + function format(error: any): any; + + /** + * Gets the native stack trace if available otherwise follows the call chain. + * The generated trace will exclude all frames up to and including the call to + * this function. + * @return {!Array.} The frames of the stack trace. + */ + function get(): Frame[]; + + /** + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const + */ + var BROWSER_SUPPORTED: boolean; + } + + namespace until { + /** + * Defines a condition to + */ + class Condition { + /** + * @param {string} message A descriptive error message. Should complete the + * sentence "Waiting [...]" + * @param {function(!webdriver.WebDriver): OUT} fn The condition function to + * evaluate on each iteration of the wait loop. + * @constructor + */ + constructor(message: string, fn: (webdriver: WebDriver) => any); + + /** @return {string} A description of this condition. */ + description(): string; + + /** @type {function(!webdriver.WebDriver): OUT} */ + fn(webdriver: WebDriver): any; + } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as: + *

      + *
    1. A numeric index into {@code window.frames} for the currently selected + * frame. + *
    2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + *
    3. A locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + *
    + * + *

    Upon successful resolution of this condition, the driver will be left + * focused on the new frame. + * + * @param {!(number|webdriver.WebElement| + * webdriver.Locator|webdriver.By.Hash| + * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * The frame identifier. + * @return {!until.Condition.} A new condition. + */ + function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!until.Condition.} The new condition. + */ + function alertIsPresent(): Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsDisabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsEnabled(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsNotSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be in the DOM, + * yet not visible to the user. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsNotVisible(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsSelected(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsVisible(element: WebElement): Condition; + + /** + * Creates a condition that will loop until an element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: Locator|By.Hash|Function): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextContains(element: WebElement, substr: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextIs(element: WebElement, text: string): Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextMatches(element: WebElement, regex: RegExp): Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: Locator|By.Hash|Function): Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!webdriver.WebElement} element The element that should become stale. + * @return {!until.Condition.} The new condition. + */ + function stalenessOf(element: WebElement): Condition; + + /** + * Creates a condition that will wait for the current page's title to contain + * the given substring. + * + * @param {string} substr The substring that should be present in the page + * title. + * @return {!until.Condition.} The new condition. + */ + function titleContains(substr: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given value. + * + * @param {string} title The expected page title. + * @return {!until.Condition.} The new condition. + */ + function titleIs(title: string): Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + */ + function titleMatches(regex: RegExp): Condition; + } + + interface ILocation { + x: number; + y: number; + } + + interface ISize { + width: number; + height: number; + } + + /** + * Enumeration of the buttons used in the advanced interactions API. + * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. + * @enum {number} + */ + interface IButton { + LEFT: number; + MIDDLE: number; + RIGHT: number; + } + + var Button: IButton; + + /** + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} + */ + interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; + + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; + + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; + + COMMAND: string; // Apple command key + META: string; // alias for Windows key + + /** + * Simulate pressing many keys at once in a "chord". Takes a sequence of + * {@link webdriver.Key}s or strings, appends each of the values to a string, + * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns + * the resultant string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + * @see http://code.google.com/p/webdriver/issues/detail?id=79 + */ + chord: (...var_args: string[]) => string; + } + + var Key: IKey; + + /** + * Class for defining sequences of complex user interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + *

    Example:

    
    +     *   new webdriver.ActionSequence(driver).
    +     *       keyDown(webdriver.Key.SHIFT).
    +     *       click(element1).
    +     *       click(element2).
    +     *       dragAndDrop(element3, element4).
    +     *       keyUp(webdriver.Key.SHIFT).
    +     *       perform();
    +     * 
    + * + */ + class ActionSequence { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + //endregion + + //region Methods + + /** + * Executes this action sequence. + * @return {!webdriver.promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): webdriver.promise.Promise; + + /** + * Moves the mouse. The location to move to may be specified in terms of the + * mouse's current location, an offset relative to the top-left corner of an + * element, or an element (in which case the middle of the element is used). + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in pixels. + * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. + * Defaults to (0, 0). + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: ILocation): ActionSequence; + + /** + * Presses a mouse button. The mouse button will not be released until + * {@link #mouseUp} is called, regardless of whether that call is made in this + * sequence or another. The behavior for out-of-order events (e.g. mouseDown, + * click) is undefined. + * + *

    If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

    sequence.mouseMove(element).mouseDown()
    + * + *

    Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: number): ActionSequence; + + /** + * Releases a mouse button. Behavior is undefined for calling this function + * without a previous call to {@link #mouseDown}. + * + *

    If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

    sequence.mouseMove(element).mouseUp()
    + * + *

    Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: number): ActionSequence; + + /** + * Convenience function for performing a "drag and drop" manuever. The target + * element may be moved to the location of another element, or by an offset (in + * pixels). + * @param {!webdriver.WebElement} element The element to drag. + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in pixels. + * @return {!webdriver.ActionSequence} A self reference. + */ + dragAndDrop(element: WebElement, location: WebElement): ActionSequence; + dragAndDrop(element: WebElement, location: ILocation): ActionSequence; + + /** + * Clicks a mouse button. + * + *

    If an element is provided, the mouse will first be moved to the center + * of that element. This is equivalent to: + *

    sequence.mouseMove(element).click()
    + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: number): ActionSequence; + + /** + * Double-clicks a mouse button. + * + *

    If an element is provided, the mouse will first be moved to the center of + * that element. This is equivalent to: + *

    sequence.mouseMove(element).doubleClick()
    + * + *

    Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 + * + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * the element to interact with or the button to click with. + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * button is specified. + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * first argument. + * @return {!webdriver.ActionSequence} A self reference. + */ + doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: number): ActionSequence; + + /** + * Performs a modifier key press. The modifier key is not released + * until {@link #keyUp} or {@link #sendKeys} is called. The key press will be + * targetted at the currently focused element. + * @param {!webdriver.Key} key The modifier key to push. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyDown(key: string): ActionSequence; + + /** + * Performs a modifier key release. The release is targetted at the currently + * focused element. + * @param {!webdriver.Key} key The modifier key to release. Must be one of + * {ALT, CONTROL, SHIFT, COMMAND, META}. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + keyUp(key: string): ActionSequence; + + /** + * Simulates typing multiple keys. Each modifier key encountered in the + * sequence will not be released until it is encountered again. All key events + * will be targetted at the currently focused element. + * @param {...(string|!webdriver.Key|!Array.<(string|!webdriver.Key)>)} var_args + * The keys to type. + * @return {!webdriver.ActionSequence} A self reference. + * @throws {Error} If the key is not a valid modifier key. + */ + sendKeys(...var_args: any[]): ActionSequence; + + //endregion + } + + + /** + * Class for defining sequences of user touch interactions. Each sequence + * will not be executed until {@link #perform} is called. + * + * Example: + * + * new webdriver.TouchSequence(driver). + * tapAndHold({x: 0, y: 0}). + * move({x: 3, y: 4}). + * release({x: 10, y: 10}). + * perform(); + */ + class TouchSequence { + /* + * @param {!webdriver.WebDriver} driver The driver instance to use. + * @constructor + */ + constructor(driver: WebDriver); + + + /** + * Executes this action sequence. + * @return {!webdriver.promise.Promise} A promise that will be resolved once + * this sequence has completed. + */ + perform(): webdriver.promise.Promise; + + + /** + * Taps an element. + * + * @param {!webdriver.WebElement} elem The element to tap. + * @return {!webdriver.TouchSequence} A self reference. + */ + tap(elem: WebElement): TouchSequence; + + + /** + * Double taps an element. + * + * @param {!webdriver.WebElement} elem The element to double tap. + * @return {!webdriver.TouchSequence} A self reference. + */ + doubleTap(elem: WebElement): TouchSequence; + + + /** + * Long press on an element. + * + * @param {!webdriver.WebElement} elem The element to long press. + * @return {!webdriver.TouchSequence} A self reference. + */ + longPress(elem: WebElement): TouchSequence; + + + /** + * Touch down at the given location. + * + * @param {{ x: number, y: number }} location The location to touch down at. + * @return {!webdriver.TouchSequence} A self reference. + */ + tapAndHold(location: ILocation): TouchSequence; + + + /** + * Move a held {@linkplain #tapAndHold touch} to the specified location. + * + * @param {{x: number, y: number}} location The location to move to. + * @return {!webdriver.TouchSequence} A self reference. + */ + move(location: ILocation): TouchSequence; + + + /** + * Release a held {@linkplain #tapAndHold touch} at the specified location. + * + * @param {{x: number, y: number}} location The location to release at. + * @return {!webdriver.TouchSequence} A self reference. + */ + release(location: ILocation): TouchSequence; + + + /** + * Scrolls the touch screen by the given offset. + * + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!webdriver.TouchSequence} A self reference. + */ + scroll(offset: IOffset): TouchSequence; + + + /** + * Scrolls the touch screen, starting on `elem` and moving by the specified + * offset. + * + * @param {!webdriver.WebElement} elem The element where scroll starts. + * @param {{x: number, y: number}} offset The offset to scroll to. + * @return {!webdriver.TouchSequence} A self reference. + */ + scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; + + + /** + * Flick, starting anywhere on the screen, at speed xspeed and yspeed. + * + * @param {{xspeed: number, yspeed: number}} speed The speed to flick in each + direction, in pixels per second. + * @return {!webdriver.TouchSequence} A self reference. + */ + flick(speed: ISpeed): TouchSequence; + + + /** + * Flick starting at elem and moving by x and y at specified speed. + * + * @param {!webdriver.WebElement} elem The element where flick starts. + * @param {{x: number, y: number}} offset The offset to flick to. + * @param {number} speed The speed to flick at in pixels per second. + * @return {!webdriver.TouchSequence} A self reference. + */ + flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; + } + + + interface IOffset { + x: number; + y: number; + } + + + interface ISpeed { + xspeed: number; + yspeed: number; + } + + + /** + * Represents a modal dialog such as {@code alert}, {@code confirm}, or + * {@code prompt}. Provides functions to retrieve the message displayed with + * the alert, accept or dismiss the alert, and set the response text (in the + * case of {@code prompt}). + */ + interface Alert { + + //region Methods + + /** + * Retrieves the message text displayed with this alert. For instance, if the + * alert were opened with alert("hello"), then this would return "hello". + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * text displayed with this alert. + */ + getText(): webdriver.promise.Promise; + + /** + * Accepts this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + accept(): webdriver.promise.Promise; + + /** + * Dismisses this alert. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + dismiss(): webdriver.promise.Promise; + + /** + * Sets the response text on this alert. This command will return an error if + * the underlying alert does not support response text (e.g. window.alert and + * window.confirm). + * @param {string} text The text to set. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * this command has completed. + */ + sendKeys(text: string): webdriver.promise.Promise; + + //endregion + + } + + /** + * AlertPromise is a promise that will be fulfilled with an Alert. This promise + * serves as a forward proxy on an Alert, allowing calls to be scheduled + * directly on this instance before the underlying Alert has been fulfilled. In + * other words, the following two statements are equivalent: + *

    
    +     *     driver.switchTo().alert().dismiss();
    +     *     driver.switchTo().alert().then(function(alert) {
    +     *       return alert.dismiss();
    +     *     });
    +     * 
    + * + * @param {!webdriver.WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!webdriver.promise.Thenable.} alert A thenable + * that will be fulfilled with the promised alert. + * @constructor + * @extends {webdriver.Alert} + * @implements {webdriver.promise.Thenable.} + * @final + */ + interface AlertPromise extends Alert, webdriver.promise.IThenable { + } + + /** + * An error returned to indicate that there is an unhandled modal dialog on the + * current page. + * @extends {bot.Error} + */ + interface UnhandledAlertError extends webdriver.error.Error { + //region Methods + + /** + * @return {string} The text displayed with the unhandled alert. + */ + getAlertText(): string; + + /** + * @return {!webdriver.Alert} The open alert. + * @deprecated Use {@link #getAlertText}. This method will be removed in + * 2.45.0. + */ + getAlert(): Alert; + + + //endregion + } + + /** + * Recognized browser names. + * @enum {string} + */ + interface IBrowser { + ANDROID: string; + CHROME: string; + FIREFOX: string; + INTERNET_EXPLORER: string; + IPAD: string; + IPHONE: string; + OPERA: string; + PHANTOM_JS: string; + SAFARI: string; + HTMLUNIT: string; + } + + var Browser: IBrowser; + + interface ProxyConfig { + proxyType: string; + proxyAutoconfigUrl?: string; + ftpProxy?: string; + httpProxy?: string; + sslProxy?: string; + noProxy?: string; + } + + class Builder { + + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Creates a new WebDriver client based on this builder's current + * configuration. + * + * @return {!webdriver.WebDriver} A new WebDriver instance. + * @throws {Error} If the current configuration is invalid. + */ + build(): WebDriver; + + /** + * Configures the target browser for clients created by this instance. + * Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * + *

    You may also define the target browser using the {@code SELENIUM_BROWSER} + * environment variable. If set, this environment variable should be of the + * form {@code browser[:[version][:platform]]}. + * + * @param {(string|webdriver.Browser)} name The name of the target browser; + * common defaults are available on the {@link webdriver.Browser} enum. + * @param {string=} opt_version A desired version; may be omitted if any + * version should be used. + * @param {string=} opt_platform The desired platform; may be omitted if any + * version may be used. + * @return {!Builder} A self reference. + */ + forBrowser(name: string, opt_version?: string, opt_platform?: string): Builder; + + /** + * Returns the base set of capabilities this instance is currently configured + * to use. + * @return {!webdriver.Capabilities} The current capabilities for this builder. + */ + getCapabilities(): Capabilities; + + /** + * @return {string} The URL of the WebDriver server this instance is configured + * to use. + */ + getServerUrl(): string; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} beahvior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!Builder} A self reference. + */ + setAlertBehavior(behavior: string): Builder; + + /** + * Sets Chrome-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!chrome.Options} options The ChromeDriver options to use. + * @return {!Builder} A self reference. + */ + setChromeOptions(options: chrome.Options): Builder; + + /** + * Sets the control flow that created drivers should execute actions in. If + * the flow is never set, or is set to {@code null}, it will use the active + * flow at the time {@link #build()} is called. + * @param {webdriver.promise.ControlFlow} flow The control flow to use, or + * {@code null} to + * @return {!Builder} A self reference. + */ + setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!Builder} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Builder; + + /** + * Sets Firefox-specific options for drivers created by this builder. Any + * logging or proxy settings defined on the given options will take precedence + * over those set through {@link #setLoggingPrefs} and {@link #setProxy}, + * respectively. + * + * @param {!firefox.Options} options The FirefoxDriver options to use. + * @return {!Builder} A self reference. + */ + setFirefoxOptions(options: firefox.Options): Builder; + + /** + * Sets the logging preferences for the created session. Preferences may be + * changed by repeated calls, or by calling {@link #withCapabilities}. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * desired logging preferences. + * @return {!Builder} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; + setLoggingPrefs(prefs: { [key: string]: string }): Builder; + + /** + * Sets the proxy configuration to use for WebDriver clients created by this + * builder. Any calls to {@link #withCapabilities} after this function will + * overwrite these settings. + * @param {!webdriver.ProxyConfig} config The configuration to use. + * @return {!Builder} A self reference. + */ + setProxy(config: ProxyConfig): Builder; + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!Builder} A self reference. + */ + setScrollBehavior(behavior: number): Builder; + + /** + * Sets the URL of a remote WebDriver server to use. Once a remote URL has been + * specified, the builder direct all new clients to that server. If this method + * is never called, the Builder will attempt to create all clients locally. + * + *

    As an alternative to this method, you may also set the + * {@code SELENIUM_REMOTE_URL} environment variable. + * + * @param {string} url The URL of a remote server to use. + * @return {!Builder} A self reference. + */ + usingServer(url: string): Builder; + + /** + * Sets the desired capabilities when requesting a new session. This will + * overwrite any previously set capabilities. + * @param {!(Object|webdriver.Capabilities)} capabilities The desired + * capabilities for a new session. + * @return {!Builder} A self reference. + */ + withCapabilities(capabilities: Capabilities): Builder; + withCapabilities(capabilities: any): Builder; + + //endregion + } + + /** + * Common webdriver capability keys. + * @enum {string} + */ + interface ICapability { + + /** + * Indicates whether a driver should accept all SSL certs by default. This + * capability only applies when requesting a new session. To query whether + * a driver can handle insecure SSL certs, see + * {@link webdriver.Capability.SECURE_SSL}. + */ + ACCEPT_SSL_CERTS: string; + + + /** + * The browser name. Common browser names are defined in the + * {@link webdriver.Browser} enum. + */ + BROWSER_NAME: string; + + /** + * Defines how elements should be scrolled into the viewport for interaction. + * This capability will be set to zero (0) if elements are aligned with the + * top of the viewport, or one (1) if aligned with the bottom. The default + * behavior is to align with the top of the viewport. + */ + ELEMENT_SCROLL_BEHAVIOR: string; + + /** + * Whether the driver is capable of handling modal alerts (e.g. alert, + * confirm, prompt). To define how a driver should handle alerts, + * use {@link webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR}. + */ + HANDLES_ALERTS: string; + + /** + * Key for the logging driver logging preferences. + */ + LOGGING_PREFS: string; + + /** + * Whether this session generates native events when simulating user input. + */ + NATIVE_EVENTS: string; + + /** + * Describes the platform the browser is running on. Will be one of + * ANDROID, IOS, LINUX, MAC, UNIX, or WINDOWS. When requesting a + * session, ANY may be used to indicate no platform preference (this is + * semantically equivalent to omitting the platform capability). + */ + PLATFORM: string; + + /** + * Describes the proxy configuration to use for a new WebDriver session. + */ + PROXY: string; + + /** Whether the driver supports changing the brower's orientation. */ + ROTATABLE: string; + + /** + * Whether a driver is only capable of handling secure SSL certs. To request + * that a driver accept insecure SSL certs by default, use + * {@link webdriver.Capability.ACCEPT_SSL_CERTS}. + */ + SECURE_SSL: string; + + /** Whether the driver supports manipulating the app cache. */ + SUPPORTS_APPLICATION_CACHE: string; + + /** Whether the driver supports locating elements with CSS selectors. */ + SUPPORTS_CSS_SELECTORS: string; + + /** Whether the browser supports JavaScript. */ + SUPPORTS_JAVASCRIPT: string; + + /** Whether the driver supports controlling the browser's location info. */ + SUPPORTS_LOCATION_CONTEXT: string; + + /** Whether the driver supports taking screenshots. */ + TAKES_SCREENSHOT: string; + + /** + * Defines how the driver should handle unexpected alerts. The value should + * be one of "accept", "dismiss", or "ignore. + */ + UNEXPECTED_ALERT_BEHAVIOR: string; + + /** Defines the browser version. */ + VERSION: string; + } + + var Capability: ICapability; + + class Capabilities { + //region Constructors + + /** + * @param {(webdriver.Capabilities|Object)=} opt_other Another set of + * capabilities to merge into this instance. + * @constructor + */ + constructor(opt_other?: Capabilities); + constructor(opt_other?: any); + + //endregion + + //region Methods + + /** @return {!Object} The JSON representation of this instance. */ + toJSON(): any; + + /** + * Merges another set of capabilities into this instance. Any duplicates in + * the provided set will override those already set on this instance. + * @param {!(webdriver.Capabilities|Object)} other The capabilities to + * merge into this instance. + * @return {!webdriver.Capabilities} A self reference. + */ + merge(other: Capabilities): Capabilities; + merge(other: any): Capabilities; + + /** + * @param {string} key The capability to set. + * @param {*} value The capability value. Capability values must be JSON + * serializable. Pass {@code null} to unset the capability. + * @return {!webdriver.Capabilities} A self reference. + */ + set(key: string, value: any): Capabilities; + + /** + * Sets the logging preferences. Preferences may be specified as a + * {@link webdriver.logging.Preferences} instance, or a as a map of log-type to + * log-level. + * @param {!(webdriver.logging.Preferences|Object.)} prefs The + * logging preferences. + * @return {!webdriver.Capabilities} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; + setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; + + + /** + * Sets the proxy configuration for this instance. + * @param {webdriver.ProxyConfig} proxy The desired proxy configuration. + * @return {!webdriver.Capabilities} A self reference. + */ + setProxy(proxy: ProxyConfig): Capabilities; + + + /** + * Sets whether native events should be used. + * @param {boolean} enabled Whether to enable native events. + * @return {!webdriver.Capabilities} A self reference. + */ + setEnableNativeEvents(enabled: boolean): Capabilities; + + + /** + * Sets how elements should be scrolled into view for interaction. + * @param {number} behavior The desired scroll behavior: either 0 to align with + * the top of the viewport or 1 to align with the bottom. + * @return {!webdriver.Capabilities} A self reference. + */ + setScrollBehavior(behavior: number): Capabilities; + + /** + * Sets the default action to take with an unexpected alert before returning + * an error. + * @param {string} behavior The desired behavior; should be "accept", "dismiss", + * or "ignore". Defaults to "dismiss". + * @return {!webdriver.Capabilities} A self reference. + */ + setAlertBehavior(behavior: string): Capabilities; + + /** + * @param {string} key The capability to return. + * @return {*} The capability with the given key, or {@code null} if it has + * not been set. + */ + get(key: string): any; + + /** + * @param {string} key The capability to check. + * @return {boolean} Whether the specified capability is set. + */ + has(key: string): boolean; + + //endregion + + //region Static Methods + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Android. + */ + static android(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Chrome. + */ + static chrome(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. + */ + static firefox(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * Internet Explorer. + */ + static ie(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPad. + */ + static ipad(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for iPhone. + */ + static iphone(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Opera. + */ + static opera(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for + * PhantomJS. + */ + static phantomjs(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for Safari. + */ + static safari(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit. + */ + static htmlunit(): Capabilities; + + /** + * @return {!webdriver.Capabilities} A basic set of capabilities for HTMLUnit + * with enabled Javascript. + */ + static htmlunitwithjs(): Capabilities; + + //endregion + } + + /** + * An enumeration of valid command string. + */ + interface ICommandName { + GET_SERVER_STATUS: string; + + NEW_SESSION: string; + GET_SESSIONS: string; + DESCRIBE_SESSION: string; + + CLOSE: string; + QUIT: string; + + GET_CURRENT_URL: string; + GET: string; + GO_BACK: string; + GO_FORWARD: string; + REFRESH: string; + + ADD_COOKIE: string; + GET_COOKIE: string; + GET_ALL_COOKIES: string; + DELETE_COOKIE: string; + DELETE_ALL_COOKIES: string; + + GET_ACTIVE_ELEMENT: string; + FIND_ELEMENT: string; + FIND_ELEMENTS: string; + FIND_CHILD_ELEMENT: string; + FIND_CHILD_ELEMENTS: string; + + CLEAR_ELEMENT: string; + CLICK_ELEMENT: string; + SEND_KEYS_TO_ELEMENT: string; + SUBMIT_ELEMENT: string; + + GET_CURRENT_WINDOW_HANDLE: string; + GET_WINDOW_HANDLES: string; + GET_WINDOW_POSITION: string; + SET_WINDOW_POSITION: string; + GET_WINDOW_SIZE: string; + SET_WINDOW_SIZE: string; + MAXIMIZE_WINDOW: string; + + SWITCH_TO_WINDOW: string; + SWITCH_TO_FRAME: string; + GET_PAGE_SOURCE: string; + GET_TITLE: string; + + EXECUTE_SCRIPT: string; + EXECUTE_ASYNC_SCRIPT: string; + + GET_ELEMENT_TEXT: string; + GET_ELEMENT_TAG_NAME: string; + IS_ELEMENT_SELECTED: string; + IS_ELEMENT_ENABLED: string; + IS_ELEMENT_DISPLAYED: string; + GET_ELEMENT_LOCATION: string; + GET_ELEMENT_LOCATION_IN_VIEW: string; + GET_ELEMENT_SIZE: string; + GET_ELEMENT_ATTRIBUTE: string; + GET_ELEMENT_VALUE_OF_CSS_PROPERTY: string; + ELEMENT_EQUALS: string; + + SCREENSHOT: string; + IMPLICITLY_WAIT: string; + SET_SCRIPT_TIMEOUT: string; + SET_TIMEOUT: string; + + ACCEPT_ALERT: string; + DISMISS_ALERT: string; + GET_ALERT_TEXT: string; + SET_ALERT_TEXT: string; + + EXECUTE_SQL: string; + GET_LOCATION: string; + SET_LOCATION: string; + GET_APP_CACHE: string; + GET_APP_CACHE_STATUS: string; + CLEAR_APP_CACHE: string; + IS_BROWSER_ONLINE: string; + SET_BROWSER_ONLINE: string; + + GET_LOCAL_STORAGE_ITEM: string; + GET_LOCAL_STORAGE_KEYS: string; + SET_LOCAL_STORAGE_ITEM: string; + REMOVE_LOCAL_STORAGE_ITEM: string; + CLEAR_LOCAL_STORAGE: string; + GET_LOCAL_STORAGE_SIZE: string; + + GET_SESSION_STORAGE_ITEM: string; + GET_SESSION_STORAGE_KEYS: string; + SET_SESSION_STORAGE_ITEM: string; + REMOVE_SESSION_STORAGE_ITEM: string; + CLEAR_SESSION_STORAGE: string; + GET_SESSION_STORAGE_SIZE: string; + + SET_SCREEN_ORIENTATION: string; + GET_SCREEN_ORIENTATION: string; + + // These belong to the Advanced user interactions - an element is + // optional for these commands. + CLICK: string; + DOUBLE_CLICK: string; + MOUSE_DOWN: string; + MOUSE_UP: string; + MOVE_TO: string; + SEND_KEYS_TO_ACTIVE_ELEMENT: string; + + // These belong to the Advanced Touch API + TOUCH_SINGLE_TAP: string; + TOUCH_DOWN: string; + TOUCH_UP: string; + TOUCH_MOVE: string; + TOUCH_SCROLL: string; + TOUCH_DOUBLE_TAP: string; + TOUCH_LONG_PRESS: string; + TOUCH_FLICK: string; + + GET_AVAILABLE_LOG_TYPES: string; + GET_LOG: string; + GET_SESSION_LOGS: string; + } + + var CommandName: ICommandName; + + /** + * Describes a command to be executed by the WebDriverJS framework. + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + class Command { + //region Constructors + + /** + * @param {!webdriver.CommandName} name The name of this command. + * @constructor + */ + constructor(name: string); + + //endregion + + //region Methods + + /** + * @return {!webdriver.CommandName} This command's name. + */ + getName(): string; + + /** + * Sets a parameter to send with this command. + * @param {string} name The parameter name. + * @param {*} value The parameter value. + * @return {!webdriver.Command} A self reference. + */ + setParameter(name: string, value: any): Command; + + /** + * Sets the parameters for this command. + * @param {!Object.<*>} parameters The command parameters. + * @return {!webdriver.Command} A self reference. + */ + setParameters(parameters: any): Command; + + /** + * Returns a named command parameter. + * @param {string} key The parameter key to look up. + * @return {*} The parameter value, or undefined if it has not been set. + */ + getParameter(key: string): any; + + /** + * @return {!Object.<*>} The parameters to send with this command. + */ + getParameters(): any; + + //endregion + } + + /** + * Handles the execution of {@code webdriver.Command} objects. + */ + interface CommandExecutor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * {@link bot.response.ResponseObject} object. + * @param {!webdriver.Command} command The command to execute. + * @param {function(Error, !bot.response.ResponseObject=)} callback the function + * to invoke when the command response is ready. + */ + execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + } + + /** + * Object that can emit events for others to listen for. This is used instead + * of Closure's event system because it is much more light weight. The API is + * based on Node's EventEmitters. + */ + class EventEmitter { + //region Constructors + + /** + * @constructor + */ + constructor(); + + //endregion + + //region Methods + + /** + * Fires an event and calls all listeners. + * @param {string} type The type of event to emit. + * @param {...*} var_args Any arguments to pass to each listener. + */ + emit(type: string, ...var_args: any[]): void; + + /** + * Returns a mutable list of listeners for a specific type of event. + * @param {string} type The type of event to retrieve the listeners for. + * @return {!Array.<{fn: !Function, oneshot: boolean, + * scope: (Object|undefined)}>} The registered listeners for + * the given event type. + */ + listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + + /** + * Registers a listener. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + + /** + * Registers a one-time listener which will be called only the first time an + * event is emitted, after which it will be removed. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; + + /** + * An alias for {@code #addListener()}. + * @param {string} type The type of event to listen for. + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. + */ + on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + + /** + * Removes a previously registered event listener. + * @param {string} type The type of event to unregister. + * @param {!Function} listenerFn The handler function to remove. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeListener(type: string, listenerFn: Function): EventEmitter; + + /** + * Removes all listeners for a specific type of event. If no event is + * specified, all listeners across all types will be removed. + * @param {string=} opt_type The type of event to remove listeners from. + * @return {!webdriver.EventEmitter} A self reference. + */ + removeAllListeners(opt_type?: string): EventEmitter; + + //endregion + } + + + /** + * Interface for navigating back and forth in the browser history. + */ + interface WebDriverNavigation { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverNavigation; + + //endregion + + //region Methods + + /** + * Schedules a command to navigate to a new URL. + * @param {string} url The URL to navigate to. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the URL has been loaded. + */ + to(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to move backwards in the browser history. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + back(): webdriver.promise.Promise; + + /** + * Schedules a command to move forwards in the browser history. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + forward(): webdriver.promise.Promise; + + /** + * Schedules a command to refresh the current page. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the navigation event has completed. + */ + refresh(): webdriver.promise.Promise; + + //endregion + } + + interface IWebDriverOptionsCookie { + name: string; + value: string; + path?: string; + domain?: string; + secure?: boolean; + expiry?: number; + } + + /** + * Provides methods for managing browser and driver state. + */ + interface WebDriverOptions { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: webdriver.WebDriver): WebDriverOptions; + + //endregion + + //region Methods + + /** + * Schedules a command to add a cookie. + * @param {string} name The cookie name. + * @param {string} value The cookie value. + * @param {string=} opt_path The cookie path. + * @param {string=} opt_domain The cookie domain. + * @param {boolean=} opt_isSecure Whether the cookie is secure. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as + * a number, should be in milliseconds since midnight, January 1, 1970 UTC. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been added to the page. + */ + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + + /** + * Schedules a command to delete all cookies visible to the current page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * cookies have been deleted. + */ + deleteAllCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to delete the cookie with the given name. This command is + * a no-op if there is no cookie with the given name visible to the current + * page. + * @param {string} name The name of the cookie to delete. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been deleted. + */ + deleteCookie(name: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve all cookies visible to the current page. + * Each cookie will be returned as a JSON object as described by the WebDriver + * wire protocol. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * cookies visible to the current page. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookies(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the cookie with the given name. Returns null + * if there is no such cookie. The cookie will be returned as a JSON object as + * described by the WebDriver wire protocol. + * @param {string} name The name of the cookie to retrieve. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * named cookie, or {@code null} if there is no such cookie. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol#Cookie_JSON_Object + */ + getCookie(name: string): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Logs} The interface for managing driver + * logs. + */ + logs(): WebDriverLogs; + + /** + * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver + * timeouts. + */ + timeouts(): WebDriverTimeouts; + + /** + * @return {!webdriver.WebDriver.Window} The interface for managing the + * current window. + */ + window(): WebDriverWindow; + + //endregion + } + + /** + * An interface for managing timeout behavior for WebDriver instances. + */ + interface WebDriverTimeouts { + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverTimeouts; + + //endregion + + //region Methods + + /** + * Specifies the amount of time the driver should wait when searching for an + * element if it is not immediately present. + *

    + * When searching for a single element, the driver should poll the page + * until the element has been found, or this timeout expires before failing + * with a {@code bot.ErrorCode.NO_SUCH_ELEMENT} error. When searching + * for multiple elements, the driver should poll the page until at least one + * element has been found or this timeout has expired. + *

    + * Setting the wait timeout to 0 (its default value), disables implicit + * waiting. + *

    + * Increasing the implicit wait timeout should be used judiciously as it + * will have an adverse effect on test run time, especially when used with + * slower location strategies like XPath. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * implicit wait timeout has been set. + */ + implicitlyWait(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait, in milliseconds, for an asynchronous script + * to finish execution before returning an error. If the timeout is less than or + * equal to 0, the script will be allowed to run indefinitely. + * + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * script timeout has been set. + */ + setScriptTimeout(ms: number): webdriver.promise.Promise; + + /** + * Sets the amount of time to wait for a page load to complete before returning + * an error. If the timeout is negative, page loads may be indefinite. + * @param {number} ms The amount of time to wait, in milliseconds. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the timeout has been set. + */ + pageLoadTimeout(ms: number): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for managing the current window. + */ + interface WebDriverWindow { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverWindow; + + //endregion + + //region Methods + + /** + * Retrieves the window's current position, relative to the top left corner of + * the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's position in the form of a {x:number, y:number} object literal. + */ + getPosition(): webdriver.promise.Promise; + + /** + * Repositions the current window. + * @param {number} x The desired horizontal position, relative to the left side + * of the screen. + * @param {number} y The desired vertical position, relative to the top of the + * of the screen. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setPosition(x: number, y: number): webdriver.promise.Promise; + + /** + * Retrieves the window's current size. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * window's size in the form of a {width:number, height:number} object + * literal. + */ + getSize(): webdriver.promise.Promise; + + /** + * Resizes the current window. + * @param {number} width The desired window width. + * @param {number} height The desired window height. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + setSize(width: number, height: number): webdriver.promise.Promise; + + /** + * Maximizes the current window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * command has completed. + */ + maximize(): webdriver.promise.Promise; + + //endregion + } + + /** + * Interface for managing WebDriver log records. + */ + interface WebDriverLogs { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverLogs; + + //endregion + + //region + + /** + * Fetches available log entries for the given type. + * + *

    Note that log buffers are reset after each call, meaning that + * available log entries correspond to those entries not yet returned for a + * given log type. In practice, this means that this call will return the + * available log entries since the last call, or from the start of the + * session. + * + * @param {!webdriver.logging.Type} type The desired log type. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of log entries for the specified + * type. + */ + get(type: string): webdriver.promise.Promise; + + /** + * Retrieves the log types available to this driver. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to a list of available log types. + */ + getAvailableLogTypes(): webdriver.promise.Promise; + + //endregion + } + + /** + * An interface for changing the focus of the driver to another frame or window. + */ + interface WebDriverTargetLocator { + + //region Constructors + + /** + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor + */ + new (driver: WebDriver): WebDriverTargetLocator; + + //endregion + + //region Methods + + /** + * Schedules a command retrieve the {@code document.activeElement} element on + * the current document, or {@code document.body} if activeElement is not + * available. + * @return {!webdriver.WebElement} The active element. + */ + activeElement(): WebElementPromise; + + /** + * Schedules a command to switch focus of all future commands to the first frame + * on the page. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the default content. + */ + defaultContent(): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * frame on the page. + *

    + * If the frame is specified by a number, the command will switch to the frame + * by its (zero-based) index into the {@code window.frames} collection. + *

    + * If the frame is specified by a string, the command will select the frame by + * its name or ID. To select sub-frames, simply separate the frame names/IDs by + * dots. As an example, "main.child" will select the frame with the name "main" + * and then its child "child". + *

    + * If the specified frame can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. + * @param {string|number} nameOrIndex The frame locator. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified frame. + */ + frame(nameOrIndex: string): webdriver.promise.Promise; + frame(nameOrIndex: number): webdriver.promise.Promise; + + /** + * Schedules a command to switch the focus of all future commands to another + * window. Windows may be specified by their {@code window.name} attribute or + * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). + *

    + * If the specificed window can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * @param {string} nameOrHandle The name or window handle of the window to + * switch focus to. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified window. + */ + window(nameOrHandle: string): webdriver.promise.Promise; + + /** + * Schedules a command to change focus to the active alert dialog. This command + * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal + * dialog is not currently open. + * @return {!webdriver.Alert} The open alert. + */ + alert(): AlertPromise; + + //endregion + } + + /** + * Used with {@link webdriver.WebElement#sendKeys WebElement#sendKeys} on file + * input elements ({@code }) to detect when the entered key + * sequence defines the path to a file. + * + * By default, {@linkplain webdriver.WebElement WebElement's} will enter all + * key sequences exactly as entered. You may set a + * {@linkplain webdriver.WebDriver#setFileDetector file detector} on the parent + * WebDriver instance to define custom behavior for handling file elements. Of + * particular note is the {@link selenium-webdriver/remote.FileDetector}, which + * should be used when running against a remote + * [Selenium Server](http://docs.seleniumhq.org/download/). + */ + class FileDetector { + /** @constructor */ + constructor(); + + /** + * Handles the file specified by the given path, preparing it for use with + * the current browser. If the path does not refer to a valid file, it will + * be returned unchanged, otherwisee a path suitable for use with the current + * browser will be returned. + * + * This default implementation is a no-op. Subtypes may override this + * function for custom tailored file handling. + * + * @param {!webdriver.WebDriver} driver The driver for the current browser. + * @param {string} path The path to process. + * @return {!webdriver.promise.Promise} A promise for the processed + * file path. + * @package + */ + handleFile(driver: webdriver.WebDriver, path: string): webdriver.promise.Promise; + } + + /** + * Creates a new WebDriver client, which provides control over a browser. + * + * Every WebDriver command returns a {@code webdriver.promise.Promise} that + * represents the result of that command. Callbacks may be registered on this + * object to manipulate the command result or catch an expected error. Any + * commands scheduled with a callback are considered sub-commands and will + * execute before the next command in the current frame. For example: + * + * var message = []; + * driver.call(message.push, message, 'a').then(function() { + * driver.call(message.push, message, 'b'); + * }); + * driver.call(message.push, message, 'c'); + * driver.call(function() { + * alert('message is abc? ' + (message.join('') == 'abc')); + * }); + * + */ + class WebDriver { + //region Constructors + + /** + * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * known session or a promise that will be resolved to a session. + * @param {!webdriver.CommandExecutor} executor The executor to use when + * sending commands to the browser. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region Static Properties + + static Navigation: WebDriverNavigation; + static Options: WebDriverOptions; + static Timeouts: WebDriverTimeouts; + static Window: WebDriverWindow; + static Logs: WebDriverLogs; + static TargetLocator: WebDriverTargetLocator; + + //endregion + + //region StaticMethods + + /** + * Creates a new WebDriver client for an existing session. + * @param {!webdriver.CommandExecutor} executor Command executor to use when + * querying for session details. + * @param {string} sessionId ID of the session to attach to. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under. Defaults to the + * {@link webdriver.promise.controlFlow() currently active} control flow. + * @return {!webdriver.WebDriver} A new client for the specified session. + */ + static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + /** + * Creates a new WebDriver session. + * @param {!webdriver.CommandExecutor} executor The executor to create the new + * session with. + * @param {!webdriver.Capabilities} desiredCapabilities The desired + * capabilities for the new session. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under, including the initial session creation. + * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * control flow. + * @return {!webdriver.WebDriver} The driver for the newly created session. + */ + static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + + //endregion + + //region Methods + + /** + * @return {!webdriver.promise.ControlFlow} The control flow used by this + * instance. + */ + controlFlow(): webdriver.promise.ControlFlow; + + /** + * Schedules a {@code webdriver.Command} to be executed by this driver's + * {@code webdriver.CommandExecutor}. + * @param {!webdriver.Command} command The command to schedule. + * @param {string} description A description of the command for debugging. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the command result. + */ + schedule(command: Command, description: string): webdriver.promise.Promise; + + + /** + * Sets the {@linkplain webdriver.FileDetector file detector} that should be + * used with this instance. + * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + */ + setFileDetector(detector: FileDetector): void; + + + /** + * @return {!webdriver.promise.Promise.} A promise for this + * client's session. + */ + getSession(): webdriver.promise.Promise; + + + /** + * @return {!webdriver.promise.Promise.} A promise + * that will resolve with the this instance's capabilities. + */ + getCapabilities(): webdriver.promise.Promise; + + + /** + * Schedules a command to quit the current session. After calling quit, this + * instance will be invalidated and may no longer be used to issue commands + * against the browser. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the command has completed. + */ + quit(): webdriver.promise.Promise; + + /** + * Creates a new action sequence using this driver. The sequence will not be + * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * called. Example: + *

    
    +         *   driver.actions().
    +         *       mouseDown(element1).
    +         *       mouseMove(element2).
    +         *       mouseUp().
    +         *       perform();
    +         * 
    + * @return {!webdriver.ActionSequence} A new action sequence for this instance. + */ + actions(): ActionSequence; + + + /** + * Creates a new touch sequence using this driver. The sequence will not be + * scheduled for execution until {@link webdriver.TouchSequence#perform} is + * called. Example: + * + * driver.touchActions(). + * tap(element1). + * doubleTap(element2). + * perform(); + * + * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + */ + touchActions(): TouchSequence; + + + /** + * Schedules a command to execute JavaScript in the context of the currently + * selected frame or window. The script fragment will be executed as the body + * of an anonymous function. If the script is provided as a function object, + * that function will be converted to a string for injection into the target + * window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * The script may refer to any variables accessible from the current window. + * Furthermore, the script will execute in the window's context, thus + * {@code document} may be used to refer to the current document. Any local + * variables will not be available once the script has finished executing, + * though global variables will persist. + * + * If the script has a return value (i.e. if the script contains a return + * statement), then the following steps will be taken for resolving this + * functions return value: + * + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute asynchronous JavaScript in the context of the + * currently selected frame or window. The script fragment will be executed as + * the body of an anonymous function. If the script is provided as a function + * object, that function will be converted to a string for injection into the + * target window. + * + * Any arguments provided in addition to the script will be included as script + * arguments and may be referenced using the {@code arguments} object. + * Arguments may be a boolean, number, string, or {@code webdriver.WebElement}. + * Arrays and objects may also be used as script arguments as long as each item + * adheres to the types previously mentioned. + * + * Unlike executing synchronous JavaScript with {@link #executeScript}, + * scripts executed with this function must explicitly signal they are finished + * by invoking the provided callback. This callback will always be injected + * into the executed function as the last argument, and thus may be referenced + * with {@code arguments[arguments.length - 1]}. The following steps will be + * taken for resolving this functions return value against the first argument + * to the script's callback function: + * + * - For a HTML element, the value will resolve to a + * {@link webdriver.WebElement} + * - Null and undefined return values will resolve to null + * - Booleans, numbers, and strings will resolve as is + * - Functions will resolve to their string representation + * - For arrays and objects, each member item will be converted according to + * the rules above + * + * __Example #1:__ Performing a sleep that is synchronized with the currently + * selected window: + * + * var start = new Date().getTime(); + * driver.executeAsyncScript( + * 'window.setTimeout(arguments[arguments.length - 1], 500);'). + * then(function() { + * console.log( + * 'Elapsed time: ' + (new Date().getTime() - start) + ' ms'); + * }); + * + * __Example #2:__ Synchronizing a test with an AJAX application: + * + * var button = driver.findElement(By.id('compose-button')); + * button.click(); + * driver.executeAsyncScript( + * 'var callback = arguments[arguments.length - 1];' + + * 'mailClient.getComposeWindowWidget().onload(callback);'); + * driver.switchTo().frame('composeWidget'); + * driver.findElement(By.id('to')).sendKeys('dog@example.com'); + * + * __Example #3:__ Injecting a XMLHttpRequest and waiting for the result. In + * this example, the inject script is specified with a function literal. When + * using this format, the function is converted to a string for injection, so it + * should not reference any symbols not defined in the scope of the page under + * test. + * + * driver.executeAsyncScript(function() { + * var callback = arguments[arguments.length - 1]; + * var xhr = new XMLHttpRequest(); + * xhr.open("GET", "/resource/data.json", true); + * xhr.onreadystatechange = function() { + * if (xhr.readyState == 4) { + * callback(xhr.responseText); + * } + * } + * xhr.send(''); + * }).then(function(str) { + * console.log(JSON.parse(str)['food']); + * }); + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * scripts return value. + * @template T + */ + executeAsyncScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to execute a custom function. + * @param {function(...): (T|webdriver.promise.Promise.)} fn The function to + * execute. + * @param {Object=} opt_scope The object in whose scope to execute the function. + * @param {...*} var_args Any arguments to pass to the function. + * @return {!webdriver.promise.Promise.} A promise that will be resolved' + * with the function's result. + * @template T + */ + call(fn: (...var_args: any[])=>(T|webdriver.promise.Promise), opt_scope?: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Schedules a command to wait for a condition to hold. The condition may be + * specified by a {@link webdriver.until.Condition}, as a custom function, or + * as a {@link webdriver.promise.Promise}. + * + * For a {@link webdriver.until.Condition} or function, the wait will repeatedly + * evaluate the condition until it returns a truthy value. If any errors occur + * while evaluating the condition, they will be allowed to propagate. In the + * event a condition returns a {@link webdriver.promise.Promise promise}, the + * polling loop will wait for it to be resolved and use the resolved value for + * whether the condition has been satisified. Note the resolution time for + * a promise is factored into whether a wait has timed out. + * + * *Example:* waiting up to 10 seconds for an element to be present and visible + * on the page. + * + * var button = driver.wait(until.elementLocated(By.id('foo'), 10000); + * button.click(); + * + * This function may also be used to block the command flow on the resolution + * of a {@link webdriver.promise.Promise promise}. When given a promise, the + * command will simply wait for its resolution before completing. A timeout may + * be provided to fail the command if the promise does not resolve before the + * timeout expires. + * + * *Example:* Suppose you have a function, `startTestServer`, that returns a + * promise for when a server is ready for requests. You can block a `WebDriver` + * client on this promise with: + * + * var started = startTestServer(); + * driver.wait(started, 5 * 1000, 'Server should start within 5 seconds'); + * driver.get(getServerUrl()); + * + * @param {!(webdriver.promise.Promise| + * webdriver.until.Condition| + * function(!webdriver.WebDriver): T)} condition The condition to + * wait on, defined as a promise, condition object, or a function to + * evaluate as a condition. + * @param {number=} opt_timeout How long to wait for the condition to be true. + * @param {string=} opt_message An optional message to use if the wait times + * out. + * @return {!webdriver.promise.Promise} A promise that will be fulfilled + * with the first truthy value returned by the condition function, or + * rejected if the condition times out. + * @template T + */ + wait(condition: webdriver.promise.Promise|webdriver.until.Condition|((driver: WebDriver)=>T), timeout?: number, opt_message?: string): webdriver.promise.Promise; + + /** + * Schedules a command to make the driver sleep for the given amount of time. + * @param {number} ms The amount of time, in milliseconds, to sleep. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the sleep has finished. + */ + sleep(ms: number): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve they current window handle. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current window handle. + */ + getWindowHandle(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current list of available window handles. + * @return {!webdriver.promise.Promise.>} A promise that will + * be resolved with an array of window handles. + */ + getAllWindowHandles(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's source. The page source + * returned is a representation of the underlying DOM: do not expect it to be + * formatted or escaped in the same way as the response sent from the web + * server. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page source. + */ + getPageSource(): webdriver.promise.Promise; + + /** + * Schedules a command to close the current window. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when this command has completed. + */ + close(): webdriver.promise.Promise; + + /** + * Schedules a command to navigate to the given URL. + * @param {string} url The fully qualified URL to open. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the document has finished loading. + */ + get(url: string): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the URL of the current page. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current URL. + */ + getCurrentUrl(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the current page's title. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the current page's title. + */ + getTitle(): webdriver.promise.Promise; + + /** + * Schedule a command to find an element on the page. If the element cannot be + * found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will be returned + * by the driver. Unlike other commands, this error cannot be suppressed. In + * other words, scheduling a command to find an element doubles as an assert + * that the element is present on the page. To test whether an element is + * present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = driver.findElement(By.id('foo')); + * var e2 = driver.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + * + * var link = driver.findElement(firstVisibleLink); + * + * function firstVisibleLink(driver) { + * var links = driver.findElements(By.tagName('a')); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The + * locator to use. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; + + /** + * Schedules a command to test if an element is present on the page. + * + * If given a DOM element, this function will check if it belongs to the + * document the driver is currently focused on. Otherwise, the function will + * test if at least one element can be found with the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Element| + * Function)} locatorOrElement The locator to use, or the actual + * DOM element to be located by the server. + * @return {!webdriver.promise.Promise.} A promise that will resolve + * with whether the element is present on the page. + */ + isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; + + /** + * Schedule a command to search for multiple elements on the page. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + + /** + * Schedule a command to take a screenshot. The driver makes a best effort to + * return a screenshot of the following, in order of preference: + *
      + *
    1. Entire page + *
    2. Current window + *
    3. Visible portion of the current frame + *
    4. The screenshot of the entire display containing the browser + *
    + * + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(): webdriver.promise.Promise; + + /** + * @return {!webdriver.WebDriver.Options} The options interface for this + * instance. + */ + manage(): WebDriverOptions; + + /** + * @return {!webdriver.WebDriver.Navigation} The navigation interface for this + * instance. + */ + navigate(): WebDriverNavigation; + + /** + * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for + * this instance. + */ + switchTo(): WebDriverTargetLocator; + + //endregion + } + + interface IWebElementId { + ELEMENT: string; + } + + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; + } + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@code webdriver.WebDriver} instance, or by searching + * under another {@code webdriver.WebElement}: + *
    
    +     *   driver.get('http://www.google.com');
    +     *   var searchForm = driver.findElement(By.tagName('form'));
    +     *   var searchBox = searchForm.findElement(By.name('q'));
    +     *   searchBox.sendKeys('webdriver');
    +     * 
    + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + *
    
    +     *   driver.findElement(By.id('not-there')).then(function(element) {
    +     *     alert('Found an element that was not expected to be there!');
    +     *   }, function(error) {
    +     *     alert('The element was not found, as expected');
    +     *   });
    +     * 
    + */ + interface IWebElement { + //region Methods + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

    + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

      + *
    • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
    • + *
    • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
    • + *
    • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
    • + *
    + * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

    + * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

    async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

    Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

      + *
    • "class" + *
    • "readonly" + *
    + * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + //endregion + } + + interface IWebElementFinders { + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@code bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@code #isElementPresent} instead. + * + *

    The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + *

    +         * var e1 = element.findElement(By.id('foo'));
    +         * var e2 = element.findElement({id:'foo'});
    +         * 
    + * + *

    You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + *

    +         * var link = element.findElement(firstVisibleLink);
    +         *
    +         * function firstVisibleLink(element) {
    +         *   var links = element.findElements(By.tagName('a'));
    +         *   return webdriver.promise.filter(links, function(link) {
    +         *     return links.isDisplayed();
    +         *   }).then(function(visibleLinks) {
    +         *     return visibleLinks[0];
    +         *   });
    +         * }
    +         * 
    + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: Locator|By.Hash|Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + } + + + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; + } + + + /** + * Represents a DOM element. WebElements can be found by searching from the + * document root using a {@link webdriver.WebDriver} instance, or by searching + * under another WebElement: + * + * driver.get('http://www.google.com'); + * var searchForm = driver.findElement(By.tagName('form')); + * var searchBox = searchForm.findElement(By.name('q')); + * searchBox.sendKeys('webdriver'); + * + * The WebElement is implemented as a promise for compatibility with the promise + * API. It will always resolve itself when its internal state has been fully + * resolved and commands may be issued against the element. This can be used to + * catch errors when an element cannot be located on the page: + * + * driver.findElement(By.id('not-there')).then(function(element) { + * alert('Found an element that was not expected to be there!'); + * }, function(error) { + * alert('The element was not found, as expected'); + * }); + * + * @extends {webdriver.Serializable.} + */ + class WebElement implements Serializable { + /** + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!(webdriver.promise.Promise.| + * webdriver.WebElement.Id)} id The server-assigned opaque ID for the + * underlying DOM element. + * @constructor + */ + constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); + + /** + * Wire protocol definition of a WebElement ID. + * @typedef {{ELEMENT: string}} + * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + */ + static Id: IWebElementId; + + /** + * The property key used in the wire protocol to indicate that a JSON object + * contains the ID of a WebElement. + * @type {string} + * @const + */ + static ELEMENT_KEY: string; + + + /** + * @return {!webdriver.WebDriver} The parent driver for this instance. + */ + getDriver(): WebDriver; + + /** + * Schedule a command to find a descendant of this element. If the element + * cannot be found, a {@link bot.ErrorCode.NO_SUCH_ELEMENT} result will + * be returned by the driver. Unlike other commands, this error cannot be + * suppressed. In other words, scheduling a command to find an element doubles + * as an assert that the element is present on the page. To test whether an + * element is present on the page, use {@link #isElementPresent} instead. + * + * The search criteria for an element may be defined using one of the + * factories in the {@link webdriver.By} namespace, or as a short-hand + * {@link webdriver.By.Hash} object. For example, the following two statements + * are equivalent: + * + * var e1 = element.findElement(By.id('foo')); + * var e2 = element.findElement({id:'foo'}); + * + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: + * + * var link = element.findElement(firstVisibleLink); + * + * function firstVisibleLink(element) { + * var links = element.findElements(By.tagName('a')); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; + * }); + * } + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue + * commands against the located element. If the element is not found, the + * element will be invalidated and all scheduled commands aborted. + */ + findElement(locator: Locator|By.Hash|Function): WebElementPromise; + + /** + * Schedules a command to test if there is at least one descendant of this + * element that matches the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether an element could be located on the page. + */ + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + + /** + * Schedules a command to find all of the descendants of this element that + * match the given search criteria. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A + * promise that will resolve to an array of WebElements. + */ + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + * + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + * + * - The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + * - The {@link webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + * + * - The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + * + * If this element is a file input ({@code }), the + * specified key sequence should specify the path to the file to attach to + * the element. This is analgous to the user clicking "Browse..." and entering + * the path into the file select dialog. + * + * var form = driver.findElement(By.css('form')); + * var element = form.findElement(By.css('input[type=file]')); + * element.sendKeys('/path/to/file.txt'); + * form.submit(); + * + * For uploads to function correctly, the entered path must reference a file + * on the _browser's_ machine, not the local machine running this script. When + * running against a remote Selenium server, a {@link webdriver.FileDetector} + * may be used to transparently copy files to the remote machine before + * attempting to upload them in the browser. + * + * __Note:__ On browsers where native keyboard events are not supported + * (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...(string|!webdriver.promise.Promise)} var_args The sequence + * of keys to type. All arguments will be joined into a single sequence. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when all keys have been typed. + */ + sendKeys(...var_args: Array>): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + * + * _Warning:_ the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value, even if it has been modified after + * the page has been loaded. More exactly, this method will return the value of + * the given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned (for example, the "value" property of a textarea + * element). The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will return either "true" or null: + * + * async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + * Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + * + * - "class" + * - "readonly" + * + * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the attribute's value. The returned value will always be + * either a string or null. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise.<{width: number, height: number}>} A + * promise that will be resolved with the element's size as a + * {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise.<{x: number, y: number}>} A promise that + * will be resolved to the element's location as a + * {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise.} A promise that will be resolved + * when the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise.} A promise that will be + * resolved with the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise; + + /** + * Returns the raw ID string ID for this element. + * @return {!webdriver.promise.Promise} A promise that resolves to this + * element's raw ID as a string value. + * @package + */ + getRawId(): webdriver.promise.Promise; + + /** @override */ + serialize(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + + /** + * Compares to WebElements for equality. + * @param {!webdriver.WebElement} a A WebElement. + * @param {!webdriver.WebElement} b A WebElement. + * @return {!webdriver.promise.Promise} A promise that will be resolved to + * whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + } + + /** + * WebElementPromise is a promise that will be fulfilled with a WebElement. + * This serves as a forward proxy on WebElement, allowing calls to be + * scheduled without directly on this instance before the underlying + * WebElement has been fulfilled. In other words, the following two statements + * are equivalent: + *
    
    +     *     driver.findElement({id: 'my-button'}).click();
    +     *     driver.findElement({id: 'my-button'}).then(function(el) {
    +     *       return el.click();
    +     *     });
    +     * 
    + * + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!webdriver.promise.Promise.} el A promise + * that will resolve to the promised element. + * @constructor + * @extends {webdriver.WebElement} + * @implements {webdriver.promise.Thenable.} + * @final + */ + class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => webdriver.promise.Promise, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: WebElement) => R, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
    
    +         *   // Synchronous API:
    +         *   try {
    +         *     doSynchronousWork();
    +         *   } catch (ex) {
    +         *     console.error(ex);
    +         *   }
    +         *
    +         *   // Asynchronous promise API:
    +         *   doAsynchronousWork().thenCatch(function(ex) {
    +         *     console.error(ex);
    +         *   });
    +         * 
    + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): webdriver.promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
    
    +         *   // Synchronous API:
    +         *   try {
    +         *     doSynchronousWork();
    +         *   } finally {
    +         *     cleanUp();
    +         *   }
    +         *
    +         *   // Asynchronous promise API:
    +         *   doAsynchronousWork().thenFinally(cleanUp);
    +         * 
    + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
    
    +         *   try {
    +         *     throw Error('one');
    +         *   } finally {
    +         *     throw Error('two');  // Hides Error: one
    +         *   }
    +         *
    +         *   webdriver.promise.rejected(Error('one'))
    +         *       .thenFinally(function() {
    +         *         throw Error('two');  // Hides Error: one
    +         *       });
    +         * 
    + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): webdriver.promise.Promise; + } + + namespace By { + /** + * Locates elements that have a specific class name. The returned locator + * is equivalent to searching for elements with the CSS selector ".clazz". + * + * @param {string} className The class name to search for. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + function className(value: string): Locator; + + /** + * Locates elements using a CSS selector. For browsers that do not support + * CSS selectors, WebDriver implementations may return an + * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An + * implementation may, however, emulate the CSS selector API. + * + * @param {string} selector The CSS selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + function css(value: string): Locator; + + /** + * Locates an element by its ID. + * + * @param {string} id The ID to search for. + * @return {!webdriver.Locator} The new locator. + */ + function id(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} matches the given string. + * + * @param {string} text The link text to search for. + * @return {!webdriver.Locator} The new locator. + */ + function linkText(value: string): Locator; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, + * JavaScript-based locator function. + */ + function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose {@code name} attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!webdriver.Locator} The new locator. + */ + function name(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} contains the given substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + */ + function partialLinkText(value: string): Locator; + + /** + * Locates elements with a given tag name. The returned locator is + * equivalent to using the + * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) + * DOM function. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html + */ + function tagName(value: string): Locator; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector {@code "//div"}, WebDriver will search from the + * document root regardless of whether the locator was used with a + * WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + function xpath(value: string): Locator; + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type Hash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + } + + /** + * An element locator. + */ + class Locator { + /** + * An element locator. + * @param {string} using The type of strategy to use for this locator. + * @param {string} value The search target of this locator. + * @constructor + */ + constructor(using: string, value: string); + + + /** + * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. + * @type {!Object.} + * @const + */ + static Strategy: { + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + js: typeof webdriver.By.js; + linkText: typeof webdriver.By.linkText; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; + }; + + /** + * Verifies that a {@code value} is a valid locator to use for searching for + * elements on the page. + * + * @param {*} value The value to check is a valid locator. + * @return {!(webdriver.Locator|Function)} A valid locator object or function. + * @throws {TypeError} If the given value is an invalid locator. + */ + static checkLocator(value: any): Locator | Function; + + /** + * The search strategy to use when searching for an element. + * @type {string} + */ + using: string; + + /** + * The search target for this locator. + * @type {string} + */ + value: string; + + /** @return {string} String representation of this locator. */ + toString(): string; + } + + /** + * Contains information about a WebDriver session. + */ + class Session { + + //region Constructors + + /** + * @param {string} id The session ID. + * @param {!(Object|webdriver.Capabilities)} capabilities The session + * capabilities. + * @constructor + */ + constructor(id: string, capabilities: Capabilities); + constructor(id: string, capabilities: any); + + //endregion + + //region Methods + + /** + * @return {string} This session's ID. + */ + getId(): string; + + /** + * @return {!webdriver.Capabilities} This session's capabilities. + */ + getCapabilities(): Capabilities; + + /** + * Retrieves the value of a specific capability. + * @param {string} key The capability to retrieve. + * @return {*} The capability value. + */ + getCapability(key: string): any; + + /** + * Returns the JSON representation of this object, which is just the string + * session ID. + * @return {string} The JSON representation of this Session. + */ + toJSON(): string; + + //endregion + } +} + +declare namespace testing { + /** + * Registers a new test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function describe(name: string, fn: Function): void; + + /** + * Defines a suppressed test suite. + * @param name The suite name. + * @param fn The suite function, or {@code undefined} to define a pending test suite. + */ + function xdescribe(name: string, fn: Function): void; + + /** + * Register a function to call after the current suite finishes. + * @param fn + */ + function after(fn: Function): void; + + /** + * Register a function to call after each test in a suite. + * @param fn + */ + function afterEach(fn: Function): void; + + /** + * Register a function to call before the current suite starts. + * @param fn + */ + function before(fn: Function): void; + + /** + * Register a function to call before each test in a suite. + * @param fn + */ + function beforeEach(fn: Function): void; + + /** + * Add a test to the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function it(name: string, fn: Function): void; + + /** + * An alias for {@link #it()} that flags the test as the only one that should + * be run within the current suite. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function iit(name: string, fn: Function): void; + + /** + * Adds a test to the current suite while suppressing it so it is not run. + * @param name The test name. + * @param fn The test function, or {@code undefined} to define a pending test case. + */ + function xit(name: string, fn: Function): void; +} + +declare module 'selenium-webdriver/chrome' { + export = chrome; +} + +declare module 'selenium-webdriver/firefox' { + export = firefox; +} + +declare module 'selenium-webdriver/executors' { + export = executors; +} + +declare module 'selenium-webdriver' { + export = webdriver; +} + +declare module 'selenium-webdriver/testing' { + export = testing; +} diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 345a8efc5b..1ab39ba02a 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -3,7 +3,7 @@ function TestChromeDriver() { var driver: chrome.Driver = new chrome.Driver(); driver = new chrome.Driver(webdriver.Capabilities.chrome()); - driver = new chrome.Driver(webdriver.Capabilities.chrome(), new webdriver.promise.ControlFlow()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -31,7 +31,6 @@ function TestChromeOptions() { options = options.setUserPreferences("preferences"); var capabilities: webdriver.Capabilities = options.toCapabilities(); capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); - var values: chrome.IOptionsValues = options.toJSON(); } function TestServiceBuilder() { @@ -52,7 +51,7 @@ function TestServiceBuilder() { function TestChromeModule() { var service: any = chrome.getDefaultService(); - chrome.setDefaultService({}); + chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); } function TestBinary() { @@ -66,8 +65,8 @@ function TestBinary() { function TestFirefoxDriver() { var driver: firefox.Driver = new firefox.Driver(); - driver = new chrome.Driver(webdriver.Capabilities.firefox()); - driver = new chrome.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + driver = new firefox.Driver(webdriver.Capabilities.firefox()); + driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -82,7 +81,6 @@ function TestFirefoxOptions() { options = options.setProfile(new firefox.Profile()); options = options.setProxy({ proxyType: "proxy" }); var capabilities: webdriver.Capabilities = options.toCapabilities(); - var capabilities: webdriver.Capabilities = options.toCapabilities({}); } function TestFirefoxProfile() { @@ -108,7 +106,7 @@ function TestFirefoxProfile() { } function TestExecutors() { - var exec: webdriver.CommandExecutor = executors.createExecutor("url"); + var exec: webdriver.Executor = executors.createExecutor("url"); var promise: webdriver.promise.Promise; exec = executors.createExecutor(promise); } @@ -144,7 +142,9 @@ function TestActionSequence() { build(); var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); - var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var promise: webdriver.promise.Promise; + element = new webdriver.WebElement(driver, promise); // Click sequence = sequence.click(); @@ -187,7 +187,6 @@ function TestActionSequence() { // SendKeys sequence = sequence.sendKeys("A", "B", "C"); - sequence = sequence.sendKeys(["A", "B", "C"]); sequence.perform().then(function () { }); } @@ -196,7 +195,7 @@ function TestTouchSequence() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); @@ -319,9 +318,9 @@ function TestCommand() { command = command.setParameters({ param: 123 }); } -function TestCommandExecutor() { - var c: webdriver.CommandExecutor = { execute: function (command: webdriver.Command, callback: (error: Error, obj: any) => any) { } }; - c.execute(new webdriver.Command('name'), function (error: Error, response: any) { }); +function TestDeferredExecutor() { + var promise: webdriver.promise.Promise; + var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); } function TestCommandName() { @@ -458,7 +457,7 @@ function TestEventEmitter() { } function TestKey() { - var key: string; + var key: webdriver.Key; key = webdriver.Key.ADD; key = webdriver.Key.ALT; @@ -520,35 +519,15 @@ function TestKey() { key = webdriver.Key.SUBTRACT; key = webdriver.Key.TAB; key = webdriver.Key.UP; - - key = webdriver.Key.chord(webdriver.Key.NUMPAD0, webdriver.Key.NUMPAD1); } -function TestLocator() { +function TestBy() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.Locator = new webdriver.Locator('class name', 'class'); + var locator: webdriver.By = new webdriver.By('class name', 'class'); - var locatorOrFn: webdriver.Locator|Function; - - locatorOrFn = webdriver.Locator.Strategy.className; - locatorOrFn = webdriver.Locator.Strategy.css; - locatorOrFn = webdriver.Locator.Strategy.id; - locatorOrFn = webdriver.Locator.Strategy.js; - locatorOrFn = webdriver.Locator.Strategy.linkText; - locatorOrFn = webdriver.Locator.Strategy.name; - locatorOrFn = webdriver.Locator.Strategy.partialLinkText; - locatorOrFn = webdriver.Locator.Strategy.tagName; - locatorOrFn = webdriver.Locator.Strategy.xpath; - - locatorOrFn = webdriver.Locator.checkLocator(locator); - locatorOrFn = webdriver.Locator.checkLocator({ className: 'class' }); - locatorOrFn = webdriver.Locator.checkLocator(Error); - - var using: string = locator.using; - var value: string = locator.value; var str: string = locator.toString(); locator = webdriver.By.className('class'); @@ -563,7 +542,7 @@ function TestLocator() { // Can import "By" without import declarations var By = webdriver.By; - var locatorHash: webdriver.By.Hash; + var locatorHash: webdriver.ByHash; locatorHash = { className: 'class' }; locatorHash = { css: 'css' }; locatorHash = { id: 'id' }; @@ -591,9 +570,7 @@ function TestSession() { function TestUnhandledAlertError() { var someFunc = function (error: webdriver.UnhandledAlertError) { - var baseError: webdriver.error.Error = error; - - var alert: webdriver.Alert = error.getAlert(); + var baseError: Error = error; var str: string = error.getAlertText(); str = error.toString(); } @@ -614,7 +591,7 @@ function TestWebDriverLogs() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var logs: webdriver.WebDriverLogs = new webdriver.WebDriver.Logs(driver); + var logs: webdriver.Logs = new webdriver.Logs(driver); logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; logs.getAvailableLogTypes().then(function (types: string[]) { }); @@ -625,7 +602,7 @@ function TestWebDriverNavigation() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var navigation: webdriver.WebDriverNavigation = new webdriver.WebDriver.Navigation(driver); + var navigation: webdriver.Navigation = new webdriver.Navigation(driver); navigation.back().then(function () { }); navigation.forward().then(function () { }); @@ -638,7 +615,7 @@ function TestWebDriverOptions() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var options: webdriver.WebDriverOptions = new webdriver.WebDriver.Options(driver); + var options: webdriver.Options = new webdriver.Options(driver); var promise: webdriver.promise.Promise; // Add Cookie @@ -654,9 +631,9 @@ function TestWebDriverOptions() { options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); - var logs: webdriver.WebDriverLogs = options.logs(); - var timeouts: webdriver.WebDriverTimeouts = options.timeouts(); - var window: webdriver.WebDriverWindow = options.window(); + var logs: webdriver.Logs = options.logs(); + var timeouts: webdriver.Timeouts = options.timeouts(); + var window: webdriver.Window = options.window(); } function TestWebDriverTargetLocator() { @@ -664,13 +641,12 @@ function TestWebDriverTargetLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.WebDriverTargetLocator = new webdriver.WebDriver.TargetLocator(driver); + var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); var promise: webdriver.promise.Promise; var element: webdriver.WebElement = locator.activeElement(); var alert: webdriver.Alert = locator.alert(); promise = locator.defaultContent(); - promise = locator.frame('name'); promise = locator.frame(1); promise = locator.window('nameOrHandle'); } @@ -680,7 +656,7 @@ function TestWebDriverTimeouts() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var timeouts: webdriver.WebDriverTimeouts = new webdriver.WebDriver.Timeouts(driver); + var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); var promise: webdriver.promise.Promise; promise = timeouts.implicitlyWait(123); @@ -693,7 +669,7 @@ function TestWebDriverWindow() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var window: webdriver.WebDriverWindow = new webdriver.WebDriver.Window(driver); + var window: webdriver.Window = new webdriver.Window(driver); var locationPromise: webdriver.promise.Promise; var sizePromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; @@ -708,7 +684,7 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); var sessionPromise: webdriver.promise.Promise; - var executor: webdriver.CommandExecutor = executors.createExecutor("http://someserver"); + var executor: webdriver.Executor = executors.createExecutor("http://someserver"); var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); driver = new webdriver.WebDriver(session, executor, flow); @@ -746,15 +722,11 @@ function TestWebDriver() { // findElement var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); - element = driver.findElement({id: 'ABC'}); element = driver.findElement(webdriver.By.js('function(){}')); - element = driver.findElement({js: 'function(){}'}); // findElements driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ js: 'function(){}' }).then(function (elements: webdriver.WebElement[]) { }); voidPromise = driver.get('http://www.google.com'); driver.getAllWindowHandles().then(function (handles: string[]) { }); @@ -766,13 +738,11 @@ function TestWebDriver() { stringPromise = driver.getWindowHandle(); booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = driver.isElementPresent({className: 'ABC'}); booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); - booleanPromise = driver.isElementPresent({js: 'function(){}'}); - var options: webdriver.WebDriverOptions = driver.manage(); - var navigation: webdriver.WebDriverNavigation = driver.navigate(); - var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); + var options: webdriver.Options = driver.manage(); + var navigation: webdriver.Navigation = driver.navigate(); + var locator: webdriver.TargetLocator = driver.switchTo(); var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); driver.setFileDetector(fileDetector); @@ -795,7 +765,7 @@ function TestWebDriver() { function TestSerializable() { var serializable: webdriver.Serializable; - var serial: string|webdriver.promise.Promise = serializable.serialize(); + var serial: string|webdriver.promise.IThenable = serializable.serialize(); } function TestWebElement() { @@ -803,10 +773,10 @@ function TestWebElement() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var promise: webdriver.promise.Promise; + var promise: webdriver.promise.Promise; var element: webdriver.WebElement; - element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); + element = new webdriver.WebElement(driver, 'elementId'); element = new webdriver.WebElement(driver, promise); var voidPromise: webdriver.promise.Promise; @@ -817,13 +787,8 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); - element = element.findElement({id: 'ABC'}); - element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); - element.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); - booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = element.isElementPresent({className: 'ABC'}); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); @@ -840,14 +805,11 @@ function TestWebElement() { voidPromise = element.sendKeys('A', 'B', 'C'); voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: typeof webdriver.WebElement.Id) { }); + element.getId().then(function (id: string) { }); element.getRawId().then(function (id: string) { }); - element.serialize().then(function (id: typeof webdriver.WebElement.Id) { }); + element.serialize().then(function (id: webdriver.IWebElementId) { }); - booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); - - var id: typeof webdriver.WebElement.Id = webdriver.WebElement.Id; - var key: string = webdriver.WebElement.ELEMENT_KEY; + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); } function TestWebElementPromise() { @@ -877,7 +839,7 @@ function TestLogging() { preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); var prefs: any = preferences.toJSON(); - var level: webdriver.logging.ILevel = webdriver.logging.getLevel('OFF'); + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); level = webdriver.logging.getLevel(1); level = webdriver.logging.Level.ALL; @@ -887,10 +849,10 @@ function TestLogging() { level = webdriver.logging.Level.SEVERE; level = webdriver.logging.Level.WARNING; - var name: string = level.name; - var value: number = level.value; + var name: string = level.name(); + var value: number = level.value(); - var type: string; + var type: webdriver.logging.Type; type = webdriver.logging.Type.BROWSER; type = webdriver.logging.Type.CLIENT; type = webdriver.logging.Type.DRIVER; @@ -913,9 +875,6 @@ function TestLoggingEntry() { var message: string = entry.message; var timestamp: number = entry.timestamp; var type: string = entry.type; - - entry = webdriver.logging.Entry.fromClosureLogRecord({}); - entry = webdriver.logging.Entry.fromClosureLogRecord({}, webdriver.logging.Type.DRIVER); } function TestPromiseModule() { @@ -946,29 +905,29 @@ function TestPromiseModule() { return 5; }, this, 1, 2, 3).then(function (value: number) { }); - var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { return true; }, this); @@ -995,26 +954,13 @@ function TestPromiseModule() { var bool: boolean = webdriver.promise.isGenerator(function () { }); var isPromise: boolean = webdriver.promise.isPromise('ABC'); - voidPromise = webdriver.promise.rejected({a: 123}); + stringPromise = webdriver.promise.rejected('{a: 123}'); webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); numberPromise = webdriver.promise.when('abc', function(value: any) { return 123; }, function(err: Error) { return 123; }); } -function TestStacktraceModule() { - var bool: boolean = webdriver.stacktrace.BROWSER_SUPPORTED; - - var frame: webdriver.stacktrace.Frame = new webdriver.stacktrace.Frame(); - var baseFrame: webdriver.stacktrace.Frame = frame; - - var snapshot: webdriver.stacktrace.Snapshot = new webdriver.stacktrace.Snapshot(); - var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; - - var err: Error = webdriver.stacktrace.format(new Error("Error")); - var frames: webdriver.stacktrace.Frame[] = webdriver.stacktrace.get(); -} - function TestUntilModule() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -1125,13 +1071,12 @@ function TestPromiseClass() { } function TestThenableClass() { - var thenable: webdriver.promise.Thenable = new webdriver.promise.Thenable(); + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); thenable.cancel('Abort'); var isPending: boolean = thenable.isPending(); - thenable = thenable.then(); thenable = thenable.then(function (a: string) { return 'cde'; }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); @@ -1144,76 +1089,30 @@ function TestThenableClass() { function TestErrorCode() { var errorCode: number; - errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE; - errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_VISIBLE; - errorCode = webdriver.error.ErrorCode.IME_ENGINE_ACTIVATION_FAILED; - errorCode = webdriver.error.ErrorCode.IME_NOT_AVAILABLE; - errorCode = webdriver.error.ErrorCode.INVALID_COOKIE_DOMAIN; - errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_COORDINATES; - errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_STATE; - errorCode = webdriver.error.ErrorCode.INVALID_SELECTOR_ERROR; - errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR; - errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPE; - errorCode = webdriver.error.ErrorCode.JAVASCRIPT_ERROR; - errorCode = webdriver.error.ErrorCode.METHOD_NOT_ALLOWED; - errorCode = webdriver.error.ErrorCode.MODAL_DIALOG_OPENED; - errorCode = webdriver.error.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS; - errorCode = webdriver.error.ErrorCode.NO_MODAL_DIALOG_OPEN; - errorCode = webdriver.error.ErrorCode.NO_SUCH_ELEMENT; - errorCode = webdriver.error.ErrorCode.NO_SUCH_FRAME; - errorCode = webdriver.error.ErrorCode.NO_SUCH_WINDOW; - errorCode = webdriver.error.ErrorCode.SCRIPT_TIMEOUT; - errorCode = webdriver.error.ErrorCode.SESSION_NOT_CREATED; - errorCode = webdriver.error.ErrorCode.SQL_DATABASE_ERROR; - errorCode = webdriver.error.ErrorCode.STALE_ELEMENT_REFERENCE; - errorCode = webdriver.error.ErrorCode.SUCCESS; - errorCode = webdriver.error.ErrorCode.TIMEOUT; - errorCode = webdriver.error.ErrorCode.UNABLE_TO_SET_COOKIE; - errorCode = webdriver.error.ErrorCode.UNKNOWN_COMMAND; - errorCode = webdriver.error.ErrorCode.UNKNOWN_ERROR; - errorCode = webdriver.error.ErrorCode.UNSUPPORTED_OPERATION; - errorCode = webdriver.error.ErrorCode.XPATH_LOOKUP_ERROR; -} - -function TestError() { - var error: webdriver.error.Error; - - error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE); - error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE, 'Message'); - - var code: number = error.code; - var state: string = error.state; - var message: string = error.message; - var name: string = error.name; - var stack: string = error.stack; - var isAutomationError: boolean = error.isAutomationError; - var errorStr: string = error.toString(); - - state = webdriver.error.Error.State.ELEMENT_NOT_SELECTABLE - state = webdriver.error.Error.State.ELEMENT_NOT_VISIBLE; - state = webdriver.error.Error.State.IME_ENGINE_ACTIVATION_FAILED; - state = webdriver.error.Error.State.IME_NOT_AVAILABLE; - state = webdriver.error.Error.State.INVALID_COOKIE_DOMAIN; - state = webdriver.error.Error.State.INVALID_ELEMENT_COORDINATES; - state = webdriver.error.Error.State.INVALID_ELEMENT_STATE; - state = webdriver.error.Error.State.INVALID_SELECTOR; - state = webdriver.error.Error.State.JAVASCRIPT_ERROR; - state = webdriver.error.Error.State.MOVE_TARGET_OUT_OF_BOUNDS; - state = webdriver.error.Error.State.NO_SUCH_ALERT; - state = webdriver.error.Error.State.NO_SUCH_DOM - state = webdriver.error.Error.State.NO_SUCH_ELEMENT; - state = webdriver.error.Error.State.NO_SUCH_FRAME; - state = webdriver.error.Error.State.NO_SUCH_WINDOW; - state = webdriver.error.Error.State.SCRIPT_TIMEOUT; - state = webdriver.error.Error.State.SESSION_NOT_CREATED; - state = webdriver.error.Error.State.STALE_ELEMENT_REFERENCE; - state = webdriver.error.Error.State.SUCCESS; - state = webdriver.error.Error.State.TIMEOUT; - state = webdriver.error.Error.State.UNABLE_TO_SET_COOKIE; - state = webdriver.error.Error.State.UNEXPECTED_ALERT_OPEN - state = webdriver.error.Error.State.UNKNOWN_COMMAND; - state = webdriver.error.Error.State.UNKNOWN_ERROR; - state = webdriver.error.Error.State.UNSUPPORTED_OPERATION; + errorCode = new webdriver.error.ElementNotSelectableError().code(); + errorCode = new webdriver.error.ElementNotVisibleError().code(); + errorCode = new webdriver.error.InvalidArgumentError().code(); + errorCode = new webdriver.error.InvalidCookieDomainError().code(); + errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); + errorCode = new webdriver.error.InvalidElementStateError().code(); + errorCode = new webdriver.error.InvalidSelectorError().code(); + errorCode = new webdriver.error.NoSuchSessionError().code(); + errorCode = new webdriver.error.JavascriptError().code(); + errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); + errorCode = new webdriver.error.NoSuchAlertError().code(); + errorCode = new webdriver.error.NoSuchElementError().code(); + errorCode = new webdriver.error.NoSuchFrameError().code(); + errorCode = new webdriver.error.NoSuchWindowError().code(); + errorCode = new webdriver.error.ScriptTimeoutError().code(); + errorCode = new webdriver.error.SessionNotCreatedError().code(); + errorCode = new webdriver.error.StaleElementReferenceError().code(); + errorCode = new webdriver.error.TimeoutError().code(); + errorCode = new webdriver.error.UnableToSetCookieError().code(); + errorCode = new webdriver.error.UnableToCaptureScreenError().code(); + errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); + errorCode = new webdriver.error.UnknownCommandError().code(); + errorCode = new webdriver.error.UnknownMethodError().code(); + errorCode = new webdriver.error.UnsupportedOperationError().code(); } function TestTestingModule() { diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index 548048b695..b3afe098ac 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1,5 +1,5 @@ -// Type definitions for Selenium WebDriverJS 2.44.0 -// Project: https://code.google.com/p/selenium/ +// Type definitions for Selenium WebDriverJS 2.53.1 +// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver // Definitions by: Bill Armstrong , Yuki Kokubun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -19,8 +19,7 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -240,6 +239,53 @@ declare namespace chrome { setChromeLogFile(path: string): Options; + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + /** * Sets the proxy settings for the new session. * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. @@ -255,21 +301,6 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - - - /** - * Converts this instance to its JSON wire protocol representation. Note this - * function is an implementation not intended for general use. - * @return {{args: !Array., - * binary: (string|undefined), - * detach: boolean, - * extensions: !Array., - * localState: (Object|undefined), - * logFile: (string|undefined), - * prefs: (Object|undefined)}} The JSON wire protocol representation - * of this instance. - */ - toJSON(): IOptionsValues; } /** @@ -348,8 +379,7 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string): ServiceBuilder; - setStdio(config: any[]): ServiceBuilder; + setStdio(config: string|Array): ServiceBuilder; /** @@ -368,7 +398,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): any; + build(): remote.DriverService; } /** @@ -377,395 +407,1325 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): any; + function getDefaultService(): remote.DriverService; /** * Sets the default service to use for new ChromeDriver instances. * @param {!remote.DriverService} service The service to use. * @throws {Error} If the default service is currently running. */ - function setDefaultService(service: any): void; + function setDefaultService(service: remote.DriverService): void; } -declare namespace firefox { - /** - * Manages a Firefox subprocess configured for use with WebDriver. - */ - class Binary { - /** - * @param {string=} opt_exe Path to the Firefox binary to use. If not - * specified, will attempt to locate Firefox on the current system. - * @constructor - */ - constructor(opt_exe?: string); +declare namespace edge { - /** - * Add arguments to the command line used to start Firefox. - * @param {...(string|!Array.)} var_args Either the arguments to add as - * varargs, or the arguments as an array. - */ - addArguments(...var_args: string[]): void; - - - /** - * Launches Firefox and eturns a promise that will be fulfilled when the process - * terminates. - * @param {string} profile Path to the profile directory to use. - * @return {!promise.Promise.} A promise for the process result. - * @throws {Error} If this instance has already been started. - */ - launch(profile: string): webdriver.promise.Promise; - - - /** - * Kills the managed Firefox process. - * @return {!promise.Promise} A promise for when the process has terminated. - */ - kill(): webdriver.promise.Promise; - } - - /** - * A WebDriver client for Firefox. - * - * @extends {webdriver.WebDriver} - */ class Driver extends webdriver.WebDriver { - /** - * @param {(Options|webdriver.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash - * object. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - * @constructor - */ - constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@linkplain #getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; } /** - * Configuration options for the FirefoxDriver. + * Class for managing MicrosoftEdgeDriver specific options. */ class Options { - /** - * @constructor - */ - constructor(); - /** - * Sets the profile to use. The profile may be specified as a - * {@link Profile} object or as the path to an existing Firefox profile to use - * as a template. - * - * @param {(string|!Profile)} profile The profile to use. - * @return {!Options} A self reference. - */ - setProfile(profile: string): Options; - setProfile(profile: Profile): Options; + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; - /** - * Sets the binary to use. The binary may be specified as the path to a Firefox - * executable, or as a {@link Binary} object. - * - * @param {(string|!Binary)} binary The binary to use. - * @return {!Options} A self reference. - */ - setBinary(binary: string): Options; - setBinary(binary: Binary): Options; + /** + * Sets the page load strategy for Edge. + * Supported values are "normal", "eager", and "none"; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; - - /** - * Sets the logging preferences for the new session. - * @param {webdriver.logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - - /** - * Sets the proxy to use. - * - * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - - /** - * Converts these options to a {@link webdriver.Capabilities} instance. - * - * @return {!webdriver.Capabilities} A new capabilities object. - */ - toCapabilities(opt_remote?: any): webdriver.Capabilities; + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; } /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. */ - class Profile { - /** - * @param {string=} opt_dir Path to an existing Firefox profile directory to - * use a template for this profile. If not specified, a blank profile will - * be used. - * @constructor - */ - constructor(opt_dir?: string); + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); - /** - * Registers an extension to be included with this profile. - * @param {string} extension Path to the extension to include, as either an - * unpacked extension directory or the path to a xpi file. - */ - addExtension(extension: string): void; + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; - /** - * Sets a desired preference for this profile. - * @param {string} key The preference key. - * @param {(string|number|boolean)} value The preference value. - * @throws {Error} If attempting to set a frozen preference. - */ - setPreference(key: string, value: string): void; - setPreference(key: string, value: number): void; - setPreference(key: string, value: boolean): void; + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; - - /** - * Returns the currently configured value of a profile preference. This does - * not include any defaults defined in the profile's template directory user.js - * file (if a template were specified on construction). - * @param {string} key The desired preference. - * @return {(string|number|boolean|undefined)} The current value of the - * requested preference. - */ - getPreference(key: string): any; - - - /** - * @return {number} The port this profile is currently configured to use, or - * 0 if the port will be selected at random when the profile is written - * to disk. - */ - getPort(): number; - - - /** - * Sets the port to use for the WebDriver extension loaded by this profile. - * @param {number} port The desired port, or 0 to use any free port. - */ - setPort(port: number): void; - - - /** - * @return {boolean} Whether the FirefoxDriver is configured to automatically - * accept untrusted SSL certificates. - */ - acceptUntrustedCerts(): boolean; - - - /** - * Sets whether the FirefoxDriver should automatically accept untrusted SSL - * certificates. - * @param {boolean} value . - */ - setAcceptUntrustedCerts(value: boolean): void; - - - /** - * Sets whether to assume untrusted certificates come from untrusted issuers. - * @param {boolean} value . - */ - setAssumeUntrustedCertIssuer(value: boolean): void; - - - /** - * @return {boolean} Whether to assume untrusted certs come from untrusted - * issuers. - */ - assumeUntrustedCertIssuer(): boolean; - - - /** - * Sets whether to use native events with this profile. - * @param {boolean} enabled . - */ - setNativeEventsEnabled(enabled: boolean): void; - - - /** - * Returns whether native events are enabled in this profile. - * @return {boolean} . - */ - nativeEventsEnabled(): boolean; - - - /** - * Writes this profile to disk. - * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver - * extension from the generated profile. Used to reduce the size of an - * {@link #encode() encoded profile} since the server will always install - * the extension itself. - * @return {!promise.Promise.} A promise for the path to the new - * profile directory. - */ - writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; - - - /** - * Encodes this profile as a zipped, base64 encoded directory. - * @return {!promise.Promise.} A promise for the encoded profile. - */ - encode(): webdriver.promise.Promise; + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; } + + /** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Sets the default service to use for new MicrosoftEdgeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): void; } declare namespace executors { /** * Creates a command executor that uses WebDriver's JSON wire protocol. - * @param url The server's URL, or a promise that will resolve to that URL. - * @returns {!webdriver.CommandExecutor} The new command executor. + * @param {(string|!promise.Promise)} url The server's URL, + * or a promise that will resolve to that URL. + * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the + * client to use. + * @returns {!./lib/command.Executor} The new command executor. */ - function createExecutor(url: string): webdriver.CommandExecutor; - function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; + function createExecutor(url: string|webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; +} + +declare namespace firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; + } + + /** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string|any): Options; + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string|any): Options; + + /** + * Sets the logging preferences for the new session. + * @param {logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy to use. + * + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets whether to use Mozilla's Marionette to drive the browser. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + */ + useMarionette(marionette: any): Options; + + /** + * Converts these options to a {@link capabilities.Capabilities} instance. + * + * @return {!capabilities.Capabilities} A new capabilities object. + */ + toCapabilities(): webdriver.Capabilities; + } + + /** + * @return {string} . + * @throws {Error} + */ + function findWires(): string; + + /** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ + function createWiresService(binary: string|any): remote.DriverService; + + /** + * @param {(Profile|string)} profile The profile to prepare. + * @param {number} port The port the FirefoxDriver should listen on. + * @return {!Promise} a promise for the path to the profile directory. + */ + function prepareProfile(profile: string|any, port: number): any; + + /** + * A WebDriver client for Firefox. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|capabilities.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash + * object. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(opt_config?: Options|webdriver.Capabilities|Object, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace http { + /** + * Converts a headers map to a HTTP header block string. + * @param {!Map} headers The map to convert. + * @return {string} The headers as a string. + */ + function headersToString(headers: any): string; + + /** + * Represents a HTTP request message. This class is a "partial" request and only + * defines the path on the server to send a request to. It is each client's + * responsibility to build the full URL for the final request. + * @final + */ + class HttpRequest { + /** + * @param {string} method The HTTP method to use for the request. + * @param {string} path The path on the server to send the request to. + * @param {Object=} opt_data This request's non-serialized JSON payload data. + */ + constructor(method: string, path: string, opt_data?: Object); + + /** @override */ + toString(): string; + } + + /** + * Represents a HTTP response message. + * @final + */ + class HttpResponse { + /** + * @param {number} status The response code. + * @param {!Object} headers The response headers. All header names + * will be converted to lowercase strings for consistent lookups. + * @param {string} body The response body. + */ + constructor(status: number, headers: Object, body: string); + + /** @override */ + toString(): string; + } + + + function post(path: string): any; + function del(path: string): any; + function get(path: string): any; + function resource(method: string, path: string): any; + + /** + * A basic HTTP client used to send messages to a remote end. + */ + class HttpClient { + /** + * @param {string} serverUrl URL for the WebDriver server to send commands to. + * @param {http.Agent=} opt_agent The agent to use for each request. + * Defaults to `http.globalAgent`. + * @param {?string=} opt_proxy The proxy to use for the connection to the + * server. Default is to use no proxy. + */ + constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); + + /** + * Sends a request to the server. The client will automatically follow any + * redirects returned by the server, fulfilling the returned promise with the + * final response. + * + * @param {!HttpRequest} httpRequest The request to send. + * @return {!promise.Promise} A promise that will be fulfilled + * with the server's response. + */ + send(httpRequest: HttpRequest): webdriver.promise.Promise; + } + + /** + * Sends a single HTTP request. + * @param {!Object} options The request options. + * @param {function(!HttpResponse)} onOk The function to call if the + * request succeeds. + * @param {function(!Error)} onError The function to call if the request fails. + * @param {?string=} opt_data The data to send with the request. + * @param {?string=} opt_proxy The proxy server to use for the request. + */ + function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; + + /** + * A command executor that communicates with the server using HTTP + JSON. + * + * By default, each instance of this class will use the legacy wire protocol + * from [Selenium project][json]. The executor will automatically switch to the + * [W3C wire protocol][w3c] if the remote end returns a compliant response to + * a new session command. + * + * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html + * + * @implements {cmd.Executor} + */ + class Executor { + /** + * @param {!HttpClient} client The client to use for sending requests to the + * server. + */ + constructor(client: HttpClient); + + /** + * Defines a new command for use with this executor. When a command is sent, + * the {@code path} will be preprocessed using the command's parameters; any + * path segments prefixed with ":" will be replaced by the parameter of the + * same name. For example, given "/person/:name" and the parameters + * "{name: 'Bob'}", the final command path will be "/person/Bob". + * + * @param {string} name The command name. + * @param {string} method The HTTP method to use when sending this command. + * @param {string} path The path to send the command to, relative to + * the WebDriver server's command root and of the form + * "/path/:variable/segment". + */ + defineCommand(name: string, method: string, path: string): void; + + /** @override */ + execute(command: any): any; + } + + /** + * @param {string} str . + * @return {?} . + */ + function tryParse(str: string): any; + + /** + * Callback used to parse {@link HttpResponse} objects from a + * {@link HttpClient}. + * @param {!HttpResponse} httpResponse The HTTP response to parse. + * @param {boolean} w3c Whether the response should be processed using the + * W3C wire protocol. + * @return {{value: ?}} The parsed response. + * @throws {WebDriverError} If the HTTP response is an error. + */ + function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; + + /** + * Builds a fully qualified path using the given set of command parameters. Each + * path segment prefixed with ':' will be replaced by the value of the + * corresponding parameter. All parameters spliced into the path will be + * removed from the parameter map. + * @param {string} path The original resource path. + * @param {!Object<*>} parameters The parameters object to splice into the path. + * @return {string} The modified path. + */ + function buildPath(path: string, parameters: Object): string; +} + +declare namespace ie { + + /** + * A WebDriver client for Microsoft's Internet Explorer. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } + + /** + * Class for managing IEDriver specific options. + */ + class Options { + constructor(); + + /** + * Extracts the IEDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The IEDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Whether to disable the protected mode settings check when the session is + * created. Disbling this setting may lead to significant instability as the + * browser may become unresponsive/hang. Only "best effort" support is provided + * when using this capability. + * + * For more information, refer to the IEDriver's + * [required system configuration](http://goo.gl/eH0Yi3). + * + * @param {boolean} ignoreSettings Whether to ignore protected mode settings. + * @return {!Options} A self reference. + */ + introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; + + /** + * Indicates whether to skip the check that the browser's zoom level is set to + * 100%. + * + * @param {boolean} ignore Whether to ignore the browser's zoom level settings. + * @return {!Options} A self reference. + */ + ignoreZoomSetting(ignore: boolean): Options; + + /** + * Sets the initial URL loaded when IE starts. This is intended to be used with + * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in + * the proper Protected Mode zone. Setting this option may cause browser + * instability or flaky and unresponsive code. Only "best effort" support is + * provided when using this option. + * + * @param {string} url The initial browser URL. + * @return {!Options} A self reference. + */ + initialBrowserUrl(url: string): Options; + + /** + * Configures whether to enable persistent mouse hovering (true by default). + * Persistent hovering is achieved by continuously firing mouse over events at + * the last location the mouse cursor has been moved to. + * + * @param {boolean} enable Whether to enable persistent hovering. + * @return {!Options} A self reference. + */ + enablePersistentHover(enable: boolean): Options; + + /** + * Configures whether the driver should attempt to remove obsolete + * {@linkplain webdriver.WebElement WebElements} from its internal cache on + * page navigation (true by default). Disabling this option will cause the + * driver to run with a larger memory footprint. + * + * @param {boolean} enable Whether to enable element reference cleanup. + * @return {!Options} A self reference. + */ + enableElementCacheCleanup(enable: boolean): Options; + + /** + * Configures whether to require the IE window to have input focus before + * performing any user interactions (i.e. mouse or keyboard events). This + * option is disabled by default, but delivers much more accurate interaction + * events when enabled. + * + * @param {boolean} require Whether to require window focus. + * @return {!Options} A self reference. + */ + requireWindowFocus(require: boolean): Options; + + /** + * Configures the timeout, in milliseconds, that the driver will attempt to + * located and attach to a newly opened instance of Internet Explorer. The + * default is zero, which indicates waiting indefinitely. + * + * @param {number} timeout How long to wait for IE. + * @return {!Options} A self reference. + */ + browserAttachTimeout(timeout: number): Options; + + /** + * Configures whether to launch Internet Explorer using the CreateProcess API. + * If this option is not specified, IE is launched using IELaunchURL, if + * available. For IE 8 and above, this option requires the TabProcGrowth + * registry value to be set to 0. + * + * @param {boolean} force Whether to use the CreateProcess API. + * @return {!Options} A self reference. + */ + forceCreateProcessApi(force: boolean): Options; + + /** + * Specifies command-line switches to use when launching Internet Explorer. + * This is only valid when used with {@link #forceCreateProcessApi}. + * + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Configures whether proxies should be configured on a per-process basis. If + * not set, setting a {@linkplain #setProxy proxy} will configure the system + * proxy. The default behavior is to use the system proxy. + * + * @param {boolean} enable Whether to enable per-process proxy settings. + * @return {!Options} A self reference. + */ + usePerProcessProxy(enable: boolean): Options; + + /** + * Configures whether to clear the cache, cookies, history, and saved form data + * before starting the browser. _Using this capability will clear session data + * for all running instances of Internet Explorer, including those started + * manually._ + * + * @param {boolean} cleanSession Whether to clear all session data on startup. + * @return {!Options} A self reference. + */ + ensureCleanSession(cleanSession: boolean): Options; + + /** + * Sets the path to the log file the driver should log to. + * @param {string} file The log file path. + * @return {!Options} A self reference. + */ + setLogFile(file: string): Options; + + /** + * Sets the IEDriverServer's logging {@linkplain Level level}. + * @param {Level} level The logging level. + * @return {!Options} A self reference. + */ + setLogLevel(level: webdriver.logging.Level): Options; + + /** + * Sets the IP address of the driver's host adapter. + * @param {string} host The IP address to use. + * @return {!Options} A self reference. + */ + setHost(host: string): Options; + + /** + * Sets the path of the temporary data directory to use. + * @param {string} path The log file path. + * @return {!Options} A self reference. + */ + setExtractPath(path: string): Options; + + /** + * Sets whether the driver should start in silent mode. + * @param {boolean} silent Whether to run in silent mode. + * @return {!Options} A self reference. + */ + silent(silent: boolean): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + +} + +declare namespace opera { + /** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the operadriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the operadriver + * cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the OperaDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; + } + + /** + * Sets the default service to use for new OperaDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): any; + + /** + * Returns the default OperaDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a OperaDriver executable found on the system PATH. + * @return {!remote.DriverService} The default OperaDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ + class Options { + /** + * Extracts the OperaDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The OperaDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Add additional command line arguments to use when launching the Opera + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Add additional extensions to install when launching Opera. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: Array): Options; + + /** + * Sets the path to the Opera binary to use. On Mac OS X, this path should + * reference the actual Opera executable, not just the application binary. The + * binary path be absolute or relative to the operadriver server executable, but + * it must exist on the machine that will launch Opera. + * + * @param {string} path The path to the Opera binary to use. + * @return {!Options} A self reference. + */ + setOperaBinaryPath(path: string): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + } + + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace remote { + /** + * A record object that defines the configuration options for a DriverService + * instance. + * + * @record + */ + interface ServiceOptions {} + + /** + * Manages the life and death of a native executable WebDriver server. + * + * It is expected that the driver server implements the + * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. + * Furthermore, the managed server should support multiple concurrent sessions, + * so that this class may be reused for multiple clients. + */ + class DriverService { + /** + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. + */ + constructor(executable: string, options: ServiceOptions); + + /** + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. + */ + address(): webdriver.promise.Promise; + + /** + * Returns whether the underlying process is still running. This does not take + * into account whether the process is in the process of shutting down. + * @return {boolean} Whether the underlying service process is running. + */ + isRunning(): boolean; + + /** + * Starts the server if it is not already running. + * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the + * server to start accepting requests. Defaults to 30 seconds. + * @return {!promise.Promise} A promise that will resolve + * to the server's base URL when it has started accepting requests. If the + * timeout expires before the server has started, the promise will be + * rejected. + */ + start(opt_timeoutMs?: number): webdriver.promise.Promise; + + /** + * Stops the service if it is not currently running. This function will kill + * the server immediately. To synchronize with the active control flow, use + * {@link #stop()}. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + kill(): webdriver.promise.Promise; + + /** + * Schedules a task in the current control flow to stop the server if it is + * currently running. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + stop(): webdriver.promise.Promise; + } +} + +declare namespace safari { + class Server {} + + /** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ + function findSafariExecutable(): any; + + /** + * @param {string} serverUrl The URL to connect to. + * @return {!Promise} A promise for the path to a file that Safari can + * open on start-up to trigger a new connection to the WebSocket server. + */ + function createConnectFile(serverUrl: string): any; + + /** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ + function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; + + /** @return {string} . */ + function getRandomString(): string; + + /** + * @implements {command.Executor} + */ + class CommandExecutor { + } + + /** + * Configuration options specific to the {@link Driver SafariDriver}. + */ + class Options { + /** + * Extracts the SafariDriver specific options from the given capabilities + * object. + * @param {!Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + /** + * Sets whether to force Safari to start with a clean session. Enabling this + * option will cause all global browser data to be deleted. + * @param {boolean} clean Whether to make sure the session has no cookies, + * cache entries, local storage, or databases. + * @return {!Options} A self reference. + */ + setCleanSession(clean: boolean): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Converts this options instance to a {@link Capabilities} object. + * @param {Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + + /** + * A WebDriver client for Safari. This class should never be instantiated + * directly; instead, use the {@linkplain ./builder.Builder Builder}: + * + * var driver = new Builder() + * .forBrowser('safari') + * .build(); + * + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|Capabilities)=} opt_config The configuration + * options for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow to create + * the driver under. + */ + constructor(opt_config?: Options|webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + + } } declare namespace webdriver { namespace error { - interface IErrorCode { - SUCCESS: number; + class IError extends Error { + constructor(opt_error?: string); - NO_SUCH_ELEMENT: number; - NO_SUCH_FRAME: number; - UNKNOWN_COMMAND: number; - UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. - STALE_ELEMENT_REFERENCE: number; - ELEMENT_NOT_VISIBLE: number; - INVALID_ELEMENT_STATE: number; - UNKNOWN_ERROR: number; - ELEMENT_NOT_SELECTABLE: number; - JAVASCRIPT_ERROR: number; - XPATH_LOOKUP_ERROR: number; - TIMEOUT: number; - NO_SUCH_WINDOW: number; - INVALID_COOKIE_DOMAIN: number; - UNABLE_TO_SET_COOKIE: number; - MODAL_DIALOG_OPENED: number; - UNEXPECTED_ALERT_OPEN: number; - NO_SUCH_ALERT: number; - NO_MODAL_DIALOG_OPEN: number; - SCRIPT_TIMEOUT: number; - INVALID_ELEMENT_COORDINATES: number; - IME_NOT_AVAILABLE: number; - IME_ENGINE_ACTIVATION_FAILED: number; - INVALID_SELECTOR_ERROR: number; - SESSION_NOT_CREATED: number; - MOVE_TARGET_OUT_OF_BOUNDS: number; - SQL_DATABASE_ERROR: number; - INVALID_XPATH_SELECTOR: number; - INVALID_XPATH_SELECTOR_RETURN_TYPE: number; - // The following error codes are derived straight from HTTP return codes. - METHOD_NOT_ALLOWED: number; + code(): number; } - var ErrorCode: IErrorCode; + /** + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } /** - * Error extension that includes error status codes from the WebDriver wire - * protocol: - * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes - * - * @extends {Error} + * An attempt was made to select an element that cannot be selected. */ - class Error { + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Constructors + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * @param {!bot.ErrorCode} code The error's status code. - * @param {string=} opt_message Optional error message. - * @constructor - */ - constructor(code: number, opt_message?: string); + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Static Properties + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Status strings enumerated in the W3C WebDriver working draft. - * @enum {string} - * @see http://www.w3.org/TR/webdriver/#status-codes - */ - static State: { - ELEMENT_NOT_SELECTABLE: string; - ELEMENT_NOT_VISIBLE: string; - IME_ENGINE_ACTIVATION_FAILED: string; - IME_NOT_AVAILABLE: string; - INVALID_COOKIE_DOMAIN: string; - INVALID_ELEMENT_COORDINATES: string; - INVALID_ELEMENT_STATE: string; - INVALID_SELECTOR: string; - JAVASCRIPT_ERROR: string; - MOVE_TARGET_OUT_OF_BOUNDS: string; - NO_SUCH_ALERT: string; - NO_SUCH_DOM: string; - NO_SUCH_ELEMENT: string; - NO_SUCH_FRAME: string; - NO_SUCH_WINDOW: string; - SCRIPT_TIMEOUT: string; - SESSION_NOT_CREATED: string; - STALE_ELEMENT_REFERENCE: string; - SUCCESS: string; - TIMEOUT: string; - UNABLE_TO_SET_COOKIE: string; - UNEXPECTED_ALERT_OPEN: string; - UNKNOWN_COMMAND: string; - UNKNOWN_ERROR: string; - UNSUPPORTED_OPERATION: string; - }; + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Properties + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * This error's status code. - * @type {!bot.ErrorCode} - */ - code: number; + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @type {string} */ - state: string; + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - message: string; + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - name: string; + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - stack: string; + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Flag used for duck-typing when this code is embedded in a Firefox extension. - * This is required since an Error thrown in one component and then reported - * to another will fail instanceof checks in the second component. - * @type {boolean} - */ - isAutomationError: boolean; + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Methods + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @return {string} The string representation of this error. */ - toString(): string; + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); } } @@ -776,48 +1736,96 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string, level: ILevel): void; + setLevel(type: string|Type, level: Level|string|number): void; toJSON(): { [key: string]: string }; } - interface IType { - /** Logs originating from the browser. */ - BROWSER: string; - /** Logs from a WebDriver client. */ - CLIENT: string; - /** Logs from a WebDriver implementation. */ - DRIVER: string; - /** Logs related to performance. */ - PERFORMANCE: string; - /** Logs from the remote server. */ - SERVER: string; - } - /** * Common log types. * @enum {string} */ - var Type: IType; + enum Type { + /** Logs originating from the browser. */ + BROWSER, + /** Logs from a WebDriver client. */ + CLIENT, + /** Logs from a WebDriver implementation. */ + DRIVER, + /** Logs related to performance. */ + PERFORMANCE, + /** Logs from the remote server. */ + SERVER + } /** - * Logging levels. - * @enum {{value: number, name: webdriver.logging.LevelName}} + * Defines a message level that may be used to control logging output. + * + * @final */ - interface ILevel { - value: number; - name: string; - } + class Level { + name_: string; + value_: number; + /** + * @param {string} name the level's name. + * @param {number} level the level's numeric value. + */ + constructor(name: string, level: number); - interface ILevelValues { - ALL: ILevel; - DEBUG: ILevel; - INFO: ILevel; - WARNING: ILevel; - SEVERE: ILevel; - OFF: ILevel; - } + /** @override */ + toString(): string; - var Level: ILevelValues; + /** This logger's name. */ + name(): string; + + /** The numeric log level. */ + value(): number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } /** * Converts a level name or value to a {@link webdriver.logging.Level} value. @@ -827,75 +1835,209 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string): ILevel; - function getLevel(nameOrValue: number): ILevel; + function getLevel(nameOrValue: string|number): Level; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + level: string; + message: string; + timestamp: number; + type: string; } /** * A single log entry. */ class Entry { + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: Level|string|number, message: string, opt_timestamp?:number, opt_type?:string|Type); - //region Constructors + /** @type {!webdriver.logging.Level} */ + level: Level; - /** - * @param {(!webdriver.logging.Level|string)} level The entry level. - * @param {string} message The log message. - * @param {number=} opt_timestamp The time this entry was generated, in - * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the - * current time will be used. - * @param {string=} opt_type The log type, if known. - * @constructor - */ - constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); - constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + /** @type {string} */ + message: string; - //endregion + /** @type {number} */ + timestamp: number; - //region Public Properties + /** @type {string} */ + type: string; - /** @type {!webdriver.logging.Level} */ - level: ILevel; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } - /** @type {string} */ - message: string; + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, "foo" is considered the parent of + * the "foo.bar" and an ancestor of "foo.bar.baz". + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); - /** @type {number} */ - timestamp: number; + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; - /** @type {string} */ - type: string; + /** @return {string} the name of this logger. */ + getName(): string; - //endregion + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; - //region Static Methods + /** @return {Level} the log level for this logger. */ + getLevel(): Level; - /** - * Converts a {@link goog.debug.LogRecord} into a - * {@link webdriver.logging.Entry}. - * @param {!goog.debug.LogRecord} logRecord The record to convert. - * @param {string=} opt_type The log type. - * @return {!webdriver.logging.Entry} The converted entry. - */ - static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; - //endregion + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; - //region Methods + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; - //endregion + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string|Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; } } @@ -908,15 +2050,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * @param {!Array<(T|!ManagedPromise)>} arr An array of * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is + * @return {!ManagedPromise>} A promise that is * fulfilled with an array containing the fulfilled values of the * input array, or rejected with the same reason as the first * rejected value. * @template T */ - function all(arr: Promise[]): Promise; + function all(arr: Array>): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -939,9 +2081,9 @@ declare namespace webdriver { * Creates a new control flow. The provided callback will be invoked as the * first task within the new flow, with the flow as its sole argument. Returns * a promise that resolves to the callback result. - * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * @param {function(!ControlFlow)} callback The entry point * to the newly created flow. - * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * @return {!ManagedPromise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -966,7 +2108,7 @@ declare namespace webdriver { * Creates a promise that will be resolved at a set time in the future. * @param {number} ms The amount of time, in milliseconds, to wait before * resolving the promise. - * @return {!webdriver.promise.Promise} The promise. + * @return {!ManagedPromise} The promise. */ function delayed(ms: number): Promise; @@ -974,26 +2116,25 @@ declare namespace webdriver { * Calls a function for each element in an array, and if the function returns * true adds the element to a new array. * - *

    If the return value of the filter function is a promise, this function + * If the return value of the filter function is a promise, this function * will wait for it to be fulfilled before determining whether to insert the * element into the new array. * - *

    If the filter function throws or returns a rejected promise, the promise + * If the filter function throws or returns a rejected promise, the promise * returned by this function will be rejected with the same reason. Only the * first failure will be reported; all subsequent errors will be silently * ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ( - * boolean|webdriver.promise.Promise.)} fn The function + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function * to call for each element in the array. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; - function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; /** * Creates a new deferred object. @@ -1003,8 +2144,9 @@ declare namespace webdriver { /** * Creates a promise that has been resolved with the given value. - * @param {*=} opt_value The resolved value. - * @return {!webdriver.promise.Promise} The resolved promise. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T */ function fulfilled(opt_value?: T): Promise; @@ -1013,42 +2155,44 @@ declare namespace webdriver { * new array, which is used as the fulfillment value of the promise returned * by this function. * - *

    If the return value of the mapping function is a promise, this function + * If the return value of the mapping function is a promise, this function * will wait for it to be fulfilled before inserting it into the new array. * - *

    If the mapping function throws or returns a rejected promise, the + * If the mapping function throws or returns a rejected promise, the * promise returned by this function will be rejected with the same reason. * Only the first failure will be reported; all subsequent errors will be * silently ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The * function to call for each element in the array. This function should * expect three arguments (the element, the index, and the array itself. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise - function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Array|Promise>, fn: (self: any, type: any, index: number, array: any[]) => any, opt_self?: any): Promise /** * Creates a promise that has been rejected with the given reason. * @param {*=} opt_reason The rejection reason; may be any value, but is * usually an Error or a string. - * @return {!webdriver.promise.Promise} The rejected promise. + * @return {!ManagedPromise} The rejected promise. + * @template T */ - function rejected(opt_reason?: any): Promise; + function rejected(opt_reason?: any): Promise; /** - * Wraps a function that is assumed to be a node-style callback as its final - * argument. This callback takes two arguments: an error value (which will be + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be * null if the call succeeded), and the success value as the second argument. - * If the call fails, the returned promise will be rejected, otherwise it will - * be resolved with the result. + * The callback will the resolve or reject the returned promise, based on its + * arguments. * @param {!Function} fn The function to wrap. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the * result of the provided function's callback. */ function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; @@ -1059,37 +2203,35 @@ declare namespace webdriver { * fulfilled value back into {@code next}. Likewise, if a yielded promise is * rejected, the rejection error will be passed to {@code throw}. * - *

    Example 1: the Fibonacci Sequence. - *

    
    -         * webdriver.promise.consume(function* fibonacci() {
    -         *   var n1 = 1, n2 = 1;
    -         *   for (var i = 0; i < 4; ++i) {
    -         *     var tmp = yield n1 + n2;
    -         *     n1 = n2;
    -         *     n2 = tmp;
    -         *   }
    -         *   return n1 + n2;
    -         * }).then(function(result) {
    -         *   console.log(result);  // 13
    -         * });
    -         * 
    + * __Example 1:__ the Fibonacci Sequence. * - *

    Example 2: a generator that throws. - *

    
    -         * webdriver.promise.consume(function* () {
    -         *   yield webdriver.promise.delayed(250).then(function() {
    -         *     throw Error('boom');
    -         *   });
    -         * }).thenCatch(function(e) {
    -         *   console.log(e.toString());  // Error: boom
    -         * });
    -         * 
    + * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); * * @param {!Function} generatorFn The generator function to execute. * @param {Object=} opt_self The object to use as "this" when invoking the * initial generator. * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * @return {!ManagedPromise} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -1104,10 +2246,9 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!webdriver.promise.Promise} A new promise. + * @return {!ManagedPromise} A new promise. */ - function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; - function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: T|Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; /** * Returns a promise that will be resolved with the input value in a @@ -1120,19 +2261,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * webdriver.promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * @return {!ManagedPromise} A promise for a fully resolved version * of the input value. */ function fullyResolved(value: any): Promise; /** * Changes the default flow to use when no others are active. - * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @param {!ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -1141,265 +2282,181 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. - * - * @extends {goog.debug.Error} - * @final */ - class CancellationError { - /** - * @param {string=} opt_msg The cancellation message. - * @constructor - */ - constructor(opt_msg?: string); - - name: string; - message: string; + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); } interface IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } catch (ex) {
    -             *     console.error(ex);
    -             *   }
                  *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } finally {
    -             *     cleanUp();
    -             *   }
    -             *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenFinally(cleanUp);
    -             * 
    - * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *
    
    -             *   try {
    -             *     throw Error('one');
    -             *   } finally {
    -             *     throw Error('two');  // Hides Error: one
    -             *   }
    -             *
    -             *   webdriver.promise.rejected(Error('one'))
    -             *       .thenFinally(function() {
    -             *         throw Error('two');  // Hides Error: one
    -             *       });
    -             * 
    - * - * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: () => any): Promise; + catch(errback: Function): Promise; } /** - * Thenable is a promise-like object with a {@code then} method which may be - * used to schedule callbacks on a promised value. - * - * @interface - * @template T - */ + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ class Thenable implements IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } catch (ex) {
    -             *     console.error(ex);
    -             *   }
                  *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - + catch(errback: Function): Promise; /** * Registers a listener to invoke when this promise is resolved, regardless * of whether the promise's value was successfully computed. This function * is synonymous with the {@code finally} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } finally {
    -             *     cleanUp();
    -             *   }
                  *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenFinally(cleanUp);
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } * - * Note: similar to the {@code finally} clause, if the registered + * // Asynchronous promise API: + * doAsynchronousWork().finally(cleanUp); + * + * __Note:__ similar to the {@code finally} clause, if the registered * callback returns a rejected promise or throws an error, it will silently * replace the rejection error (if any) from this promise: - *
    
    -             *   try {
    -             *     throw Error('one');
    -             *   } finally {
    -             *     throw Error('two');  // Hides Error: one
    -             *   }
                  *
    -             *   webdriver.promise.rejected(Error('one'))
    -             *       .thenFinally(function() {
    -             *         throw Error('two');  // Hides Error: one
    -             *       });
    -             * 
    + * try { + * throw Error('one'); + * } finally { + * throw Error('two'); // Hides Error: one + * } * + * promise.rejected(Error('one')) + * .finally(function() { + * throw Error('two'); // Hides Error: one + * }); * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @param {function(): (R|IThenable)} callback The function to call when + * this promise is resolved. + * @return {!ManagedPromise} A promise that will be fulfilled * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + finally(callback: Function): Promise; /** * Adds a property to a class prototype to allow runtime checks of whether - * instances of that class implement the Thenable interface. This function will - * also ensure the prototype's {@code then} function is exported from compiled - * code. - * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * instances of that class implement the Thenable interface. This function + * will also ensure the prototype's {@code then} function is exported from + * compiled code. + * @param {function(new: Thenable, ...?)} ctor The * constructor whose prototype to modify. */ static addImplementation(ctor: Function): void; - /** - * Checks if an object has been tagged for implementing the Thenable interface - * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * Checks if an object has been tagged for implementing the Thenable + * interface as defined by {@link Thenable.addImplementation}. * @param {*} object The object to test. * @return {boolean} Whether the object is an implementation of the Thenable * interface. @@ -1432,12 +2489,11 @@ declare namespace webdriver { * function((T|IThenable|Thenable)=), * function(*=))} resolver * Function that is invoked immediately to begin computation of this - * promise's value. The function should accept a pair of callback functions, - * one for fulfilling the promise and another for rejecting it. - * @param {promise.ControlFlow=} opt_flow The control flow + * promise's value. The function should accept a pair of callback + * functions, one for fulfilling the promise and another for rejecting it. + * @param {ControlFlow=} opt_flow The control flow * this instance was created under. Defaults to the currently active flow. - * @constructor - */ + */ constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); constructor(); // For angular-protractor/angular-protractor-tests.ts @@ -1450,7 +2506,7 @@ declare namespace webdriver { * {@code Error}, one will be created using the value's string * representation. */ - cancel(reason: any): void; + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; @@ -1468,23 +2524,7 @@ declare namespace webdriver { * @return A new promise which will be resolved * with the result of the invoked callback. */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. - * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: Function, opt_errback?: Function): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -1512,6 +2552,31 @@ declare namespace webdriver { */ thenCatch(errback: (error: any) => any): Promise; + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + /** * Registers a listener to invoke when this promise is resolved, regardless @@ -1552,7 +2617,7 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + thenFinally(callback: Function): Promise; //endregion } @@ -1791,107 +2856,6 @@ declare namespace webdriver { } } - namespace stacktrace { - /** - * Class representing one stack frame. - */ - class Frame { - /** - * @param {(string|undefined)} context Context object, empty in case of global - * functions or if the browser doesn't provide this information. - * @param {(string|undefined)} name Function name, empty in case of anonymous - * functions. - * @param {(string|undefined)} alias Alias of the function if available. For - * example the function name will be 'c' and the alias will be 'b' if the - * function is defined as a.b = function c() {};. - * @param {(string|undefined)} path File path or URL including line number and - * optionally column number separated by colons. - * @constructor - */ - constructor(context?: string, name?: string, alias?: string, path?: string); - - /** - * @return {string} The function name or empty string if the function is - * anonymous and the object field which it's assigned to is unknown. - */ - getName(): string; - - - /** - * @return {string} The url or empty string if it is unknown. - */ - getUrl(): string; - - - /** - * @return {number} The line number if known or -1 if it is unknown. - */ - getLine(): number; - - - /** - * @return {number} The column number if known and -1 if it is unknown. - */ - getColumn(): number; - - - /** - * @return {boolean} Whether the stack frame contains an anonymous function. - */ - isAnonymous(): boolean; - - - /** - * Converts this frame to its string representation using V8's stack trace - * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - * @return {string} The string representation of this frame. - * @override - */ - toString(): string; - } - - /** - * Stores a snapshot of the stack trace at the time this instance was created. - * The stack trace will always be adjusted to exclude this function call. - */ - class Snapshot { - /** - * @param {number=} opt_slice The number of frames to remove from the top of - * the generated stack trace. - * @constructor - */ - constructor(opt_slice?: number); - - /** - * @return {!Array.} The parsed stack trace. - */ - getStacktrace(): Frame[]; - } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - namespace until { /** * Defines a condition to @@ -1915,32 +2879,31 @@ declare namespace webdriver { /** * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as: - *
      - *
    1. A numeric index into {@code window.frames} for the currently selected - * frame. - *
    2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - *
    3. A locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - *
    + * to the designated frame. The target frame may be specified as * - *

    Upon successful resolution of this condition, the driver will be left + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + * 3. a locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + * + * Upon successful resolution of this condition, the driver will be left * focused on the new frame. * - * @param {!(number|webdriver.WebElement| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * @param {!(number|./webdriver.WebElement|By| + * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame * The frame identifier. - * @return {!until.Condition.} A new condition. + * @return {!Condition} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|By|((webdriver: WebDriver)=>WebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the * returned promise will be fulfilled with the handle for the opened alert. * - * @return {!until.Condition.} The new condition. + * @return {!Condition} The new condition. */ function alertIsPresent(): Condition; @@ -2000,13 +2963,12 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. + * {@link ./webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. + * @param {!(By|Function)} locator The locator to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator|By.Hash|Function): Condition; + function elementLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -2039,7 +3001,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -2053,7 +3015,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator|By.Hash|Function): Condition; + function elementsLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -2061,7 +3023,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -2080,7 +3042,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function titleIs(title: string): Condition; @@ -2105,18 +3067,18 @@ declare namespace webdriver { } /** - * Enumeration of the buttons used in the advanced interactions API. - * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. - * @enum {number} + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} */ - interface IButton { - LEFT: number; - MIDDLE: number; - RIGHT: number; + enum Button { + LEFT, + MIDDLE, + RIGHT, } - var Button: IButton; - /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -2124,102 +3086,86 @@ declare namespace webdriver { * * @enum {string} */ - interface IKey { - NULL: string; - CANCEL: string; // ^break - HELP: string; - BACK_SPACE: string; - TAB: string; - CLEAR: string; - RETURN: string; - ENTER: string; - SHIFT: string; - CONTROL: string; - ALT: string; - PAUSE: string; - ESCAPE: string; - SPACE: string; - PAGE_UP: string; - PAGE_DOWN: string; - END: string; - HOME: string; - ARROW_LEFT: string; - LEFT: string; - ARROW_UP: string; - UP: string; - ARROW_RIGHT: string; - RIGHT: string; - ARROW_DOWN: string; - DOWN: string; - INSERT: string; - DELETE: string; - SEMICOLON: string; - EQUALS: string; + enum Key { + NULL, + CANCEL, // ^break + HELP, + BACK_SPACE, + TAB, + CLEAR, + RETURN, + ENTER, + SHIFT, + CONTROL, + ALT, + PAUSE, + ESCAPE, + SPACE, + PAGE_UP, + PAGE_DOWN, + END, + HOME, + ARROW_LEFT, + LEFT, + ARROW_UP, + UP, + ARROW_RIGHT, + RIGHT, + ARROW_DOWN, + DOWN, + INSERT, + DELETE, + SEMICOLON, + EQUALS, - NUMPAD0: string; // number pad keys - NUMPAD1: string; - NUMPAD2: string; - NUMPAD3: string; - NUMPAD4: string; - NUMPAD5: string; - NUMPAD6: string; - NUMPAD7: string; - NUMPAD8: string; - NUMPAD9: string; - MULTIPLY: string; - ADD: string; - SEPARATOR: string; - SUBTRACT: string; - DECIMAL: string; - DIVIDE: string; + NUMPAD0, // number pad keys + NUMPAD1, + NUMPAD2, + NUMPAD3, + NUMPAD4, + NUMPAD5, + NUMPAD6, + NUMPAD7, + NUMPAD8, + NUMPAD9, + MULTIPLY, + ADD, + SEPARATOR, + SUBTRACT, + DECIMAL, + DIVIDE, - F1: string; // function keys - F2: string; - F3: string; - F4: string; - F5: string; - F6: string; - F7: string; - F8: string; - F9: string; - F10: string; - F11: string; - F12: string; + F1, // function keys + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, - COMMAND: string; // Apple command key - META: string; // alias for Windows key + COMMAND, // Apple command key + META // alias for Windows key - /** - * Simulate pressing many keys at once in a "chord". Takes a sequence of - * {@link webdriver.Key}s or strings, appends each of the values to a string, - * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns - * the resultant string. - * - * Note: when the low-level webdriver key handlers see Keys.NULL, active - * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. - * - * @param {...string} var_args The key sequence to concatenate. - * @return {string} The null-terminated key sequence. - * @see http://code.google.com/p/webdriver/issues/detail?id=79 - */ - chord: (...var_args: string[]) => string; } - var Key: IKey; - /** * Class for defining sequences of complex user interactions. Each sequence * will not be executed until {@link #perform} is called. * - *

    Example:

    
    -     *   new webdriver.ActionSequence(driver).
    -     *       keyDown(webdriver.Key.SHIFT).
    -     *       click(element1).
    -     *       click(element2).
    -     *       dragAndDrop(element3, element4).
    -     *       keyUp(webdriver.Key.SHIFT).
    -     *       perform();
    -     * 
    + * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); * */ class ActionSequence { @@ -2247,14 +3193,18 @@ declare namespace webdriver { * Moves the mouse. The location to move to may be specified in terms of the * mouse's current location, an offset relative to the top-left corner of an * element, or an element (in which case the middle of the element is used). - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, as either another WebElement or an offset in pixels. - * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. - * Defaults to (0, 0). - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in + * pixels. + * @param {{x: number, y: number}=} opt_offset If the target {@code location} + * is defined as a {@link ./webdriver.WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. */ - mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; - mouseMove(location: ILocation): ActionSequence; + mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -2262,100 +3212,101 @@ declare namespace webdriver { * sequence or another. The behavior for out-of-order events (e.g. mouseDown, * click) is undefined. * - *

    If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

    sequence.mouseMove(element).mouseDown()
    * - *

    Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseDown() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseDown(opt_elementOrButton?: number): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Releases a mouse button. Behavior is undefined for calling this function * without a previous call to {@link #mouseDown}. * - *

    If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

    sequence.mouseMove(element).mouseUp()
    * - *

    Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseUp() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseUp(opt_elementOrButton?: number): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Convenience function for performing a "drag and drop" manuever. The target * element may be moved to the location of another element, or by an offset (in * pixels). - * @param {!webdriver.WebElement} element The element to drag. - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, either as another WebElement or an offset in pixels. - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {!./webdriver.WebElement} element The element to drag. + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. */ - dragAndDrop(element: WebElement, location: WebElement): ActionSequence; - dragAndDrop(element: WebElement, location: ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement|ILocation): ActionSequence; /** * Clicks a mouse button. * - *

    If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

    sequence.mouseMove(element).click()
    * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * sequence.mouseMove(element).click() + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - click(opt_elementOrButton?: number): ActionSequence; + click(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Double-clicks a mouse button. * - *

    If an element is provided, the mouse will first be moved to the center of + * If an element is provided, the mouse will first be moved to the center of * that element. This is equivalent to: - *

    sequence.mouseMove(element).doubleClick()
    * - *

    Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).doubleClick() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - doubleClick(opt_elementOrButton?: number): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -2366,7 +3317,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: string): ActionSequence; + keyDown(key: Key): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -2376,7 +3327,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: string): ActionSequence; + keyUp(key: Key): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -2387,7 +3338,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: any[]): ActionSequence; + sendKeys(...var_args: Array): ActionSequence; //endregion } @@ -2483,7 +3434,6 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; - /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -2494,7 +3444,6 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; - /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -2504,7 +3453,6 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; - /** * Flick starting at elem and moving by x and y at specified speed. * @@ -2516,26 +3464,29 @@ declare namespace webdriver { flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; } - interface IOffset { x: number; y: number; } - interface ISpeed { xspeed: number; yspeed: number; } - /** * Represents a modal dialog such as {@code alert}, {@code confirm}, or * {@code prompt}. Provides functions to retrieve the message displayed with * the alert, accept or dismiss the alert, and set the response text (in the * case of {@code prompt}). */ - interface Alert { + class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); //region Methods @@ -2547,6 +3498,18 @@ declare namespace webdriver { */ getText(): webdriver.promise.Promise; + /** + * Sets the username and password in an alert prompting for credentials (such + * as a Basic HTTP Auth prompt). This method will implicitly + * {@linkplain #accept() submit} the dialog. + * + * @param {string} username The username to send. + * @param {string} password The password to send. + * @return {!promise.Promise} A promise that will be resolved when this + * command has completed. + */ + authenticateAs(username: string, password: string): webdriver.promise.Promise; + /** * Accepts this alert. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -2580,47 +3543,27 @@ declare namespace webdriver { * serves as a forward proxy on an Alert, allowing calls to be scheduled * directly on this instance before the underlying Alert has been fulfilled. In * other words, the following two statements are equivalent: - *

    
    +     *
          *     driver.switchTo().alert().dismiss();
          *     driver.switchTo().alert().then(function(alert) {
          *       return alert.dismiss();
          *     });
    -     * 
    * - * @param {!webdriver.WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!webdriver.promise.Thenable.} alert A thenable - * that will be fulfilled with the promised alert. - * @constructor - * @extends {webdriver.Alert} - * @implements {webdriver.promise.Thenable.} + * @implements {promise.Thenable.} * @final */ - interface AlertPromise extends Alert, webdriver.promise.IThenable { + class AlertPromise extends Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!promise.Thenable} alert A thenable + * that will be fulfilled with the promised alert. + */ + constructor(driver: WebDriver, alert: webdriver.promise.Promise); } - /** - * An error returned to indicate that there is an unhandled modal dialog on the - * current page. - * @extends {bot.Error} - */ - interface UnhandledAlertError extends webdriver.error.Error { - //region Methods - - /** - * @return {string} The text displayed with the unhandled alert. - */ - getAlertText(): string; - - /** - * @return {!webdriver.Alert} The open alert. - * @deprecated Use {@link #getAlertText}. This method will be removed in - * 2.45.0. - */ - getAlert(): Alert; - - - //endregion + /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ + class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { } /** @@ -2630,7 +3573,9 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; + EDGE: string; FIREFOX: string; + IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -2651,6 +3596,45 @@ declare namespace webdriver { noProxy?: string; } + /** + * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment + * variables listed below may be used to override a builder's configuration, + * allowing quick runtime changes. + * + * - {@code SELENIUM_BROWSER}: defines the target browser in the form + * {@code browser[:version][:platform]}. + * + * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder + * instances. This environment variable should be set to a fully qualified + * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This + * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * + * - {@code SELENIUM_SERVER_JAR}: defines the path to the + * + * standalone Selenium server jar to use. The server will be started the + * first time a WebDriver instance and be killed when the process exits. + * + * Suppose you had mytest.js that created WebDriver with + * + * var driver = new webdriver.Builder() + * .forBrowser('chrome') + * .build(); + * + * This test could be made to use Firefox on the local machine by running with + * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to + * target Google Chrome on a remote machine, you can simply set the + * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ + * node mytest.js + * + * You could also use a local copy of the standalone Selenium server: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ + * node mytest.js + */ class Builder { //region Constructors @@ -2664,15 +3648,45 @@ declare namespace webdriver { //region Methods + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + /** * Creates a new WebDriver client based on this builder's current * configuration. * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * * @return {!webdriver.WebDriver} A new WebDriver instance. * @throws {Error} If the current configuration is invalid. + * @see #buildAsync() */ build(): WebDriver; + /** + * Creates a new WebDriver client based on this builder's current + * configuration. This method returns a promise that will not be fulfilled + * until the new browser session has been fully initialized. + * + * __Note:__ this method is purely a convenience wrapper around + * {@link #build()}. + * + * @return {!promise.Promise} A promise that will be + * fulfilled with the newly created WebDriver instance once the browser + * has been fully initialized. + * @see #build() + */ + buildAsync(): webdriver.promise.Promise; + /** * Configures the target browser for clients created by this instance. * Any calls to {@link #withCapabilities} after this function will @@ -2705,6 +3719,12 @@ declare namespace webdriver { */ getServerUrl(): string; + /** + * @return {?string} The URL of the proxy server to use for the WebDriver's + * HTTP connections, or `null` if not set. + */ + getWebDriverProxy(): string; + /** * Sets the default action to take with an unexpected alert before returning * an error. @@ -2735,6 +3755,17 @@ declare namespace webdriver { */ setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + /** + * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser + * for drivers created by this builder. Any proxy settings defined on the + * given options will take precedence over those set through + * {@link #setProxy}. + * + * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. + * @return {!Builder} A self reference. + */ + setEdgeOptions(options: edge.Options): Builder; + /** * Sets whether native events should be used. * @param {boolean} enabled Whether to enable native events. @@ -2753,6 +3784,16 @@ declare namespace webdriver { */ setFirefoxOptions(options: firefox.Options): Builder; + /** + * Set Internet Explorer specific {@linkplain ie.Options options} for drivers + * created by this builder. Any proxy settings defined on the given options + * will take precedence over those set through {@link #setProxy}. + * + * @param {!ie.Options} options The IEDriver options to use. + * @return {!Builder} A self reference. + */ + setIeOptions(options: ie.Options): Builder; + /** * Sets the logging preferences for the created session. Preferences may be * changed by repeated calls, or by calling {@link #withCapabilities}. @@ -2760,17 +3801,37 @@ declare namespace webdriver { * desired logging preferences. * @return {!Builder} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; - setLoggingPrefs(prefs: { [key: string]: string }): Builder; + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Builder; + + /** + * Sets Opera specific {@linkplain opera.Options options} for drivers created + * by this builder. Any logging or proxy settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs} and + * {@link #setProxy}, respectively. + * + * @param {!opera.Options} options The OperaDriver options to use. + * @return {!Builder} A self reference. + */ + setOperaOptions(options: opera.Options): Builder; /** * Sets the proxy configuration to use for WebDriver clients created by this * builder. Any calls to {@link #withCapabilities} after this function will * overwrite these settings. - * @param {!webdriver.ProxyConfig} config The configuration to use. + * @param {!capabilities.ProxyConfig} config The configuration to use. * @return {!Builder} A self reference. */ - setProxy(config: ProxyConfig): Builder; + setProxy(config: webdriver.ProxyConfig): Builder; + + /** + * Sets Safari specific {@linkplain safari.Options options} for drivers + * created by this builder. Any logging settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs}. + * + * @param {!safari.Options} options The Safari options to use. + * @return {!Builder} A self reference. + */ + setSafari(options: safari.Options): Builder; /** * Sets how elements should be scrolled into view for interaction. @@ -2793,6 +3854,16 @@ declare namespace webdriver { */ usingServer(url: string): Builder; + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + /** * Sets the desired capabilities when requesting a new session. This will * overwrite any previously set capabilities. @@ -2800,12 +3871,149 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Capabilities): Builder; - withCapabilities(capabilities: any): Builder; + withCapabilities(capabilities: Object|Capabilities): Builder; //endregion } + /** + * Describes a mechanism for locating an element on the page. + * @final + */ + class By { + + /** + * @param {string} using the name of the location strategy to use. + * @param {string} value the value to search for. + */ + constructor(using: string, value: string); + + /** + * Locates elements that have a specific class name. + * + * @param {string} name The class name to search for. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + static className(name: string): By; + + /** + * Locates elements using a CSS selector. + * + * @param {string} selector The CSS selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + static css(selector: string): By; + + /** + * Locates eleemnts by the ID attribute. This locator uses the CSS selector + * `*[id="$ID"]`, _not_ `document.getElementById`. + * + * @param {string} id The ID to search for. + * @return {!By} The new locator. + */ + static id(id: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} matches the given + * string. + * + * @param {string} text The link text to search for. + * @return {!By} The new locator. + */ + static linkText(text: string): By; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!./webdriver.WebDriver): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string|Function, ...var_args: Array): (webdriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose `name` attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!By} The new locator. + */ + static name(name: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} contains the given + * substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!By} The new locator. + */ + static partialLinkText(text: string): By; + + /** + * Locates elements with a given tag name. + * + * @param {string} name The tag name to search for. + * @return {!By} The new locator. + * @deprecated Use {@link By.css() By.css(tagName)} instead. + */ + static tagName(name: string): By; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector `//div`, WebDriver will search from the document root + * regardless of whether the locator was used with a WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + static xpath(xpath: string): By; + + /** @override */ + toString(): string; + } + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type ByHash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + /** * Common webdriver capability keys. * @enum {string} @@ -2876,7 +4084,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -2910,8 +4118,7 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities); - constructor(opt_other?: any); + constructor(opt_other?: Capabilities|Object); //endregion @@ -2927,8 +4134,7 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities): Capabilities; - merge(other: any): Capabilities; + merge(other: Capabilities|Object): Capabilities; /** * @param {string} key The capability to set. @@ -2946,9 +4152,7 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; - setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; - + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; /** * Sets the proxy configuration for this instance. @@ -3010,6 +4214,11 @@ declare namespace webdriver { */ static chrome(): Capabilities; + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + /** * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. */ @@ -3183,6 +4392,8 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -3241,19 +4452,47 @@ declare namespace webdriver { } /** - * Handles the execution of {@code webdriver.Command} objects. + * Handles the execution of WebDriver {@link Command commands}. + * @interface */ - interface CommandExecutor { - /** - * Executes the given {@code command}. If there is an error executing the - * command, the provided callback will be invoked with the offending error. - * Otherwise, the callback will be invoked with a null Error and non-null - * {@link bot.response.ResponseObject} object. - * @param {!webdriver.Command} command The command to execute. - * @param {function(Error, !bot.response.ResponseObject=)} callback the function - * to invoke when the command response is ready. - */ - execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + class Executor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * response object. + * + * @param {!Command} command The command to execute. + * @return {!promise.Promise} A promise that will be fulfilled with + * the command result. + */ + execute(command: Command): webdriver.promise.Promise + } + + /** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ + class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: webdriver.promise.Promise); + } + + /** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ + class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); } /** @@ -3283,39 +4522,42 @@ declare namespace webdriver { /** * Returns a mutable list of listeners for a specific type of event. * @param {string} type The type of event to retrieve the listeners for. - * @return {!Array.<{fn: !Function, oneshot: boolean, - * scope: (Object|undefined)}>} The registered listeners for - * the given event type. + * @return {!Set} The registered listeners for the given event + * type. */ - listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + listeners(type: string): any; /** * Registers a listener. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. - * @param {Object=} opt_scope The object in whose scope to invoke the listener. - * @return {!webdriver.EventEmitter} A self reference. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private */ - addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + addListener(type: string, fn: Function, opt_scope?:any, opt_oneshot?: boolean): EventEmitter; + /** * Registers a one-time listener which will be called only the first time an * event is emitted, after which it will be removed. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; + once(type: string, fn: any, opt_scope?: any): EventEmitter; /** * An alias for {@code #addListener()}. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + on(type: string, fn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -3340,14 +4582,20 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - interface WebDriverNavigation { + class Navigation { //region Constructors /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * webdriver.navigate() + * + * @see WebDriver#navigate() */ - new (driver: WebDriver): WebDriverNavigation; + constructor(driver: WebDriver); //endregion @@ -3397,14 +4645,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - interface WebDriverOptions { + class Options { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: webdriver.WebDriver): WebDriverOptions; + constructor(driver: webdriver.WebDriver); //endregion @@ -3417,13 +4665,13 @@ declare namespace webdriver { * @param {string=} opt_path The cookie path. * @param {string=} opt_domain The cookie domain. * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as - * a number, should be in milliseconds since midnight, January 1, 1970 UTC. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * cookie has been added to the page. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number|Date): webdriver.promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -3467,19 +4715,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): WebDriverLogs; + logs(): webdriver.Logs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): WebDriverTimeouts; + timeouts(): webdriver.Timeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): WebDriverWindow; + window(): webdriver.Window; //endregion } @@ -3487,14 +4735,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - interface WebDriverTimeouts { + class Timeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTimeouts; + constructor(driver: webdriver.WebDriver); //endregion @@ -3549,7 +4797,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - interface WebDriverWindow { + class Window { //region Constructors @@ -3557,7 +4805,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverWindow; + constructor(driver: webdriver.WebDriver); //endregion @@ -3612,7 +4860,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - interface WebDriverLogs { + class Logs { //region Constructors @@ -3620,7 +4868,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverLogs; + constructor(driver: webdriver.WebDriver); //endregion @@ -3640,7 +4888,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: string): webdriver.promise.Promise; + get(type: webdriver.logging.Type): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -3655,7 +4903,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - interface WebDriverTargetLocator { + class TargetLocator { //region Constructors @@ -3663,7 +4911,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTargetLocator; + constructor(driver: webdriver.WebDriver); //endregion @@ -3687,44 +4935,47 @@ declare namespace webdriver { /** * Schedules a command to switch the focus of all future commands to another - * frame on the page. - *

    - * If the frame is specified by a number, the command will switch to the frame - * by its (zero-based) index into the {@code window.frames} collection. - *

    - * If the frame is specified by a string, the command will select the frame by - * its name or ID. To select sub-frames, simply separate the frame names/IDs by - * dots. As an example, "main.child" will select the frame with the name "main" - * and then its child "child". - *

    - * If the specified frame can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. - * @param {string|number} nameOrIndex The frame locator. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified frame. + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. */ - frame(nameOrIndex: string): webdriver.promise.Promise; - frame(nameOrIndex: number): webdriver.promise.Promise; + frame(nameOrIndex: number|WebElement): webdriver.promise.Promise; /** * Schedules a command to switch the focus of all future commands to another * window. Windows may be specified by their {@code window.name} attribute or - * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). - *

    - * If the specificed window can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * * @param {string} nameOrHandle The name or window handle of the window to * switch focus to. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified window. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. */ window(nameOrHandle: string): webdriver.promise.Promise; /** - * Schedules a command to change focus to the active alert dialog. This command - * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal - * dialog is not currently open. - * @return {!webdriver.Alert} The open alert. + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. */ alert(): AlertPromise; @@ -3789,27 +5040,14 @@ declare namespace webdriver { //region Constructors /** - * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * @param {!(Session|promise.Promise)} session Either a * known session or a promise that will be resolved to a session. - * @param {!webdriver.CommandExecutor} executor The executor to use when - * sending commands to the browser. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. - * @constructor */ - constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - - //endregion - - //region Static Properties - - static Navigation: WebDriverNavigation; - static Options: WebDriverOptions; - static Timeouts: WebDriverTimeouts; - static Window: WebDriverWindow; - static Logs: WebDriverLogs; - static TargetLocator: WebDriverTargetLocator; + constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); //endregion @@ -3817,29 +5055,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!webdriver.CommandExecutor} executor Command executor to use when - * querying for session details. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. * @param {string} sessionId ID of the session to attach to. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver - * commands should execute under. Defaults to the - * {@link webdriver.promise.controlFlow() currently active} control flow. - * @return {!webdriver.WebDriver} A new client for the specified session. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. */ - static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. - * @param {!webdriver.CommandExecutor} executor The executor to create the new - * session with. - * @param {!webdriver.Capabilities} desiredCapabilities The desired + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * @param {promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. - * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * Defaults to the {@link promise.controlFlow() currently active} * control flow. - * @return {!webdriver.WebDriver} The driver for the newly created session. + * @return {!WebDriver} The driver for the newly created session. */ - static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -3852,20 +5090,22 @@ declare namespace webdriver { controlFlow(): webdriver.promise.ControlFlow; /** - * Schedules a {@code webdriver.Command} to be executed by this driver's - * {@code webdriver.CommandExecutor}. - * @param {!webdriver.Command} command The command to schedule. + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. * @param {string} description A description of the command for debugging. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the command result. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T */ schedule(command: Command, description: string): webdriver.promise.Promise; /** - * Sets the {@linkplain webdriver.FileDetector file detector} that should be + * Sets the {@linkplain input.FileDetector file detector} that should be * used with this instance. - * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + * @param {input.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -3895,23 +5135,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * scheduled for execution until {@link actions.ActionSequence#perform} is * called. Example: - *

    
    -         *   driver.actions().
    -         *       mouseDown(element1).
    -         *       mouseMove(element2).
    -         *       mouseUp().
    -         *       perform();
    -         * 
    - * @return {!webdriver.ActionSequence} A new action sequence for this instance. + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. */ actions(): ActionSequence; /** * Creates a new touch sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.TouchSequence#perform} is + * scheduled for execution until {@link actions.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -3919,7 +5159,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + * @return {!actions.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -3961,8 +5201,7 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -4179,38 +5418,27 @@ declare namespace webdriver { * var e1 = driver.findElement(By.id('foo')); * var e2 = driver.findElement({id:'foo'}); * - * You may also provide a custom locator function, which takes as input - * this WebDriver instance and returns a {@link webdriver.WebElement}, or a - * promise that will resolve to a WebElement. For example, to find the first - * visible link on a page, you could write: + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: * * var link = driver.findElement(firstVisibleLink); * * function firstVisibleLink(driver) { * var links = driver.findElements(By.tagName('a')); - * return webdriver.promise.filter(links, function(link) { - * return links.isDisplayed(); - * }).then(function(visibleLinks) { - * return visibleLinks[0]; + * return promise.filter(links, function(link) { + * return link.isDisplayed(); * }); * } * - * When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The - * locator to use. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -4219,35 +5447,36 @@ declare namespace webdriver { * document the driver is currently focused on. Otherwise, the function will * test if at least one element can be found with the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element| - * Function)} locatorOrElement The locator to use, or the actual - * DOM element to be located by the server. - * @return {!webdriver.promise.Promise.} A promise that will resolve + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); */ - isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; + isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to * return a screenshot of the following, in order of preference: - *
      - *
    1. Entire page - *
    2. Current window - *
    3. Visible portion of the current frame - *
    4. The screenshot of the entire display containing the browser - *
    * - * @return {!webdriver.promise.Promise.} A promise that will be + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; @@ -4256,45 +5485,25 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): WebDriverOptions; + manage(): webdriver.Options; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): WebDriverNavigation; + navigate(): Navigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): WebDriverTargetLocator; + switchTo(): webdriver.TargetLocator; //endregion } interface IWebElementId { - ELEMENT: string; - } - - /** - * Defines an object that can be asynchronously serialized to its WebDriver - * wire representation. - * - * @constructor - * @template T - */ - interface Serializable { - /** - * Returns either this instance's serialized represention, if immediately - * available, or a promise for its serialized representation. This function is - * conceptually equivalent to objects that have a {@code toJSON()} property, - * except the serialize() result may be a promise or an object containing a - * promise (which are not directly JSON friendly). - * - * @return {!(T|IThenable.)} This instance's serialized wire format. - */ - serialize(): T|webdriver.promise.IThenable; + [ELEMENT:string]: string; } /** @@ -4554,7 +5763,7 @@ declare namespace webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4565,7 +5774,7 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4576,10 +5785,9 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; } - /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -4600,7 +5808,6 @@ declare namespace webdriver { serialize(): T|webdriver.promise.IThenable; } - /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@link webdriver.WebDriver} instance, or by searching @@ -4626,35 +5833,59 @@ declare namespace webdriver { */ class WebElement implements Serializable { /** - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!(webdriver.promise.Promise.| - * webdriver.WebElement.Id)} id The server-assigned opaque ID for the - * underlying DOM element. - * @constructor + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. */ - constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); /** - * Wire protocol definition of a WebElement ID. - * @typedef {{ELEMENT: string}} - * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. */ - static Id: IWebElementId; + static buildId(id: string, opt_noLegacy?: boolean): Object; /** - * The property key used in the wire protocol to indicate that a JSON object - * contains the ID of a WebElement. - * @type {string} - * @const + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. */ - static ELEMENT_KEY: string; + static extractId(obj: IWebElementId): string; + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; /** * @return {!webdriver.WebDriver} The parent driver for this instance. */ - getDriver(): WebDriver; + getDriver(): webdriver.WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): webdriver.promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; /** * Schedule a command to find a descendant of this element. If the element @@ -4688,35 +5919,40 @@ declare namespace webdriver { * }); * } * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this * element that matches the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.} A promise that will be + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that * match the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the elements. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -4727,7 +5963,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * instance. + * promsieinstance. * * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is * processed in the keysequence, that key state is toggled until one of the @@ -4799,7 +6035,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!webdriver.promise.Promise.} A promise that will be + * @return {!promise.Promise} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -4885,10 +6121,10 @@ declare namespace webdriver { submit(): webdriver.promise.Promise; /** - * Schedules a command to clear the {@code value} of this element. This command - * has no effect if the underlying DOM element is neither a text INPUT element + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise.} A promise that will be resolved + * @return {!promise.Promise} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -4900,6 +6136,18 @@ declare namespace webdriver { */ isDisplayed(): webdriver.promise.Promise; + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; + /** * Schedules a command to retrieve the outer HTML of this element. * @return {!webdriver.promise.Promise.} A promise that will be @@ -4907,25 +6155,6 @@ declare namespace webdriver { */ getOuterHtml(): webdriver.promise.Promise; - /** - * @return {!webdriver.promise.Promise.} A promise - * that resolves to this element's JSON representation as defined by the - * WebDriver wire protocol. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol - */ - getId(): webdriver.promise.Promise; - - /** - * Returns the raw ID string ID for this element. - * @return {!webdriver.promise.Promise} A promise that resolves to this - * element's raw ID as a string value. - * @package - */ - getRawId(): webdriver.promise.Promise; - - /** @override */ - serialize(): webdriver.promise.Promise; - /** * Schedules a command to retrieve the inner HTML of this element. * @return {!webdriver.promise.Promise} A promise that will be resolved with the @@ -4933,14 +6162,8 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** - * Compares to WebElements for equality. - * @param {!webdriver.WebElement} a A WebElement. - * @param {!webdriver.WebElement} b A WebElement. - * @return {!webdriver.promise.Promise} A promise that will be resolved to - * whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + /** @override */ + serialize(): webdriver.promise.Promise; } /** @@ -4966,6 +6189,14 @@ declare namespace webdriver { * @final */ class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); + /** * Cancels the computation of this promise's value, rejecting the promise in the * process. This method is a no-op if the promise has alreayd been resolved. @@ -5075,191 +6306,31 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; - } - namespace By { /** - * Locates elements that have a specific class name. The returned locator - * is equivalent to searching for elements with the CSS selector ".clazz". + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: * - * @param {string} className The class name to search for. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes - * @see http://www.w3.org/TR/CSS2/selector.html#class-html - */ - function className(value: string): Locator; - - /** - * Locates elements using a CSS selector. For browsers that do not support - * CSS selectors, WebDriver implementations may return an - * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An - * implementation may, however, emulate the CSS selector API. + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {string} selector The CSS selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - function css(value: string): Locator; - - /** - * Locates an element by its ID. + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); * - * @param {string} id The ID to search for. - * @return {!webdriver.Locator} The new locator. + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R */ - function id(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} matches the given string. - * - * @param {string} text The link text to search for. - * @return {!webdriver.Locator} The new locator. - */ - function linkText(value: string): Locator; - - /** - * Locates an elements by evaluating a - * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. - * The result of this expression must be an element or list of elements. - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, - * JavaScript-based locator function. - */ - function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose {@code name} attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!webdriver.Locator} The new locator. - */ - function name(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} contains the given substring. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - */ - function partialLinkText(value: string): Locator; - - /** - * Locates elements with a given tag name. The returned locator is - * equivalent to using the - * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) - * DOM function. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html - */ - function tagName(value: string): Locator; - - /** - * Locates elements matching a XPath selector. Care should be taken when - * using an XPath selector with a {@link webdriver.WebElement} as WebDriver - * will respect the context in the specified in the selector. For example, - * given the selector {@code "//div"}, WebDriver will search from the - * document root regardless of whether the locator was used with a - * WebElement. - * - * @param {string} xpath The XPath selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - function xpath(value: string): Locator; - - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type Hash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - } - - /** - * An element locator. - */ - class Locator { - /** - * An element locator. - * @param {string} using The type of strategy to use for this locator. - * @param {string} value The search target of this locator. - * @constructor - */ - constructor(using: string, value: string); - - - /** - * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. - * @type {!Object.} - * @const - */ - static Strategy: { - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - js: typeof webdriver.By.js; - linkText: typeof webdriver.By.linkText; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - }; - - /** - * Verifies that a {@code value} is a valid locator to use for searching for - * elements on the page. - * - * @param {*} value The value to check is a valid locator. - * @return {!(webdriver.Locator|Function)} A valid locator object or function. - * @throws {TypeError} If the given value is an invalid locator. - */ - static checkLocator(value: any): Locator | Function; - - /** - * The search strategy to use when searching for an element. - * @type {string} - */ - using: string; - - /** - * The search target for this locator. - * @type {string} - */ - value: string; - - /** @return {string} String representation of this locator. */ - toString(): string; + catch(errback: Function): webdriver.promise.Promise; } /** @@ -5275,8 +6346,7 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities); - constructor(id: string, capabilities: any); + constructor(id: string, capabilities: Capabilities|Object); //endregion @@ -5290,7 +6360,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): Capabilities; + getCapabilities(): webdriver.Capabilities; /** * Retrieves the value of a specific capability. @@ -5376,10 +6446,6 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } -declare module 'selenium-webdriver/firefox' { - export = firefox; -} - declare module 'selenium-webdriver/executors' { export = executors; } From 6f536ea9c1958814737f437d0803380c14ed4389 Mon Sep 17 00:00:00 2001 From: IOAyman Date: Wed, 14 Sep 2016 14:52:37 +0100 Subject: [PATCH 081/212] Updated Validator API to v5.7.0 --- validator/index.d.ts | 59 +++++++++++++++++++++--------------- validator/validator-tests.ts | 33 ++++++++++++-------- 2 files changed, 54 insertions(+), 38 deletions(-) diff --git a/validator/index.d.ts b/validator/index.d.ts index 09f302c27d..1ec4711828 100644 --- a/validator/index.d.ts +++ b/validator/index.d.ts @@ -1,14 +1,14 @@ -// Type definitions for validator.js v4.5.1 +// Type definitions for validator.js v5.7.0 // Project: https://github.com/chriso/validator.js -// Definitions by: tgfjt , Ilya Mochalov +// Definitions by: tgfjt , Ilya Mochalov , Ayman Nedjmeddine , Louy Alakkad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace ValidatorJS { interface ValidatorStatic { - /* ************ - * Validators * - **************/ + // ************** + // * Validators * + // ************** // check if the string contains the seed. contains(str: string, elem: any): boolean; @@ -17,7 +17,7 @@ declare namespace ValidatorJS { equals(str: string, comparison: any): boolean; // check if the string is a date that's after the specified date (defaults to now). - isAfter(str: string, date?: Date): boolean; + isAfter(str: string, date?: string): boolean; // check if the string contains only letters (a-zA-Z). isAlpha(str: string): boolean; @@ -32,7 +32,7 @@ declare namespace ValidatorJS { isBase64(str: string): boolean; // check if the string is a date that's before the specified date. - isBefore(str: string, date?: Date): boolean; + isBefore(str: string, date?: string): boolean; // check if a string is a boolean. isBoolean(str: string): boolean; @@ -47,6 +47,9 @@ declare namespace ValidatorJS { // check if the string is a valid currency amount. isCurrency(str: string, options?: IsCurrencyOptions): boolean; + // check if the string is a data uri format (https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs) + isDataURI(str: string): boolean; + // check if the string is a date. isDate(str: string): boolean; @@ -110,8 +113,14 @@ declare namespace ValidatorJS { // check if the string is a MAC address. isMACAddress(str: string): boolean; - // check if the string is a mobile phone number, (locale is one of ['zh-CN', 'zh-TW', 'en-ZA', 'en-AU', 'en-HK', - // 'pt-PT', 'fr-FR', 'el-GR', 'en-GB', 'en-US', 'en-ZM', 'ru-RU', 'nb-NO', 'nn-NO', 'vi-VN', 'en-NZ', 'en-IN']). + // check if the string is a MD5 hash. + isMD5(str: string): boolean; + + // check if the string is a mobile phone number, (locale is one of + // ['ar-DZ', 'ar-SA', 'ar-SY', 'cs-CZ', 'de-DE', 'da-DK', 'el-GR', 'en-AU', 'en-GB', 'en-HK', + // 'en-IN', 'en-NZ', 'en-US', 'en-CA', 'en-ZA', 'en-ZM', 'es-ES', 'fi-FI', 'fr-FR', 'hu-HU', + // 'it-IT', 'ja-JP', 'ms-MY', 'nb-NO', 'nn-NO', 'pl-PL', 'pt-PT', 'ru-RU', 'sr-RS', 'tr-TR', + // 'vi-VN', 'zh-CN', 'zh-TW']). isMobilePhone(str: string, locale: string): boolean; // check if the string is a valid hex-encoded representation of a MongoDB ObjectId @@ -133,8 +142,8 @@ declare namespace ValidatorJS { // check if the string is an URL. isURL(str: string, options?: IsURLOptions): boolean; - // check if the string is a UUID (version 3, 4 or 5). - isUUID(str: string, version?: number): boolean; + // check if the string is a UUID. Must be one of ['3', '4', '5', 'all'], default is all. + isUUID(str: string, version?: string|number): boolean; // check if the string is uppercase. isUppercase(str: string): boolean; @@ -146,11 +155,11 @@ declare namespace ValidatorJS { isWhitelisted(str: string, chars: string|string[]): boolean; // check if string matches the pattern. - matches(str: string, pattern: any, modifiers?: string): boolean; + matches(str: string, pattern: RegExp|string, modifiers?: string): boolean; - /************** - * Sanitizers * - **************/ + // ************** + // * Sanitizers * + // ************** // remove characters that appear in the blacklist. The characters are used in a RegExp and so you will need // to escape some chars, e.g. blacklist(input, '\\[\\]'). @@ -159,6 +168,9 @@ declare namespace ValidatorJS { // replace <, >, &, ', " and / with HTML entities. escape(input: string): string; + // replaces HTML encoded entities with <, >, &, ', " and /. + unescape(input: string): string; + // trim characters from the left-side of the input. ltrim(input: any, chars?: string): string; @@ -185,9 +197,6 @@ declare namespace ValidatorJS { // convert the input to an integer, or NaN if the input is not an integer. toInt(input: any, radix?: number): number; // number or NaN - // convert the input to a string. - toString(input: any): string; - // trim characters (whitespace by default) from both sides of the input. trim(input: any, chars?: string): string; @@ -195,9 +204,9 @@ declare namespace ValidatorJS { // need to escape some chars, e.g. whitelist(input, '\\[\\]'). whitelist(input: string, chars: string): string; - /************** - * Extensions * - **************/ + // ************** + // * Extensions * + // ************** // add your own validators. // Note: that the first argument will be automatically coerced to a string. @@ -263,10 +272,11 @@ declare namespace ValidatorJS { protocols?: string[]; require_tld?: boolean; require_protocol?: boolean; + require_host: boolean; require_valid_protocol?: boolean; allow_underscores?: boolean; - host_whitelist?: boolean; - host_blacklist?: boolean; + host_whitelist?: (string|RegExp)[]; + host_blacklist?: (string|RegExp)[]; allow_trailing_dot?: boolean; allow_protocol_relative_urls?: boolean; } @@ -280,8 +290,7 @@ declare namespace ValidatorJS { } declare module "validator" { - let validator: ValidatorJS.ValidatorStatic; - namespace validator {} + const validator: ValidatorJS.ValidatorStatic; export = validator; } diff --git a/validator/validator-tests.ts b/validator/validator-tests.ts index 191502de11..fca8c87f7e 100644 --- a/validator/validator-tests.ts +++ b/validator/validator-tests.ts @@ -1,10 +1,12 @@ +/// + import * as validator from 'validator'; let any: any; -/************** - * Validators * - **************/ +// ************** +// * Validators * +// ************** { let result: boolean; @@ -14,7 +16,7 @@ let any: any; result = validator.equals('sample', 'sample'); result = validator.isAfter('sample'); - result = validator.isAfter('sample', new Date()); + result = validator.isAfter('sample', new Date().toString()); result = validator.isAlpha('sample'); @@ -25,7 +27,7 @@ let any: any; result = validator.isBase64('sample'); result = validator.isBefore('sample'); - result = validator.isBefore('sample', new Date()); + result = validator.isBefore('sample', new Date().toString()); result = validator.isBoolean('sample'); @@ -40,6 +42,8 @@ let any: any; result = validator.isCurrency('sample'); result = validator.isCurrency('sample', isCurrencyOptions); + result = validator.isDataURI('sample'); + result = validator.isDate('sample'); result = validator.isDecimal('sample'); @@ -93,6 +97,8 @@ let any: any; result = validator.isMACAddress('sample'); + result = validator.isMD5('sample'); + result = validator.isMobilePhone('sample', 'en-US'); result = validator.isMongoId('sample'); @@ -111,6 +117,7 @@ let any: any; result = validator.isUUID('sample'); result = validator.isUUID('sample', 5); + result = validator.isUUID('sample', 'all'); result = validator.isUppercase('sample'); @@ -123,9 +130,9 @@ let any: any; result = validator.matches('foobar', 'foo', 'i'); } -/************** - * Sanitizers * - **************/ +// ************** +// * Sanitizers * +// ************** { let result: string; @@ -134,6 +141,8 @@ let any: any; result = validator.escape('sample'); + result = validator.unescape('sample'); + result = validator.ltrim('sample'); result = validator.ltrim('sample', ' '); @@ -173,16 +182,14 @@ let any: any; { let result: string; - result = validator.toString(any); - result = validator.trim('sample'); result = validator.trim('sample', ' '); result = validator.whitelist('sample', 'abc'); } -/************** - * Extensions * - **************/ +// ************** +// * Extensions * +// ************** validator.extend<(str: string, options: {}) => boolean>('isTest', (str: any, options: {}) => !str); From ab5876b6df73ae917772efcc161efe635d019b51 Mon Sep 17 00:00:00 2001 From: rvassar Date: Wed, 14 Sep 2016 09:17:23 -0700 Subject: [PATCH 082/212] Updated the Attribution class with constructor and methods. --- openlayers/openlayers.d.ts | 62 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/openlayers/openlayers.d.ts b/openlayers/openlayers.d.ts index 7cc216f1c2..346a9edef6 100644 --- a/openlayers/openlayers.d.ts +++ b/openlayers/openlayers.d.ts @@ -88,6 +88,34 @@ declare namespace olx { target?: Element; } + interface AttributionControlOptions { + /*** CSS class name. Default is ol-attribution.*/ + className?: string; + /*** Target.*/ + target?: Element; + /** + * Specify if attributions can be collapsed. If you use an OSM source, + * should be set to false — see OSM Copyright — Default is true. + */ + collapsible?: boolean; + /*** Specify if attributions should be collapsed at startup. Default is true.*/ + collapsed?: boolean; + /*** Text label to use for the button tip. Default is "Attributions".*/ + tipLabel?: Array | ol.Collection; + /** + * Text label to use for the collapsed attributions button. Default is i. + * Instead of text, also a Node (e.g. a span element) can be used. + */ + label?: string | Node; + /** + * Text label to use for the expanded attributions button. Default is ». + * Instead of text, also a Node (e.g. a span element) can be used. + */ + collapseLabel?: string | Node; + /*** Function called when the control should be re-rendered. This is called in a requestAnimationFrame callback.*/ + render?: Function; + } + interface AttributionOptions { /** HTML markup for this attribution. */ @@ -2841,7 +2869,41 @@ declare namespace ol { } + /** + * Control to show all the attributions associated with the layer sources in the map. + * This control is one of the default controls included in maps. By default it will show in the bottom right portion of the map, + * but this can be changed by using a css selector for .ol-attribution. + */ class Attribution extends Control { + constructor(opt_options?: olx.AttributionControlOptions); + /** + * Update the attribution element. + * @param mapEvent + */ + render(mapEvent: ol.MapEvent): void; + + /** + * Return true when the attribution is currently collapsed or false otherwise. + */ + getCollapsed(): boolean; + + /** + * Return true if the attribution is collapsible, false otherwise. + */ + getCollapsible(): boolean; + + /** + * Collapse or expand the attribution according to the passed parameter. Will not do anything if the attribution isn't + * collapsible or if the current collapsed state is already the one requested. + * @param collapsed + */ + setCollapsed(collapsed: boolean): void; + + /** + * Set whether the attribution should be collapsible. + * @param collapsible + */ + setCollapsible(collapsible: boolean): void; } class FullScreen extends Control { From 47588ba8f9a2ceb05acef2ec2c69263cf057405d Mon Sep 17 00:00:00 2001 From: Igor Oleinikov Date: Wed, 14 Sep 2016 11:27:33 -0700 Subject: [PATCH 083/212] [knockout] Introduce specialized signatures for subscribe method, specifically common "change" and "beforeChange" Add subscribe for "arrayChange" event for observable array (fixes #11203) Improve KnockoutArrayChange status typing. --- knockout/knockout.d.ts | 11 ++++++++-- knockout/knockoutamd-tests.ts | 2 +- knockout/tests/knockout-tests.ts | 35 ++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/knockout/knockout.d.ts b/knockout/knockout.d.ts index 6321cff0a5..f0e9fe023f 100644 --- a/knockout/knockout.d.ts +++ b/knockout/knockout.d.ts @@ -61,8 +61,10 @@ interface KnockoutSubscription { } interface KnockoutSubscribable extends KnockoutSubscribableFunctions { - subscribe(callback: (newValue: T) => void, target?: any, event?: string): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T) => void, target?: any, event?: "change"): KnockoutSubscription; subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutSubscribable; getSubscriptionsCount(): number; } @@ -91,6 +93,11 @@ interface KnockoutObservableArrayStatic { } interface KnockoutObservableArray extends KnockoutObservable, KnockoutObservableArrayFunctions { + subscribe(callback: (newValue: KnockoutArrayChange[]) => void, target: any, event: "arrayChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target: any, event: "beforeChange"): KnockoutSubscription; + subscribe(callback: (newValue: T[]) => void, target?: any, event?: "change"): KnockoutSubscription; + subscribe(callback: (newValue: TEvent) => void, target: any, event: string): KnockoutSubscription; + extend(requestedExtenders: { [key: string]: any; }): KnockoutObservableArray; } @@ -325,7 +332,7 @@ interface KnockoutUtils { } interface KnockoutArrayChange { - status: string; + status: "added" | "deleted"; value: T; index: number; moved?: number; diff --git a/knockout/knockoutamd-tests.ts b/knockout/knockoutamd-tests.ts index c874c6208b..9ee6658335 100644 --- a/knockout/knockoutamd-tests.ts +++ b/knockout/knockoutamd-tests.ts @@ -1,6 +1,6 @@ /// -import ko = require("knockout"); +import ko = require("knockout"); var myArray = ko.observableArray([1, 2, 3]); diff --git a/knockout/tests/knockout-tests.ts b/knockout/tests/knockout-tests.ts index 8da6c12950..122617b180 100644 --- a/knockout/tests/knockout-tests.ts +++ b/knockout/tests/knockout-tests.ts @@ -680,3 +680,38 @@ function test_tasks() { setTimeout(callback, 0); }; } + +function observableEventsTests() { + var observable = ko.observable(1); + observable.subscribe(value => { + var num: number = value; + }); + observable.subscribe(value => { + var num: number = value; + }, null, "change"); + observable.subscribe(value => { + var num: number = value; + }, null, "beforeChange"); +} + +function observableArrayEventsTests() { + var observableArray = ko.observableArray([1, 2, 3, 4]); + observableArray.subscribe(array => { + var arr: number[] = array; + }); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "change"); + observableArray.subscribe(array => { + var arr: number[] = array; + }, null, "beforeChange"); + var count = 0; + observableArray.subscribe(changes => { + changes.forEach(change => { + if (change.status == "added") + count++; + else if (change.status == "deleted") + count--; + }); + }, null, "arrayChange"); +} \ No newline at end of file From 36d40a63a05b5cb3413737fbdf7c9a2a26f211fd Mon Sep 17 00:00:00 2001 From: Craig Date: Wed, 14 Sep 2016 16:56:35 -0700 Subject: [PATCH 084/212] types(selenium-webdriver): revert 2.44 as default (#11226) - previous change would break installing angular-protractor ambient types - adding myself as author --- angular-protractor/angular-protractor.d.ts | 2 +- protractor-helpers/protractor-helpers.d.ts | 2 +- .../protractor-http-mock.d.ts | 2 +- .../selenium-webdriver-2.53.1-tests.ts | 1144 +++++ ....0.d.ts => selenium-webdriver-2.53.1.d.ts} | 3994 ++++++++++------ .../selenium-webdriver-tests.ts | 249 +- selenium-webdriver/selenium-webdriver.d.ts | 4250 ++++++----------- 7 files changed, 5444 insertions(+), 4199 deletions(-) create mode 100644 selenium-webdriver/selenium-webdriver-2.53.1-tests.ts rename selenium-webdriver/{selenium-webdriver-2.44.0.d.ts => selenium-webdriver-2.53.1.d.ts} (60%) diff --git a/angular-protractor/angular-protractor.d.ts b/angular-protractor/angular-protractor.d.ts index add8264b7e..d33eeddace 100644 --- a/angular-protractor/angular-protractor.d.ts +++ b/angular-protractor/angular-protractor.d.ts @@ -3,7 +3,7 @@ // Definitions by: Bill Armstrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace protractor { //region Wrapped webdriver Items diff --git a/protractor-helpers/protractor-helpers.d.ts b/protractor-helpers/protractor-helpers.d.ts index 16d67cfbb9..3966acd36e 100644 --- a/protractor-helpers/protractor-helpers.d.ts +++ b/protractor-helpers/protractor-helpers.d.ts @@ -5,7 +5,7 @@ /// /// -/// +/// // ElementArrayFinder diff --git a/protractor-http-mock/protractor-http-mock.d.ts b/protractor-http-mock/protractor-http-mock.d.ts index 2300246e43..29d6dfb276 100644 --- a/protractor-http-mock/protractor-http-mock.d.ts +++ b/protractor-http-mock/protractor-http-mock.d.ts @@ -3,7 +3,7 @@ // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace mock { interface ProtractorHttpMock { diff --git a/selenium-webdriver/selenium-webdriver-2.53.1-tests.ts b/selenium-webdriver/selenium-webdriver-2.53.1-tests.ts new file mode 100644 index 0000000000..77c68bb58d --- /dev/null +++ b/selenium-webdriver/selenium-webdriver-2.53.1-tests.ts @@ -0,0 +1,1144 @@ +/// + +function TestChromeDriver() { + var driver: chrome.Driver = new chrome.Driver(); + driver = new chrome.Driver(webdriver.Capabilities.chrome()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestChromeOptions() { + var options: chrome.Options = new chrome.Options(); + options = chrome.Options.fromCapabilities(webdriver.Capabilities.chrome()); + + options = options.addArguments("a", "b", "c"); + options = options.addExtensions("a", "b", "c"); + options = options.excludeSwitches("a", "b", "c"); + options = options.detachDriver(true); + options = options.setChromeBinaryPath("path"); + options = options.setChromeLogFile("logfile"); + options = options.setLocalState("state"); + options = options.androidActivity("com.example.Activity"); + options = options.androidDeviceSerial("emulator-5554"); + options = options.androidChrome(); + options = options.androidPackage("com.android.chrome"); + options = options.androidProcess("com.android.chrome"); + options = options.androidUseRunningApp(true); + options = options.setLoggingPrefs(new webdriver.logging.Preferences()); + options = options.setPerfLoggingPrefs({enableNetwork: true, enablePage: true, enableTimeline: true, tracingCategories: "category", bufferUsageReportingInterval: 1000}); + options = options.setProxy({ proxyType: "proxyType" }); + options = options.setUserPreferences("preferences"); + var capabilities: webdriver.Capabilities = options.toCapabilities(); + capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); +} + +function TestServiceBuilder() { + var builder: chrome.ServiceBuilder = new chrome.ServiceBuilder(); + builder = new chrome.ServiceBuilder("exe"); + + var anything: any = builder.build(); + builder = builder.usingPort(8080); + builder = builder.setAdbPort(5037); + builder = builder.loggingTo("path"); + builder = builder.enableVerboseLogging(); + builder = builder.setNumHttpThreads(5); + builder = builder.setUrlBasePath("path"); + builder = builder.setStdio("config"); + builder = builder.setStdio(["A", "B"]); + builder = builder.withEnvironment({ "A": "a", "B": "b" }); +} + +function TestChromeModule() { + var service: any = chrome.getDefaultService(); + chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); +} + +function TestBinary() { + var binary: firefox.Binary = new firefox.Binary(); + binary = new firefox.Binary("exe"); + + binary.addArguments("A", "B", "C"); + var promise: webdriver.promise.Promise = binary.kill(); + binary.launch("profile").then(function (result: any) { }); +} + +function TestFirefoxDriver() { + var driver: firefox.Driver = new firefox.Driver(); + driver = new firefox.Driver(webdriver.Capabilities.firefox()); + driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + + var baseDriver: webdriver.WebDriver = driver; +} + +function TestFirefoxOptions() { + var options: firefox.Options = new firefox.Options(); + + options = options.setBinary("binary"); + options = options.setBinary(new firefox.Binary()); + options = options.setLoggingPreferences(new webdriver.logging.Preferences()); + options = options.setProfile("profile"); + options = options.setProfile(new firefox.Profile()); + options = options.setProxy({ proxyType: "proxy" }); + var capabilities: webdriver.Capabilities = options.toCapabilities(); +} + +function TestFirefoxProfile() { + var profile: firefox.Profile = new firefox.Profile(); + profile = new firefox.Profile("dir"); + + var bool: boolean = profile.acceptUntrustedCerts(); + profile.addExtension("ext"); + bool = profile.assumeUntrustedCertIssuer(); + profile.encode().then(function (prof: string) { }); + var num: number = profile.getPort(); + var anything: any = profile.getPreference("key"); + bool = profile.nativeEventsEnabled(); + profile.setAcceptUntrustedCerts(true); + profile.setAssumeUntrustedCertIssuer(true); + profile.setNativeEventsEnabled(true); + profile.setPort(8080); + profile.setPreference("key", "value"); + profile.setPreference("key", 5); + profile.setPreference("key", true); + var stringPromise: webdriver.promise.Promise = profile.writeToDisk(); + stringPromise = profile.writeToDisk(true); +} + +function TestExecutors() { + var exec: webdriver.Executor = executors.createExecutor("url"); + var promise: webdriver.promise.Promise; + exec = executors.createExecutor(promise); +} + +function TestBuilder() { + var builder: webdriver.Builder = new webdriver.Builder(); + + var driver: webdriver.WebDriver = builder.build(); + builder = builder.forBrowser('name'); + builder = builder.forBrowser('name', 'version'); + builder = builder.forBrowser('name', 'version', 'platform'); + + var cap: webdriver.Capabilities = builder.getCapabilities(); + var str:string = builder.getServerUrl(); + + builder = builder.setAlertBehavior('behavior'); + builder = builder.setChromeOptions(new chrome.Options()); + builder = builder.setControlFlow(new webdriver.promise.ControlFlow()); + builder = builder.setEnableNativeEvents(true); + builder = builder.setFirefoxOptions(new firefox.Options()); + builder = builder.setLoggingPrefs(new webdriver.logging.Preferences()); + builder = builder.setLoggingPrefs({ "key": "value" }); + builder = builder.setProxy({ proxyType: 'type' }); + builder = builder.setScrollBehavior(1); + builder = builder.usingServer('http://someserver'); + builder = builder.withCapabilities(new webdriver.Capabilities()); + builder = builder.withCapabilities({ something: true }); +} + +function TestActionSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var promise: webdriver.promise.Promise; + element = new webdriver.WebElement(driver, promise); + + // Click + sequence = sequence.click(); + sequence = sequence.click(webdriver.Button.LEFT); + sequence = sequence.click(element); + sequence = sequence.click(element, webdriver.Button.LEFT); + + // DoubleClick + sequence = sequence.doubleClick(); + sequence = sequence.doubleClick(webdriver.Button.LEFT); + sequence = sequence.doubleClick(element); + sequence = sequence.doubleClick(element, webdriver.Button.LEFT); + + // DragAndDrop + sequence = sequence.dragAndDrop(element, element); + sequence = sequence.dragAndDrop(element, {x: 1, y: 2}); + + // KeyDown + sequence = sequence.keyDown(webdriver.Key.ADD); + + // KeyUp + sequence = sequence.keyUp(webdriver.Key.ADD); + + // MouseDown + sequence = sequence.mouseDown(); + sequence = sequence.mouseDown(webdriver.Button.LEFT); + sequence = sequence.mouseDown(element); + sequence = sequence.mouseDown(element, webdriver.Button.LEFT); + + // MouseMove + sequence = sequence.mouseMove(element); + sequence = sequence.mouseMove({x: 1, y: 1}); + sequence = sequence.mouseMove(element, {x: 1, y: 2}); + + // MouseUp + sequence = sequence.mouseUp(); + sequence = sequence.mouseUp(webdriver.Button.LEFT); + sequence = sequence.mouseUp(element); + sequence = sequence.mouseUp(element, webdriver.Button.LEFT); + + // SendKeys + sequence = sequence.sendKeys("A", "B", "C"); + + sequence.perform().then(function () { }); +} + +function TestTouchSequence() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + + var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); + + sequence = sequence.tap(element); + sequence = sequence.doubleTap(element); + sequence = sequence.longPress(element); + sequence = sequence.tapAndHold({ x: 100, y: 100 }); + sequence = sequence.move({ x: 100, y: 100 }); + sequence = sequence.release({ x: 100, y: 100 }); + sequence = sequence.scroll({ x: 100, y: 100 }); + sequence = sequence.scrollFromElement(element, { x: 100, y: 100 }); + sequence = sequence.flick({ xspeed: 100, yspeed: 100 }); + sequence = sequence.flickElement(element, { x: 100, y: 100 }, 100); + + sequence.perform().then(function () { }); +} + +function TestAlert() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var alert: webdriver.Alert = driver.switchTo().alert(); + + alert.accept().then(function () { }); + alert.dismiss().then(function () { }); + alert.getText().then(function (text: string) { }); + alert.sendKeys("ABC").then(function () { }); +} + +function TestBrowser() { + var browser: string; + + browser = webdriver.Browser.ANDROID; + browser = webdriver.Browser.CHROME; + browser = webdriver.Browser.FIREFOX; + browser = webdriver.Browser.HTMLUNIT; + browser = webdriver.Browser.INTERNET_EXPLORER; + browser = webdriver.Browser.IPAD; + browser = webdriver.Browser.IPHONE; + browser = webdriver.Browser.OPERA; + browser = webdriver.Browser.PHANTOM_JS; + browser = webdriver.Browser.SAFARI; +} + +function TestButton() { + var button: number; + + button = webdriver.Button.LEFT; + button = webdriver.Button.MIDDLE; + button = webdriver.Button.RIGHT; +} + +function TestCapabilities() { + var capabilities: webdriver.Capabilities = new webdriver.Capabilities(); + capabilities = new webdriver.Capabilities(webdriver.Capabilities.chrome()); + var objCapabilities: any = {}; + objCapabilities[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.PHANTOM_JS; + capabilities = new webdriver.Capabilities(objCapabilities); + + var anything: any = capabilities.get(webdriver.Capability.SECURE_SSL); + var check: boolean = capabilities.has(webdriver.Capability.SECURE_SSL); + capabilities = capabilities.merge(capabilities); + capabilities = capabilities.merge(objCapabilities); + capabilities = capabilities.set(webdriver.Capability.VERSION, { abc: 'def' }); + capabilities = capabilities.set(webdriver.Capability.VERSION, null); + capabilities = capabilities.setLoggingPrefs(new webdriver.logging.Preferences()); + capabilities = capabilities.setLoggingPrefs({ "key": "value" }); + capabilities = capabilities.setProxy({ proxyType: 'Type' }); + capabilities = capabilities.setEnableNativeEvents(true); + capabilities = capabilities.setScrollBehavior(1); + capabilities = capabilities.setAlertBehavior('accept'); + + anything = capabilities.toJSON(); + + capabilities = webdriver.Capabilities.android(); + capabilities = webdriver.Capabilities.chrome(); + capabilities = webdriver.Capabilities.firefox(); + capabilities = webdriver.Capabilities.htmlunit(); + capabilities = webdriver.Capabilities.htmlunitwithjs(); + capabilities = webdriver.Capabilities.ie(); + capabilities = webdriver.Capabilities.ipad(); + capabilities = webdriver.Capabilities.iphone(); + capabilities = webdriver.Capabilities.opera(); + capabilities = webdriver.Capabilities.phantomjs(); + capabilities = webdriver.Capabilities.safari(); +} + +function TestCapability() { + var capability: string; + + capability = webdriver.Capability.ACCEPT_SSL_CERTS; + capability = webdriver.Capability.BROWSER_NAME; + capability = webdriver.Capability.ELEMENT_SCROLL_BEHAVIOR; + capability = webdriver.Capability.HANDLES_ALERTS; + capability = webdriver.Capability.LOGGING_PREFS; + capability = webdriver.Capability.NATIVE_EVENTS; + capability = webdriver.Capability.PLATFORM; + capability = webdriver.Capability.PROXY; + capability = webdriver.Capability.ROTATABLE; + capability = webdriver.Capability.SECURE_SSL; + capability = webdriver.Capability.SUPPORTS_APPLICATION_CACHE; + capability = webdriver.Capability.SUPPORTS_CSS_SELECTORS; + capability = webdriver.Capability.SUPPORTS_JAVASCRIPT; + capability = webdriver.Capability.SUPPORTS_LOCATION_CONTEXT; + capability = webdriver.Capability.TAKES_SCREENSHOT; + capability = webdriver.Capability.UNEXPECTED_ALERT_BEHAVIOR; + capability = webdriver.Capability.VERSION; +} + +function TestCommand() { + var command: webdriver.Command = new webdriver.Command(webdriver.CommandName.ADD_COOKIE); + + var name: string = command.getName(); + var param: any = command.getParameter("param"); + + var params: any = command.getParameters(); + + command = command.setParameter("param", 123); + command = command.setParameters({ param: 123 }); +} + +function TestDeferredExecutor() { + var promise: webdriver.promise.Promise; + var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); +} + +function TestCommandName() { + var command: string; + + command = webdriver.CommandName.ACCEPT_ALERT; + command = webdriver.CommandName.ADD_COOKIE; + command = webdriver.CommandName.CLEAR_APP_CACHE; + command = webdriver.CommandName.CLEAR_ELEMENT; + command = webdriver.CommandName.CLEAR_LOCAL_STORAGE; + command = webdriver.CommandName.CLEAR_SESSION_STORAGE; + command = webdriver.CommandName.CLICK; + command = webdriver.CommandName.CLICK_ELEMENT; + command = webdriver.CommandName.CLOSE; + command = webdriver.CommandName.DELETE_ALL_COOKIES; + command = webdriver.CommandName.DELETE_COOKIE; + command = webdriver.CommandName.DESCRIBE_SESSION; + command = webdriver.CommandName.DISMISS_ALERT; + command = webdriver.CommandName.DOUBLE_CLICK; + command = webdriver.CommandName.ELEMENT_EQUALS; + command = webdriver.CommandName.EXECUTE_ASYNC_SCRIPT; + command = webdriver.CommandName.EXECUTE_SCRIPT; + command = webdriver.CommandName.EXECUTE_SQL; + command = webdriver.CommandName.FIND_CHILD_ELEMENT; + command = webdriver.CommandName.FIND_CHILD_ELEMENTS; + command = webdriver.CommandName.FIND_ELEMENT; + command = webdriver.CommandName.FIND_ELEMENTS; + command = webdriver.CommandName.GET; + command = webdriver.CommandName.GET_ACTIVE_ELEMENT; + command = webdriver.CommandName.GET_ALERT_TEXT; + command = webdriver.CommandName.GET_ALL_COOKIES; + command = webdriver.CommandName.GET_APP_CACHE; + command = webdriver.CommandName.GET_APP_CACHE_STATUS; + command = webdriver.CommandName.GET_AVAILABLE_LOG_TYPES; + command = webdriver.CommandName.GET_COOKIE; + command = webdriver.CommandName.GET_CURRENT_URL; + command = webdriver.CommandName.GET_CURRENT_WINDOW_HANDLE; + command = webdriver.CommandName.GET_ELEMENT_ATTRIBUTE; + command = webdriver.CommandName.GET_ELEMENT_LOCATION; + command = webdriver.CommandName.GET_ELEMENT_LOCATION_IN_VIEW; + command = webdriver.CommandName.GET_ELEMENT_SIZE; + command = webdriver.CommandName.GET_ELEMENT_TAG_NAME; + command = webdriver.CommandName.GET_ELEMENT_TEXT; + command = webdriver.CommandName.GET_ELEMENT_VALUE_OF_CSS_PROPERTY; + command = webdriver.CommandName.GET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.GET_LOCAL_STORAGE_KEYS; + command = webdriver.CommandName.GET_LOCAL_STORAGE_SIZE; + command = webdriver.CommandName.GET_LOCATION; + command = webdriver.CommandName.GET_LOG; + command = webdriver.CommandName.GET_PAGE_SOURCE; + command = webdriver.CommandName.GET_SCREEN_ORIENTATION; + command = webdriver.CommandName.GET_SERVER_STATUS; + command = webdriver.CommandName.GET_SESSION_LOGS; + command = webdriver.CommandName.GET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.GET_SESSION_STORAGE_KEYS; + command = webdriver.CommandName.GET_SESSION_STORAGE_SIZE; + command = webdriver.CommandName.GET_SESSIONS; + command = webdriver.CommandName.GET_TITLE; + command = webdriver.CommandName.GET_WINDOW_HANDLES; + command = webdriver.CommandName.GET_WINDOW_POSITION; + command = webdriver.CommandName.GET_WINDOW_SIZE; + command = webdriver.CommandName.GO_BACK; + command = webdriver.CommandName.GO_FORWARD; + command = webdriver.CommandName.IMPLICITLY_WAIT; + command = webdriver.CommandName.IS_BROWSER_ONLINE; + command = webdriver.CommandName.IS_ELEMENT_DISPLAYED; + command = webdriver.CommandName.IS_ELEMENT_ENABLED; + command = webdriver.CommandName.IS_ELEMENT_SELECTED; + command = webdriver.CommandName.MAXIMIZE_WINDOW; + command = webdriver.CommandName.MOUSE_DOWN; + command = webdriver.CommandName.MOUSE_UP; + command = webdriver.CommandName.MOVE_TO; + command = webdriver.CommandName.NEW_SESSION; + command = webdriver.CommandName.QUIT; + command = webdriver.CommandName.REFRESH; + command = webdriver.CommandName.REMOVE_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.REMOVE_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SCREENSHOT; + command = webdriver.CommandName.SEND_KEYS_TO_ACTIVE_ELEMENT; + command = webdriver.CommandName.SEND_KEYS_TO_ELEMENT; + command = webdriver.CommandName.SET_ALERT_TEXT; + command = webdriver.CommandName.SET_BROWSER_ONLINE; + command = webdriver.CommandName.SET_LOCAL_STORAGE_ITEM; + command = webdriver.CommandName.SET_LOCATION; + command = webdriver.CommandName.SET_SCREEN_ORIENTATION; + command = webdriver.CommandName.SET_SCRIPT_TIMEOUT; + command = webdriver.CommandName.SET_SESSION_STORAGE_ITEM; + command = webdriver.CommandName.SET_TIMEOUT; + command = webdriver.CommandName.SET_WINDOW_POSITION; + command = webdriver.CommandName.SET_WINDOW_SIZE; + command = webdriver.CommandName.SUBMIT_ELEMENT; + command = webdriver.CommandName.SWITCH_TO_FRAME; + command = webdriver.CommandName.SWITCH_TO_WINDOW; + command = webdriver.CommandName.TOUCH_DOUBLE_TAP; + command = webdriver.CommandName.TOUCH_DOWN; + command = webdriver.CommandName.TOUCH_FLICK; + command = webdriver.CommandName.TOUCH_LONG_PRESS; + command = webdriver.CommandName.TOUCH_MOVE; + command = webdriver.CommandName.TOUCH_SCROLL; + command = webdriver.CommandName.TOUCH_SINGLE_TAP; + command = webdriver.CommandName.TOUCH_UP; +} + +function TestEventEmitter() { + var emitter: webdriver.EventEmitter = new webdriver.EventEmitter(); + + var callback = function (a: number, b: number, c: number) {}; + + emitter = emitter.addListener('ABC', callback); + emitter = emitter.addListener('ABC', callback, this); + + emitter.emit('ABC', 1, 2, 3); + + var listeners = emitter.listeners('ABC'); + if (listeners[0].oneshot) { + listeners[0].fn.apply(listeners[0].scope); + } + var length: number = listeners.length; + var listenerInfo = listeners[0]; + if (listenerInfo.oneshot) { + listenerInfo.fn.apply(listenerInfo.scope, [1, 2, 3]); + } + + emitter = emitter.on('ABC', callback); + emitter = emitter.on('ABC', callback, this); + + emitter = emitter.once('ABC', callback); + emitter = emitter.once('ABC', callback, this); + + emitter = emitter.removeListener('ABC', callback); + + emitter.removeAllListeners('ABC'); + emitter.removeAllListeners(); +} + +function TestKey() { + var key: webdriver.Key; + + key = webdriver.Key.ADD; + key = webdriver.Key.ALT; + key = webdriver.Key.ARROW_DOWN; + key = webdriver.Key.ARROW_LEFT; + key = webdriver.Key.ARROW_RIGHT; + key = webdriver.Key.ARROW_UP; + key = webdriver.Key.BACK_SPACE; + key = webdriver.Key.CANCEL; + key = webdriver.Key.CLEAR; + key = webdriver.Key.COMMAND; + key = webdriver.Key.CONTROL; + key = webdriver.Key.DECIMAL; + key = webdriver.Key.DELETE; + key = webdriver.Key.DIVIDE; + key = webdriver.Key.DOWN; + key = webdriver.Key.END; + key = webdriver.Key.ENTER; + key = webdriver.Key.EQUALS; + key = webdriver.Key.ESCAPE; + key = webdriver.Key.F1; + key = webdriver.Key.F2; + key = webdriver.Key.F3; + key = webdriver.Key.F4; + key = webdriver.Key.F5; + key = webdriver.Key.F6; + key = webdriver.Key.F7; + key = webdriver.Key.F8; + key = webdriver.Key.F9; + key = webdriver.Key.F10; + key = webdriver.Key.F11; + key = webdriver.Key.F12; + key = webdriver.Key.HELP; + key = webdriver.Key.HOME; + key = webdriver.Key.INSERT; + key = webdriver.Key.LEFT; + key = webdriver.Key.META; + key = webdriver.Key.MULTIPLY; + key = webdriver.Key.NULL; + key = webdriver.Key.NUMPAD0; + key = webdriver.Key.NUMPAD1; + key = webdriver.Key.NUMPAD2; + key = webdriver.Key.NUMPAD3; + key = webdriver.Key.NUMPAD4; + key = webdriver.Key.NUMPAD5; + key = webdriver.Key.NUMPAD6; + key = webdriver.Key.NUMPAD7; + key = webdriver.Key.NUMPAD8; + key = webdriver.Key.NUMPAD9; + key = webdriver.Key.PAGE_DOWN; + key = webdriver.Key.PAGE_UP; + key = webdriver.Key.PAUSE; + key = webdriver.Key.RETURN; + key = webdriver.Key.RIGHT; + key = webdriver.Key.SEMICOLON; + key = webdriver.Key.SEPARATOR; + key = webdriver.Key.SHIFT; + key = webdriver.Key.SPACE; + key = webdriver.Key.SUBTRACT; + key = webdriver.Key.TAB; + key = webdriver.Key.UP; +} + +function TestBy() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.By = new webdriver.By('class name', 'class'); + + var str: string = locator.toString(); + + locator = webdriver.By.className('class'); + locator = webdriver.By.css('css'); + locator = webdriver.By.id('id'); + locator = webdriver.By.linkText('link'); + locator = webdriver.By.name('name'); + locator = webdriver.By.partialLinkText('text'); + locator = webdriver.By.tagName('tag'); + locator = webdriver.By.xpath('xpath'); + + // Can import "By" without import declarations + var By = webdriver.By; + + var locatorHash: webdriver.ByHash; + locatorHash = { className: 'class' }; + locatorHash = { css: 'css' }; + locatorHash = { id: 'id' }; + locatorHash = { linkText: 'link' }; + locatorHash = { name: 'name' }; + locatorHash = { partialLinkText: 'text' }; + locatorHash = { tagName: 'tag' }; + locatorHash = { xpath: 'xpath' }; + + webdriver.By.js('script', 1, 2, 3)(driver).then(function (abc: number) { }); +} + +function TestSession() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var capabilitiesObj: any = {}; + capabilitiesObj[webdriver.Capability.BROWSER_NAME] = webdriver.Browser.ANDROID; + capabilitiesObj[webdriver.Capability.PLATFORM] = 'ANDROID'; + session = new webdriver.Session('ABC', capabilitiesObj); + + var capabilities: webdriver.Capabilities = session.getCapabilities(); + var capability: any = session.getCapability(webdriver.Capability.BROWSER_NAME); + var id: string = session.getId(); + var data: string = session.toJSON(); +} + +function TestUnhandledAlertError() { + var someFunc = function (error: webdriver.UnhandledAlertError) { + var baseError: Error = error; + var str: string = error.getAlertText(); + str = error.toString(); + } +} + +function TestWebDriverFileDetector() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + + fileDetector.handleFile(driver, 'path/to/file').then(function(path: string) {}); +} + +function TestWebDriverLogs() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var logs: webdriver.Logs = new webdriver.Logs(driver); + + logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; + logs.getAvailableLogTypes().then(function (types: string[]) { }); +} + +function TestWebDriverNavigation() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var navigation: webdriver.Navigation = new webdriver.Navigation(driver); + + navigation.back().then(function () { }); + navigation.forward().then(function () { }); + navigation.refresh().then(function () { }); + navigation.to('http://google.com').then(function () { }); +} + +function TestWebDriverOptions() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var options: webdriver.Options = new webdriver.Options(driver); + var promise: webdriver.promise.Promise; + + // Add Cookie + promise = options.addCookie('name', 'value'); + promise = options.addCookie('name', 'value', 'path'); + promise = options.addCookie('name', 'value', 'path', 'domain'); + promise = options.addCookie('name', 'value', 'path', 'domain', true); + promise = options.addCookie('name', 'value', 'path', 'domain', true, 123); + promise = options.addCookie('name', 'value', 'path', 'domain', true, Date.now()); + + promise = options.deleteAllCookies(); + promise = options.deleteCookie('name'); + options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); + options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); + + var logs: webdriver.Logs = options.logs(); + var timeouts: webdriver.Timeouts = options.timeouts(); + var window: webdriver.Window = options.window(); +} + +function TestWebDriverTargetLocator() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); + var promise: webdriver.promise.Promise; + + var element: webdriver.WebElement = locator.activeElement(); + var alert: webdriver.Alert = locator.alert(); + promise = locator.defaultContent(); + promise = locator.frame(1); + promise = locator.window('nameOrHandle'); +} + +function TestWebDriverTimeouts() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); + var promise: webdriver.promise.Promise; + + promise = timeouts.implicitlyWait(123); + promise = timeouts.pageLoadTimeout(123); + promise = timeouts.setScriptTimeout(123); +} + +function TestWebDriverWindow() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var window: webdriver.Window = new webdriver.Window(driver); + var locationPromise: webdriver.promise.Promise; + var sizePromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + locationPromise = window.getPosition(); + sizePromise = window.getSize(); + voidPromise = window.maximize(); + voidPromise = window.setPosition(12, 34); + voidPromise = window.setSize(12, 34); +} + +function TestWebDriver() { + var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); + var sessionPromise: webdriver.promise.Promise; + var executor: webdriver.Executor = executors.createExecutor("http://someserver"); + var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); + var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); + driver = new webdriver.WebDriver(session, executor, flow); + driver = new webdriver.WebDriver(sessionPromise, executor); + driver = new webdriver.WebDriver(sessionPromise, executor, flow); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + var actions: webdriver.ActionSequence = driver.actions(); + var touchActions: webdriver.TouchSequence = driver.touchActions(); + + // call + stringPromise = driver.call(function(){ return 'value'; }); + stringPromise = driver.call(function(){ return stringPromise; }); + stringPromise = driver.call(function(){ var d: any = this; return 'value'; }, driver); + stringPromise = driver.call(function(a: number){ return 'value'; }, driver, 1); + + voidPromise = driver.close(); + flow = driver.controlFlow(); + + // executeAsyncScript + stringPromise = driver.executeAsyncScript('function(){}'); + stringPromise = driver.executeAsyncScript('function(){}', 1, 2, 3); + stringPromise = driver.executeAsyncScript(function(){}); + stringPromise = driver.executeAsyncScript(function(a: number){}, 1); + + // executeScript + stringPromise = driver.executeScript('function(){}'); + stringPromise = driver.executeScript('function(){}', 1, 2, 3); + stringPromise = driver.executeScript(function(){}); + stringPromise = driver.executeScript(function(a: number){}, 1); + + // findElement + var element: webdriver.WebElement; + element = driver.findElement(webdriver.By.id('ABC')); + element = driver.findElement(webdriver.By.js('function(){}')); + + // findElements + driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); + + voidPromise = driver.get('http://www.google.com'); + driver.getAllWindowHandles().then(function (handles: string[]) { }); + driver.getCapabilities().then(function (caps: webdriver.Capabilities) { }); + stringPromise = driver.getCurrentUrl(); + stringPromise = driver.getPageSource() + driver.getSession().then(function (session: webdriver.Session) { });; + stringPromise = driver.getTitle(); + stringPromise = driver.getWindowHandle(); + + booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + + var options: webdriver.Options = driver.manage(); + var navigation: webdriver.Navigation = driver.navigate(); + var locator: webdriver.TargetLocator = driver.switchTo(); + + var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); + driver.setFileDetector(fileDetector); + + voidPromise = driver.quit(); + voidPromise = driver.schedule(new webdriver.Command(webdriver.CommandName.CLICK), 'ABC'); + voidPromise = driver.sleep(123); + stringPromise = driver.takeScreenshot(); + + var booleanCondition: webdriver.until.Condition; + booleanPromise = driver.wait(booleanPromise); + booleanPromise = driver.wait(booleanCondition); + booleanPromise = driver.wait(function(driver: webdriver.WebDriver) { return true; }); + booleanPromise = driver.wait(booleanPromise, 123); + booleanPromise = driver.wait(booleanPromise, 123, 'Message'); + + driver = webdriver.WebDriver.attachToSession(executor, 'ABC'); + driver = webdriver.WebDriver.createSession(executor, webdriver.Capabilities.android()); +} + +function TestSerializable() { + var serializable: webdriver.Serializable; + var serial: string|webdriver.promise.IThenable = serializable.serialize(); +} + +function TestWebElement() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var promise: webdriver.promise.Promise; + var element: webdriver.WebElement; + + element = new webdriver.WebElement(driver, 'elementId'); + element = new webdriver.WebElement(driver, promise); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + voidPromise = element.clear(); + voidPromise = element.click(); + + element = element.findElement(webdriver.By.id('ABC')); + element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + + stringPromise = element.getAttribute('class'); + stringPromise = element.getCssValue('display'); + driver = element.getDriver(); + stringPromise = element.getInnerHtml(); + element.getLocation().then(function (location: webdriver.ILocation) { }); + stringPromise = element.getOuterHtml(); + element.getSize().then(function (size: webdriver.ISize) { }); + stringPromise = element.getTagName(); + stringPromise = element.getText(); + booleanPromise = element.isDisplayed(); + booleanPromise = element.isEnabled(); + booleanPromise = element.isSelected(); + voidPromise = element.sendKeys('A', 'B', 'C'); + voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); + voidPromise = element.submit(); + element.getId().then(function (id: string) { }); + element.getRawId().then(function (id: string) { }); + element.serialize().then(function (id: webdriver.IWebElementId) { }); + + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); +} + +function TestWebElementPromise() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var elementPromise: webdriver.WebElementPromise = driver.findElement(webdriver.By.id('id')); + + elementPromise.cancel(); + elementPromise.cancel('reason'); + + var bool: boolean = elementPromise.isPending(); + + elementPromise.then(); + elementPromise.then(function (element: webdriver.WebElement) { }); + elementPromise.then(function (element: webdriver.WebElement) { }, function (error: any) { }); + elementPromise.then(function (element: webdriver.WebElement) { return "foo"; }, function (error: any) { }).then(function (result: string) { }); + + elementPromise.thenCatch(function (error: any) { }).then(function (value: any) { }); + + elementPromise.thenFinally(function () { }); +} + +function TestLogging() { + var preferences: webdriver.logging.Preferences = new webdriver.logging.Preferences(); + preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); + var prefs: any = preferences.toJSON(); + + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + level = webdriver.logging.getLevel(1); + + level = webdriver.logging.Level.ALL; + level = webdriver.logging.Level.DEBUG; + level = webdriver.logging.Level.INFO; + level = webdriver.logging.Level.OFF; + level = webdriver.logging.Level.SEVERE; + level = webdriver.logging.Level.WARNING; + + var name: string = level.name(); + var value: number = level.value(); + + var type: webdriver.logging.Type; + type = webdriver.logging.Type.BROWSER; + type = webdriver.logging.Type.CLIENT; + type = webdriver.logging.Type.DRIVER; + type = webdriver.logging.Type.PERFORMANCE; + type = webdriver.logging.Type.SERVER; +} + +function TestLoggingEntry() { + var entry: webdriver.logging.Entry; + + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC'); + entry = new webdriver.logging.Entry('ALL', 'ABC'); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123); + entry = new webdriver.logging.Entry(webdriver.logging.Level.ALL, 'ABC', 123, webdriver.logging.Type.BROWSER); + entry = new webdriver.logging.Entry('ALL', 'ABC', 123, webdriver.logging.Type.BROWSER); + + var entryObj: any = entry.toJSON(); + + var message: string = entry.message; + var timestamp: number = entry.timestamp; + var type: string = entry.type; +} + +function TestPromiseModule() { + var cancellationError: webdriver.promise.CancellationError = new webdriver.promise.CancellationError(); + cancellationError = new webdriver.promise.CancellationError("message"); + var str: string = cancellationError.message; + str = cancellationError.name; + + var stringPromise: webdriver.promise.Promise; + var numberPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + var voidPromise: webdriver.promise.Promise; + + webdriver.promise.all([stringPromise]).then(function (values: string[]) { }); + + webdriver.promise.asap('abc', function(value: any){ return true; }); + webdriver.promise.asap('abc', function(value: any){}, function(err: any) { return 'ABC'; }); + + stringPromise = webdriver.promise.checkedNodeCall(function(err: any, value: any) { return 'abc'; }); + + webdriver.promise.consume(function () { + return 5; + }).then(function (value: number) { }); + webdriver.promise.consume(function () { + return 5; + }, this).then(function (value: number) { }); + webdriver.promise.consume(function (a: number, b: number, c: number) { + return 5; + }, this, 1, 2, 3).then(function (value: number) { }); + + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + return true; + }, this); + + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + return true; + }); + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + return true; + }, this); + + var flow: webdriver.promise.ControlFlow = webdriver.promise.controlFlow(); + + stringPromise = webdriver.promise.createFlow(function(newFlow: webdriver.promise.ControlFlow) { return 'ABC' }); + + var deferred: webdriver.promise.Deferred; + deferred = webdriver.promise.defer(); + deferred = webdriver.promise.defer(); + + stringPromise = deferred.promise; + + deferred.fulfill('ABC'); + deferred.reject('error'); + + voidPromise = webdriver.promise.delayed(123); + + voidPromise = webdriver.promise.fulfilled(); + stringPromise = webdriver.promise.fulfilled('abc'); + + stringPromise = webdriver.promise.fullyResolved('abc'); + + var bool: boolean = webdriver.promise.isGenerator(function () { }); + var isPromise: boolean = webdriver.promise.isPromise('ABC'); + + stringPromise = webdriver.promise.rejected('{a: 123}'); + + webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + numberPromise = webdriver.promise.when('abc', function(value: any) { return 123; }, function(err: Error) { return 123; }); +} + +function TestUntilModule() { + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + var conditionB: webdriver.until.Condition = new webdriver.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); + var conditionBBase: webdriver.until.Condition = conditionB; + var conditionWebElement: webdriver.until.Condition; + var conditionWebElements: webdriver.until.Condition; + + conditionB = webdriver.until.ableToSwitchToFrame(5); + var conditionAlert: webdriver.until.Condition = webdriver.until.alertIsPresent(); + var el: webdriver.WebElement = driver.findElement(webdriver.By.id('id')); + conditionB = webdriver.until.elementIsDisabled(el); + conditionB = webdriver.until.elementIsEnabled(el); + conditionB = webdriver.until.elementIsNotSelected(el); + conditionB = webdriver.until.elementIsNotVisible(el); + conditionB = webdriver.until.elementIsSelected(el); + conditionB = webdriver.until.elementIsVisible(el); + conditionB = webdriver.until.elementTextContains(el, 'text'); + conditionB = webdriver.until.elementTextIs(el, 'text'); + conditionB = webdriver.until.elementTextMatches(el, /text/); + conditionB = webdriver.until.stalenessOf(el); + conditionB = webdriver.until.titleContains('text'); + conditionB = webdriver.until.titleIs('text'); + conditionB = webdriver.until.titleMatches(/text/); + + conditionWebElement = webdriver.until.elementLocated(webdriver.By.id('id')); + conditionWebElements = webdriver.until.elementsLocated(webdriver.By.className('class')); +} + +function TestControlFlow() { + var flow: webdriver.promise.ControlFlow; + flow = new webdriver.promise.ControlFlow(); + + var emitter: webdriver.EventEmitter = flow; + + var eventType: string; + + eventType = webdriver.promise.ControlFlow.EventType.IDLE; + eventType = webdriver.promise.ControlFlow.EventType.RESET; + eventType = webdriver.promise.ControlFlow.EventType.SCHEDULE_TASK; + eventType = webdriver.promise.ControlFlow.EventType.UNCAUGHT_EXCEPTION; + + var stringPromise: webdriver.promise.Promise; + stringPromise = flow.execute(function() { return 'value'; }); + stringPromise = flow.execute(function() { return stringPromise; }); + stringPromise = flow.execute(function() { return stringPromise; }, 'Description'); + + var schedule: string; + schedule = flow.toString(); + schedule = flow.getSchedule(); + schedule = flow.getSchedule(true); + + flow.reset(); + + var voidPromise: webdriver.promise.Promise = flow.timeout(123); + voidPromise = flow.timeout(123, 'Description'); + + stringPromise = flow.wait(stringPromise); + + voidPromise = flow.wait(function() { return true; }); + voidPromise = flow.wait(function() { return true; }, 123); + voidPromise = flow.wait(function() { return stringPromise; }, 123, 'Timeout Message'); +} + +function TestDeferred() { + var deferred: webdriver.promise.Deferred; + + deferred = new webdriver.promise.Deferred(); + deferred = new webdriver.promise.Deferred(new webdriver.promise.ControlFlow()); + + var promise: webdriver.promise.Promise = deferred.promise; + + deferred.errback(new Error('Error')); + deferred.errback('Error'); + deferred.fulfill('abc'); + deferred.reject(new Error('Error')); + deferred.reject('Error'); + deferred.removeAll(); +} + +function TestPromiseClass() { + var controlFlow: webdriver.promise.ControlFlow; + var promise: webdriver.promise.Promise; + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: webdriver.promise.Promise)=>void, + onRejected: ()=>void) { }); + promise = new webdriver.promise.Promise(function( + onFulfilled: (value: string)=>void, + onRejected: ()=>void) { }, controlFlow); + + promise.cancel('Abort'); + + var isPending: boolean = promise.isPending(); + + promise = promise.then(); + promise = promise.then(function( a: string ) { return 'cde'; }); + promise = promise.then(function( a: string ) { return 'cde'; }, function( e: any) {}); + promise = promise.then(function( a: string ) { return 'cde'; }, function (e: any) { return 123; }); + + promise = promise.thenCatch(function (error: any) { }); + + promise.thenFinally(function () { }); +} + +function TestThenableClass() { + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); + + thenable.cancel('Abort'); + + var isPending: boolean = thenable.isPending(); + + thenable = thenable.then(function (a: string) { return 'cde'; }); + thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { }); + thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); + + thenable = thenable.thenCatch(function (error: any) { }); + + thenable.thenFinally(function () { }); +} + +function TestErrorCode() { + var errorCode: number; + + errorCode = new webdriver.error.ElementNotSelectableError().code(); + errorCode = new webdriver.error.ElementNotVisibleError().code(); + errorCode = new webdriver.error.InvalidArgumentError().code(); + errorCode = new webdriver.error.InvalidCookieDomainError().code(); + errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); + errorCode = new webdriver.error.InvalidElementStateError().code(); + errorCode = new webdriver.error.InvalidSelectorError().code(); + errorCode = new webdriver.error.NoSuchSessionError().code(); + errorCode = new webdriver.error.JavascriptError().code(); + errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); + errorCode = new webdriver.error.NoSuchAlertError().code(); + errorCode = new webdriver.error.NoSuchElementError().code(); + errorCode = new webdriver.error.NoSuchFrameError().code(); + errorCode = new webdriver.error.NoSuchWindowError().code(); + errorCode = new webdriver.error.ScriptTimeoutError().code(); + errorCode = new webdriver.error.SessionNotCreatedError().code(); + errorCode = new webdriver.error.StaleElementReferenceError().code(); + errorCode = new webdriver.error.TimeoutError().code(); + errorCode = new webdriver.error.UnableToSetCookieError().code(); + errorCode = new webdriver.error.UnableToCaptureScreenError().code(); + errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); + errorCode = new webdriver.error.UnknownCommandError().code(); + errorCode = new webdriver.error.UnknownMethodError().code(); + errorCode = new webdriver.error.UnsupportedOperationError().code(); +} + +function TestTestingModule() { + testing.before(function () { + }); + + testing.beforeEach(function () { + }); + + testing.describe("My test suite", function () { + testing.it("My test", function () { + }); + + testing.iit("My exclusive test.", function () { + }); + + }); + + testing.xdescribe("My disabled suite", function () { + testing.xit("My disabled test.", function () { + }); + }); + + testing.after(function () { + }); + + testing.afterEach(function () { + }); +} diff --git a/selenium-webdriver/selenium-webdriver-2.44.0.d.ts b/selenium-webdriver/selenium-webdriver-2.53.1.d.ts similarity index 60% rename from selenium-webdriver/selenium-webdriver-2.44.0.d.ts rename to selenium-webdriver/selenium-webdriver-2.53.1.d.ts index 548048b695..a6e419755d 100644 --- a/selenium-webdriver/selenium-webdriver-2.44.0.d.ts +++ b/selenium-webdriver/selenium-webdriver-2.53.1.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Selenium WebDriverJS 2.44.0 -// Project: https://code.google.com/p/selenium/ -// Definitions by: Bill Armstrong , Yuki Kokubun +// Type definitions for Selenium WebDriverJS 2.53.1 +// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace chrome { @@ -19,8 +19,7 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -240,6 +239,53 @@ declare namespace chrome { setChromeLogFile(path: string): Options; + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + /** * Sets the proxy settings for the new session. * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. @@ -255,21 +301,6 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - - - /** - * Converts this instance to its JSON wire protocol representation. Note this - * function is an implementation not intended for general use. - * @return {{args: !Array., - * binary: (string|undefined), - * detach: boolean, - * extensions: !Array., - * localState: (Object|undefined), - * logFile: (string|undefined), - * prefs: (Object|undefined)}} The JSON wire protocol representation - * of this instance. - */ - toJSON(): IOptionsValues; } /** @@ -348,8 +379,7 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string): ServiceBuilder; - setStdio(config: any[]): ServiceBuilder; + setStdio(config: string|Array): ServiceBuilder; /** @@ -368,7 +398,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): any; + build(): remote.DriverService; } /** @@ -377,395 +407,1325 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): any; + function getDefaultService(): remote.DriverService; /** * Sets the default service to use for new ChromeDriver instances. * @param {!remote.DriverService} service The service to use. * @throws {Error} If the default service is currently running. */ - function setDefaultService(service: any): void; + function setDefaultService(service: remote.DriverService): void; } -declare namespace firefox { - /** - * Manages a Firefox subprocess configured for use with WebDriver. - */ - class Binary { - /** - * @param {string=} opt_exe Path to the Firefox binary to use. If not - * specified, will attempt to locate Firefox on the current system. - * @constructor - */ - constructor(opt_exe?: string); +declare namespace edge { - /** - * Add arguments to the command line used to start Firefox. - * @param {...(string|!Array.)} var_args Either the arguments to add as - * varargs, or the arguments as an array. - */ - addArguments(...var_args: string[]): void; - - - /** - * Launches Firefox and eturns a promise that will be fulfilled when the process - * terminates. - * @param {string} profile Path to the profile directory to use. - * @return {!promise.Promise.} A promise for the process result. - * @throws {Error} If this instance has already been started. - */ - launch(profile: string): webdriver.promise.Promise; - - - /** - * Kills the managed Firefox process. - * @return {!promise.Promise} A promise for when the process has terminated. - */ - kill(): webdriver.promise.Promise; - } - - /** - * A WebDriver client for Firefox. - * - * @extends {webdriver.WebDriver} - */ class Driver extends webdriver.WebDriver { - /** - * @param {(Options|webdriver.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash - * object. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - * @constructor - */ - constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@linkplain #getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; } /** - * Configuration options for the FirefoxDriver. + * Class for managing MicrosoftEdgeDriver specific options. */ class Options { - /** - * @constructor - */ - constructor(); - /** - * Sets the profile to use. The profile may be specified as a - * {@link Profile} object or as the path to an existing Firefox profile to use - * as a template. - * - * @param {(string|!Profile)} profile The profile to use. - * @return {!Options} A self reference. - */ - setProfile(profile: string): Options; - setProfile(profile: Profile): Options; + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; - /** - * Sets the binary to use. The binary may be specified as the path to a Firefox - * executable, or as a {@link Binary} object. - * - * @param {(string|!Binary)} binary The binary to use. - * @return {!Options} A self reference. - */ - setBinary(binary: string): Options; - setBinary(binary: Binary): Options; + /** + * Sets the page load strategy for Edge. + * Supported values are "normal", "eager", and "none"; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; - - /** - * Sets the logging preferences for the new session. - * @param {webdriver.logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - - /** - * Sets the proxy to use. - * - * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - - /** - * Converts these options to a {@link webdriver.Capabilities} instance. - * - * @return {!webdriver.Capabilities} A new capabilities object. - */ - toCapabilities(opt_remote?: any): webdriver.Capabilities; + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; } /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. */ - class Profile { - /** - * @param {string=} opt_dir Path to an existing Firefox profile directory to - * use a template for this profile. If not specified, a blank profile will - * be used. - * @constructor - */ - constructor(opt_dir?: string); + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); - /** - * Registers an extension to be included with this profile. - * @param {string} extension Path to the extension to include, as either an - * unpacked extension directory or the path to a xpi file. - */ - addExtension(extension: string): void; + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; - /** - * Sets a desired preference for this profile. - * @param {string} key The preference key. - * @param {(string|number|boolean)} value The preference value. - * @throws {Error} If attempting to set a frozen preference. - */ - setPreference(key: string, value: string): void; - setPreference(key: string, value: number): void; - setPreference(key: string, value: boolean): void; + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; - - /** - * Returns the currently configured value of a profile preference. This does - * not include any defaults defined in the profile's template directory user.js - * file (if a template were specified on construction). - * @param {string} key The desired preference. - * @return {(string|number|boolean|undefined)} The current value of the - * requested preference. - */ - getPreference(key: string): any; - - - /** - * @return {number} The port this profile is currently configured to use, or - * 0 if the port will be selected at random when the profile is written - * to disk. - */ - getPort(): number; - - - /** - * Sets the port to use for the WebDriver extension loaded by this profile. - * @param {number} port The desired port, or 0 to use any free port. - */ - setPort(port: number): void; - - - /** - * @return {boolean} Whether the FirefoxDriver is configured to automatically - * accept untrusted SSL certificates. - */ - acceptUntrustedCerts(): boolean; - - - /** - * Sets whether the FirefoxDriver should automatically accept untrusted SSL - * certificates. - * @param {boolean} value . - */ - setAcceptUntrustedCerts(value: boolean): void; - - - /** - * Sets whether to assume untrusted certificates come from untrusted issuers. - * @param {boolean} value . - */ - setAssumeUntrustedCertIssuer(value: boolean): void; - - - /** - * @return {boolean} Whether to assume untrusted certs come from untrusted - * issuers. - */ - assumeUntrustedCertIssuer(): boolean; - - - /** - * Sets whether to use native events with this profile. - * @param {boolean} enabled . - */ - setNativeEventsEnabled(enabled: boolean): void; - - - /** - * Returns whether native events are enabled in this profile. - * @return {boolean} . - */ - nativeEventsEnabled(): boolean; - - - /** - * Writes this profile to disk. - * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver - * extension from the generated profile. Used to reduce the size of an - * {@link #encode() encoded profile} since the server will always install - * the extension itself. - * @return {!promise.Promise.} A promise for the path to the new - * profile directory. - */ - writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; - - - /** - * Encodes this profile as a zipped, base64 encoded directory. - * @return {!promise.Promise.} A promise for the encoded profile. - */ - encode(): webdriver.promise.Promise; + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; } + + /** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Sets the default service to use for new MicrosoftEdgeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): void; } declare namespace executors { /** * Creates a command executor that uses WebDriver's JSON wire protocol. - * @param url The server's URL, or a promise that will resolve to that URL. - * @returns {!webdriver.CommandExecutor} The new command executor. + * @param {(string|!promise.Promise)} url The server's URL, + * or a promise that will resolve to that URL. + * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the + * client to use. + * @returns {!./lib/command.Executor} The new command executor. */ - function createExecutor(url: string): webdriver.CommandExecutor; - function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; + function createExecutor(url: string|webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; +} + +declare namespace firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; + } + + /** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string|any): Options; + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string|any): Options; + + /** + * Sets the logging preferences for the new session. + * @param {logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy to use. + * + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets whether to use Mozilla's Marionette to drive the browser. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + */ + useMarionette(marionette: any): Options; + + /** + * Converts these options to a {@link capabilities.Capabilities} instance. + * + * @return {!capabilities.Capabilities} A new capabilities object. + */ + toCapabilities(): webdriver.Capabilities; + } + + /** + * @return {string} . + * @throws {Error} + */ + function findWires(): string; + + /** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ + function createWiresService(binary: string|any): remote.DriverService; + + /** + * @param {(Profile|string)} profile The profile to prepare. + * @param {number} port The port the FirefoxDriver should listen on. + * @return {!Promise} a promise for the path to the profile directory. + */ + function prepareProfile(profile: string|any, port: number): any; + + /** + * A WebDriver client for Firefox. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|capabilities.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash + * object. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(opt_config?: Options|webdriver.Capabilities|Object, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace http { + /** + * Converts a headers map to a HTTP header block string. + * @param {!Map} headers The map to convert. + * @return {string} The headers as a string. + */ + function headersToString(headers: any): string; + + /** + * Represents a HTTP request message. This class is a "partial" request and only + * defines the path on the server to send a request to. It is each client's + * responsibility to build the full URL for the final request. + * @final + */ + class HttpRequest { + /** + * @param {string} method The HTTP method to use for the request. + * @param {string} path The path on the server to send the request to. + * @param {Object=} opt_data This request's non-serialized JSON payload data. + */ + constructor(method: string, path: string, opt_data?: Object); + + /** @override */ + toString(): string; + } + + /** + * Represents a HTTP response message. + * @final + */ + class HttpResponse { + /** + * @param {number} status The response code. + * @param {!Object} headers The response headers. All header names + * will be converted to lowercase strings for consistent lookups. + * @param {string} body The response body. + */ + constructor(status: number, headers: Object, body: string); + + /** @override */ + toString(): string; + } + + + function post(path: string): any; + function del(path: string): any; + function get(path: string): any; + function resource(method: string, path: string): any; + + /** + * A basic HTTP client used to send messages to a remote end. + */ + class HttpClient { + /** + * @param {string} serverUrl URL for the WebDriver server to send commands to. + * @param {http.Agent=} opt_agent The agent to use for each request. + * Defaults to `http.globalAgent`. + * @param {?string=} opt_proxy The proxy to use for the connection to the + * server. Default is to use no proxy. + */ + constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); + + /** + * Sends a request to the server. The client will automatically follow any + * redirects returned by the server, fulfilling the returned promise with the + * final response. + * + * @param {!HttpRequest} httpRequest The request to send. + * @return {!promise.Promise} A promise that will be fulfilled + * with the server's response. + */ + send(httpRequest: HttpRequest): webdriver.promise.Promise; + } + + /** + * Sends a single HTTP request. + * @param {!Object} options The request options. + * @param {function(!HttpResponse)} onOk The function to call if the + * request succeeds. + * @param {function(!Error)} onError The function to call if the request fails. + * @param {?string=} opt_data The data to send with the request. + * @param {?string=} opt_proxy The proxy server to use for the request. + */ + function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; + + /** + * A command executor that communicates with the server using HTTP + JSON. + * + * By default, each instance of this class will use the legacy wire protocol + * from [Selenium project][json]. The executor will automatically switch to the + * [W3C wire protocol][w3c] if the remote end returns a compliant response to + * a new session command. + * + * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html + * + * @implements {cmd.Executor} + */ + class Executor { + /** + * @param {!HttpClient} client The client to use for sending requests to the + * server. + */ + constructor(client: HttpClient); + + /** + * Defines a new command for use with this executor. When a command is sent, + * the {@code path} will be preprocessed using the command's parameters; any + * path segments prefixed with ":" will be replaced by the parameter of the + * same name. For example, given "/person/:name" and the parameters + * "{name: 'Bob'}", the final command path will be "/person/Bob". + * + * @param {string} name The command name. + * @param {string} method The HTTP method to use when sending this command. + * @param {string} path The path to send the command to, relative to + * the WebDriver server's command root and of the form + * "/path/:variable/segment". + */ + defineCommand(name: string, method: string, path: string): void; + + /** @override */ + execute(command: any): any; + } + + /** + * @param {string} str . + * @return {?} . + */ + function tryParse(str: string): any; + + /** + * Callback used to parse {@link HttpResponse} objects from a + * {@link HttpClient}. + * @param {!HttpResponse} httpResponse The HTTP response to parse. + * @param {boolean} w3c Whether the response should be processed using the + * W3C wire protocol. + * @return {{value: ?}} The parsed response. + * @throws {WebDriverError} If the HTTP response is an error. + */ + function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; + + /** + * Builds a fully qualified path using the given set of command parameters. Each + * path segment prefixed with ':' will be replaced by the value of the + * corresponding parameter. All parameters spliced into the path will be + * removed from the parameter map. + * @param {string} path The original resource path. + * @param {!Object<*>} parameters The parameters object to splice into the path. + * @return {string} The modified path. + */ + function buildPath(path: string, parameters: Object): string; +} + +declare namespace ie { + + /** + * A WebDriver client for Microsoft's Internet Explorer. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } + + /** + * Class for managing IEDriver specific options. + */ + class Options { + constructor(); + + /** + * Extracts the IEDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The IEDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Whether to disable the protected mode settings check when the session is + * created. Disbling this setting may lead to significant instability as the + * browser may become unresponsive/hang. Only "best effort" support is provided + * when using this capability. + * + * For more information, refer to the IEDriver's + * [required system configuration](http://goo.gl/eH0Yi3). + * + * @param {boolean} ignoreSettings Whether to ignore protected mode settings. + * @return {!Options} A self reference. + */ + introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; + + /** + * Indicates whether to skip the check that the browser's zoom level is set to + * 100%. + * + * @param {boolean} ignore Whether to ignore the browser's zoom level settings. + * @return {!Options} A self reference. + */ + ignoreZoomSetting(ignore: boolean): Options; + + /** + * Sets the initial URL loaded when IE starts. This is intended to be used with + * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in + * the proper Protected Mode zone. Setting this option may cause browser + * instability or flaky and unresponsive code. Only "best effort" support is + * provided when using this option. + * + * @param {string} url The initial browser URL. + * @return {!Options} A self reference. + */ + initialBrowserUrl(url: string): Options; + + /** + * Configures whether to enable persistent mouse hovering (true by default). + * Persistent hovering is achieved by continuously firing mouse over events at + * the last location the mouse cursor has been moved to. + * + * @param {boolean} enable Whether to enable persistent hovering. + * @return {!Options} A self reference. + */ + enablePersistentHover(enable: boolean): Options; + + /** + * Configures whether the driver should attempt to remove obsolete + * {@linkplain webdriver.WebElement WebElements} from its internal cache on + * page navigation (true by default). Disabling this option will cause the + * driver to run with a larger memory footprint. + * + * @param {boolean} enable Whether to enable element reference cleanup. + * @return {!Options} A self reference. + */ + enableElementCacheCleanup(enable: boolean): Options; + + /** + * Configures whether to require the IE window to have input focus before + * performing any user interactions (i.e. mouse or keyboard events). This + * option is disabled by default, but delivers much more accurate interaction + * events when enabled. + * + * @param {boolean} require Whether to require window focus. + * @return {!Options} A self reference. + */ + requireWindowFocus(require: boolean): Options; + + /** + * Configures the timeout, in milliseconds, that the driver will attempt to + * located and attach to a newly opened instance of Internet Explorer. The + * default is zero, which indicates waiting indefinitely. + * + * @param {number} timeout How long to wait for IE. + * @return {!Options} A self reference. + */ + browserAttachTimeout(timeout: number): Options; + + /** + * Configures whether to launch Internet Explorer using the CreateProcess API. + * If this option is not specified, IE is launched using IELaunchURL, if + * available. For IE 8 and above, this option requires the TabProcGrowth + * registry value to be set to 0. + * + * @param {boolean} force Whether to use the CreateProcess API. + * @return {!Options} A self reference. + */ + forceCreateProcessApi(force: boolean): Options; + + /** + * Specifies command-line switches to use when launching Internet Explorer. + * This is only valid when used with {@link #forceCreateProcessApi}. + * + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Configures whether proxies should be configured on a per-process basis. If + * not set, setting a {@linkplain #setProxy proxy} will configure the system + * proxy. The default behavior is to use the system proxy. + * + * @param {boolean} enable Whether to enable per-process proxy settings. + * @return {!Options} A self reference. + */ + usePerProcessProxy(enable: boolean): Options; + + /** + * Configures whether to clear the cache, cookies, history, and saved form data + * before starting the browser. _Using this capability will clear session data + * for all running instances of Internet Explorer, including those started + * manually._ + * + * @param {boolean} cleanSession Whether to clear all session data on startup. + * @return {!Options} A self reference. + */ + ensureCleanSession(cleanSession: boolean): Options; + + /** + * Sets the path to the log file the driver should log to. + * @param {string} file The log file path. + * @return {!Options} A self reference. + */ + setLogFile(file: string): Options; + + /** + * Sets the IEDriverServer's logging {@linkplain Level level}. + * @param {Level} level The logging level. + * @return {!Options} A self reference. + */ + setLogLevel(level: webdriver.logging.Level): Options; + + /** + * Sets the IP address of the driver's host adapter. + * @param {string} host The IP address to use. + * @return {!Options} A self reference. + */ + setHost(host: string): Options; + + /** + * Sets the path of the temporary data directory to use. + * @param {string} path The log file path. + * @return {!Options} A self reference. + */ + setExtractPath(path: string): Options; + + /** + * Sets whether the driver should start in silent mode. + * @param {boolean} silent Whether to run in silent mode. + * @return {!Options} A self reference. + */ + silent(silent: boolean): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + +} + +declare namespace opera { + /** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the operadriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the operadriver + * cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the OperaDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; + } + + /** + * Sets the default service to use for new OperaDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): any; + + /** + * Returns the default OperaDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a OperaDriver executable found on the system PATH. + * @return {!remote.DriverService} The default OperaDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ + class Options { + /** + * Extracts the OperaDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The OperaDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Add additional command line arguments to use when launching the Opera + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Add additional extensions to install when launching Opera. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: Array): Options; + + /** + * Sets the path to the Opera binary to use. On Mac OS X, this path should + * reference the actual Opera executable, not just the application binary. The + * binary path be absolute or relative to the operadriver server executable, but + * it must exist on the machine that will launch Opera. + * + * @param {string} path The path to the Opera binary to use. + * @return {!Options} A self reference. + */ + setOperaBinaryPath(path: string): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + } + + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace remote { + /** + * A record object that defines the configuration options for a DriverService + * instance. + * + * @record + */ + interface ServiceOptions {} + + /** + * Manages the life and death of a native executable WebDriver server. + * + * It is expected that the driver server implements the + * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. + * Furthermore, the managed server should support multiple concurrent sessions, + * so that this class may be reused for multiple clients. + */ + class DriverService { + /** + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. + */ + constructor(executable: string, options: ServiceOptions); + + /** + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. + */ + address(): webdriver.promise.Promise; + + /** + * Returns whether the underlying process is still running. This does not take + * into account whether the process is in the process of shutting down. + * @return {boolean} Whether the underlying service process is running. + */ + isRunning(): boolean; + + /** + * Starts the server if it is not already running. + * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the + * server to start accepting requests. Defaults to 30 seconds. + * @return {!promise.Promise} A promise that will resolve + * to the server's base URL when it has started accepting requests. If the + * timeout expires before the server has started, the promise will be + * rejected. + */ + start(opt_timeoutMs?: number): webdriver.promise.Promise; + + /** + * Stops the service if it is not currently running. This function will kill + * the server immediately. To synchronize with the active control flow, use + * {@link #stop()}. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + kill(): webdriver.promise.Promise; + + /** + * Schedules a task in the current control flow to stop the server if it is + * currently running. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + stop(): webdriver.promise.Promise; + } +} + +declare namespace safari { + class Server {} + + /** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ + function findSafariExecutable(): any; + + /** + * @param {string} serverUrl The URL to connect to. + * @return {!Promise} A promise for the path to a file that Safari can + * open on start-up to trigger a new connection to the WebSocket server. + */ + function createConnectFile(serverUrl: string): any; + + /** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ + function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; + + /** @return {string} . */ + function getRandomString(): string; + + /** + * @implements {command.Executor} + */ + class CommandExecutor { + } + + /** + * Configuration options specific to the {@link Driver SafariDriver}. + */ + class Options { + /** + * Extracts the SafariDriver specific options from the given capabilities + * object. + * @param {!Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + /** + * Sets whether to force Safari to start with a clean session. Enabling this + * option will cause all global browser data to be deleted. + * @param {boolean} clean Whether to make sure the session has no cookies, + * cache entries, local storage, or databases. + * @return {!Options} A self reference. + */ + setCleanSession(clean: boolean): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Converts this options instance to a {@link Capabilities} object. + * @param {Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + + /** + * A WebDriver client for Safari. This class should never be instantiated + * directly; instead, use the {@linkplain ./builder.Builder Builder}: + * + * var driver = new Builder() + * .forBrowser('safari') + * .build(); + * + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|Capabilities)=} opt_config The configuration + * options for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow to create + * the driver under. + */ + constructor(opt_config?: Options|webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + + } } declare namespace webdriver { namespace error { - interface IErrorCode { - SUCCESS: number; + class IError extends Error { + constructor(opt_error?: string); - NO_SUCH_ELEMENT: number; - NO_SUCH_FRAME: number; - UNKNOWN_COMMAND: number; - UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. - STALE_ELEMENT_REFERENCE: number; - ELEMENT_NOT_VISIBLE: number; - INVALID_ELEMENT_STATE: number; - UNKNOWN_ERROR: number; - ELEMENT_NOT_SELECTABLE: number; - JAVASCRIPT_ERROR: number; - XPATH_LOOKUP_ERROR: number; - TIMEOUT: number; - NO_SUCH_WINDOW: number; - INVALID_COOKIE_DOMAIN: number; - UNABLE_TO_SET_COOKIE: number; - MODAL_DIALOG_OPENED: number; - UNEXPECTED_ALERT_OPEN: number; - NO_SUCH_ALERT: number; - NO_MODAL_DIALOG_OPEN: number; - SCRIPT_TIMEOUT: number; - INVALID_ELEMENT_COORDINATES: number; - IME_NOT_AVAILABLE: number; - IME_ENGINE_ACTIVATION_FAILED: number; - INVALID_SELECTOR_ERROR: number; - SESSION_NOT_CREATED: number; - MOVE_TARGET_OUT_OF_BOUNDS: number; - SQL_DATABASE_ERROR: number; - INVALID_XPATH_SELECTOR: number; - INVALID_XPATH_SELECTOR_RETURN_TYPE: number; - // The following error codes are derived straight from HTTP return codes. - METHOD_NOT_ALLOWED: number; + code(): number; } - var ErrorCode: IErrorCode; + /** + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } /** - * Error extension that includes error status codes from the WebDriver wire - * protocol: - * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes - * - * @extends {Error} + * An attempt was made to select an element that cannot be selected. */ - class Error { + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Constructors + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * @param {!bot.ErrorCode} code The error's status code. - * @param {string=} opt_message Optional error message. - * @constructor - */ - constructor(code: number, opt_message?: string); + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Static Properties + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Status strings enumerated in the W3C WebDriver working draft. - * @enum {string} - * @see http://www.w3.org/TR/webdriver/#status-codes - */ - static State: { - ELEMENT_NOT_SELECTABLE: string; - ELEMENT_NOT_VISIBLE: string; - IME_ENGINE_ACTIVATION_FAILED: string; - IME_NOT_AVAILABLE: string; - INVALID_COOKIE_DOMAIN: string; - INVALID_ELEMENT_COORDINATES: string; - INVALID_ELEMENT_STATE: string; - INVALID_SELECTOR: string; - JAVASCRIPT_ERROR: string; - MOVE_TARGET_OUT_OF_BOUNDS: string; - NO_SUCH_ALERT: string; - NO_SUCH_DOM: string; - NO_SUCH_ELEMENT: string; - NO_SUCH_FRAME: string; - NO_SUCH_WINDOW: string; - SCRIPT_TIMEOUT: string; - SESSION_NOT_CREATED: string; - STALE_ELEMENT_REFERENCE: string; - SUCCESS: string; - TIMEOUT: string; - UNABLE_TO_SET_COOKIE: string; - UNEXPECTED_ALERT_OPEN: string; - UNKNOWN_COMMAND: string; - UNKNOWN_ERROR: string; - UNSUPPORTED_OPERATION: string; - }; + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Properties + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * This error's status code. - * @type {!bot.ErrorCode} - */ - code: number; + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @type {string} */ - state: string; + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - message: string; + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - name: string; + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - stack: string; + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Flag used for duck-typing when this code is embedded in a Firefox extension. - * This is required since an Error thrown in one component and then reported - * to another will fail instanceof checks in the second component. - * @type {boolean} - */ - isAutomationError: boolean; + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Methods + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @return {string} The string representation of this error. */ - toString(): string; + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); } } @@ -776,48 +1736,96 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string, level: ILevel): void; + setLevel(type: string|Type, level: Level|string|number): void; toJSON(): { [key: string]: string }; } - interface IType { - /** Logs originating from the browser. */ - BROWSER: string; - /** Logs from a WebDriver client. */ - CLIENT: string; - /** Logs from a WebDriver implementation. */ - DRIVER: string; - /** Logs related to performance. */ - PERFORMANCE: string; - /** Logs from the remote server. */ - SERVER: string; - } - /** * Common log types. * @enum {string} */ - var Type: IType; + enum Type { + /** Logs originating from the browser. */ + BROWSER, + /** Logs from a WebDriver client. */ + CLIENT, + /** Logs from a WebDriver implementation. */ + DRIVER, + /** Logs related to performance. */ + PERFORMANCE, + /** Logs from the remote server. */ + SERVER + } /** - * Logging levels. - * @enum {{value: number, name: webdriver.logging.LevelName}} + * Defines a message level that may be used to control logging output. + * + * @final */ - interface ILevel { - value: number; - name: string; - } + class Level { + name_: string; + value_: number; + /** + * @param {string} name the level's name. + * @param {number} level the level's numeric value. + */ + constructor(name: string, level: number); - interface ILevelValues { - ALL: ILevel; - DEBUG: ILevel; - INFO: ILevel; - WARNING: ILevel; - SEVERE: ILevel; - OFF: ILevel; - } + /** @override */ + toString(): string; - var Level: ILevelValues; + /** This logger's name. */ + name(): string; + + /** The numeric log level. */ + value(): number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } /** * Converts a level name or value to a {@link webdriver.logging.Level} value. @@ -827,75 +1835,209 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string): ILevel; - function getLevel(nameOrValue: number): ILevel; + function getLevel(nameOrValue: string|number): Level; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + level: string; + message: string; + timestamp: number; + type: string; } /** * A single log entry. */ class Entry { + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: Level|string|number, message: string, opt_timestamp?:number, opt_type?:string|Type); - //region Constructors + /** @type {!webdriver.logging.Level} */ + level: Level; - /** - * @param {(!webdriver.logging.Level|string)} level The entry level. - * @param {string} message The log message. - * @param {number=} opt_timestamp The time this entry was generated, in - * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the - * current time will be used. - * @param {string=} opt_type The log type, if known. - * @constructor - */ - constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); - constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + /** @type {string} */ + message: string; - //endregion + /** @type {number} */ + timestamp: number; - //region Public Properties + /** @type {string} */ + type: string; - /** @type {!webdriver.logging.Level} */ - level: ILevel; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } - /** @type {string} */ - message: string; + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, "foo" is considered the parent of + * the "foo.bar" and an ancestor of "foo.bar.baz". + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); - /** @type {number} */ - timestamp: number; + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; - /** @type {string} */ - type: string; + /** @return {string} the name of this logger. */ + getName(): string; - //endregion + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; - //region Static Methods + /** @return {Level} the log level for this logger. */ + getLevel(): Level; - /** - * Converts a {@link goog.debug.LogRecord} into a - * {@link webdriver.logging.Entry}. - * @param {!goog.debug.LogRecord} logRecord The record to convert. - * @param {string=} opt_type The log type. - * @return {!webdriver.logging.Entry} The converted entry. - */ - static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; - //endregion + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; - //region Methods + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; - //endregion + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string|Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; } } @@ -908,15 +2050,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * @param {!Array<(T|!ManagedPromise)>} arr An array of * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is + * @return {!ManagedPromise>} A promise that is * fulfilled with an array containing the fulfilled values of the * input array, or rejected with the same reason as the first * rejected value. * @template T */ - function all(arr: Promise[]): Promise; + function all(arr: Array>): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -939,9 +2081,9 @@ declare namespace webdriver { * Creates a new control flow. The provided callback will be invoked as the * first task within the new flow, with the flow as its sole argument. Returns * a promise that resolves to the callback result. - * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * @param {function(!ControlFlow)} callback The entry point * to the newly created flow. - * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * @return {!ManagedPromise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -966,7 +2108,7 @@ declare namespace webdriver { * Creates a promise that will be resolved at a set time in the future. * @param {number} ms The amount of time, in milliseconds, to wait before * resolving the promise. - * @return {!webdriver.promise.Promise} The promise. + * @return {!ManagedPromise} The promise. */ function delayed(ms: number): Promise; @@ -974,26 +2116,25 @@ declare namespace webdriver { * Calls a function for each element in an array, and if the function returns * true adds the element to a new array. * - *

    If the return value of the filter function is a promise, this function + * If the return value of the filter function is a promise, this function * will wait for it to be fulfilled before determining whether to insert the * element into the new array. * - *

    If the filter function throws or returns a rejected promise, the promise + * If the filter function throws or returns a rejected promise, the promise * returned by this function will be rejected with the same reason. Only the * first failure will be reported; all subsequent errors will be silently * ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ( - * boolean|webdriver.promise.Promise.)} fn The function + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function * to call for each element in the array. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; - function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; /** * Creates a new deferred object. @@ -1003,8 +2144,9 @@ declare namespace webdriver { /** * Creates a promise that has been resolved with the given value. - * @param {*=} opt_value The resolved value. - * @return {!webdriver.promise.Promise} The resolved promise. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T */ function fulfilled(opt_value?: T): Promise; @@ -1013,42 +2155,44 @@ declare namespace webdriver { * new array, which is used as the fulfillment value of the promise returned * by this function. * - *

    If the return value of the mapping function is a promise, this function + * If the return value of the mapping function is a promise, this function * will wait for it to be fulfilled before inserting it into the new array. * - *

    If the mapping function throws or returns a rejected promise, the + * If the mapping function throws or returns a rejected promise, the * promise returned by this function will be rejected with the same reason. * Only the first failure will be reported; all subsequent errors will be * silently ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The * function to call for each element in the array. This function should * expect three arguments (the element, the index, and the array itself. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise - function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Array|Promise>, fn: (self: any, type: any, index: number, array: any[]) => any, opt_self?: any): Promise /** * Creates a promise that has been rejected with the given reason. * @param {*=} opt_reason The rejection reason; may be any value, but is * usually an Error or a string. - * @return {!webdriver.promise.Promise} The rejected promise. + * @return {!ManagedPromise} The rejected promise. + * @template T */ - function rejected(opt_reason?: any): Promise; + function rejected(opt_reason?: any): Promise; /** - * Wraps a function that is assumed to be a node-style callback as its final - * argument. This callback takes two arguments: an error value (which will be + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be * null if the call succeeded), and the success value as the second argument. - * If the call fails, the returned promise will be rejected, otherwise it will - * be resolved with the result. + * The callback will the resolve or reject the returned promise, based on its + * arguments. * @param {!Function} fn The function to wrap. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the * result of the provided function's callback. */ function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; @@ -1059,37 +2203,35 @@ declare namespace webdriver { * fulfilled value back into {@code next}. Likewise, if a yielded promise is * rejected, the rejection error will be passed to {@code throw}. * - *

    Example 1: the Fibonacci Sequence. - *

    
    -         * webdriver.promise.consume(function* fibonacci() {
    -         *   var n1 = 1, n2 = 1;
    -         *   for (var i = 0; i < 4; ++i) {
    -         *     var tmp = yield n1 + n2;
    -         *     n1 = n2;
    -         *     n2 = tmp;
    -         *   }
    -         *   return n1 + n2;
    -         * }).then(function(result) {
    -         *   console.log(result);  // 13
    -         * });
    -         * 
    + * __Example 1:__ the Fibonacci Sequence. * - *

    Example 2: a generator that throws. - *

    
    -         * webdriver.promise.consume(function* () {
    -         *   yield webdriver.promise.delayed(250).then(function() {
    -         *     throw Error('boom');
    -         *   });
    -         * }).thenCatch(function(e) {
    -         *   console.log(e.toString());  // Error: boom
    -         * });
    -         * 
    + * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); * * @param {!Function} generatorFn The generator function to execute. * @param {Object=} opt_self The object to use as "this" when invoking the * initial generator. * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * @return {!ManagedPromise} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -1104,10 +2246,9 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!webdriver.promise.Promise} A new promise. + * @return {!ManagedPromise} A new promise. */ - function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; - function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: T|Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; /** * Returns a promise that will be resolved with the input value in a @@ -1120,19 +2261,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * webdriver.promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * @return {!ManagedPromise} A promise for a fully resolved version * of the input value. */ function fullyResolved(value: any): Promise; /** * Changes the default flow to use when no others are active. - * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @param {!ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -1141,265 +2282,181 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. - * - * @extends {goog.debug.Error} - * @final */ - class CancellationError { - /** - * @param {string=} opt_msg The cancellation message. - * @constructor - */ - constructor(opt_msg?: string); - - name: string; - message: string; + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); } interface IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } catch (ex) {
    -             *     console.error(ex);
    -             *   }
                  *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } finally {
    -             *     cleanUp();
    -             *   }
    -             *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenFinally(cleanUp);
    -             * 
    - * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *
    
    -             *   try {
    -             *     throw Error('one');
    -             *   } finally {
    -             *     throw Error('two');  // Hides Error: one
    -             *   }
    -             *
    -             *   webdriver.promise.rejected(Error('one'))
    -             *       .thenFinally(function() {
    -             *         throw Error('two');  // Hides Error: one
    -             *       });
    -             * 
    - * - * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: () => any): Promise; + catch(errback: Function): Promise; } /** - * Thenable is a promise-like object with a {@code then} method which may be - * used to schedule callbacks on a promised value. - * - * @interface - * @template T - */ + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ class Thenable implements IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } catch (ex) {
    -             *     console.error(ex);
    -             *   }
                  *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - + catch(errback: Function): Promise; /** * Registers a listener to invoke when this promise is resolved, regardless * of whether the promise's value was successfully computed. This function * is synonymous with the {@code finally} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } finally {
    -             *     cleanUp();
    -             *   }
                  *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenFinally(cleanUp);
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } * - * Note: similar to the {@code finally} clause, if the registered + * // Asynchronous promise API: + * doAsynchronousWork().finally(cleanUp); + * + * __Note:__ similar to the {@code finally} clause, if the registered * callback returns a rejected promise or throws an error, it will silently * replace the rejection error (if any) from this promise: - *
    
    -             *   try {
    -             *     throw Error('one');
    -             *   } finally {
    -             *     throw Error('two');  // Hides Error: one
    -             *   }
                  *
    -             *   webdriver.promise.rejected(Error('one'))
    -             *       .thenFinally(function() {
    -             *         throw Error('two');  // Hides Error: one
    -             *       });
    -             * 
    + * try { + * throw Error('one'); + * } finally { + * throw Error('two'); // Hides Error: one + * } * + * promise.rejected(Error('one')) + * .finally(function() { + * throw Error('two'); // Hides Error: one + * }); * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @param {function(): (R|IThenable)} callback The function to call when + * this promise is resolved. + * @return {!ManagedPromise} A promise that will be fulfilled * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + finally(callback: Function): Promise; /** * Adds a property to a class prototype to allow runtime checks of whether - * instances of that class implement the Thenable interface. This function will - * also ensure the prototype's {@code then} function is exported from compiled - * code. - * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * instances of that class implement the Thenable interface. This function + * will also ensure the prototype's {@code then} function is exported from + * compiled code. + * @param {function(new: Thenable, ...?)} ctor The * constructor whose prototype to modify. */ static addImplementation(ctor: Function): void; - /** - * Checks if an object has been tagged for implementing the Thenable interface - * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * Checks if an object has been tagged for implementing the Thenable + * interface as defined by {@link Thenable.addImplementation}. * @param {*} object The object to test. * @return {boolean} Whether the object is an implementation of the Thenable * interface. @@ -1432,12 +2489,11 @@ declare namespace webdriver { * function((T|IThenable|Thenable)=), * function(*=))} resolver * Function that is invoked immediately to begin computation of this - * promise's value. The function should accept a pair of callback functions, - * one for fulfilling the promise and another for rejecting it. - * @param {promise.ControlFlow=} opt_flow The control flow + * promise's value. The function should accept a pair of callback + * functions, one for fulfilling the promise and another for rejecting it. + * @param {ControlFlow=} opt_flow The control flow * this instance was created under. Defaults to the currently active flow. - * @constructor - */ + */ constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); constructor(); // For angular-protractor/angular-protractor-tests.ts @@ -1450,7 +2506,7 @@ declare namespace webdriver { * {@code Error}, one will be created using the value's string * representation. */ - cancel(reason: any): void; + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; @@ -1468,23 +2524,7 @@ declare namespace webdriver { * @return A new promise which will be resolved * with the result of the invoked callback. */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. - * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: Function, opt_errback?: Function): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -1512,6 +2552,31 @@ declare namespace webdriver { */ thenCatch(errback: (error: any) => any): Promise; + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + /** * Registers a listener to invoke when this promise is resolved, regardless @@ -1552,7 +2617,7 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + thenFinally(callback: Function): Promise; //endregion } @@ -1791,107 +2856,6 @@ declare namespace webdriver { } } - namespace stacktrace { - /** - * Class representing one stack frame. - */ - class Frame { - /** - * @param {(string|undefined)} context Context object, empty in case of global - * functions or if the browser doesn't provide this information. - * @param {(string|undefined)} name Function name, empty in case of anonymous - * functions. - * @param {(string|undefined)} alias Alias of the function if available. For - * example the function name will be 'c' and the alias will be 'b' if the - * function is defined as a.b = function c() {};. - * @param {(string|undefined)} path File path or URL including line number and - * optionally column number separated by colons. - * @constructor - */ - constructor(context?: string, name?: string, alias?: string, path?: string); - - /** - * @return {string} The function name or empty string if the function is - * anonymous and the object field which it's assigned to is unknown. - */ - getName(): string; - - - /** - * @return {string} The url or empty string if it is unknown. - */ - getUrl(): string; - - - /** - * @return {number} The line number if known or -1 if it is unknown. - */ - getLine(): number; - - - /** - * @return {number} The column number if known and -1 if it is unknown. - */ - getColumn(): number; - - - /** - * @return {boolean} Whether the stack frame contains an anonymous function. - */ - isAnonymous(): boolean; - - - /** - * Converts this frame to its string representation using V8's stack trace - * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - * @return {string} The string representation of this frame. - * @override - */ - toString(): string; - } - - /** - * Stores a snapshot of the stack trace at the time this instance was created. - * The stack trace will always be adjusted to exclude this function call. - */ - class Snapshot { - /** - * @param {number=} opt_slice The number of frames to remove from the top of - * the generated stack trace. - * @constructor - */ - constructor(opt_slice?: number); - - /** - * @return {!Array.} The parsed stack trace. - */ - getStacktrace(): Frame[]; - } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - namespace until { /** * Defines a condition to @@ -1915,32 +2879,31 @@ declare namespace webdriver { /** * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as: - *
      - *
    1. A numeric index into {@code window.frames} for the currently selected - * frame. - *
    2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - *
    3. A locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - *
    + * to the designated frame. The target frame may be specified as * - *

    Upon successful resolution of this condition, the driver will be left + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + * 3. a locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + * + * Upon successful resolution of this condition, the driver will be left * focused on the new frame. * - * @param {!(number|webdriver.WebElement| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * @param {!(number|./webdriver.WebElement|By| + * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame * The frame identifier. - * @return {!until.Condition.} A new condition. + * @return {!Condition} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|By|((webdriver: WebDriver)=>WebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the * returned promise will be fulfilled with the handle for the opened alert. * - * @return {!until.Condition.} The new condition. + * @return {!Condition} The new condition. */ function alertIsPresent(): Condition; @@ -2000,13 +2963,12 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. + * {@link ./webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. + * @param {!(By|Function)} locator The locator to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator|By.Hash|Function): Condition; + function elementLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -2039,7 +3001,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -2053,7 +3015,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator|By.Hash|Function): Condition; + function elementsLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -2061,7 +3023,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -2080,7 +3042,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function titleIs(title: string): Condition; @@ -2105,18 +3067,18 @@ declare namespace webdriver { } /** - * Enumeration of the buttons used in the advanced interactions API. - * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. - * @enum {number} + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} */ - interface IButton { - LEFT: number; - MIDDLE: number; - RIGHT: number; + enum Button { + LEFT, + MIDDLE, + RIGHT, } - var Button: IButton; - /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -2124,102 +3086,86 @@ declare namespace webdriver { * * @enum {string} */ - interface IKey { - NULL: string; - CANCEL: string; // ^break - HELP: string; - BACK_SPACE: string; - TAB: string; - CLEAR: string; - RETURN: string; - ENTER: string; - SHIFT: string; - CONTROL: string; - ALT: string; - PAUSE: string; - ESCAPE: string; - SPACE: string; - PAGE_UP: string; - PAGE_DOWN: string; - END: string; - HOME: string; - ARROW_LEFT: string; - LEFT: string; - ARROW_UP: string; - UP: string; - ARROW_RIGHT: string; - RIGHT: string; - ARROW_DOWN: string; - DOWN: string; - INSERT: string; - DELETE: string; - SEMICOLON: string; - EQUALS: string; + enum Key { + NULL, + CANCEL, // ^break + HELP, + BACK_SPACE, + TAB, + CLEAR, + RETURN, + ENTER, + SHIFT, + CONTROL, + ALT, + PAUSE, + ESCAPE, + SPACE, + PAGE_UP, + PAGE_DOWN, + END, + HOME, + ARROW_LEFT, + LEFT, + ARROW_UP, + UP, + ARROW_RIGHT, + RIGHT, + ARROW_DOWN, + DOWN, + INSERT, + DELETE, + SEMICOLON, + EQUALS, - NUMPAD0: string; // number pad keys - NUMPAD1: string; - NUMPAD2: string; - NUMPAD3: string; - NUMPAD4: string; - NUMPAD5: string; - NUMPAD6: string; - NUMPAD7: string; - NUMPAD8: string; - NUMPAD9: string; - MULTIPLY: string; - ADD: string; - SEPARATOR: string; - SUBTRACT: string; - DECIMAL: string; - DIVIDE: string; + NUMPAD0, // number pad keys + NUMPAD1, + NUMPAD2, + NUMPAD3, + NUMPAD4, + NUMPAD5, + NUMPAD6, + NUMPAD7, + NUMPAD8, + NUMPAD9, + MULTIPLY, + ADD, + SEPARATOR, + SUBTRACT, + DECIMAL, + DIVIDE, - F1: string; // function keys - F2: string; - F3: string; - F4: string; - F5: string; - F6: string; - F7: string; - F8: string; - F9: string; - F10: string; - F11: string; - F12: string; + F1, // function keys + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, - COMMAND: string; // Apple command key - META: string; // alias for Windows key + COMMAND, // Apple command key + META // alias for Windows key - /** - * Simulate pressing many keys at once in a "chord". Takes a sequence of - * {@link webdriver.Key}s or strings, appends each of the values to a string, - * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns - * the resultant string. - * - * Note: when the low-level webdriver key handlers see Keys.NULL, active - * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. - * - * @param {...string} var_args The key sequence to concatenate. - * @return {string} The null-terminated key sequence. - * @see http://code.google.com/p/webdriver/issues/detail?id=79 - */ - chord: (...var_args: string[]) => string; } - var Key: IKey; - /** * Class for defining sequences of complex user interactions. Each sequence * will not be executed until {@link #perform} is called. * - *

    Example:

    
    -     *   new webdriver.ActionSequence(driver).
    -     *       keyDown(webdriver.Key.SHIFT).
    -     *       click(element1).
    -     *       click(element2).
    -     *       dragAndDrop(element3, element4).
    -     *       keyUp(webdriver.Key.SHIFT).
    -     *       perform();
    -     * 
    + * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); * */ class ActionSequence { @@ -2247,14 +3193,18 @@ declare namespace webdriver { * Moves the mouse. The location to move to may be specified in terms of the * mouse's current location, an offset relative to the top-left corner of an * element, or an element (in which case the middle of the element is used). - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, as either another WebElement or an offset in pixels. - * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. - * Defaults to (0, 0). - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in + * pixels. + * @param {{x: number, y: number}=} opt_offset If the target {@code location} + * is defined as a {@link ./webdriver.WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. */ - mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; - mouseMove(location: ILocation): ActionSequence; + mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -2262,100 +3212,101 @@ declare namespace webdriver { * sequence or another. The behavior for out-of-order events (e.g. mouseDown, * click) is undefined. * - *

    If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

    sequence.mouseMove(element).mouseDown()
    * - *

    Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseDown() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseDown(opt_elementOrButton?: number): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Releases a mouse button. Behavior is undefined for calling this function * without a previous call to {@link #mouseDown}. * - *

    If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

    sequence.mouseMove(element).mouseUp()
    * - *

    Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseUp() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseUp(opt_elementOrButton?: number): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Convenience function for performing a "drag and drop" manuever. The target * element may be moved to the location of another element, or by an offset (in * pixels). - * @param {!webdriver.WebElement} element The element to drag. - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, either as another WebElement or an offset in pixels. - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {!./webdriver.WebElement} element The element to drag. + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. */ - dragAndDrop(element: WebElement, location: WebElement): ActionSequence; - dragAndDrop(element: WebElement, location: ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement|ILocation): ActionSequence; /** * Clicks a mouse button. * - *

    If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

    sequence.mouseMove(element).click()
    * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * sequence.mouseMove(element).click() + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - click(opt_elementOrButton?: number): ActionSequence; + click(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Double-clicks a mouse button. * - *

    If an element is provided, the mouse will first be moved to the center of + * If an element is provided, the mouse will first be moved to the center of * that element. This is equivalent to: - *

    sequence.mouseMove(element).doubleClick()
    * - *

    Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).doubleClick() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - doubleClick(opt_elementOrButton?: number): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -2366,7 +3317,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: string): ActionSequence; + keyDown(key: Key): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -2376,7 +3327,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: string): ActionSequence; + keyUp(key: Key): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -2387,7 +3338,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: any[]): ActionSequence; + sendKeys(...var_args: Array): ActionSequence; //endregion } @@ -2483,7 +3434,6 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; - /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -2494,7 +3444,6 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; - /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -2504,7 +3453,6 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; - /** * Flick starting at elem and moving by x and y at specified speed. * @@ -2516,26 +3464,29 @@ declare namespace webdriver { flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; } - interface IOffset { x: number; y: number; } - interface ISpeed { xspeed: number; yspeed: number; } - /** * Represents a modal dialog such as {@code alert}, {@code confirm}, or * {@code prompt}. Provides functions to retrieve the message displayed with * the alert, accept or dismiss the alert, and set the response text (in the * case of {@code prompt}). */ - interface Alert { + class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); //region Methods @@ -2547,6 +3498,18 @@ declare namespace webdriver { */ getText(): webdriver.promise.Promise; + /** + * Sets the username and password in an alert prompting for credentials (such + * as a Basic HTTP Auth prompt). This method will implicitly + * {@linkplain #accept() submit} the dialog. + * + * @param {string} username The username to send. + * @param {string} password The password to send. + * @return {!promise.Promise} A promise that will be resolved when this + * command has completed. + */ + authenticateAs(username: string, password: string): webdriver.promise.Promise; + /** * Accepts this alert. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -2580,47 +3543,27 @@ declare namespace webdriver { * serves as a forward proxy on an Alert, allowing calls to be scheduled * directly on this instance before the underlying Alert has been fulfilled. In * other words, the following two statements are equivalent: - *

    
    +     *
          *     driver.switchTo().alert().dismiss();
          *     driver.switchTo().alert().then(function(alert) {
          *       return alert.dismiss();
          *     });
    -     * 
    * - * @param {!webdriver.WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!webdriver.promise.Thenable.} alert A thenable - * that will be fulfilled with the promised alert. - * @constructor - * @extends {webdriver.Alert} - * @implements {webdriver.promise.Thenable.} + * @implements {promise.Thenable.} * @final */ - interface AlertPromise extends Alert, webdriver.promise.IThenable { + class AlertPromise extends Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!promise.Thenable} alert A thenable + * that will be fulfilled with the promised alert. + */ + constructor(driver: WebDriver, alert: webdriver.promise.Promise); } - /** - * An error returned to indicate that there is an unhandled modal dialog on the - * current page. - * @extends {bot.Error} - */ - interface UnhandledAlertError extends webdriver.error.Error { - //region Methods - - /** - * @return {string} The text displayed with the unhandled alert. - */ - getAlertText(): string; - - /** - * @return {!webdriver.Alert} The open alert. - * @deprecated Use {@link #getAlertText}. This method will be removed in - * 2.45.0. - */ - getAlert(): Alert; - - - //endregion + /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ + class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { } /** @@ -2630,7 +3573,9 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; + EDGE: string; FIREFOX: string; + IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -2651,6 +3596,45 @@ declare namespace webdriver { noProxy?: string; } + /** + * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment + * variables listed below may be used to override a builder's configuration, + * allowing quick runtime changes. + * + * - {@code SELENIUM_BROWSER}: defines the target browser in the form + * {@code browser[:version][:platform]}. + * + * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder + * instances. This environment variable should be set to a fully qualified + * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This + * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * + * - {@code SELENIUM_SERVER_JAR}: defines the path to the + * + * standalone Selenium server jar to use. The server will be started the + * first time a WebDriver instance and be killed when the process exits. + * + * Suppose you had mytest.js that created WebDriver with + * + * var driver = new webdriver.Builder() + * .forBrowser('chrome') + * .build(); + * + * This test could be made to use Firefox on the local machine by running with + * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to + * target Google Chrome on a remote machine, you can simply set the + * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ + * node mytest.js + * + * You could also use a local copy of the standalone Selenium server: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ + * node mytest.js + */ class Builder { //region Constructors @@ -2664,15 +3648,45 @@ declare namespace webdriver { //region Methods + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + /** * Creates a new WebDriver client based on this builder's current * configuration. * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * * @return {!webdriver.WebDriver} A new WebDriver instance. * @throws {Error} If the current configuration is invalid. + * @see #buildAsync() */ build(): WebDriver; + /** + * Creates a new WebDriver client based on this builder's current + * configuration. This method returns a promise that will not be fulfilled + * until the new browser session has been fully initialized. + * + * __Note:__ this method is purely a convenience wrapper around + * {@link #build()}. + * + * @return {!promise.Promise} A promise that will be + * fulfilled with the newly created WebDriver instance once the browser + * has been fully initialized. + * @see #build() + */ + buildAsync(): webdriver.promise.Promise; + /** * Configures the target browser for clients created by this instance. * Any calls to {@link #withCapabilities} after this function will @@ -2705,6 +3719,12 @@ declare namespace webdriver { */ getServerUrl(): string; + /** + * @return {?string} The URL of the proxy server to use for the WebDriver's + * HTTP connections, or `null` if not set. + */ + getWebDriverProxy(): string; + /** * Sets the default action to take with an unexpected alert before returning * an error. @@ -2735,6 +3755,17 @@ declare namespace webdriver { */ setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + /** + * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser + * for drivers created by this builder. Any proxy settings defined on the + * given options will take precedence over those set through + * {@link #setProxy}. + * + * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. + * @return {!Builder} A self reference. + */ + setEdgeOptions(options: edge.Options): Builder; + /** * Sets whether native events should be used. * @param {boolean} enabled Whether to enable native events. @@ -2753,6 +3784,16 @@ declare namespace webdriver { */ setFirefoxOptions(options: firefox.Options): Builder; + /** + * Set Internet Explorer specific {@linkplain ie.Options options} for drivers + * created by this builder. Any proxy settings defined on the given options + * will take precedence over those set through {@link #setProxy}. + * + * @param {!ie.Options} options The IEDriver options to use. + * @return {!Builder} A self reference. + */ + setIeOptions(options: ie.Options): Builder; + /** * Sets the logging preferences for the created session. Preferences may be * changed by repeated calls, or by calling {@link #withCapabilities}. @@ -2760,17 +3801,37 @@ declare namespace webdriver { * desired logging preferences. * @return {!Builder} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; - setLoggingPrefs(prefs: { [key: string]: string }): Builder; + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Builder; + + /** + * Sets Opera specific {@linkplain opera.Options options} for drivers created + * by this builder. Any logging or proxy settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs} and + * {@link #setProxy}, respectively. + * + * @param {!opera.Options} options The OperaDriver options to use. + * @return {!Builder} A self reference. + */ + setOperaOptions(options: opera.Options): Builder; /** * Sets the proxy configuration to use for WebDriver clients created by this * builder. Any calls to {@link #withCapabilities} after this function will * overwrite these settings. - * @param {!webdriver.ProxyConfig} config The configuration to use. + * @param {!capabilities.ProxyConfig} config The configuration to use. * @return {!Builder} A self reference. */ - setProxy(config: ProxyConfig): Builder; + setProxy(config: webdriver.ProxyConfig): Builder; + + /** + * Sets Safari specific {@linkplain safari.Options options} for drivers + * created by this builder. Any logging settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs}. + * + * @param {!safari.Options} options The Safari options to use. + * @return {!Builder} A self reference. + */ + setSafari(options: safari.Options): Builder; /** * Sets how elements should be scrolled into view for interaction. @@ -2793,6 +3854,16 @@ declare namespace webdriver { */ usingServer(url: string): Builder; + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + /** * Sets the desired capabilities when requesting a new session. This will * overwrite any previously set capabilities. @@ -2800,12 +3871,149 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Capabilities): Builder; - withCapabilities(capabilities: any): Builder; + withCapabilities(capabilities: Object|Capabilities): Builder; //endregion } + /** + * Describes a mechanism for locating an element on the page. + * @final + */ + class By { + + /** + * @param {string} using the name of the location strategy to use. + * @param {string} value the value to search for. + */ + constructor(using: string, value: string); + + /** + * Locates elements that have a specific class name. + * + * @param {string} name The class name to search for. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + static className(name: string): By; + + /** + * Locates elements using a CSS selector. + * + * @param {string} selector The CSS selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + static css(selector: string): By; + + /** + * Locates eleemnts by the ID attribute. This locator uses the CSS selector + * `*[id="$ID"]`, _not_ `document.getElementById`. + * + * @param {string} id The ID to search for. + * @return {!By} The new locator. + */ + static id(id: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} matches the given + * string. + * + * @param {string} text The link text to search for. + * @return {!By} The new locator. + */ + static linkText(text: string): By; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!./webdriver.WebDriver): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string|Function, ...var_args: Array): (webdriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose `name` attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!By} The new locator. + */ + static name(name: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} contains the given + * substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!By} The new locator. + */ + static partialLinkText(text: string): By; + + /** + * Locates elements with a given tag name. + * + * @param {string} name The tag name to search for. + * @return {!By} The new locator. + * @deprecated Use {@link By.css() By.css(tagName)} instead. + */ + static tagName(name: string): By; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector `//div`, WebDriver will search from the document root + * regardless of whether the locator was used with a WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + static xpath(xpath: string): By; + + /** @override */ + toString(): string; + } + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type ByHash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + /** * Common webdriver capability keys. * @enum {string} @@ -2876,7 +4084,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -2910,8 +4118,7 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities); - constructor(opt_other?: any); + constructor(opt_other?: Capabilities|Object); //endregion @@ -2927,8 +4134,7 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities): Capabilities; - merge(other: any): Capabilities; + merge(other: Capabilities|Object): Capabilities; /** * @param {string} key The capability to set. @@ -2946,9 +4152,7 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; - setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; - + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; /** * Sets the proxy configuration for this instance. @@ -3010,6 +4214,11 @@ declare namespace webdriver { */ static chrome(): Capabilities; + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + /** * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. */ @@ -3183,6 +4392,8 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -3241,19 +4452,47 @@ declare namespace webdriver { } /** - * Handles the execution of {@code webdriver.Command} objects. + * Handles the execution of WebDriver {@link Command commands}. + * @interface */ - interface CommandExecutor { - /** - * Executes the given {@code command}. If there is an error executing the - * command, the provided callback will be invoked with the offending error. - * Otherwise, the callback will be invoked with a null Error and non-null - * {@link bot.response.ResponseObject} object. - * @param {!webdriver.Command} command The command to execute. - * @param {function(Error, !bot.response.ResponseObject=)} callback the function - * to invoke when the command response is ready. - */ - execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + class Executor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * response object. + * + * @param {!Command} command The command to execute. + * @return {!promise.Promise} A promise that will be fulfilled with + * the command result. + */ + execute(command: Command): webdriver.promise.Promise + } + + /** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ + class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: webdriver.promise.Promise); + } + + /** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ + class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); } /** @@ -3283,39 +4522,42 @@ declare namespace webdriver { /** * Returns a mutable list of listeners for a specific type of event. * @param {string} type The type of event to retrieve the listeners for. - * @return {!Array.<{fn: !Function, oneshot: boolean, - * scope: (Object|undefined)}>} The registered listeners for - * the given event type. + * @return {!Set} The registered listeners for the given event + * type. */ - listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + listeners(type: string): any; /** * Registers a listener. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. - * @param {Object=} opt_scope The object in whose scope to invoke the listener. - * @return {!webdriver.EventEmitter} A self reference. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private */ - addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + addListener(type: string, fn: Function, opt_scope?:any, opt_oneshot?: boolean): EventEmitter; + /** * Registers a one-time listener which will be called only the first time an * event is emitted, after which it will be removed. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; + once(type: string, fn: any, opt_scope?: any): EventEmitter; /** * An alias for {@code #addListener()}. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + on(type: string, fn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -3340,14 +4582,20 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - interface WebDriverNavigation { + class Navigation { //region Constructors /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * webdriver.navigate() + * + * @see WebDriver#navigate() */ - new (driver: WebDriver): WebDriverNavigation; + constructor(driver: WebDriver); //endregion @@ -3397,14 +4645,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - interface WebDriverOptions { + class Options { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: webdriver.WebDriver): WebDriverOptions; + constructor(driver: webdriver.WebDriver); //endregion @@ -3417,13 +4665,13 @@ declare namespace webdriver { * @param {string=} opt_path The cookie path. * @param {string=} opt_domain The cookie domain. * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as - * a number, should be in milliseconds since midnight, January 1, 1970 UTC. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * cookie has been added to the page. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number|Date): webdriver.promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -3467,19 +4715,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): WebDriverLogs; + logs(): webdriver.Logs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): WebDriverTimeouts; + timeouts(): webdriver.Timeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): WebDriverWindow; + window(): webdriver.Window; //endregion } @@ -3487,14 +4735,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - interface WebDriverTimeouts { + class Timeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTimeouts; + constructor(driver: webdriver.WebDriver); //endregion @@ -3549,7 +4797,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - interface WebDriverWindow { + class Window { //region Constructors @@ -3557,7 +4805,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverWindow; + constructor(driver: webdriver.WebDriver); //endregion @@ -3612,7 +4860,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - interface WebDriverLogs { + class Logs { //region Constructors @@ -3620,7 +4868,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverLogs; + constructor(driver: webdriver.WebDriver); //endregion @@ -3640,7 +4888,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: string): webdriver.promise.Promise; + get(type: webdriver.logging.Type): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -3655,7 +4903,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - interface WebDriverTargetLocator { + class TargetLocator { //region Constructors @@ -3663,7 +4911,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTargetLocator; + constructor(driver: webdriver.WebDriver); //endregion @@ -3687,44 +4935,47 @@ declare namespace webdriver { /** * Schedules a command to switch the focus of all future commands to another - * frame on the page. - *

    - * If the frame is specified by a number, the command will switch to the frame - * by its (zero-based) index into the {@code window.frames} collection. - *

    - * If the frame is specified by a string, the command will select the frame by - * its name or ID. To select sub-frames, simply separate the frame names/IDs by - * dots. As an example, "main.child" will select the frame with the name "main" - * and then its child "child". - *

    - * If the specified frame can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. - * @param {string|number} nameOrIndex The frame locator. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified frame. + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. */ - frame(nameOrIndex: string): webdriver.promise.Promise; - frame(nameOrIndex: number): webdriver.promise.Promise; + frame(nameOrIndex: number|WebElement): webdriver.promise.Promise; /** * Schedules a command to switch the focus of all future commands to another * window. Windows may be specified by their {@code window.name} attribute or - * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). - *

    - * If the specificed window can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * * @param {string} nameOrHandle The name or window handle of the window to * switch focus to. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified window. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. */ window(nameOrHandle: string): webdriver.promise.Promise; /** - * Schedules a command to change focus to the active alert dialog. This command - * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal - * dialog is not currently open. - * @return {!webdriver.Alert} The open alert. + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. */ alert(): AlertPromise; @@ -3789,27 +5040,14 @@ declare namespace webdriver { //region Constructors /** - * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * @param {!(Session|promise.Promise)} session Either a * known session or a promise that will be resolved to a session. - * @param {!webdriver.CommandExecutor} executor The executor to use when - * sending commands to the browser. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. - * @constructor */ - constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - - //endregion - - //region Static Properties - - static Navigation: WebDriverNavigation; - static Options: WebDriverOptions; - static Timeouts: WebDriverTimeouts; - static Window: WebDriverWindow; - static Logs: WebDriverLogs; - static TargetLocator: WebDriverTargetLocator; + constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); //endregion @@ -3817,29 +5055,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!webdriver.CommandExecutor} executor Command executor to use when - * querying for session details. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. * @param {string} sessionId ID of the session to attach to. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver - * commands should execute under. Defaults to the - * {@link webdriver.promise.controlFlow() currently active} control flow. - * @return {!webdriver.WebDriver} A new client for the specified session. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. */ - static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. - * @param {!webdriver.CommandExecutor} executor The executor to create the new - * session with. - * @param {!webdriver.Capabilities} desiredCapabilities The desired + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * @param {promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. - * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * Defaults to the {@link promise.controlFlow() currently active} * control flow. - * @return {!webdriver.WebDriver} The driver for the newly created session. + * @return {!WebDriver} The driver for the newly created session. */ - static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -3852,20 +5090,22 @@ declare namespace webdriver { controlFlow(): webdriver.promise.ControlFlow; /** - * Schedules a {@code webdriver.Command} to be executed by this driver's - * {@code webdriver.CommandExecutor}. - * @param {!webdriver.Command} command The command to schedule. + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. * @param {string} description A description of the command for debugging. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the command result. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T */ schedule(command: Command, description: string): webdriver.promise.Promise; /** - * Sets the {@linkplain webdriver.FileDetector file detector} that should be + * Sets the {@linkplain input.FileDetector file detector} that should be * used with this instance. - * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + * @param {input.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -3895,23 +5135,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * scheduled for execution until {@link actions.ActionSequence#perform} is * called. Example: - *

    
    -         *   driver.actions().
    -         *       mouseDown(element1).
    -         *       mouseMove(element2).
    -         *       mouseUp().
    -         *       perform();
    -         * 
    - * @return {!webdriver.ActionSequence} A new action sequence for this instance. + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. */ actions(): ActionSequence; /** * Creates a new touch sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.TouchSequence#perform} is + * scheduled for execution until {@link actions.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -3919,7 +5159,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + * @return {!actions.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -3961,8 +5201,7 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -4179,38 +5418,27 @@ declare namespace webdriver { * var e1 = driver.findElement(By.id('foo')); * var e2 = driver.findElement({id:'foo'}); * - * You may also provide a custom locator function, which takes as input - * this WebDriver instance and returns a {@link webdriver.WebElement}, or a - * promise that will resolve to a WebElement. For example, to find the first - * visible link on a page, you could write: + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: * * var link = driver.findElement(firstVisibleLink); * * function firstVisibleLink(driver) { * var links = driver.findElements(By.tagName('a')); - * return webdriver.promise.filter(links, function(link) { - * return links.isDisplayed(); - * }).then(function(visibleLinks) { - * return visibleLinks[0]; + * return promise.filter(links, function(link) { + * return link.isDisplayed(); * }); * } * - * When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The - * locator to use. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -4219,35 +5447,36 @@ declare namespace webdriver { * document the driver is currently focused on. Otherwise, the function will * test if at least one element can be found with the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element| - * Function)} locatorOrElement The locator to use, or the actual - * DOM element to be located by the server. - * @return {!webdriver.promise.Promise.} A promise that will resolve + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); */ - isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; + isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to * return a screenshot of the following, in order of preference: - *
      - *
    1. Entire page - *
    2. Current window - *
    3. Visible portion of the current frame - *
    4. The screenshot of the entire display containing the browser - *
    * - * @return {!webdriver.promise.Promise.} A promise that will be + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; @@ -4256,45 +5485,25 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): WebDriverOptions; + manage(): webdriver.Options; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): WebDriverNavigation; + navigate(): Navigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): WebDriverTargetLocator; + switchTo(): webdriver.TargetLocator; //endregion } interface IWebElementId { - ELEMENT: string; - } - - /** - * Defines an object that can be asynchronously serialized to its WebDriver - * wire representation. - * - * @constructor - * @template T - */ - interface Serializable { - /** - * Returns either this instance's serialized represention, if immediately - * available, or a promise for its serialized representation. This function is - * conceptually equivalent to objects that have a {@code toJSON()} property, - * except the serialize() result may be a promise or an object containing a - * promise (which are not directly JSON friendly). - * - * @return {!(T|IThenable.)} This instance's serialized wire format. - */ - serialize(): T|webdriver.promise.IThenable; + [ELEMENT:string]: string; } /** @@ -4554,7 +5763,7 @@ declare namespace webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4565,7 +5774,7 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4576,10 +5785,9 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; } - /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -4600,7 +5808,6 @@ declare namespace webdriver { serialize(): T|webdriver.promise.IThenable; } - /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@link webdriver.WebDriver} instance, or by searching @@ -4626,35 +5833,59 @@ declare namespace webdriver { */ class WebElement implements Serializable { /** - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!(webdriver.promise.Promise.| - * webdriver.WebElement.Id)} id The server-assigned opaque ID for the - * underlying DOM element. - * @constructor + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. */ - constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); /** - * Wire protocol definition of a WebElement ID. - * @typedef {{ELEMENT: string}} - * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. */ - static Id: IWebElementId; + static buildId(id: string, opt_noLegacy?: boolean): Object; /** - * The property key used in the wire protocol to indicate that a JSON object - * contains the ID of a WebElement. - * @type {string} - * @const + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. */ - static ELEMENT_KEY: string; + static extractId(obj: IWebElementId): string; + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; /** * @return {!webdriver.WebDriver} The parent driver for this instance. */ - getDriver(): WebDriver; + getDriver(): webdriver.WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): webdriver.promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; /** * Schedule a command to find a descendant of this element. If the element @@ -4688,35 +5919,40 @@ declare namespace webdriver { * }); * } * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this * element that matches the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.} A promise that will be + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that * match the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the elements. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -4727,7 +5963,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * instance. + * promsieinstance. * * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is * processed in the keysequence, that key state is toggled until one of the @@ -4799,7 +6035,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!webdriver.promise.Promise.} A promise that will be + * @return {!promise.Promise} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -4885,10 +6121,10 @@ declare namespace webdriver { submit(): webdriver.promise.Promise; /** - * Schedules a command to clear the {@code value} of this element. This command - * has no effect if the underlying DOM element is neither a text INPUT element + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise.} A promise that will be resolved + * @return {!promise.Promise} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -4900,6 +6136,18 @@ declare namespace webdriver { */ isDisplayed(): webdriver.promise.Promise; + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; + /** * Schedules a command to retrieve the outer HTML of this element. * @return {!webdriver.promise.Promise.} A promise that will be @@ -4907,25 +6155,6 @@ declare namespace webdriver { */ getOuterHtml(): webdriver.promise.Promise; - /** - * @return {!webdriver.promise.Promise.} A promise - * that resolves to this element's JSON representation as defined by the - * WebDriver wire protocol. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol - */ - getId(): webdriver.promise.Promise; - - /** - * Returns the raw ID string ID for this element. - * @return {!webdriver.promise.Promise} A promise that resolves to this - * element's raw ID as a string value. - * @package - */ - getRawId(): webdriver.promise.Promise; - - /** @override */ - serialize(): webdriver.promise.Promise; - /** * Schedules a command to retrieve the inner HTML of this element. * @return {!webdriver.promise.Promise} A promise that will be resolved with the @@ -4933,14 +6162,8 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** - * Compares to WebElements for equality. - * @param {!webdriver.WebElement} a A WebElement. - * @param {!webdriver.WebElement} b A WebElement. - * @return {!webdriver.promise.Promise} A promise that will be resolved to - * whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + /** @override */ + serialize(): webdriver.promise.Promise; } /** @@ -4966,6 +6189,14 @@ declare namespace webdriver { * @final */ class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); + /** * Cancels the computation of this promise's value, rejecting the promise in the * process. This method is a no-op if the promise has alreayd been resolved. @@ -5075,191 +6306,31 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; - } - namespace By { /** - * Locates elements that have a specific class name. The returned locator - * is equivalent to searching for elements with the CSS selector ".clazz". + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: * - * @param {string} className The class name to search for. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes - * @see http://www.w3.org/TR/CSS2/selector.html#class-html - */ - function className(value: string): Locator; - - /** - * Locates elements using a CSS selector. For browsers that do not support - * CSS selectors, WebDriver implementations may return an - * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An - * implementation may, however, emulate the CSS selector API. + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {string} selector The CSS selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - function css(value: string): Locator; - - /** - * Locates an element by its ID. + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); * - * @param {string} id The ID to search for. - * @return {!webdriver.Locator} The new locator. + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R */ - function id(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} matches the given string. - * - * @param {string} text The link text to search for. - * @return {!webdriver.Locator} The new locator. - */ - function linkText(value: string): Locator; - - /** - * Locates an elements by evaluating a - * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. - * The result of this expression must be an element or list of elements. - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, - * JavaScript-based locator function. - */ - function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose {@code name} attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!webdriver.Locator} The new locator. - */ - function name(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} contains the given substring. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - */ - function partialLinkText(value: string): Locator; - - /** - * Locates elements with a given tag name. The returned locator is - * equivalent to using the - * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) - * DOM function. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html - */ - function tagName(value: string): Locator; - - /** - * Locates elements matching a XPath selector. Care should be taken when - * using an XPath selector with a {@link webdriver.WebElement} as WebDriver - * will respect the context in the specified in the selector. For example, - * given the selector {@code "//div"}, WebDriver will search from the - * document root regardless of whether the locator was used with a - * WebElement. - * - * @param {string} xpath The XPath selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - function xpath(value: string): Locator; - - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type Hash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - } - - /** - * An element locator. - */ - class Locator { - /** - * An element locator. - * @param {string} using The type of strategy to use for this locator. - * @param {string} value The search target of this locator. - * @constructor - */ - constructor(using: string, value: string); - - - /** - * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. - * @type {!Object.} - * @const - */ - static Strategy: { - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - js: typeof webdriver.By.js; - linkText: typeof webdriver.By.linkText; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - }; - - /** - * Verifies that a {@code value} is a valid locator to use for searching for - * elements on the page. - * - * @param {*} value The value to check is a valid locator. - * @return {!(webdriver.Locator|Function)} A valid locator object or function. - * @throws {TypeError} If the given value is an invalid locator. - */ - static checkLocator(value: any): Locator | Function; - - /** - * The search strategy to use when searching for an element. - * @type {string} - */ - using: string; - - /** - * The search target for this locator. - * @type {string} - */ - value: string; - - /** @return {string} String representation of this locator. */ - toString(): string; + catch(errback: Function): webdriver.promise.Promise; } /** @@ -5275,8 +6346,7 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities); - constructor(id: string, capabilities: any); + constructor(id: string, capabilities: Capabilities|Object); //endregion @@ -5290,7 +6360,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): Capabilities; + getCapabilities(): webdriver.Capabilities; /** * Retrieves the value of a specific capability. @@ -5376,10 +6446,6 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } -declare module 'selenium-webdriver/firefox' { - export = firefox; -} - declare module 'selenium-webdriver/executors' { export = executors; } diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index 1ab39ba02a..345a8efc5b 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -3,7 +3,7 @@ function TestChromeDriver() { var driver: chrome.Driver = new chrome.Driver(); driver = new chrome.Driver(webdriver.Capabilities.chrome()); - driver = new chrome.Driver(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -31,6 +31,7 @@ function TestChromeOptions() { options = options.setUserPreferences("preferences"); var capabilities: webdriver.Capabilities = options.toCapabilities(); capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); + var values: chrome.IOptionsValues = options.toJSON(); } function TestServiceBuilder() { @@ -51,7 +52,7 @@ function TestServiceBuilder() { function TestChromeModule() { var service: any = chrome.getDefaultService(); - chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); + chrome.setDefaultService({}); } function TestBinary() { @@ -65,8 +66,8 @@ function TestBinary() { function TestFirefoxDriver() { var driver: firefox.Driver = new firefox.Driver(); - driver = new firefox.Driver(webdriver.Capabilities.firefox()); - driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + driver = new chrome.Driver(webdriver.Capabilities.firefox()); + driver = new chrome.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -81,6 +82,7 @@ function TestFirefoxOptions() { options = options.setProfile(new firefox.Profile()); options = options.setProxy({ proxyType: "proxy" }); var capabilities: webdriver.Capabilities = options.toCapabilities(); + var capabilities: webdriver.Capabilities = options.toCapabilities({}); } function TestFirefoxProfile() { @@ -106,7 +108,7 @@ function TestFirefoxProfile() { } function TestExecutors() { - var exec: webdriver.Executor = executors.createExecutor("url"); + var exec: webdriver.CommandExecutor = executors.createExecutor("url"); var promise: webdriver.promise.Promise; exec = executors.createExecutor(promise); } @@ -142,9 +144,7 @@ function TestActionSequence() { build(); var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); - var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); - var promise: webdriver.promise.Promise; - element = new webdriver.WebElement(driver, promise); + var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); // Click sequence = sequence.click(); @@ -187,6 +187,7 @@ function TestActionSequence() { // SendKeys sequence = sequence.sendKeys("A", "B", "C"); + sequence = sequence.sendKeys(["A", "B", "C"]); sequence.perform().then(function () { }); } @@ -195,7 +196,7 @@ function TestTouchSequence() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); @@ -318,9 +319,9 @@ function TestCommand() { command = command.setParameters({ param: 123 }); } -function TestDeferredExecutor() { - var promise: webdriver.promise.Promise; - var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); +function TestCommandExecutor() { + var c: webdriver.CommandExecutor = { execute: function (command: webdriver.Command, callback: (error: Error, obj: any) => any) { } }; + c.execute(new webdriver.Command('name'), function (error: Error, response: any) { }); } function TestCommandName() { @@ -457,7 +458,7 @@ function TestEventEmitter() { } function TestKey() { - var key: webdriver.Key; + var key: string; key = webdriver.Key.ADD; key = webdriver.Key.ALT; @@ -519,15 +520,35 @@ function TestKey() { key = webdriver.Key.SUBTRACT; key = webdriver.Key.TAB; key = webdriver.Key.UP; + + key = webdriver.Key.chord(webdriver.Key.NUMPAD0, webdriver.Key.NUMPAD1); } -function TestBy() { +function TestLocator() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.By = new webdriver.By('class name', 'class'); + var locator: webdriver.Locator = new webdriver.Locator('class name', 'class'); + var locatorOrFn: webdriver.Locator|Function; + + locatorOrFn = webdriver.Locator.Strategy.className; + locatorOrFn = webdriver.Locator.Strategy.css; + locatorOrFn = webdriver.Locator.Strategy.id; + locatorOrFn = webdriver.Locator.Strategy.js; + locatorOrFn = webdriver.Locator.Strategy.linkText; + locatorOrFn = webdriver.Locator.Strategy.name; + locatorOrFn = webdriver.Locator.Strategy.partialLinkText; + locatorOrFn = webdriver.Locator.Strategy.tagName; + locatorOrFn = webdriver.Locator.Strategy.xpath; + + locatorOrFn = webdriver.Locator.checkLocator(locator); + locatorOrFn = webdriver.Locator.checkLocator({ className: 'class' }); + locatorOrFn = webdriver.Locator.checkLocator(Error); + + var using: string = locator.using; + var value: string = locator.value; var str: string = locator.toString(); locator = webdriver.By.className('class'); @@ -542,7 +563,7 @@ function TestBy() { // Can import "By" without import declarations var By = webdriver.By; - var locatorHash: webdriver.ByHash; + var locatorHash: webdriver.By.Hash; locatorHash = { className: 'class' }; locatorHash = { css: 'css' }; locatorHash = { id: 'id' }; @@ -570,7 +591,9 @@ function TestSession() { function TestUnhandledAlertError() { var someFunc = function (error: webdriver.UnhandledAlertError) { - var baseError: Error = error; + var baseError: webdriver.error.Error = error; + + var alert: webdriver.Alert = error.getAlert(); var str: string = error.getAlertText(); str = error.toString(); } @@ -591,7 +614,7 @@ function TestWebDriverLogs() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var logs: webdriver.Logs = new webdriver.Logs(driver); + var logs: webdriver.WebDriverLogs = new webdriver.WebDriver.Logs(driver); logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; logs.getAvailableLogTypes().then(function (types: string[]) { }); @@ -602,7 +625,7 @@ function TestWebDriverNavigation() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var navigation: webdriver.Navigation = new webdriver.Navigation(driver); + var navigation: webdriver.WebDriverNavigation = new webdriver.WebDriver.Navigation(driver); navigation.back().then(function () { }); navigation.forward().then(function () { }); @@ -615,7 +638,7 @@ function TestWebDriverOptions() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var options: webdriver.Options = new webdriver.Options(driver); + var options: webdriver.WebDriverOptions = new webdriver.WebDriver.Options(driver); var promise: webdriver.promise.Promise; // Add Cookie @@ -631,9 +654,9 @@ function TestWebDriverOptions() { options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); - var logs: webdriver.Logs = options.logs(); - var timeouts: webdriver.Timeouts = options.timeouts(); - var window: webdriver.Window = options.window(); + var logs: webdriver.WebDriverLogs = options.logs(); + var timeouts: webdriver.WebDriverTimeouts = options.timeouts(); + var window: webdriver.WebDriverWindow = options.window(); } function TestWebDriverTargetLocator() { @@ -641,12 +664,13 @@ function TestWebDriverTargetLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); + var locator: webdriver.WebDriverTargetLocator = new webdriver.WebDriver.TargetLocator(driver); var promise: webdriver.promise.Promise; var element: webdriver.WebElement = locator.activeElement(); var alert: webdriver.Alert = locator.alert(); promise = locator.defaultContent(); + promise = locator.frame('name'); promise = locator.frame(1); promise = locator.window('nameOrHandle'); } @@ -656,7 +680,7 @@ function TestWebDriverTimeouts() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); + var timeouts: webdriver.WebDriverTimeouts = new webdriver.WebDriver.Timeouts(driver); var promise: webdriver.promise.Promise; promise = timeouts.implicitlyWait(123); @@ -669,7 +693,7 @@ function TestWebDriverWindow() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var window: webdriver.Window = new webdriver.Window(driver); + var window: webdriver.WebDriverWindow = new webdriver.WebDriver.Window(driver); var locationPromise: webdriver.promise.Promise; var sizePromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; @@ -684,7 +708,7 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); var sessionPromise: webdriver.promise.Promise; - var executor: webdriver.Executor = executors.createExecutor("http://someserver"); + var executor: webdriver.CommandExecutor = executors.createExecutor("http://someserver"); var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); driver = new webdriver.WebDriver(session, executor, flow); @@ -722,11 +746,15 @@ function TestWebDriver() { // findElement var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); + element = driver.findElement({id: 'ABC'}); element = driver.findElement(webdriver.By.js('function(){}')); + element = driver.findElement({js: 'function(){}'}); // findElements driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); + driver.findElements({ js: 'function(){}' }).then(function (elements: webdriver.WebElement[]) { }); voidPromise = driver.get('http://www.google.com'); driver.getAllWindowHandles().then(function (handles: string[]) { }); @@ -738,11 +766,13 @@ function TestWebDriver() { stringPromise = driver.getWindowHandle(); booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = driver.isElementPresent({className: 'ABC'}); booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); + booleanPromise = driver.isElementPresent({js: 'function(){}'}); - var options: webdriver.Options = driver.manage(); - var navigation: webdriver.Navigation = driver.navigate(); - var locator: webdriver.TargetLocator = driver.switchTo(); + var options: webdriver.WebDriverOptions = driver.manage(); + var navigation: webdriver.WebDriverNavigation = driver.navigate(); + var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); driver.setFileDetector(fileDetector); @@ -765,7 +795,7 @@ function TestWebDriver() { function TestSerializable() { var serializable: webdriver.Serializable; - var serial: string|webdriver.promise.IThenable = serializable.serialize(); + var serial: string|webdriver.promise.Promise = serializable.serialize(); } function TestWebElement() { @@ -773,10 +803,10 @@ function TestWebElement() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var promise: webdriver.promise.Promise; + var promise: webdriver.promise.Promise; var element: webdriver.WebElement; - element = new webdriver.WebElement(driver, 'elementId'); + element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); element = new webdriver.WebElement(driver, promise); var voidPromise: webdriver.promise.Promise; @@ -787,8 +817,13 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); + element = element.findElement({id: 'ABC'}); + element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); + element.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); + booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); + booleanPromise = element.isElementPresent({className: 'ABC'}); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); @@ -805,11 +840,14 @@ function TestWebElement() { voidPromise = element.sendKeys('A', 'B', 'C'); voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: string) { }); + element.getId().then(function (id: typeof webdriver.WebElement.Id) { }); element.getRawId().then(function (id: string) { }); - element.serialize().then(function (id: webdriver.IWebElementId) { }); + element.serialize().then(function (id: typeof webdriver.WebElement.Id) { }); - booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); + + var id: typeof webdriver.WebElement.Id = webdriver.WebElement.Id; + var key: string = webdriver.WebElement.ELEMENT_KEY; } function TestWebElementPromise() { @@ -839,7 +877,7 @@ function TestLogging() { preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); var prefs: any = preferences.toJSON(); - var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); + var level: webdriver.logging.ILevel = webdriver.logging.getLevel('OFF'); level = webdriver.logging.getLevel(1); level = webdriver.logging.Level.ALL; @@ -849,10 +887,10 @@ function TestLogging() { level = webdriver.logging.Level.SEVERE; level = webdriver.logging.Level.WARNING; - var name: string = level.name(); - var value: number = level.value(); + var name: string = level.name; + var value: number = level.value; - var type: webdriver.logging.Type; + var type: string; type = webdriver.logging.Type.BROWSER; type = webdriver.logging.Type.CLIENT; type = webdriver.logging.Type.DRIVER; @@ -875,6 +913,9 @@ function TestLoggingEntry() { var message: string = entry.message; var timestamp: number = entry.timestamp; var type: string = entry.type; + + entry = webdriver.logging.Entry.fromClosureLogRecord({}); + entry = webdriver.logging.Entry.fromClosureLogRecord({}, webdriver.logging.Type.DRIVER); } function TestPromiseModule() { @@ -905,29 +946,29 @@ function TestPromiseModule() { return 5; }, this, 1, 2, 3).then(function (value: number) { }); - var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { return true; }, this); @@ -954,13 +995,26 @@ function TestPromiseModule() { var bool: boolean = webdriver.promise.isGenerator(function () { }); var isPromise: boolean = webdriver.promise.isPromise('ABC'); - stringPromise = webdriver.promise.rejected('{a: 123}'); + voidPromise = webdriver.promise.rejected({a: 123}); webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); numberPromise = webdriver.promise.when('abc', function(value: any) { return 123; }, function(err: Error) { return 123; }); } +function TestStacktraceModule() { + var bool: boolean = webdriver.stacktrace.BROWSER_SUPPORTED; + + var frame: webdriver.stacktrace.Frame = new webdriver.stacktrace.Frame(); + var baseFrame: webdriver.stacktrace.Frame = frame; + + var snapshot: webdriver.stacktrace.Snapshot = new webdriver.stacktrace.Snapshot(); + var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; + + var err: Error = webdriver.stacktrace.format(new Error("Error")); + var frames: webdriver.stacktrace.Frame[] = webdriver.stacktrace.get(); +} + function TestUntilModule() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -1071,12 +1125,13 @@ function TestPromiseClass() { } function TestThenableClass() { - var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); + var thenable: webdriver.promise.Thenable = new webdriver.promise.Thenable(); thenable.cancel('Abort'); var isPending: boolean = thenable.isPending(); + thenable = thenable.then(); thenable = thenable.then(function (a: string) { return 'cde'; }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); @@ -1089,30 +1144,76 @@ function TestThenableClass() { function TestErrorCode() { var errorCode: number; - errorCode = new webdriver.error.ElementNotSelectableError().code(); - errorCode = new webdriver.error.ElementNotVisibleError().code(); - errorCode = new webdriver.error.InvalidArgumentError().code(); - errorCode = new webdriver.error.InvalidCookieDomainError().code(); - errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); - errorCode = new webdriver.error.InvalidElementStateError().code(); - errorCode = new webdriver.error.InvalidSelectorError().code(); - errorCode = new webdriver.error.NoSuchSessionError().code(); - errorCode = new webdriver.error.JavascriptError().code(); - errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); - errorCode = new webdriver.error.NoSuchAlertError().code(); - errorCode = new webdriver.error.NoSuchElementError().code(); - errorCode = new webdriver.error.NoSuchFrameError().code(); - errorCode = new webdriver.error.NoSuchWindowError().code(); - errorCode = new webdriver.error.ScriptTimeoutError().code(); - errorCode = new webdriver.error.SessionNotCreatedError().code(); - errorCode = new webdriver.error.StaleElementReferenceError().code(); - errorCode = new webdriver.error.TimeoutError().code(); - errorCode = new webdriver.error.UnableToSetCookieError().code(); - errorCode = new webdriver.error.UnableToCaptureScreenError().code(); - errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); - errorCode = new webdriver.error.UnknownCommandError().code(); - errorCode = new webdriver.error.UnknownMethodError().code(); - errorCode = new webdriver.error.UnsupportedOperationError().code(); + errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE; + errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_VISIBLE; + errorCode = webdriver.error.ErrorCode.IME_ENGINE_ACTIVATION_FAILED; + errorCode = webdriver.error.ErrorCode.IME_NOT_AVAILABLE; + errorCode = webdriver.error.ErrorCode.INVALID_COOKIE_DOMAIN; + errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_COORDINATES; + errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_STATE; + errorCode = webdriver.error.ErrorCode.INVALID_SELECTOR_ERROR; + errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR; + errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPE; + errorCode = webdriver.error.ErrorCode.JAVASCRIPT_ERROR; + errorCode = webdriver.error.ErrorCode.METHOD_NOT_ALLOWED; + errorCode = webdriver.error.ErrorCode.MODAL_DIALOG_OPENED; + errorCode = webdriver.error.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS; + errorCode = webdriver.error.ErrorCode.NO_MODAL_DIALOG_OPEN; + errorCode = webdriver.error.ErrorCode.NO_SUCH_ELEMENT; + errorCode = webdriver.error.ErrorCode.NO_SUCH_FRAME; + errorCode = webdriver.error.ErrorCode.NO_SUCH_WINDOW; + errorCode = webdriver.error.ErrorCode.SCRIPT_TIMEOUT; + errorCode = webdriver.error.ErrorCode.SESSION_NOT_CREATED; + errorCode = webdriver.error.ErrorCode.SQL_DATABASE_ERROR; + errorCode = webdriver.error.ErrorCode.STALE_ELEMENT_REFERENCE; + errorCode = webdriver.error.ErrorCode.SUCCESS; + errorCode = webdriver.error.ErrorCode.TIMEOUT; + errorCode = webdriver.error.ErrorCode.UNABLE_TO_SET_COOKIE; + errorCode = webdriver.error.ErrorCode.UNKNOWN_COMMAND; + errorCode = webdriver.error.ErrorCode.UNKNOWN_ERROR; + errorCode = webdriver.error.ErrorCode.UNSUPPORTED_OPERATION; + errorCode = webdriver.error.ErrorCode.XPATH_LOOKUP_ERROR; +} + +function TestError() { + var error: webdriver.error.Error; + + error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE); + error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE, 'Message'); + + var code: number = error.code; + var state: string = error.state; + var message: string = error.message; + var name: string = error.name; + var stack: string = error.stack; + var isAutomationError: boolean = error.isAutomationError; + var errorStr: string = error.toString(); + + state = webdriver.error.Error.State.ELEMENT_NOT_SELECTABLE + state = webdriver.error.Error.State.ELEMENT_NOT_VISIBLE; + state = webdriver.error.Error.State.IME_ENGINE_ACTIVATION_FAILED; + state = webdriver.error.Error.State.IME_NOT_AVAILABLE; + state = webdriver.error.Error.State.INVALID_COOKIE_DOMAIN; + state = webdriver.error.Error.State.INVALID_ELEMENT_COORDINATES; + state = webdriver.error.Error.State.INVALID_ELEMENT_STATE; + state = webdriver.error.Error.State.INVALID_SELECTOR; + state = webdriver.error.Error.State.JAVASCRIPT_ERROR; + state = webdriver.error.Error.State.MOVE_TARGET_OUT_OF_BOUNDS; + state = webdriver.error.Error.State.NO_SUCH_ALERT; + state = webdriver.error.Error.State.NO_SUCH_DOM + state = webdriver.error.Error.State.NO_SUCH_ELEMENT; + state = webdriver.error.Error.State.NO_SUCH_FRAME; + state = webdriver.error.Error.State.NO_SUCH_WINDOW; + state = webdriver.error.Error.State.SCRIPT_TIMEOUT; + state = webdriver.error.Error.State.SESSION_NOT_CREATED; + state = webdriver.error.Error.State.STALE_ELEMENT_REFERENCE; + state = webdriver.error.Error.State.SUCCESS; + state = webdriver.error.Error.State.TIMEOUT; + state = webdriver.error.Error.State.UNABLE_TO_SET_COOKIE; + state = webdriver.error.Error.State.UNEXPECTED_ALERT_OPEN + state = webdriver.error.Error.State.UNKNOWN_COMMAND; + state = webdriver.error.Error.State.UNKNOWN_ERROR; + state = webdriver.error.Error.State.UNSUPPORTED_OPERATION; } function TestTestingModule() { diff --git a/selenium-webdriver/selenium-webdriver.d.ts b/selenium-webdriver/selenium-webdriver.d.ts index b3afe098ac..e1301d5b58 100644 --- a/selenium-webdriver/selenium-webdriver.d.ts +++ b/selenium-webdriver/selenium-webdriver.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Selenium WebDriverJS 2.53.1 -// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver -// Definitions by: Bill Armstrong , Yuki Kokubun +// Type definitions for Selenium WebDriverJS 2.44.0 +// Project: https://code.google.com/p/selenium/ +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace chrome { @@ -19,7 +19,8 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -239,53 +240,6 @@ declare namespace chrome { setChromeLogFile(path: string): Options; - /** - * Sets the directory to store Chrome minidumps in. This option is only - * supported when ChromeDriver is running on Linux. - * @param {string} path The directory path. - * @return {!Options} A self reference. - */ - setChromeMinidumpPath(path: string): Options; - - - /** - * Configures Chrome to emulate a mobile device. For more information, refer - * to the ChromeDriver project page on [mobile emulation][em]. Configuration - * options include: - * - * - `deviceName`: The name of a pre-configured [emulated device][devem] - * - `width`: screen width, in pixels - * - `height`: screen height, in pixels - * - `pixelRatio`: screen pixel ratio - * - * __Example 1: Using a Pre-configured Device__ - * - * let options = new chrome.Options().setMobileEmulation( - * {deviceName: 'Google Nexus 5'}); - * - * let driver = new chrome.Driver(options); - * - * __Example 2: Using Custom Screen Configuration__ - * - * let options = new chrome.Options().setMobileEmulation({ - * width: 360, - * height: 640, - * pixelRatio: 3.0 - * }); - * - * let driver = new chrome.Driver(options); - * - * - * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation - * [devem]: https://developer.chrome.com/devtools/docs/device-mode - * - * @param {?({deviceName: string}| - * {width: number, height: number, pixelRatio: number})} config The - * mobile emulation configuration, or `null` to disable emulation. - * @return {!Options} A self reference. - */ - setMobileEmulation(config: any): Options; - /** * Sets the proxy settings for the new session. * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. @@ -301,6 +255,21 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + + + /** + * Converts this instance to its JSON wire protocol representation. Note this + * function is an implementation not intended for general use. + * @return {{args: !Array., + * binary: (string|undefined), + * detach: boolean, + * extensions: !Array., + * localState: (Object|undefined), + * logFile: (string|undefined), + * prefs: (Object|undefined)}} The JSON wire protocol representation + * of this instance. + */ + toJSON(): IOptionsValues; } /** @@ -379,7 +348,8 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string|Array): ServiceBuilder; + setStdio(config: string): ServiceBuilder; + setStdio(config: any[]): ServiceBuilder; /** @@ -398,7 +368,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): remote.DriverService; + build(): any; } /** @@ -407,1325 +377,395 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): remote.DriverService; + function getDefaultService(): any; /** * Sets the default service to use for new ChromeDriver instances. * @param {!remote.DriverService} service The service to use. * @throws {Error} If the default service is currently running. */ - function setDefaultService(service: remote.DriverService): void; + function setDefaultService(service: any): void; } -declare namespace edge { +declare namespace firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@linkplain #getDefaultService default service} by default. - * @param {promise.ControlFlow=} opt_flow The control flow to use, or - * {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; } /** - * Class for managing MicrosoftEdgeDriver specific options. + * A WebDriver client for Firefox. + * + * @extends {webdriver.WebDriver} + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|webdriver.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash + * object. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + * @constructor + */ + constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + } + + /** + * Configuration options for the FirefoxDriver. */ class Options { + /** + * @constructor + */ + constructor(); - /** - * Extracts the MicrosoftEdgeDriver specific options from the given - * capabilities object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The MicrosoftEdgeDriver options. - */ - static fromCapabilities(cap: webdriver.Capabilities): Options; + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string): Options; + setProfile(profile: Profile): Options; - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - /** - * Sets the page load strategy for Edge. - * Supported values are "normal", "eager", and "none"; - * - * @param {string} pageLoadStrategy The page load strategy to use. - * @return {!Options} A self reference. - */ - setPageLoadStrategy(pageLoadStrategy: string): Options; + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string): Options; + setBinary(binary: Binary): Options; - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + + /** + * Sets the logging preferences for the new session. + * @param {webdriver.logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + + /** + * Sets the proxy to use. + * + * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + + /** + * Converts these options to a {@link webdriver.Capabilities} instance. + * + * @return {!webdriver.Capabilities} A new capabilities object. + */ + toCapabilities(opt_remote?: any): webdriver.Capabilities; } /** - * Creates {@link remote.DriverService} instances that manage a - * MicrosoftEdgeDriver server in a child process. + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. */ - class ServiceBuilder { - /** - * @param {string=} opt_exe Path to the server executable to use. If omitted, - * the builder will attempt to locate the MicrosoftEdgeDriver on the current - * PATH. - * @throws {Error} If provided executable does not exist, or the - * MicrosoftEdgeDriver cannot be found on the PATH. - */ - constructor(opt_exe?: string); + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array.)} - * config The configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string|Array): ServiceBuilder; + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; - /** - * Sets the port to start the MicrosoftEdgeDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: Object): ServiceBuilder; + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; - /** - * Creates a new DriverService using this instance's current configuration. - * @return {!remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; } - - /** - * Returns the default MicrosoftEdgeDriver service. If such a service has - * not been configured, one will be constructed using the default configuration - * for an MicrosoftEdgeDriver executable found on the system PATH. - * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. - */ - function getDefaultService(): remote.DriverService; - - /** - * Sets the default service to use for new MicrosoftEdgeDriver instances. - * @param {!remote.DriverService} service The service to use. - * @throws {Error} If the default service is currently running. - */ - function setDefaultService(service: remote.DriverService): void; } declare namespace executors { /** * Creates a command executor that uses WebDriver's JSON wire protocol. - * @param {(string|!promise.Promise)} url The server's URL, - * or a promise that will resolve to that URL. - * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the - * client to use. - * @returns {!./lib/command.Executor} The new command executor. + * @param url The server's URL, or a promise that will resolve to that URL. + * @returns {!webdriver.CommandExecutor} The new command executor. */ - function createExecutor(url: string|webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; -} - -declare namespace firefox { - /** - * Manages a Firefox subprocess configured for use with WebDriver. - */ - class Binary { - /** - * @param {string=} opt_exe Path to the Firefox binary to use. If not - * specified, will attempt to locate Firefox on the current system. - * @constructor - */ - constructor(opt_exe?: string); - - /** - * Add arguments to the command line used to start Firefox. - * @param {...(string|!Array.)} var_args Either the arguments to add as - * varargs, or the arguments as an array. - */ - addArguments(...var_args: string[]): void; - - - /** - * Launches Firefox and eturns a promise that will be fulfilled when the process - * terminates. - * @param {string} profile Path to the profile directory to use. - * @return {!promise.Promise.} A promise for the process result. - * @throws {Error} If this instance has already been started. - */ - launch(profile: string): webdriver.promise.Promise; - - - /** - * Kills the managed Firefox process. - * @return {!promise.Promise} A promise for when the process has terminated. - */ - kill(): webdriver.promise.Promise; - } - - /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. - */ - class Profile { - /** - * @param {string=} opt_dir Path to an existing Firefox profile directory to - * use a template for this profile. If not specified, a blank profile will - * be used. - * @constructor - */ - constructor(opt_dir?: string); - - /** - * Registers an extension to be included with this profile. - * @param {string} extension Path to the extension to include, as either an - * unpacked extension directory or the path to a xpi file. - */ - addExtension(extension: string): void; - - - /** - * Sets a desired preference for this profile. - * @param {string} key The preference key. - * @param {(string|number|boolean)} value The preference value. - * @throws {Error} If attempting to set a frozen preference. - */ - setPreference(key: string, value: string): void; - setPreference(key: string, value: number): void; - setPreference(key: string, value: boolean): void; - - - /** - * Returns the currently configured value of a profile preference. This does - * not include any defaults defined in the profile's template directory user.js - * file (if a template were specified on construction). - * @param {string} key The desired preference. - * @return {(string|number|boolean|undefined)} The current value of the - * requested preference. - */ - getPreference(key: string): any; - - - /** - * @return {number} The port this profile is currently configured to use, or - * 0 if the port will be selected at random when the profile is written - * to disk. - */ - getPort(): number; - - - /** - * Sets the port to use for the WebDriver extension loaded by this profile. - * @param {number} port The desired port, or 0 to use any free port. - */ - setPort(port: number): void; - - - /** - * @return {boolean} Whether the FirefoxDriver is configured to automatically - * accept untrusted SSL certificates. - */ - acceptUntrustedCerts(): boolean; - - - /** - * Sets whether the FirefoxDriver should automatically accept untrusted SSL - * certificates. - * @param {boolean} value . - */ - setAcceptUntrustedCerts(value: boolean): void; - - - /** - * Sets whether to assume untrusted certificates come from untrusted issuers. - * @param {boolean} value . - */ - setAssumeUntrustedCertIssuer(value: boolean): void; - - - /** - * @return {boolean} Whether to assume untrusted certs come from untrusted - * issuers. - */ - assumeUntrustedCertIssuer(): boolean; - - - /** - * Sets whether to use native events with this profile. - * @param {boolean} enabled . - */ - setNativeEventsEnabled(enabled: boolean): void; - - - /** - * Returns whether native events are enabled in this profile. - * @return {boolean} . - */ - nativeEventsEnabled(): boolean; - - - /** - * Writes this profile to disk. - * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver - * extension from the generated profile. Used to reduce the size of an - * {@link #encode() encoded profile} since the server will always install - * the extension itself. - * @return {!promise.Promise.} A promise for the path to the new - * profile directory. - */ - writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; - - - /** - * Encodes this profile as a zipped, base64 encoded directory. - * @return {!promise.Promise.} A promise for the encoded profile. - */ - encode(): webdriver.promise.Promise; - } - - /** - * Configuration options for the FirefoxDriver. - */ - class Options { - /** - * Sets the profile to use. The profile may be specified as a - * {@link Profile} object or as the path to an existing Firefox profile to use - * as a template. - * - * @param {(string|!Profile)} profile The profile to use. - * @return {!Options} A self reference. - */ - setProfile(profile: string|any): Options; - - /** - * Sets the binary to use. The binary may be specified as the path to a Firefox - * executable, or as a {@link Binary} object. - * - * @param {(string|!Binary)} binary The binary to use. - * @return {!Options} A self reference. - */ - setBinary(binary: string|any): Options; - - /** - * Sets the logging preferences for the new session. - * @param {logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - /** - * Sets the proxy to use. - * - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Sets whether to use Mozilla's Marionette to drive the browser. - * - * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver - */ - useMarionette(marionette: any): Options; - - /** - * Converts these options to a {@link capabilities.Capabilities} instance. - * - * @return {!capabilities.Capabilities} A new capabilities object. - */ - toCapabilities(): webdriver.Capabilities; - } - - /** - * @return {string} . - * @throws {Error} - */ - function findWires(): string; - - /** - * @param {(string|!Binary)} binary . - * @return {!remote.DriverService} . - */ - function createWiresService(binary: string|any): remote.DriverService; - - /** - * @param {(Profile|string)} profile The profile to prepare. - * @param {number} port The port the FirefoxDriver should listen on. - * @return {!Promise} a promise for the path to the profile directory. - */ - function prepareProfile(profile: string|any, port: number): any; - - /** - * A WebDriver client for Firefox. - */ - class Driver extends webdriver.WebDriver { - /** - * @param {(Options|capabilities.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash - * object. - * @param {promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - */ - constructor(opt_config?: Options|webdriver.Capabilities|Object, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } -} - -declare namespace http { - /** - * Converts a headers map to a HTTP header block string. - * @param {!Map} headers The map to convert. - * @return {string} The headers as a string. - */ - function headersToString(headers: any): string; - - /** - * Represents a HTTP request message. This class is a "partial" request and only - * defines the path on the server to send a request to. It is each client's - * responsibility to build the full URL for the final request. - * @final - */ - class HttpRequest { - /** - * @param {string} method The HTTP method to use for the request. - * @param {string} path The path on the server to send the request to. - * @param {Object=} opt_data This request's non-serialized JSON payload data. - */ - constructor(method: string, path: string, opt_data?: Object); - - /** @override */ - toString(): string; - } - - /** - * Represents a HTTP response message. - * @final - */ - class HttpResponse { - /** - * @param {number} status The response code. - * @param {!Object} headers The response headers. All header names - * will be converted to lowercase strings for consistent lookups. - * @param {string} body The response body. - */ - constructor(status: number, headers: Object, body: string); - - /** @override */ - toString(): string; - } - - - function post(path: string): any; - function del(path: string): any; - function get(path: string): any; - function resource(method: string, path: string): any; - - /** - * A basic HTTP client used to send messages to a remote end. - */ - class HttpClient { - /** - * @param {string} serverUrl URL for the WebDriver server to send commands to. - * @param {http.Agent=} opt_agent The agent to use for each request. - * Defaults to `http.globalAgent`. - * @param {?string=} opt_proxy The proxy to use for the connection to the - * server. Default is to use no proxy. - */ - constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); - - /** - * Sends a request to the server. The client will automatically follow any - * redirects returned by the server, fulfilling the returned promise with the - * final response. - * - * @param {!HttpRequest} httpRequest The request to send. - * @return {!promise.Promise} A promise that will be fulfilled - * with the server's response. - */ - send(httpRequest: HttpRequest): webdriver.promise.Promise; - } - - /** - * Sends a single HTTP request. - * @param {!Object} options The request options. - * @param {function(!HttpResponse)} onOk The function to call if the - * request succeeds. - * @param {function(!Error)} onError The function to call if the request fails. - * @param {?string=} opt_data The data to send with the request. - * @param {?string=} opt_proxy The proxy server to use for the request. - */ - function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; - - /** - * A command executor that communicates with the server using HTTP + JSON. - * - * By default, each instance of this class will use the legacy wire protocol - * from [Selenium project][json]. The executor will automatically switch to the - * [W3C wire protocol][w3c] if the remote end returns a compliant response to - * a new session command. - * - * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol - * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html - * - * @implements {cmd.Executor} - */ - class Executor { - /** - * @param {!HttpClient} client The client to use for sending requests to the - * server. - */ - constructor(client: HttpClient); - - /** - * Defines a new command for use with this executor. When a command is sent, - * the {@code path} will be preprocessed using the command's parameters; any - * path segments prefixed with ":" will be replaced by the parameter of the - * same name. For example, given "/person/:name" and the parameters - * "{name: 'Bob'}", the final command path will be "/person/Bob". - * - * @param {string} name The command name. - * @param {string} method The HTTP method to use when sending this command. - * @param {string} path The path to send the command to, relative to - * the WebDriver server's command root and of the form - * "/path/:variable/segment". - */ - defineCommand(name: string, method: string, path: string): void; - - /** @override */ - execute(command: any): any; - } - - /** - * @param {string} str . - * @return {?} . - */ - function tryParse(str: string): any; - - /** - * Callback used to parse {@link HttpResponse} objects from a - * {@link HttpClient}. - * @param {!HttpResponse} httpResponse The HTTP response to parse. - * @param {boolean} w3c Whether the response should be processed using the - * W3C wire protocol. - * @return {{value: ?}} The parsed response. - * @throws {WebDriverError} If the HTTP response is an error. - */ - function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; - - /** - * Builds a fully qualified path using the given set of command parameters. Each - * path segment prefixed with ':' will be replaced by the value of the - * corresponding parameter. All parameters spliced into the path will be - * removed from the parameter map. - * @param {string} path The original resource path. - * @param {!Object<*>} parameters The parameters object to splice into the path. - * @return {string} The modified path. - */ - function buildPath(path: string, parameters: Object): string; -} - -declare namespace ie { - - /** - * A WebDriver client for Microsoft's Internet Explorer. - */ - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {promise.ControlFlow=} opt_flow The control flow to use, - * or {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities|Options, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } - - /** - * Class for managing IEDriver specific options. - */ - class Options { - constructor(); - - /** - * Extracts the IEDriver specific options from the given capabilities - * object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The IEDriver options. - */ - static fromCapabilities(caps: webdriver.Capabilities): Options; - - /** - * Whether to disable the protected mode settings check when the session is - * created. Disbling this setting may lead to significant instability as the - * browser may become unresponsive/hang. Only "best effort" support is provided - * when using this capability. - * - * For more information, refer to the IEDriver's - * [required system configuration](http://goo.gl/eH0Yi3). - * - * @param {boolean} ignoreSettings Whether to ignore protected mode settings. - * @return {!Options} A self reference. - */ - introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; - - /** - * Indicates whether to skip the check that the browser's zoom level is set to - * 100%. - * - * @param {boolean} ignore Whether to ignore the browser's zoom level settings. - * @return {!Options} A self reference. - */ - ignoreZoomSetting(ignore: boolean): Options; - - /** - * Sets the initial URL loaded when IE starts. This is intended to be used with - * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in - * the proper Protected Mode zone. Setting this option may cause browser - * instability or flaky and unresponsive code. Only "best effort" support is - * provided when using this option. - * - * @param {string} url The initial browser URL. - * @return {!Options} A self reference. - */ - initialBrowserUrl(url: string): Options; - - /** - * Configures whether to enable persistent mouse hovering (true by default). - * Persistent hovering is achieved by continuously firing mouse over events at - * the last location the mouse cursor has been moved to. - * - * @param {boolean} enable Whether to enable persistent hovering. - * @return {!Options} A self reference. - */ - enablePersistentHover(enable: boolean): Options; - - /** - * Configures whether the driver should attempt to remove obsolete - * {@linkplain webdriver.WebElement WebElements} from its internal cache on - * page navigation (true by default). Disabling this option will cause the - * driver to run with a larger memory footprint. - * - * @param {boolean} enable Whether to enable element reference cleanup. - * @return {!Options} A self reference. - */ - enableElementCacheCleanup(enable: boolean): Options; - - /** - * Configures whether to require the IE window to have input focus before - * performing any user interactions (i.e. mouse or keyboard events). This - * option is disabled by default, but delivers much more accurate interaction - * events when enabled. - * - * @param {boolean} require Whether to require window focus. - * @return {!Options} A self reference. - */ - requireWindowFocus(require: boolean): Options; - - /** - * Configures the timeout, in milliseconds, that the driver will attempt to - * located and attach to a newly opened instance of Internet Explorer. The - * default is zero, which indicates waiting indefinitely. - * - * @param {number} timeout How long to wait for IE. - * @return {!Options} A self reference. - */ - browserAttachTimeout(timeout: number): Options; - - /** - * Configures whether to launch Internet Explorer using the CreateProcess API. - * If this option is not specified, IE is launched using IELaunchURL, if - * available. For IE 8 and above, this option requires the TabProcGrowth - * registry value to be set to 0. - * - * @param {boolean} force Whether to use the CreateProcess API. - * @return {!Options} A self reference. - */ - forceCreateProcessApi(force: boolean): Options; - - /** - * Specifies command-line switches to use when launching Internet Explorer. - * This is only valid when used with {@link #forceCreateProcessApi}. - * - * @param {...(string|!Array.)} var_args The arguments to add. - * @return {!Options} A self reference. - */ - addArguments(...var_args: Array): Options; - - /** - * Configures whether proxies should be configured on a per-process basis. If - * not set, setting a {@linkplain #setProxy proxy} will configure the system - * proxy. The default behavior is to use the system proxy. - * - * @param {boolean} enable Whether to enable per-process proxy settings. - * @return {!Options} A self reference. - */ - usePerProcessProxy(enable: boolean): Options; - - /** - * Configures whether to clear the cache, cookies, history, and saved form data - * before starting the browser. _Using this capability will clear session data - * for all running instances of Internet Explorer, including those started - * manually._ - * - * @param {boolean} cleanSession Whether to clear all session data on startup. - * @return {!Options} A self reference. - */ - ensureCleanSession(cleanSession: boolean): Options; - - /** - * Sets the path to the log file the driver should log to. - * @param {string} file The log file path. - * @return {!Options} A self reference. - */ - setLogFile(file: string): Options; - - /** - * Sets the IEDriverServer's logging {@linkplain Level level}. - * @param {Level} level The logging level. - * @return {!Options} A self reference. - */ - setLogLevel(level: webdriver.logging.Level): Options; - - /** - * Sets the IP address of the driver's host adapter. - * @param {string} host The IP address to use. - * @return {!Options} A self reference. - */ - setHost(host: string): Options; - - /** - * Sets the path of the temporary data directory to use. - * @param {string} path The log file path. - * @return {!Options} A self reference. - */ - setExtractPath(path: string): Options; - - /** - * Sets whether the driver should start in silent mode. - * @param {boolean} silent Whether to run in silent mode. - * @return {!Options} A self reference. - */ - silent(silent: boolean): Options; - - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; - } - -} - -declare namespace opera { - /** - * Creates {@link remote.DriverService} instances that manages an - * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) - * server in a child process. - */ - class ServiceBuilder { - /** - * @param {string=} opt_exe Path to the server executable to use. If omitted, - * the builder will attempt to locate the operadriver on the current - * PATH. - * @throws {Error} If provided executable does not exist, or the operadriver - * cannot be found on the PATH. - */ - constructor(opt_exe?: string); - - /** - * Sets the port to start the OperaDriver on. - * @param {number} port The port to use, or 0 for any free port. - * @return {!ServiceBuilder} A self reference. - * @throws {Error} If the port is invalid. - */ - usingPort(port: number): ServiceBuilder; - - /** - * Sets the path of the log file the driver should log to. If a log file is - * not specified, the driver will log to stderr. - * @param {string} path Path of the log file to use. - * @return {!ServiceBuilder} A self reference. - */ - loggingTo(path: string): ServiceBuilder; - - /** - * Enables verbose logging. - * @return {!ServiceBuilder} A self reference. - */ - enableVerboseLogging(): ServiceBuilder; - - /** - * Silence sthe drivers output. - * @return {!ServiceBuilder} A self reference. - */ - silent(): ServiceBuilder; - - /** - * Defines the stdio configuration for the driver service. See - * {@code child_process.spawn} for more information. - * @param {(string|!Array)} - * config The configuration to use. - * @return {!ServiceBuilder} A self reference. - */ - setStdio(config: string|Array): ServiceBuilder; - - /** - * Defines the environment to start the server under. This settings will be - * inherited by every browser session started by the server. - * @param {!Object.} env The environment to use. - * @return {!ServiceBuilder} A self reference. - */ - withEnvironment(env: Object): ServiceBuilder; - - /** - * Creates a new DriverService using this instance's current configuration. - * @return {!remote.DriverService} A new driver service using this instance's - * current configuration. - * @throws {Error} If the driver exectuable was not specified and a default - * could not be found on the current PATH. - */ - build(): remote.DriverService; - } - - /** - * Sets the default service to use for new OperaDriver instances. - * @param {!remote.DriverService} service The service to use. - * @throws {Error} If the default service is currently running. - */ - function setDefaultService(service: remote.DriverService): any; - - /** - * Returns the default OperaDriver service. If such a service has not been - * configured, one will be constructed using the default configuration for - * a OperaDriver executable found on the system PATH. - * @return {!remote.DriverService} The default OperaDriver service. - */ - function getDefaultService(): remote.DriverService; - - /** - * Class for managing {@linkplain Driver OperaDriver} specific options. - */ - class Options { - /** - * Extracts the OperaDriver specific options from the given capabilities - * object. - * @param {!capabilities.Capabilities} caps The capabilities object. - * @return {!Options} The OperaDriver options. - */ - static fromCapabilities(caps: webdriver.Capabilities): Options; - - /** - * Add additional command line arguments to use when launching the Opera - * browser. Each argument may be specified with or without the "--" prefix - * (e.g. "--foo" and "foo"). Arguments with an associated value should be - * delimited by an "=": "foo=bar". - * @param {...(string|!Array.)} var_args The arguments to add. - * @return {!Options} A self reference. - */ - addArguments(...var_args: Array): Options; - - /** - * Add additional extensions to install when launching Opera. Each extension - * should be specified as the path to the packed CRX file, or a Buffer for an - * extension. - * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The - * extensions to add. - * @return {!Options} A self reference. - */ - addExtensions(...var_args: Array): Options; - - /** - * Sets the path to the Opera binary to use. On Mac OS X, this path should - * reference the actual Opera executable, not just the application binary. The - * binary path be absolute or relative to the operadriver server executable, but - * it must exist on the machine that will launch Opera. - * - * @param {string} path The path to the Opera binary to use. - * @return {!Options} A self reference. - */ - setOperaBinaryPath(path: string): Options; - - /** - * Sets the logging preferences for the new session. - * @param {!./lib/logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; - - /** - * Sets the proxy settings for the new session. - * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - /** - * Converts this options instance to a {@link capabilities.Capabilities} - * object. - * @param {capabilities.Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!capabilities.Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - } - - class Driver extends webdriver.WebDriver { - /** - * @param {(capabilities.Capabilities|Options)=} opt_config The configuration - * options. - * @param {remote.DriverService=} opt_service The session to use; will use - * the {@link getDefaultService default service} by default. - * @param {promise.ControlFlow=} opt_flow The control flow to use, - * or {@code null} to use the currently active flow. - */ - constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); - - /** - * This function is a no-op as file detectors are not supported by this - * implementation. - * @override - */ - setFileDetector(): void; - } -} - -declare namespace remote { - /** - * A record object that defines the configuration options for a DriverService - * instance. - * - * @record - */ - interface ServiceOptions {} - - /** - * Manages the life and death of a native executable WebDriver server. - * - * It is expected that the driver server implements the - * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. - * Furthermore, the managed server should support multiple concurrent sessions, - * so that this class may be reused for multiple clients. - */ - class DriverService { - /** - * @param {string} executable Path to the executable to run. - * @param {!ServiceOptions} options Configuration options for the service. - */ - constructor(executable: string, options: ServiceOptions); - - /** - * @return {!promise.Promise} A promise that resolves to - * the server's address. - * @throws {Error} If the server has not been started. - */ - address(): webdriver.promise.Promise; - - /** - * Returns whether the underlying process is still running. This does not take - * into account whether the process is in the process of shutting down. - * @return {boolean} Whether the underlying service process is running. - */ - isRunning(): boolean; - - /** - * Starts the server if it is not already running. - * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the - * server to start accepting requests. Defaults to 30 seconds. - * @return {!promise.Promise} A promise that will resolve - * to the server's base URL when it has started accepting requests. If the - * timeout expires before the server has started, the promise will be - * rejected. - */ - start(opt_timeoutMs?: number): webdriver.promise.Promise; - - /** - * Stops the service if it is not currently running. This function will kill - * the server immediately. To synchronize with the active control flow, use - * {@link #stop()}. - * @return {!promise.Promise} A promise that will be resolved when - * the server has been stopped. - */ - kill(): webdriver.promise.Promise; - - /** - * Schedules a task in the current control flow to stop the server if it is - * currently running. - * @return {!promise.Promise} A promise that will be resolved when - * the server has been stopped. - */ - stop(): webdriver.promise.Promise; - } -} - -declare namespace safari { - class Server {} - - /** - * @return {!Promise} A promise that will resolve with the path - * to Safari on the current system. - */ - function findSafariExecutable(): any; - - /** - * @param {string} serverUrl The URL to connect to. - * @return {!Promise} A promise for the path to a file that Safari can - * open on start-up to trigger a new connection to the WebSocket server. - */ - function createConnectFile(serverUrl: string): any; - - /** - * Deletes all session data files if so desired. - * @param {!Object} desiredCapabilities . - * @return {!Array} A list of promises for the deleted files. - */ - function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; - - /** @return {string} . */ - function getRandomString(): string; - - /** - * @implements {command.Executor} - */ - class CommandExecutor { - } - - /** - * Configuration options specific to the {@link Driver SafariDriver}. - */ - class Options { - /** - * Extracts the SafariDriver specific options from the given capabilities - * object. - * @param {!Capabilities} capabilities The capabilities object. - * @return {!Options} The ChromeDriver options. - */ - static fromCapabilities(capabilities: webdriver.Capabilities): Options; - - /** - * Sets whether to force Safari to start with a clean session. Enabling this - * option will cause all global browser data to be deleted. - * @param {boolean} clean Whether to make sure the session has no cookies, - * cache entries, local storage, or databases. - * @return {!Options} A self reference. - */ - setCleanSession(clean: boolean): Options; - - /** - * Sets the logging preferences for the new session. - * @param {!./lib/logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; - - /** - * Converts this options instance to a {@link Capabilities} object. - * @param {Capabilities=} opt_capabilities The capabilities to - * merge these options into, if any. - * @return {!Capabilities} The capabilities. - */ - toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; - } - - /** - * A WebDriver client for Safari. This class should never be instantiated - * directly; instead, use the {@linkplain ./builder.Builder Builder}: - * - * var driver = new Builder() - * .forBrowser('safari') - * .build(); - * - */ - class Driver extends webdriver.WebDriver { - /** - * @param {(Options|Capabilities)=} opt_config The configuration - * options for the new session. - * @param {promise.ControlFlow=} opt_flow The control flow to create - * the driver under. - */ - constructor(opt_config?: Options|webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - - } + function createExecutor(url: string): webdriver.CommandExecutor; + function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; } declare namespace webdriver { namespace error { - class IError extends Error { - constructor(opt_error?: string); + interface IErrorCode { + SUCCESS: number; - code(): number; + NO_SUCH_ELEMENT: number; + NO_SUCH_FRAME: number; + UNKNOWN_COMMAND: number; + UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. + STALE_ELEMENT_REFERENCE: number; + ELEMENT_NOT_VISIBLE: number; + INVALID_ELEMENT_STATE: number; + UNKNOWN_ERROR: number; + ELEMENT_NOT_SELECTABLE: number; + JAVASCRIPT_ERROR: number; + XPATH_LOOKUP_ERROR: number; + TIMEOUT: number; + NO_SUCH_WINDOW: number; + INVALID_COOKIE_DOMAIN: number; + UNABLE_TO_SET_COOKIE: number; + MODAL_DIALOG_OPENED: number; + UNEXPECTED_ALERT_OPEN: number; + NO_SUCH_ALERT: number; + NO_MODAL_DIALOG_OPEN: number; + SCRIPT_TIMEOUT: number; + INVALID_ELEMENT_COORDINATES: number; + IME_NOT_AVAILABLE: number; + IME_ENGINE_ACTIVATION_FAILED: number; + INVALID_SELECTOR_ERROR: number; + SESSION_NOT_CREATED: number; + MOVE_TARGET_OUT_OF_BOUNDS: number; + SQL_DATABASE_ERROR: number; + INVALID_XPATH_SELECTOR: number; + INVALID_XPATH_SELECTOR_RETURN_TYPE: number; + // The following error codes are derived straight from HTTP return codes. + METHOD_NOT_ALLOWED: number; } - /** - * The base WebDriver error type. This error type is only used directly when a - * more appropriate category is not defined for the offending error. - */ - class WebDriverError extends IError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + var ErrorCode: IErrorCode; /** - * An attempt was made to select an element that cannot be selected. + * Error extension that includes error status codes from the WebDriver wire + * protocol: + * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes + * + * @extends {Error} */ - class ElementNotSelectableError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + class Error { - /** - * An element command could not be completed because the element is not visible - * on the page. - */ - class ElementNotVisibleError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //region Constructors - /** - * The arguments passed to a command are either invalid or malformed. - */ - class InvalidArgumentError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** + * @param {!bot.ErrorCode} code The error's status code. + * @param {string=} opt_message Optional error message. + * @constructor + */ + constructor(code: number, opt_message?: string); - /** - * An illegal attempt was made to set a cookie under a different domain than - * the current page. - */ - class InvalidCookieDomainError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //endregion - /** - * The coordinates provided to an interactions operation are invalid. - */ - class InvalidElementCoordinatesError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //region Static Properties - /** - * An element command could not be completed because the element is in an - * invalid state, e.g. attempting to click an element that is no longer attached - * to the document. - */ - class InvalidElementStateError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** + * Status strings enumerated in the W3C WebDriver working draft. + * @enum {string} + * @see http://www.w3.org/TR/webdriver/#status-codes + */ + static State: { + ELEMENT_NOT_SELECTABLE: string; + ELEMENT_NOT_VISIBLE: string; + IME_ENGINE_ACTIVATION_FAILED: string; + IME_NOT_AVAILABLE: string; + INVALID_COOKIE_DOMAIN: string; + INVALID_ELEMENT_COORDINATES: string; + INVALID_ELEMENT_STATE: string; + INVALID_SELECTOR: string; + JAVASCRIPT_ERROR: string; + MOVE_TARGET_OUT_OF_BOUNDS: string; + NO_SUCH_ALERT: string; + NO_SUCH_DOM: string; + NO_SUCH_ELEMENT: string; + NO_SUCH_FRAME: string; + NO_SUCH_WINDOW: string; + SCRIPT_TIMEOUT: string; + SESSION_NOT_CREATED: string; + STALE_ELEMENT_REFERENCE: string; + SUCCESS: string; + TIMEOUT: string; + UNABLE_TO_SET_COOKIE: string; + UNEXPECTED_ALERT_OPEN: string; + UNKNOWN_COMMAND: string; + UNKNOWN_ERROR: string; + UNSUPPORTED_OPERATION: string; + }; - /** - * Argument was an invalid selector. - */ - class InvalidSelectorError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //endregion - /** - * Occurs when a command is directed to a session that does not exist. - */ - class NoSuchSessionError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //region Properties - /** - * An error occurred while executing JavaScript supplied by the user. - */ - class JavascriptError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** + * This error's status code. + * @type {!bot.ErrorCode} + */ + code: number; - /** - * The target for mouse interaction is not in the browser’s viewport and cannot - * be brought into that viewport. - */ - class MoveTargetOutOfBoundsError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @type {string} */ + state: string; - /** - * An attempt was made to operate on a modal dialog when one was not open. - */ - class NoSuchAlertError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @override */ + message: string; - /** - * An element could not be located on the page using the given search - * parameters. - */ - class NoSuchElementError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @override */ + name: string; - /** - * A request to switch to a frame could not be satisfied because the frame - * could not be found. - */ - class NoSuchFrameError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @override */ + stack: string; - /** - * A request to switch to a window could not be satisfied because the window - * could not be found. - */ - class NoSuchWindowError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** + * Flag used for duck-typing when this code is embedded in a Firefox extension. + * This is required since an Error thrown in one component and then reported + * to another will fail instanceof checks in the second component. + * @type {boolean} + */ + isAutomationError: boolean; - /** - * A script did not complete before its timeout expired. - */ - class ScriptTimeoutError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //endregion - /** - * A new session could not be created. - */ - class SessionNotCreatedError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + //region Methods - /** - * An element command failed because the referenced element is no longer - * attached to the DOM. - */ - class StaleElementReferenceError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } + /** @return {string} The string representation of this error. */ + toString(): string; - /** - * An operation did not completErrorCodee before its timeout expired. - */ - class TimeoutError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A request to set a cookie’s value could not be satisfied. - */ - class UnableToSetCookieError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A screen capture operation was not possible. - */ - class UnableToCaptureScreenError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * A modal dialog was open, blocking this operation. - */ - class UnexpectedAlertOpenError extends WebDriverError { - /** - * @param {string=} opt_error the error message, if any. - * @param {string=} opt_text the text of the open dialog, if available. - */ - constructor(opt_error?: string, opt_text?: string); - - /** - * @return {(string|undefined)} The text displayed with the unhandled alert, - * if available. - */ - getAlertText(): string; - } - - /** - * A command could not be executed because the remote end is not aware of it. - */ - class UnknownCommandError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * The requested command matched a known URL but did not match an method for - * that URL. - */ - class UnknownMethodError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); - } - - /** - * Reports an unsupport operation. - */ - class UnsupportedOperationError extends WebDriverError { - /** @param {string=} opt_error the error message, if any. */ - constructor(opt_error?: string); + //endregion } } @@ -1736,97 +776,49 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string|Type, level: Level|string|number): void; + setLevel(type: string, level: ILevel): void; toJSON(): { [key: string]: string }; } + interface IType { + /** Logs originating from the browser. */ + BROWSER: string; + /** Logs from a WebDriver client. */ + CLIENT: string; + /** Logs from a WebDriver implementation. */ + DRIVER: string; + /** Logs related to performance. */ + PERFORMANCE: string; + /** Logs from the remote server. */ + SERVER: string; + } + /** * Common log types. * @enum {string} */ - enum Type { - /** Logs originating from the browser. */ - BROWSER, - /** Logs from a WebDriver client. */ - CLIENT, - /** Logs from a WebDriver implementation. */ - DRIVER, - /** Logs related to performance. */ - PERFORMANCE, - /** Logs from the remote server. */ - SERVER - } + var Type: IType; /** - * Defines a message level that may be used to control logging output. - * - * @final + * Logging levels. + * @enum {{value: number, name: webdriver.logging.LevelName}} */ - class Level { - name_: string; - value_: number; - /** - * @param {string} name the level's name. - * @param {number} level the level's numeric value. - */ - constructor(name: string, level: number); - - /** @override */ - toString(): string; - - /** This logger's name. */ - name(): string; - - /** The numeric log level. */ - value(): number; - - /** - * Indicates no log messages should be recorded. - * @const - */ - static OFF: Level; - /** - * Log messages with a level of `1000` or higher. - * @const - */ - static SEVERE: Level; - /** - * Log messages with a level of `900` or higher. - * @const - */ - static WARNING: Level; - /** - * Log messages with a level of `800` or higher. - * @const - */ - static INFO: Level; - /** - * Log messages with a level of `700` or higher. - * @const - */ - static DEBUG: Level; - /** - * Log messages with a level of `500` or higher. - * @const - */ - static FINE: Level; - /** - * Log messages with a level of `400` or higher. - * @const - */ - static FINER: Level; - /** - * Log messages with a level of `300` or higher. - * @const - */ - static FINEST: Level; - /** - * Indicates all log messages should be recorded. - * @const - */ - static ALL: Level; + interface ILevel { + value: number; + name: string; } + interface ILevelValues { + ALL: ILevel; + DEBUG: ILevel; + INFO: ILevel; + WARNING: ILevel; + SEVERE: ILevel; + OFF: ILevel; + } + + var Level: ILevelValues; + /** * Converts a level name or value to a {@link webdriver.logging.Level} value. * If the name/value is not recognized, {@link webdriver.logging.Level.ALL} @@ -1835,209 +827,75 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string|number): Level; + function getLevel(nameOrValue: string): ILevel; + function getLevel(nameOrValue: number): ILevel; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + level: string; + message: string; + timestamp: number; + type: string; } /** * A single log entry. */ class Entry { - /** - * @param {(!webdriver.logging.Level|string)} level The entry level. - * @param {string} message The log message. - * @param {number=} opt_timestamp The time this entry was generated, in - * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the - * current time will be used. - * @param {string=} opt_type The log type, if known. - * @constructor - */ - constructor(level: Level|string|number, message: string, opt_timestamp?:number, opt_type?:string|Type); - /** @type {!webdriver.logging.Level} */ - level: Level; + //region Constructors - /** @type {string} */ - message: string; + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); + constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); - /** @type {number} */ - timestamp: number; + //endregion - /** @type {string} */ - type: string; + //region Public Properties - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; - } + /** @type {!webdriver.logging.Level} */ + level: ILevel; - /** - * An object used to log debugging messages. Loggers use a hierarchical, - * dot-separated naming scheme. For instance, "foo" is considered the parent of - * the "foo.bar" and an ancestor of "foo.bar.baz". - * - * Each logger may be assigned a {@linkplain #setLevel log level}, which - * controls which level of messages will be reported to the - * {@linkplain #addHandler handlers} attached to this instance. If a log level - * is not explicitly set on a logger, it will inherit its parent. - * - * This class should never be directly instantiated. Instead, users should - * obtain logger references using the {@linkplain ./logging.getLogger() - * getLogger()} function. - * - * @final - */ - class Logger { - /** - * @param {string} name the name of this logger. - * @param {Level=} opt_level the initial level for this logger. - */ - constructor(name: string, opt_level?: Level); + /** @type {string} */ + message: string; - /** @private {string} */ - name_: string; - /** @private {Level} */ - level_: Level; - /** @private {Logger} */ - parent_: Logger; - /** @private {Set} */ - handlers_: any; + /** @type {number} */ + timestamp: number; - /** @return {string} the name of this logger. */ - getName(): string; + /** @type {string} */ + type: string; - /** - * @param {Level} level the new level for this logger, or `null` if the logger - * should inherit its level from its parent logger. - */ - setLevel(level: Level): void; + //endregion - /** @return {Level} the log level for this logger. */ - getLevel(): Level; + //region Static Methods - /** - * @return {!Level} the effective level for this logger. - */ - getEffectiveLevel(): Level; + /** + * Converts a {@link goog.debug.LogRecord} into a + * {@link webdriver.logging.Entry}. + * @param {!goog.debug.LogRecord} logRecord The record to convert. + * @param {string=} opt_type The log type. + * @return {!webdriver.logging.Entry} The converted entry. + */ + static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; - /** - * @param {!Level} level the level to check. - * @return {boolean} whether messages recorded at the given level are loggable - * by this instance. - */ - isLoggable(level: Level): boolean; + //endregion - /** - * Adds a handler to this logger. The handler will be invoked for each message - * logged with this instance, or any of its descendants. - * - * @param {function(!Entry)} handler the handler to add. - */ - addHandler(handler: any): void; + //region Methods - /** - * Removes a handler from this logger. - * - * @param {function(!Entry)} handler the handler to remove. - * @return {boolean} whether a handler was successfully removed. - */ - removeHandler(handler: any): void; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; - /** - * Logs a message at the given level. The message may be defined as a string - * or as a function that will return the message. If a function is provided, - * it will only be invoked if this logger's - * {@linkplain #getEffectiveLevel() effective log level} includes the given - * `level`. - * - * @param {!Level} level the level at which to log the message. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - log(level: Level, loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.SEVERE} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - severe(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.WARNING} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - warning(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.INFO} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - info(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.DEBUG} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - debug(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.FINE} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - fine(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.FINER} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - finer(loggable: string|Function): void; - - /** - * Logs a message at the {@link Level.FINEST} log level. - * @param {(string|function(): string)} loggable the message to log, or a - * function that will return the message. - */ - finest(loggable: string|Function): void; - } - - /** - * Maintains a collection of loggers. - * - * @final - */ - class LogManager { - /** - * Retrieves a named logger, creating it in the process. This function will - * implicitly create the requested logger, and any of its parents, if they - * do not yet exist. - * - * @param {string} name the logger's name. - * @return {!Logger} the requested logger. - */ - getLogger(name: string): Logger; - - /** - * Creates a new logger. - * - * @param {string} name the logger's name. - * @param {!Logger} parent the logger's parent. - * @return {!Logger} the new logger. - * @private - */ - createLogger_(name: string, parent: Logger): Logger; + //endregion } } @@ -2050,15 +908,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array<(T|!ManagedPromise)>} arr An array of + * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of * promises to wait on. - * @return {!ManagedPromise>} A promise that is + * @return {!webdriver.promise.Promise.>} A promise that is * fulfilled with an array containing the fulfilled values of the * input array, or rejected with the same reason as the first * rejected value. * @template T */ - function all(arr: Array>): Promise; + function all(arr: Promise[]): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -2081,9 +939,9 @@ declare namespace webdriver { * Creates a new control flow. The provided callback will be invoked as the * first task within the new flow, with the flow as its sole argument. Returns * a promise that resolves to the callback result. - * @param {function(!ControlFlow)} callback The entry point + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point * to the newly created flow. - * @return {!ManagedPromise} A promise that resolves to the callback + * @return {!webdriver.promise.Promise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -2108,7 +966,7 @@ declare namespace webdriver { * Creates a promise that will be resolved at a set time in the future. * @param {number} ms The amount of time, in milliseconds, to wait before * resolving the promise. - * @return {!ManagedPromise} The promise. + * @return {!webdriver.promise.Promise} The promise. */ function delayed(ms: number): Promise; @@ -2116,25 +974,26 @@ declare namespace webdriver { * Calls a function for each element in an array, and if the function returns * true adds the element to a new array. * - * If the return value of the filter function is a promise, this function + *

    If the return value of the filter function is a promise, this function * will wait for it to be fulfilled before determining whether to insert the * element into the new array. * - * If the filter function throws or returns a rejected promise, the promise + *

    If the filter function throws or returns a rejected promise, the promise * returned by this function will be rejected with the same reason. Only the * first failure will be reported; all subsequent errors will be silently * ignored. * - * @param {!(Array|ManagedPromise>)} arr The + * @param {!(Array.|webdriver.promise.Promise.>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array): ( - * boolean|ManagedPromise)} fn The function + * @param {function(this: SELF, TYPE, number, !Array.): ( + * boolean|webdriver.promise.Promise.)} fn The function * to call for each element in the array. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; + function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; + function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise /** * Creates a new deferred object. @@ -2144,9 +1003,8 @@ declare namespace webdriver { /** * Creates a promise that has been resolved with the given value. - * @param {T=} opt_value The resolved value. - * @return {!ManagedPromise} The resolved promise. - * @template T + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. */ function fulfilled(opt_value?: T): Promise; @@ -2155,44 +1013,42 @@ declare namespace webdriver { * new array, which is used as the fulfillment value of the promise returned * by this function. * - * If the return value of the mapping function is a promise, this function + *

    If the return value of the mapping function is a promise, this function * will wait for it to be fulfilled before inserting it into the new array. * - * If the mapping function throws or returns a rejected promise, the + *

    If the mapping function throws or returns a rejected promise, the * promise returned by this function will be rejected with the same reason. * Only the first failure will be reported; all subsequent errors will be * silently ignored. * - * @param {!(Array|ManagedPromise>)} arr The + * @param {!(Array.|webdriver.promise.Promise.>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array): ?} fn The + * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The * function to call for each element in the array. This function should * expect three arguments (the element, the index, and the array itself. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function map(arr: Array|Promise>, fn: (self: any, type: any, index: number, array: any[]) => any, opt_self?: any): Promise + function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise /** * Creates a promise that has been rejected with the given reason. * @param {*=} opt_reason The rejection reason; may be any value, but is * usually an Error or a string. - * @return {!ManagedPromise} The rejected promise. - * @template T + * @return {!webdriver.promise.Promise} The rejected promise. */ - function rejected(opt_reason?: any): Promise; + function rejected(opt_reason?: any): Promise; /** - * Wraps a function that expects a node-style callback as its final - * argument. This callback expects two arguments: an error value (which will be + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be * null if the call succeeded), and the success value as the second argument. - * The callback will the resolve or reject the returned promise, based on its - * arguments. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. * @param {!Function} fn The function to wrap. - * @param {...?} var_args The arguments to apply to the function, excluding the - * final callback. - * @return {!ManagedPromise} A promise that will be resolved with the + * @return {!webdriver.promise.Promise} A promise that will be resolved with the * result of the provided function's callback. */ function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; @@ -2203,35 +1059,37 @@ declare namespace webdriver { * fulfilled value back into {@code next}. Likewise, if a yielded promise is * rejected, the rejection error will be passed to {@code throw}. * - * __Example 1:__ the Fibonacci Sequence. + *

    Example 1: the Fibonacci Sequence. + *

    
    +         * webdriver.promise.consume(function* fibonacci() {
    +         *   var n1 = 1, n2 = 1;
    +         *   for (var i = 0; i < 4; ++i) {
    +         *     var tmp = yield n1 + n2;
    +         *     n1 = n2;
    +         *     n2 = tmp;
    +         *   }
    +         *   return n1 + n2;
    +         * }).then(function(result) {
    +         *   console.log(result);  // 13
    +         * });
    +         * 
    * - * promise.consume(function* fibonacci() { - * var n1 = 1, n2 = 1; - * for (var i = 0; i < 4; ++i) { - * var tmp = yield n1 + n2; - * n1 = n2; - * n2 = tmp; - * } - * return n1 + n2; - * }).then(function(result) { - * console.log(result); // 13 - * }); - * - * __Example 2:__ a generator that throws. - * - * promise.consume(function* () { - * yield promise.delayed(250).then(function() { - * throw Error('boom'); - * }); - * }).catch(function(e) { - * console.log(e.toString()); // Error: boom - * }); + *

    Example 2: a generator that throws. + *

    
    +         * webdriver.promise.consume(function* () {
    +         *   yield webdriver.promise.delayed(250).then(function() {
    +         *     throw Error('boom');
    +         *   });
    +         * }).thenCatch(function(e) {
    +         *   console.log(e.toString());  // Error: boom
    +         * });
    +         * 
    * * @param {!Function} generatorFn The generator function to execute. * @param {Object=} opt_self The object to use as "this" when invoking the * initial generator. * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!ManagedPromise} A promise that will resolve to the + * @return {!webdriver.promise.Promise.} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -2246,9 +1104,10 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!ManagedPromise} A new promise. + * @return {!webdriver.promise.Promise} A new promise. */ - function when(value: T|Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; /** * Returns a promise that will be resolved with the input value in a @@ -2261,19 +1120,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!ManagedPromise} A promise for a fully resolved version + * @return {!webdriver.promise.Promise} A promise for a fully resolved version * of the input value. */ function fullyResolved(value: any): Promise; /** * Changes the default flow to use when no others are active. - * @param {!ControlFlow} flow The new default flow. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -2282,249 +1141,63 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. + * + * @extends {goog.debug.Error} + * @final */ - class CancellationError extends Error { - /** - * @param {string=} opt_msg The cancellation message. - */ - constructor(opt_msg?: string); + class CancellationError { + /** + * @param {string=} opt_msg The cancellation message. + * @constructor + */ + constructor(opt_msg?: string); + + name: string; + message: string; } interface IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string|Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. - * - * @param {?(function(T): (R|IThenable))=} opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param {?(function(*): (R|IThenable))=} opt_errback - * The function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - } - - /** - * Thenable is a promise-like object with a {@code then} method which may be - * used to schedule callbacks on a promised value. - * - * @interface - * @template T - */ - class Thenable implements IThenable { - /** - * Cancels the computation of this promise's value, rejecting the promise in - * the process. This method is a no-op if the promise has already been - * resolved. - * - * @param {(string|Error)=} opt_reason The reason this promise is being - * cancelled. This value will be wrapped in a {@link CancellationError}. - */ - cancel(opt_reason?: string|Error): void; - - /** @return {boolean} Whether this promise's value is still being computed. */ - isPending(): boolean; - - /** - * Registers listeners for when this instance is resolved. - * - * @param {?(function(T): (R|IThenable))=} opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param {?(function(*): (R|IThenable))=} opt_errback - * The function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; - - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } finally { - * cleanUp(); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().finally(cleanUp); - * - * __Note:__ similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - * - * try { - * throw Error('one'); - * } finally { - * throw Error('two'); // Hides Error: one - * } - * - * promise.rejected(Error('one')) - * .finally(function() { - * throw Error('two'); // Hides Error: one - * }); - * - * @param {function(): (R|IThenable)} callback The function to call when - * this promise is resolved. - * @return {!ManagedPromise} A promise that will be fulfilled - * with the callback result. - * @template R - */ - finally(callback: Function): Promise; - - /** - * Adds a property to a class prototype to allow runtime checks of whether - * instances of that class implement the Thenable interface. This function - * will also ensure the prototype's {@code then} function is exported from - * compiled code. - * @param {function(new: Thenable, ...?)} ctor The - * constructor whose prototype to modify. - */ - static addImplementation(ctor: Function): void; - - /** - * Checks if an object has been tagged for implementing the Thenable - * interface as defined by {@link Thenable.addImplementation}. - * @param {*} object The object to test. - * @return {boolean} Whether the object is an implementation of the Thenable - * interface. - */ - static isImplementation(object: any): boolean; - } - - interface IFulfilledCallback { - (value: T|IThenable|Thenable|void): void; - } - - interface IRejectedCallback { - (reason: any): void; - } - - /** - * Represents the eventual value of a completed operation. Each promise may be - * in one of three states: pending, fulfilled, or rejected. Each promise starts - * in the pending state and may make a single transition to either a - * fulfilled or rejected state, at which point the promise is considered - * resolved. - * - * @implements {promise.Thenable} - * @template T - * @see http://promises-aplus.github.io/promises-spec/ - */ - class Promise implements IThenable { - /** - * @param {function( - * function((T|IThenable|Thenable)=), - * function(*=))} resolver - * Function that is invoked immediately to begin computation of this - * promise's value. The function should accept a pair of callback - * functions, one for fulfilling the promise and another for rejecting it. - * @param {ControlFlow=} opt_flow The control flow - * this instance was created under. Defaults to the currently active flow. - */ - constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); - constructor(); // For angular-protractor/angular-protractor-tests.ts - - //region Methods - /** * Cancels the computation of this promise's value, rejecting the promise in the - * process. - * @param {*} reason The reason this promise is being cancelled. If not an - * {@code Error}, one will be created using the value's string - * representation. + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. */ - cancel(opt_reason?: string|Error): void; + cancel(opt_reason?: string): void; + /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; + /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. + * Registers listeners for when this instance is resolved. * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. */ - then(opt_callback?: Function, opt_errback?: Function): Promise; + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + /** * Registers a listener for when this promise is rejected. This is synonymous @@ -2552,31 +1225,6 @@ declare namespace webdriver { */ thenCatch(errback: (error: any) => any): Promise; - /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: - * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R - */ - catch(errback: Function): Promise; - /** * Registers a listener to invoke when this promise is resolved, regardless @@ -2617,7 +1265,294 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: Function): Promise; + thenFinally(callback: () => any): Promise; + } + + /** + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ + class Thenable implements IThenable { + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. This method is a no-op if the promise has alreayd been resolved. + * + * @param {string=} opt_reason The reason this promise is being cancelled. + */ + cancel(opt_reason?: string): void; + + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. + * + * @param opt_callback The + * function to call if this promise is successfully resolved. The function + * should expect a single argument: the promise's resolved value. + * @param opt_errback The + * function to call if this promise is rejected. The function should expect + * a single argument: the rejection reason. + * @return A new promise which will be + * resolved with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } catch (ex) {
    +             *     console.error(ex);
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenCatch(function(ex) {
    +             *     console.error(ex);
    +             *   });
    +             * 
    + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } finally {
    +             *     cleanUp();
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenFinally(cleanUp);
    +             * 
    + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
    
    +             *   try {
    +             *     throw Error('one');
    +             *   } finally {
    +             *     throw Error('two');  // Hides Error: one
    +             *   }
    +             *
    +             *   webdriver.promise.rejected(Error('one'))
    +             *       .thenFinally(function() {
    +             *         throw Error('two');  // Hides Error: one
    +             *       });
    +             * 
    + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; + + /** + * Adds a property to a class prototype to allow runtime checks of whether + * instances of that class implement the Thenable interface. This function will + * also ensure the prototype's {@code then} function is exported from compiled + * code. + * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * constructor whose prototype to modify. + */ + static addImplementation(ctor: Function): void; + + + /** + * Checks if an object has been tagged for implementing the Thenable interface + * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * @param {*} object The object to test. + * @return {boolean} Whether the object is an implementation of the Thenable + * interface. + */ + static isImplementation(object: any): boolean; + } + + interface IFulfilledCallback { + (value: T|IThenable|Thenable|void): void; + } + + interface IRejectedCallback { + (reason: any): void; + } + + /** + * Represents the eventual value of a completed operation. Each promise may be + * in one of three states: pending, fulfilled, or rejected. Each promise starts + * in the pending state and may make a single transition to either a + * fulfilled or rejected state, at which point the promise is considered + * resolved. + * + * @implements {promise.Thenable} + * @template T + * @see http://promises-aplus.github.io/promises-spec/ + */ + class Promise implements IThenable { + /** + * @param {function( + * function((T|IThenable|Thenable)=), + * function(*=))} resolver + * Function that is invoked immediately to begin computation of this + * promise's value. The function should accept a pair of callback functions, + * one for fulfilling the promise and another for rejecting it. + * @param {promise.ControlFlow=} opt_flow The control flow + * this instance was created under. Defaults to the currently active flow. + * @constructor + */ + constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); + constructor(); // For angular-protractor/angular-protractor-tests.ts + + //region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(reason: any): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; + + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } catch (ex) {
    +             *     console.error(ex);
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenCatch(function(ex) {
    +             *     console.error(ex);
    +             *   });
    +             * 
    + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } finally {
    +             *     cleanUp();
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenFinally(cleanUp);
    +             * 
    + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
    
    +             *   try {
    +             *     throw Error('one');
    +             *   } finally {
    +             *     throw Error('two');  // Hides Error: one
    +             *   }
    +             *
    +             *   webdriver.promise.rejected(Error('one'))
    +             *       .thenFinally(function() {
    +             *         throw Error('two');  // Hides Error: one
    +             *       });
    +             * 
    + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: () => any): Promise; //endregion } @@ -2856,6 +1791,107 @@ declare namespace webdriver { } } + namespace stacktrace { + /** + * Class representing one stack frame. + */ + class Frame { + /** + * @param {(string|undefined)} context Context object, empty in case of global + * functions or if the browser doesn't provide this information. + * @param {(string|undefined)} name Function name, empty in case of anonymous + * functions. + * @param {(string|undefined)} alias Alias of the function if available. For + * example the function name will be 'c' and the alias will be 'b' if the + * function is defined as a.b = function c() {};. + * @param {(string|undefined)} path File path or URL including line number and + * optionally column number separated by colons. + * @constructor + */ + constructor(context?: string, name?: string, alias?: string, path?: string); + + /** + * @return {string} The function name or empty string if the function is + * anonymous and the object field which it's assigned to is unknown. + */ + getName(): string; + + + /** + * @return {string} The url or empty string if it is unknown. + */ + getUrl(): string; + + + /** + * @return {number} The line number if known or -1 if it is unknown. + */ + getLine(): number; + + + /** + * @return {number} The column number if known and -1 if it is unknown. + */ + getColumn(): number; + + + /** + * @return {boolean} Whether the stack frame contains an anonymous function. + */ + isAnonymous(): boolean; + + + /** + * Converts this frame to its string representation using V8's stack trace + * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi + * @return {string} The string representation of this frame. + * @override + */ + toString(): string; + } + + /** + * Stores a snapshot of the stack trace at the time this instance was created. + * The stack trace will always be adjusted to exclude this function call. + */ + class Snapshot { + /** + * @param {number=} opt_slice The number of frames to remove from the top of + * the generated stack trace. + * @constructor + */ + constructor(opt_slice?: number); + + /** + * @return {!Array.} The parsed stack trace. + */ + getStacktrace(): Frame[]; + } + + /** + * Formats an error's stack trace. + * @param {!(Error|goog.testing.JsUnitException)} error The error to format. + * @return {!(Error|goog.testing.JsUnitException)} The formatted error. + */ + function format(error: any): any; + + /** + * Gets the native stack trace if available otherwise follows the call chain. + * The generated trace will exclude all frames up to and including the call to + * this function. + * @return {!Array.} The frames of the stack trace. + */ + function get(): Frame[]; + + /** + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const + */ + var BROWSER_SUPPORTED: boolean; + } + namespace until { /** * Defines a condition to @@ -2879,31 +1915,32 @@ declare namespace webdriver { /** * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as + * to the designated frame. The target frame may be specified as: + *
      + *
    1. A numeric index into {@code window.frames} for the currently selected + * frame. + *
    2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + *
    3. A locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + *
    * - * 1. a numeric index into - * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) - * for the currently selected frame. - * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - * 3. a locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - * - * Upon successful resolution of this condition, the driver will be left + *

    Upon successful resolution of this condition, the driver will be left * focused on the new frame. * - * @param {!(number|./webdriver.WebElement|By| - * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame + * @param {!(number|webdriver.WebElement| + * webdriver.Locator|webdriver.By.Hash| + * function(!webdriver.WebDriver): !webdriver.WebElement)} frame * The frame identifier. - * @return {!Condition} A new condition. + * @return {!until.Condition.} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|By|((webdriver: WebDriver)=>WebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the * returned promise will be fulfilled with the handle for the opened alert. * - * @return {!Condition} The new condition. + * @return {!until.Condition.} The new condition. */ function alertIsPresent(): Condition; @@ -2963,12 +2000,13 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link ./webdriver.WebDriver#findElement found} with the given locator. + * {@link webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(By|Function)} locator The locator to use. + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: By|Function): Condition; + function elementLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -3001,7 +2039,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition} The new condition. + * @return {!until.Condition.} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -3015,7 +2053,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: By|Function): Condition; + function elementsLocated(locator: Locator|By.Hash|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -3023,7 +2061,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition} The new condition. + * @return {!until.Condition.} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -3042,7 +2080,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition} The new condition. + * @return {!until.Condition.} The new condition. */ function titleIs(title: string): Condition; @@ -3067,18 +2105,18 @@ declare namespace webdriver { } /** - * Representations of pressable keys that aren't text. These are stored in - * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to - * http://www.google.com.au/search?&q=unicode+pua&btnG=Search - * - * @enum {string} + * Enumeration of the buttons used in the advanced interactions API. + * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. + * @enum {number} */ - enum Button { - LEFT, - MIDDLE, - RIGHT, + interface IButton { + LEFT: number; + MIDDLE: number; + RIGHT: number; } + var Button: IButton; + /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -3086,86 +2124,102 @@ declare namespace webdriver { * * @enum {string} */ - enum Key { - NULL, - CANCEL, // ^break - HELP, - BACK_SPACE, - TAB, - CLEAR, - RETURN, - ENTER, - SHIFT, - CONTROL, - ALT, - PAUSE, - ESCAPE, - SPACE, - PAGE_UP, - PAGE_DOWN, - END, - HOME, - ARROW_LEFT, - LEFT, - ARROW_UP, - UP, - ARROW_RIGHT, - RIGHT, - ARROW_DOWN, - DOWN, - INSERT, - DELETE, - SEMICOLON, - EQUALS, + interface IKey { + NULL: string; + CANCEL: string; // ^break + HELP: string; + BACK_SPACE: string; + TAB: string; + CLEAR: string; + RETURN: string; + ENTER: string; + SHIFT: string; + CONTROL: string; + ALT: string; + PAUSE: string; + ESCAPE: string; + SPACE: string; + PAGE_UP: string; + PAGE_DOWN: string; + END: string; + HOME: string; + ARROW_LEFT: string; + LEFT: string; + ARROW_UP: string; + UP: string; + ARROW_RIGHT: string; + RIGHT: string; + ARROW_DOWN: string; + DOWN: string; + INSERT: string; + DELETE: string; + SEMICOLON: string; + EQUALS: string; - NUMPAD0, // number pad keys - NUMPAD1, - NUMPAD2, - NUMPAD3, - NUMPAD4, - NUMPAD5, - NUMPAD6, - NUMPAD7, - NUMPAD8, - NUMPAD9, - MULTIPLY, - ADD, - SEPARATOR, - SUBTRACT, - DECIMAL, - DIVIDE, + NUMPAD0: string; // number pad keys + NUMPAD1: string; + NUMPAD2: string; + NUMPAD3: string; + NUMPAD4: string; + NUMPAD5: string; + NUMPAD6: string; + NUMPAD7: string; + NUMPAD8: string; + NUMPAD9: string; + MULTIPLY: string; + ADD: string; + SEPARATOR: string; + SUBTRACT: string; + DECIMAL: string; + DIVIDE: string; - F1, // function keys - F2, - F3, - F4, - F5, - F6, - F7, - F8, - F9, - F10, - F11, - F12, + F1: string; // function keys + F2: string; + F3: string; + F4: string; + F5: string; + F6: string; + F7: string; + F8: string; + F9: string; + F10: string; + F11: string; + F12: string; - COMMAND, // Apple command key - META // alias for Windows key + COMMAND: string; // Apple command key + META: string; // alias for Windows key + /** + * Simulate pressing many keys at once in a "chord". Takes a sequence of + * {@link webdriver.Key}s or strings, appends each of the values to a string, + * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns + * the resultant string. + * + * Note: when the low-level webdriver key handlers see Keys.NULL, active + * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. + * + * @param {...string} var_args The key sequence to concatenate. + * @return {string} The null-terminated key sequence. + * @see http://code.google.com/p/webdriver/issues/detail?id=79 + */ + chord: (...var_args: string[]) => string; } + var Key: IKey; + /** * Class for defining sequences of complex user interactions. Each sequence * will not be executed until {@link #perform} is called. * - * Example: - * - * new ActionSequence(driver). - * keyDown(Key.SHIFT). - * click(element1). - * click(element2). - * dragAndDrop(element3, element4). - * keyUp(Key.SHIFT). - * perform(); + *

    Example:

    
    +     *   new webdriver.ActionSequence(driver).
    +     *       keyDown(webdriver.Key.SHIFT).
    +     *       click(element1).
    +     *       click(element2).
    +     *       dragAndDrop(element3, element4).
    +     *       keyUp(webdriver.Key.SHIFT).
    +     *       perform();
    +     * 
    * */ class ActionSequence { @@ -3193,18 +2247,14 @@ declare namespace webdriver { * Moves the mouse. The location to move to may be specified in terms of the * mouse's current location, an offset relative to the top-left corner of an * element, or an element (in which case the middle of the element is used). - * - * @param {(!./webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, as either another WebElement or an offset in - * pixels. - * @param {{x: number, y: number}=} opt_offset If the target {@code location} - * is defined as a {@link ./webdriver.WebElement}, this parameter defines - * an offset within that element. The offset should be specified in pixels - * relative to the top-left corner of the element's bounding box. If - * omitted, the element's center will be used as the target offset. - * @return {!ActionSequence} A self reference. + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in pixels. + * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. + * Defaults to (0, 0). + * @return {!webdriver.ActionSequence} A self reference. */ - mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; + mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; + mouseMove(location: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -3212,101 +2262,100 @@ declare namespace webdriver { * sequence or another. The behavior for out-of-order events (e.g. mouseDown, * click) is undefined. * - * If an element is provided, the mouse will first be moved to the center + *

    If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: + *

    sequence.mouseMove(element).mouseDown()
    * - * sequence.mouseMove(element).mouseDown() + *

    Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseDown(opt_elementOrButton?: number): ActionSequence; /** * Releases a mouse button. Behavior is undefined for calling this function * without a previous call to {@link #mouseDown}. * - * If an element is provided, the mouse will first be moved to the center + *

    If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: + *

    sequence.mouseMove(element).mouseUp()
    * - * sequence.mouseMove(element).mouseUp() + *

    Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + mouseUp(opt_elementOrButton?: number): ActionSequence; /** * Convenience function for performing a "drag and drop" manuever. The target * element may be moved to the location of another element, or by an offset (in * pixels). - * - * @param {!./webdriver.WebElement} element The element to drag. - * @param {(!./webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, either as another WebElement or an offset in - * pixels. - * @return {!ActionSequence} A self reference. + * @param {!webdriver.WebElement} element The element to drag. + * @param {(!webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in pixels. + * @return {!webdriver.ActionSequence} A self reference. */ - dragAndDrop(element: WebElement, location: WebElement|ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement): ActionSequence; + dragAndDrop(element: WebElement, location: ILocation): ActionSequence; /** * Clicks a mouse button. * - * If an element is provided, the mouse will first be moved to the center + *

    If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: + *

    sequence.mouseMove(element).click()
    * - * sequence.mouseMove(element).click() - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + click(opt_elementOrButton?: number): ActionSequence; /** * Double-clicks a mouse button. * - * If an element is provided, the mouse will first be moved to the center of + *

    If an element is provided, the mouse will first be moved to the center of * that element. This is equivalent to: + *

    sequence.mouseMove(element).doubleClick()
    * - * sequence.mouseMove(element).doubleClick() + *

    Warning: this method currently only supports the left mouse button. See + * http://code.google.com/p/selenium/issues/detail?id=4047 * - * Warning: this method currently only supports the left mouse button. See - * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). - * - * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either + * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link input.Button.LEFT} if neither an element nor + * Defaults to {@link webdriver.Button.LEFT} if neither an element nor * button is specified. - * @param {input.Button=} opt_button The button to use. Defaults to - * {@link input.Button.LEFT}. Ignored if a button is provided as the + * @param {webdriver.Button=} opt_button The button to use. Defaults to + * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!ActionSequence} A self reference. + * @return {!webdriver.ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; + doubleClick(opt_elementOrButton?: number): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -3317,7 +2366,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: Key): ActionSequence; + keyDown(key: string): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -3327,7 +2376,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: Key): ActionSequence; + keyUp(key: string): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -3338,7 +2387,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: Array): ActionSequence; + sendKeys(...var_args: any[]): ActionSequence; //endregion } @@ -3434,6 +2483,7 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; + /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -3444,6 +2494,7 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; + /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -3453,6 +2504,7 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; + /** * Flick starting at elem and moving by x and y at specified speed. * @@ -3464,29 +2516,26 @@ declare namespace webdriver { flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; } + interface IOffset { x: number; y: number; } + interface ISpeed { xspeed: number; yspeed: number; } + /** * Represents a modal dialog such as {@code alert}, {@code confirm}, or * {@code prompt}. Provides functions to retrieve the message displayed with * the alert, accept or dismiss the alert, and set the response text (in the * case of {@code prompt}). */ - class Alert { - /** - * @param {!WebDriver} driver The driver controlling the browser this alert - * is attached to. - * @param {string} text The message text displayed with this alert. - */ - constructor(driver: WebDriver, text: string); + interface Alert { //region Methods @@ -3498,18 +2547,6 @@ declare namespace webdriver { */ getText(): webdriver.promise.Promise; - /** - * Sets the username and password in an alert prompting for credentials (such - * as a Basic HTTP Auth prompt). This method will implicitly - * {@linkplain #accept() submit} the dialog. - * - * @param {string} username The username to send. - * @param {string} password The password to send. - * @return {!promise.Promise} A promise that will be resolved when this - * command has completed. - */ - authenticateAs(username: string, password: string): webdriver.promise.Promise; - /** * Accepts this alert. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -3543,27 +2580,47 @@ declare namespace webdriver { * serves as a forward proxy on an Alert, allowing calls to be scheduled * directly on this instance before the underlying Alert has been fulfilled. In * other words, the following two statements are equivalent: - * + *

    
          *     driver.switchTo().alert().dismiss();
          *     driver.switchTo().alert().then(function(alert) {
          *       return alert.dismiss();
          *     });
    +     * 
    * - * @implements {promise.Thenable.} + * @param {!webdriver.WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!webdriver.promise.Thenable.} alert A thenable + * that will be fulfilled with the promised alert. + * @constructor + * @extends {webdriver.Alert} + * @implements {webdriver.promise.Thenable.} * @final */ - class AlertPromise extends Alert { - /** - * @param {!WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!promise.Thenable} alert A thenable - * that will be fulfilled with the promised alert. - */ - constructor(driver: WebDriver, alert: webdriver.promise.Promise); + interface AlertPromise extends Alert, webdriver.promise.IThenable { } - /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ - class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { + /** + * An error returned to indicate that there is an unhandled modal dialog on the + * current page. + * @extends {bot.Error} + */ + interface UnhandledAlertError extends webdriver.error.Error { + //region Methods + + /** + * @return {string} The text displayed with the unhandled alert. + */ + getAlertText(): string; + + /** + * @return {!webdriver.Alert} The open alert. + * @deprecated Use {@link #getAlertText}. This method will be removed in + * 2.45.0. + */ + getAlert(): Alert; + + + //endregion } /** @@ -3573,9 +2630,7 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; - EDGE: string; FIREFOX: string; - IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -3596,45 +2651,6 @@ declare namespace webdriver { noProxy?: string; } - /** - * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment - * variables listed below may be used to override a builder's configuration, - * allowing quick runtime changes. - * - * - {@code SELENIUM_BROWSER}: defines the target browser in the form - * {@code browser[:version][:platform]}. - * - * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder - * instances. This environment variable should be set to a fully qualified - * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This - * option always takes precedence over {@code SELENIUM_SERVER_JAR}. - * - * - {@code SELENIUM_SERVER_JAR}: defines the path to the - * - * standalone Selenium server jar to use. The server will be started the - * first time a WebDriver instance and be killed when the process exits. - * - * Suppose you had mytest.js that created WebDriver with - * - * var driver = new webdriver.Builder() - * .forBrowser('chrome') - * .build(); - * - * This test could be made to use Firefox on the local machine by running with - * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to - * target Google Chrome on a remote machine, you can simply set the - * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: - * - * SELENIUM_BROWSER=chrome:36:LINUX \ - * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ - * node mytest.js - * - * You could also use a local copy of the standalone Selenium server: - * - * SELENIUM_BROWSER=chrome:36:LINUX \ - * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ - * node mytest.js - */ class Builder { //region Constructors @@ -3648,45 +2664,15 @@ declare namespace webdriver { //region Methods - /** - * Configures this builder to ignore any environment variable overrides and to - * only use the configuration specified through this instance's API. - * - * @return {!Builder} A self reference. - */ - disableEnvironmentOverrides(): Builder; - /** * Creates a new WebDriver client based on this builder's current * configuration. * - * While this method will immediately return a new WebDriver instance, any - * commands issued against it will be deferred until the associated browser - * has been fully initialized. Users may call {@link #buildAsync()} to obtain - * a promise that will not be fulfilled until the browser has been created - * (the difference is purely in style). - * * @return {!webdriver.WebDriver} A new WebDriver instance. * @throws {Error} If the current configuration is invalid. - * @see #buildAsync() */ build(): WebDriver; - /** - * Creates a new WebDriver client based on this builder's current - * configuration. This method returns a promise that will not be fulfilled - * until the new browser session has been fully initialized. - * - * __Note:__ this method is purely a convenience wrapper around - * {@link #build()}. - * - * @return {!promise.Promise} A promise that will be - * fulfilled with the newly created WebDriver instance once the browser - * has been fully initialized. - * @see #build() - */ - buildAsync(): webdriver.promise.Promise; - /** * Configures the target browser for clients created by this instance. * Any calls to {@link #withCapabilities} after this function will @@ -3719,12 +2705,6 @@ declare namespace webdriver { */ getServerUrl(): string; - /** - * @return {?string} The URL of the proxy server to use for the WebDriver's - * HTTP connections, or `null` if not set. - */ - getWebDriverProxy(): string; - /** * Sets the default action to take with an unexpected alert before returning * an error. @@ -3755,17 +2735,6 @@ declare namespace webdriver { */ setControlFlow(flow: webdriver.promise.ControlFlow): Builder; - /** - * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser - * for drivers created by this builder. Any proxy settings defined on the - * given options will take precedence over those set through - * {@link #setProxy}. - * - * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. - * @return {!Builder} A self reference. - */ - setEdgeOptions(options: edge.Options): Builder; - /** * Sets whether native events should be used. * @param {boolean} enabled Whether to enable native events. @@ -3784,16 +2753,6 @@ declare namespace webdriver { */ setFirefoxOptions(options: firefox.Options): Builder; - /** - * Set Internet Explorer specific {@linkplain ie.Options options} for drivers - * created by this builder. Any proxy settings defined on the given options - * will take precedence over those set through {@link #setProxy}. - * - * @param {!ie.Options} options The IEDriver options to use. - * @return {!Builder} A self reference. - */ - setIeOptions(options: ie.Options): Builder; - /** * Sets the logging preferences for the created session. Preferences may be * changed by repeated calls, or by calling {@link #withCapabilities}. @@ -3801,37 +2760,17 @@ declare namespace webdriver { * desired logging preferences. * @return {!Builder} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Builder; - - /** - * Sets Opera specific {@linkplain opera.Options options} for drivers created - * by this builder. Any logging or proxy settings defined on the given options - * will take precedence over those set through {@link #setLoggingPrefs} and - * {@link #setProxy}, respectively. - * - * @param {!opera.Options} options The OperaDriver options to use. - * @return {!Builder} A self reference. - */ - setOperaOptions(options: opera.Options): Builder; + setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; + setLoggingPrefs(prefs: { [key: string]: string }): Builder; /** * Sets the proxy configuration to use for WebDriver clients created by this * builder. Any calls to {@link #withCapabilities} after this function will * overwrite these settings. - * @param {!capabilities.ProxyConfig} config The configuration to use. + * @param {!webdriver.ProxyConfig} config The configuration to use. * @return {!Builder} A self reference. */ - setProxy(config: webdriver.ProxyConfig): Builder; - - /** - * Sets Safari specific {@linkplain safari.Options options} for drivers - * created by this builder. Any logging settings defined on the given options - * will take precedence over those set through {@link #setLoggingPrefs}. - * - * @param {!safari.Options} options The Safari options to use. - * @return {!Builder} A self reference. - */ - setSafari(options: safari.Options): Builder; + setProxy(config: ProxyConfig): Builder; /** * Sets how elements should be scrolled into view for interaction. @@ -3854,16 +2793,6 @@ declare namespace webdriver { */ usingServer(url: string): Builder; - /** - * Sets the URL of the proxy to use for the WebDriver's HTTP connections. - * If this method is never called, the Builder will create a connection - * without a proxy. - * - * @param {string} proxy The URL of a proxy to use. - * @return {!Builder} A self reference. - */ - usingWebDriverProxy(proxy: string): Builder; - /** * Sets the desired capabilities when requesting a new session. This will * overwrite any previously set capabilities. @@ -3871,149 +2800,12 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Object|Capabilities): Builder; + withCapabilities(capabilities: Capabilities): Builder; + withCapabilities(capabilities: any): Builder; //endregion } - /** - * Describes a mechanism for locating an element on the page. - * @final - */ - class By { - - /** - * @param {string} using the name of the location strategy to use. - * @param {string} value the value to search for. - */ - constructor(using: string, value: string); - - /** - * Locates elements that have a specific class name. - * - * @param {string} name The class name to search for. - * @return {!By} The new locator. - * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes - * @see http://www.w3.org/TR/CSS2/selector.html#class-html - */ - static className(name: string): By; - - /** - * Locates elements using a CSS selector. - * - * @param {string} selector The CSS selector to use. - * @return {!By} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - static css(selector: string): By; - - /** - * Locates eleemnts by the ID attribute. This locator uses the CSS selector - * `*[id="$ID"]`, _not_ `document.getElementById`. - * - * @param {string} id The ID to search for. - * @return {!By} The new locator. - */ - static id(id: string): By; - - /** - * Locates link elements whose - * {@linkplain webdriver.WebElement#getText visible text} matches the given - * string. - * - * @param {string} text The link text to search for. - * @return {!By} The new locator. - */ - static linkText(text: string): By; - - /** - * Locates an elements by evaluating a - * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. - * The result of this expression must be an element or list of elements. - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {function(!./webdriver.WebDriver): !./promise.Promise} - * A new JavaScript-based locator function. - */ - static js(script: string|Function, ...var_args: Array): (webdriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose `name` attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!By} The new locator. - */ - static name(name: string): By; - - /** - * Locates link elements whose - * {@linkplain webdriver.WebElement#getText visible text} contains the given - * substring. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!By} The new locator. - */ - static partialLinkText(text: string): By; - - /** - * Locates elements with a given tag name. - * - * @param {string} name The tag name to search for. - * @return {!By} The new locator. - * @deprecated Use {@link By.css() By.css(tagName)} instead. - */ - static tagName(name: string): By; - - /** - * Locates elements matching a XPath selector. Care should be taken when - * using an XPath selector with a {@link webdriver.WebElement} as WebDriver - * will respect the context in the specified in the selector. For example, - * given the selector `//div`, WebDriver will search from the document root - * regardless of whether the locator was used with a WebElement. - * - * @param {string} xpath The XPath selector to use. - * @return {!By} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - static xpath(xpath: string): By; - - /** @override */ - toString(): string; - } - - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type ByHash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - /** * Common webdriver capability keys. * @enum {string} @@ -4084,7 +2876,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -4118,7 +2910,8 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities|Object); + constructor(opt_other?: Capabilities); + constructor(opt_other?: any); //endregion @@ -4134,7 +2927,8 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities|Object): Capabilities; + merge(other: Capabilities): Capabilities; + merge(other: any): Capabilities; /** * @param {string} key The capability to set. @@ -4152,7 +2946,9 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; + setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; + setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; + /** * Sets the proxy configuration for this instance. @@ -4214,11 +3010,6 @@ declare namespace webdriver { */ static chrome(): Capabilities; - /** - * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. - */ - static edge(): Capabilities; - /** * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. */ @@ -4392,8 +3183,6 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; - - UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -4452,47 +3241,19 @@ declare namespace webdriver { } /** - * Handles the execution of WebDriver {@link Command commands}. - * @interface + * Handles the execution of {@code webdriver.Command} objects. */ - class Executor { - /** - * Executes the given {@code command}. If there is an error executing the - * command, the provided callback will be invoked with the offending error. - * Otherwise, the callback will be invoked with a null Error and non-null - * response object. - * - * @param {!Command} command The command to execute. - * @return {!promise.Promise} A promise that will be fulfilled with - * the command result. - */ - execute(command: Command): webdriver.promise.Promise - } - - /** - * Wraps a promised {@link Executor}, ensuring no commands are executed until - * the wrapped executor has been fully resolved. - * @implements {Executor} - */ - class DeferredExecutor { - /** - * @param {!promise.Promise} delegate The promised delegate, which - * may be provided by any promise-like thenable object. - */ - constructor(delegate: webdriver.promise.Promise); - } - - /** - * Describes an event listener registered on an {@linkplain EventEmitter}. - */ - class Listener { - /** - * @param {!Function} fn The acutal listener function. - * @param {(Object|undefined)} scope The object in whose scope to invoke the - * listener. - * @param {boolean} oneshot Whether this listener should only be used once. - */ - constructor(fn: Function, scope: Object, oneshot: boolean); + interface CommandExecutor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * {@link bot.response.ResponseObject} object. + * @param {!webdriver.Command} command The command to execute. + * @param {function(Error, !bot.response.ResponseObject=)} callback the function + * to invoke when the command response is ready. + */ + execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; } /** @@ -4522,42 +3283,39 @@ declare namespace webdriver { /** * Returns a mutable list of listeners for a specific type of event. * @param {string} type The type of event to retrieve the listeners for. - * @return {!Set} The registered listeners for the given event - * type. + * @return {!Array.<{fn: !Function, oneshot: boolean, + * scope: (Object|undefined)}>} The registered listeners for + * the given event type. */ - listeners(type: string): any; + listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; /** * Registers a listener. * @param {string} type The type of event to listen for. - * @param {!Function} fn The function to invoke when the event is fired. - * @param {Object=} opt_self The object in whose scope to invoke the listener. - * @param {boolean=} opt_oneshot Whether the listener should b (e removed after - * the first event is fired. - * @return {!EventEmitter} A self reference. - * @private + * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {Object=} opt_scope The object in whose scope to invoke the listener. + * @return {!webdriver.EventEmitter} A self reference. */ - addListener(type: string, fn: Function, opt_scope?:any, opt_oneshot?: boolean): EventEmitter; - + addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; /** * Registers a one-time listener which will be called only the first time an * event is emitted, after which it will be removed. * @param {string} type The type of event to listen for. - * @param {!Function} fn The function to invoke when the event is fired. + * @param {!Function} listenerFn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - once(type: string, fn: any, opt_scope?: any): EventEmitter; + once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; /** * An alias for {@code #addListener()}. * @param {string} type The type of event to listen for. - * @param {!Function} fn The function to invoke when the event is fired. + * @param {!Function} listenerFn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - on(type: string, fn: Function, opt_scope?:any): EventEmitter; + on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -4582,20 +3340,14 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - class Navigation { + interface WebDriverNavigation { //region Constructors /** - * Interface for navigating back and forth in the browser history. - * - * This class should never be instantiated directly. Insead, obtain an instance - * with - * - * webdriver.navigate() - * - * @see WebDriver#navigate() + * @param {!webdriver.WebDriver} driver The parent driver. + * @constructor */ - constructor(driver: WebDriver); + new (driver: WebDriver): WebDriverNavigation; //endregion @@ -4645,14 +3397,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - class Options { + interface WebDriverOptions { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: webdriver.WebDriver): WebDriverOptions; //endregion @@ -4665,13 +3417,13 @@ declare namespace webdriver { * @param {string=} opt_path The cookie path. * @param {string=} opt_domain The cookie domain. * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified - * as a number, should be in milliseconds since midnight, - * January 1, 1970 UTC. - * @return {!promise.Promise} A promise that will be resolved - * when the cookie has been added to the page. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as + * a number, should be in milliseconds since midnight, January 1, 1970 UTC. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * cookie has been added to the page. */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number|Date): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -4715,19 +3467,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): webdriver.Logs; + logs(): WebDriverLogs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): webdriver.Timeouts; + timeouts(): WebDriverTimeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): webdriver.Window; + window(): WebDriverWindow; //endregion } @@ -4735,14 +3487,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - class Timeouts { + interface WebDriverTimeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverTimeouts; //endregion @@ -4797,7 +3549,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - class Window { + interface WebDriverWindow { //region Constructors @@ -4805,7 +3557,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverWindow; //endregion @@ -4860,7 +3612,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - class Logs { + interface WebDriverLogs { //region Constructors @@ -4868,7 +3620,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverLogs; //endregion @@ -4888,7 +3640,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: webdriver.logging.Type): webdriver.promise.Promise; + get(type: string): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -4903,7 +3655,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - class TargetLocator { + interface WebDriverTargetLocator { //region Constructors @@ -4911,7 +3663,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - constructor(driver: webdriver.WebDriver); + new (driver: WebDriver): WebDriverTargetLocator; //endregion @@ -4935,47 +3687,44 @@ declare namespace webdriver { /** * Schedules a command to switch the focus of all future commands to another - * frame on the page. The target frame may be specified as one of the - * following: - * - * - A number that specifies a (zero-based) index into [window.frames]( - * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). - * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` - * DOM element. - * - The `null` value, to select the topmost frame on the page. Passing `null` - * is the same as calling {@link #defaultContent defaultContent()}. - * - * If the specified frame can not be found, the returned promise will be - * rejected with a {@linkplain error.NoSuchFrameError}. - * - * @param {(number|WebElement|null)} id The frame locator. - * @return {!promise.Promise} A promise that will be resolved - * when the driver has changed focus to the specified frame. + * frame on the page. + *

    + * If the frame is specified by a number, the command will switch to the frame + * by its (zero-based) index into the {@code window.frames} collection. + *

    + * If the frame is specified by a string, the command will select the frame by + * its name or ID. To select sub-frames, simply separate the frame names/IDs by + * dots. As an example, "main.child" will select the frame with the name "main" + * and then its child "child". + *

    + * If the specified frame can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. + * @param {string|number} nameOrIndex The frame locator. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified frame. */ - frame(nameOrIndex: number|WebElement): webdriver.promise.Promise; + frame(nameOrIndex: string): webdriver.promise.Promise; + frame(nameOrIndex: number): webdriver.promise.Promise; /** * Schedules a command to switch the focus of all future commands to another * window. Windows may be specified by their {@code window.name} attribute or - * by its handle (as returned by {@link WebDriver#getWindowHandles}). - * - * If the specified window cannot be found, the returned promise will be - * rejected with a {@linkplain error.NoSuchWindowError}. - * + * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). + *

    + * If the specificed window can not be found, the deferred result will errback + * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. * @param {string} nameOrHandle The name or window handle of the window to * switch focus to. - * @return {!promise.Promise} A promise that will be resolved - * when the driver has changed focus to the specified window. + * @return {!webdriver.promise.Promise} A promise that will be resolved when the + * driver has changed focus to the specified window. */ window(nameOrHandle: string): webdriver.promise.Promise; /** - * Schedules a command to change focus to the active modal dialog, such as - * those opened by `window.alert()`, `window.confirm()`, and - * `window.prompt()`. The returned promise will be rejected with a - * {@linkplain error.NoSuchAlertError} if there are no open alerts. - * - * @return {!AlertPromise} The open alert. + * Schedules a command to change focus to the active alert dialog. This command + * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal + * dialog is not currently open. + * @return {!webdriver.Alert} The open alert. */ alert(): AlertPromise; @@ -5040,14 +3789,27 @@ declare namespace webdriver { //region Constructors /** - * @param {!(Session|promise.Promise)} session Either a + * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a * known session or a promise that will be resolved to a session. - * @param {!command.Executor} executor The executor to use when sending - * commands to the browser. - * @param {promise.ControlFlow=} opt_flow The flow to + * @param {!webdriver.CommandExecutor} executor The executor to use when + * sending commands to the browser. + * @param {webdriver.promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. + * @constructor */ - constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); + + //endregion + + //region Static Properties + + static Navigation: WebDriverNavigation; + static Options: WebDriverOptions; + static Timeouts: WebDriverTimeouts; + static Window: WebDriverWindow; + static Logs: WebDriverLogs; + static TargetLocator: WebDriverTargetLocator; //endregion @@ -5055,29 +3817,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!command.Executor} executor Command executor to use when querying - * for session details. + * @param {!webdriver.CommandExecutor} executor Command executor to use when + * querying for session details. * @param {string} sessionId ID of the session to attach to. - * @param {promise.ControlFlow=} opt_flow The control flow all - * driver commands should execute under. Defaults to the - * {@link promise.controlFlow() currently active} control flow. - * @return {!WebDriver} A new client for the specified session. + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * commands should execute under. Defaults to the + * {@link webdriver.promise.controlFlow() currently active} control flow. + * @return {!webdriver.WebDriver} A new client for the specified session. */ - static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. - * @param {!command.Executor} executor The executor to create the new session - * with. - * @param {!./capabilities.Capabilities} desiredCapabilities The desired + * @param {!webdriver.CommandExecutor} executor The executor to create the new + * session with. + * @param {!webdriver.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {promise.ControlFlow=} opt_flow The control flow all driver + * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. - * Defaults to the {@link promise.controlFlow() currently active} + * Defaults to the {@link webdriver.promise.controlFlow() currently active} * control flow. - * @return {!WebDriver} The driver for the newly created session. + * @return {!webdriver.WebDriver} The driver for the newly created session. */ - static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -5090,22 +3852,20 @@ declare namespace webdriver { controlFlow(): webdriver.promise.ControlFlow; /** - * Schedules a {@link command.Command} to be executed by this driver's - * {@link command.Executor}. - * - * @param {!command.Command} command The command to schedule. + * Schedules a {@code webdriver.Command} to be executed by this driver's + * {@code webdriver.CommandExecutor}. + * @param {!webdriver.Command} command The command to schedule. * @param {string} description A description of the command for debugging. - * @return {!promise.Promise} A promise that will be resolved - * with the command result. - * @template T + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the command result. */ schedule(command: Command, description: string): webdriver.promise.Promise; /** - * Sets the {@linkplain input.FileDetector file detector} that should be + * Sets the {@linkplain webdriver.FileDetector file detector} that should be * used with this instance. - * @param {input.FileDetector} detector The detector to use or {@code null}. + * @param {webdriver.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -5135,23 +3895,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link actions.ActionSequence#perform} is + * scheduled for execution until {@link webdriver.ActionSequence#perform} is * called. Example: - * - * driver.actions(). - * mouseDown(element1). - * mouseMove(element2). - * mouseUp(). - * perform(); - * - * @return {!actions.ActionSequence} A new action sequence for this instance. + *

    
    +         *   driver.actions().
    +         *       mouseDown(element1).
    +         *       mouseMove(element2).
    +         *       mouseUp().
    +         *       perform();
    +         * 
    + * @return {!webdriver.ActionSequence} A new action sequence for this instance. */ actions(): ActionSequence; /** * Creates a new touch sequence using this driver. The sequence will not be - * scheduled for execution until {@link actions.TouchSequence#perform} is + * scheduled for execution until {@link webdriver.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -5159,7 +3919,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!actions.TouchSequence} A new touch sequence for this instance. + * @return {!webdriver.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -5201,7 +3961,8 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -5418,27 +4179,38 @@ declare namespace webdriver { * var e1 = driver.findElement(By.id('foo')); * var e2 = driver.findElement({id:'foo'}); * - * You may also provide a custom locator function, which takes as input this - * instance and returns a {@link WebElement}, or a promise that will resolve - * to a WebElement. If the returned promise resolves to an array of - * WebElements, WebDriver will use the first element. For example, to find the - * first visible link on a page, you could write: + * You may also provide a custom locator function, which takes as input + * this WebDriver instance and returns a {@link webdriver.WebElement}, or a + * promise that will resolve to a WebElement. For example, to find the first + * visible link on a page, you could write: * * var link = driver.findElement(firstVisibleLink); * * function firstVisibleLink(driver) { * var links = driver.findElements(By.tagName('a')); - * return promise.filter(links, function(link) { - * return link.isDisplayed(); + * return webdriver.promise.filter(links, function(link) { + * return links.isDisplayed(); + * }).then(function(visibleLinks) { + * return visibleLinks[0]; * }); * } * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!WebElementPromise} A WebElement that can be used to issue + * When running in the browser, a WebDriver cannot manipulate DOM elements + * directly; it may do so only through a {@link webdriver.WebElement} reference. + * This function may be used to generate a WebElement from a DOM element. A + * reference to the DOM element will be stored in a known location and this + * driver will attempt to retrieve it through {@link #executeScript}. If the + * element cannot be found (eg, it belongs to a different document than the + * one this instance is currently focused on), a + * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The + * locator to use. + * @return {!webdriver.WebElement} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By|Function): WebElementPromise; + findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -5447,36 +4219,35 @@ declare namespace webdriver { * document the driver is currently focused on. Otherwise, the function will * test if at least one element can be found with the given search criteria. * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!promise.Promise} A promise that will resolve + * @param {!(webdriver.Locator|webdriver.By.Hash|Element| + * Function)} locatorOrElement The locator to use, or the actual + * DOM element to be located by the server. + * @return {!webdriver.promise.Promise.} A promise that will resolve * with whether the element is present on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * driver.findElements(locator).then(e => !!e.length); */ - isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; + isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {!(by.By|Function)} locator The locator to use. - * @return {!promise.Promise.>} A + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By|Function): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to * return a screenshot of the following, in order of preference: + *
      + *
    1. Entire page + *
    2. Current window + *
    3. Visible portion of the current frame + *
    4. The screenshot of the entire display containing the browser + *
    * - * 1. Entire page - * 2. Current window - * 3. Visible portion of the current frame - * 4. The entire display containing the browser - * - * @return {!promise.Promise} A promise that will be + * @return {!webdriver.promise.Promise.} A promise that will be * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; @@ -5485,25 +4256,45 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): webdriver.Options; + manage(): WebDriverOptions; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): Navigation; + navigate(): WebDriverNavigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): webdriver.TargetLocator; + switchTo(): WebDriverTargetLocator; //endregion } interface IWebElementId { - [ELEMENT:string]: string; + ELEMENT: string; + } + + /** + * Defines an object that can be asynchronously serialized to its WebDriver + * wire representation. + * + * @constructor + * @template T + */ + interface Serializable { + /** + * Returns either this instance's serialized represention, if immediately + * available, or a promise for its serialized representation. This function is + * conceptually equivalent to objects that have a {@code toJSON()} property, + * except the serialize() result may be a promise or an object containing a + * promise (which are not directly JSON friendly). + * + * @return {!(T|IThenable.)} This instance's serialized wire format. + */ + serialize(): T|webdriver.promise.IThenable; } /** @@ -5763,7 +4554,7 @@ declare namespace webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By|Function): WebElementPromise; + findElement(locator: Locator|By.Hash|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -5774,7 +4565,7 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: By|Function): webdriver.promise.Promise; + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -5785,9 +4576,10 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By|Function): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; } + /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -5808,6 +4600,7 @@ declare namespace webdriver { serialize(): T|webdriver.promise.IThenable; } + /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@link webdriver.WebDriver} instance, or by searching @@ -5833,59 +4626,35 @@ declare namespace webdriver { */ class WebElement implements Serializable { /** - * @param {!WebDriver} driver the parent WebDriver instance for this element. - * @param {(!IThenable|string)} id The server-assigned opaque ID for - * the underlying DOM element. + * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!(webdriver.promise.Promise.| + * webdriver.WebElement.Id)} id The server-assigned opaque ID for the + * underlying DOM element. + * @constructor */ - constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); + constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); /** - * @param {string} id The raw ID. - * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. - * @return {!Object} The element ID for use with WebDriver's wire protocol. + * Wire protocol definition of a WebElement ID. + * @typedef {{ELEMENT: string}} + * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol */ - static buildId(id: string, opt_noLegacy?: boolean): Object; + static Id: IWebElementId; /** - * Extracts the encoded WebElement ID from the object. - * - * @param {?} obj The object to extract the ID from. - * @return {string} the extracted ID. - * @throws {TypeError} if the object is not a valid encoded ID. + * The property key used in the wire protocol to indicate that a JSON object + * contains the ID of a WebElement. + * @type {string} + * @const */ - static extractId(obj: IWebElementId): string; + static ELEMENT_KEY: string; - /** - * @param {?} obj the object to test. - * @return {boolean} whether the object is a valid encoded WebElement ID. - */ - static isId(obj: IWebElementId): boolean; - - /** - * Compares two WebElements for equality. - * - * @param {!WebElement} a A WebElement. - * @param {!WebElement} b A WebElement. - * @return {!promise.Promise} A promise that will be - * resolved to whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; /** * @return {!webdriver.WebDriver} The parent driver for this instance. */ - getDriver(): webdriver.WebDriver; - - /** - * @return {!promise.Promise} A promise that resolves to - * the server-assigned opaque ID assigned to this element. - */ - getId(): webdriver.promise.Promise; - - /** - * @deprecated Use {@link #getId()} instead. - */ - getRawId(): any; + getDriver(): WebDriver; /** * Schedule a command to find a descendant of this element. If the element @@ -5919,40 +4688,35 @@ declare namespace webdriver { * }); * } * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!WebElementPromise} A WebElement that can be used to issue + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.WebElement} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: By|Function): WebElementPromise; + findElement(locator: Locator|By.Hash|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this * element that matches the given search criteria. * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise} A promise that will be + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the element. + * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. - * @deprecated This method will be removed in Selenium 3.0 for consistency - * with the other Selenium language bindings. This method is equivalent - * to - * - * element.findElements(locator).then(e => !!e.length); */ - isElementPresent(locator: By|Function): webdriver.promise.Promise; + isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that * match the given search criteria. * - * @param {!(by.By|Function)} locator The locator strategy to use when - * searching for the element. - * @return {!promise.Promise>} A + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The + * locator strategy to use when searching for the elements. + * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: By|Function): webdriver.promise.Promise; + findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -5963,7 +4727,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * promsieinstance. + * instance. * * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is * processed in the keysequence, that key state is toggled until one of the @@ -6035,7 +4799,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!promise.Promise} A promise that will be + * @return {!webdriver.promise.Promise.} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -6121,10 +4885,10 @@ declare namespace webdriver { submit(): webdriver.promise.Promise; /** - * Schedules a command to clear the `value` of this element. This command has - * no effect if the underlying DOM element is neither a text INPUT element + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element * nor a TEXTAREA element. - * @return {!promise.Promise} A promise that will be resolved + * @return {!webdriver.promise.Promise.} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -6136,18 +4900,6 @@ declare namespace webdriver { */ isDisplayed(): webdriver.promise.Promise; - /** - * Take a screenshot of the visible region encompassed by this element's - * bounding rectangle. - * - * @param {boolean=} opt_scroll Optional argument that indicates whether the - * element should be scrolled into view before taking a screenshot. - * Defaults to false. - * @return {!promise.Promise} A promise that will be - * resolved to the screenshot as a base-64 encoded PNG. - */ - takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; - /** * Schedules a command to retrieve the outer HTML of this element. * @return {!webdriver.promise.Promise.} A promise that will be @@ -6155,6 +4907,25 @@ declare namespace webdriver { */ getOuterHtml(): webdriver.promise.Promise; + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise; + + /** + * Returns the raw ID string ID for this element. + * @return {!webdriver.promise.Promise} A promise that resolves to this + * element's raw ID as a string value. + * @package + */ + getRawId(): webdriver.promise.Promise; + + /** @override */ + serialize(): webdriver.promise.Promise; + /** * Schedules a command to retrieve the inner HTML of this element. * @return {!webdriver.promise.Promise} A promise that will be resolved with the @@ -6162,8 +4933,14 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** @override */ - serialize(): webdriver.promise.Promise; + /** + * Compares to WebElements for equality. + * @param {!webdriver.WebElement} a A WebElement. + * @param {!webdriver.WebElement} b A WebElement. + * @return {!webdriver.promise.Promise} A promise that will be resolved to + * whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; } /** @@ -6189,14 +4966,6 @@ declare namespace webdriver { * @final */ class WebElementPromise extends WebElement implements webdriver.promise.IThenable { - /** - * @param {!WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!promise.Promise} el A promise - * that will resolve to the promised element. - */ - constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); - /** * Cancels the computation of this promise's value, rejecting the promise in the * process. This method is a no-op if the promise has alreayd been resolved. @@ -6306,31 +5075,191 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; + } + + namespace By { + /** + * Locates elements that have a specific class name. The returned locator + * is equivalent to searching for elements with the CSS selector ".clazz". + * + * @param {string} className The class name to search for. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + function className(value: string): Locator; /** - * Registers a listener for when this promise is rejected. This is synonymous - * with the {@code catch} clause in a synchronous API: + * Locates elements using a CSS selector. For browsers that do not support + * CSS selectors, WebDriver implementations may return an + * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An + * implementation may, however, emulate the CSS selector API. * - * // Synchronous API: - * try { - * doSynchronousWork(); - * } catch (ex) { - * console.error(ex); - * } - * - * // Asynchronous promise API: - * doAsynchronousWork().catch(function(ex) { - * console.error(ex); - * }); - * - * @param {function(*): (R|IThenable)} errback The - * function to call if this promise is rejected. The function should - * expect a single argument: the rejection reason. - * @return {!ManagedPromise} A new promise which will be - * resolved with the result of the invoked callback. - * @template R + * @param {string} selector The CSS selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html */ - catch(errback: Function): webdriver.promise.Promise; + function css(value: string): Locator; + + /** + * Locates an element by its ID. + * + * @param {string} id The ID to search for. + * @return {!webdriver.Locator} The new locator. + */ + function id(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} matches the given string. + * + * @param {string} text The link text to search for. + * @return {!webdriver.Locator} The new locator. + */ + function linkText(value: string): Locator; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, + * JavaScript-based locator function. + */ + function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose {@code name} attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!webdriver.Locator} The new locator. + */ + function name(value: string): Locator; + + /** + * Locates link elements whose {@linkplain webdriver.WebElement#getText visible + * text} contains the given substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + */ + function partialLinkText(value: string): Locator; + + /** + * Locates elements with a given tag name. The returned locator is + * equivalent to using the + * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) + * DOM function. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html + */ + function tagName(value: string): Locator; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector {@code "//div"}, WebDriver will search from the + * document root regardless of whether the locator was used with a + * WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!webdriver.Locator} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + function xpath(value: string): Locator; + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type Hash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + } + + /** + * An element locator. + */ + class Locator { + /** + * An element locator. + * @param {string} using The type of strategy to use for this locator. + * @param {string} value The search target of this locator. + * @constructor + */ + constructor(using: string, value: string); + + + /** + * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. + * @type {!Object.} + * @const + */ + static Strategy: { + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + js: typeof webdriver.By.js; + linkText: typeof webdriver.By.linkText; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; + }; + + /** + * Verifies that a {@code value} is a valid locator to use for searching for + * elements on the page. + * + * @param {*} value The value to check is a valid locator. + * @return {!(webdriver.Locator|Function)} A valid locator object or function. + * @throws {TypeError} If the given value is an invalid locator. + */ + static checkLocator(value: any): Locator | Function; + + /** + * The search strategy to use when searching for an element. + * @type {string} + */ + using: string; + + /** + * The search target for this locator. + * @type {string} + */ + value: string; + + /** @return {string} String representation of this locator. */ + toString(): string; } /** @@ -6346,7 +5275,8 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities|Object); + constructor(id: string, capabilities: Capabilities); + constructor(id: string, capabilities: any); //endregion @@ -6360,7 +5290,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): webdriver.Capabilities; + getCapabilities(): Capabilities; /** * Retrieves the value of a specific capability. @@ -6446,6 +5376,10 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } +declare module 'selenium-webdriver/firefox' { + export = firefox; +} + declare module 'selenium-webdriver/executors' { export = executors; } From 08850929a37774c447dba246e80a2e65d5035d33 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 17:10:58 +0800 Subject: [PATCH 085/212] Since express has been imported, it should be used --- twilio/twilio.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 8ef14760b8..d6c2dfebf7 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -449,7 +449,7 @@ declare module twilio { export function webhook(options?: string | webhookOptions): MiddlewareFunction; export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; - export function validateExpressRequest(request: Express.Request, authToken: string, options?: WebhookExpressOptions): boolean; + export function validateExpressRequest(request: express.Request, authToken: string, options?: WebhookExpressOptions): boolean; /// resources/Accounts.js export interface OutgoingCallerIdInstance extends InstanceResource { From a715a568847661320c4f643dc1c6f318c0a3e440 Mon Sep 17 00:00:00 2001 From: Jonny Stoten Date: Thu, 15 Sep 2016 14:19:23 +0100 Subject: [PATCH 086/212] Add some typings for multipart upload (#11223) --- aws-sdk/aws-sdk.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index b950790058..09ec2f6267 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -236,6 +236,11 @@ declare module "aws-sdk" { listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void; listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void; waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void; + + createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; + uploadPart(params: any, callback: (err: Error, data: any) => void): void; + listParts(params: any, callback: (err: Error, data: any) => void): void; + completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void; } export class STS { From 1a97636e037e5a0c1dff8d723c8585db24ccf433 Mon Sep 17 00:00:00 2001 From: paulmorphy Date: Thu, 15 Sep 2016 15:20:21 +0200 Subject: [PATCH 087/212] Added definition for the missing dns.setServers(servers) method (#11183) * Added definition for the missing dns.setServers(servers) method Method is documented here: https://nodejs.org/docs/latest/api/dns.html#dns_dns_setservers_servers * Updated definition for dns.resolveMx The addresses argument passed to the callback function will contain an array of objects containing both a priority and exchange property: https://nodejs.org/docs/latest/api/dns.html#dns_dns_resolvemx_hostname_callback --- node/node.d.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/node/node.d.ts b/node/node.d.ts index 2094959e6e..e4e66e69ee 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1396,18 +1396,24 @@ declare module "url" { } declare module "dns" { + export interface MxRecord { + exchange: string, + priority: number + } + export function lookup(domain: string, family: number, callback: (err: Error, address: string, family: number) => void): string; export function lookup(domain: string, callback: (err: Error, address: string, family: number) => void): string; 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 resolveMx(domain: string, callback: (err: Error, addresses: MxRecord[]) =>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 setServers(servers: string[]): void; //Error codes export var NODATA: string; From 6a9eb69291eb1154cce41664c668ab479c6c5732 Mon Sep 17 00:00:00 2001 From: Kazuki Oota Date: Thu, 15 Sep 2016 22:22:12 +0900 Subject: [PATCH 088/212] add access property to table. (#11158) * add access property. * fix ci error. --- azure-mobile-apps/azure-mobile-apps-tests.ts | 7 +++++++ azure-mobile-apps/azure-mobile-apps.d.ts | 4 ++++ 2 files changed, 11 insertions(+) diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts index 6b994b4f05..302f732889 100644 --- a/azure-mobile-apps/azure-mobile-apps-tests.ts +++ b/azure-mobile-apps/azure-mobile-apps-tests.ts @@ -72,6 +72,13 @@ table.read.use([function () {}, function () {}]); table.read.use(function () {}, function () {}); table.use(function () {}).use(function () {}).read(function () {}).use(function () {}) +table.access = undefined; +table.access = 'authenticated'; +table.read.access = 'anonymous'; +table.update.access = 'disabled'; +table.delete.access = 'authenticated'; +table.insert.access = 'authenticated'; + // Express.Table, instantiated from the static require('azure-mobile-apps').table() // This is going to be interesting if we ever support more than one provider var table2 = mobileApps.table(); diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts index 436d88b3cb..a17e41e2d6 100644 --- a/azure-mobile-apps/azure-mobile-apps.d.ts +++ b/azure-mobile-apps/azure-mobile-apps.d.ts @@ -47,6 +47,7 @@ declare namespace Azure.MobileApps { interface Table { authorize?: boolean; + access?: AccessType; autoIncrement?: boolean; dynamicSchema?: boolean; name: string; @@ -66,8 +67,11 @@ declare namespace Azure.MobileApps { (operationHandler: (context: Context) => void): Table; use(...middleware: Middleware[]): Table; use(middleware: Middleware[]): Table; + access: AccessType; } + type AccessType = 'anonymous' | 'authenticated' | 'disabled'; + interface Tables { configuration: Configuration; add(name: string, definition?: Table | TableDefinition): void; From d51cb64351dad6f50a890d8cd2ddb2c2a90e3104 Mon Sep 17 00:00:00 2001 From: Jacob Baskin Date: Thu, 15 Sep 2016 09:24:40 -0400 Subject: [PATCH 089/212] Typings for Busboy (#11227) * Add typings for Busboy. * Fix indent style * Fix for es6 imports * Re-add module def --- busboy/busboy-tests.ts | 39 +++++++++++++++++++++++++++ busboy/busboy.d.ts | 60 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 busboy/busboy-tests.ts create mode 100644 busboy/busboy.d.ts diff --git a/busboy/busboy-tests.ts b/busboy/busboy-tests.ts new file mode 100644 index 0000000000..058b5c92d3 --- /dev/null +++ b/busboy/busboy-tests.ts @@ -0,0 +1,39 @@ +/// +/// + +import * as Busboy from 'busboy'; +import * as http from 'http'; +import * as util from 'util'; + +function serverFn(req: http.ServerRequest, res: http.ServerResponse) { + if (req.method === 'POST') { + var busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype); + file.on('data', function(data: Buffer) { + console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); + }); + file.on('end', function() { + console.log('File [' + fieldname + '] Finished'); + }); + }); + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) { + console.log('Field [' + fieldname + ']: value: ' + util.inspect(val)); + }); + busboy.on('finish', function() { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end('\ +
    \ +
    \ +
    \ + \ +
    \ + '); + } +} diff --git a/busboy/busboy.d.ts b/busboy/busboy.d.ts new file mode 100644 index 0000000000..3b64f3d112 --- /dev/null +++ b/busboy/busboy.d.ts @@ -0,0 +1,60 @@ +// Type definitions for busboy v0.2.13 +// Project: https://www.npmjs.com/package/busboy +// Definitions by: Jacob Baskin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// + +declare namespace busboy { + interface Options { + headers: any; + } + + interface BusboyConfig { + headers?: any; + highWaterMark?: number; + fileHwm?: number; + defCharset?: string; + preservePath?: boolean; + limits?: { + fieldNameSize?: number; + fieldSize?: number; + fields?: number; + fileSize?: number; + files?: number; + parts?: number; + headerPairs?: number; + }; + } + + interface Busboy extends NodeJS.WritableStream { + on(event: 'field', + listener: ( + fieldname: string, + val: any, + fieldnameTruncated: boolean, + valTruncated: boolean, + encoding: string, + mimetype: string) => void): this; + on(event: 'file', + listener: ( + fieldname: string, + file: NodeJS.ReadableStream, + filename: string, + encoding: string, + mimetype: string) => void): this; + on(event: 'finish', callback: () => void): this; + on(event: 'partsLimit', callback: () => void): this; + on(event: 'filesLimit', callback: () => void): this; + on(event: 'fieldsLimit', callback: () => void): this; + on(event: string, listener: Function): this; + } + + interface BusboyConstructor { + new (options: BusboyConfig): Busboy; + } +} + +declare module 'busboy' { + const temp: busboy.BusboyConstructor; + export = temp; +} From 1e4db4e1877c0a224f8fd4a6a9bd143a205ed3ea Mon Sep 17 00:00:00 2001 From: Mykhailo Stadnyk Date: Thu, 15 Sep 2016 16:40:19 +0300 Subject: [PATCH 090/212] Added type definitions for new module canvas-gauges (#11211) * Added type definitions for new module canvas-gauges * definitions re-factored as a ghost module * Typo fixed in url protocol --- canvas-gauges/canvas-gauges-tests.ts | 20 ++ canvas-gauges/canvas-gauges.d.ts | 263 +++++++++++++++++++++++++++ 2 files changed, 283 insertions(+) create mode 100644 canvas-gauges/canvas-gauges-tests.ts create mode 100644 canvas-gauges/canvas-gauges.d.ts diff --git a/canvas-gauges/canvas-gauges-tests.ts b/canvas-gauges/canvas-gauges-tests.ts new file mode 100644 index 0000000000..d0f04e1082 --- /dev/null +++ b/canvas-gauges/canvas-gauges-tests.ts @@ -0,0 +1,20 @@ +/// + +import { + LinearGaugeOptions, + RadialGaugeOptions, + LinearGauge, + RadialGauge +} from 'canvas-gauges'; + +let linearOptions: LinearGaugeOptions = { + renderTo: document.createElement('canvas') +}; +let radialOptions: RadialGaugeOptions = { + renderTo: 'gauge-id' +}; + +new LinearGauge(linearOptions); +new RadialGauge(radialOptions); + +console.log(document.gauges.length); diff --git a/canvas-gauges/canvas-gauges.d.ts b/canvas-gauges/canvas-gauges.d.ts new file mode 100644 index 0000000000..53858e566e --- /dev/null +++ b/canvas-gauges/canvas-gauges.d.ts @@ -0,0 +1,263 @@ +// Type definitions for canvas-gauges +// Project: https://github.com/Mikhus/canvas-gauges +// Definitions by: Mikhus +// Definitions: https://github.com/Mikhus/DefinitelyTyped + +declare namespace CanvasGauges { + export type RenderTarget = string|HTMLElement; + + export interface AnimationRule { + (percent: number): number; + } + + export interface Highlight { + from: number, + to: number, + color: string + } + + export type MajorTicks = string[]|number[]; + + export interface GenericOptions { + renderTo: RenderTarget, + width?: number, + height?: number, + minValue?: number, + maxValue?: number, + value?: number, + units?: string|boolean, + majorTicks?: MajorTicks, + minorTicks?: number, + strokeTicks?: boolean, + animatedValue?: boolean, + title?: string|boolean, + borders?: boolean, + valueInt?: number, + valueDec?: number, + majorTicksInt?: number, + majorTicksDec?: number, + animation?: boolean, + animationDuration?: number, + animationRule?: string|AnimationRule, + colorPlate?: string, + colorMajorTicks?: string, + colorMinorTicks?: string, + colorTitle?: string, + colorUnits?: string, + colorNumbers?: string, + colorNeedle?: string, + colorNeedleEnd?: string, + colorValueText?: string, + colorValueTextShadow?: string, + colorBorderShadow?: string, + colorBorderOuter?: string, + colorBorderOuterEnd?: string, + colorBorderMiddle?: string, + colorBorderMiddleEnd?: string, + colorBorderInner?: string, + colorBorderInnerEnd?: string, + colorValueBoxRect?: string, + colorValueBoxRectEnd?: string, + colorValueBoxBackground?: string, + colorValueBoxShadow?: string, + colorNeedleShadowUp?: string, + colorNeedleShadowDown?: string, + needle?: boolean, + needleShadow?: boolean, + needleType?: string, + needleStart?: number, + needleEnd?: number, + needleWidth?: number, + borderOuterWidth?: number, + borderMiddleWidth?: number, + borderInnerWidth?: number, + borderShadowWidth?: number, + valueBox?: boolean, + valueBoxStroke?: number, + valueText?: string, + valueTextShadow?: boolean, + valueBoxBorderRadius?: number, + highlights?: Highlight[], + fontNumbers?: string, + fontTitle?: string, + fontUnits?: string, + fontValue?: string, + fontTitleSize?: number, + fontValueSize?: number, + fontUnitsSize?: number, + fontNumbersSize?: number + } + + export interface RadialGaugeOptions extends GenericOptions { + ticksAngle?: number, + startAngle?: number, + colorNeedleCircleOuter?: string, + colorNeedleCircleOuterEnd?: string, + colorNeedleCircleInner?: string, + colorNeedleCircleInnerEnd?: string, + needleCircleSize?: number, + needleCircleInner?: boolean, + needleCircleOuter?: boolean, + animationTarget?: string + } + + export interface LinearGaugeOptions extends GenericOptions { + borderRadius?: number, + barBeginCircle?: number, + barWidth?: number, + barStrokeWidth?: number, + barProgress?: boolean, + colorBar?: string, + colorBarEnd?: string, + colorBarStroke?: string, + colorBarProgress?: string, + colorBarProgressEnd?: string, + tickSide?: string, + needleSide?: string, + numberSide?: string, + ticksWidth?: number, + ticksWidthMinor?: number, + ticksPadding?: number, + barLength?: number + } + + export interface DrawEventCallback { + (percent: number): any; + } + + export interface EndEventCallback { + (): any; + } + + export interface rules { + linear: AnimationRule, + quad: AnimationRule, + dequad: AnimationRule, + quint: AnimationRule, + dequint: AnimationRule, + cycle: AnimationRule, + decycle: AnimationRule, + bounce: AnimationRule, + debounce: AnimationRule, + elastic: AnimationRule, + delastic: AnimationRule + } + + export class Animation { + public duration: number; + public rule: string|AnimationRule; + public draw: DrawEventCallback; + public end: EndEventCallback; + + public static rules: rules; + + constructor(rule?: string|AnimationRule, duration?: number, + draw?: DrawEventCallback, end?: EndEventCallback); + + public animate(draw?: DrawEventCallback, end?: EndEventCallback): any; + public destroy(): any; + } + + export class SmartCanvas { + public element: HTMLCanvasElement; + public elementClone: HTMLCanvasElement; + public context: CanvasRenderingContext2D; + public contextClone: CanvasRenderingContext2D; + public drawWidth: number; + public drawHeight: number; + public drawX: number; + public drawY: number; + public minSide: number; + public width: number; + public height: number; + + constructor(element: HTMLCanvasElement, + width?: number, + height?: number); + + public init(): any; + public onRedraw(): any; + public destroy(): any; + public commit(): SmartCanvas; + public redraw(): SmartCanvas; + + public pixelRatio: number; + public static redraw(): any; + public static collection: Array; + } + + export class DomObserver { + public Type: BaseGauge; + public mutationsObserved: boolean; + public isObservable: boolean; + public options: GenericOptions; + public element: string; + public type: string; + + constructor(options: GenericOptions, + element: string, + type: string); + + public isValidNode(node: Node|HTMLElement): boolean; + public traverse(): any; + public observe(records: MutationRecord[]): any; + public process(node: Node|HTMLElement): BaseGauge; + + public static parse(value: any): any; + public static toDashed(camelCase: string): string; + public static toAttributeName(str: string): string; + static domReady(handler: Function): any; + } + + export abstract class BaseGauge { + public type: BaseGauge; + public options: GenericOptions; + public canvas: SmartCanvas; + public animation: Animation; + public value: number; + + constructor(options: GenericOptions); + + public update(options: GenericOptions): BaseGauge; + public destroy(): any; + public abstract draw(): BaseGauge; + + public static initialize(type: string, options: GenericOptions): any; + } + + export class RadialGauge extends BaseGauge { + public type: RadialGauge; + public options: RadialGaugeOptions; + + constructor(options: RadialGaugeOptions); + + public draw(): RadialGauge; + } + + export class LinearGauge extends BaseGauge { + public type: LinearGauge; + public options: LinearGaugeOptions; + + constructor(options: LinearGaugeOptions); + + public draw(): LinearGauge; + } + + export interface Collection extends Array { + get: (id: number | string) => BaseGauge; + } +} + +declare module 'canvas-gauges' { + export = CanvasGauges; +} + +interface Document { + gauges: CanvasGauges.Collection; +} + +interface Window { + BaseGauge: CanvasGauges.BaseGauge; + RadialGauge: CanvasGauges.RadialGauge; + LinearGauge: CanvasGauges.LinearGauge; +} From 9d66141d077d4f17f148b41fa1adca7a651102e4 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:41:55 +0800 Subject: [PATCH 091/212] [node.d.ts] Update cluster definition (#11235) * Update cluster * Add ; --- node/node.d.ts | 171 +++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 152 insertions(+), 19 deletions(-) diff --git a/node/node.d.ts b/node/node.d.ts index e4e66e69ee..346f7e7413 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -741,17 +741,30 @@ declare module "http" { declare module "cluster" { import * as child from "child_process"; import * as events from "events"; + import * as net from "net"; + // interfaces export interface ClusterSettings { + execArgv?: string[]; // default: process.execArgv exec?: string; args?: string[]; silent?: boolean; + stdio?: any[]; + uid?: number; + gid?: number; + } + + export interface ClusterSetupMasterSettings { + exec?: string; // default: process.argv[1] + args?: string[]; // default: process.argv.slice(2) + silent?: boolean; // default: false + stdio?: any[]; } export interface Address { address: string; port: number; - addressType: string; + addressType: number | "udp4" | "udp6"; // 4, 6, -1, "udp4", "udp6" } export class Worker extends events.EventEmitter { @@ -766,33 +779,153 @@ declare module "cluster" { isDead(): boolean; } - export var settings: ClusterSettings; + export interface Cluster extends events.EventEmitter { + Worker: Worker; + disconnect(callback?: Function): void; + fork(env?: any): Worker; + isMaster: boolean; + isWorker: boolean; + // TODO: cluster.schedulingPolicy + settings: ClusterSettings; + setupMaster(settings?: ClusterSetupMasterSettings): void; + worker: Worker; + workers: { + [index: string]: Worker + }; + + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: any) => void): this; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: any) => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: any) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: any) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: any) => void): this; + + } + + export function disconnect(callback ?: Function): void; + export function fork(env?: any): Worker; export var isMaster: boolean; export var isWorker: boolean; - export function setupMaster(settings?: ClusterSettings): void; - export function fork(env?: any): Worker; - export function disconnect(callback?: Function): void; + // TODO: cluster.schedulingPolicy + export var settings: ClusterSettings; + export function setupMaster(settings?: ClusterSetupMasterSettings): void; export var worker: Worker; export var workers: { [index: string]: Worker }; - // Event emitter - export function addListener(event: string, listener: Function): void; - export function on(event: "disconnect", listener: (worker: Worker) => void): void; - export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): void; - export function on(event: "fork", listener: (worker: Worker) => void): void; - export function on(event: "listening", listener: (worker: Worker, address: any) => void): void; - export function on(event: "message", listener: (worker: Worker, message: any) => void): void; - export function on(event: "online", listener: (worker: Worker) => void): void; - export function on(event: "setup", listener: (settings: any) => void): void; - export function on(event: string, listener: Function): any; - export function once(event: string, listener: Function): void; - export function removeListener(event: string, listener: Function): void; - export function removeAllListeners(event?: string): void; - export function setMaxListeners(n: number): void; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + export function addListener(event: string, listener: Function): Cluster; + export function addListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function addListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function addListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function addListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function addListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function on(event: string, listener: Function): Cluster; + export function on(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function on(event: "fork", listener: (worker: Worker) => void): Cluster; + export function on(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function on(event: "online", listener: (worker: Worker) => void): Cluster; + export function on(event: "setup", listener: (settings: any) => void): Cluster; + + export function once(event: string, listener: Function): Cluster; + export function once(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function once(event: "fork", listener: (worker: Worker) => void): Cluster; + export function once(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function once(event: "online", listener: (worker: Worker) => void): Cluster; + export function once(event: "setup", listener: (settings: any) => void): Cluster; + + export function removeListener(event: string, listener: Function): Cluster; + export function removeAllListeners(event?: string): Cluster; + export function setMaxListeners(n: number): Cluster; + export function getMaxListeners(): number; export function listeners(event: string): Function[]; export function emit(event: string, ...args: any[]): boolean; + export function listenerCount(type: string): number; + + export function prependListener(event: string, listener: Function): Cluster; + export function prependListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function prependOnceListener(event: string, listener: Function): Cluster; + export function prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): Cluster; + export function prependOnceListener(event: "fork", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): Cluster; + export function prependOnceListener(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): Cluster; // the handle is a net.Socket or net.Server object, or undefined. + export function prependOnceListener(event: "online", listener: (worker: Worker) => void): Cluster; + export function prependOnceListener(event: "setup", listener: (settings: any) => void): Cluster; + + export function eventNames(): string[]; } declare module "zlib" { From a72353df2416348b0d3f176b8019229c87c064bf Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:42:17 +0800 Subject: [PATCH 092/212] [node-tests.ts] A test should move to events_tests in node (#11237) * A test should move to events_tests in node v6.x * A test should move to events_tests in node v4.x --- node/node-4-tests.ts | 18 ++++++++++-------- node/node-tests.ts | 18 ++++++++++-------- 2 files changed, 20 insertions(+), 16 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 35fe3553a6..1aebd6d201 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -108,6 +108,16 @@ namespace events_tests { result = emitter.emit(event, any, any); result = emitter.emit(event, any, any, any); } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } } //////////////////////////////////////////////////// @@ -167,14 +177,6 @@ namespace fs_tests { } -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } -} - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// diff --git a/node/node-tests.ts b/node/node-tests.ts index 7e010bc9a3..19048bea9c 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -118,6 +118,16 @@ namespace events_tests { result = emitter.eventNames(); } + + { + class Networker extends events.EventEmitter { + constructor() { + super(); + + this.emit("mingling"); + } + } + } } //////////////////////////////////////////////////// @@ -212,14 +222,6 @@ namespace fs_tests { } } -class Networker extends events.EventEmitter { - constructor() { - super(); - - this.emit("mingling"); - } -} - /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// From d6854025495626c9e92efd666032f98313a487ce Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:42:34 +0800 Subject: [PATCH 093/212] [node-tests.ts] The test should test type, not function (#11238) * The test should test type, not function * The test should test type, not function --- node/node-4-tests.ts | 8 ++++---- node/node-tests.ts | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 1aebd6d201..30098021ec 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -906,14 +906,13 @@ namespace errors_tests { /////////////////////////////////////////////////////////// import * as p from "process"; -namespace process_tests{ +namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... var _p: NodeJS.Process = process; _p = p; - assert(p === process); } } @@ -922,8 +921,9 @@ namespace process_tests{ /////////////////////////////////////////////////////////// import * as c from "console"; -namespace console_tests{ +namespace console_tests { { - assert(c === console); + var _c: Console = console; + _c = c; } } diff --git a/node/node-tests.ts b/node/node-tests.ts index 19048bea9c..9a2c2e22cd 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -1112,14 +1112,13 @@ namespace errors_tests { /////////////////////////////////////////////////////////// import * as p from "process"; -namespace process_tests{ +namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... var _p: NodeJS.Process = process; _p = p; - assert(p === process); } } @@ -1128,9 +1127,10 @@ namespace process_tests{ /////////////////////////////////////////////////////////// import * as c from "console"; -namespace console_tests{ +namespace console_tests { { - assert(c === console); + var _c: Console = console; + _c = c; } } From 89030200ceb205da4db2fc56d8e750e9c16be92f Mon Sep 17 00:00:00 2001 From: Jeremy Foster Date: Thu, 15 Sep 2016 06:42:49 -0700 Subject: [PATCH 094/212] add err:any to close, flush, and drain methods (#11239) --- serialport/serialport.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/serialport/serialport.d.ts b/serialport/serialport.d.ts index 53d8a4e92e..60c240bbda 100644 --- a/serialport/serialport.d.ts +++ b/serialport/serialport.d.ts @@ -13,10 +13,10 @@ declare module 'serialport' { pause(): void; resume(): void; disconnected(err: Error): void; - close(callback?: () => void): void; - flush(callback?: () => void): void; + close(callback?: (err:any) => void): void; + flush(callback?: (err:any) => void): void; set(options: SerialPort.setOptions, callback: () => void): void; - drain(callback?: () => void): void; + drain(callback?: (err:any) => void): void; update(options: SerialPort.updateOptions, callback?: () => void): void; static list(callback: (err: string, ports: SerialPort.portConfig[]) => void): void; static parsers: { From 62f98f1a3bce86763366541830b482e4117b5cfb Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:43:21 +0800 Subject: [PATCH 095/212] [node-tests.ts] Clean up http_tests and net_tests (#11240) * Clean up http_tests and net_tests * Clean up fs tests and wrap in namespace --- node/node-4-tests.ts | 69 +++++++++++++++++++++++++------------------- node/node-tests.ts | 69 +++++++++++++++++++++++++------------------- 2 files changed, 80 insertions(+), 58 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 30098021ec..2d84e8f175 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -379,27 +379,18 @@ var tlsOpts: tls.TlsOptions = { }; var tlsSocket = tls.connect(tlsOpts); - +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html -//////////////////////////////////////////////////// namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } + { var agent: http.Agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 10000, @@ -409,20 +400,29 @@ namespace http_tests { var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({agent: false}); + http.request({agent: agent}); + http.request({agent: undefined}); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -927,3 +927,14 @@ namespace console_tests { _c = c; } } + +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + // Make sure .listen() and .close() retuern a Server instance + net.createServer().listen(0).close().address(); + } +} diff --git a/node/node-tests.ts b/node/node-tests.ts index 9a2c2e22cd..ef9f48783f 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -554,27 +554,18 @@ var connOpts: tls.ConnectionOptions = { }; var tlsSocket = tls.connect(connOpts); - +//////////////////////////////////////////////////// +/// Http tests : http://nodejs.org/api/http.html /// //////////////////////////////////////////////////// -// Make sure .listen() and .close() retuern a Server instance -http.createServer().listen(0).close().address(); -net.createServer().listen(0).close().address(); - -var request = http.request('http://0.0.0.0'); -request.once('error', function () {}); -request.setNoDelay(true); -request.abort(); - -//////////////////////////////////////////////////// -/// Http tests : http://nodejs.org/api/http.html -//////////////////////////////////////////////////// namespace http_tests { - // Status codes - var code = 100; - var codeMessage = http.STATUS_CODES['400']; - var codeMessage = http.STATUS_CODES[400]; + { + // Status codes + var codeMessage = http.STATUS_CODES['400']; + var codeMessage = http.STATUS_CODES[400]; + } + { var agent: http.Agent = new http.Agent({ keepAlive: true, keepAliveMsecs: 10000, @@ -584,20 +575,29 @@ namespace http_tests { var agent: http.Agent = http.globalAgent; - http.request({ - agent: false - }); - http.request({ - agent: agent - }); - http.request({ - agent: undefined - }); + http.request({agent: false}); + http.request({agent: agent}); + http.request({agent: undefined}); + } + + { + // Make sure .listen() and .close() retuern a Server instance + http.createServer().listen(0).close().address(); + net.createServer().listen(0).close().address(); + } + + { + var request = http.request('http://0.0.0.0'); + request.once('error', function() { }); + request.setNoDelay(true); + request.abort(); + } } -//////////////////////////////////////////////////// -/// Https tests : http://nodejs.org/api/https.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////////// +/// Https tests : http://nodejs.org/api/https.html /// +////////////////////////////////////////////////////// + namespace https_tests { var agent: https.Agent = new https.Agent({ keepAlive: true, @@ -1134,6 +1134,17 @@ namespace console_tests { } } +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + // Make sure .listen() and .close() retuern a Server instance + net.createServer().listen(0).close().address(); + } +} + /***************************************************************************** * * * The following tests are the modules not mentioned in document but existed * From 48f9040fcc94f007cc7f14415ee4959988543949 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:44:31 +0800 Subject: [PATCH 096/212] [node-tests.ts] Clean up crypto_tests and wrap in namespace (#11242) * Clean up crypto_tests tests and wrap in namespace * Clean up crypto_tests and wrap in namespace * Use let to declares a block scope local variable * Use let to declares a block scope local variable --- node/node-4-tests.ts | 80 ++++++++++++++++++++++++-------------------- node/node-tests.ts | 80 ++++++++++++++++++++++++-------------------- 2 files changed, 86 insertions(+), 74 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 2d84e8f175..2de910db67 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -316,51 +316,57 @@ function stream_readable_pipe_test() { r.close(); } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } + + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); - }); -} + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + assert.equal(clearText2, clearText); + } - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); - assert.equal(clearText2, clearText); -} + let cipherText: Buffer = Buffer.concat(cipherBuffers); -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); - var cipherText:Buffer = Buffer.concat(cipherBuffers); + let clearText2: Buffer = Buffer.concat(decipherBuffers); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); + } } //////////////////////////////////////////////////// diff --git a/node/node-tests.ts b/node/node-tests.ts index ef9f48783f..e0600d936d 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -491,51 +491,57 @@ function simplified_stream_ctor_test() { }) } -//////////////////////////////////////////////////// -/// Crypto tests : http://nodejs.org/api/crypto.html -//////////////////////////////////////////////////// +//////////////////////////////////////////////////////// +/// Crypto tests : http://nodejs.org/api/crypto.html /// +//////////////////////////////////////////////////////// -var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); +namespace crypto_tests { + { + var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); + } + + { + let hmac: crypto.Hmac; + (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { + let hash: Buffer | string = hmac.read(); + }); + } + + { + //crypto_cipher_decipher_string_test + let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: string = "This is the clear text."; + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherText: string = cipher.update(clearText, "utf8", "hex"); + cipherText += cipher.final("hex"); -{ - let hmac: crypto.Hmac; - (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { - let hash: Buffer|string = hmac.read(); - }); -} + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let clearText2: string = decipher.update(cipherText, "hex", "utf8"); + clearText2 += decipher.final("utf8"); -function crypto_cipher_decipher_string_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:string = "This is the clear text."; - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherText:string = cipher.update(clearText, "utf8", "hex"); - cipherText += cipher.final("hex"); + assert.equal(clearText2, clearText); + } - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var clearText2:string = decipher.update(cipherText, "hex", "utf8"); - clearText2 += decipher.final("utf8"); + { + //crypto_cipher_decipher_buffer_test + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let clearText: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); + let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); + let cipherBuffers: Buffer[] = []; + cipherBuffers.push(cipher.update(clearText)); + cipherBuffers.push(cipher.final()); - assert.equal(clearText2, clearText); -} + let cipherText: Buffer = Buffer.concat(cipherBuffers); -function crypto_cipher_decipher_buffer_test() { - var key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); - var clearText:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5, 4]); - var cipher:crypto.Cipher = crypto.createCipher("aes-128-ecb", key); - var cipherBuffers:Buffer[] = []; - cipherBuffers.push(cipher.update(clearText)); - cipherBuffers.push(cipher.final()); + let decipher: crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); + let decipherBuffers: Buffer[] = []; + decipherBuffers.push(decipher.update(cipherText)); + decipherBuffers.push(decipher.final()); - var cipherText:Buffer = Buffer.concat(cipherBuffers); + let clearText2: Buffer = Buffer.concat(decipherBuffers); - var decipher:crypto.Decipher = crypto.createDecipher("aes-128-ecb", key); - var decipherBuffers:Buffer[] = []; - decipherBuffers.push(decipher.update(cipherText)); - decipherBuffers.push(decipher.final()); - - var clearText2:Buffer = Buffer.concat(decipherBuffers); - - assert.deepEqual(clearText2, clearText); + assert.deepEqual(clearText2, clearText); + } } //////////////////////////////////////////////////// From 4871fb2876696025b0a1704d629378915d7cdd3c Mon Sep 17 00:00:00 2001 From: TonyYang Date: Thu, 15 Sep 2016 21:45:12 +0800 Subject: [PATCH 097/212] Add listening for http.Server (#11246) --- node/node.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/node/node.d.ts b/node/node.d.ts index 346f7e7413..81b13e4e1d 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -592,6 +592,7 @@ declare module "http" { setTimeout(msecs: number, callback: Function): void; maxHeadersCount: number; timeout: number; + listening: boolean; } /** * @deprecated Use IncomingMessage From 9dbdb50546cbec870208edb11e962872128cc1f8 Mon Sep 17 00:00:00 2001 From: Blake Smith Date: Thu, 15 Sep 2016 08:46:59 -0500 Subject: [PATCH 098/212] Updating elasticsearch definition with some of the missing components (#11149) * Updating elasticsearch definition with some of the missing components. (https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/api-reference.html#api-cluster-getsettings) Adding Cluster definitions, one Cat definition. * Correcting header. --- CONTRIBUTORS.md | 1 + elasticsearch/elasticsearch-tests.ts | 40 +++++++++++++ elasticsearch/elasticsearch.d.ts | 90 +++++++++++++++++++++++++++- 3 files changed, 130 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 7ebdcc514f..44f0d8e9a0 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam * [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii) * [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000) * [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped) +* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped) * [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan) * [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak) * [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT) diff --git a/elasticsearch/elasticsearch-tests.ts b/elasticsearch/elasticsearch-tests.ts index 14070aa8cc..6d308dc6ed 100644 --- a/elasticsearch/elasticsearch-tests.ts +++ b/elasticsearch/elasticsearch-tests.ts @@ -45,4 +45,44 @@ client.create({ index: 'index', type: 'type' }, (err, repsonse, status) => { +}); + +client.cluster.getSettings({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.health({ + masterTimeout: 100 +}, (err, response) => { +}); + +client.cluster.pendingTasks({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.putSettings({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.reroute({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.state({ + ignore: 1 +}, (err, response) => { +}); + +client.cluster.stats({ + ignore: 1 +}, (err, response) => { }); \ No newline at end of file diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index ec67e6a59d..e2079b19d0 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,12 +1,14 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt +// Definitions by: Casper Skydt , Blake Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { export class Client { constructor(params: ConfigOptions); indices: Indices; + cluster: Cluster; + cat: Cat; bulk(params: BulkIndexDocumentsParams): PromiseLike; bulk(params: BulkIndexDocumentsParams, callback: (error: any, response: any) => void): void; create(params: CreateDocumentParams): PromiseLike; @@ -230,6 +232,7 @@ declare module Elasticsearch { scroll?: string; search_type?: string; fields?: string[]; + from?: number; size?: number; sort?: string | string[] | boolean; _source?: string | string[] | boolean; @@ -333,6 +336,91 @@ declare module Elasticsearch { body: string | any; index: string | string[] | boolean; } + + export interface Cat { + health(params: CatHealthOptions, callback: (error: any, response: any) => void): void; + health(params: CatHealthOptions): PromiseLike + } + + export interface CatHealthOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + h?: string | string[] | boolean; + help?: boolean; + ts?: boolean; + v?: boolean; + } + + export interface Cluster { + getSettings(params: ClusterGetSettingsOptions, callback: (error: any, response: any) => void): void; + getSettings(params: ClusterGetSettingsOptions): PromiseLike; + health(params: ClusterHealthOptions, callback: (error: any, response: any) => void): void; + health(params: ClusterHealthOptions): PromiseLike; + pendingTasks(params: ClusterPendingTasksOptions, callback: (error: any, response: any) => void): void; + pendingTasks(params: ClusterPendingTasksOptions): PromiseLike; + putSettings(params: ClusterPutSettingsOptions, callback: (error: any, response: any) => void): void; + putSettings(params: ClusterPutSettingsOptions): PromiseLike; + reroute(params: ClusterRerouteOptions, callback: (error: any, response: any) => void): void; + reroute(params: ClusterRerouteOptions): PromiseLike; + state(params: ClusterStateOptions, callback: (error: any, response: any) => void): void; + state(params: ClusterStateOptions): PromiseLike; + stats(params: ClusterStatsOptions, callback: (error: any, response: any) => void): void; + stats(params: ClusterStatsOptions): PromiseLike; + } + + export interface ClusterGetSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterHealthOptions extends GenericParams { + level?: string; // cluster, indices, shards + local?: boolean; + masterTimeout?: number | Date; + waitForActiveShards?: number; + waitForNodes?: string; + waitForRelocatingShards?: number; + waitForStatus?: string; // green, yellow, red + index?: string | string[] | boolean; + } + + export interface ClusterPendingTasksOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + } + + export interface ClusterPutSettingsOptions extends GenericParams { + flatSettings?: boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterRerouteOptions extends GenericParams { + dryRun?: boolean; + explain?: boolean; + metric?: string | string[] | boolean; + masterTimeout?: number | Date; + timeout?: number | Date; + } + + export interface ClusterStateOptions extends GenericParams { + local?: boolean; + masterTimeout?: number | Date; + flatSettings?: boolean; + ignoreUnavailable?: boolean; + allowNoIndices?: boolean; + expandWildcards?: string; // open, closed, none, all (default open) + index?: string | string[] | boolean; + metric?: string | string[] | boolean; + } + + export interface ClusterStatsOptions extends GenericParams { + flatSettings?: boolean; + human?: boolean; + timeout?: number | Date; + nodeId?: string | string[] | boolean; + } } declare module "elasticsearch" { From 22a0c3a9a6e798052192b49c104c67057288df6d Mon Sep 17 00:00:00 2001 From: NoHomey Date: Thu, 15 Sep 2016 18:22:20 +0300 Subject: [PATCH 099/212] [jest] updating definition to match latest API reference --- jest/jest-tests.ts | 232 ++++++++++++++++++++++++++++++++++++++++++++- jest/jest.d.ts | 158 ++++++++++++------------------ 2 files changed, 290 insertions(+), 100 deletions(-) diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index f3e33c4061..04fba5ab09 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -37,8 +37,6 @@ describe('fetchCurrentUser', function() { // unmock is the recommended approach for unmocking... jest.unmock('../displayUser.js') -// ...but dontMock also still works. -jest.dontMock('jquery'); describe('displayUser', function() { it('displays a user after a click', function() { @@ -100,6 +98,157 @@ describe('CheckboxWithLabel', function() { }); }); +jest.runAllTicks(); +xdescribe('Hooks and Suits', function () { + let tested: boolean; + + beforeEach(function () { + tested = false; + }); + + afterEach(function () { + tested = true; + }); + + test('tested', function () { + expect(tested).toBeTruthy(); + expect(tested).not.toBeFalsy(); + }); + + fit('tested', function () { + expect(tested).toBeDefined(); + expect(tested).not.toBeUndefined(); + }); + + xit('expect null to be null', function () { + expect(null).toBeNull(); + }); +}); + +describe('compartion', function () { + var sum: (a: number, b: number) => number = require.requireMock('../sum'); + + it('compares is 7 + 2 greater than 3', function () { + expect(sum(7, 2)).toBeGreaterThan(3); + }); + + it('compares is 2 + 7 greater than or equal to 3', function () { + expect(sum(2, 7)).toBeGreaterThanOrEqual(3); + }); + + it('compares is 3 less than 3 + 4', function () { + expect(3).toBeLessThan(sum(3, 4)); + }); + + it('compares is 3 less than or equal to 4 + 3', function () { + expect(3).toBeLessThanOrEqual(sum(4, 3)); + }); + + it('works sanely with simple decimals', function () { + expect(0.2 + 0.1).toBeCloseTo(0.3, 5); + }); +}); + +describe('toThrow API', function () { + function throwTypeError(): void { + throw new TypeError('toThrow Definition was out of date'); + } + + it('throws', function () { + expect(throwTypeError()).toThrow(); + }); + + it('throws TypeError', function () { + expect(throwTypeError()).toThrowError(TypeError); + }); + + it('throws \'Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError(/Definition was out of date/); + }); + + it('throws \'toThorow Definition was out of date\'', function () { + expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); + }); +}); + +describe('missing tests', function () { + it('creates closures', function () { + class Closure { + private arg: T; + + public constructor(private fn: (arg: T) => void) { + this.fn = fn; + } + + public bind(arg: T): void { + this.arg = arg; + } + + public call(): void { + this.fn(this.arg); + } + } + + type StringClosure = (arg: string) => void; + let spy: jest.Mock = jest.fn(); + let closure: Closure = new Closure(spy); + closure.bind('jest'); + closure.call(); + expect(spy).lastCalledWith('jest'); + expect(spy).toBeCalledWith('jest'); + expect(jest.isMockFunction(spy)).toBeTruthy(); + }); + + it('tests all mising Mocks functionality', function () { + type FruitsGetter = () => Array; + let mock: jest.Mock = jest.fn(); + mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum']) + jest.setMock('./../tesks/getFruits', mock); + const getFruits: FruitsGetter = require('./../tesks/getFruits'); + expect(getFruits()).toContain('Orange'); + mock.mockReturnValueOnce(['Apple', 'Plum']); + expect(mock()).not.toContain('Orange'); + mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. + mock.mockClear(); + let thisMock: jest.Mock = jest.fn().mockReturnThis(); + expect(thisMock()).toBe(this); + }); + + it('creates snapshoter', function () { + jest.disableAutomock(); + jest.mock('./render', () => jest.fn((): string => "{Link to: \"facebook\"}"), { virtual: true }); + const render: () => string = require('./render'); + expect(render()).toMatch(/Link/); + jest.enableAutomock(); + }); + + it('runs only pending timers', function () { + jest.useRealTimers(); + setTimeout(() => expect(1).not.toEqual(0), 3000); + jest.runOnlyPendingTimers(); + }); + + it('runs all timers', function () { + jest.clearAllTimers(); + jest.useFakeTimers(); + setTimeout(() => expect(0).not.toEqual(1), 3000); + jest.runAllTimers(); + }); + + it('cleares cache', function () { + const sum1 = require('../sum'); + jest.resetModules(); + const sum2 = require('../sum'); + expect(sum1).not.toBe(sum2); + }) +}); + +describe('toMatchSnapshot', function () { + it('compares snapshots', function () { + expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); + }); +}); + function testInstances() { var mockFn = jest.fn(); var a = new mockFn(); @@ -123,3 +272,82 @@ function testMockImplementation() { mockFn.mock.calls[0][0] === 0; // true mockFn.mock.calls[1][0] === 1; // true } + +// Test from jest Docs: +describe('genMockFromModule', function () { + // Interfaces: + interface MockFiles { + [index: string]: string; + } + + interface MockedFS { + readdirSync: (dir: string) => string[]; + __setMockFiles: (newMockFiles: MockFiles) => void ; + } + + // ------------------------------------------------------------------------------------ + // FileSummarizer.ts + + const fs = require('fs'); + + function summarizeFilesInDirectorySync(directory: string): string[] { + return fs.readdirSync(directory).map((fileName: string) => ({ + fileName, + directory, + })); + } + + //export default summarizeFilesInDirectorySync; // For sake of compilation + + // ------------------------------------------------------------------------------------ + // __mocks__/fs.js + + const path = require('path'); + + const mockedFS: MockedFS = jest.genMockFromModule('fs'); + + let mockFiles: any = Object.create(null); + function __setMockFiles(newMockFiles: MockFiles): void { + mockFiles = Object.create(null); + for(const file in newMockFiles) { + const dir: string = path.dirname(file); + + if (!mockFiles[dir]) { + mockFiles[dir] = []; + } + mockFiles[dir].push(path.basename(file)); + } + } + + function readdirSync(directoryPath: string): string[] { + return mockFiles[directoryPath] || []; + } + + mockedFS.readdirSync = readdirSync; + mockedFS.__setMockFiles = __setMockFiles; + + //export = mockedFS; // For sake of compilation + // ------------------------------------------------------------------------------------ + // __tests__/FileSummarizer-test.js + + jest.mock('fs'); + + describe('listFilesInDirectorySync', () => { + const MOCK_FILE_INFO: MockFiles = { + '/path/to/file1.js': 'console.log("file1 contents");', + '/path/to/file2.txt': 'file2 contents', + }; + + beforeEach(() => { + // Set up some mocked out file info before each test + (require('fs') as MockedFS).__setMockFiles(MOCK_FILE_INFO); + }); + + it('includes all files in the directory in the summary', () => { + const FileSummarizer: (dir: string) => string[] = require('../FileSummarizer'); + const fileSummary = FileSummarizer('/path/to'); + + expect(fileSummary.length).toBe(2); + }); + }); +}); diff --git a/jest/jest.d.ts b/jest/jest.d.ts index b2484dfcc5..506bd6533d 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -1,122 +1,79 @@ -// Type definitions for Jest 0.9.0 +// Type definitions for Jest 15.1.1 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana +// Definitions by: Asana , Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare function afterEach(fn: jest.EmptyFunction): void; -declare function beforeEach(fn: jest.EmptyFunction): void; -declare function describe(name: string, fn: jest.EmptyFunction): void; -declare var it: jest.It; -declare function pit(name: string, fn: jest.EmptyFunction): void; - -declare function xdescribe(name: string, fn: jest.EmptyFunction): void; -declare function xit(name: string, fn: jest.EmptyFunction): void; - +declare function afterEach(fn: () => any): void; +declare function beforeEach(fn: () => any): void; +declare function describe(name: string, fn: () => any): void; declare function expect(actual: any): jest.Matchers; +declare function it(name: string, fn: () => any): void; +declare function fit(name: string, fn: () => any): void; -interface NodeRequire { - requireActual(moduleName: string): any; -} +declare function test(name: string, fn: () => any): void; +declare function xdescribe(name: string, fn: () => any): void; +declare function xit(name: string, fn: () => any): void; declare namespace jest { - function addMatchers(matchers: CustomMatcherFactories): void; - function autoMockOff(): void; - function autoMockOn(): void; - function clearAllTimers(): void; - function currentTestPath(): string; - function disableAutomock(): void; - function fn(implementation?: Function): Mock; - function dontMock(moduleName: string): void; - function genMockFromModule(moduleName: string): Mock; - function mock(moduleName: string, factory?: Function): void; - function runAllTicks(): void; - function runAllTimers(): void; - function runOnlyPendingTimers(): void; - function setMock(moduleName: string, moduleExports: T): void; - function unmock(moduleName: string): void; - - interface EmptyFunction { - (): void; - } - interface Matchers { + lastCalledWith(...args: any[]): boolean; not: Matchers; - toThrow(expected?: any): boolean; - toThrowError(expected?: any): boolean; toBe(expected: any): boolean; - toEqual(expected: any): boolean; - toBeFalsy(): boolean; - toBeTruthy(): boolean; - toBeNull(): boolean; - toBeDefined(): boolean; - toBeUndefined(): boolean; - toMatch(expected: RegExp): boolean; - toContain(expected: string): boolean; - toBeCloseTo(expected: number, delta: number): boolean; - toBeGreaterThan(expected: number): boolean; - toBeLessThan(expected: number): boolean; toBeCalled(): boolean; toBeCalledWith(...args: any[]): boolean; - lastCalledWith(...args: any[]): boolean; + toBeCloseTo(expected: number, delta: number): boolean; + toBeDefined(): boolean; + toBeFalsy(): boolean; + toBeGreaterThan(expected: number): boolean; + toBeGreaterThanOrEqual(expected: number): boolean; + toBeLessThan(expected: number): boolean; + toBeLessThanOrEqual(expected: number): boolean; + toBeNull(): boolean; + toBeTruthy(): boolean; + toBeUndefined(): boolean; + toContain(expected: string): boolean; + toEqual(expected: any): boolean; + toMatch(expected: RegExp): boolean; + toMatchSnapshot(): boolean; + toThrow(): boolean; + toThrowError(expected: string | RegExp): boolean; + toThrowError(expected: TFunction): boolean; } - - interface It { - (name: string, fn: EmptyFunction): void; - only(name: string, fn: EmptyFunction): void; - } - - interface Mock { - new (): T; - (...args: any[]): any; // TODO please fix this line! added for TypeScript 1.1.0-1 https://github.com/DefinitelyTyped/DefinitelyTyped/pull/2932 - mock: MockContext; - mockClear(): void; - mockImplementation(fn: Function): Mock; - mockImpl(fn: Function): Mock; - mockReturnThis(): Mock; - mockReturnValue(value: any): Mock; - mockReturnValueOnce(value: any): Mock; - } - + interface MockContext { calls: any[][]; instances: T[]; } - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcherFactories { - [index: string]: CustomMatcherFactory; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcherFactory { - (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface MatchersUtil { - equals(a: any, b: any, customTesters?: Array): boolean; - contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; - buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomEqualityTester { - (first: any, second: any): boolean; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcher { - compare(actual: T, expected: T): CustomMatcherResult; - compare(actual: any, expected: any): CustomMatcherResult; - } - - // taken from Jasmine since addMatchers calls into the jasmine api - interface CustomMatcherResult { - pass: boolean; - message: string; + interface Mock { + new (): T; + (...args: any[]): any; // Making Mock Callable and fixing: Value of type 'Mock' is not callable. + mock: MockContext; + mockClear(): void; + mockImplementation(fn: Function): Mock; + mockImplementationOnce(fn: Function): Mock; + mockReturnThis(): Mock; + mockReturnValue(value: any): Mock; + mockReturnValueOnce(value: any): Mock; } + + function clearAllTimers(): void; + function disableAutomock(): void; + function enableAutomock(): void; + function fn(implementation?: Function): Mock; + function isMockFunction(fn: Function): boolean; + function genMockFromModule(moduleName: string): T; + function mock(moduleName: string, factory?: Function, options?: {virtual: boolean}): void; + function resetModules(): void; + function runAllTicks(): void; + function runAllTimers(): void; + function runOnlyPendingTimers(): void; + function setMock(moduleName: string, moduleExports: T): void; + function unmock(moduleName: string): void; + function useFakeTimers(): void; + function useRealTimers(): void; // taken from Jasmine which takes from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() interface ArrayLike { @@ -124,3 +81,8 @@ declare namespace jest { [n: number]: T; } } + +interface NodeRequire { + requireActual(moduleName: string): any; + requireMock(moduleName: string): any; +} From 4e6cafda2c6c59c87ebe394f039c63aa35f312ac Mon Sep 17 00:00:00 2001 From: Derek Finlinson Date: Thu, 15 Sep 2016 11:49:51 -0600 Subject: [PATCH 100/212] Fix openQuickCreate signature Fixed openQuickCreate signature which had a callback as the first parameter when it should just return a XrmPromise. --- xrm/xrm.d.ts | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index 824c91ba0c..2e4856e0c7 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -160,8 +160,6 @@ declare namespace Xrm /** * Opens quick create. * - * @param {Function} callback The function that will be called when a record is created. This - * function is passed a LookupValue object as a parameter. * @param {string} entityLogicalName The logical name of the entity to create. * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values * based on mapped attribute values. @@ -170,10 +168,9 @@ declare namespace Xrm * error. */ openQuickCreate( - callback: ( recordReference: Page.LookupValue ) => void, entityLogicalName: string, createFromEntity?: Page.LookupValue, - parameters?: Utility.OpenParameters ): void; + parameters?: Utility.OpenParameters ): Async.XrmPromise; /** * Opens an entity form. @@ -1477,11 +1474,11 @@ declare namespace Xrm * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an * entity. * - * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with + * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with * dictionary properties where the name of the property is the Id of the * business process flow and the value of the property is the name of the * business process flow. - * + * * The enabled processes are filtered according to the user’s privileges. The * list of enabled processes is the same ones a user can see in the UI if they * want to change the process manually. @@ -1501,7 +1498,7 @@ declare namespace Xrm * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event * handler pipeline. The execution context is automatically * set to be the first parameter passed to the event handler. - * + * * Use a reference to a named function rather than an * anonymous function if you may later want to remove the * event handler. @@ -1515,7 +1512,7 @@ declare namespace Xrm * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event * handler pipeline. The execution context is automatically * set to be the first parameter passed to the event handler. - * + * * Use a reference to a named function rather than an * anonymous function if you may later want to remove the * event handler. @@ -2587,4 +2584,4 @@ declare namespace XrmEnum SystemView = 1039, UserView = 4230 } -} \ No newline at end of file +} From 1b803f972a8edfcd8341520f195e7354fa091ec2 Mon Sep 17 00:00:00 2001 From: feitzi Date: Fri, 16 Sep 2016 12:49:30 +0200 Subject: [PATCH 101/212] Added definition file for randomColor --- randomColor/randomColor-tests.ts | 2 ++ randomColor/randomColor.d.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 randomColor/randomColor-tests.ts create mode 100644 randomColor/randomColor.d.ts diff --git a/randomColor/randomColor-tests.ts b/randomColor/randomColor-tests.ts new file mode 100644 index 0000000000..274768ebc1 --- /dev/null +++ b/randomColor/randomColor-tests.ts @@ -0,0 +1,2 @@ +/// + diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts new file mode 100644 index 0000000000..e439e2d77d --- /dev/null +++ b/randomColor/randomColor.d.ts @@ -0,0 +1,30 @@ +// Type definitions for randomColor 0.4.1 +// Project: https://github.com/davidmerfield/randomColor +// Definitions by: Mathias Feitzinger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace RandomColor { + + interface RandomColorStatic { + + () : string; + + (options : randomColorOptions): string; + +} + +interface randomColorOptions { + hue? : string; + luminosity? : string; + count? : string; + seed?: string; + format?: string; + } +} + + +declare var randomColor: RandomColor.RandomColorStatic; + +declare module 'randomColor' { + export = randomColor; +} \ No newline at end of file From 300d30753459bbd6fe6b53b61e44e21e3669fc97 Mon Sep 17 00:00:00 2001 From: feitzi Date: Fri, 16 Sep 2016 12:58:59 +0200 Subject: [PATCH 102/212] added test for randomColor --- randomColor/randomColor-tests.ts | 38 ++++++++++++++++++++++++++++++++ randomColor/randomColor.d.ts | 2 +- 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/randomColor/randomColor-tests.ts b/randomColor/randomColor-tests.ts index 274768ebc1..69b617615e 100644 --- a/randomColor/randomColor-tests.ts +++ b/randomColor/randomColor-tests.ts @@ -1,2 +1,40 @@ /// +// Returns a hex code for an attractive color +randomColor(); + +// Returns an array of ten green colors +randomColor({ + count: 10, + hue: 'green' +}); + +// Returns a hex code for a light blue +randomColor({ + luminosity: 'light', + hue: 'blue' +}); + +// Returns a hex code for a 'truly random' color +randomColor({ + luminosity: 'random', + hue: 'random' +}); + +// Returns a bright color in RGB +randomColor({ + luminosity: 'bright', + format: 'rgb' // e.g. 'rgb(225,200,20)' +}); + +// Returns a dark RGB color with random alpha +randomColor({ + luminosity: 'dark', + format: 'rgba' // e.g. 'rgba(9, 1, 107, 0.6482447960879654)' +}); + +// Returns a light HSL color with random alpha +randomColor({ + luminosity: 'light', + format: 'hsla' // e.g. 'hsla(27, 88.99%, 81.83%, 0.6450211517512798)' +}); \ No newline at end of file diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts index e439e2d77d..81f43a0228 100644 --- a/randomColor/randomColor.d.ts +++ b/randomColor/randomColor.d.ts @@ -16,7 +16,7 @@ declare namespace RandomColor { interface randomColorOptions { hue? : string; luminosity? : string; - count? : string; + count? : string | number; seed?: string; format?: string; } From 1175068a71da6baf10fffaf08df4fa8c32ebb6a9 Mon Sep 17 00:00:00 2001 From: feitzi Date: Fri, 16 Sep 2016 13:14:08 +0200 Subject: [PATCH 103/212] styling for randomColor --- randomColor/randomColor.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts index 81f43a0228..1c52f39be1 100644 --- a/randomColor/randomColor.d.ts +++ b/randomColor/randomColor.d.ts @@ -10,7 +10,6 @@ declare namespace RandomColor { () : string; (options : randomColorOptions): string; - } interface randomColorOptions { @@ -22,7 +21,6 @@ interface randomColorOptions { } } - declare var randomColor: RandomColor.RandomColorStatic; declare module 'randomColor' { From 28ef3d201b4271f3bb6c417b01a98d5706dd62a5 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Wed, 14 Sep 2016 12:12:01 -0700 Subject: [PATCH 104/212] Remove `` from definitions files and replace it with `import * as Xxx from "xxx"` or `` --- 3d-bin-packing/3d-bin-packing-tests.ts | 2 - 3d-bin-packing/3d-bin-packing.d.ts | 10 +- 3d-bin-packing/tsconfig.json | 19 + angular-q-spread/angular-q-spread-tests.ts | 2 - angular-q-spread/angular-q-spread.d.ts | 4 +- angular-q-spread/tsconfig.json | 19 + angular-websocket/angular-websocket.d.ts | 256 +++---- angular-websocket/tsconfig.json | 19 + angular-xeditable/angular-xeditable.d.ts | 162 ++-- angular-xeditable/tsconfig.json | 19 + .../backbone-fetch-cache-tests.ts | 5 +- .../backbone-fetch-cache.d.ts | 189 ----- backbone-fetch-cache/index.d.ts | 183 +++++ backbone-fetch-cache/tsconfig.json | 19 + backbone/index.d.ts | 2 +- backlog-js/backlog-js-tests.ts | 2 - backlog-js/backlog-js.d.ts | 695 ------------------ backlog-js/index.d.ts | 690 +++++++++++++++++ backlog-js/tsconfig.json | 19 + bootstrap-fileinput/bootstrap-fileinput.d.ts | 2 +- bootstrap-fileinput/tsconfig.json | 18 + browserify/index.d.ts | 4 +- chai-dom/chai-dom.d.ts | 10 +- chai-dom/tsconfig.json | 19 + chai-enzyme/chai-enzyme-tests.tsx | 6 +- chai-enzyme/chai-enzyme.d.ts | 8 +- chai-enzyme/tsconfig.json | 21 + commangular/commangular.d.ts | 144 ++-- commangular/tsconfig.json | 19 + connect-redis/connect-redis-tests.ts | 2 +- connect-redis/connect-redis.d.ts | 6 +- connect-redis/tsconfig.json | 19 + cordova-plugin-file-transfer/index.d.ts | 6 +- cordova-plugin-file-transfer/tsconfig.json | 10 +- csv-parse/csv-parse.d.ts | 48 +- csv-parse/tsconfig.json | 19 + d3kit/d3kit-tests.ts | 6 +- d3kit/d3kit.d.ts | 16 +- d3kit/tsconfig.json | 19 + daterangepicker/daterangepicker-tests.ts | 1 + daterangepicker/daterangepicker.d.ts | 12 +- daterangepicker/package.json | 5 + daterangepicker/tsconfig.json | 19 + df-visible/df-visible.d.ts | 2 +- df-visible/tsconfig.json | 19 + dva/dva-tests.tsx | 12 +- dva/dva.d.ts | 4 +- dva/tsconfig.json | 21 + electron/index.d.ts | 2 +- epub/epub.d.ts | 22 +- epub/tsconfig.json | 19 + eq.js/index.d.ts | 2 +- eq.js/tsconfig.json | 3 +- esprima-walk/esprima-walk-tests.ts | 6 +- esprima-walk/esprima-walk.d.ts | 40 - esprima-walk/index.d.ts | 34 + esprima-walk/tsconfig.json | 19 + exorcist/exorcist.d.ts | 2 +- exorcist/tsconfig.json | 19 + .../express-domain-middleware.d.ts | 2 +- express-domain-middleware/tsconfig.json | 19 + file-type/file-type-tests.ts | 2 - file-type/{file-type.d.ts => index.d.ts} | 18 +- file-type/tsconfig.json | 19 + fill-pdf/fill-pdf.d.ts | 2 +- fill-pdf/tsconfig.json | 19 + fluent-ffmpeg/fluent-ffmpeg.d.ts | 2 +- fluent-ffmpeg/tsconfig.json | 19 + fullpage.js/fullpage.js.d.ts | 100 +-- fullpage.js/tsconfig.json | 19 + geojson2osm/geojson2osm-tests.ts | 3 - geojson2osm/geojson2osm.d.ts | 15 - geojson2osm/index.d.ts | 13 + geojson2osm/tsconfig.json | 19 + .../globalize-compiler-tests.ts | 13 +- globalize-compiler/globalize-compiler.d.ts | 106 --- globalize-compiler/index.d.ts | 96 +++ globalize-compiler/tsconfig.json | 19 + .../gulp-angular-templatecache-tests.ts | 3 - .../gulp-angular-templatecache.d.ts | 2 +- gulp-angular-templatecache/tsconfig.json | 19 + gulp-help-doc/gulp-help-doc-tests.ts | 4 - gulp-help-doc/gulp-help-doc.d.ts | 4 +- gulp-help-doc/tsconfig.json | 19 + gulp-insert/gulp-insert-tests.ts | 3 - gulp-insert/gulp-insert.d.ts | 4 +- gulp-insert/tsconfig.json | 19 + gulp/index.d.ts | 1 + html-pdf/html-pdf-tests.ts | 3 - html-pdf/html-pdf.d.ts | 2 +- html-pdf/tsconfig.json | 19 + html-webpack-plugin/html-webpack-plugin.d.ts | 2 +- html-webpack-plugin/tsconfig.json | 19 + imagemapster/imagemapster-tests.ts | 3 - imagemapster/imagemapster.d.ts | 2 +- imagemapster/tsconfig.json | 19 + intl-tel-input/intl-tel-input-tests.ts | 3 - intl-tel-input/intl-tel-input.d.ts | 2 +- intl-tel-input/tsconfig.json | 19 + inversify-binding-decorators/index.d.ts | 47 ++ .../inversify-binding-decorators-tests.ts | 2 - .../inversify-binding-decorators.d.ts | 59 -- inversify-binding-decorators/tsconfig.json | 20 + inversify-devtools/inversify-devtools-test.ts | 2 - inversify-devtools/inversify-devtools.d.ts | 7 +- inversify-devtools/tsconfig.json | 20 + .../inversify-express-utils-tests.ts | 2 - .../inversify-express-utils.d.ts | 4 +- inversify-express-utils/tsconfig.json | 20 + inversify-inject-decorators/index.d.ts | 23 + .../inversify-inject-decorators-tests.ts | 3 - .../inversify-inject-decorators.d.ts | 31 - inversify-inject-decorators/tsconfig.json | 20 + inversify-logger-middleware/index.d.ts | 65 ++ .../inversify-logger-middleware-tests.ts | 3 +- .../inversify-logger-middleware.d.ts | 70 -- inversify-logger-middleware/tsconfig.json | 20 + inversify-restify-utils/index.d.ts | 52 ++ .../inversify-restify-utils-tests.ts | 2 - .../inversify-restify-utils.d.ts | 59 -- inversify-restify-utils/tsconfig.json | 20 + .../istanbul-middleware-tests.ts | 1 - istanbul-middleware/istanbul-middleware.d.ts | 2 +- istanbul-middleware/tsconfig.json | 19 + jquery-mousewheel/jquery-mousewheel-tests.ts | 4 +- jquery-mousewheel/jquery-mousewheel.d.ts | 2 +- jquery-mousewheel/tsconfig.json | 19 + .../jquery-truncate-html-tests.ts | 5 +- .../jquery-truncate-html.d.ts | 4 +- jquery-truncate-html/tsconfig.json | 19 + jquery/index.d.ts | 310 ++++---- jsoneditor/jsoneditor.d.ts | 2 +- jsoneditor/tsconfig.json | 19 + jsuite/jsuite.d.ts | 4 +- jsuite/tsconfig.json | 18 + karma-chai-sinon/karma-chai-sinon-tests.ts | 4 + karma-chai-sinon/karma-chai-sinon.d.ts | 14 +- karma-chai-sinon/tsconfig.json | 19 + koa-compress/koa-compress-tests.ts | 3 - koa-compress/koa-compress.d.ts | 6 +- koa-compress/tsconfig.json | 19 + koa-hbs/koa-hbs-tests.ts | 3 - koa-hbs/koa-hbs.d.ts | 4 +- koa-hbs/tsconfig.json | 19 + koa-json-error/index.d.ts | 31 + koa-json-error/koa-json-error-tests.ts | 4 - koa-json-error/koa-json-error.d.ts | 36 - koa-json-error/tsconfig.json | 19 + .../leaflet-geocoder-mapzen-tests.ts | 3 - .../leaflet-geocoder-mapzen.d.ts | 3 +- leaflet-geocoder-mapzen/tsconfig.json | 19 + libxslt/index.d.ts | 59 ++ libxslt/libxslt-tests.ts | 3 - libxslt/libxslt.d.ts | 61 -- libxslt/tsconfig.json | 19 + .../marker-animate-unobtrusive-amd-tests.ts | 3 - .../marker-animate-unobtrusive-tests.ts | 5 +- .../marker-animate-unobtrusive.d.ts | 2 +- marker-animate-unobtrusive/tsconfig.json | 20 + masonry-layout/masonry-layout.d.ts | 30 +- masonry-layout/tsconfig.json | 19 + mitm/mitm-tests.ts | 2 - mitm/mitm.d.ts | 10 +- mitm/tsconfig.json | 19 + mongoose-paginate/mongoose-paginate-tests.ts | 4 +- mongoose-paginate/mongoose-paginate.d.ts | 2 +- mongoose-paginate/tsconfig.json | 19 + multer-s3/multer-s3-tests.ts | 2 - multer-s3/multer-s3.d.ts | 4 +- multer-s3/tsconfig.json | 19 + multer/index.d.ts | 58 +- musicmetadata/musicmetadata-tests.ts | 3 - musicmetadata/musicmetadata.d.ts | 2 +- musicmetadata/tsconfig.json | 19 + nes/nes-tests.ts | 6 +- nes/nes.d.ts | 2 +- nes/tsconfig.json | 19 + ngmap/ngmap-tests.ts | 5 +- ngmap/ngmap.d.ts | 14 +- ngmap/tsconfig.json | 19 + ngreact/ngreact-tests.tsx | 6 +- ngreact/ngreact.d.ts | 6 +- ngreact/tsconfig.json | 21 + node-usb/node-usb-tests.ts | 2 - node-usb/node-usb.d.ts | 2 +- node-usb/tsconfig.json | 19 + .../nodemailer-ses-transport-tests.ts | 4 +- .../nodemailer-ses-transport.d.ts | 5 +- nodemailer-ses-transport/tsconfig.json | 19 + notify.js/notify.js.d.ts | 216 +++--- notify.js/notify.js.tests.ts | 5 +- notify.js/tsconfig.json | 19 + nw.js/nw.js-tests.ts | 1 - nw.js/nw.js.d.ts | 2 +- nw.js/tsconfig.json | 19 + o.js/o.js-tests.ts | 3 +- o.js/o.js.d.ts | 6 +- o.js/tsconfig.json | 19 + .../passport-local-mongoose-tests.ts | 6 +- .../passport-local-mongoose.d.ts | 4 +- passport-local-mongoose/tsconfig.json | 19 + pg-pool/pg-pool.d.ts | 2 +- pg-pool/tsconfig.json | 19 + pino/pino-tests.ts | 2 - pino/pino.d.ts | 2 +- pino/tsconfig.json | 19 + ...chdb-adapter-fruitdown.d.ts => index.d.ts} | 2 +- .../pouchdb-adapter-fruitdown-tests.ts | 3 - pouchdb-adapter-fruitdown/tsconfig.json | 19 + .../{pouchdb-adapter-http.d.ts => index.d.ts} | 2 +- .../pouchdb-adapter-http-tests.ts | 3 - pouchdb-adapter-http/tsconfig.json | 19 + .../{pouchdb-adapter-idb.d.ts => index.d.ts} | 2 +- .../pouchdb-adapter-idb-tests.ts | 3 - pouchdb-adapter-idb/tsconfig.json | 19 + ...ouchdb-adapter-leveldb.d.ts => index.d.ts} | 2 +- .../pouchdb-adapter-leveldb-tests.ts | 3 - pouchdb-adapter-leveldb/tsconfig.json | 19 + ...b-adapter-localstorage.d.ts => index.d.ts} | 4 +- .../pouchdb-adapter-localstorage-tests.ts | 3 - pouchdb-adapter-localstorage/tsconfig.json | 19 + ...pouchdb-adapter-memory.d.ts => index.d.ts} | 2 +- .../pouchdb-adapter-memory-tests.ts | 3 - pouchdb-adapter-memory/tsconfig.json | 19 + ...db-adapter-node-websql.d.ts => index.d.ts} | 4 +- .../pouchdb-adapter-node-websql-tests.ts | 3 - pouchdb-adapter-node-websql/tsconfig.json | 19 + ...pouchdb-adapter-websql.d.ts => index.d.ts} | 2 +- .../pouchdb-adapter-websql-tests.ts | 3 - pouchdb-adapter-websql/tsconfig.json | 19 + .../{pouchdb-browser.d.ts => index.d.ts} | 10 +- pouchdb-browser/pouchdb-browser-tests.ts | 3 - pouchdb-browser/tsconfig.json | 19 + .../{pouchdb-core.d.ts => index.d.ts} | 0 pouchdb-core/pouchdb-core-tests.ts | 2 - pouchdb-core/tsconfig.json | 19 + .../{pouchdb-http.d.ts => index.d.ts} | 4 +- pouchdb-http/pouchdb-http-tests.ts | 3 - pouchdb-http/tsconfig.json | 19 + .../{pouchdb-mapreduce.d.ts => index.d.ts} | 2 +- pouchdb-mapreduce/pouchdb-mapreduce-tests.ts | 2 - pouchdb-mapreduce/tsconfig.json | 19 + .../{pouchdb-node.d.ts => index.d.ts} | 10 +- pouchdb-node/pouchdb-node-tests.ts | 3 - pouchdb-node/tsconfig.json | 19 + .../{pouchdb-replication.d.ts => index.d.ts} | 2 +- .../pouchdb-replication-tests.ts | 1 - pouchdb-replication/tsconfig.json | 19 + pouchdb-upsert/pouchdb-upsert.d.ts | 2 +- pouchdb-upsert/tsconfig.json | 19 + pouchdb/index.d.ts | 28 +- rc-tooltip/rc-tooltip-tests.tsx | 3 - rc-tooltip/rc-tooltip.d.ts | 6 +- rc-tooltip/tsconfig.json | 21 + react-autosuggest/react-autosuggest-tests.tsx | 24 +- react-autosuggest/react-autosuggest.d.ts | 10 +- react-autosuggest/tsconfig.json | 21 + .../react-big-calendar-tests.tsx | 7 +- react-big-calendar/react-big-calendar.d.ts | 2 - react-big-calendar/tsconfig.json | 21 + react-breadcrumbs/react-breadcrumbs-tests.tsx | 6 +- react-breadcrumbs/react-breadcrumbs.d.ts | 9 +- react-breadcrumbs/tsconfig.json | 21 + .../react-calendar-timeline-tests.tsx | 9 +- .../react-calendar-timeline.d.ts | 8 +- react-calendar-timeline/tsconfig.json | 21 + react-codemirror/react-codemirror-tests.tsx | 5 +- react-codemirror/react-codemirror.d.ts | 10 +- react-codemirror/tsconfig.json | 21 + .../{react-data-grid.d.ts => index.d.ts} | 11 +- react-data-grid/react-data-grid-tests.tsx | 8 +- react-data-grid/tsconfig.json | 20 + react-datepicker/package.json | 5 + react-datepicker/react-datepicker-tests.tsx | 18 +- react-datepicker/react-datepicker.d.ts | 4 +- react-datepicker/tsconfig.json | 21 + react-daterange-picker/index.d.ts | 65 ++ react-daterange-picker/package.json | 5 + .../react-daterange-picker-tests.tsx | 9 +- .../react-daterange-picker.d.ts | 77 -- react-daterange-picker/tsconfig.json | 21 + .../react-dnd-html5-backend.d.ts | 6 +- react-dnd-html5-backend/tsconfig.json | 19 + react-file-input/react-file-input-tests.tsx | 5 +- react-file-input/react-file-input.d.ts | 6 +- react-file-input/tsconfig.json | 21 + .../react-file-reader-input-tests.tsx | 5 +- .../react-file-reader-input.d.ts | 6 +- react-file-reader-input/tsconfig.json | 21 + react-flexr/react-flexr-tests.tsx | 3 +- react-flexr/react-flexr.d.ts | 4 +- react-flexr/tsconfig.json | 21 + react-fontawesome/react-fontawesome-tests.tsx | 4 - react-fontawesome/react-fontawesome.d.ts | 2 - react-fontawesome/tsconfig.json | 21 + react-i18next/index.d.ts | 57 ++ react-i18next/react-i18next-tests.tsx | 6 - react-i18next/react-i18next.d.ts | 65 -- react-i18next/tsconfig.json | 22 + react-imageloader/react-imageloader-tests.tsx | 3 - react-imageloader/react-imageloader.d.ts | 12 +- react-imageloader/tsconfig.json | 21 + .../react-is-deprecated-tests.ts | 3 - react-is-deprecated/react-is-deprecated.d.ts | 2 - react-is-deprecated/tsconfig.json | 21 + .../react-jsonschema-form-tests.tsx | 3 - .../react-jsonschema-form.d.ts | 2 - react-jsonschema-form/tsconfig.json | 21 + react-measure/react-measure-tests.tsx | 3 - react-measure/react-measure.d.ts | 2 - react-measure/tsconfig.json | 21 + react-modal/react-modal-tests.tsx | 3 - react-modal/react-modal.d.ts | 4 +- react-modal/tsconfig.json | 20 + .../react-motion-slider-tests.tsx | 3 - react-motion-slider/react-motion-slider.d.ts | 4 - react-motion-slider/tsconfig.json | 21 + react-relay/react-relay-test.tsx | 3 - react-relay/react-relay.d.ts | 2 - react-relay/tsconfig.json | 21 + react-responsive/react-responsive-tests.tsx | 3 - react-responsive/react-responsive.d.ts | 2 - react-responsive/tsconfig.json | 21 + react-router-redux/index.d.ts | 4 +- react-router/index.d.ts | 3 +- react-router/lib/Router.d.ts | 2 +- react-scrollbar/react-scrollbar-tests.tsx | 3 - react-scrollbar/react-scrollbar.d.ts | 6 +- react-scrollbar/tsconfig.json | 20 + react-slick/react-slick-test.tsx | 4 - react-slick/react-slick.d.ts | 4 +- react-slick/tsconfig.json | 20 + .../react-sortable-hoc-tests.tsx | 3 - react-sortable-hoc/react-sortable-hoc.d.ts | 4 +- react-sortable-hoc/tsconfig.json | 20 + react-split-pane/react-split-pane-tests.tsx | 3 - react-split-pane/react-split-pane.d.ts | 4 +- react-split-pane/tsconfig.json | 20 + react-swipeable/react-swipeable-tests.tsx | 3 - react-swipeable/react-swipeable.d.ts | 13 +- react-swipeable/tsconfig.json | 21 + .../react-textarea-autosize-tests.tsx | 3 - .../react-textarea-autosize.d.ts | 5 +- react-textarea-autosize/tsconfig.json | 21 + react-user-tour/react-user-tour-tests.tsx | 6 +- .../react-user-tour-tests.tsx.tscparams | 1 - react-user-tour/react-user-tour.d.ts | 8 +- react-user-tour/tsconfig.json | 21 + redux-bootstrap/redux-bootstrap-tests.tsx | 2 - redux-bootstrap/redux-bootstrap.d.ts | 6 +- redux-bootstrap/tsconfig.json | 21 + redux-mock-store/redux-mock-store-tests.ts | 3 +- redux-mock-store/redux-mock-store.d.ts | 2 +- redux-mock-store/tsconfig.json | 19 + .../redux-optimistic-ui-tests.ts | 3 - redux-optimistic-ui/redux-optimistic-ui.d.ts | 2 +- redux-optimistic-ui/tsconfig.json | 19 + .../redux-promise-middleware-tests.ts | 5 +- .../redux-promise-middleware.d.ts | 2 +- redux-promise-middleware/tsconfig.json | 19 + redux-storage/redux-storage-tests.ts | 3 - redux-storage/redux-storage.d.ts | 2 +- redux-storage/tsconfig.json | 19 + redux-ui/redux-ui-tests.ts | 4 +- redux-ui/redux-ui.d.ts | 2 - redux-ui/tsconfig.json | 21 + restler/restler.d.ts | 2 +- restler/tsconfig.json | 19 + rx-node/rx-node-tests.ts | 3 - rx-node/rx-node.d.ts | 4 +- rx-node/tsconfig.json | 19 + rx.wamp/{rx-wamp.d.ts => index.d.ts} | 15 +- .../{rx-wamp-tests.ts => rx.wamp-tests.ts} | 7 +- rx.wamp/tsconfig.json | 19 + rx/rx.aggregates.d.ts | 2 +- rx/rx.all.d.ts | 18 +- rx/rx.async.d.ts | 2 +- rx/rx.binding.d.ts | 2 +- rx/rx.coincidence.d.ts | 2 +- rx/rx.experimental.d.ts | 2 +- rx/rx.joinpatterns.d.ts | 2 +- rx/rx.testing.d.ts | 2 +- rx/rx.time.d.ts | 2 +- rx/rx.virtualtime.d.ts | 2 +- .../samchon-collection-tests.ts | 2 - samchon-collection/samchon-collection.d.ts | 2 +- samchon-collection/tsconfig.json | 19 + .../{samchon-framework.d.ts => index.d.ts} | 6 +- samchon-framework/samchon-framework-tests.ts | 2 - samchon-framework/tsconfig.json | 19 + samchon-library/samchon-library-tests.ts | 2 - samchon-library/samchon-library.d.ts | 2 +- samchon-library/tsconfig.json | 19 + samlp/samlp-tests.ts | 4 - samlp/samlp.d.ts | 4 +- samlp/tsconfig.json | 19 + set-cookie-parser/set-cookie-parser-tests.ts | 3 - set-cookie-parser/set-cookie-parser.d.ts | 2 +- set-cookie-parser/tsconfig.json | 19 + sinon-as-promised/sinon-as-promised-tests.ts | 7 +- sinon-as-promised/sinon-as-promised.d.ts | 11 +- sinon-as-promised/tsconfig.json | 19 + sinon/index.d.ts | 1 + socket.io-parser/socket.io-parser-tests.ts | 3 - socket.io-parser/socket.io-parser.d.ts | 2 +- socket.io-parser/tsconfig.json | 19 + spectacle/spectacle-tests.tsx | 3 - spectacle/spectacle.d.ts | 3 +- spectacle/tsconfig.json | 21 + split2/split2-tests.ts | 2 - split2/split2.d.ts | 2 +- split2/tsconfig.json | 19 + sqs-consumer/sqs-consumer-tests.ts | 8 +- sqs-consumer/sqs-consumer.d.ts | 16 +- sqs-consumer/tsconfig.json | 19 + sqs-producer/sqs-producer-tests.ts | 3 - sqs-producer/sqs-producer.d.ts | 2 +- sqs-producer/tsconfig.json | 19 + ssh2-sftp-client/ssh2-sftp-client-tests.ts | 2 - ssh2-sftp-client/ssh2-sftp-client.d.ts | 2 +- ssh2-sftp-client/tsconfig.json | 19 + suitescript/{suitescript.d.ts => index.d.ts} | 0 .../swagger-express-middleware-tests.ts | 6 +- .../swagger-express-middleware.d.ts | 78 +- swagger-express-middleware/tsconfig.json | 19 + tinder/tinder-tests.ts | 8 +- tinder/tinder.d.ts | 26 +- tinder/tsconfig.json | 19 + torrent-stream/torrent-stream-tests.ts | 2 - torrent-stream/torrent-stream.d.ts | 6 +- torrent-stream/tsconfig.json | 19 + twilio/index.d.ts | 14 +- twit/tsconfig.json | 19 + twit/twit-tests.ts | 2 - twit/twit.d.ts | 4 +- .../{typescript-stl.d.ts => index.d.ts} | 0 v8-profiler/tsconfig.json | 19 + v8-profiler/v8-profiler.d.ts | 2 +- victory/tsconfig.json | 21 + victory/victory-tests.tsx | 3 - victory/victory.d.ts | 11 +- watchify/index.d.ts | 48 ++ watchify/tsconfig.json | 19 + watchify/watchify-tests.ts | 2 - watchify/watchify.d.ts | 51 -- webpack-dev-server/tsconfig.json | 19 + .../webpack-dev-server-tests.ts | 5 +- webpack-dev-server/webpack-dev-server.d.ts | 4 - webpack-fail-plugin/tsconfig.json | 19 + .../webpack-fail-plugin-tests.ts | 1 - webpack-fail-plugin/webpack-fail-plugin.d.ts | 2 +- webpack-merge/tsconfig.json | 19 + webpack-merge/webpack-merge-tests.ts | 2 - webpack-merge/webpack-merge.d.ts | 2 +- webpack-stream/tsconfig.json | 19 + webpack-stream/webpack-stream-tests.ts | 3 - webpack-stream/webpack-stream.d.ts | 4 +- webpack-validator/tsconfig.json | 19 + webpack-validator/webpack-validator-tests.ts | 2 - webpack-validator/webpack-validator.d.ts | 2 +- whatwg-fetch/index.d.ts | 2 +- whatwg-fetch/whatwg-fetch-tests.ts | 6 +- .../{whatwg-streams.d.ts => index.d.ts} | 0 whatwg-streams/tsconfig.json | 19 + whatwg-streams/whatwg-streams-tests.ts | 6 +- why-did-you-update/tsconfig.json | 19 + .../why-did-you-update-tests.ts | 3 - why-did-you-update/why-did-you-update.d.ts | 4 +- winston-dynamodb/tsconfig.json | 19 + winston-dynamodb/winston-dynamodb-tests.ts | 3 - winston-dynamodb/winston-dynamodb.d.ts | 2 +- xmlpoke/tsconfig.json | 19 + xmlpoke/xmlpoke-tests.ts | 7 +- xmlpoke/xmlpoke.d.ts | 2 +- 474 files changed, 5537 insertions(+), 3063 deletions(-) create mode 100644 3d-bin-packing/tsconfig.json create mode 100644 angular-q-spread/tsconfig.json create mode 100644 angular-websocket/tsconfig.json create mode 100644 angular-xeditable/tsconfig.json delete mode 100644 backbone-fetch-cache/backbone-fetch-cache.d.ts create mode 100644 backbone-fetch-cache/index.d.ts create mode 100644 backbone-fetch-cache/tsconfig.json delete mode 100644 backlog-js/backlog-js.d.ts create mode 100644 backlog-js/index.d.ts create mode 100644 backlog-js/tsconfig.json create mode 100644 bootstrap-fileinput/tsconfig.json create mode 100644 chai-dom/tsconfig.json create mode 100644 chai-enzyme/tsconfig.json create mode 100644 commangular/tsconfig.json create mode 100644 connect-redis/tsconfig.json create mode 100644 csv-parse/tsconfig.json create mode 100644 d3kit/tsconfig.json create mode 100644 daterangepicker/package.json create mode 100644 daterangepicker/tsconfig.json create mode 100644 df-visible/tsconfig.json create mode 100644 dva/tsconfig.json create mode 100644 epub/tsconfig.json delete mode 100644 esprima-walk/esprima-walk.d.ts create mode 100644 esprima-walk/index.d.ts create mode 100644 esprima-walk/tsconfig.json create mode 100644 exorcist/tsconfig.json create mode 100644 express-domain-middleware/tsconfig.json rename file-type/{file-type.d.ts => index.d.ts} (51%) create mode 100644 file-type/tsconfig.json create mode 100644 fill-pdf/tsconfig.json create mode 100644 fluent-ffmpeg/tsconfig.json create mode 100644 fullpage.js/tsconfig.json delete mode 100644 geojson2osm/geojson2osm.d.ts create mode 100644 geojson2osm/index.d.ts create mode 100644 geojson2osm/tsconfig.json delete mode 100644 globalize-compiler/globalize-compiler.d.ts create mode 100644 globalize-compiler/index.d.ts create mode 100644 globalize-compiler/tsconfig.json create mode 100644 gulp-angular-templatecache/tsconfig.json create mode 100644 gulp-help-doc/tsconfig.json create mode 100644 gulp-insert/tsconfig.json create mode 100644 html-pdf/tsconfig.json create mode 100644 html-webpack-plugin/tsconfig.json create mode 100644 imagemapster/tsconfig.json create mode 100644 intl-tel-input/tsconfig.json create mode 100644 inversify-binding-decorators/index.d.ts delete mode 100644 inversify-binding-decorators/inversify-binding-decorators.d.ts create mode 100644 inversify-binding-decorators/tsconfig.json create mode 100644 inversify-devtools/tsconfig.json create mode 100644 inversify-express-utils/tsconfig.json create mode 100644 inversify-inject-decorators/index.d.ts delete mode 100644 inversify-inject-decorators/inversify-inject-decorators.d.ts create mode 100644 inversify-inject-decorators/tsconfig.json create mode 100644 inversify-logger-middleware/index.d.ts delete mode 100644 inversify-logger-middleware/inversify-logger-middleware.d.ts create mode 100644 inversify-logger-middleware/tsconfig.json create mode 100644 inversify-restify-utils/index.d.ts delete mode 100644 inversify-restify-utils/inversify-restify-utils.d.ts create mode 100644 inversify-restify-utils/tsconfig.json create mode 100644 istanbul-middleware/tsconfig.json create mode 100644 jquery-mousewheel/tsconfig.json create mode 100644 jquery-truncate-html/tsconfig.json create mode 100644 jsoneditor/tsconfig.json create mode 100644 jsuite/tsconfig.json create mode 100644 karma-chai-sinon/karma-chai-sinon-tests.ts create mode 100644 karma-chai-sinon/tsconfig.json create mode 100644 koa-compress/tsconfig.json create mode 100644 koa-hbs/tsconfig.json create mode 100644 koa-json-error/index.d.ts delete mode 100644 koa-json-error/koa-json-error.d.ts create mode 100644 koa-json-error/tsconfig.json create mode 100644 leaflet-geocoder-mapzen/tsconfig.json create mode 100644 libxslt/index.d.ts delete mode 100644 libxslt/libxslt.d.ts create mode 100644 libxslt/tsconfig.json create mode 100644 marker-animate-unobtrusive/tsconfig.json create mode 100644 masonry-layout/tsconfig.json create mode 100644 mitm/tsconfig.json create mode 100644 mongoose-paginate/tsconfig.json create mode 100644 multer-s3/tsconfig.json create mode 100644 musicmetadata/tsconfig.json create mode 100644 nes/tsconfig.json create mode 100644 ngmap/tsconfig.json create mode 100644 ngreact/tsconfig.json create mode 100644 node-usb/tsconfig.json create mode 100644 nodemailer-ses-transport/tsconfig.json create mode 100644 notify.js/tsconfig.json create mode 100644 nw.js/tsconfig.json create mode 100644 o.js/tsconfig.json create mode 100644 passport-local-mongoose/tsconfig.json create mode 100644 pg-pool/tsconfig.json create mode 100644 pino/tsconfig.json rename pouchdb-adapter-fruitdown/{pouchdb-adapter-fruitdown.d.ts => index.d.ts} (93%) create mode 100644 pouchdb-adapter-fruitdown/tsconfig.json rename pouchdb-adapter-http/{pouchdb-adapter-http.d.ts => index.d.ts} (93%) create mode 100644 pouchdb-adapter-http/tsconfig.json rename pouchdb-adapter-idb/{pouchdb-adapter-idb.d.ts => index.d.ts} (94%) create mode 100644 pouchdb-adapter-idb/tsconfig.json rename pouchdb-adapter-leveldb/{pouchdb-adapter-leveldb.d.ts => index.d.ts} (93%) create mode 100644 pouchdb-adapter-leveldb/tsconfig.json rename pouchdb-adapter-localstorage/{pouchdb-adapter-localstorage.d.ts => index.d.ts} (87%) create mode 100644 pouchdb-adapter-localstorage/tsconfig.json rename pouchdb-adapter-memory/{pouchdb-adapter-memory.d.ts => index.d.ts} (93%) create mode 100644 pouchdb-adapter-memory/tsconfig.json rename pouchdb-adapter-node-websql/{pouchdb-adapter-node-websql.d.ts => index.d.ts} (75%) create mode 100644 pouchdb-adapter-node-websql/tsconfig.json rename pouchdb-adapter-websql/{pouchdb-adapter-websql.d.ts => index.d.ts} (94%) create mode 100644 pouchdb-adapter-websql/tsconfig.json rename pouchdb-browser/{pouchdb-browser.d.ts => index.d.ts} (53%) create mode 100644 pouchdb-browser/tsconfig.json rename pouchdb-core/{pouchdb-core.d.ts => index.d.ts} (100%) create mode 100644 pouchdb-core/tsconfig.json rename pouchdb-http/{pouchdb-http.d.ts => index.d.ts} (74%) create mode 100644 pouchdb-http/tsconfig.json rename pouchdb-mapreduce/{pouchdb-mapreduce.d.ts => index.d.ts} (94%) create mode 100644 pouchdb-mapreduce/tsconfig.json rename pouchdb-node/{pouchdb-node.d.ts => index.d.ts} (63%) create mode 100644 pouchdb-node/tsconfig.json rename pouchdb-replication/{pouchdb-replication.d.ts => index.d.ts} (92%) create mode 100644 pouchdb-replication/tsconfig.json create mode 100644 pouchdb-upsert/tsconfig.json create mode 100644 rc-tooltip/tsconfig.json create mode 100644 react-autosuggest/tsconfig.json create mode 100644 react-big-calendar/tsconfig.json create mode 100644 react-breadcrumbs/tsconfig.json create mode 100644 react-calendar-timeline/tsconfig.json create mode 100644 react-codemirror/tsconfig.json rename react-data-grid/{react-data-grid.d.ts => index.d.ts} (98%) create mode 100644 react-data-grid/tsconfig.json create mode 100644 react-datepicker/package.json create mode 100644 react-datepicker/tsconfig.json create mode 100644 react-daterange-picker/index.d.ts create mode 100644 react-daterange-picker/package.json delete mode 100644 react-daterange-picker/react-daterange-picker.d.ts create mode 100644 react-daterange-picker/tsconfig.json create mode 100644 react-dnd-html5-backend/tsconfig.json create mode 100644 react-file-input/tsconfig.json create mode 100644 react-file-reader-input/tsconfig.json create mode 100644 react-flexr/tsconfig.json create mode 100644 react-fontawesome/tsconfig.json create mode 100644 react-i18next/index.d.ts delete mode 100644 react-i18next/react-i18next.d.ts create mode 100644 react-i18next/tsconfig.json create mode 100644 react-imageloader/tsconfig.json create mode 100644 react-is-deprecated/tsconfig.json create mode 100644 react-jsonschema-form/tsconfig.json create mode 100644 react-measure/tsconfig.json create mode 100644 react-modal/tsconfig.json create mode 100644 react-motion-slider/tsconfig.json create mode 100644 react-relay/tsconfig.json create mode 100644 react-responsive/tsconfig.json create mode 100644 react-scrollbar/tsconfig.json create mode 100644 react-slick/tsconfig.json create mode 100644 react-sortable-hoc/tsconfig.json create mode 100644 react-split-pane/tsconfig.json create mode 100644 react-swipeable/tsconfig.json create mode 100644 react-textarea-autosize/tsconfig.json delete mode 100644 react-user-tour/react-user-tour-tests.tsx.tscparams create mode 100644 react-user-tour/tsconfig.json create mode 100644 redux-bootstrap/tsconfig.json create mode 100644 redux-mock-store/tsconfig.json create mode 100644 redux-optimistic-ui/tsconfig.json create mode 100644 redux-promise-middleware/tsconfig.json create mode 100644 redux-storage/tsconfig.json create mode 100644 redux-ui/tsconfig.json create mode 100644 restler/tsconfig.json create mode 100644 rx-node/tsconfig.json rename rx.wamp/{rx-wamp.d.ts => index.d.ts} (89%) rename rx.wamp/{rx-wamp-tests.ts => rx.wamp-tests.ts} (97%) create mode 100644 rx.wamp/tsconfig.json create mode 100644 samchon-collection/tsconfig.json rename samchon-framework/{samchon-framework.d.ts => index.d.ts} (99%) create mode 100644 samchon-framework/tsconfig.json create mode 100644 samchon-library/tsconfig.json create mode 100644 samlp/tsconfig.json create mode 100644 set-cookie-parser/tsconfig.json create mode 100644 sinon-as-promised/tsconfig.json create mode 100644 socket.io-parser/tsconfig.json create mode 100644 spectacle/tsconfig.json create mode 100644 split2/tsconfig.json create mode 100644 sqs-consumer/tsconfig.json create mode 100644 sqs-producer/tsconfig.json create mode 100644 ssh2-sftp-client/tsconfig.json rename suitescript/{suitescript.d.ts => index.d.ts} (100%) create mode 100644 swagger-express-middleware/tsconfig.json create mode 100644 tinder/tsconfig.json create mode 100644 torrent-stream/tsconfig.json create mode 100644 twit/tsconfig.json rename typescript-stl/{typescript-stl.d.ts => index.d.ts} (100%) create mode 100644 v8-profiler/tsconfig.json create mode 100644 victory/tsconfig.json create mode 100644 watchify/index.d.ts create mode 100644 watchify/tsconfig.json delete mode 100644 watchify/watchify.d.ts create mode 100644 webpack-dev-server/tsconfig.json create mode 100644 webpack-fail-plugin/tsconfig.json create mode 100644 webpack-merge/tsconfig.json create mode 100644 webpack-stream/tsconfig.json create mode 100644 webpack-validator/tsconfig.json rename whatwg-streams/{whatwg-streams.d.ts => index.d.ts} (100%) create mode 100644 whatwg-streams/tsconfig.json create mode 100644 why-did-you-update/tsconfig.json create mode 100644 winston-dynamodb/tsconfig.json create mode 100644 xmlpoke/tsconfig.json diff --git a/3d-bin-packing/3d-bin-packing-tests.ts b/3d-bin-packing/3d-bin-packing-tests.ts index 4562c26ce9..319624d597 100644 --- a/3d-bin-packing/3d-bin-packing-tests.ts +++ b/3d-bin-packing/3d-bin-packing-tests.ts @@ -1,5 +1,3 @@ -/// - import packer = require("3d-bin-packing"); import samchon = require("samchon-framework"); diff --git a/3d-bin-packing/3d-bin-packing.d.ts b/3d-bin-packing/3d-bin-packing.d.ts index afd3af6050..2461538194 100644 --- a/3d-bin-packing/3d-bin-packing.d.ts +++ b/3d-bin-packing/3d-bin-packing.d.ts @@ -3,11 +3,11 @@ // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// declare module "3d-bin-packing" { diff --git a/3d-bin-packing/tsconfig.json b/3d-bin-packing/tsconfig.json new file mode 100644 index 0000000000..ddad71a1fe --- /dev/null +++ b/3d-bin-packing/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "3d-bin-packing.d.ts", + "3d-bin-packing-tests.ts" + ] +} \ No newline at end of file diff --git a/angular-q-spread/angular-q-spread-tests.ts b/angular-q-spread/angular-q-spread-tests.ts index 932ecc4fa9..31fad81acd 100644 --- a/angular-q-spread/angular-q-spread-tests.ts +++ b/angular-q-spread/angular-q-spread-tests.ts @@ -1,5 +1,3 @@ -/// - interface IMyService { getFirstname(): ng.IPromise; getLastname(): ng.IPromise; diff --git a/angular-q-spread/angular-q-spread.d.ts b/angular-q-spread/angular-q-spread.d.ts index 3eb37dc4e0..57f6327071 100644 --- a/angular-q-spread/angular-q-spread.d.ts +++ b/angular-q-spread/angular-q-spread.d.ts @@ -3,9 +3,9 @@ // Definitions by: rafw87 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as a from "angular"; -declare module angular { +declare module "angular" { interface IPromise { /** This method can be used as a replacement for then. Similarly, it takes two parameters, a callback when all promises are resolved and a callback for failure. The resolve callback is going to be called with the result of the list of promises passed to $q.all as separate parameters instead of one parameters which is an array. diff --git a/angular-q-spread/tsconfig.json b/angular-q-spread/tsconfig.json new file mode 100644 index 0000000000..90110b0e9f --- /dev/null +++ b/angular-q-spread/tsconfig.json @@ -0,0 +1,19 @@ +{ + "files": [ + "angular-q-spread.d.ts", + "angular-q-spread-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": false + } +} \ No newline at end of file diff --git a/angular-websocket/angular-websocket.d.ts b/angular-websocket/angular-websocket.d.ts index 6929561f9c..9c2c93ea09 100644 --- a/angular-websocket/angular-websocket.d.ts +++ b/angular-websocket/angular-websocket.d.ts @@ -3,155 +3,157 @@ // Definitions by: Nick Veys // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as ng from "angular"; -declare namespace angular.websocket { - - /** - * Options available to be specified for IWebSocketProvider. - */ - type IWebSocketConfigOptions = { - scope?: ng.IScope; - rootScopeFailOver?: boolean; - useApplyAsync?: boolean; - initialTimeout?: number; - maxTimeout?: number; - binaryType?: "blob" | "arraybuffer"; - reconnectIfNotNormalClose?: boolean; - } - interface IWebSocketProvider { - /** - * Creates and opens an IWebSocket instance. - * - * @param url url to connect to - * @return websocket instance - */ - (url: string, protocols?: string | string[] | IWebSocketConfigOptions, options?: IWebSocketConfigOptions): IWebSocket; - } - - /** Options available to be specified for IWebSocket.onMessage */ - type IWebSocketMessageOptions = { +declare module "angular" { + namespace websocket { /** - * If specified, only messages that match the filter will cause the message event - * to be fired. + * Options available to be specified for IWebSocketProvider. */ - filter?: string | RegExp; + type IWebSocketConfigOptions = { + scope?: ng.IScope; + rootScopeFailOver?: boolean; + useApplyAsync?: boolean; + initialTimeout?: number; + maxTimeout?: number; + binaryType?: "blob" | "arraybuffer"; + reconnectIfNotNormalClose?: boolean; + } + interface IWebSocketProvider { + /** + * Creates and opens an IWebSocket instance. + * + * @param url url to connect to + * @return websocket instance + */ + (url: string, protocols?: string | string[] | IWebSocketConfigOptions, options?: IWebSocketConfigOptions): IWebSocket; + } - /** If true, each message handled will safely call `$rootScope.$digest()`. */ - autoApply?: boolean; - } + /** Options available to be specified for IWebSocket.onMessage */ + type IWebSocketMessageOptions = { - /** Type corresponding to onMessage callbaks stored in $Websocket#onMessageCallbacks instance. */ - type IWebSocketMessageHandler = { - fn: (evt: MessageEvent) => void; - pattern: string | RegExp; - autoApply: boolean; - } + /** + * If specified, only messages that match the filter will cause the message event + * to be fired. + */ + filter?: string | RegExp; - /** Type corresponding to items stored in $WebSocket#sendQueue instance. */ - type IWebSocketQueueItem = { - message: any; - defered: ng.IPromise; - } + /** If true, each message handled will safely call `$rootScope.$digest()`. */ + autoApply?: boolean; + } - interface IWebSocket { + /** Type corresponding to onMessage callbaks stored in $Websocket#onMessageCallbacks instance. */ + type IWebSocketMessageHandler = { + fn: (evt: MessageEvent) => void; + pattern: string | RegExp; + autoApply: boolean; + } - /** - * Adds a callback to be executed each time a socket connection is opened for - * this instance. - * - * @param event event object - * @returns this instance, for method chaining - */ - onOpen(callback: (event: Event) => void): IWebSocket; + /** Type corresponding to items stored in $WebSocket#sendQueue instance. */ + type IWebSocketQueueItem = { + message: any; + defered: ng.IPromise; + } - /** - * Adds a callback to be executed each time a socket connection is closed for - * this instance. - * - * @param event event object - * @returns this instance, for method chaining - */ - onClose(callback: (event: CloseEvent) => void): IWebSocket; + interface IWebSocket { - /** - * Adds a callback to be executed each time a socket connection is closed for - * this instance. - * - * @param event event object - * @returns this instance, for method chaining - */ - onError(callback: (event: Event) => void): IWebSocket; + /** + * Adds a callback to be executed each time a socket connection is opened for + * this instance. + * + * @param event event object + * @returns this instance, for method chaining + */ + onOpen(callback: (event: Event) => void): IWebSocket; - /** - * Adds a callback to be executed each time a socket connection has an error for - * this instance. - * - * @param event event object - * @returns this instance, for method chaining - */ - onMessage(callback: (event: MessageEvent) => void, options?: IWebSocketMessageOptions): IWebSocket; + /** + * Adds a callback to be executed each time a socket connection is closed for + * this instance. + * + * @param event event object + * @returns this instance, for method chaining + */ + onClose(callback: (event: CloseEvent) => void): IWebSocket; - /** - * Closes the underlying socket, as long as no data is still being sent from the client. - * - * @param force if `true`, force close even if data is still being sent - * @returns this instance, for method chaining - */ - close(force?: boolean): IWebSocket; + /** + * Adds a callback to be executed each time a socket connection is closed for + * this instance. + * + * @param event event object + * @returns this instance, for method chaining + */ + onError(callback: (event: Event) => void): IWebSocket; - /** - * Adds data to a queue, and attempts to send if the socket is ready. - * - * @param data data to send, if this is an object, it will be stringified before sending - */ - send(data: string | {}): ng.IPromise; + /** + * Adds a callback to be executed each time a socket connection has an error for + * this instance. + * + * @param event event object + * @returns this instance, for method chaining + */ + onMessage(callback: (event: MessageEvent) => void, options?: IWebSocketMessageOptions): IWebSocket; - /** - * WebSocket instance. - */ - socket: WebSocket; + /** + * Closes the underlying socket, as long as no data is still being sent from the client. + * + * @param force if `true`, force close even if data is still being sent + * @returns this instance, for method chaining + */ + close(force?: boolean): IWebSocket; - /** - * Queue of send calls to be made on socket when socket is able to receive data. - */ - sendQueue: IWebSocketQueueItem[]; + /** + * Adds data to a queue, and attempts to send if the socket is ready. + * + * @param data data to send, if this is an object, it will be stringified before sending + */ + send(data: string | {}): ng.IPromise; - /** - * List of callbacks to be executed when the socket is opened. - */ - onOpenCallbacks: ((evt: Event) => void)[]; + /** + * WebSocket instance. + */ + socket: WebSocket; - /** - * List of callbacks to be executed when a message is received from the socket. - */ - onMessageCallbacks: IWebSocketMessageHandler[]; + /** + * Queue of send calls to be made on socket when socket is able to receive data. + */ + sendQueue: IWebSocketQueueItem[]; - /** - * List of callbacks to be executed when an error is received from the socket. - */ - onErrorCallbacks: ((evt: Event) => void)[]; + /** + * List of callbacks to be executed when the socket is opened. + */ + onOpenCallbacks: ((evt: Event) => void)[]; - /** - * List of callbacks to be executed when the socket is closed. - */ - onCloseCallbacks: ((evt: CloseEvent) => void)[]; + /** + * List of callbacks to be executed when a message is received from the socket. + */ + onMessageCallbacks: IWebSocketMessageHandler[]; - /** - * Returns either the readyState value from the underlying WebSocket instance - * or a proprietary value representing the internal state - */ - readyState: number; + /** + * List of callbacks to be executed when an error is received from the socket. + */ + onErrorCallbacks: ((evt: Event) => void)[]; - /** - * The initial timeout. - */ - initialTimeout: number; + /** + * List of callbacks to be executed when the socket is closed. + */ + onCloseCallbacks: ((evt: CloseEvent) => void)[]; - /** - * Maximun timeout used to determine reconnection delay. - */ - maxTimeout: number; + /** + * Returns either the readyState value from the underlying WebSocket instance + * or a proprietary value representing the internal state + */ + readyState: number; + + /** + * The initial timeout. + */ + initialTimeout: number; + + /** + * Maximun timeout used to determine reconnection delay. + */ + maxTimeout: number; + } } } diff --git a/angular-websocket/tsconfig.json b/angular-websocket/tsconfig.json new file mode 100644 index 0000000000..7579a1591c --- /dev/null +++ b/angular-websocket/tsconfig.json @@ -0,0 +1,19 @@ +{ + "files": [ + "angular-websocket.d.ts", + "angular-websocket-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": false + } +} \ No newline at end of file diff --git a/angular-xeditable/angular-xeditable.d.ts b/angular-xeditable/angular-xeditable.d.ts index 026fc5d2fb..e0aba2a0e9 100644 --- a/angular-xeditable/angular-xeditable.d.ts +++ b/angular-xeditable/angular-xeditable.d.ts @@ -3,96 +3,96 @@ // Definitions by: Joao Monteiro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as angular from "angular"; -declare namespace angular.xeditable { +declare module "angular" { + namespace xeditable { + interface IEditableOptions { - interface IEditableOptions { + /** + * Theme. Possible values `bs3`, `bs2`, `default` + */ + theme: string; - /** - * Theme. Possible values `bs3`, `bs2`, `default` - */ - theme: string; + /** + * Icon Set. Possible values `font-awesome`, `default`. + */ + icon_set: string; - /** - * Icon Set. Possible values `font-awesome`, `default`. - */ - icon_set: string; + /** + * Whether to show buttons for single editalbe element. + * Possible values `right` (default), `no`. + */ + buttons: string; - /** - * Whether to show buttons for single editalbe element. - * Possible values `right` (default), `no`. - */ - buttons: string; + /** + * Default value for `blur` attribute of single editable element. + * Can be `cancel|submit|ignore`. + */ + blurElem: string; - /** - * Default value for `blur` attribute of single editable element. - * Can be `cancel|submit|ignore`. - */ - blurElem: string; + /** + * Default value for `blur` attribute of editable form. + * Can be `cancel|submit|ignore`. + */ + blurForm: string; - /** - * Default value for `blur` attribute of editable form. - * Can be `cancel|submit|ignore`. - */ - blurForm: string; + /** + * How input elements get activated. Possible values: `focus|select|none`. + */ + activate: string; - /** - * How input elements get activated. Possible values: `focus|select|none`. - */ - activate: string; + /** + * Whether to disable x-editable. Can be overloaded on each element. + */ + isDisabled: boolean; - /** - * Whether to disable x-editable. Can be overloaded on each element. - */ - isDisabled: boolean; + /* + * Event, on which the edit mode gets activated. + * Can be any event. + */ + activationEvent: string; + } - /* - * Event, on which the edit mode gets activated. - * Can be any event. - */ - activationEvent: string; + interface IEditableFormController extends angular.IFormController { + + /** + * Shows form with editable controls. + */ + $show(): void; + + /** + * Hides form with editable controls without saving. + */ + $hide(): void; + + /** + * Sets focus on form field specified by `name`.
    + * When trying to set the focus on a form field of a new row in the editable table, the `$activate` call needs to be wrapped in a `$timeout` call so that the form is rendered before the `$activate` function is called. + * + * @param name name of field + */ + $activate(name: string): void; + + /** + * Triggers `oncancel` event and calls `$hide()`. + */ + $cancel(): void; + + $setWaiting(value: boolean): void; + + /** + * Shows error message for particular field. + * + * @param name name of field + * @param msg error message + */ + $setError(name: string, msg: string): void; + + $submit(): void; + + $save(): void; + + } } - - interface IEditableFormController extends angular.IFormController { - - /** - * Shows form with editable controls. - */ - $show(): void; - - /** - * Hides form with editable controls without saving. - */ - $hide(): void; - - /** - * Sets focus on form field specified by `name`.
    - * When trying to set the focus on a form field of a new row in the editable table, the `$activate` call needs to be wrapped in a `$timeout` call so that the form is rendered before the `$activate` function is called. - * - * @param name name of field - */ - $activate(name: string): void; - - /** - * Triggers `oncancel` event and calls `$hide()`. - */ - $cancel(): void; - - $setWaiting(value: boolean): void; - - /** - * Shows error message for particular field. - * - * @param name name of field - * @param msg error message - */ - $setError(name: string, msg: string): void; - - $submit(): void; - - $save(): void; - - } - } diff --git a/angular-xeditable/tsconfig.json b/angular-xeditable/tsconfig.json new file mode 100644 index 0000000000..e9a9c10c51 --- /dev/null +++ b/angular-xeditable/tsconfig.json @@ -0,0 +1,19 @@ +{ + "files": [ + "angular-xeditable.d.ts", + "angular-xeditable-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": false + } +} \ No newline at end of file diff --git a/backbone-fetch-cache/backbone-fetch-cache-tests.ts b/backbone-fetch-cache/backbone-fetch-cache-tests.ts index e2eb532690..072e3c29ce 100644 --- a/backbone-fetch-cache/backbone-fetch-cache-tests.ts +++ b/backbone-fetch-cache/backbone-fetch-cache-tests.ts @@ -1,6 +1,5 @@ -/// - -import * as Backbone from "backbone-fetch-cache"; +import * as Backbone from "backbone"; +import * as BackboneFetchCache from "backbone-fetch-cache"; // static methods / properties diff --git a/backbone-fetch-cache/backbone-fetch-cache.d.ts b/backbone-fetch-cache/backbone-fetch-cache.d.ts deleted file mode 100644 index 449db1c667..0000000000 --- a/backbone-fetch-cache/backbone-fetch-cache.d.ts +++ /dev/null @@ -1,189 +0,0 @@ -// Type definitions for backbone-fetch-cache 1.4.0 -// Project: https://github.com/madglory/backbone-fetch-cache -// Definitions by: delphinus -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace BackboneFetchCache { - - interface SuperMethods { - - modelFetch(options?: Backbone.ModelFetchOptions): JQueryXHR; - modelSync(...arg: any[]): JQueryXHR; - collectionFetch(options?: Backbone.CollectionFetchOptions): JQueryXHR; - } - - interface GetCacheOptions { - - data?: any; - url?: string; - } - - interface SetCacheOptions extends GetCacheOptions { - - cache: boolean; - expires: boolean | number; - prefill: boolean; - prefillExpires: boolean | number; - } - - interface Cache { - - expires: number; - lastSync: number; - prefillExpires: number; - value: any; - } - - interface GetCacheKeyObject { - - getCacheKey?: (opts?: GetCacheOptions) => string; - url?: () => string; - } - - type GetCacheKeyOptions = string | {url: string} | GetCacheKeyObject; - - interface Static { - - /** - * Global flag to enable/disable caching - */ - enabled: boolean; - - /** - * By default the cache is persisted in localStorage (if available). - * Set Backbone.fetchCache.localStorage = false to disable this. - */ - localStorage: boolean; - - /** - * Sometimes you just need to clear a cached item manually. - * Backbone.fetchCache.clearItem() can be called safely from anywhere - * in your application. It will take your backbone Model or Collection, - * a function that returns the key String, or the key String itself. If - * you pass in a Model or Collection, the .getCacheKey() method will be - * checked before the url property. - */ - clearItem(...args: any[]): any; - - /** - * You can explicitly fetch a cached item, without having to call the - * models/collection fetch. This might be useful for debugging and - * testing. - */ - getCache(key: () => string, opts?: GetCacheOptions): Cache; - getCache(key: GetCacheKeyOptions, opts?: GetCacheOptions): Cache; - - getCacheKey(key: () => string, opts?: GetCacheOptions): string; - getCacheKey(key: GetCacheKeyOptions, opts?: GetCacheOptions): string; - - /** - * If you want to know when was the last (server) sync of a given key, you can use. - */ - getLastSync(key: () => string, opts?: GetCacheOptions): number; - getLastSync(key: GetCacheKeyOptions, opts?: GetCacheOptions): number; - - getLocalStorage(): void; - getLocalStorageKey(): string; - - /** - * When setting items in localStorage, the browser may throw a - * QUOTA_EXCEEDED_ERR, meaning the store is full. Backbone.fetchCache - * tries to work around this problem by deleting what it considers the - * most stale item to make space for the new data. The staleness of - * data is determined by the sorting function priorityFn, which by - * default returns the oldest item. - */ - priorityFn(a: Cache, b: Cache): number; - - reset(): void; - - setCache(instance: () => string, opts?: SetCacheOptions, attrs?: any): void; - setCache(instance: GetCacheKeyOptions, opts?: SetCacheOptions, attrs?: any): void; - - setLocalStorage(...args: any[]): any; - - _superMethods: SuperMethods; - } -} - -declare module Backbone { - - var fetchCache: BackboneFetchCache.Static; - - /** - * The most used API hook for Backbone Fetch Cache is the Model and - * Collection #.fetch() method. Here are the options you can pass into that - * method to get behaviour particular to Backbone Fetch Cache. - */ - interface ModelFetchWithCacheOptions extends ModelFetchOptions { - - /** - * Calls to modelInstance.fetch or collectionInstance.fetch will be - * fulfilled from the cache (if possible) when cache: true is set in - * the options hash. - */ - cache?: boolean; - - context?: any; - - /** - * Cache values expire after 5 minutes by default. You can adjust this - * by passing expires: to the fetch call. Set to false to - * never expire. - */ - expires?: number; - - /** - * This option allows the model/collection to be populated from the - * cache immediately and then be updated once the call to fetch has - * completed. The initial cache hit calls the prefillSuccess callback - * and then the AJAX success/error callbacks are called as normal when - * the request is complete. This allows the page to render something - * immediately and then update it after the request completes. (Note: - * the prefillSuccess callback will not fire if the data is not found - * in the cache.) - * - * prefill and prefillExpires options can be used with the promises - * interface like so (note: the progress event will not fire if the - * data is not found in the cache.). - * - * prefillExpires affects prefill in the following ways: - * - * 1. If the cache doesn't hold the requested data, just fetch it - * (usual behaviour) - * 2. If the cache holds an expired version of the requested data, just - * fetch it (usual behaviour) - * 3. If the cache holds requested data that is neither expired nor - * prefill expired, just return it and don't do a fetch / prefill - * callback (usual cache behavior, unusual prefill behaviour) - * 4. If the cache holds requested data that isn't expired but is - * prefill expired, use the prefill callback and do a fetch (usual - * prefill behaviour) - */ - prefill?: boolean; - prefillExpires?: number; - prefillSuccess?: (self: any, attributes: any, opts: ModelFetchWithCacheOptions) => void; - } - - interface CollectionFetchWithCacheOptions extends ModelFetchWithCacheOptions { - - prefillSuccess?: (self: any) => void; - } - - interface ModelWithCache extends Model { - - fetch(options?: ModelFetchWithCacheOptions): JQueryXHR; - } - - interface CollectionWithCache extends Collection { - - fetch(options?: CollectionFetchWithCacheOptions): JQueryXHR; - } -} - -declare module "backbone-fetch-cache" { - - export = Backbone; -} diff --git a/backbone-fetch-cache/index.d.ts b/backbone-fetch-cache/index.d.ts new file mode 100644 index 0000000000..0067bb4443 --- /dev/null +++ b/backbone-fetch-cache/index.d.ts @@ -0,0 +1,183 @@ +// Type definitions for backbone-fetch-cache 1.4.0 +// Project: https://github.com/madglory/backbone-fetch-cache +// Definitions by: delphinus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Backbone from "backbone"; + +interface SuperMethods { + + modelFetch(options?: Backbone.ModelFetchOptions): JQueryXHR; + modelSync(...arg: any[]): JQueryXHR; + collectionFetch(options?: Backbone.CollectionFetchOptions): JQueryXHR; +} + +interface GetCacheOptions { + + data?: any; + url?: string; +} + +interface SetCacheOptions extends GetCacheOptions { + + cache: boolean; + expires: boolean | number; + prefill: boolean; + prefillExpires: boolean | number; +} + +interface Cache { + + expires: number; + lastSync: number; + prefillExpires: number; + value: any; +} + +interface GetCacheKeyObject { + + getCacheKey?: (opts?: GetCacheOptions) => string; + url?: () => string; +} + +type GetCacheKeyOptions = string | {url: string} | GetCacheKeyObject; + +interface Static { + + /** + * Global flag to enable/disable caching + */ + enabled: boolean; + + /** + * By default the cache is persisted in localStorage (if available). + * Set Backbone.fetchCache.localStorage = false to disable this. + */ + localStorage: boolean; + + /** + * Sometimes you just need to clear a cached item manually. + * Backbone.fetchCache.clearItem() can be called safely from anywhere + * in your application. It will take your backbone Model or Collection, + * a function that returns the key String, or the key String itself. If + * you pass in a Model or Collection, the .getCacheKey() method will be + * checked before the url property. + */ + clearItem(...args: any[]): any; + + /** + * You can explicitly fetch a cached item, without having to call the + * models/collection fetch. This might be useful for debugging and + * testing. + */ + getCache(key: () => string, opts?: GetCacheOptions): Cache; + getCache(key: GetCacheKeyOptions, opts?: GetCacheOptions): Cache; + + getCacheKey(key: () => string, opts?: GetCacheOptions): string; + getCacheKey(key: GetCacheKeyOptions, opts?: GetCacheOptions): string; + + /** + * If you want to know when was the last (server) sync of a given key, you can use. + */ + getLastSync(key: () => string, opts?: GetCacheOptions): number; + getLastSync(key: GetCacheKeyOptions, opts?: GetCacheOptions): number; + + getLocalStorage(): void; + getLocalStorageKey(): string; + + /** + * When setting items in localStorage, the browser may throw a + * QUOTA_EXCEEDED_ERR, meaning the store is full. Backbone.fetchCache + * tries to work around this problem by deleting what it considers the + * most stale item to make space for the new data. The staleness of + * data is determined by the sorting function priorityFn, which by + * default returns the oldest item. + */ + priorityFn(a: Cache, b: Cache): number; + + reset(): void; + + setCache(instance: () => string, opts?: SetCacheOptions, attrs?: any): void; + setCache(instance: GetCacheKeyOptions, opts?: SetCacheOptions, attrs?: any): void; + + setLocalStorage(...args: any[]): any; + + _superMethods: SuperMethods; +} + +declare module "backbone" { + + var fetchCache: Static; + + /** + * The most used API hook for Backbone Fetch Cache is the Model and + * Collection #.fetch() method. Here are the options you can pass into that + * method to get behaviour particular to Backbone Fetch Cache. + */ + interface ModelFetchWithCacheOptions extends ModelFetchOptions { + + /** + * Calls to modelInstance.fetch or collectionInstance.fetch will be + * fulfilled from the cache (if possible) when cache: true is set in + * the options hash. + */ + cache?: boolean; + + context?: any; + + /** + * Cache values expire after 5 minutes by default. You can adjust this + * by passing expires: to the fetch call. Set to false to + * never expire. + */ + expires?: number; + + /** + * This option allows the model/collection to be populated from the + * cache immediately and then be updated once the call to fetch has + * completed. The initial cache hit calls the prefillSuccess callback + * and then the AJAX success/error callbacks are called as normal when + * the request is complete. This allows the page to render something + * immediately and then update it after the request completes. (Note: + * the prefillSuccess callback will not fire if the data is not found + * in the cache.) + * + * prefill and prefillExpires options can be used with the promises + * interface like so (note: the progress event will not fire if the + * data is not found in the cache.). + * + * prefillExpires affects prefill in the following ways: + * + * 1. If the cache doesn't hold the requested data, just fetch it + * (usual behaviour) + * 2. If the cache holds an expired version of the requested data, just + * fetch it (usual behaviour) + * 3. If the cache holds requested data that is neither expired nor + * prefill expired, just return it and don't do a fetch / prefill + * callback (usual cache behavior, unusual prefill behaviour) + * 4. If the cache holds requested data that isn't expired but is + * prefill expired, use the prefill callback and do a fetch (usual + * prefill behaviour) + */ + prefill?: boolean; + prefillExpires?: number; + prefillSuccess?: (self: any, attributes: any, opts: ModelFetchWithCacheOptions) => void; + } + + interface CollectionFetchWithCacheOptions extends ModelFetchWithCacheOptions { + + prefillSuccess?: (self: any) => void; + } + + interface ModelWithCache extends Model { + + fetch(options?: ModelFetchWithCacheOptions): JQueryXHR; + } + + interface CollectionWithCache extends Collection { + + fetch(options?: CollectionFetchWithCacheOptions): JQueryXHR; + } +} + +export as namespace BackboneFetchCache; diff --git a/backbone-fetch-cache/tsconfig.json b/backbone-fetch-cache/tsconfig.json new file mode 100644 index 0000000000..563a475286 --- /dev/null +++ b/backbone-fetch-cache/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "backbone-fetch-cache-tests.ts" + ] +} \ No newline at end of file diff --git a/backbone/index.d.ts b/backbone/index.d.ts index f1203c0967..975d7f33c9 100644 --- a/backbone/index.d.ts +++ b/backbone/index.d.ts @@ -58,7 +58,7 @@ declare namespace Backbone { interface ModelSetOptions extends Silenceable, Validable { } - interface ModelFetchOptions extends PersistenceOptions, ModelSetOptions, Parseable { + export interface ModelFetchOptions extends PersistenceOptions, ModelSetOptions, Parseable { } interface ModelSaveOptions extends Silenceable, Waitable, Validable, Parseable, PersistenceOptions { diff --git a/backlog-js/backlog-js-tests.ts b/backlog-js/backlog-js-tests.ts index 979eb57ca4..8a3e47fbb1 100644 --- a/backlog-js/backlog-js-tests.ts +++ b/backlog-js/backlog-js-tests.ts @@ -1,5 +1,3 @@ -/// - import * as backlogjs from 'backlog-js'; const host = 'example.backlog.jp'; diff --git a/backlog-js/backlog-js.d.ts b/backlog-js/backlog-js.d.ts deleted file mode 100644 index 353e7e90cd..0000000000 --- a/backlog-js/backlog-js.d.ts +++ /dev/null @@ -1,695 +0,0 @@ -// Type definitions for backlog-js 0.9.0 -// Project: https://github.com/nulab/backlog-js -// Definitions by: Yuichi Watanabe -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// - -declare module 'backlog-js' { - - class Request { - private configure; - constructor(configure: { - host: string; - apiKey?: string; - accessToken?: string; - timeout?: number; - }); - get(path: string, params?: any): Promise; - post(path: string, params?: any): Promise; - put(path: string, params: any): Promise; - patch(path: string, params: any): Promise; - delete(path: string, params?: any): Promise; - request(options: { - method: string; - path: string; - params?: Params | FormData; - }): Promise; - checkStatus(response: IResponse): Promise; - parseJSON(response: IResponse): Promise; - private toFormData(params); - private toQueryString(params); - webAppBaseURL: string; - restBaseURL: string; - } - - type Params = { - [index: string]: number | string | number[] | string[]; - }; - - export class Backlog extends Request { - constructor(configure: { - host: string; - apiKey?: string; - accessToken?: string; - timeout?: number; - }); - getSpace(): Promise; - getSpaceActivities(params: Option.Space.GetActivitiesParams): Promise; - getSpaceNotification(): Promise; - putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise; - getSpaceDiskUsage(): Promise; - getSpaceIcon(): Promise; - postSpaceAttachment(form: FormData): Promise; - getUsers(): Promise; - getUser(userId: number): Promise; - postUser(params: Option.User.PostUserParams): Promise; - patchUser(userId: number, params: Option.User.PatchUserParams): Promise; - deleteUser(userId: number): Promise; - getMyself(): Promise; - getUserActivities(userId: number, params: Option.User.GetUserActivitiesParams): Promise; - getUserStars(userId: number, params: Option.User.GetUserStarsParams): Promise; - getUserStarsCount(userId: number, params: Option.User.GetUserStarsCountParams): Promise; - getRecentlyViewedIssues(params: Option.User.GetRecentlyViewedParams): Promise; - getRecentlyViewedProjects(params: Option.User.GetRecentlyViewedParams): Promise; - getRecentlyViewedWikis(params: Option.User.GetRecentlyViewedParams): Promise; - getUserIcon(userId: number): Promise; - getGroups(params: Option.Group.GetGroupsParams): Promise; - postGroups(params: Option.Group.PostGroupsParams): Promise; - getGroup(groupId: number): Promise; - patchGroup(groupId: number, params: Option.Group.PatchGroupParams): Promise; - deleteGroup(groupId: number): Promise; - getStatuses(): Promise; - getResolutions(): Promise; - getPriorities(): Promise; - postProject(params: Option.Project.PostProjectParams): Promise; - getProjects(params?: Option.Project.GetProjectsParams): Promise; - getProject(projectIdOrKey: string): Promise; - patchProject(projectIdOrKey: string, params: Option.Project.PatchProjectParams): Promise; - deleteProject(projectIdOrKey: string): Promise; - getProjectActivities(projectIdOrKey: string, params: Option.Space.GetActivitiesParams): Promise; - getProjectUsers(projectIdOrKey: string): Promise; - deleteProjectUsers(projectIdOrKey: string, params: Option.Project.DeleteProjectUsersParams): Promise; - postProjectAdministrators(projectIdOrKey: string, params: Option.Project.PostProjectAdministrators): Promise; - getProjectAdministrators(projectIdOrKey: string): Promise; - deleteProjectAdministrators(projectIdOrKey: string, params: Option.Project.DeleteProjectAdministrators): Promise; - getIssueTypes(projectIdOrKey: string): Promise; - postIssueType(projectIdOrKey: string, params: Option.Project.PostIssueTypeParams): Promise; - patchIssueType(projectIdOrKey: string, id: number, params: Option.Project.PatchIssueTypeParams): Promise; - deleteIssueType(projectIdOrKey: string, id: number, params: Option.Project.DeleteIssueTypeParams): Promise; - getCategories(projectIdOrKey: string): Promise; - postCategories(projectIdOrKey: string, params: Option.Project.PostCategoriesParams): Promise; - patchCategories(projectIdOrKey: string, id: number, params: Option.Project.PatchCategoriesParams): Promise; - deleteCategories(projectIdOrKey: string, id: number): Promise; - getVersions(projectIdOrKey: string): Promise; - postVersions(projectIdOrKey: string, params: Option.Project.PostVersionsParams): Promise; - patchVersions(projectIdOrKey: string, id: number, params: Option.Project.PatchVersionsParams): Promise; - deleteVersions(projectIdOrKey: string, id: number): Promise; - getCustomFields(projectIdOrKey: string): Promise; - postCustomField(projectIdOrKey: string, params: Option.Project.PostCustomFieldParams | Option.Project.PostCustomFieldWithNumericParams | Option.Project.PostCustomFieldWithDateParams | Option.Project.PostCustomFieldWithListParams): Promise; - patchCustomField(projectIdOrKey: string, id: number, params: Option.Project.PatchCustomFieldParams | Option.Project.PatchCustomFieldWithNumericParams | Option.Project.PatchCustomFieldWithDateParams | Option.Project.PatchCustomFieldWithListParams): Promise; - deleteCustomField(projectIdOrKey: string, id: number): Promise; - postCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; - patchCustomFieldItem(projectIdOrKey: string, id: number, itemId: number, params: Option.Project.PatchCustomFieldItemParams): Promise; - deleteCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; - getSharedFiles(projectIdOrKey: string, path: string, params: Option.Project.GetSharedFilesParams): Promise; - getProjectsDiskUsage(projectIdOrKey: string): Promise; - getWebhooks(projectIdOrKey: string): Promise; - postWebhook(projectIdOrKey: string, params: Option.Project.PostWebhookParams): Promise; - getWebhook(projectIdOrKey: string, webhookId: string): Promise; - patchWebhook(projectIdOrKey: string, webhookId: string, params: Option.Project.PatchWebhookParams): Promise; - deleteWebhook(projectIdOrKey: string, webhookId: string): Promise; - postIssue(params: Option.Issue.PostIssueParams): Promise; - patchIssue(issueIdOrKey: string, params: Option.Issue.PatchIssueParams): Promise; - getIssues(params?: Option.Issue.GetIssuesParams): Promise; - getIssue(issueIdOrKey: string): Promise; - getIssuesCount(params?: Option.Issue.GetIssuesParams): Promise; - deleteIssuesCount(issueIdOrKey: string): Promise; - getIssueComments(issueIdOrKey: string, params: Option.Issue.GetIssueCommentsParams): Promise; - postIssueComments(issueIdOrKey: string, params: Option.Issue.PostIssueCommentsParams): Promise; - getIssueCommentsCount(issueIdOrKey: string): Promise; - getIssueComment(issueIdOrKey: string, commentId: number): Promise; - patchIssueComment(issueIdOrKey: string, commentId: number, params: Option.Issue.PatchIssueCommentParams): Promise; - getIssueCommentNotifications(issueIdOrKey: string, commentId: number): Promise; - postIssueCommentNotifications(issueIdOrKey: string, commentId: number, prams: Option.Issue.IssueCommentNotifications): Promise; - getIssueAttachments(issueIdOrKey: string): Promise; - deleteIssueAttachment(issueIdOrKey: string, attachmentId: string): Promise; - getIssueSharedFiles(issueIdOrKey: string): Promise; - linkIssueSharedFiles(issueIdOrKey: string, params: Option.Issue.LinkIssueSharedFilesParams): Promise; - unlinkIssueSharedFile(issueIdOrKey: string, id: number): Promise; - getWikis(projectIdOrKey: number): Promise; - getWikisCount(projectIdOrKey: number): Promise; - getWikisTags(projectIdOrKey: number): Promise; - postWiki(params: Option.Wiki.PostWikiParams): Promise; - getWiki(wikiId: number): Promise; - patchWiki(wikiId: number, params: Option.Wiki.PatchWikiParams): Promise; - deleteWiki(wikiId: number, mailNotify: boolean): Promise; - getWikisAttachments(wikiId: number): Promise; - postWikisAttachments(wikiId: number, attachmentId: number[]): Promise; - deleteWikisAttachments(wikiId: number, attachmentId: number): Promise; - getWikisSharedFiles(wikiId: number): Promise; - linkWikisSharedFiles(wikiId: number, fileId: number[]): Promise; - unlinkWikisSharedFiles(wikiId: number, id: number): Promise; - getWikisHistory(wikiId: number, params: Option.Wiki.GetWikisHistoryParams): Promise; - getWikisStars(wikiId: number): Promise; - postStar(params: Option.Project.PostStarParams): Promise; - getNotifications(params: Option.Notification.GetNotificationsParams): Promise; - getNotificationsCount(params: Option.Notification.GetNotificationsCountParams): Promise; - resetNotificationsMarkAsRead(): Promise; - markAsReadNotification(id: number): Promise; - getGitRepositories(projectIdOrKey: string): Promise; - getGitRepository(projectIdOrKey: string, repoIdOrName: string): Promise; - getPullRequests(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; - getPullRequestsCount(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; - postPullRequest(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.PostPullRequestParams): Promise; - getPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; - patchPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PatchPullRequestParams): Promise; - getPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.GetPullRequestCommentsParams): Promise; - postPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PostPullRequestCommentsParams): Promise; - getPullRequestCommentsCount(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; - patchPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, commentId: number, params: Option.PullRequest.PatchPullRequestCommentsParams): Promise; - getPullRequestAttachments(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; - deletePullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; - getProjectIcon(projectIdOrKey: string): Promise; - getSharedFile(projectIdOrKey: string, sharedFileId: number): Promise; - getIssueAttachment(issueIdOrKey: string, attachmentId: number): Promise; - getWikiAttachment(wikiId: number, attachmentId: number): Promise; - getPullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; - private download(path); - private upload(path, params); - private parseFileData(response); - } - - export class OAuth2 { - private credentials; - private timeout; - constructor(credentials: Option.OAuth2.Credentials, timeout?: number); - getAuthorizationURL(options: { - host: string; - redirectUri?: string; - state?: string; - }): string; - getAccessToken(options: { - host: string; - code: string; - redirectUri?: string; - }): Promise; - refreshAccessToken(options: { - host: string; - refreshToken: string; - }): Promise; - } - - import { PassThrough } from 'stream'; - export namespace Entity { - export namespace File { - export type FileData = NodeFileData | BrowserFileData; - export interface NodeFileData { - body: PassThrough; - url: string; - filename: string; - } - export interface BrowserFileData { - body: any; - url: string; - blob?: () => Promise; - } - } - export namespace OAuth2 { - export interface AccessToken { - access_token: string; - token_type: string; - expires_in: number; - refresh_token: string; - } - } - } - - - export namespace Option { - export type Order = "asc" | "desc"; - export enum ActivityType { - Undefined = -1, - IssueCreated = 1, - IssueUpdated = 2, - IssueCommented = 3, - IssueDeleted = 4, - WikiCreated = 5, - WikiUpdated = 6, - WikiDeleted = 7, - FileAdded = 8, - FileUpdated = 9, - FileDeleted = 10, - SvnCommitted = 11, - GitPushed = 12, - GitRepositoryCreated = 13, - IssueMultiUpdated = 14, - ProjectUserAdded = 15, - ProjectUserRemoved = 16, - NotifyAdded = 17, - PullRequestAdded = 18, - PullRequestUpdated = 19, - PullRequestCommented = 20, - PullRequestMerged = 21, - } - export namespace Notification { - export interface GetNotificationsParams { - minId?: number; - maxId?: number; - count?: number; - order?: Order; - } - export interface GetNotificationsCountParams { - alreadyRead: boolean; - resourceAlreadyRead: boolean; - } - } - export namespace Space { - export interface GetActivitiesParams { - activityTypeId?: ActivityType[]; - minId?: number; - maxId?: number; - count?: number; - order?: Order; - } - export interface PutSpaceNotificationParams { - content: string; - } - } - export namespace User { - export interface PostUserParams { - userId: string; - password: string; - name: string; - mailAddress: string; - roleType: RoleType; - } - export interface PatchUserParams { - password?: string; - name?: string; - mailAddress?: string; - roleType?: RoleType; - } - export enum RoleType { - Admin = 1, - User = 2, - Reporter = 3, - Viewer = 4, - GuestReporter = 5, - GuestViewer = 6, - } - export interface GetUserActivitiesParams { - activityTypeId?: ActivityType[]; - minId?: number; - maxId?: number; - count?: number; - order?: Order; - } - export interface GetUserStarsParams { - minId?: number; - maxId?: number; - count?: number; - order?: Order; - } - export interface GetUserStarsCountParams { - since?: string; - until?: string; - } - export interface GetRecentlyViewedParams { - order?: Order; - offset?: number; - count?: number; - } - } - export namespace Group { - export interface GetGroupsParams { - order?: Order; - offset?: number; - count?: number; - } - export interface PostGroupsParams { - name: string; - members?: string[]; - } - export interface PatchGroupParams { - name?: string; - members?: string[]; - } - } - export namespace Project { - export type TextFormattingRule = "backlog" | "markdown"; - export interface PostProjectParams { - name: string; - key: string; - chartEnabled: boolean; - projectLeaderCanEditProjectLeader?: boolean; - subtaskingEnabled: boolean; - textFormattingRule: TextFormattingRule; - } - export interface PatchProjectParams { - name?: string; - key?: string; - chartEnabled?: boolean; - subtaskingEnabled?: boolean; - projectLeaderCanEditProjectLeader?: boolean; - textFormattingRule?: TextFormattingRule; - archived?: boolean; - } - export interface GetProjectsParams { - archived?: boolean; - all?: boolean; - } - export interface DeleteProjectUsersParams { - userId: number; - } - export interface PostProjectAdministrators { - userId: number; - } - export interface DeleteProjectAdministrators { - userId: number; - } - export type IssueTypeColor = "#e30000" | "#990000" | "#934981" | "#814fbc" | "#2779ca" | "#007e9a" | "#7ea800" | "#ff9200" | "#ff3265" | "#666665"; - export interface PostIssueTypeParams { - name: string; - color: IssueTypeColor; - } - export interface PatchIssueTypeParams { - name?: string; - color?: IssueTypeColor; - } - export interface DeleteIssueTypeParams { - substituteIssueTypeId: number; - } - export interface PostCategoriesParams { - name: string; - } - export interface PatchCategoriesParams { - name: string; - } - export interface PostVersionsParams { - name: string; - description: string; - startDate: string; - releaseDueDate: string; - } - export interface PatchVersionsParams { - name: string; - description?: string; - startDate?: string; - releaseDueDate?: string; - archived?: boolean; - } - export interface PostCustomFieldParams { - typeId: FieldType; - name: string; - applicableIssueTypes?: number[]; - description?: string; - required?: boolean; - } - export interface PostCustomFieldWithNumericParams extends PostCustomFieldParams { - min?: number; - max?: number; - initialValue?: number; - unit?: string; - } - export interface PostCustomFieldWithDateParams extends PostCustomFieldParams { - min?: string; - max?: string; - initialValueType?: number; - initialDate?: string; - initialShift?: number; - } - export interface PostCustomFieldWithListParams extends PostCustomFieldParams { - items?: string[]; - allowInput?: boolean; - allowAddItem?: boolean; - } - export interface PatchCustomFieldParams { - name?: string; - applicableIssueTypes?: number[]; - description?: string; - required?: boolean; - } - export interface PatchCustomFieldWithNumericParams extends PatchCustomFieldParams { - min?: number; - max?: number; - initialValue?: number; - unit?: string; - } - export interface PatchCustomFieldWithDateParams extends PatchCustomFieldParams { - min?: string; - max?: string; - initialValueType?: number; - initialDate?: string; - initialShift?: number; - } - export interface PatchCustomFieldWithListParams extends PatchCustomFieldParams { - items?: string[]; - allowInput?: boolean; - allowAddItem?: boolean; - } - export interface PostCustomFieldItemParams { - name: string; - } - export interface PatchCustomFieldItemParams { - name: string; - } - export interface GetSharedFilesParams { - order?: Order; - offset?: number; - count?: number; - } - export interface PostWebhookParams { - name?: string; - description?: string; - hookUrl?: string; - allEvent?: boolean; - activityTypeIds?: number[]; - } - export interface PatchWebhookParams { - name?: string; - description?: string; - hookUrl?: string; - allEvent?: boolean; - activityTypeIds?: number[]; - } - export enum FieldType { - Text = 1, - TextArea = 2, - Numeric = 3, - Date = 4, - SingleList = 5, - MultipleList = 6, - CheckBox = 7, - Radio = 8, - } - export interface PostStarParams { - issueId?: number; - commentId?: number; - wikiId?: number; - pullRequestId?: number; - pullRequestCommentId?: number; - } - } - export namespace Issue { - export interface PostIssueParams { - projectId: number; - summary: string; - priorityId: number; - issueTypeId: number; - parentIssueId?: number; - description?: string; - startDate?: string; - dueDate?: string; - estimatedHours?: number; - actualHours?: number; - categoryId?: number[]; - versionId?: number[]; - milestoneId?: number[]; - assigneeId?: number; - notifiedUserId?: number[]; - attachmentId?: number[]; - [customField_: string]: any; - } - export interface PatchIssueParams { - summary?: string; - parentIssueId?: number; - description?: string; - statusId?: number; - resolutionId?: number; - startDate?: string; - dueDate?: string; - estimatedHours?: number; - actualHours?: number; - issueTypeId?: number; - categoryId?: number[]; - versionId?: number[]; - milestoneId?: number[]; - priorityId?: number; - assigneeId?: number; - notifiedUserId?: number[]; - attachmentId?: number[]; - comment?: string; - [customField_: string]: any; - } - export interface GetIssuesParams { - projectId?: number[]; - issueTypeId?: number[]; - categoryId?: number[]; - versionId?: number[]; - milestoneId?: number[]; - statusId?: number[]; - priorityId?: number[]; - assigneeId?: number[]; - createdUserId?: number[]; - resolutionId?: number[]; - parentChild?: ParentChildType; - attachment?: boolean; - sharedFile?: boolean; - sort?: SortKey; - order?: Order; - offset?: number; - count?: number; - createdSince?: string; - createdUntil?: string; - updatedSince?: string; - updatedUntil?: string; - startDateSince?: string; - startDateUntil?: string; - dueDateSince?: string; - dueDateUntil?: string; - id?: number[]; - parentIssueId?: number[]; - keyword: string; - [customField_: string]: any; - } - export enum ParentChildType { - All = 0, - NotChild = 1, - Child = 2, - NotChildNotParent = 3, - Parent = 4, - } - export type SortKey = "issueType" | "category" | "version" | "milestone" | "summary" | "status" | "priority" | "attachment" | "sharedFile" | "created" | "createdUser" | "updated" | "updatedUser" | "assignee" | "startDate" | "dueDate" | "estimatedHours" | "actualHours" | "childIssue"; - export interface GetIssueCommentsParams { - minId?: number; - maxId?: number; - count?: number; - order?: Order; - } - export interface PostIssueCommentsParams { - content: string; - notifiedUserId?: number[]; - attachmentId?: number[]; - } - export interface PatchIssueCommentParams { - content: string; - } - export interface IssueCommentNotifications { - notifiedUserId: number[]; - } - export interface LinkIssueSharedFilesParams { - fileId: number[]; - } - } - export namespace PullRequest { - export interface GetPullRequestsParams { - statusId?: number[]; - assigneeId?: number[]; - issueId?: number[]; - createdUserId?: number[]; - offset?: number; - count?: number; - } - export interface PostPullRequestParams { - summary: string; - description: string; - base: string; - branch: string; - issueId?: number; - assigneeId?: number; - notifiedUserId?: number[]; - attachmentId?: number[]; - } - export interface PatchPullRequestParams { - summary?: string; - description?: string; - issueId?: number; - assigneeId?: number; - notifiedUserId?: number[]; - comment?: string[]; - } - export interface GetPullRequestCommentsParams { - minId?: number; - maxId?: number; - count?: number; - order?: Order; - } - export interface PostPullRequestCommentsParams { - content: string; - notifiedUserId?: number[]; - } - export interface PatchPullRequestCommentsParams { - content: string; - } - } - export namespace Wiki { - export interface PostWikiParams { - projectId: number; - name: string; - content: string; - mailNotify?: boolean; - } - export interface PatchWikiParams { - name?: string; - content?: string; - mailNotify?: boolean; - } - export interface GetWikisHistoryParams { - minId?: number; - maxId?: number; - count?: number; - order?: Order; - } - } - export namespace OAuth2 { - export interface Credentials { - clientId: string; - clientSecret: string; - } - } - } - - export namespace Error { - export class BacklogError extends global.Error { - private _name; - private _url; - private _status; - private _body; - private _response; - constructor(name: BacklogErrorNameType, response: IResponse, body?: { - errors: BacklogErrorMessage[]; - }); - name: BacklogErrorNameType; - url: string; - status: number; - body: { - errors: BacklogErrorMessage[]; - }; - response: IResponse; - } - export class BacklogApiError extends BacklogError { - constructor(response: IResponse, body?: { - errors: BacklogErrorMessage[]; - }); - } - export class BacklogAuthError extends BacklogError { - constructor(response: IResponse, body?: { - errors: BacklogErrorMessage[]; - }); - } - export class UnexpectedError extends BacklogError { - constructor(response: IResponse); - } - export interface BacklogErrorMessage { - message: string; - code: number; - errorInfo: string; - moreInfo: string; - } - export type BacklogErrorNameType = 'BacklogApiError' | 'BacklogAuthError' | 'UnexpectedError'; - } - -} diff --git a/backlog-js/index.d.ts b/backlog-js/index.d.ts new file mode 100644 index 0000000000..b15602f958 --- /dev/null +++ b/backlog-js/index.d.ts @@ -0,0 +1,690 @@ +// Type definitions for backlog-js 0.9.0 +// Project: https://github.com/nulab/backlog-js +// Definitions by: Yuichi Watanabe +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +declare class Request { + private configure; + constructor(configure: { + host: string; + apiKey?: string; + accessToken?: string; + timeout?: number; + }); + get(path: string, params?: any): Promise; + post(path: string, params?: any): Promise; + put(path: string, params: any): Promise; + patch(path: string, params: any): Promise; + delete(path: string, params?: any): Promise; + request(options: { + method: string; + path: string; + params?: Params | FormData; + }): Promise; + checkStatus(response: IResponse): Promise; + parseJSON(response: IResponse): Promise; + private toFormData(params); + private toQueryString(params); + webAppBaseURL: string; + restBaseURL: string; +} + +type Params = { + [index: string]: number | string | number[] | string[]; +}; + +export class Backlog extends Request { + constructor(configure: { + host: string; + apiKey?: string; + accessToken?: string; + timeout?: number; + }); + getSpace(): Promise; + getSpaceActivities(params: Option.Space.GetActivitiesParams): Promise; + getSpaceNotification(): Promise; + putSpaceNotification(params: Option.Space.PutSpaceNotificationParams): Promise; + getSpaceDiskUsage(): Promise; + getSpaceIcon(): Promise; + postSpaceAttachment(form: FormData): Promise; + getUsers(): Promise; + getUser(userId: number): Promise; + postUser(params: Option.User.PostUserParams): Promise; + patchUser(userId: number, params: Option.User.PatchUserParams): Promise; + deleteUser(userId: number): Promise; + getMyself(): Promise; + getUserActivities(userId: number, params: Option.User.GetUserActivitiesParams): Promise; + getUserStars(userId: number, params: Option.User.GetUserStarsParams): Promise; + getUserStarsCount(userId: number, params: Option.User.GetUserStarsCountParams): Promise; + getRecentlyViewedIssues(params: Option.User.GetRecentlyViewedParams): Promise; + getRecentlyViewedProjects(params: Option.User.GetRecentlyViewedParams): Promise; + getRecentlyViewedWikis(params: Option.User.GetRecentlyViewedParams): Promise; + getUserIcon(userId: number): Promise; + getGroups(params: Option.Group.GetGroupsParams): Promise; + postGroups(params: Option.Group.PostGroupsParams): Promise; + getGroup(groupId: number): Promise; + patchGroup(groupId: number, params: Option.Group.PatchGroupParams): Promise; + deleteGroup(groupId: number): Promise; + getStatuses(): Promise; + getResolutions(): Promise; + getPriorities(): Promise; + postProject(params: Option.Project.PostProjectParams): Promise; + getProjects(params?: Option.Project.GetProjectsParams): Promise; + getProject(projectIdOrKey: string): Promise; + patchProject(projectIdOrKey: string, params: Option.Project.PatchProjectParams): Promise; + deleteProject(projectIdOrKey: string): Promise; + getProjectActivities(projectIdOrKey: string, params: Option.Space.GetActivitiesParams): Promise; + getProjectUsers(projectIdOrKey: string): Promise; + deleteProjectUsers(projectIdOrKey: string, params: Option.Project.DeleteProjectUsersParams): Promise; + postProjectAdministrators(projectIdOrKey: string, params: Option.Project.PostProjectAdministrators): Promise; + getProjectAdministrators(projectIdOrKey: string): Promise; + deleteProjectAdministrators(projectIdOrKey: string, params: Option.Project.DeleteProjectAdministrators): Promise; + getIssueTypes(projectIdOrKey: string): Promise; + postIssueType(projectIdOrKey: string, params: Option.Project.PostIssueTypeParams): Promise; + patchIssueType(projectIdOrKey: string, id: number, params: Option.Project.PatchIssueTypeParams): Promise; + deleteIssueType(projectIdOrKey: string, id: number, params: Option.Project.DeleteIssueTypeParams): Promise; + getCategories(projectIdOrKey: string): Promise; + postCategories(projectIdOrKey: string, params: Option.Project.PostCategoriesParams): Promise; + patchCategories(projectIdOrKey: string, id: number, params: Option.Project.PatchCategoriesParams): Promise; + deleteCategories(projectIdOrKey: string, id: number): Promise; + getVersions(projectIdOrKey: string): Promise; + postVersions(projectIdOrKey: string, params: Option.Project.PostVersionsParams): Promise; + patchVersions(projectIdOrKey: string, id: number, params: Option.Project.PatchVersionsParams): Promise; + deleteVersions(projectIdOrKey: string, id: number): Promise; + getCustomFields(projectIdOrKey: string): Promise; + postCustomField(projectIdOrKey: string, params: Option.Project.PostCustomFieldParams | Option.Project.PostCustomFieldWithNumericParams | Option.Project.PostCustomFieldWithDateParams | Option.Project.PostCustomFieldWithListParams): Promise; + patchCustomField(projectIdOrKey: string, id: number, params: Option.Project.PatchCustomFieldParams | Option.Project.PatchCustomFieldWithNumericParams | Option.Project.PatchCustomFieldWithDateParams | Option.Project.PatchCustomFieldWithListParams): Promise; + deleteCustomField(projectIdOrKey: string, id: number): Promise; + postCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; + patchCustomFieldItem(projectIdOrKey: string, id: number, itemId: number, params: Option.Project.PatchCustomFieldItemParams): Promise; + deleteCustomFieldItem(projectIdOrKey: string, id: number, params: Option.Project.PostCustomFieldItemParams): Promise; + getSharedFiles(projectIdOrKey: string, path: string, params: Option.Project.GetSharedFilesParams): Promise; + getProjectsDiskUsage(projectIdOrKey: string): Promise; + getWebhooks(projectIdOrKey: string): Promise; + postWebhook(projectIdOrKey: string, params: Option.Project.PostWebhookParams): Promise; + getWebhook(projectIdOrKey: string, webhookId: string): Promise; + patchWebhook(projectIdOrKey: string, webhookId: string, params: Option.Project.PatchWebhookParams): Promise; + deleteWebhook(projectIdOrKey: string, webhookId: string): Promise; + postIssue(params: Option.Issue.PostIssueParams): Promise; + patchIssue(issueIdOrKey: string, params: Option.Issue.PatchIssueParams): Promise; + getIssues(params?: Option.Issue.GetIssuesParams): Promise; + getIssue(issueIdOrKey: string): Promise; + getIssuesCount(params?: Option.Issue.GetIssuesParams): Promise; + deleteIssuesCount(issueIdOrKey: string): Promise; + getIssueComments(issueIdOrKey: string, params: Option.Issue.GetIssueCommentsParams): Promise; + postIssueComments(issueIdOrKey: string, params: Option.Issue.PostIssueCommentsParams): Promise; + getIssueCommentsCount(issueIdOrKey: string): Promise; + getIssueComment(issueIdOrKey: string, commentId: number): Promise; + patchIssueComment(issueIdOrKey: string, commentId: number, params: Option.Issue.PatchIssueCommentParams): Promise; + getIssueCommentNotifications(issueIdOrKey: string, commentId: number): Promise; + postIssueCommentNotifications(issueIdOrKey: string, commentId: number, prams: Option.Issue.IssueCommentNotifications): Promise; + getIssueAttachments(issueIdOrKey: string): Promise; + deleteIssueAttachment(issueIdOrKey: string, attachmentId: string): Promise; + getIssueSharedFiles(issueIdOrKey: string): Promise; + linkIssueSharedFiles(issueIdOrKey: string, params: Option.Issue.LinkIssueSharedFilesParams): Promise; + unlinkIssueSharedFile(issueIdOrKey: string, id: number): Promise; + getWikis(projectIdOrKey: number): Promise; + getWikisCount(projectIdOrKey: number): Promise; + getWikisTags(projectIdOrKey: number): Promise; + postWiki(params: Option.Wiki.PostWikiParams): Promise; + getWiki(wikiId: number): Promise; + patchWiki(wikiId: number, params: Option.Wiki.PatchWikiParams): Promise; + deleteWiki(wikiId: number, mailNotify: boolean): Promise; + getWikisAttachments(wikiId: number): Promise; + postWikisAttachments(wikiId: number, attachmentId: number[]): Promise; + deleteWikisAttachments(wikiId: number, attachmentId: number): Promise; + getWikisSharedFiles(wikiId: number): Promise; + linkWikisSharedFiles(wikiId: number, fileId: number[]): Promise; + unlinkWikisSharedFiles(wikiId: number, id: number): Promise; + getWikisHistory(wikiId: number, params: Option.Wiki.GetWikisHistoryParams): Promise; + getWikisStars(wikiId: number): Promise; + postStar(params: Option.Project.PostStarParams): Promise; + getNotifications(params: Option.Notification.GetNotificationsParams): Promise; + getNotificationsCount(params: Option.Notification.GetNotificationsCountParams): Promise; + resetNotificationsMarkAsRead(): Promise; + markAsReadNotification(id: number): Promise; + getGitRepositories(projectIdOrKey: string): Promise; + getGitRepository(projectIdOrKey: string, repoIdOrName: string): Promise; + getPullRequests(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; + getPullRequestsCount(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.GetPullRequestsParams): Promise; + postPullRequest(projectIdOrKey: string, repoIdOrName: string, params: Option.PullRequest.PostPullRequestParams): Promise; + getPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + patchPullRequest(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PatchPullRequestParams): Promise; + getPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.GetPullRequestCommentsParams): Promise; + postPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, params: Option.PullRequest.PostPullRequestCommentsParams): Promise; + getPullRequestCommentsCount(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + patchPullRequestComments(projectIdOrKey: string, repoIdOrName: string, number: number, commentId: number, params: Option.PullRequest.PatchPullRequestCommentsParams): Promise; + getPullRequestAttachments(projectIdOrKey: string, repoIdOrName: string, number: number): Promise; + deletePullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; + getProjectIcon(projectIdOrKey: string): Promise; + getSharedFile(projectIdOrKey: string, sharedFileId: number): Promise; + getIssueAttachment(issueIdOrKey: string, attachmentId: number): Promise; + getWikiAttachment(wikiId: number, attachmentId: number): Promise; + getPullRequestAttachment(projectIdOrKey: string, repoIdOrName: string, number: number, attachmentId: number): Promise; + private download(path); + private upload(path, params); + private parseFileData(response); +} + +export class OAuth2 { + private credentials; + private timeout; + constructor(credentials: Option.OAuth2.Credentials, timeout?: number); + getAuthorizationURL(options: { + host: string; + redirectUri?: string; + state?: string; + }): string; + getAccessToken(options: { + host: string; + code: string; + redirectUri?: string; + }): Promise; + refreshAccessToken(options: { + host: string; + refreshToken: string; + }): Promise; +} + +import { PassThrough } from 'stream'; +export namespace Entity { + export namespace File { + export type FileData = NodeFileData | BrowserFileData; + export interface NodeFileData { + body: PassThrough; + url: string; + filename: string; + } + export interface BrowserFileData { + body: any; + url: string; + blob?: () => Promise; + } + } + export namespace OAuth2 { + export interface AccessToken { + access_token: string; + token_type: string; + expires_in: number; + refresh_token: string; + } + } +} + + +export namespace Option { + export type Order = "asc" | "desc"; + export enum ActivityType { + Undefined = -1, + IssueCreated = 1, + IssueUpdated = 2, + IssueCommented = 3, + IssueDeleted = 4, + WikiCreated = 5, + WikiUpdated = 6, + WikiDeleted = 7, + FileAdded = 8, + FileUpdated = 9, + FileDeleted = 10, + SvnCommitted = 11, + GitPushed = 12, + GitRepositoryCreated = 13, + IssueMultiUpdated = 14, + ProjectUserAdded = 15, + ProjectUserRemoved = 16, + NotifyAdded = 17, + PullRequestAdded = 18, + PullRequestUpdated = 19, + PullRequestCommented = 20, + PullRequestMerged = 21, + } + export namespace Notification { + export interface GetNotificationsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface GetNotificationsCountParams { + alreadyRead: boolean; + resourceAlreadyRead: boolean; + } + } + export namespace Space { + export interface GetActivitiesParams { + activityTypeId?: ActivityType[]; + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface PutSpaceNotificationParams { + content: string; + } + } + export namespace User { + export interface PostUserParams { + userId: string; + password: string; + name: string; + mailAddress: string; + roleType: RoleType; + } + export interface PatchUserParams { + password?: string; + name?: string; + mailAddress?: string; + roleType?: RoleType; + } + export enum RoleType { + Admin = 1, + User = 2, + Reporter = 3, + Viewer = 4, + GuestReporter = 5, + GuestViewer = 6, + } + export interface GetUserActivitiesParams { + activityTypeId?: ActivityType[]; + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface GetUserStarsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface GetUserStarsCountParams { + since?: string; + until?: string; + } + export interface GetRecentlyViewedParams { + order?: Order; + offset?: number; + count?: number; + } + } + export namespace Group { + export interface GetGroupsParams { + order?: Order; + offset?: number; + count?: number; + } + export interface PostGroupsParams { + name: string; + members?: string[]; + } + export interface PatchGroupParams { + name?: string; + members?: string[]; + } + } + export namespace Project { + export type TextFormattingRule = "backlog" | "markdown"; + export interface PostProjectParams { + name: string; + key: string; + chartEnabled: boolean; + projectLeaderCanEditProjectLeader?: boolean; + subtaskingEnabled: boolean; + textFormattingRule: TextFormattingRule; + } + export interface PatchProjectParams { + name?: string; + key?: string; + chartEnabled?: boolean; + subtaskingEnabled?: boolean; + projectLeaderCanEditProjectLeader?: boolean; + textFormattingRule?: TextFormattingRule; + archived?: boolean; + } + export interface GetProjectsParams { + archived?: boolean; + all?: boolean; + } + export interface DeleteProjectUsersParams { + userId: number; + } + export interface PostProjectAdministrators { + userId: number; + } + export interface DeleteProjectAdministrators { + userId: number; + } + export type IssueTypeColor = "#e30000" | "#990000" | "#934981" | "#814fbc" | "#2779ca" | "#007e9a" | "#7ea800" | "#ff9200" | "#ff3265" | "#666665"; + export interface PostIssueTypeParams { + name: string; + color: IssueTypeColor; + } + export interface PatchIssueTypeParams { + name?: string; + color?: IssueTypeColor; + } + export interface DeleteIssueTypeParams { + substituteIssueTypeId: number; + } + export interface PostCategoriesParams { + name: string; + } + export interface PatchCategoriesParams { + name: string; + } + export interface PostVersionsParams { + name: string; + description: string; + startDate: string; + releaseDueDate: string; + } + export interface PatchVersionsParams { + name: string; + description?: string; + startDate?: string; + releaseDueDate?: string; + archived?: boolean; + } + export interface PostCustomFieldParams { + typeId: FieldType; + name: string; + applicableIssueTypes?: number[]; + description?: string; + required?: boolean; + } + export interface PostCustomFieldWithNumericParams extends PostCustomFieldParams { + min?: number; + max?: number; + initialValue?: number; + unit?: string; + } + export interface PostCustomFieldWithDateParams extends PostCustomFieldParams { + min?: string; + max?: string; + initialValueType?: number; + initialDate?: string; + initialShift?: number; + } + export interface PostCustomFieldWithListParams extends PostCustomFieldParams { + items?: string[]; + allowInput?: boolean; + allowAddItem?: boolean; + } + export interface PatchCustomFieldParams { + name?: string; + applicableIssueTypes?: number[]; + description?: string; + required?: boolean; + } + export interface PatchCustomFieldWithNumericParams extends PatchCustomFieldParams { + min?: number; + max?: number; + initialValue?: number; + unit?: string; + } + export interface PatchCustomFieldWithDateParams extends PatchCustomFieldParams { + min?: string; + max?: string; + initialValueType?: number; + initialDate?: string; + initialShift?: number; + } + export interface PatchCustomFieldWithListParams extends PatchCustomFieldParams { + items?: string[]; + allowInput?: boolean; + allowAddItem?: boolean; + } + export interface PostCustomFieldItemParams { + name: string; + } + export interface PatchCustomFieldItemParams { + name: string; + } + export interface GetSharedFilesParams { + order?: Order; + offset?: number; + count?: number; + } + export interface PostWebhookParams { + name?: string; + description?: string; + hookUrl?: string; + allEvent?: boolean; + activityTypeIds?: number[]; + } + export interface PatchWebhookParams { + name?: string; + description?: string; + hookUrl?: string; + allEvent?: boolean; + activityTypeIds?: number[]; + } + export enum FieldType { + Text = 1, + TextArea = 2, + Numeric = 3, + Date = 4, + SingleList = 5, + MultipleList = 6, + CheckBox = 7, + Radio = 8, + } + export interface PostStarParams { + issueId?: number; + commentId?: number; + wikiId?: number; + pullRequestId?: number; + pullRequestCommentId?: number; + } + } + export namespace Issue { + export interface PostIssueParams { + projectId: number; + summary: string; + priorityId: number; + issueTypeId: number; + parentIssueId?: number; + description?: string; + startDate?: string; + dueDate?: string; + estimatedHours?: number; + actualHours?: number; + categoryId?: number[]; + versionId?: number[]; + milestoneId?: number[]; + assigneeId?: number; + notifiedUserId?: number[]; + attachmentId?: number[]; + [customField_: string]: any; + } + export interface PatchIssueParams { + summary?: string; + parentIssueId?: number; + description?: string; + statusId?: number; + resolutionId?: number; + startDate?: string; + dueDate?: string; + estimatedHours?: number; + actualHours?: number; + issueTypeId?: number; + categoryId?: number[]; + versionId?: number[]; + milestoneId?: number[]; + priorityId?: number; + assigneeId?: number; + notifiedUserId?: number[]; + attachmentId?: number[]; + comment?: string; + [customField_: string]: any; + } + export interface GetIssuesParams { + projectId?: number[]; + issueTypeId?: number[]; + categoryId?: number[]; + versionId?: number[]; + milestoneId?: number[]; + statusId?: number[]; + priorityId?: number[]; + assigneeId?: number[]; + createdUserId?: number[]; + resolutionId?: number[]; + parentChild?: ParentChildType; + attachment?: boolean; + sharedFile?: boolean; + sort?: SortKey; + order?: Order; + offset?: number; + count?: number; + createdSince?: string; + createdUntil?: string; + updatedSince?: string; + updatedUntil?: string; + startDateSince?: string; + startDateUntil?: string; + dueDateSince?: string; + dueDateUntil?: string; + id?: number[]; + parentIssueId?: number[]; + keyword: string; + [customField_: string]: any; + } + export enum ParentChildType { + All = 0, + NotChild = 1, + Child = 2, + NotChildNotParent = 3, + Parent = 4, + } + export type SortKey = "issueType" | "category" | "version" | "milestone" | "summary" | "status" | "priority" | "attachment" | "sharedFile" | "created" | "createdUser" | "updated" | "updatedUser" | "assignee" | "startDate" | "dueDate" | "estimatedHours" | "actualHours" | "childIssue"; + export interface GetIssueCommentsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface PostIssueCommentsParams { + content: string; + notifiedUserId?: number[]; + attachmentId?: number[]; + } + export interface PatchIssueCommentParams { + content: string; + } + export interface IssueCommentNotifications { + notifiedUserId: number[]; + } + export interface LinkIssueSharedFilesParams { + fileId: number[]; + } + } + export namespace PullRequest { + export interface GetPullRequestsParams { + statusId?: number[]; + assigneeId?: number[]; + issueId?: number[]; + createdUserId?: number[]; + offset?: number; + count?: number; + } + export interface PostPullRequestParams { + summary: string; + description: string; + base: string; + branch: string; + issueId?: number; + assigneeId?: number; + notifiedUserId?: number[]; + attachmentId?: number[]; + } + export interface PatchPullRequestParams { + summary?: string; + description?: string; + issueId?: number; + assigneeId?: number; + notifiedUserId?: number[]; + comment?: string[]; + } + export interface GetPullRequestCommentsParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + export interface PostPullRequestCommentsParams { + content: string; + notifiedUserId?: number[]; + } + export interface PatchPullRequestCommentsParams { + content: string; + } + } + export namespace Wiki { + export interface PostWikiParams { + projectId: number; + name: string; + content: string; + mailNotify?: boolean; + } + export interface PatchWikiParams { + name?: string; + content?: string; + mailNotify?: boolean; + } + export interface GetWikisHistoryParams { + minId?: number; + maxId?: number; + count?: number; + order?: Order; + } + } + export namespace OAuth2 { + export interface Credentials { + clientId: string; + clientSecret: string; + } + } +} + +export namespace Error { + export class BacklogError extends global.Error { + private _name; + private _url; + private _status; + private _body; + private _response; + constructor(name: BacklogErrorNameType, response: IResponse, body?: { + errors: BacklogErrorMessage[]; + }); + name: BacklogErrorNameType; + url: string; + status: number; + body: { + errors: BacklogErrorMessage[]; + }; + response: IResponse; + } + export class BacklogApiError extends BacklogError { + constructor(response: IResponse, body?: { + errors: BacklogErrorMessage[]; + }); + } + export class BacklogAuthError extends BacklogError { + constructor(response: IResponse, body?: { + errors: BacklogErrorMessage[]; + }); + } + export class UnexpectedError extends BacklogError { + constructor(response: IResponse); + } + export interface BacklogErrorMessage { + message: string; + code: number; + errorInfo: string; + moreInfo: string; + } + export type BacklogErrorNameType = 'BacklogApiError' | 'BacklogAuthError' | 'UnexpectedError'; +} diff --git a/backlog-js/tsconfig.json b/backlog-js/tsconfig.json new file mode 100644 index 0000000000..cd1d4da21f --- /dev/null +++ b/backlog-js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "backlog-js-tests.ts" + ] +} \ No newline at end of file diff --git a/bootstrap-fileinput/bootstrap-fileinput.d.ts b/bootstrap-fileinput/bootstrap-fileinput.d.ts index fadfadd612..139ca2c490 100644 --- a/bootstrap-fileinput/bootstrap-fileinput.d.ts +++ b/bootstrap-fileinput/bootstrap-fileinput.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ché Coxshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface JQuery { fileinput: (options?: BootstrapFileInput.FileInputOptions) => JQuery; diff --git a/bootstrap-fileinput/tsconfig.json b/bootstrap-fileinput/tsconfig.json new file mode 100644 index 0000000000..5b7c6fc2bf --- /dev/null +++ b/bootstrap-fileinput/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "bootstrap-fileinput.d.ts" + ] +} \ No newline at end of file diff --git a/browserify/index.d.ts b/browserify/index.d.ts index 506bc3dd86..8554025402 100644 --- a/browserify/index.d.ts +++ b/browserify/index.d.ts @@ -5,9 +5,10 @@ /// -declare var browserify: BrowserifyConstructor; +declare var browserify: browserify.BrowserifyConstructor; export = browserify; +declare namespace browserify { /** * Options pertaining to an individual file. */ @@ -173,3 +174,4 @@ interface BrowserifyObject extends NodeJS.EventEmitter { */ pipeline: any; } +} diff --git a/chai-dom/chai-dom.d.ts b/chai-dom/chai-dom.d.ts index 64cf97f516..4338de92e2 100644 --- a/chai-dom/chai-dom.d.ts +++ b/chai-dom/chai-dom.d.ts @@ -3,7 +3,7 @@ // Definitions by: Matt Lewis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Chai { @@ -24,13 +24,13 @@ declare namespace Chai { value(text: string): Assertion; } - + interface Include { - + text(text: string|string[]): Assertion; - + html(text: string|string[]): Assertion; - + } } diff --git a/chai-dom/tsconfig.json b/chai-dom/tsconfig.json new file mode 100644 index 0000000000..79855c3e09 --- /dev/null +++ b/chai-dom/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "chai-dom.d.ts", + "chai-dom-tests.ts" + ] +} \ No newline at end of file diff --git a/chai-enzyme/chai-enzyme-tests.tsx b/chai-enzyme/chai-enzyme-tests.tsx index f85320cee0..0e491a7ba7 100644 --- a/chai-enzyme/chai-enzyme-tests.tsx +++ b/chai-enzyme/chai-enzyme-tests.tsx @@ -1,7 +1,7 @@ -/// +/// /// -/// -/// +/// +/// import * as React from "react"; import * as chaiEnzyme from "chai-enzyme"; diff --git a/chai-enzyme/chai-enzyme.d.ts b/chai-enzyme/chai-enzyme.d.ts index 21e463dac5..72842332ad 100644 --- a/chai-enzyme/chai-enzyme.d.ts +++ b/chai-enzyme/chai-enzyme.d.ts @@ -4,12 +4,12 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// +/// +/// +/// declare namespace Chai { - type EnzymeSelector = string | __React.StatelessComponent | __React.ComponentClass | { [key: string]: any }; + type EnzymeSelector = string | React.StatelessComponent | React.ComponentClass | { [key: string]: any }; interface Match { /** diff --git a/chai-enzyme/tsconfig.json b/chai-enzyme/tsconfig.json new file mode 100644 index 0000000000..81fa4a5105 --- /dev/null +++ b/chai-enzyme/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "chai-enzyme.d.ts", + "chai-enzyme-tests.tsx" + ] +} \ No newline at end of file diff --git a/commangular/commangular.d.ts b/commangular/commangular.d.ts index b03a22574e..06126ac64f 100644 --- a/commangular/commangular.d.ts +++ b/commangular/commangular.d.ts @@ -3,12 +3,12 @@ // Definitions by: Hiraash Thawfeek // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare var commangular: commangular.ICommAngularStatic; declare module commangular { - + /////////////////////////////////////////////////////////////////////////// // Commangular Static // see http://commangular.org/docs/#commangular-namespace @@ -19,78 +19,78 @@ declare module commangular { * Use this function to create and register a command with Commangular * * @param commandName It's the name of the command you are creating. It's useful to reference the command from the command provider. - * @param commandFunction It's the command class that will be executed when commangular runs this command. + * @param commandFunction It's the command class that will be executed when commangular runs this command. * It has to be something that implements ICommand. Same as angular syntax * @param commandConfig It's and object with paramaters to configure the command execution. */ create (commandName: string, commandFunction: Function, commandConfig?:ICommandConfig) : void; command (commandName: string, commandFunction: Function, commandConfig?:ICommandConfig) : void; - + /** * This function allows you to hijack the execution before or after and * execute some cross cutting functionality. * see http://commangular.org/docs/#command-aspects * @param aspectDescriptor The interceptor descriptor has two parts 'Where' and 'What'. * Where do you want to intercept? you've 5 options : - * - @Before : The interceptor will be executed before the command. You will be able to - * cancel the command or modify the data that will be injected in the command or do + * - @Before : The interceptor will be executed before the command. You will be able to + * cancel the command or modify the data that will be injected in the command or do * some other operation you need before the command execution. - * - @After : The interceptor will be executed just after the command and before any other next + * - @After : The interceptor will be executed just after the command and before any other next * command. You can get the lastResult from the command, cancel execution etc etc. - * - @AfterExecution : This intercetor is executed just after the command execute method and + * - @AfterExecution : This intercetor is executed just after the command execute method and * it can get the result from the command and update it before the onResult method is executed. - * - @AfterThrowing : This interceptor will be executed if the command or any interceptor of + * - @AfterThrowing : This interceptor will be executed if the command or any interceptor of * the command throws an exception. You can get the error throwed injected to do what you need. - * - @Around : The interceptor is executed around a command.That means that a especial - * object 'processor' will be injected in the interceptor and you can invoke the command + * - @Around : The interceptor is executed around a command.That means that a especial + * object 'processor' will be injected in the interceptor and you can invoke the command * or the next interceptor. It will be better explained below. * @param aspectFunction It's the command class execute function that will be run for the given aspect. - * @param order You can chain any number of interceptors to the same command, so if you need to executed + * @param order You can chain any number of interceptors to the same command, so if you need to executed * the interceptor in a specific order you can indicate it here. An order of 0 is assigned by default. */ aspect ( aspectDescriptor: string, aspectFunction: ICommand, order: number ) : void; - + /** - * Event aspects work the same way command aspects do, but they intercept all the command groups instead, - * so you can run some function before the command group starts it's execution , after or when any + * Event aspects work the same way command aspects do, but they intercept all the command groups instead, + * so you can run some function before the command group starts it's execution , after or when any * command or interceptor in the group throw an exception. * see http://commangular.org/docs/#event-aspects * @param aspectDescriptor The interceptor descriptor has two parts 'Where' and 'What'. * Where do you want to intercept? you've 3 options : - * - @Before : The interceptor will be executed before the command. You will be able to - * cancel the command or modify the data that will be injected in the command or do + * - @Before : The interceptor will be executed before the command. You will be able to + * cancel the command or modify the data that will be injected in the command or do * some other operation you need before the command execution. - * - @After : The interceptor will be executed just after the command and before any other next + * - @After : The interceptor will be executed just after the command and before any other next * command. You can get the lastResult from the command, cancel execution etc etc. - * - @AfterThrowing : This interceptor will be executed if the command or any interceptor of + * - @AfterThrowing : This interceptor will be executed if the command or any interceptor of * the command throws an exception. You can get the error throwed injected to do what you need. * @param aspectFunction It's the command class execute function that will be run for the given aspect. - * @param order You can chain any number of interceptors to the same command, so if you need to executed + * @param order You can chain any number of interceptors to the same command, so if you need to executed * the interceptor in a specific order you can indicate it here. An order of 0 is assigned by default. */ eventAspect( aspectDescriptor: string, aspectFunction: ICommand, order: number ) : void; - + /** * TBD */ - resolver( commandName: string, resolverFunction : Function ) : void; - + resolver( commandName: string, resolverFunction : Function ) : void; + /** * Clears all commands and aspects registered with commangular. */ reset() : void; - + /** - * Can be used to enable/disable debug + * Can be used to enable/disable debug */ debug( enableDebug : boolean ) : void; - + /** * TBD */ build() : void; } - + /** * The command function/object * see http://commangular.org/docs/#commangular-namespace @@ -101,29 +101,29 @@ declare module commangular { * It can take parameters in as injected by angular */ execute() : any; - + } - + interface IResultCommand extends ICommand{ /** - * Is executed after the execute method and the interception chain and can receive + * Is executed after the execute method and the interception chain and can receive * the result from the execute method of the same command. - * + * * @param result Value/object returned by the execution. */ onResult ( result: any ) : void; - + /** * Is executed when the executed method ends with an error. Can receive the error throw by the execute method. * @param error The error that occured during execution */ onError ( error: Error ) : void; } - + /** * The result object expected in the promise returned by the dispatch function * This must be extended to add custom result keys - * see http://commangular.org/docs/#returning-result-from-commands + * see http://commangular.org/docs/#returning-result-from-commands */ interface ICommandResult { /** @@ -131,65 +131,65 @@ declare module commangular { */ lastResult : any; } - + /** * Command creation configuration * see http://commangular.org/docs/#the-command-config-object */ interface ICommandConfig { /** - * This property instruct commangular to keep the value returned by the command in the value - * key passed in 'resultKey'. It has to be a string. It means that after the execution of this + * This property instruct commangular to keep the value returned by the command in the value + * key passed in 'resultKey'. It has to be a string. It means that after the execution of this * commands you will be able to inject on the next command using that key and the result of the command will be injected. */ resultKey : string; } - + /** - * All the command configuration of your application is done in an angular config block and - * with the $commangularProvider. The provider is responsible to build the command strutures and - * map them to the desired event names. You can create multiple configs blocks in angular, so you + * All the command configuration of your application is done in an angular config block and + * with the $commangularProvider. The provider is responsible to build the command strutures and + * map them to the desired event names. You can create multiple configs blocks in angular, so you * can have multiple command config blocks to separate functional parts of your application. * see http://commangular.org/docs/#using-the-provider */ interface ICommAngularProvider { - + /** * This function lets you map a even name to a command sequence * @param eventName An event that will be watched by commangular */ mapTo( eventName: string ) : ICommAngularDescriptor; - + /** - * Used along with mapTo function. Creates a sequence of commands that + * Used along with mapTo function. Creates a sequence of commands that * execute after one and other * see http://commangular.org/docs/#building-command-sequences */ asSequence(): ICommAngularDescriptor; - + /** * Used along with mapTo function. Maps commands to be executed parallel * see http://commangular.org/docs/#building-parallel-commands */ asParallel(): ICommAngularDescriptor; - + /** - * A command flow is a decision point inside the command group.You can have any number + * A command flow is a decision point inside the command group.You can have any number * of flows inside a command group and nesting them how you perfer. * see http://commangular.org/docs/#building-command-flows */ - asFlow(): ICommAngularDescriptor; - + asFlow(): ICommAngularDescriptor; + findCommand( eventName: string ): ICommAngularDescriptor; - + } - + /** * The service that enables the execution of commands * see http://commangular.org/docs/#dispatching-events */ interface ICommAngularService { - + /** * This function executes the given command sequence. * see http://commangular.org/docs/#dispatching-events @@ -198,76 +198,76 @@ declare module commangular { */ dispatch( eventName: string, data?: any ) : ng.IPromise; } - + interface ICommAngularDescriptor { - + /** - * Used along with mapTo function. Creates a sequence of commands that + * Used along with mapTo function. Creates a sequence of commands that * execute after one and other * see http://commangular.org/docs/#building-command-sequences */ - asSequence (): ICommAngularDescriptor; + asSequence (): ICommAngularDescriptor; /** * Used along with mapTo function. Maps commands to be executed parallel * see http://commangular.org/docs/#building-parallel-commands */ asParallel(): ICommAngularDescriptor; - + /** - * A command flow is a decision point inside the command group.You can have any number + * A command flow is a decision point inside the command group.You can have any number * of flows inside a command group and nesting them how you perfer. * see http://commangular.org/docs/#building-command-flows */ - asFlow(): ICommAngularDescriptor; - + asFlow(): ICommAngularDescriptor; + /** * Add commands to a descriptor. * @param command The name that was used to create the command. */ add ( command: string ): ICommAngularDescriptor; - + /** * Add descriptor to a descriptor. * @param descriptor Another descriptor attached to a sequnce of commands. */ add ( descriptor: ICommAngularDescriptor ): ICommAngularDescriptor; - + /** - * This is to be used with flowing commands to attach an expression that + * This is to be used with flowing commands to attach an expression that * evaluates using Angular $parse. * see http://commangular.org/docs/#building-command-flows * @param expression A string form expression that can make use of services to validate conditions. * @param services A comma seperated list of services that are used in the above expression */ link ( expression: string, services?: string ): ICommAngularDescriptor; - + /** - * Works with the link function to attach a command to the flow if the - * expression becomes truthy. + * Works with the link function to attach a command to the flow if the + * expression becomes truthy. * see http://commangular.org/docs/#building-command-flows * @param command The name that was used to create the command. */ - to ( command: string ): ICommAngularDescriptor; + to ( command: string ): ICommAngularDescriptor; } - + } /** * Extending the angular rootScope to include the dispatch function in all scopes. */ declare module angular { - + interface IRootScopeService { - + /** * Commangular method to execute a command. * @param eventName Name of the even that will trigger a command sequence * @param data Data of any type that will be passed to the command. */ dispatch( eventName: string, data?: any ) : ng.IPromise; - + } - + } \ No newline at end of file diff --git a/commangular/tsconfig.json b/commangular/tsconfig.json new file mode 100644 index 0000000000..e52f7e1a12 --- /dev/null +++ b/commangular/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "commangular.d.ts", + "commangular-mock.d.ts" + ] +} \ No newline at end of file diff --git a/connect-redis/connect-redis-tests.ts b/connect-redis/connect-redis-tests.ts index abc14977ee..73e0e4d8f7 100644 --- a/connect-redis/connect-redis-tests.ts +++ b/connect-redis/connect-redis-tests.ts @@ -1,5 +1,5 @@ /// -/// +/// import * as connectRedis from "connect-redis"; import * as session from "express-session"; diff --git a/connect-redis/connect-redis.d.ts b/connect-redis/connect-redis.d.ts index b3a1529569..f66314a083 100644 --- a/connect-redis/connect-redis.d.ts +++ b/connect-redis/connect-redis.d.ts @@ -3,9 +3,9 @@ // Definitions by: Xavier Stouder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// +/// +/// +/// declare module "connect-redis" { import * as express from "express"; diff --git a/connect-redis/tsconfig.json b/connect-redis/tsconfig.json new file mode 100644 index 0000000000..441b3c70c6 --- /dev/null +++ b/connect-redis/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "connect-redis.d.ts", + "connect-redis-tests.ts" + ] +} diff --git a/cordova-plugin-file-transfer/index.d.ts b/cordova-plugin-file-transfer/index.d.ts index 4644dddd42..ad8d9945f5 100644 --- a/cordova-plugin-file-transfer/index.d.ts +++ b/cordova-plugin-file-transfer/index.d.ts @@ -2,11 +2,11 @@ // Project: https://github.com/apache/cordova-plugin-file-transfer // Definitions by: Microsoft Open Technologies Inc. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// // Copyright (c) Microsoft Open Technologies Inc // Licensed under the MIT license -/// +/// /** * The FileTransfer object provides a way to upload files using an HTTP multi-part POST request, @@ -21,7 +21,7 @@ interface FileTransfer { * this can also be the full path of the file on the device. * @param server URL of the server to receive the file, as encoded by encodeURI(). * @param successCallback A callback that is passed a FileUploadResult object. - * @param errorCallback A callback that executes if an error occurs retrieving the FileUploadResult. + * @param errorCallback A callback that executes if an error occurs retrieving the FileUploadResult. * Invoked with a FileTransferError object. * @param options Optional parameters. * @param trustAllHosts Optional parameter, defaults to false. If set to true, it accepts all security certificates. diff --git a/cordova-plugin-file-transfer/tsconfig.json b/cordova-plugin-file-transfer/tsconfig.json index 0e88ebb590..a4d326b967 100644 --- a/cordova-plugin-file-transfer/tsconfig.json +++ b/cordova-plugin-file-transfer/tsconfig.json @@ -2,9 +2,15 @@ "compilerOptions": { "module": "commonjs", "target": "es6", - "noImplicitAny": false, + "noImplicitAny": true, "strictNullChecks": false, - "noEmit": true + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", diff --git a/csv-parse/csv-parse.d.ts b/csv-parse/csv-parse.d.ts index 74184ca680..eb60d18fde 100644 --- a/csv-parse/csv-parse.d.ts +++ b/csv-parse/csv-parse.d.ts @@ -3,44 +3,44 @@ // Definitions by: David Muller // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "csv-parse/types" { interface callbackFn { (err: any, output: any): void } - + interface nameCallback { (line1: any[]): boolean | string[] - } - + } + interface options { /*** - * Set the field delimiter. One character only, defaults to comma. + * Set the field delimiter. One character only, defaults to comma. */ delimiter?: string; /*** * String used to delimit record rows or a special value; special constants are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified). - */ + */ rowDelimiter?: string; /*** - * Optional character surrounding a field, one character only, defaults to double quotes. + * Optional character surrounding a field, one character only, defaults to double quotes. */ quote?: string - + /*** - * Set the escape character, one character only, defaults to double quotes. - */ + * Set the escape character, one character only, defaults to double quotes. + */ escape?: string /*** - * List of fields as an array, a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, default to null, affect the result data set in the sense that records will be objects instead of arrays. + * List of fields as an array, a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, default to null, affect the result data set in the sense that records will be objects instead of arrays. */ columns?: any[]|boolean|nameCallback; /*** - * Treat all the characters after this one as a comment, default to '' (disabled). + * Treat all the characters after this one as a comment, default to '' (disabled). */ comment?: string @@ -88,24 +88,24 @@ declare module "csv-parse/types" { * If true, the parser will attempt to convert read data types to native types. */ auto_parse?: boolean - + /*** * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. */ auto_parse_date?: boolean } - - import * as stream from "stream"; - + + import * as stream from "stream"; + interface Parser extends stream.Transform { __push(line: any): any ; - __write(chars: any, end: any, callback: any): any; + __write(chars: any, end: any, callback: any): any; } - + interface ParserConstructor { new (options: options): Parser; } - + interface parse { (input: string, options?: options, callback?: callbackFn): any; (options: options, callback: callbackFn): any; @@ -117,16 +117,16 @@ declare module "csv-parse/types" { declare module "csv-parse" { import { parse as parseIntf } from "csv-parse/types"; - + let parse: parseIntf; - + export = parse; } declare module "csv-parse/lib/sync" { - import { options } from "csv-parse/types"; - + import { options } from "csv-parse/types"; + function parse (input: string, options?: options): any; - + export = parse; } \ No newline at end of file diff --git a/csv-parse/tsconfig.json b/csv-parse/tsconfig.json new file mode 100644 index 0000000000..9e359a8737 --- /dev/null +++ b/csv-parse/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "csv-parse.d.ts", + "csv-parse-tests.ts" + ] +} \ No newline at end of file diff --git a/d3kit/d3kit-tests.ts b/d3kit/d3kit-tests.ts index 1b8d2a24f9..5eab2a4e79 100644 --- a/d3kit/d3kit-tests.ts +++ b/d3kit/d3kit-tests.ts @@ -1,7 +1,7 @@ /// -/// -/// -/// +/// +/// +/// /* jshint expr: true */ diff --git a/d3kit/d3kit.d.ts b/d3kit/d3kit.d.ts index 4e53472b7b..d5033d32df 100644 --- a/d3kit/d3kit.d.ts +++ b/d3kit/d3kit.d.ts @@ -3,7 +3,7 @@ // Definitions by: Morgan Benton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace d3kit { @@ -29,7 +29,7 @@ declare namespace d3kit { export class Skeleton { constructor(selector: string|Element, options?: ChartOptions, customEvents?: Array); - + // Getters getCustomEventNames(): Array; getDispatcher(): any; // should be d3.Dispatch but this throws error for user-created events @@ -78,9 +78,9 @@ declare namespace d3kit { export class Chartlet { constructor( - enterFunction?: ChartletEventFunction, - updateFunction?: ChartletEventFunction, - exitFunction?: ChartletEventFunction, + enterFunction?: ChartletEventFunction, + updateFunction?: ChartletEventFunction, + exitFunction?: ChartletEventFunction, customEventName?: Array); // Getter functions @@ -116,15 +116,15 @@ declare namespace d3kit { constructor(container: d3.Selection, tag?: string); - create(config: string|Array|LayerConfig|Array): d3.Selection|Array>; + create(config: string|Array|LayerConfig|Array|any): d3.Selection|Array>; get(name: string): d3.Selection; has(name: string): boolean; } export namespace factory { export function createChart( - defaultOptions: ChartOptions, - customEvents: Array, + defaultOptions: ChartOptions, + customEvents: Array, constructor: (skeleton: Skeleton) => void ): (selector: string|Element, options?: ChartOptions, customEvents?: Array) => Skeleton; } diff --git a/d3kit/tsconfig.json b/d3kit/tsconfig.json new file mode 100644 index 0000000000..67ab2f9e8c --- /dev/null +++ b/d3kit/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "d3kit.d.ts", + "d3kit-tests.ts" + ] +} \ No newline at end of file diff --git a/daterangepicker/daterangepicker-tests.ts b/daterangepicker/daterangepicker-tests.ts index ca1f99961c..0b8051b06a 100644 --- a/daterangepicker/daterangepicker-tests.ts +++ b/daterangepicker/daterangepicker-tests.ts @@ -1,4 +1,5 @@ /// +import moment = require("moment") function tests_simple() { $('#daterange').daterangepicker(); diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts index a86614cfe8..88cce7c0a2 100644 --- a/daterangepicker/daterangepicker.d.ts +++ b/daterangepicker/daterangepicker.d.ts @@ -3,12 +3,14 @@ // Definitions by: SirMartin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +import moment = require("moment"); -interface JQuery { - daterangepicker(settings?: daterangepicker.Settings): JQuery; - daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; +declare global { + interface JQuery { + daterangepicker(settings?: daterangepicker.Settings): JQuery; + daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery; + } } declare namespace daterangepicker { diff --git a/daterangepicker/package.json b/daterangepicker/package.json new file mode 100644 index 0000000000..992b24d513 --- /dev/null +++ b/daterangepicker/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "moment": "2.14.*" + } +} \ No newline at end of file diff --git a/daterangepicker/tsconfig.json b/daterangepicker/tsconfig.json new file mode 100644 index 0000000000..cbf48c5f61 --- /dev/null +++ b/daterangepicker/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "daterangepicker.d.ts", + "daterangepicker-tests.ts" + ] +} \ No newline at end of file diff --git a/df-visible/df-visible.d.ts b/df-visible/df-visible.d.ts index b8d05fe360..f7303a46ae 100644 --- a/df-visible/df-visible.d.ts +++ b/df-visible/df-visible.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andrey Lipatkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// type Direction = "horizontal" | "vertical" | "both"; diff --git a/df-visible/tsconfig.json b/df-visible/tsconfig.json new file mode 100644 index 0000000000..49c372fd65 --- /dev/null +++ b/df-visible/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "df-visible.d.ts", + "df-visible-tests.ts" + ] +} \ No newline at end of file diff --git a/dva/dva-tests.tsx b/dva/dva-tests.tsx index 917ee69e60..467be594ab 100644 --- a/dva/dva-tests.tsx +++ b/dva/dva-tests.tsx @@ -1,11 +1,7 @@ -/// -/// - -import React = __React; - import dva from 'dva'; import { connect } from 'dva'; import { Router, Route } from 'dva/router'; +import * as React from "react"; // 1. Initialize const app = dva(); @@ -25,9 +21,9 @@ app.model({ }); // 3. View -const App = connect(({ count }) => ({ +const App = connect(({ count }: any) => ({ count -}))(function ({ count, dispatch }) { +}))(function ({ count, dispatch }: any) { return (

    { count }

    @@ -38,7 +34,7 @@ const App = connect(({ count }) => ({ }); // 4. Router -app.router(({ history }) => +app.router(({ history }: any) => diff --git a/dva/dva.d.ts b/dva/dva.d.ts index 0cf7206e63..7f7651c2f4 100644 --- a/dva/dva.d.ts +++ b/dva/dva.d.ts @@ -3,7 +3,7 @@ // Definitions by: nikogu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'dva' { /** connecting Container Components */ export function connect(maps:Object):Function; @@ -28,8 +28,6 @@ declare module 'dva' { * https://github.com/reactjs/react-router */ declare module 'dva/router' { - import React = __React; - interface RouterProps { history?: Object } diff --git a/dva/tsconfig.json b/dva/tsconfig.json new file mode 100644 index 0000000000..8c73ec457e --- /dev/null +++ b/dva/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "dva.d.ts", + "dva-tests.tsx" + ] +} \ No newline at end of file diff --git a/electron/index.d.ts b/electron/index.d.ts index 7d10fce465..cac4bab9b2 100644 --- a/electron/index.d.ts +++ b/electron/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Electron { diff --git a/epub/epub.d.ts b/epub/epub.d.ts index 7c813e003d..fe4f36ce87 100644 --- a/epub/epub.d.ts +++ b/epub/epub.d.ts @@ -3,7 +3,7 @@ // Definitions by: Julien Chaumond // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /** * new EPub(fname[, imageroot][, linkroot]) @@ -31,9 +31,9 @@ * /images/logo_img/OPT/logo.jpg **/ declare module "epub" { - + import {EventEmitter} from "events"; - + interface TocElement { level: number; order: number; @@ -41,26 +41,26 @@ declare module "epub" { id: string; href?: string; } - + class EPub extends EventEmitter { constructor(epubfile: string, imagewebroot?: string, chapterwebroot?: string); - + metadata: Object; manifest: Object; spine: Object; flow: Array; toc: Array; - + parse(): void; - + getChapter(chapterId: string, callback: (error: Error, text: string) => void): void; - + getChapterRaw(chapterId: string, callback: (error: Error, text: string) => void): void; - + getImage(id: string, callback: (error: Error, data: Buffer, mimeType: string) => void): void; - + getFile(id: string, callback: (error: Error, data: Buffer, mimeType: string) => void): void; } - + export = EPub; } diff --git a/epub/tsconfig.json b/epub/tsconfig.json new file mode 100644 index 0000000000..eda2b3868b --- /dev/null +++ b/epub/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "epub.d.ts", + "epub-tests.ts" + ] +} \ No newline at end of file diff --git a/eq.js/index.d.ts b/eq.js/index.d.ts index 5876649f3e..4f48c092d5 100644 --- a/eq.js/index.d.ts +++ b/eq.js/index.d.ts @@ -11,7 +11,7 @@ declare module 'eq.js' { } declare namespace eq { - type AvailableElementType = HTMLElement|HTMLElement[]|NodeList|JQuery; + type AvailableElementType = HTMLElement|HTMLCollectionOf|HTMLElement[]|NodeList|JQuery; interface EqjsStatic { diff --git a/eq.js/tsconfig.json b/eq.js/tsconfig.json index 79b9eb6b27..60aa90fe0c 100644 --- a/eq.js/tsconfig.json +++ b/eq.js/tsconfig.json @@ -13,6 +13,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "eq.js.tests.ts" ] } \ No newline at end of file diff --git a/esprima-walk/esprima-walk-tests.ts b/esprima-walk/esprima-walk-tests.ts index 4588ebb615..31ec3b91e0 100644 --- a/esprima-walk/esprima-walk-tests.ts +++ b/esprima-walk/esprima-walk-tests.ts @@ -1,7 +1,5 @@ -/// -/// - -import * as walk from 'esprima-walk' +import * as ESTree from "estree"; +import walk = require("esprima-walk"); var program: ESTree.Program var string: string diff --git a/esprima-walk/esprima-walk.d.ts b/esprima-walk/esprima-walk.d.ts deleted file mode 100644 index d18cf96bb1..0000000000 --- a/esprima-walk/esprima-walk.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -// Type definitions for esprima-walk v0.1.0 -// Project: https://github.com/jrajav/esprima-walk -// Definitions by: tswaters -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module "esprima-walk" { - - interface NodeWithParent extends ESTree.Node { - parent?: ESTree.Node - } - - /** - * Walk the provided AST; fn is called once for each node with a `type` - * @param {ESTree.Program} ast program to walk - * @param {function} fn function invoked for each node with type - */ - function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void - - namespace walk { - /** - * Walk the provided AST; fn is called once for each node with a `type` - * @param {ESTree.Program} ast program to walk - * @param {function} fn function invoked for each node - */ - export function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void - - /** - * Walk the provided AST; fn is called once for each node with a `type`. - * Adds a parent property prior to invoking fn when applicable - * @param {ESTree.Program} ast program to walk - * @param {function} fn function invoked for each node - */ - export function walkAddParent (ast: ESTree.Program, fn:(node: NodeWithParent)=>void) :void - } - - export = walk -} - diff --git a/esprima-walk/index.d.ts b/esprima-walk/index.d.ts new file mode 100644 index 0000000000..c79675df6d --- /dev/null +++ b/esprima-walk/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for esprima-walk v0.1.0 +// Project: https://github.com/jrajav/esprima-walk +// Definitions by: tswaters +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as ESTree from "estree"; + +type NodeWithParent = ESTree.Node & { parent?: ESTree.Node }; + +/** + * Walk the provided AST; fn is called once for each node with a `type` + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node with type + */ +declare function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void + +declare namespace walk { + /** + * Walk the provided AST; fn is called once for each node with a `type` + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node + */ + export function walk (ast: ESTree.Program, fn:(node: ESTree.Node)=>void) :void + + /** + * Walk the provided AST; fn is called once for each node with a `type`. + * Adds a parent property prior to invoking fn when applicable + * @param {ESTree.Program} ast program to walk + * @param {function} fn function invoked for each node + */ + export function walkAddParent (ast: ESTree.Program, fn:(node: NodeWithParent)=>void) :void +} + +export = walk diff --git a/esprima-walk/tsconfig.json b/esprima-walk/tsconfig.json new file mode 100644 index 0000000000..53ed459f2d --- /dev/null +++ b/esprima-walk/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "esprima-walk-tests.ts" + ] +} \ No newline at end of file diff --git a/exorcist/exorcist.d.ts b/exorcist/exorcist.d.ts index a60908915b..93c11cd23d 100644 --- a/exorcist/exorcist.d.ts +++ b/exorcist/exorcist.d.ts @@ -3,7 +3,7 @@ // Definitions by: TeamworkGuy2 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'exorcist' { import through = require("through"); diff --git a/exorcist/tsconfig.json b/exorcist/tsconfig.json new file mode 100644 index 0000000000..e0ca3628a8 --- /dev/null +++ b/exorcist/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "exorcist.d.ts", + "exorcist-tests.ts" + ] +} \ No newline at end of file diff --git a/express-domain-middleware/express-domain-middleware.d.ts b/express-domain-middleware/express-domain-middleware.d.ts index 1710d548e0..935f315dd4 100644 --- a/express-domain-middleware/express-domain-middleware.d.ts +++ b/express-domain-middleware/express-domain-middleware.d.ts @@ -3,7 +3,7 @@ // Definitions by: Hookclaw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "express-domain-middleware" { import express = require('express'); diff --git a/express-domain-middleware/tsconfig.json b/express-domain-middleware/tsconfig.json new file mode 100644 index 0000000000..456e26404a --- /dev/null +++ b/express-domain-middleware/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "express-domain-middleware.d.ts", + "express-domain-middleware-tests.ts" + ] +} \ No newline at end of file diff --git a/file-type/file-type-tests.ts b/file-type/file-type-tests.ts index ebbee83783..1ce0bf6bdf 100644 --- a/file-type/file-type-tests.ts +++ b/file-type/file-type-tests.ts @@ -1,5 +1,3 @@ -/// - "use strict"; import fileType = require("file-type") diff --git a/file-type/file-type.d.ts b/file-type/index.d.ts similarity index 51% rename from file-type/file-type.d.ts rename to file-type/index.d.ts index 58c449ca3c..a1bc0d8466 100644 --- a/file-type/file-type.d.ts +++ b/file-type/index.d.ts @@ -3,15 +3,13 @@ // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk // Definitions: https://github.com/DefinitelyType/DefinitelyTyped -/// +/// -declare module "file-type" { - interface FileTypeResult { - ext: string - mime: string - } - - function FileType(buf: Buffer): FileTypeResult - - export = FileType +interface FileTypeResult { + ext: string + mime: string } + +declare function FileType(buf: Buffer): FileTypeResult + +export = FileType diff --git a/file-type/tsconfig.json b/file-type/tsconfig.json new file mode 100644 index 0000000000..52468981c7 --- /dev/null +++ b/file-type/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "file-type-tests.ts" + ] +} \ No newline at end of file diff --git a/fill-pdf/fill-pdf.d.ts b/fill-pdf/fill-pdf.d.ts index d35057f934..94adba6e75 100644 --- a/fill-pdf/fill-pdf.d.ts +++ b/fill-pdf/fill-pdf.d.ts @@ -3,7 +3,7 @@ // Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'fill-pdf' { diff --git a/fill-pdf/tsconfig.json b/fill-pdf/tsconfig.json new file mode 100644 index 0000000000..51c99ab9de --- /dev/null +++ b/fill-pdf/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "fill-pdf.d.ts", + "fill-pdf-tests.ts" + ] +} \ No newline at end of file diff --git a/fluent-ffmpeg/fluent-ffmpeg.d.ts b/fluent-ffmpeg/fluent-ffmpeg.d.ts index 92e1a33891..538ac71761 100644 --- a/fluent-ffmpeg/fluent-ffmpeg.d.ts +++ b/fluent-ffmpeg/fluent-ffmpeg.d.ts @@ -3,7 +3,7 @@ // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk // Definitions: https://github.com/DefinitelyType/DefinitelyTyped -/// +/// declare module "fluent-ffmpeg" { import * as events from "events" diff --git a/fluent-ffmpeg/tsconfig.json b/fluent-ffmpeg/tsconfig.json new file mode 100644 index 0000000000..3e2fd3a624 --- /dev/null +++ b/fluent-ffmpeg/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "fluent-ffmpeg.d.ts", + "fluent-ffmpeg-tests.ts" + ] +} \ No newline at end of file diff --git a/fullpage.js/fullpage.js.d.ts b/fullpage.js/fullpage.js.d.ts index b2bedc62d9..7716a3bca8 100644 --- a/fullpage.js/fullpage.js.d.ts +++ b/fullpage.js/fullpage.js.d.ts @@ -3,215 +3,215 @@ // Definitions by: Andrew Roberts // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface FullPageJsOptions { /** * (default false) A selector can be used to specify the menu to link with the sections. This way the scrolling of the sections will activate the corresponding element in the menu using the class active. This won't generate a menu but will just add the active class to the element in the given menu with the corresponding anchor links. In order to link the elements of the menu with the sections, an HTML 5 data-tag (data-menuanchor) will be needed to use with the same anchor links as used within the sections. */ menu?: string; - + /** * (default false). Determines whether anchors in the URL will have any effect at all in the plugin. You can still using anchors internally for your own functions and callbacks, but they won't have any effect in the scrolling of the site. Useful if you want to combine fullPage.js with other plugins using anchor in the URL. */ lockAnchors?: boolean; - + /** * (default []) Defines the anchor links (#example) to be shown on the URL for each section. Anchors value should be unique. The position of the anchors in the array will define to which sections the anchor is applied. (second position for second section and so on). Using anchors forward and backward navigation will also be possible through the browser. This option also allows users to bookmark a specific section or slide. Be careful! anchors can not have the same value as any ID element on the site (or NAME element for IE). Now anchors can be defined directly in the HTML structure by using the attribute data-anchor as explained here. */ anchors?: string[]; - + /** * (default false) If set to true, it will show a navigation bar made up of small circles. */ navigation?: boolean; - + /** * (default none) It can be set to left or right and defines which position the navigation bar will be shown (if using one). */ navigationPosition?: string; - + /** * (default []) Defines the tooltips to show for the navigation circles in case they are being used. Example: navigationTooltips: ['firstSlide', 'secondSlide']. */ navigationTooltips?: string[]; - + /** * (default false) Shows a persistent tooltip for the actively viewed section in the vertical navigation. */ showActiveTooltip?: boolean; - + /** * (default false) If set to true it will show a navigation bar made up of small circles for each landscape slider on the site. */ slidesNavigation?: boolean; - + /** * (default bottom) Defines the position for the landscape navigation bar for sliders. Admits top and bottom as values. You may want to modify the CSS styles to determine the distance from the top or bottom as well as any other style such as color. */ slidesNavPosition?: string; - // Scrolling - + // Scrolling + /** * (default true). Defines whether to use JavaScript or CSS3 transforms to scroll within sections and slides. Useful to speed up the movement in tablet and mobile devices with browsers supporting CSS3. If this option is set to true and the browser doesn't support CSS3, a jQuery fallback will be used instead. */ css3?: boolean; - + /** * (default 700) Speed in milliseconds for the scrolling transitions. */ scrollingSpeed?: number; - + /** * (default true) Defines whether to use the "automatic" scrolling or the "normal" one. It also has affects the way the sections fit in the browser/device window in tablets and mobile phones. */ autoScrolling?: boolean; - + /** * (default true). Determines whether or not to fit sections to the viewport or not. When set to true the current active section will always fill the whole viewport. Otherwise the user will be free to stop in the middle of a section (when ) */ fitToSection?: boolean; - + /** * (default 1000). If fitToSection is set to true, this delays the fitting by the configured milliseconds. */ fitToSectionDelay?: number; - + /** * (default false). Determines whether to use scrollbar for the site or not. In case of using scroll bar, the autoScrolling functionality will still working as expected. The user will also be free to scroll the site with the scroll bar and fullPage.js will fit the section in the screen when scrolling finishes. */ scrollBar?: boolean; - + /** * (default easeInOutCubic) Defines the transition effect to use for the vertical and horizontal scrolling. It requires the file vendors/jquery.easings.min.js or jQuery UI for using some of its transitions. Other libraries could be used instead. */ easing?: string; - + /** * (default ease) Defines the transition effect to use in case of using css3:true. You can use the pre-defined ones (such as linear, ease-out...) or create your own ones using the cubic-bezier function. You might want to use Matthew Lein CSS Easing Animation Tool for it. */ easingcss3?: string; - + /** * (default false) Defines whether scrolling down in the last section should scroll to the first one or not. */ loopBottom?: boolean; - + /** * (default false) Defines whether scrolling up in the first section should scroll to the last one or not. */ loopTop?: boolean; - + /** * (default true) Defines whether horizontal sliders will loop after reaching the last or previous slide or not. */ loopHorizontal?: boolean; - + /** * (default false) Defines whether scrolling down in the last section should scroll down to the first one or not, and if scrolling up in the first section should scroll up to the last one or not. Not compatible with loopTop or loopBottom. */ continuousVertical?: boolean; - + /** * (default null) If you want to avoid the auto scroll when scrolling over some elements, this is the option you need to use. (useful for maps, scrolling divs etc.) It requires a string with the jQuery selectors for those elements. (For example: normalScrollElements: '#element1, .element2') */ normalScrollElements?: string; - + /** * (default false) defines whether or not to create a scroll for the section/slide in case its content is bigger than the height of it. When set to true, your content will be wrapped by the plugin. Consider using delegation or load your other scripts in the afterRender callback. In case of setting it to true, it requires the vendor library scrolloverflow.min.js and it should be loaded before the fullPage.js plugin. */ scrollOverflow?: boolean; - + /** * when using scrollOverflow:true fullpage.js will make use of a forked and modified version of iScroll.js libary. You can customize the scrolling behaviour by providing fullpage.js with the iScroll.js options you want to use. Check its documentation for more info. */ scrollOverflowOptions?: any; - + /** * (default 5) Defines a percentage of the browsers window width/height, and how far a swipe must measure for navigating to the next section / slide */ touchSensitivity?: number; - + /** * (default 5) Defines the threshold for the number of hops up the html node tree Fullpage will test to see if normalScrollElements is a match to allow scrolling functionality on divs on a touch device. (For example: normalScrollElementTouchThreshold: 3) */ normalScrollElementTouchThreshold?: number; // Accessibility - + /** * (default true) Defines if the content can be navigated using the keyboard */ keyboardScrolling?: boolean; - + /** * (default true) Defines whether the load of the site when given an anchor (#) will scroll with animation to its destination or will directly load on the given section. */ animateAnchor?: boolean; - + /** * (default true) Defines whether to push the state of the site to the browser's history. When set to true each section/slide of the site will act as a new page and the back and forward buttons of the browser will scroll the sections/slides to reach the previous or next state of the site. When set to false, the URL will keep changing but will have no effect ont he browser's history. This option is automatically turned off when using autoScrolling:false. */ recordHistory?: boolean; - // Design + // Design /** * (default: true) Determines whether to use control arrows for the slides to move right or left. */ controlArrows?: boolean; - + /** * (default true) Vertically centering of the content within sections. When set to true, your content will be wrapped by the plugin. Consider using delegation or load your other scripts in the afterRender callback. */ verticalCentered?: boolean; - - + + resize ?: boolean; - + /** * (default none) Define the CSS background-color property for each section */ sectionsColor ?: string[]; - + /** * (default 0) Defines the top padding for each section with a numerical value and its measure (paddingTop: '10px', paddingTop: '10em'...) Useful in case of using a fixed header. */ paddingTop?: string; - + /** * (default 0) Defines the bottom padding for each section with a numerical value and its measure (paddingBottom: '10px', paddingBottom: '10em'...). Useful in case of using a fixed footer. */ paddingBottom?: string; - + /** * (default null) Defines which elements will be taken off the scrolling structure of the plugin which is necessary when using the css3 option to keep them fixed. It requires a string with the jQuery selectors for those elements. (For example: fixedElements: '#element1, .element2') */ fixedElements?: string; - + /** * (default 0) A normal scroll (autoScrolling:false) will be used under the defined width in pixels. A class fp-responsive is added to the body tag in case the user wants to use it for his own responsive CSS. For example, if set to 900, whenever the browser's width is less than 900 the plugin will scroll like a normal site. */ responsiveWidth?: number; - + /** * (default 0) A normal scroll (autoScrolling:false) will be used under the defined height in pixels. A class fp-responsive is added to the body tag in case the user wants to use it for his own responsive CSS. For example, if set to 900, whenever the browser's height is less than 900 the plugin will scroll like a normal site. */ responsiveHeight?: number; // Custom selectors - + /** * (default .section) Defines the jQuery selector used for the plugin sections. It might need to be changed sometimes to avoid problem with other plugins using the same selectors as fullpage.js. */ sectionSelector?: string; - + /** * (default .slide) Defines the jQuery selector used for the plugin slides. It might need to be changed sometimes to avoid problem with other plugins using the same selectors as fullpage.js. */ slideSelector?: string; - // Events + // Events /** * This callback is fired once the user leaves a section, in the transition to the new section. Returning false will cancel the move before it takes place. * @param index index of the leaving section. Starting from 1. @@ -219,29 +219,29 @@ interface FullPageJsOptions { * @param direction it will take the values up or down depending on the scrolling direction. */ onLeave?: (index: number, nextIndex: number, direction: string) => void; - + /** * Callback fired once the sections have been loaded, after the scrolling has ended. * @param anchorLink anchorLink corresponding to the section. * @param index index of the section. Starting from 1. */ afterLoad?: (anchorLink: string, index: number) => void; - + /** * This callback is fired just after the structure of the page is generated. This is the callback you want to use to initialize other plugins or fire any code which requires the document to be ready (as this plugin modifies the DOM to create the resulting structure). */ afterRender?: () => void; - + /** * This callback is fired after resizing the browser's window. Just after the sections are resized. */ afterResize?: () => void; - + /** * Callback fired once the slide of a section have been loaded, after the scrolling has ended. - * + * * In case of not having anchorLinks defined for the slide or slides the slideIndex parameter would be the only one to use. - * + * * Parameters: * * @param anchorLink anchorLink corresponding to the section. @@ -250,7 +250,7 @@ interface FullPageJsOptions { * @param slideIndex index of the slide. Starting from 1. (the default slide doesn't count as slide, but as a section) */ afterSlideLoad?: (anchorLink: string, index: number, slideAnchor: string, slideIndex: number) => void; - + /** * This callback is fired once the user leaves an slide to go to another, in the transition to the new slide. Returning false will cancel the move before it takes place. * @param anchorLink: anchorLink corresponding to the section. diff --git a/fullpage.js/tsconfig.json b/fullpage.js/tsconfig.json new file mode 100644 index 0000000000..0e6588b0f4 --- /dev/null +++ b/fullpage.js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "fullpage.js.d.ts", + "fullpage.js-tests.ts" + ] +} \ No newline at end of file diff --git a/geojson2osm/geojson2osm-tests.ts b/geojson2osm/geojson2osm-tests.ts index c7bfc05b85..887f10a83c 100644 --- a/geojson2osm/geojson2osm-tests.ts +++ b/geojson2osm/geojson2osm-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import { geojson2osm } from 'geojson2osm' const features: GeoJSON.FeatureCollection = { diff --git a/geojson2osm/geojson2osm.d.ts b/geojson2osm/geojson2osm.d.ts deleted file mode 100644 index 58393411f1..0000000000 --- a/geojson2osm/geojson2osm.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Type definitions for geojson2osm 0.0.5 -// Project: https://github.com/Rub21/geojson2osm -// Definitions by: Denis Carriere -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'geojson2osm' { - /** - * Converts GeoJSON features to OpenStreetMap XML. - * @param features Input features - * @returns OpenStreetMap XML - */ - export function geojson2osm(features: GeoJSON.Feature | GeoJSON.FeatureCollection): any -} diff --git a/geojson2osm/index.d.ts b/geojson2osm/index.d.ts new file mode 100644 index 0000000000..08bc529cc0 --- /dev/null +++ b/geojson2osm/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for geojson2osm 0.0.5 +// Project: https://github.com/Rub21/geojson2osm +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +/** + * Converts GeoJSON features to OpenStreetMap XML. + * @param features Input features + * @returns OpenStreetMap XML + */ +export function geojson2osm(features: GeoJSON.Feature | GeoJSON.FeatureCollection): any diff --git a/geojson2osm/tsconfig.json b/geojson2osm/tsconfig.json new file mode 100644 index 0000000000..310959268e --- /dev/null +++ b/geojson2osm/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "geojson2osm-tests.ts" + ] +} \ No newline at end of file diff --git a/globalize-compiler/globalize-compiler-tests.ts b/globalize-compiler/globalize-compiler-tests.ts index f4fc934d1f..648ed40032 100644 --- a/globalize-compiler/globalize-compiler-tests.ts +++ b/globalize-compiler/globalize-compiler-tests.ts @@ -1,12 +1,11 @@ -/// - -import globalizeCompiler = require("globalize-compiler"); +import * as ESTree from "estree"; +import * as globalizeCompiler from "globalize-compiler"; const globalize: GlobalizeStatic = null; -let extractsArray: GlobalizeCompiler.FormatterOrParserFunction[]; +let extractsArray: globalizeCompiler.FormatterOrParserFunction[]; -const templateFunction: (options: GlobalizeCompiler.CompileTemplateOptions) => string = - (options: GlobalizeCompiler.CompileTemplateOptions): string => { +const templateFunction: (options: globalizeCompiler.CompileTemplateOptions) => string = + (options: globalizeCompiler.CompileTemplateOptions): string => { const deps: string[] = options.dependencies; const code: string = options.code; return `${deps.join(';')}${code}`; @@ -18,7 +17,7 @@ compileOutput = globalizeCompiler.compile({ x: () => "test", y: (x: string) => x compileOutput = globalizeCompiler.compile(extractsArray, { template: templateFunction }); compileOutput = globalizeCompiler.compile({ x: () => "test", y: (x: string) => x }, { template: templateFunction }); -let extractOutput: GlobalizeCompiler.ExtractFunction; +let extractOutput: globalizeCompiler.ExtractFunction; extractOutput = globalizeCompiler.extract("path"); const ast: ESTree.Program = undefined; diff --git a/globalize-compiler/globalize-compiler.d.ts b/globalize-compiler/globalize-compiler.d.ts deleted file mode 100644 index 3959924412..0000000000 --- a/globalize-compiler/globalize-compiler.d.ts +++ /dev/null @@ -1,106 +0,0 @@ -// Type definitions for globalize-compiler v0.2.0 -// Project: https://github.com/jquery-support/globalize-compiler -// Definitions by: Ian Clanton-Thuon -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// - -declare namespace GlobalizeCompiler { - interface CompileTemplateOptions { - /** - * the source of the compiled formatters and parsers. - */ - code: string; - - /** - * a list of globalize runtime modules that the compiled code depends on, e.g. globalize-runtime/number. - */ - dependencies: string[]; - } - - interface CompileOptions { - /** - * A function that replaces the default template. - */ - template?: (options: CompileTemplateOptions) => string; - } - - interface FormatterOrParserFunction { - (...arguments: any[]): any; - } - - interface ExtractFunction { - /** - * @param {globalize} the globalize object. - * - * @returns an Array with the formatters and parsers created using the passed Globalize. - */ - (globalize: GlobalizeStatic): FormatterOrParserFunction[]; - } - - interface CompileExtractsAttributes extends CompileOptions { - /** - * an Array of extracts obtained by @see{GlobalizeCompilerStatic.extract} - */ - extracts: ExtractFunction; - - /** - * a locale to be used as Globalize.locale(defaultLocale) when generating the extracted formatters and parsers. - */ - defaultLocale: string; - - /** - * an Object with CLDR data (in the JSON format) or a Function taking one argument: locale, a String; returning - * an Object with the CLDR data for the passed locale. Defaults to the entire supplemental data plus the entire - * main data for the defaultLocale. - */ - cldr?: Object | ((locale: string) => Object); - - /** - * an Object with messages data (in the JSON format) or a Function taking one argument: locale, a String; returning - * an Object with the messages data for the passed locale. Defaults to {}. - */ - messages?: Object | ((locale: string) => Object); - } - - interface GlobalizeCompilerStatic { - /** - * Generates a JavaScript bundle containing the specified globalize formatters and parsers. - * - * @param {formattersAndParsers} an Array or an Object containing formatters and/or parsers. - * @param {options} compiler options. - * - * @returns a String with the generated JavaScript bundle (UMD wrapped) including the compiled formatters and - * parsers. - */ - compile(formattersAndParsers: FormatterOrParserFunction[] | { [key: string]: FormatterOrParserFunction }, - options?: CompileOptions): string; - - /** - * Creates an extract function from a source file. - * - * @param {input} a String with a filename, or a String with the file content, or an AST Object. - * - * @returns an extract. An extract is a Function taking one argument: Globalize, the Globalize Object; - * and returning an Array with the formatters and parsers created using the passed Globalize. - */ - extract(input: string | ESTree.Program): ExtractFunction; - - /** - * Generates a JavaScript bundle containing the specified globalize formatters and parsers. - * - * @param {options} compiler attributes. - * - * @returns a String with the generated JavaScript bundle (UMD wrapped) including the compiled formatters and - * parsers. - */ - compileExtracts(attributes: CompileExtractsAttributes): string; - } -} - -declare module "globalize-compiler" { - var globalizeCompiler: GlobalizeCompiler.GlobalizeCompilerStatic; - - export = globalizeCompiler; -} diff --git a/globalize-compiler/index.d.ts b/globalize-compiler/index.d.ts new file mode 100644 index 0000000000..6f3874636a --- /dev/null +++ b/globalize-compiler/index.d.ts @@ -0,0 +1,96 @@ +// Type definitions for globalize-compiler v0.2.0 +// Project: https://github.com/jquery-support/globalize-compiler +// Definitions by: Ian Clanton-Thuon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as ESTree from "estree"; + +interface CompileTemplateOptions { + /** + * the source of the compiled formatters and parsers. + */ + code: string; + + /** + * a list of globalize runtime modules that the compiled code depends on, e.g. globalize-runtime/number. + */ + dependencies: string[]; +} + +interface CompileOptions { + /** + * A function that replaces the default template. + */ + template?: (options: CompileTemplateOptions) => string; +} + +interface FormatterOrParserFunction { + (...args: any[]): any; +} + +interface ExtractFunction { + /** + * @param {globalize} the globalize object. + * + * @returns an Array with the formatters and parsers created using the passed Globalize. + */ + (globalize: GlobalizeStatic): FormatterOrParserFunction[]; +} + +interface CompileExtractsAttributes extends CompileOptions { + /** + * an Array of extracts obtained by @see{GlobalizeCompilerStatic.extract} + */ + extracts: ExtractFunction; + + /** + * a locale to be used as Globalize.locale(defaultLocale) when generating the extracted formatters and parsers. + */ + defaultLocale: string; + + /** + * an Object with CLDR data (in the JSON format) or a Function taking one argument: locale, a String; returning + * an Object with the CLDR data for the passed locale. Defaults to the entire supplemental data plus the entire + * main data for the defaultLocale. + */ + cldr?: Object | ((locale: string) => Object); + + /** + * an Object with messages data (in the JSON format) or a Function taking one argument: locale, a String; returning + * an Object with the messages data for the passed locale. Defaults to {}. + */ + messages?: Object | ((locale: string) => Object); +} + +/** + * Generates a JavaScript bundle containing the specified globalize formatters and parsers. + * + * @param {formattersAndParsers} an Array or an Object containing formatters and/or parsers. + * @param {options} compiler options. + * + * @returns a String with the generated JavaScript bundle (UMD wrapped) including the compiled formatters and + * parsers. + */ +export function compile(formattersAndParsers: FormatterOrParserFunction[] | { [key: string]: FormatterOrParserFunction }, + options?: CompileOptions): string; + +/** + * Creates an extract function from a source file. + * + * @param {input} a String with a filename, or a String with the file content, or an AST Object. + * + * @returns an extract. An extract is a Function taking one argument: Globalize, the Globalize Object; + * and returning an Array with the formatters and parsers created using the passed Globalize. + */ +export function extract(input: string | ESTree.Program): ExtractFunction; + +/** + * Generates a JavaScript bundle containing the specified globalize formatters and parsers. + * + * @param {options} compiler attributes. + * + * @returns a String with the generated JavaScript bundle (UMD wrapped) including the compiled formatters and + * parsers. + */ +export function compileExtracts(attributes: CompileExtractsAttributes): string; diff --git a/globalize-compiler/tsconfig.json b/globalize-compiler/tsconfig.json new file mode 100644 index 0000000000..87dae3c759 --- /dev/null +++ b/globalize-compiler/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "globalize-compiler-tests.ts" + ] +} \ No newline at end of file diff --git a/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts index fd7a053ce6..559dd4f609 100644 --- a/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts +++ b/gulp-angular-templatecache/gulp-angular-templatecache-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as gulp from 'gulp'; import * as templateCache from 'gulp-angular-templatecache'; diff --git a/gulp-angular-templatecache/gulp-angular-templatecache.d.ts b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts index 34e52acc36..ac608c39a6 100644 --- a/gulp-angular-templatecache/gulp-angular-templatecache.d.ts +++ b/gulp-angular-templatecache/gulp-angular-templatecache.d.ts @@ -3,7 +3,7 @@ // Definitions by: Aman Mahajan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "gulp-angular-templatecache" { function templatecache(): NodeJS.ReadWriteStream; diff --git a/gulp-angular-templatecache/tsconfig.json b/gulp-angular-templatecache/tsconfig.json new file mode 100644 index 0000000000..6b3a7a2fa2 --- /dev/null +++ b/gulp-angular-templatecache/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "gulp-angular-templatecache.d.ts", + "gulp-angular-templatecache-tests.ts" + ] +} \ No newline at end of file diff --git a/gulp-help-doc/gulp-help-doc-tests.ts b/gulp-help-doc/gulp-help-doc-tests.ts index f06c25e55c..4e5d2117aa 100644 --- a/gulp-help-doc/gulp-help-doc-tests.ts +++ b/gulp-help-doc/gulp-help-doc-tests.ts @@ -1,7 +1,3 @@ -/// -/// -/// - import gulp = require('gulp'); import usage = require('gulp-help-doc'); diff --git a/gulp-help-doc/gulp-help-doc.d.ts b/gulp-help-doc/gulp-help-doc.d.ts index 80d4922774..22bf5b4b5f 100644 --- a/gulp-help-doc/gulp-help-doc.d.ts +++ b/gulp-help-doc/gulp-help-doc.d.ts @@ -3,8 +3,8 @@ // Definitions by: Mikhus // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module "gulp-help-doc" { diff --git a/gulp-help-doc/tsconfig.json b/gulp-help-doc/tsconfig.json new file mode 100644 index 0000000000..f7206b7785 --- /dev/null +++ b/gulp-help-doc/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "gulp-help-doc.d.ts", + "gulp-help-doc-tests.ts" + ] +} \ No newline at end of file diff --git a/gulp-insert/gulp-insert-tests.ts b/gulp-insert/gulp-insert-tests.ts index e420cf5e4a..d3c84ecce5 100644 --- a/gulp-insert/gulp-insert-tests.ts +++ b/gulp-insert/gulp-insert-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as gulp from 'gulp'; import * as insert from 'gulp-insert'; diff --git a/gulp-insert/gulp-insert.d.ts b/gulp-insert/gulp-insert.d.ts index 9777280d5b..3ade4e803e 100644 --- a/gulp-insert/gulp-insert.d.ts +++ b/gulp-insert/gulp-insert.d.ts @@ -3,8 +3,8 @@ // Definitions by: Shant Marouti // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module 'gulp-insert' { diff --git a/gulp-insert/tsconfig.json b/gulp-insert/tsconfig.json new file mode 100644 index 0000000000..109f4aaa90 --- /dev/null +++ b/gulp-insert/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "gulp-insert.d.ts", + "gulp-insert-tests.ts" + ] +} \ No newline at end of file diff --git a/gulp/index.d.ts b/gulp/index.d.ts index 0387e0962f..ac4888043b 100644 --- a/gulp/index.d.ts +++ b/gulp/index.d.ts @@ -8,6 +8,7 @@ import Orchestrator = require("orchestrator"); +import VinylFile = require("vinyl"); declare namespace gulp { interface Gulp extends Orchestrator { diff --git a/html-pdf/html-pdf-tests.ts b/html-pdf/html-pdf-tests.ts index 6a214ef231..f6a5ad6e1b 100644 --- a/html-pdf/html-pdf-tests.ts +++ b/html-pdf/html-pdf-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as fs from 'fs'; import * as pdf from 'html-pdf'; diff --git a/html-pdf/html-pdf.d.ts b/html-pdf/html-pdf.d.ts index 07c4be9f71..a75ac3fd1f 100644 --- a/html-pdf/html-pdf.d.ts +++ b/html-pdf/html-pdf.d.ts @@ -3,7 +3,7 @@ // Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'html-pdf' { diff --git a/html-pdf/tsconfig.json b/html-pdf/tsconfig.json new file mode 100644 index 0000000000..b3b3941f12 --- /dev/null +++ b/html-pdf/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "html-pdf.d.ts", + "html-pdf-tests.ts" + ] +} \ No newline at end of file diff --git a/html-webpack-plugin/html-webpack-plugin.d.ts b/html-webpack-plugin/html-webpack-plugin.d.ts index 59917abf62..17f1023c68 100644 --- a/html-webpack-plugin/html-webpack-plugin.d.ts +++ b/html-webpack-plugin/html-webpack-plugin.d.ts @@ -3,7 +3,7 @@ // Definitions by: Simon Hartcher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "html-webpack-plugin" { import {Plugin} from "webpack"; diff --git a/html-webpack-plugin/tsconfig.json b/html-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..ea542ae271 --- /dev/null +++ b/html-webpack-plugin/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "html-webpack-plugin.d.ts", + "html-webpack-plugin-tests.ts" + ] +} \ No newline at end of file diff --git a/imagemapster/imagemapster-tests.ts b/imagemapster/imagemapster-tests.ts index 7f9ec9d761..9712cb4e1a 100644 --- a/imagemapster/imagemapster-tests.ts +++ b/imagemapster/imagemapster-tests.ts @@ -1,6 +1,3 @@ -/// -/// - const areaOptions: ImageMapster.AreaRenderingOptions = { key: "foo", includeKeys: "foo", diff --git a/imagemapster/imagemapster.d.ts b/imagemapster/imagemapster.d.ts index ad9eed3066..0c28c2ad2b 100644 --- a/imagemapster/imagemapster.d.ts +++ b/imagemapster/imagemapster.d.ts @@ -3,7 +3,7 @@ // Definitions by: delphinus // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace ImageMapster { diff --git a/imagemapster/tsconfig.json b/imagemapster/tsconfig.json new file mode 100644 index 0000000000..02230dff2f --- /dev/null +++ b/imagemapster/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "imagemapster.d.ts", + "imagemapster-tests.ts" + ] +} \ No newline at end of file diff --git a/intl-tel-input/intl-tel-input-tests.ts b/intl-tel-input/intl-tel-input-tests.ts index c10acfffa0..0d23c40d75 100644 --- a/intl-tel-input/intl-tel-input-tests.ts +++ b/intl-tel-input/intl-tel-input-tests.ts @@ -1,6 +1,3 @@ -/// -/// - $('#phone').intlTelInput(); $('#phone').intlTelInput({ diff --git a/intl-tel-input/intl-tel-input.d.ts b/intl-tel-input/intl-tel-input.d.ts index c092084738..38ac9274ca 100644 --- a/intl-tel-input/intl-tel-input.d.ts +++ b/intl-tel-input/intl-tel-input.d.ts @@ -8,7 +8,7 @@ // https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/jquery/jquery.d.ts#L958 // fn: any; //TODO: Decide how we want to type this -/// +/// declare namespace IntlTelInput { diff --git a/intl-tel-input/tsconfig.json b/intl-tel-input/tsconfig.json new file mode 100644 index 0000000000..2290a860c8 --- /dev/null +++ b/intl-tel-input/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "intl-tel-input.d.ts", + "intl-tel-input-tests.ts" + ] +} \ No newline at end of file diff --git a/inversify-binding-decorators/index.d.ts b/inversify-binding-decorators/index.d.ts new file mode 100644 index 0000000000..5887df8791 --- /dev/null +++ b/inversify-binding-decorators/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for inversify 1.0.0-beta.5 +// Project: https://github.com/inversify/inversify-binding-decorators +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +import inversify = require("inversify") + +interface IProvideInSyntax extends IProvideDoneSyntax { + inSingletonScope(): IProvideWhenOnSyntax; +} + +interface IProvideDoneSyntax { + done(): (target: any) => any; +} + +interface IProvideOnSyntax extends IProvideDoneSyntax { + onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): IProvideWhenSyntax; +} + +interface IProvideInWhenOnSyntax extends IProvideInSyntax, IProvideWhenSyntax, IProvideOnSyntax {} + +interface IProvideWhenOnSyntax extends IProvideWhenSyntax, IProvideOnSyntax {} + +interface IProvideWhenSyntax extends IProvideDoneSyntax { + when(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; + whenTargetNamed(name: string): IProvideOnSyntax; + whenTargetTagged(tag: string, value: any): IProvideOnSyntax; + whenInjectedInto(parent: (Function|string)): IProvideOnSyntax; + whenParentNamed(name: string): IProvideOnSyntax; + whenParentTagged(tag: string, value: any): IProvideOnSyntax; + whenAnyAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; + whenNoAncestorIs(ancestor: (Function|string)): IProvideOnSyntax; + whenAnyAncestorNamed(name: string): IProvideOnSyntax; + whenAnyAncestorTagged(tag: string, value: any): IProvideOnSyntax; + whenNoAncestorNamed(name: string): IProvideOnSyntax; + whenNoAncestorTagged(tag: string, value: any): IProvideOnSyntax; + whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; + whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): IProvideOnSyntax; +} + +export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void; + +export function makeProvideDecorator(kernel: inversify.interfaces.Kernel): + (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => (target: any) => any; + +export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel): + (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => IProvideInWhenOnSyntax; diff --git a/inversify-binding-decorators/inversify-binding-decorators-tests.ts b/inversify-binding-decorators/inversify-binding-decorators-tests.ts index 8ca0acc551..f55d419429 100644 --- a/inversify-binding-decorators/inversify-binding-decorators-tests.ts +++ b/inversify-binding-decorators/inversify-binding-decorators-tests.ts @@ -1,5 +1,3 @@ -/// - import { inject, Kernel } from "inversify"; import { autoProvide, makeProvideDecorator, makeFluentProvideDecorator } from "inversify-binding-decorators"; diff --git a/inversify-binding-decorators/inversify-binding-decorators.d.ts b/inversify-binding-decorators/inversify-binding-decorators.d.ts deleted file mode 100644 index d5f92132a3..0000000000 --- a/inversify-binding-decorators/inversify-binding-decorators.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -// Type definitions for inversify-binding-decorators 1.0.0 -// Project: https://github.com/inversify/inversify-binding-decorators -// Definitions by: inversify -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare namespace inversifyBindingDecorators { - - namespace interfaces { - - export interface ProvideInSyntax extends ProvideDoneSyntax { - inSingletonScope(): ProvideWhenOnSyntax; - } - - export interface ProvideDoneSyntax { - done(): (target: any) => any; - } - - export interface ProvideOnSyntax extends ProvideDoneSyntax { - onActivation(fn: (context: inversify.interfaces.Context, injectable: T) => T): ProvideWhenSyntax; - } - - export interface ProvideInWhenOnSyntax extends ProvideInSyntax, ProvideWhenSyntax, ProvideOnSyntax {} - - export interface ProvideWhenOnSyntax extends ProvideWhenSyntax, ProvideOnSyntax {} - - export interface ProvideWhenSyntax extends ProvideDoneSyntax { - when(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; - whenTargetNamed(name: string): ProvideOnSyntax; - whenTargetTagged(tag: string, value: any): ProvideOnSyntax; - whenInjectedInto(parent: (Function|string)): ProvideOnSyntax; - whenParentNamed(name: string): ProvideOnSyntax; - whenParentTagged(tag: string, value: any): ProvideOnSyntax; - whenAnyAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; - whenNoAncestorIs(ancestor: (Function|string)): ProvideOnSyntax; - whenAnyAncestorNamed(name: string): ProvideOnSyntax; - whenAnyAncestorTagged(tag: string, value: any): ProvideOnSyntax; - whenNoAncestorNamed(name: string): ProvideOnSyntax; - whenNoAncestorTagged(tag: string, value: any): ProvideOnSyntax; - whenAnyAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; - whenNoAncestorMatches(constraint: (request: inversify.interfaces.Request) => boolean): ProvideOnSyntax; - } - - } - - export function autoProvide(kernel: inversify.interfaces.Kernel, ...modules: any[]): void; - - export function makeProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => (target: any) => any; - - export function makeFluentProvideDecorator(kernel: inversify.interfaces.Kernel): - (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => interfaces.ProvideInWhenOnSyntax; - -} - -declare module "inversify-binding-decorators" { - export = inversifyBindingDecorators; -} diff --git a/inversify-binding-decorators/tsconfig.json b/inversify-binding-decorators/tsconfig.json new file mode 100644 index 0000000000..0cfbf3bb2f --- /dev/null +++ b/inversify-binding-decorators/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "experimentalDecorators": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "inversify-binding-decorators-tests.ts" + ] +} \ No newline at end of file diff --git a/inversify-devtools/inversify-devtools-test.ts b/inversify-devtools/inversify-devtools-test.ts index 3b99d7df93..0a148f013c 100644 --- a/inversify-devtools/inversify-devtools-test.ts +++ b/inversify-devtools/inversify-devtools-test.ts @@ -1,5 +1,3 @@ -/// - import render from "inversify-devtools"; import { Kernel } from "inversify"; diff --git a/inversify-devtools/inversify-devtools.d.ts b/inversify-devtools/inversify-devtools.d.ts index 841ae228c5..12e1bebd02 100644 --- a/inversify-devtools/inversify-devtools.d.ts +++ b/inversify-devtools/inversify-devtools.d.ts @@ -3,13 +3,10 @@ // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +import * as inversify from "inversify"; interface ConnectKernel extends Function { (kernel: inversify.interfaces.Kernel): void; } -declare module "inversify-devtools" { - let render: (container: string) => ConnectKernel; - export default render; -} +export default function render(container: string): ConnectKernel; diff --git a/inversify-devtools/tsconfig.json b/inversify-devtools/tsconfig.json new file mode 100644 index 0000000000..7493d3ee13 --- /dev/null +++ b/inversify-devtools/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "experimentalDecorators": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "inversify-devtools.d.ts", + "inversify-devtools-test.ts" + ] +} \ No newline at end of file diff --git a/inversify-express-utils/inversify-express-utils-tests.ts b/inversify-express-utils/inversify-express-utils-tests.ts index b082546448..25591cd4bc 100644 --- a/inversify-express-utils/inversify-express-utils-tests.ts +++ b/inversify-express-utils/inversify-express-utils-tests.ts @@ -1,5 +1,3 @@ -/// - import { InversifyExpressServer, Controller, Get, All, Delete, Head, Put, Patch, Post, Method, TYPE } from "inversify-express-utils"; import * as express from "express"; import { Kernel } from "inversify"; diff --git a/inversify-express-utils/inversify-express-utils.d.ts b/inversify-express-utils/inversify-express-utils.d.ts index f90b0cac88..185b33363d 100644 --- a/inversify-express-utils/inversify-express-utils.d.ts +++ b/inversify-express-utils/inversify-express-utils.d.ts @@ -3,8 +3,8 @@ // Definitions by: inversify // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// -/// +/// +/// declare module "inversify-express-utils" { diff --git a/inversify-express-utils/tsconfig.json b/inversify-express-utils/tsconfig.json new file mode 100644 index 0000000000..c7e399100e --- /dev/null +++ b/inversify-express-utils/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "experimentalDecorators": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "inversify-express-utils.d.ts", + "inversify-express-utils-tests.ts" + ] +} \ No newline at end of file diff --git a/inversify-inject-decorators/index.d.ts b/inversify-inject-decorators/index.d.ts new file mode 100644 index 0000000000..9b0c628eb2 --- /dev/null +++ b/inversify-inject-decorators/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for inversify-inject-decorators 1.0.0-beta.1 +// Project: https://github.com/inversify/inversify-inject-decorators +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +import inversify = require("inversify") + +interface InjectDecorators { + + lazyInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + (proto: any, key: string) => void; + + lazyInjectNamed: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), named: string) => + (proto: any, key: string) => void; + + lazyInjectTagged: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable), key: string, value: any) => + (proto: any, propertyName: string) => void; + + lazyMultiInject: (serviceIdentifier: (string|Symbol|inversify.interfaces.Newable)) => + (proto: any, key: string) => void; +} + +export default function getDecorators(kernel: inversify.interfaces.Kernel): InjectDecorators; diff --git a/inversify-inject-decorators/inversify-inject-decorators-tests.ts b/inversify-inject-decorators/inversify-inject-decorators-tests.ts index 468bbaf763..577d4f5b1c 100644 --- a/inversify-inject-decorators/inversify-inject-decorators-tests.ts +++ b/inversify-inject-decorators/inversify-inject-decorators-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import getDecorators from "inversify-inject-decorators"; import { Kernel, injectable, tagged, named } from "inversify"; diff --git a/inversify-inject-decorators/inversify-inject-decorators.d.ts b/inversify-inject-decorators/inversify-inject-decorators.d.ts deleted file mode 100644 index 34244c6d5e..0000000000 --- a/inversify-inject-decorators/inversify-inject-decorators.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Type definitions for inversify-inject-decorators 1.0.0 -// Project: https://github.com/inversify/inversify-inject-decorators -// Definitions by: inversify -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare namespace inversifyInjectDecorators { - - export interface InjectDecorators { - - lazyInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => - (proto: any, key: string) => void; - - lazyInjectNamed: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, named: string) => - (proto: any, key: string) => void; - - lazyInjectTagged: (serviceIdentifier: inversify.interfaces.ServiceIdentifier, key: string, value: any) => - (proto: any, propertyName: string) => void; - - lazyMultiInject: (serviceIdentifier: inversify.interfaces.ServiceIdentifier) => - (proto: any, key: string) => void; - - } - -} - -declare module "inversify-inject-decorators" { - let getDecorators: (kernel: inversify.interfaces.Kernel) => inversifyInjectDecorators.InjectDecorators; - export default getDecorators; -} diff --git a/inversify-inject-decorators/tsconfig.json b/inversify-inject-decorators/tsconfig.json new file mode 100644 index 0000000000..7b922e01fa --- /dev/null +++ b/inversify-inject-decorators/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "experimentalDecorators": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "inversify-inject-decorators-tests.ts" + ] +} \ No newline at end of file diff --git a/inversify-logger-middleware/index.d.ts b/inversify-logger-middleware/index.d.ts new file mode 100644 index 0000000000..aba35a5d21 --- /dev/null +++ b/inversify-logger-middleware/index.d.ts @@ -0,0 +1,65 @@ +// Type definitions for inversify-logger-middleware 1.0.0 +// Project: https://github.com/inversify/inversify-logger-middleware +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +import * as inversify from "inversify"; + +export namespace interfaces { + + export interface LoggerSettings { + request?: RequestLoggerSettings; + time?: boolean; + } + + export interface RequestLoggerSettings { + serviceIdentifier?: boolean; + bindings?: BindingLoggerSettings; + target?: TargetLoggerSettings; + } + + export interface BindingLoggerSettings { + activated?: boolean; + serviceIdentifier?: boolean; + implementationType?: boolean; + factory?: boolean; + provider?: boolean; + constraint?: boolean; + onActivation?: boolean; + cache?: boolean; + dynamicValue?: boolean; + scope?: boolean; + type?: boolean; + } + + export interface TargetLoggerSettings { + serviceIdentifier?: boolean; + name?: boolean; + metadata?: boolean; + } + + export interface LogEntry { + error: boolean; + exception: any; + guid: string; + multiInject: boolean; + results: any[]; + rootRequest: inversify.interfaces.Request; + serviceIdentifier: any; + target: any; + time: string; + } + +} + +export function makeLoggerMiddleware( + settings?: interfaces.LoggerSettings, + renderer?: (out: interfaces.LogEntry) => void +): inversify.interfaces.Middleware; + +export function textSerializer(entry: interfaces.LogEntry): string; +export function bindingTypeFormatter(type: number): string; +export function scopeFormatter(scope: number): string; + + +export as namespace inversifyLoggerMiddleware; diff --git a/inversify-logger-middleware/inversify-logger-middleware-tests.ts b/inversify-logger-middleware/inversify-logger-middleware-tests.ts index 3b2119911a..ba33687072 100644 --- a/inversify-logger-middleware/inversify-logger-middleware-tests.ts +++ b/inversify-logger-middleware/inversify-logger-middleware-tests.ts @@ -1,7 +1,8 @@ -/// +import * as inversify from "inversify"; declare var kernel: inversify.interfaces.Kernel; +import * as inversifyLoggerMiddleware from "inversify-logger-middleware"; import { makeLoggerMiddleware, textSerializer } from "inversify-logger-middleware"; interface LoggerOutput { diff --git a/inversify-logger-middleware/inversify-logger-middleware.d.ts b/inversify-logger-middleware/inversify-logger-middleware.d.ts deleted file mode 100644 index cd0037f432..0000000000 --- a/inversify-logger-middleware/inversify-logger-middleware.d.ts +++ /dev/null @@ -1,70 +0,0 @@ -// Type definitions for inversify-logger-middleware 1.0.0 -// Project: https://github.com/inversify/inversify-logger-middleware -// Definitions by: inversify -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// - -declare namespace inversifyLoggerMiddleware { - - export namespace interfaces { - - export interface LoggerSettings { - request?: RequestLoggerSettings; - time?: boolean; - } - - export interface RequestLoggerSettings { - serviceIdentifier?: boolean; - bindings?: BindingLoggerSettings; - target?: TargetLoggerSettings; - } - - export interface BindingLoggerSettings { - activated?: boolean; - serviceIdentifier?: boolean; - implementationType?: boolean; - factory?: boolean; - provider?: boolean; - constraint?: boolean; - onActivation?: boolean; - cache?: boolean; - dynamicValue?: boolean; - scope?: boolean; - type?: boolean; - } - - export interface TargetLoggerSettings { - serviceIdentifier?: boolean; - name?: boolean; - metadata?: boolean; - } - - export interface LogEntry { - error: boolean; - exception: any; - guid: string; - multiInject: boolean; - results: any[]; - rootRequest: inversify.interfaces.Request; - serviceIdentifier: any; - target: any; - time: string; - } - - } - - export function makeLoggerMiddleware( - settings?: interfaces.LoggerSettings, - renderer?: (out: interfaces.LogEntry) => void - ): inversify.interfaces.Middleware; - - export function textSerializer(entry: interfaces.LogEntry): string; - export function bindingTypeFormatter(type: number): string; - export function scopeFormatter(scope: number): string; - -} - -declare module "inversify-logger-middleware" { - export = inversifyLoggerMiddleware; -} diff --git a/inversify-logger-middleware/tsconfig.json b/inversify-logger-middleware/tsconfig.json new file mode 100644 index 0000000000..363943998d --- /dev/null +++ b/inversify-logger-middleware/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "experimentalDecorators": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "inversify-logger-middleware-tests.ts" + ] +} \ No newline at end of file diff --git a/inversify-restify-utils/index.d.ts b/inversify-restify-utils/index.d.ts new file mode 100644 index 0000000000..211351db73 --- /dev/null +++ b/inversify-restify-utils/index.d.ts @@ -0,0 +1,52 @@ +// Type definitions for inversify-restify-utils 1.0.0 +// Project: https://github.com/inversify/inversify-restify-utils +// Definitions by: inversify +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +import * as restify from "restify"; +import * as inversify from "inversify"; + +export namespace interfaces { + + export interface InversifyRestifyServerConstructor { + new(kernel: inversify.interfaces.Kernel): InversifyRestifyServer; + } + + export interface InversifyRestifyServer { + setConfig(fn: ConfigFunction): InversifyRestifyServer; + build(): restify.Server; + } + + export interface ConfigFunction { + (app: restify.Server): void; + } + + export interface HandlerDecoratorFactory { + (path: string, ...middleware: restify.RequestHandler[]): HandlerDecorator; + } + + export interface HandlerDecorator { + (target: any, key: string, value: any): void; + } + +} + +export interface Controller {} + +interface ServiceIdentifiers { + Controller: Symbol; +} + +export var InversifyRestifyServer: interfaces.InversifyRestifyServerConstructor; + +export var Controller: (path: string, ...middleware: restify.RequestHandler[]) => (target: any) => void; + +export var Options: interfaces.HandlerDecoratorFactory; +export var Get: interfaces.HandlerDecoratorFactory; +export var Post: interfaces.HandlerDecoratorFactory; +export var Put: interfaces.HandlerDecoratorFactory; +export var Patch: interfaces.HandlerDecoratorFactory; +export var Head: interfaces.HandlerDecoratorFactory; +export var Delete: interfaces.HandlerDecoratorFactory; +export var Method: (method: string, path: string, ...middleware: restify.RequestHandler[]) => interfaces.HandlerDecorator; +export var TYPE: ServiceIdentifiers; diff --git a/inversify-restify-utils/inversify-restify-utils-tests.ts b/inversify-restify-utils/inversify-restify-utils-tests.ts index 5ff3ddc633..1190c16083 100644 --- a/inversify-restify-utils/inversify-restify-utils-tests.ts +++ b/inversify-restify-utils/inversify-restify-utils-tests.ts @@ -1,5 +1,3 @@ -/// - import { InversifyRestifyServer, Controller, Get, Options, Delete, Head, Put, Patch, Post, Method, TYPE diff --git a/inversify-restify-utils/inversify-restify-utils.d.ts b/inversify-restify-utils/inversify-restify-utils.d.ts deleted file mode 100644 index 4f2aab5510..0000000000 --- a/inversify-restify-utils/inversify-restify-utils.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -// Type definitions for inversify-restify-utils 1.0.0 -// Project: https://github.com/inversify/inversify-restify-utils -// Definitions by: inversify -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// - -declare module "inversify-restify-utils" { - - import * as restify from "restify"; - import * as inversify from "inversify"; - - export namespace interfaces { - - export interface InversifyRestifyServerConstructor { - new(kernel: inversify.interfaces.Kernel): InversifyRestifyServer; - } - - export interface InversifyRestifyServer { - setConfig(fn: ConfigFunction): InversifyRestifyServer; - build(): restify.Server; - } - - export interface ConfigFunction { - (app: restify.Server): void; - } - - export interface HandlerDecoratorFactory { - (path: string, ...middleware: restify.RequestHandler[]): HandlerDecorator; - } - - export interface HandlerDecorator { - (target: any, key: string, value: any): void; - } - - } - - export interface Controller {} - - interface ServiceIdentifiers { - Controller: Symbol; - } - - export var InversifyRestifyServer: interfaces.InversifyRestifyServerConstructor; - - export var Controller: (path: string, ...middleware: restify.RequestHandler[]) => (target: any) => void; - - export var Options: interfaces.HandlerDecoratorFactory; - export var Get: interfaces.HandlerDecoratorFactory; - export var Post: interfaces.HandlerDecoratorFactory; - export var Put: interfaces.HandlerDecoratorFactory; - export var Patch: interfaces.HandlerDecoratorFactory; - export var Head: interfaces.HandlerDecoratorFactory; - export var Delete: interfaces.HandlerDecoratorFactory; - export var Method: (method: string, path: string, ...middleware: restify.RequestHandler[]) => interfaces.HandlerDecorator; - export var TYPE: ServiceIdentifiers; - -} diff --git a/inversify-restify-utils/tsconfig.json b/inversify-restify-utils/tsconfig.json new file mode 100644 index 0000000000..c610f4fb27 --- /dev/null +++ b/inversify-restify-utils/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "experimentalDecorators": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "inversify-restify-utils-tests.ts" + ] +} \ No newline at end of file diff --git a/istanbul-middleware/istanbul-middleware-tests.ts b/istanbul-middleware/istanbul-middleware-tests.ts index 01afa92082..2a436fa0f5 100644 --- a/istanbul-middleware/istanbul-middleware-tests.ts +++ b/istanbul-middleware/istanbul-middleware-tests.ts @@ -1,2 +1 @@ -/// import i = require('istanbul-middleware'); diff --git a/istanbul-middleware/istanbul-middleware.d.ts b/istanbul-middleware/istanbul-middleware.d.ts index 054e32931e..d9c020d5f8 100644 --- a/istanbul-middleware/istanbul-middleware.d.ts +++ b/istanbul-middleware/istanbul-middleware.d.ts @@ -3,7 +3,7 @@ // Definitions by: Hookclaw // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "istanbul-middleware" { import * as express from "express"; diff --git a/istanbul-middleware/tsconfig.json b/istanbul-middleware/tsconfig.json new file mode 100644 index 0000000000..e755a0b80e --- /dev/null +++ b/istanbul-middleware/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "istanbul-middleware.d.ts", + "istanbul-middleware-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery-mousewheel/jquery-mousewheel-tests.ts b/jquery-mousewheel/jquery-mousewheel-tests.ts index 7f8807d7bb..706906b2ee 100644 --- a/jquery-mousewheel/jquery-mousewheel-tests.ts +++ b/jquery-mousewheel/jquery-mousewheel-tests.ts @@ -1,6 +1,4 @@ -/// - -$('#my_elem').on('mousewheel', (event: JQueryMousewheel.JQueryMousewheelEventObject) => { +$('#my_elem').on('mousewheel', (event: JQueryMousewheel.JQueryMousewheelEventObject) => { console.log(event.deltaX, event.deltaY, event.deltaFactor, event.deltaMode, event.absDelta); }); diff --git a/jquery-mousewheel/jquery-mousewheel.d.ts b/jquery-mousewheel/jquery-mousewheel.d.ts index 1061e49f28..e57d73be5b 100644 --- a/jquery-mousewheel/jquery-mousewheel.d.ts +++ b/jquery-mousewheel/jquery-mousewheel.d.ts @@ -3,7 +3,7 @@ // Definitions by: Brian Surowiec // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace JQueryMousewheel { interface JQueryMousewheelEventObject extends JQueryEventObject { diff --git a/jquery-mousewheel/tsconfig.json b/jquery-mousewheel/tsconfig.json new file mode 100644 index 0000000000..0c0c88bcb6 --- /dev/null +++ b/jquery-mousewheel/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "jquery-mousewheel.d.ts", + "jquery-mousewheel-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery-truncate-html/jquery-truncate-html-tests.ts b/jquery-truncate-html/jquery-truncate-html-tests.ts index e20f9c22ee..8ec263cbc3 100644 --- a/jquery-truncate-html/jquery-truncate-html-tests.ts +++ b/jquery-truncate-html/jquery-truncate-html-tests.ts @@ -1,6 +1,3 @@ -/// - - function truncateHtmlString(): string { return $.truncate('

    Stuff and Nonsense

    ', { length: 13 @@ -11,4 +8,4 @@ function truncateVirtualElement (): JQuery { return $('

    Stuff and Nonsense

    ').truncate({ length: 13 }); -} +} diff --git a/jquery-truncate-html/jquery-truncate-html.d.ts b/jquery-truncate-html/jquery-truncate-html.d.ts index e410716b0a..cb9b749e48 100644 --- a/jquery-truncate-html/jquery-truncate-html.d.ts +++ b/jquery-truncate-html/jquery-truncate-html.d.ts @@ -1,9 +1,9 @@ -// Type definitions for jQuery-truncate-html.js +// Type definitions for jQuery-truncate-html.js // Project: https://github.com/kbwood/timeentry // Definitions by: Abraão Alves // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// interface TruncateOptions{ length?: number; diff --git a/jquery-truncate-html/tsconfig.json b/jquery-truncate-html/tsconfig.json new file mode 100644 index 0000000000..a282bbf024 --- /dev/null +++ b/jquery-truncate-html/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "jquery-truncate-html.d.ts", + "jquery-truncate-html-tests.ts" + ] +} \ No newline at end of file diff --git a/jquery/index.d.ts b/jquery/index.d.ts index b08598cc53..0a748d5269 100644 --- a/jquery/index.d.ts +++ b/jquery/index.d.ts @@ -74,7 +74,7 @@ interface JQueryAjaxSettings { */ dataFilter? (data: any, ty: any): any; /** - * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). + * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). */ dataType?: string; /** @@ -168,11 +168,11 @@ interface JQueryAjaxSettings { */ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { /** - * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). + * The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header. As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). */ overrideMimeType(mimeType: string): any; /** - * Cancel the request. + * Cancel the request. * * @param statusText A string passed as the textStatus parameter for the done callback. Default value: "canceled" */ @@ -197,13 +197,13 @@ interface JQueryXHR extends XMLHttpRequest, JQueryPromise { interface JQueryCallback { /** * Add a callback or a collection of callbacks to a callback list. - * + * * @param callbacks A function, or array of functions, that are to be added to the callback list. */ add(callbacks: Function): JQueryCallback; /** * Add a callback or a collection of callbacks to a callback list. - * + * * @param callbacks A function, or array of functions, that are to be added to the callback list. */ add(callbacks: Function[]): JQueryCallback; @@ -225,7 +225,7 @@ interface JQueryCallback { /** * Call all of the callbacks with the given arguments - * + * * @param arguments The argument or list of arguments to pass back to the callback list. */ fire(...arguments: any[]): JQueryCallback; @@ -237,7 +237,7 @@ interface JQueryCallback { /** * Call all callbacks in a list with the given context and arguments. - * + * * @param context A reference to the context in which the callbacks in the list should be fired. * @param arguments An argument, or array of arguments, to pass to the callbacks in the list. */ @@ -245,7 +245,7 @@ interface JQueryCallback { /** * Determine whether a supplied callback is in a list - * + * * @param callback The callback to search for. */ has(callback: Function): boolean; @@ -262,13 +262,13 @@ interface JQueryCallback { /** * Remove a callback or a collection of callbacks from a callback list. - * + * * @param callbacks A function, or array of functions, that are to be removed from the callback list. */ remove(callbacks: Function): JQueryCallback; /** * Remove a callback or a collection of callbacks from a callback list. - * + * * @param callbacks A function, or array of functions, that are to be removed from the callback list. */ remove(callbacks: Function[]): JQueryCallback; @@ -280,7 +280,7 @@ interface JQueryCallback { interface JQueryGenericPromise { /** * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * + * * @param doneFilter A function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. */ @@ -288,7 +288,7 @@ interface JQueryGenericPromise { /** * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * + * * @param doneFilter A function that is called when the Deferred is resolved. * @param failFilter An optional function that is called when the Deferred is rejected. */ @@ -316,28 +316,28 @@ interface JQueryPromise extends JQueryGenericPromise { state(): string; /** * Add handlers to be called when the Deferred object is either resolved or rejected. - * + * * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. */ always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; /** * Add handlers to be called when the Deferred object is resolved. - * + * * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. */ done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; /** * Add handlers to be called when the Deferred object is rejected. - * + * * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. */ fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryPromise; /** * Add handlers to be called when the Deferred object generates progress notifications. - * + * * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. */ progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryPromise; @@ -356,42 +356,42 @@ interface JQueryDeferred extends JQueryGenericPromise { state(): string; /** * Add handlers to be called when the Deferred object is either resolved or rejected. - * + * * @param alwaysCallbacks1 A function, or array of functions, that is called when the Deferred is resolved or rejected. * @param alwaysCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. */ always(alwaysCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...alwaysCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; /** * Add handlers to be called when the Deferred object is resolved. - * + * * @param doneCallbacks1 A function, or array of functions, that are called when the Deferred is resolved. * @param doneCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. */ done(doneCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...doneCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; /** * Add handlers to be called when the Deferred object is rejected. - * + * * @param failCallbacks1 A function, or array of functions, that are called when the Deferred is rejected. * @param failCallbacks2 Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. */ fail(failCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...failCallbacksN: Array|JQueryPromiseCallback[]>): JQueryDeferred; /** * Add handlers to be called when the Deferred object generates progress notifications. - * + * * @param progressCallbacks A function, or array of functions, to be called when the Deferred generates progress notifications. */ progress(progressCallback1?: JQueryPromiseCallback|JQueryPromiseCallback[], ...progressCallbackN: Array|JQueryPromiseCallback[]>): JQueryDeferred; /** * Call the progressCallbacks on a Deferred object with the given args. - * + * * @param args Optional arguments that are passed to the progressCallbacks. */ notify(value?: any, ...args: any[]): JQueryDeferred; /** * Call the progressCallbacks on a Deferred object with the given context and args. - * + * * @param context Context passed to the progressCallbacks as the this object. * @param args Optional arguments that are passed to the progressCallbacks. */ @@ -399,13 +399,13 @@ interface JQueryDeferred extends JQueryGenericPromise { /** * Reject a Deferred object and call any failCallbacks with the given args. - * + * * @param args Optional arguments that are passed to the failCallbacks. */ reject(value?: any, ...args: any[]): JQueryDeferred; /** * Reject a Deferred object and call any failCallbacks with the given context and args. - * + * * @param context Context passed to the failCallbacks as the this object. * @param args An optional array of arguments that are passed to the failCallbacks. */ @@ -413,7 +413,7 @@ interface JQueryDeferred extends JQueryGenericPromise { /** * Resolve a Deferred object and call any doneCallbacks with the given args. - * + * * @param value First argument passed to doneCallbacks. * @param args Optional subsequent arguments that are passed to the doneCallbacks. */ @@ -421,7 +421,7 @@ interface JQueryDeferred extends JQueryGenericPromise { /** * Resolve a Deferred object and call any doneCallbacks with the given context and args. - * + * * @param context Context passed to the doneCallbacks as the this object. * @param args An optional array of arguments that are passed to the doneCallbacks. */ @@ -429,7 +429,7 @@ interface JQueryDeferred extends JQueryGenericPromise { /** * Return a Deferred's Promise object. - * + * * @param target Object onto which the promise methods have to be attached */ promise(target?: any): JQueryPromise; @@ -520,14 +520,14 @@ interface JQuerySupport { interface JQueryParam { /** * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * + * * @param obj An array or object to serialize. */ (obj: any): string; /** * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * + * * @param obj An array or object to serialize. * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. */ @@ -561,47 +561,47 @@ interface JQuerySerializeArrayElement { value: string; } -interface JQueryAnimationOptions { +interface JQueryAnimationOptions { /** * A string or number determining how long the animation will run. */ - duration?: any; + duration?: any; /** * A string indicating which easing function to use for the transition. */ - easing?: string; + easing?: string; /** * A function to call once the animation is complete. */ - complete?: Function; + complete?: Function; /** * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. */ - step?: (now: number, tween: any) => any; + step?: (now: number, tween: any) => any; /** * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. (version added: 1.8) */ - progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; + progress?: (animation: JQueryPromise, progress: number, remainingMs: number) => any; /** * A function to call when the animation begins. (version added: 1.8) */ - start?: (animation: JQueryPromise) => any; + start?: (animation: JQueryPromise) => any; /** * A function to be called when the animation completes (its Promise object is resolved). (version added: 1.8) */ - done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + done?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; /** * A function to be called when the animation fails to complete (its Promise object is rejected). (version added: 1.8) */ - fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + fail?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; /** * A function to be called when the animation completes or stops without completing (its Promise object is either resolved or rejected). (version added: 1.8) */ - always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; + always?: (animation: JQueryPromise, jumpedToEnd: boolean) => any; /** * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. */ - queue?: any; + queue?: any; /** * A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions. (version added: 1.4) */ @@ -965,7 +965,7 @@ interface JQueryStatic { /** * Check to see if a DOM element is a descendant of another DOM element. - * + * * @param container The DOM element that may contain the other element. * @param contained The DOM element that may be contained by (a descendant of) the other element. */ @@ -973,7 +973,7 @@ interface JQueryStatic { /** * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * + * * @param collection The object or array to iterate over. * @param callback The function that will be executed on every object. */ @@ -984,7 +984,7 @@ interface JQueryStatic { /** * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * + * * @param collection The object or array to iterate over. * @param callback The function that will be executed on every object. */ @@ -1081,21 +1081,21 @@ interface JQueryStatic { /** * Convert an array-like object into a true JavaScript array. - * + * * @param obj Any object to turn into a native Array. */ makeArray(obj: any): any[]; /** * Translate all items in an array or object to new array of items. - * + * * @param array The Array to translate. * @param callback The function to process each item against. The first argument to the function is the array item, the second argument is the index in array The function can return any value. Within the function, this refers to the global (window) object. */ map(array: T[], callback: (elementOfArray?: T, indexInArray?: number) => U): U[]; /** * Translate all items in an array or object to new array of items. - * + * * @param arrayOrObject The Array or Object to translate. * @param callback The function to process each item against. The first argument to the function is the value; the second argument is the index or key of the array or object property. The function can return any value to add to the array. A returned array will be flattened into the resulting array. Within the function, this refers to the global (window) object. */ @@ -1103,7 +1103,7 @@ interface JQueryStatic { /** * Merge the contents of two arrays together into the first array. - * + * * @param first The first array to merge, the elements of second added. * @param second The second array to merge into the first, unaltered. */ @@ -1121,7 +1121,7 @@ interface JQueryStatic { /** * Takes a well-formed JSON string and returns the resulting JavaScript object. - * + * * @param json The JSON string to parse. */ parseJSON(json: string): any; @@ -1135,21 +1135,21 @@ interface JQueryStatic { /** * Remove the whitespace from the beginning and end of a string. - * + * * @param str Remove the whitespace from the beginning and end of a string. */ trim(str: string): string; /** * Determine the internal JavaScript [[Class]] of an object. - * + * * @param obj Object to get the internal JavaScript [[Class]] of. */ type(obj: any): string; /** * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. - * + * * @param array The Array of DOM elements. */ unique(array: Element[]): Element[]; @@ -1276,7 +1276,7 @@ interface JQuery { * @param attributes An object of attribute-value pairs to set. */ attr(attributes: Object): JQuery; - + /** * Determine whether any of the matched elements are assigned the given class. * @@ -1454,7 +1454,7 @@ interface JQuery { * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). */ innerHeight(height: number|string): JQuery; - + /** * Get the current computed width for the first element in the set of matched elements, including padding but not border. */ @@ -1466,7 +1466,7 @@ interface JQuery { * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure appended (as a string). */ innerWidth(width: number|string): JQuery; - + /** * Get the current coordinates of the first element in the set of matched elements, relative to the document. */ @@ -1899,7 +1899,7 @@ interface JQuery { /** * Attach a handler to an event for the elements. - * + * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. @@ -1907,14 +1907,14 @@ interface JQuery { bind(eventType: string, eventData: any, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. - * + * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param handler A function to execute each time the event is triggered. */ bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Attach a handler to an event for the elements. - * + * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param eventData An object containing data that will be passed to the event handler. * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. @@ -1922,14 +1922,14 @@ interface JQuery { bind(eventType: string, eventData: any, preventBubble: boolean): JQuery; /** * Attach a handler to an event for the elements. - * + * * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. * @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true. */ bind(eventType: string, preventBubble: boolean): JQuery; /** * Attach a handler to an event for the elements. - * + * * @param events An object containing one or more DOM event types and functions to execute for them. */ bind(events: any): JQuery; @@ -2504,14 +2504,14 @@ interface JQuery { /** * Execute all handlers and behaviors attached to the matched elements for the given event type. - * + * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param extraParameters Additional parameters to pass along to the event handler. */ trigger(eventType: string, extraParameters?: any[]|Object): JQuery; /** * Execute all handlers and behaviors attached to the matched elements for the given event type. - * + * * @param event A jQuery.Event object. * @param extraParameters Additional parameters to pass along to the event handler. */ @@ -2519,7 +2519,7 @@ interface JQuery { /** * Execute all handlers attached to an element for an event. - * + * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param extraParameters An array of additional parameters to pass along to the event handler. */ @@ -2527,7 +2527,7 @@ interface JQuery { /** * Execute all handlers attached to an element for an event. - * + * * @param event A jQuery.Event object. * @param extraParameters An array of additional parameters to pass along to the event handler. */ @@ -2535,21 +2535,21 @@ interface JQuery { /** * Remove a previously-attached event handler from the elements. - * + * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param handler The function that is to be no longer executed. */ unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove a previously-attached event handler from the elements. - * + * * @param eventType A string containing a JavaScript event type, such as click or submit. * @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ). */ unbind(eventType: string, fls: boolean): JQuery; /** * Remove a previously-attached event handler from the elements. - * + * * @param evt A JavaScript event object as passed to an event handler. */ unbind(evt: any): JQuery; @@ -2560,7 +2560,7 @@ interface JQuery { undelegate(): JQuery; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * + * * @param selector A selector which will be used to filter the event results. * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" * @param handler A function to execute at the time the event is triggered. @@ -2568,27 +2568,27 @@ interface JQuery { undelegate(selector: string, eventType: string, handler?: (eventObject: JQueryEventObject) => any): JQuery; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * + * * @param selector A selector which will be used to filter the event results. * @param events An object of one or more event types and previously bound functions to unbind from them. */ undelegate(selector: string, events: Object): JQuery; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. - * + * * @param namespace A string containing a namespace to unbind all events from. */ undelegate(namespace: string): JQuery; /** * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * + * * @param handler A function to execute when the event is triggered. */ unload(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "unload" JavaScript event. (DEPRECATED from v1.8) - * + * * @param eventData A plain object of data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ @@ -2603,13 +2603,13 @@ interface JQuery { /** * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * + * * @param handler A function to execute when the event is triggered. */ error(handler: (eventObject: JQueryEventObject) => any): JQuery; /** * Bind an event handler to the "error" JavaScript event. (DEPRECATED from v1.8) - * + * * @param eventData A plain object of data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ @@ -2617,13 +2617,13 @@ interface JQuery { /** * Add a collection of DOM elements onto the jQuery stack. - * + * * @param elements An array of elements to push onto the stack and make into a new jQuery object. */ pushStack(elements: any[]): JQuery; /** * Add a collection of DOM elements onto the jQuery stack. - * + * * @param elements An array of elements to push onto the stack and make into a new jQuery object. * @param name The name of a jQuery method that generated the array of elements. * @param arguments The arguments that were passed in to the jQuery method (for serialization). @@ -2632,56 +2632,56 @@ interface JQuery { /** * Insert content, specified by the parameter, after each element in the set of matched elements. - * + * * param content1 HTML string, DOM element, DocumentFragment, array of elements, or jQuery object to insert after each element in the set of matched elements. * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements. */ after(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; /** * Insert content, specified by the parameter, after each element in the set of matched elements. - * + * * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. */ after(func: (index: number, html: string) => string|Element|JQuery): JQuery; /** * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * + * * param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements. * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements. */ append(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; /** * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * + * * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. */ append(func: (index: number, html: string) => string|Element|JQuery): JQuery; /** * Insert every element in the set of matched elements to the end of the target. - * + * * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the end of the element(s) specified by this parameter. */ appendTo(target: JQuery|any[]|Element|string): JQuery; /** * Insert content, specified by the parameter, before each element in the set of matched elements. - * + * * param content1 HTML string, DOM element, DocumentFragment, array of elements, or jQuery object to insert before each element in the set of matched elements. * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert before each element in the set of matched elements. */ before(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; /** * Insert content, specified by the parameter, before each element in the set of matched elements. - * + * * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert before each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. */ before(func: (index: number, html: string) => string|Element|JQuery): JQuery; /** * Create a deep copy of the set of matched elements. - * + * * param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false. * param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false). */ @@ -2689,7 +2689,7 @@ interface JQuery { /** * Remove the set of matched elements from the DOM. - * + * * param selector A selector expression that filters the set of matched elements to be removed. */ detach(selector?: string): JQuery; @@ -2701,62 +2701,62 @@ interface JQuery { /** * Insert every element in the set of matched elements after the target. - * + * * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted after the element(s) specified by this parameter. */ insertAfter(target: JQuery|any[]|Element|Text|string): JQuery; /** * Insert every element in the set of matched elements before the target. - * + * * param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements will be inserted before the element(s) specified by this parameter. */ insertBefore(target: JQuery|any[]|Element|Text|string): JQuery; /** * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * + * * param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements. * param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements. */ prepend(content1: JQuery|any[]|Element|DocumentFragment|Text|string, ...content2: any[]): JQuery; /** * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * + * * param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set. */ prepend(func: (index: number, html: string) => string|Element|JQuery): JQuery; /** * Insert every element in the set of matched elements to the beginning of the target. - * + * * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements will be inserted at the beginning of the element(s) specified by this parameter. */ prependTo(target: JQuery|any[]|Element|string): JQuery; /** * Remove the set of matched elements from the DOM. - * + * * @param selector A selector expression that filters the set of matched elements to be removed. */ remove(selector?: string): JQuery; /** * Replace each target element with the set of matched elements. - * + * * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. */ replaceAll(target: JQuery|any[]|Element|string): JQuery; /** * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * + * * param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. */ replaceWith(newContent: JQuery|any[]|Element|Text|string): JQuery; /** * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. - * + * * param func A function that returns content with which to replace the set of matched elements. */ replaceWith(func: () => Element|JQuery): JQuery; @@ -2767,13 +2767,13 @@ interface JQuery { text(): string; /** * Set the content of each element in the set of matched elements to the specified text. - * + * * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation. */ text(text: string|number|boolean): JQuery; /** * Set the content of each element in the set of matched elements to the specified text. - * + * * @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments. */ text(func: (index: number, text: string) => string): JQuery; @@ -2791,20 +2791,20 @@ interface JQuery { /** * Wrap an HTML structure around each element in the set of matched elements. - * + * * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. */ wrap(wrappingElement: JQuery|Element|string): JQuery; /** * Wrap an HTML structure around each element in the set of matched elements. - * + * * @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. */ wrap(func: (index: number) => string|JQuery): JQuery; /** * Wrap an HTML structure around all elements in the set of matched elements. - * + * * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. */ wrapAll(wrappingElement: JQuery|Element|string): JQuery; @@ -2812,27 +2812,27 @@ interface JQuery { /** * Wrap an HTML structure around the content of each element in the set of matched elements. - * + * * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap around the content of the matched elements. */ wrapInner(wrappingElement: JQuery|Element|string): JQuery; /** * Wrap an HTML structure around the content of each element in the set of matched elements. - * + * * @param func A callback function which generates a structure to wrap around the content of the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set. */ wrapInner(func: (index: number) => string): JQuery; /** * Iterate over a jQuery object, executing a function for each matched element. - * + * * @param func A function to execute for each matched element. */ each(func: (index: number, elem: Element) => any): JQuery; /** * Retrieve one of the elements matched by the jQuery object. - * + * * @param index A zero-based integer indicating which element to retrieve. */ get(index: number): HTMLElement; @@ -2848,7 +2848,7 @@ interface JQuery { index(): number; /** * Search for a given element from among the matched elements. - * + * * @param selector A selector representing a jQuery collection in which to look for an element. */ index(selector: string|JQuery|Element): number; @@ -2867,66 +2867,66 @@ interface JQuery { /** * Add elements to the set of matched elements. - * + * * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. * @param context The point in the document at which the selector should begin matching; similar to the context argument of the $(selector, context) method. */ add(selector: string, context?: Element): JQuery; /** * Add elements to the set of matched elements. - * + * * @param elements One or more elements to add to the set of matched elements. */ add(...elements: Element[]): JQuery; /** * Add elements to the set of matched elements. - * + * * @param html An HTML fragment to add to the set of matched elements. */ add(html: string): JQuery; /** * Add elements to the set of matched elements. - * + * * @param obj An existing jQuery object to add to the set of matched elements. */ add(obj: JQuery): JQuery; /** * Get the children of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ children(selector?: string): JQuery; /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * + * * @param selector A string containing a selector expression to match elements against. */ closest(selector: string): JQuery; /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * + * * @param selector A string containing a selector expression to match elements against. * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. */ closest(selector: string, context?: Element): JQuery; /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * + * * @param obj A jQuery object to match elements against. */ closest(obj: JQuery): JQuery; /** * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. - * + * * @param element An element to match elements against. */ closest(element: Element): JQuery; /** * Get an array of all the elements and selectors matched against the current element up through the DOM tree. - * + * * @param selectors An array or string containing a selector expression to match elements against (can also be a jQuery object). * @param context A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead. */ @@ -2944,52 +2944,52 @@ interface JQuery { /** * Reduce the set of matched elements to the one at the specified index. - * + * * @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set. - * + * */ eq(index: number): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. - * + * * @param selector A string containing a selector expression to match the current set of elements against. */ filter(selector: string): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. - * + * * @param func A function used as a test for each element in the set. this is the current DOM element. */ filter(func: (index: number, element: Element) => any): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. - * + * * @param element An element to match the current set of elements against. */ filter(element: Element): JQuery; /** * Reduce the set of matched elements to those that match the selector or pass the function's test. - * + * * @param obj An existing jQuery object to match the current set of elements against. */ filter(obj: JQuery): JQuery; /** * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * + * * @param selector A string containing a selector expression to match elements against. */ find(selector: string): JQuery; /** * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * + * * @param element An element to match elements against. */ find(element: Element): JQuery; /** * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. - * + * * @param obj A jQuery object to match elements against. */ find(obj: JQuery): JQuery; @@ -3001,38 +3001,38 @@ interface JQuery { /** * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * + * * @param selector A string containing a selector expression to match elements against. */ has(selector: string): JQuery; /** * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * + * * @param contained A DOM element to match elements against. */ has(contained: Element): JQuery; /** * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * + * * @param selector A string containing a selector expression to match elements against. */ is(selector: string): boolean; /** * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * + * * @param func A function used as a test for the set of elements. It accepts one argument, index, which is the element's index in the jQuery collection.Within the function, this refers to the current DOM element. */ is(func: (index: number, element: Element) => boolean): boolean; /** * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * + * * @param obj An existing jQuery object to match the current set of elements against. */ is(obj: JQuery): boolean; /** * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. - * + * * @param elements One or more elements to match the current set of elements against. */ is(elements: any): boolean; @@ -3044,42 +3044,42 @@ interface JQuery { /** * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. - * + * * @param callback A function object that will be invoked for each element in the current set. */ map(callback: (index: number, domElement: Element) => any): JQuery; /** * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. - * + * * @param selector A string containing a selector expression to match elements against. */ next(selector?: string): JQuery; /** * Get all following siblings of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ nextAll(selector?: string): JQuery; /** * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * + * * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. * @param filter A string containing a selector expression to match elements against. */ nextUntil(selector?: string, filter?: string): JQuery; /** * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * + * * @param element A DOM node or jQuery object indicating where to stop matching following sibling elements. * @param filter A string containing a selector expression to match elements against. */ nextUntil(element?: Element, filter?: string): JQuery; /** * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. - * + * * @param obj A DOM node or jQuery object indicating where to stop matching following sibling elements. * @param filter A string containing a selector expression to match elements against. */ @@ -3087,25 +3087,25 @@ interface JQuery { /** * Remove elements from the set of matched elements. - * + * * @param selector A string containing a selector expression to match elements against. */ not(selector: string): JQuery; /** * Remove elements from the set of matched elements. - * + * * @param func A function used as a test for each element in the set. this is the current DOM element. */ not(func: (index: number, element: Element) => boolean): JQuery; /** * Remove elements from the set of matched elements. - * + * * @param elements One or more DOM elements to remove from the matched set. */ not(elements: Element|Element[]): JQuery; /** * Remove elements from the set of matched elements. - * + * * @param obj An existing jQuery object to match the current set of elements against. */ not(obj: JQuery): JQuery; @@ -3117,35 +3117,35 @@ interface JQuery { /** * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ parent(selector?: string): JQuery; /** * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ parents(selector?: string): JQuery; /** * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. * @param filter A string containing a selector expression to match elements against. */ parentsUntil(selector?: string, filter?: string): JQuery; /** * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param element A DOM node or jQuery object indicating where to stop matching ancestor elements. * @param filter A string containing a selector expression to match elements against. */ parentsUntil(element?: Element, filter?: string): JQuery; /** * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param obj A DOM node or jQuery object indicating where to stop matching ancestor elements. * @param filter A string containing a selector expression to match elements against. */ @@ -3153,35 +3153,35 @@ interface JQuery { /** * Get the immediately preceding sibling of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ prev(selector?: string): JQuery; /** * Get all preceding siblings of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ prevAll(selector?: string): JQuery; /** * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. * @param filter A string containing a selector expression to match elements against. */ prevUntil(selector?: string, filter?: string): JQuery; /** * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param element A DOM node or jQuery object indicating where to stop matching preceding sibling elements. * @param filter A string containing a selector expression to match elements against. */ prevUntil(element?: Element, filter?: string): JQuery; /** * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. - * + * * @param obj A DOM node or jQuery object indicating where to stop matching preceding sibling elements. * @param filter A string containing a selector expression to match elements against. */ @@ -3189,14 +3189,14 @@ interface JQuery { /** * Get the siblings of each element in the set of matched elements, optionally filtered by a selector. - * + * * @param selector A string containing a selector expression to match elements against. */ siblings(selector?: string): JQuery; /** * Reduce the set of matched elements to a subset specified by a range of indices. - * + * * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, it indicates an offset from the end of the set. * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. */ @@ -3204,32 +3204,32 @@ interface JQuery { /** * Show the queue of functions to be executed on the matched elements. - * + * * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. */ queue(queueName?: string): any[]; /** * Manipulate the queue of functions to be executed, once for each matched element. - * + * * @param newQueue An array of functions to replace the current queue contents. */ queue(newQueue: Function[]): JQuery; /** * Manipulate the queue of functions to be executed, once for each matched element. - * + * * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. */ queue(callback: Function): JQuery; /** * Manipulate the queue of functions to be executed, once for each matched element. - * + * * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. * @param newQueue An array of functions to replace the current queue contents. */ queue(queueName: string, newQueue: Function[]): JQuery; /** * Manipulate the queue of functions to be executed, once for each matched element. - * + * * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. * @param callback The new function to add to the queue, with a function to call that will dequeue the next item. */ diff --git a/jsoneditor/jsoneditor.d.ts b/jsoneditor/jsoneditor.d.ts index ea68a751a4..175c295df6 100644 --- a/jsoneditor/jsoneditor.d.ts +++ b/jsoneditor/jsoneditor.d.ts @@ -3,7 +3,7 @@ // Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'jsoneditor' { export interface JSONEditorNode { diff --git a/jsoneditor/tsconfig.json b/jsoneditor/tsconfig.json new file mode 100644 index 0000000000..ac1de683cd --- /dev/null +++ b/jsoneditor/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "jsoneditor.d.ts", + "jsoneditor-tests.ts" + ] +} \ No newline at end of file diff --git a/jsuite/jsuite.d.ts b/jsuite/jsuite.d.ts index 2d32c88e68..0b00b0277d 100644 --- a/jsuite/jsuite.d.ts +++ b/jsuite/jsuite.d.ts @@ -3,8 +3,8 @@ // Definitions by: Darren Hill // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// interface Iconfig { logging?: boolean; diff --git a/jsuite/tsconfig.json b/jsuite/tsconfig.json new file mode 100644 index 0000000000..0742f18c9f --- /dev/null +++ b/jsuite/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "jsuite.d.ts" + ] +} \ No newline at end of file diff --git a/karma-chai-sinon/karma-chai-sinon-tests.ts b/karma-chai-sinon/karma-chai-sinon-tests.ts new file mode 100644 index 0000000000..b60f5d278f --- /dev/null +++ b/karma-chai-sinon/karma-chai-sinon-tests.ts @@ -0,0 +1,4 @@ +should.not.equal(1, 2); +expect(1 === 1); +assert.isTrue(true); +sinon.spy(); diff --git a/karma-chai-sinon/karma-chai-sinon.d.ts b/karma-chai-sinon/karma-chai-sinon.d.ts index 059a1b80ef..4d44d0ce2d 100644 --- a/karma-chai-sinon/karma-chai-sinon.d.ts +++ b/karma-chai-sinon/karma-chai-sinon.d.ts @@ -3,10 +3,12 @@ // Definitions by: Václav Ostrožlík // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// -/// +/// +import Sinon = require("Sinon"); -declare var should: Chai.Should; -declare var expect: Chai.ExpectStatic; -declare var assert: Chai.AssertStatic; -declare var sinon: Sinon.SinonStatic; +declare global { + var should: Chai.Should; + var expect: Chai.ExpectStatic; + var assert: Chai.AssertStatic; + var sinon: Sinon.SinonStatic; +} diff --git a/karma-chai-sinon/tsconfig.json b/karma-chai-sinon/tsconfig.json new file mode 100644 index 0000000000..aef2986498 --- /dev/null +++ b/karma-chai-sinon/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "karma-chai-sinon.d.ts", + "karma-chai-sinon-tests.ts" + ] +} \ No newline at end of file diff --git a/koa-compress/koa-compress-tests.ts b/koa-compress/koa-compress-tests.ts index 564fd53e2c..30195cd30c 100644 --- a/koa-compress/koa-compress-tests.ts +++ b/koa-compress/koa-compress-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as Koa from "koa"; import compress = require("koa-compress"); diff --git a/koa-compress/koa-compress.d.ts b/koa-compress/koa-compress.d.ts index 49a0bb5f1b..d66cd14df4 100644 --- a/koa-compress/koa-compress.d.ts +++ b/koa-compress/koa-compress.d.ts @@ -12,8 +12,8 @@ app.use(compress()); =============================================== */ -/// -/// +/// +/// declare module "koa-compress" { @@ -31,7 +31,7 @@ declare module "koa-compress" { */ threshold?: number } - + /** * Compress middleware for Koa */ diff --git a/koa-compress/tsconfig.json b/koa-compress/tsconfig.json new file mode 100644 index 0000000000..05c84b0a3a --- /dev/null +++ b/koa-compress/tsconfig.json @@ -0,0 +1,19 @@ +{ + "files": [ + "koa-compress.d.ts", + "koa-compress-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/koa-hbs/koa-hbs-tests.ts b/koa-hbs/koa-hbs-tests.ts index 373c3ab8b9..647eee7f22 100644 --- a/koa-hbs/koa-hbs-tests.ts +++ b/koa-hbs/koa-hbs-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as Hbs from 'koa-hbs'; import * as Koa from 'koa'; import * as Path from 'path'; diff --git a/koa-hbs/koa-hbs.d.ts b/koa-hbs/koa-hbs.d.ts index cd8fc9c5b4..8adfeaf20f 100644 --- a/koa-hbs/koa-hbs.d.ts +++ b/koa-hbs/koa-hbs.d.ts @@ -23,7 +23,7 @@ =============================================== */ -/// +/// declare module "koa-hbs" { @@ -40,7 +40,7 @@ declare module "koa-hbs" { layoutsPath?: string, contentHelperName?: string, blockHelperName?: string, - disableCache?: boolean + disableCache?: boolean } } diff --git a/koa-hbs/tsconfig.json b/koa-hbs/tsconfig.json new file mode 100644 index 0000000000..c20e3481c9 --- /dev/null +++ b/koa-hbs/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "koa-hbs.d.ts", + "koa-hbs-tests.ts" + ] +} \ No newline at end of file diff --git a/koa-json-error/index.d.ts b/koa-json-error/index.d.ts new file mode 100644 index 0000000000..cf45c1cc08 --- /dev/null +++ b/koa-json-error/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for koa-json-error v3.x +// Project: https://github.com/koajs/json-error +// Definitions by: Mudkip +// Definitions: https://github.com/mudkipme/DefinitelyTyped + +import * as Koa from "koa"; + +interface JSONErrorOptions { + /** + * Perform some task before calling `options.format`. Must be a function with the original err as its only argument. + */ + preFormat?: { (err: Error): any }; + + /** + * Runs inmediatly after `options.preFormat`. It receives two arguments: the original `err` and the output of `options.preFormat`. It should `return` a newly formatted error. + */ + format?: { (err: Error, obj: any): any }; + + /** + * Runs inmediatly after `options.format`. It receives two arguments: the original `err` and the output of `options.format`. It should `return` a newly formatted error. + */ + postFormat?: { (err: Error, obj: any): any }; +} + +/** + * Error handler for pure Koa 2.0.0+ JSON apps + */ +declare function jsonError(options?: JSONErrorOptions) : { (ctx: Koa.Context, next?: () => any): any }; + +declare namespace jsonError {} +export = jsonError; diff --git a/koa-json-error/koa-json-error-tests.ts b/koa-json-error/koa-json-error-tests.ts index 37aae696b0..07ac0fd129 100644 --- a/koa-json-error/koa-json-error-tests.ts +++ b/koa-json-error/koa-json-error-tests.ts @@ -1,7 +1,3 @@ -/// -/// -/// - import * as Koa from "koa"; import * as error from "koa-json-error"; import { assign } from "lodash"; diff --git a/koa-json-error/koa-json-error.d.ts b/koa-json-error/koa-json-error.d.ts deleted file mode 100644 index 491ead463e..0000000000 --- a/koa-json-error/koa-json-error.d.ts +++ /dev/null @@ -1,36 +0,0 @@ -// Type definitions for koa-json-error v3.x -// Project: https://github.com/koajs/json-error -// Definitions by: Mudkip -// Definitions: https://github.com/mudkipme/DefinitelyTyped - -/// - -declare module "koa-json-error" { - - import * as Koa from "koa"; - - interface JSONErrorOptions { - /** - * Perform some task before calling `options.format`. Must be a function with the original err as its only argument. - */ - preFormat?: { (err: Error): any }; - - /** - * Runs inmediatly after `options.preFormat`. It receives two arguments: the original `err` and the output of `options.preFormat`. It should `return` a newly formatted error. - */ - format?: { (err: Error, obj: any): any }; - - /** - * Runs inmediatly after `options.format`. It receives two arguments: the original `err` and the output of `options.format`. It should `return` a newly formatted error. - */ - postFormat?: { (err: Error, obj: any): any }; - } - - /** - * Error handler for pure Koa 2.0.0+ JSON apps - */ - function jsonError(options?: JSONErrorOptions) : { (ctx: Koa.Context, next?: () => any): any }; - - namespace jsonError {} - export = jsonError; -} \ No newline at end of file diff --git a/koa-json-error/tsconfig.json b/koa-json-error/tsconfig.json new file mode 100644 index 0000000000..92f9d5ce58 --- /dev/null +++ b/koa-json-error/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-json-error-tests.ts" + ] +} \ No newline at end of file diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts index c6519ab371..daf6d20bd6 100644 --- a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts @@ -1,6 +1,3 @@ -/// -/// - var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', osmAttrib = '© OpenStreetMap contributors', osm = L.tileLayer(osmUrl, {maxZoom: 18, attribution: osmAttrib}), diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts index 8809472e43..17c78c0837 100644 --- a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts @@ -3,8 +3,7 @@ // Definitions by: Leonard Lausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// +/// declare namespace L { namespace Control { diff --git a/leaflet-geocoder-mapzen/tsconfig.json b/leaflet-geocoder-mapzen/tsconfig.json new file mode 100644 index 0000000000..eb59fde803 --- /dev/null +++ b/leaflet-geocoder-mapzen/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "leaflet-geocoder-mapzen.d.ts", + "leaflet-geocoder-mapzen-tests.ts" + ] +} \ No newline at end of file diff --git a/libxslt/index.d.ts b/libxslt/index.d.ts new file mode 100644 index 0000000000..329525d7df --- /dev/null +++ b/libxslt/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for node-libxslt +// Project: https://github.com/albanm/node-libxslt +// Definitions by: Alejandro Sánchez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as xmljs from 'libxmljs'; + +export const libxmljs: typeof xmljs; + +type OutputFormat = 'document' | 'string'; + +export interface ApplyOptions { + outputFormat?: OutputFormat; + noWrapParams?: boolean; +} + +type ApplyResult = string | xmljs.XMLDocument; + +type ApplyCallback = (err: Error, result: ApplyResult) => void; + +type ApplyStringCallback = (err: Error, result: string) => void; + +type ApplyDocumentCallback = (err: Error, result: xmljs.XMLDocument) => void; + +export interface Stylesheet { + apply(source: string, params?: Object): string; + + apply(source: string, params: Object, options: ApplyOptions): ApplyResult; + + apply(source: string, params: Object, options: ApplyOptions, callback: ApplyCallback): void; + + apply(source: string, callback: ApplyStringCallback): void; + + apply(source: xmljs.XMLDocument, params?: Object): xmljs.XMLDocument; + + apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions): ApplyResult; + + apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions, callback: ApplyCallback): void; + + apply(source: xmljs.XMLDocument, callback: ApplyDocumentCallback): void; + + applyToFile(sourcePath: string, params: Object, options: ApplyOptions, callback: ApplyStringCallback): void; + + applyToFile(sourcePath: string, callback: ApplyStringCallback): void; +} + +type ParseCallback = (err: Error, stylesheet: Stylesheet) => void; + +export function parse(source: string): Stylesheet; + +export function parse(source: string, callback: ParseCallback): void; + +export function parse(source: xmljs.XMLDocument): Stylesheet; + +export function parse(source: xmljs.XMLDocument, callback: ParseCallback): void; + +export function parseFile(sourcePath: string, callback: ParseCallback): void; diff --git a/libxslt/libxslt-tests.ts b/libxslt/libxslt-tests.ts index 544269b11e..bed54e5f52 100644 --- a/libxslt/libxslt-tests.ts +++ b/libxslt/libxslt-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as libxslt from 'libxslt'; import * as libxmljs from 'libxmljs'; diff --git a/libxslt/libxslt.d.ts b/libxslt/libxslt.d.ts deleted file mode 100644 index 0cfd4e1bcd..0000000000 --- a/libxslt/libxslt.d.ts +++ /dev/null @@ -1,61 +0,0 @@ -// Type definitions for node-libxslt -// Project: https://github.com/albanm/node-libxslt -// Definitions by: Alejandro Sánchez -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'libxslt' { - import * as xmljs from 'libxmljs'; - - export const libxmljs: typeof xmljs; - - type OutputFormat = 'document' | 'string'; - - export interface ApplyOptions { - outputFormat?: OutputFormat; - noWrapParams?: boolean; - } - - type ApplyResult = string | xmljs.XMLDocument; - - type ApplyCallback = (err: Error, result: ApplyResult) => void; - - type ApplyStringCallback = (err: Error, result: string) => void; - - type ApplyDocumentCallback = (err: Error, result: xmljs.XMLDocument) => void; - - export interface Stylesheet { - apply(source: string, params?: Object): string; - - apply(source: string, params: Object, options: ApplyOptions): ApplyResult; - - apply(source: string, params: Object, options: ApplyOptions, callback: ApplyCallback): void; - - apply(source: string, callback: ApplyStringCallback): void; - - apply(source: xmljs.XMLDocument, params?: Object): xmljs.XMLDocument; - - apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions): ApplyResult; - - apply(source: xmljs.XMLDocument, params: Object, options: ApplyOptions, callback: ApplyCallback): void; - - apply(source: xmljs.XMLDocument, callback: ApplyDocumentCallback): void; - - applyToFile(sourcePath: string, params: Object, options: ApplyOptions, callback: ApplyStringCallback): void; - - applyToFile(sourcePath: string, callback: ApplyStringCallback): void; - } - - type ParseCallback = (err: Error, stylesheet: Stylesheet) => void; - - export function parse(source: string): Stylesheet; - - export function parse(source: string, callback: ParseCallback): void; - - export function parse(source: xmljs.XMLDocument): Stylesheet; - - export function parse(source: xmljs.XMLDocument, callback: ParseCallback): void; - - export function parseFile(sourcePath: string, callback: ParseCallback): void; -} diff --git a/libxslt/tsconfig.json b/libxslt/tsconfig.json new file mode 100644 index 0000000000..bcc8d2d059 --- /dev/null +++ b/libxslt/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "libxslt-tests.ts" + ] +} \ No newline at end of file diff --git a/marker-animate-unobtrusive/marker-animate-unobtrusive-amd-tests.ts b/marker-animate-unobtrusive/marker-animate-unobtrusive-amd-tests.ts index 544c95af5a..f86619fc90 100644 --- a/marker-animate-unobtrusive/marker-animate-unobtrusive-amd-tests.ts +++ b/marker-animate-unobtrusive/marker-animate-unobtrusive-amd-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import SlidingMarker = require('SlidingMarker'); import MarkerWithGhost = require('MarkerWithGhost'); diff --git a/marker-animate-unobtrusive/marker-animate-unobtrusive-tests.ts b/marker-animate-unobtrusive/marker-animate-unobtrusive-tests.ts index 73ad4da4b5..d2effcf94d 100644 --- a/marker-animate-unobtrusive/marker-animate-unobtrusive-tests.ts +++ b/marker-animate-unobtrusive/marker-animate-unobtrusive-tests.ts @@ -1,6 +1,3 @@ -/// -/// - function test_init() { SlidingMarker.initializeGlobally(); MarkerWithGhost.initializeGlobally(); @@ -43,7 +40,7 @@ function test_marker_with_ghost() { var g = new MarkerWithGhost(); slidingMarker = g; - + g.setGhostPosition(p); p = g.getGhostPosition(); p = g.getGhostAnimationPosition(); diff --git a/marker-animate-unobtrusive/marker-animate-unobtrusive.d.ts b/marker-animate-unobtrusive/marker-animate-unobtrusive.d.ts index 61a4a680df..0be3d83c8a 100644 --- a/marker-animate-unobtrusive/marker-animate-unobtrusive.d.ts +++ b/marker-animate-unobtrusive/marker-animate-unobtrusive.d.ts @@ -3,7 +3,7 @@ // Definitions by: Roman Viskin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace jQuery.easing { type IEasingType = diff --git a/marker-animate-unobtrusive/tsconfig.json b/marker-animate-unobtrusive/tsconfig.json new file mode 100644 index 0000000000..3961120707 --- /dev/null +++ b/marker-animate-unobtrusive/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "marker-animate-unobtrusive.d.ts", + "marker-animate-unobtrusive-tests.ts", + "marker-animate-unobtrusive-amd-tests.ts" + ] +} \ No newline at end of file diff --git a/masonry-layout/masonry-layout.d.ts b/masonry-layout/masonry-layout.d.ts index a76796096b..41753358c9 100644 --- a/masonry-layout/masonry-layout.d.ts +++ b/masonry-layout/masonry-layout.d.ts @@ -1,42 +1,42 @@ -// Type definitions for Masonry 4.0.0 -// Project: https://github.com/desandro/masonry +// Type definitions for Masonry 4.0.0 +// Project: https://github.com/desandro/masonry // Definitions by: Mark Wilson -// Definitions: https://github.com/borisyankov/DefinitelyTyped +// Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// -// Modified from original definitions by: +// 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); - } + class Masonry implements MasonryGrid { + constructor(options?: MasonryOptions); + constructor(selector: string, options?: MasonryOptions); + } interface MasonryGrid { masonry?(): void; masonry?(eventName: string, listener: any): void; - // layout + // layout layout?(): void; layoutItems?(items: Array, isStill?: boolean): void; stamp?(elements: Array): void; unstamp?(elements: Array): void; - // add and remove items + // add and remove items appended?(elements: Array): void; prepended?(elements: Array): void; addItems?(elements: Array): void; remove?(elements: Array): void; - // events + // events on?(eventName: string, listener: any): void; off?(eventName: string, listener: any): void; once?(eventName: string, listener: any): void; - // utilities + // utilities reloadItems?(): void; destroy?(): void; getItemElements?(): Array; @@ -45,7 +45,7 @@ declare module Masonry { interface MasonryOptions { - // layout + // layout itemSelector?: string; columnWidth?: any; percentPosition?: boolean; @@ -55,7 +55,7 @@ declare module Masonry { originLeft?: boolean; originTop?: boolean; - // setup + // setup containerStyle?: Object; transitionDuration?: any; resize?: boolean; diff --git a/masonry-layout/tsconfig.json b/masonry-layout/tsconfig.json new file mode 100644 index 0000000000..0638ecd09d --- /dev/null +++ b/masonry-layout/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "masonry-layout.d.ts", + "masonry-layout-tests.ts" + ] +} \ No newline at end of file diff --git a/mitm/mitm-tests.ts b/mitm/mitm-tests.ts index 00abe30b1a..e528cf86cb 100644 --- a/mitm/mitm-tests.ts +++ b/mitm/mitm-tests.ts @@ -1,5 +1,3 @@ -/// - import Mitm = require('mitm'); const mitm = Mitm(); diff --git a/mitm/mitm.d.ts b/mitm/mitm.d.ts index 2c5f03f8bc..0cd0d32aeb 100644 --- a/mitm/mitm.d.ts +++ b/mitm/mitm.d.ts @@ -3,7 +3,7 @@ // Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'mitm' { import * as http from 'http'; @@ -11,10 +11,10 @@ declare module 'mitm' { interface SocketOptions { port: number; - host?: string; + host?: string; localAddress?: string; - localPort?: string; - family?: number; + localPort?: string; + family?: number; allowHalfOpen?: boolean; } @@ -25,7 +25,7 @@ declare module 'mitm' { type SocketConnectCallback = (socket: BypassableSocket, opts: SocketOptions) => void; type SocketConnectionCallback = (socket: net.Socket, opts: SocketOptions) => void; - + type HttpCallback = (request: http.IncomingMessage, response: http.ServerResponse) => void; type Event = 'connect' | 'connection' | 'request'; diff --git a/mitm/tsconfig.json b/mitm/tsconfig.json new file mode 100644 index 0000000000..e14e440597 --- /dev/null +++ b/mitm/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "mitm.d.ts", + "mitm-tests.ts" + ] +} \ No newline at end of file diff --git a/mongoose-paginate/mongoose-paginate-tests.ts b/mongoose-paginate/mongoose-paginate-tests.ts index 42fc42be69..d541c44da8 100644 --- a/mongoose-paginate/mongoose-paginate-tests.ts +++ b/mongoose-paginate/mongoose-paginate-tests.ts @@ -1,6 +1,4 @@ -/// -/// -/// +/// /** * Created by Linus Brolin . diff --git a/mongoose-paginate/mongoose-paginate.d.ts b/mongoose-paginate/mongoose-paginate.d.ts index ed8b07a2fa..6b06c65ac5 100644 --- a/mongoose-paginate/mongoose-paginate.d.ts +++ b/mongoose-paginate/mongoose-paginate.d.ts @@ -3,7 +3,7 @@ // Definitions by: Linus Brolin , simonxca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'mongoose' { export interface PaginateOptions { diff --git a/mongoose-paginate/tsconfig.json b/mongoose-paginate/tsconfig.json new file mode 100644 index 0000000000..6cd106d699 --- /dev/null +++ b/mongoose-paginate/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "mongoose-paginate.d.ts", + "mongoose-paginate-tests.ts" + ] +} \ No newline at end of file diff --git a/multer-s3/multer-s3-tests.ts b/multer-s3/multer-s3-tests.ts index 2b761238f7..413ba6e313 100644 --- a/multer-s3/multer-s3-tests.ts +++ b/multer-s3/multer-s3-tests.ts @@ -1,5 +1,3 @@ -/// - "use strict"; let accessKeyId: string diff --git a/multer-s3/multer-s3.d.ts b/multer-s3/multer-s3.d.ts index 1844f3decd..1c1aa792c1 100644 --- a/multer-s3/multer-s3.d.ts +++ b/multer-s3/multer-s3.d.ts @@ -3,8 +3,8 @@ // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk // Definitions: https://github.com/DefinitelyType/DefinitelyTyped -/// -/// +/// +/// declare module "multer-s3" { import * as AWS from "aws-sdk" diff --git a/multer-s3/tsconfig.json b/multer-s3/tsconfig.json new file mode 100644 index 0000000000..04e16429ee --- /dev/null +++ b/multer-s3/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "multer-s3.d.ts", + "multer-s3-tests.ts" + ] +} \ No newline at end of file diff --git a/multer/index.d.ts b/multer/index.d.ts index 761a8dce49..2437f498db 100644 --- a/multer/index.d.ts +++ b/multer/index.d.ts @@ -81,34 +81,36 @@ declare var multer: Multer; export = multer; -declare namespace Express { - export interface Request { - file: Multer.File; - files: { - [fieldname: string]: Multer.File[]; - }; - } +declare global { + namespace Express { + export interface Request { + file: Multer.File; + files: { + [fieldname: string]: Multer.File[]; + }; + } - namespace Multer { - export interface File { - /** Field name specified in the form */ - fieldname: string; - /** Name of the file on the user's computer */ - originalname: string; - /** Encoding type of the file */ - encoding: string; - /** Mime type of the file */ - mimetype: string; - /** Size of the file in bytes */ - size: number; - /** The folder to which the file has been saved (DiskStorage) */ - destination: string; - /** The name of the file within the destination (DiskStorage) */ - filename: string; - /** Location of the uploaded file (DiskStorage) */ - path: string; - /** A Buffer of the entire file (MemoryStorage) */ - buffer: Buffer; + namespace Multer { + export interface File { + /** Field name specified in the form */ + fieldname: string; + /** Name of the file on the user's computer */ + originalname: string; + /** Encoding type of the file */ + encoding: string; + /** Mime type of the file */ + mimetype: string; + /** Size of the file in bytes */ + size: number; + /** The folder to which the file has been saved (DiskStorage) */ + destination: string; + /** The name of the file within the destination (DiskStorage) */ + filename: string; + /** Location of the uploaded file (DiskStorage) */ + path: string; + /** A Buffer of the entire file (MemoryStorage) */ + buffer: Buffer; + } } } -} +} \ No newline at end of file diff --git a/musicmetadata/musicmetadata-tests.ts b/musicmetadata/musicmetadata-tests.ts index bc99ba0900..421aec3bc5 100644 --- a/musicmetadata/musicmetadata-tests.ts +++ b/musicmetadata/musicmetadata-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as fs from "fs"; import * as mm from "musicmetadata"; diff --git a/musicmetadata/musicmetadata.d.ts b/musicmetadata/musicmetadata.d.ts index 0e951f8d08..c1ff45741f 100644 --- a/musicmetadata/musicmetadata.d.ts +++ b/musicmetadata/musicmetadata.d.ts @@ -3,7 +3,7 @@ // Definitions by: Xavier Stouder // Definitions: https://github.com/DefinitelyTyped/ -/// +/// declare module "musicmetadata" { import {Readable} from "stream"; diff --git a/musicmetadata/tsconfig.json b/musicmetadata/tsconfig.json new file mode 100644 index 0000000000..d403132a8d --- /dev/null +++ b/musicmetadata/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "musicmetadata.d.ts", + "musicmetadata-tests.ts" + ] +} \ No newline at end of file diff --git a/nes/nes-tests.ts b/nes/nes-tests.ts index d56b42a8c4..effe4e6c94 100644 --- a/nes/nes-tests.ts +++ b/nes/nes-tests.ts @@ -1,5 +1,3 @@ -/// - import Hapi = require('hapi'); import Nes = require('nes'); @@ -29,8 +27,8 @@ server.register(Nes, (regErr: any) => { } else { setTimeout(() => { wsServer.publish('/item/5', { id: 5, status: 'complete' }); - wsServer.publish('/item/6', { id: 6, status: 'initial' }); - }, 100); + wsServer.publish('/item/6', { id: 6, status: 'initial' }); + }, 100); } }); } diff --git a/nes/nes.d.ts b/nes/nes.d.ts index c86627db47..f6159be9b0 100644 --- a/nes/nes.d.ts +++ b/nes/nes.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'nes' { import Hapi = require('hapi'); diff --git a/nes/tsconfig.json b/nes/tsconfig.json new file mode 100644 index 0000000000..c0b45f689b --- /dev/null +++ b/nes/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "nes.d.ts", + "nes-tests.ts" + ] +} \ No newline at end of file diff --git a/ngmap/ngmap-tests.ts b/ngmap/ngmap-tests.ts index f1909a2b1b..b78ff9071a 100644 --- a/ngmap/ngmap-tests.ts +++ b/ngmap/ngmap-tests.ts @@ -1,4 +1,3 @@ -/// class NgMapTestController { constructor(public $scope: ng.IScope, public $window: ng.IWindowService, public NgMap: angular.map.INgMap) { this.showMap(); @@ -17,9 +16,9 @@ app.config(function(NgMapProvider: angular.map.INgMapProvider) { NgMapProvider.setDefaultOptions({ marker: { optimized: false - } + } }); }); -app.controller('testCtrl', ['$scope', '$window', 'ngMap', +app.controller('testCtrl', ['$scope', '$window', 'ngMap', ($scope: ng.IScope, $window: ng.IWindowService, NgMap: angular.map.INgMap) => new NgMapTestController($scope, $window, NgMap)]); \ No newline at end of file diff --git a/ngmap/ngmap.d.ts b/ngmap/ngmap.d.ts index 38c237abd1..23e596c88e 100644 --- a/ngmap/ngmap.d.ts +++ b/ngmap/ngmap.d.ts @@ -3,8 +3,8 @@ // Definitions by: Niko Kovačič // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module "ngmap" { let _: string; @@ -45,7 +45,7 @@ declare namespace angular.map { */ icon?: string|google.maps.Icon|google.maps.Symbol; /** - * Adds a label to the marker. The label can either be a string, or a MarkerLabel object. + * Adds a label to the marker. The label can either be a string, or a MarkerLabel object. * Only the first character of the string will be displayed. * @type {string} */ @@ -94,7 +94,7 @@ declare namespace angular.map { addMap(mapCtrl: Function | any[]): void; /** * Delete map from pool - * @param {Function | any[]} mapCtrl Map controller optional. Defaults to last + * @param {Function | any[]} mapCtrl Map controller optional. Defaults to last * controller in pool */ deleteMap(mapCtrl?: Function | any[]): void; @@ -104,13 +104,13 @@ declare namespace angular.map { * @param {PositionOptions} options optional * @return {angular.IPromise} Latitude ang longitude of the address */ - getGeoLocation(address: string, options?: PositionOptions): angular.IPromise + getGeoLocation(address: string, options?: PositionOptions): ng.IPromise /** * Get map from the pool of all shown maps. * @param {IGetMapOptions} options optional * @return {angular.IPromise} promise */ - getMap(options?: IGetMapOptions): angular.IPromise + getMap(options?: IGetMapOptions): ng.IPromise /** * Initialize map from mapId or the current first shown map * @param {string} mapId id of the map. default 0 @@ -123,7 +123,7 @@ declare namespace angular.map { * @param {Object} object a Google maps object to be changed * @return {IObserveAndSetFunc} attribute obvserve function */ - observeAndSet(attrName: string, object: Object): IObserveAndSetFunc; + observeAndSet(attrName: string, object: Object): IObserveAndSetFunc; /** * Set display, width, height of map container element * @param {HTMLElement} el map container element diff --git a/ngmap/tsconfig.json b/ngmap/tsconfig.json new file mode 100644 index 0000000000..d86f53d20a --- /dev/null +++ b/ngmap/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "ngmap.d.ts", + "ngmap-tests.ts" + ] +} \ No newline at end of file diff --git a/ngreact/ngreact-tests.tsx b/ngreact/ngreact-tests.tsx index 013e3f2f6b..46980dab1f 100644 --- a/ngreact/ngreact-tests.tsx +++ b/ngreact/ngreact-tests.tsx @@ -1,6 +1,4 @@ -/// -/// - +import * as angular from "angular"; import * as React from "react"; import { ReactDirective } from "ngreact"; @@ -22,7 +20,7 @@ app.directive('hello', function(reactDirective: ReactDirective) { return reactDirective(HelloComponent, undefined, {restrict: 'C'}); }); -app.directive('helloComponent', function(reactDirective: ReactDirective, $location: ng.ILocationService) { +app.directive('helloComponent', function(reactDirective: ReactDirective, $location: angular.ILocationService) { return reactDirective(HelloComponent, undefined, {}, { $location }); }); diff --git a/ngreact/ngreact.d.ts b/ngreact/ngreact.d.ts index 9c3ecbec11..f9df0f694f 100644 --- a/ngreact/ngreact.d.ts +++ b/ngreact/ngreact.d.ts @@ -3,11 +3,11 @@ // Definitions by: Vicky Lai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module "ngreact" { - type ReactDirective = (reactComponentName: string | __React.ComponentClass, + type ReactDirective = (reactComponentName: string | React.ComponentClass, propNames?: string[], conf?: Object, injectableProps?: Object) => angular.IDirective; diff --git a/ngreact/tsconfig.json b/ngreact/tsconfig.json new file mode 100644 index 0000000000..1b80eaf055 --- /dev/null +++ b/ngreact/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "ngreact.d.ts", + "ngreact-tests.tsx" + ] +} \ No newline at end of file diff --git a/node-usb/node-usb-tests.ts b/node-usb/node-usb-tests.ts index 9abef86ee8..85da346172 100644 --- a/node-usb/node-usb-tests.ts +++ b/node-usb/node-usb-tests.ts @@ -1,5 +1,3 @@ -/// - import * as usb from "usb"; const device = new usb.Device(); diff --git a/node-usb/node-usb.d.ts b/node-usb/node-usb.d.ts index b8d1611a51..78b93bbfd9 100644 --- a/node-usb/node-usb.d.ts +++ b/node-usb/node-usb.d.ts @@ -3,7 +3,7 @@ // Definitions by: Eric Brody // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module "usb" { diff --git a/node-usb/tsconfig.json b/node-usb/tsconfig.json new file mode 100644 index 0000000000..8b33ce72d6 --- /dev/null +++ b/node-usb/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "node-usb.d.ts", + "node-usb-tests.ts" + ] +} \ No newline at end of file diff --git a/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts b/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts index 1cbd06929b..c2135c2ec6 100644 --- a/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts +++ b/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts @@ -1,7 +1,5 @@ -/// -/// - import * as AWS from 'aws-sdk'; +import * as nodemailer from "nodemailer"; import * as sesTransport from 'nodemailer-ses-transport'; var opts: sesTransport.SesOptions = { diff --git a/nodemailer-ses-transport/nodemailer-ses-transport.d.ts b/nodemailer-ses-transport/nodemailer-ses-transport.d.ts index 8ce3d88d69..3ae0911fce 100644 --- a/nodemailer-ses-transport/nodemailer-ses-transport.d.ts +++ b/nodemailer-ses-transport/nodemailer-ses-transport.d.ts @@ -3,12 +3,9 @@ // Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// - declare module "nodemailer-ses-transport" { - import * as AWS from 'aws-sdk'; + import * as nodemailer from "nodemailer"; namespace sesTransport { export interface SesOptions { diff --git a/nodemailer-ses-transport/tsconfig.json b/nodemailer-ses-transport/tsconfig.json new file mode 100644 index 0000000000..8aa631bf9a --- /dev/null +++ b/nodemailer-ses-transport/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "nodemailer-ses-transport.d.ts", + "nodemailer-ses-transport-tests.ts" + ] +} \ No newline at end of file diff --git a/notify.js/notify.js.d.ts b/notify.js/notify.js.d.ts index 49fd3415ec..4ba66fa2d0 100644 --- a/notify.js/notify.js.d.ts +++ b/notify.js/notify.js.d.ts @@ -3,129 +3,127 @@ // Definitions by: Bahman Nikkhahan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// -declare namespace NotifyJS { - interface NotificationOptions { - // whether to hide the notification on click - clickToHide: boolean; - // whether to auto-hide the notification - autoHide: boolean; - // if autoHide, hide after milliseconds - autoHideDelay: number; - // show the arrow pointing at the element - arrowShow: boolean; - // arrow size in pixels - arrowSize: number; - // position defines the notification position though uses the defaults below - position: string; - // default positions - elementPosition: string; - globalPosition: string; - // default style - style: string; - // default class (string or [string]) - className: string; - // show animation - showAnimation: string; - // show animation duration - showDuration: number; - // hide animation - hideAnimation: string; - // hide animation duration - hideDuration: number; - // padding between element and notification - gap: number; - } +interface NotificationOptions { + // whether to hide the notification on click + clickToHide: boolean; + // whether to auto-hide the notification + autoHide: boolean; + // if autoHide, hide after milliseconds + autoHideDelay: number; + // show the arrow pointing at the element + arrowShow: boolean; + // arrow size in pixels + arrowSize: number; + // position defines the notification position though uses the defaults below + position: string; + // default positions + elementPosition: string; + globalPosition: string; + // default style + style: string; + // default class (string or [string]) + className: string; + // show animation + showAnimation: string; + // show animation duration + showDuration: number; + // hide animation + hideAnimation: string; + // hide animation duration + hideDuration: number; + // padding between element and notification + gap: number; +} - interface JQueryStaticNotify { - /** - * notify user - * @param element a jquery element - * @param notificationdata global notification data - * @param options notification options - */ - (element?: any, notificationdata?: any, options?: NotificationOptions): JQueryStatic; +interface JQueryStaticNotify { + /** + * notify user + * @param element a jquery element + * @param notificationdata global notification data + * @param options notification options + */ + (element?: any, notificationdata?: any, options?: NotificationOptions): JQueryStatic; - /** - * Add style - * @param styleName style name - * @param styleDefinition style definition object - */ - addStyle(styleName: string, styleDefinition: any): any; + /** + * Add style + * @param styleName style name + * @param styleDefinition style definition object + */ + addStyle(styleName: string, styleDefinition: any): any; - /** - * Remove style - * @param styleName style name - */ - removeStyle(styleName: string): any; + /** + * Remove style + * @param styleName style name + */ + removeStyle(styleName: string): any; - /** - * Get style - * @param styleName style name - */ - getStyle(styleName: string): any; + /** + * Get style + * @param styleName style name + */ + getStyle(styleName: string): any; - /** - * Insert css - * @param cssText css text to insert - */ - insertCSS(cssText: string): any; + /** + * Insert css + * @param cssText css text to insert + */ + insertCSS(cssText: string): any; - /** - * Set defaults for notifications - * @param options notification iptions - */ - defaults(options: NotificationOptions): any; - } + /** + * Set defaults for notifications + * @param options notification iptions + */ + defaults(options: NotificationOptions): any; +} - interface JQueryStatic { - notify: JQueryStaticNotify; - } +interface JQueryStatic { + notify: JQueryStaticNotify; +} - interface JQueryNotify { - /** - * notify user - * @param element a jquery element - * @param notificationdata global notification data - * @param options notification options - */ - (element?: any, notificationdata?: any, options?: NotificationOptions): JQuery; +interface JQueryNotify { + /** + * notify user + * @param element a jquery element + * @param notificationdata global notification data + * @param options notification options + */ + (element?: any, notificationdata?: any, options?: NotificationOptions): JQuery; - /** - * Add style - * @param styleName style name - * @param styleDefinition style definition object - */ - addStyle(styleName: string, styleDefinition: any): any; + /** + * Add style + * @param styleName style name + * @param styleDefinition style definition object + */ + addStyle(styleName: string, styleDefinition: any): any; - /** - * Remove style - * @param styleName style name - */ - removeStyle(styleName: string): any; + /** + * Remove style + * @param styleName style name + */ + removeStyle(styleName: string): any; - /** - * Get style - * @param styleName style name - */ - getStyle(styleName: string): any; + /** + * Get style + * @param styleName style name + */ + getStyle(styleName: string): any; - /** - * Insert css - * @param cssText css text to insert - */ - insertCSS(cssText: string): any; + /** + * Insert css + * @param cssText css text to insert + */ + insertCSS(cssText: string): any; - /** - * Set defaults for notifications - * @param options notification iptions - */ - defaults(options: NotificationOptions): any; + /** + * Set defaults for notifications + * @param options notification iptions + */ + defaults(options: NotificationOptions): any; - } +} - interface JQuery { - notify: JQueryStaticNotify; - } +interface JQuery { + notify: JQueryStaticNotify; } diff --git a/notify.js/notify.js.tests.ts b/notify.js/notify.js.tests.ts index 505f3c4ec5..c824a6b37b 100644 --- a/notify.js/notify.js.tests.ts +++ b/notify.js/notify.js.tests.ts @@ -1,7 +1,4 @@ -/// -/// - -// setting defaults for notification plugin +// setting defaults for notification plugin $.notify.defaults({ clickToHide: true, autoHide: false, diff --git a/notify.js/tsconfig.json b/notify.js/tsconfig.json new file mode 100644 index 0000000000..1c62932129 --- /dev/null +++ b/notify.js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "notify.js.d.ts", + "notify.js.tests.ts" + ] +} \ No newline at end of file diff --git a/nw.js/nw.js-tests.ts b/nw.js/nw.js-tests.ts index 585b7ebe3c..2efee35caa 100644 --- a/nw.js/nw.js-tests.ts +++ b/nw.js/nw.js-tests.ts @@ -1,4 +1,3 @@ -/// /* * nw.App Tests */ diff --git a/nw.js/nw.js.d.ts b/nw.js/nw.js.d.ts index 901d6743f2..7db945dcf6 100644 --- a/nw.js/nw.js.d.ts +++ b/nw.js/nw.js.d.ts @@ -3,7 +3,7 @@ // Definitions by: Alireza Dabiri Nejad // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /** * Helpers class and interfaces defined here, to make `nw` module cleaner. diff --git a/nw.js/tsconfig.json b/nw.js/tsconfig.json new file mode 100644 index 0000000000..63803a69d9 --- /dev/null +++ b/nw.js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "nw.js.d.ts", + "nw.js-tests.ts" + ] +} \ No newline at end of file diff --git a/o.js/o.js-tests.ts b/o.js/o.js-tests.ts index b9ffc1b065..f40a84ac84 100644 --- a/o.js/o.js-tests.ts +++ b/o.js/o.js-tests.ts @@ -1,6 +1,5 @@ -/// - import * as o from 'o.js'; +import * as Q from "q"; interface Product { ID : number; diff --git a/o.js/o.js.d.ts b/o.js/o.js.d.ts index d0d53dce88..eaa6732c40 100644 --- a/o.js/o.js.d.ts +++ b/o.js/o.js.d.ts @@ -3,7 +3,7 @@ // Definitions by: Matteo Antony Mistretta , Brad Zacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'o.js' { interface Options { @@ -29,7 +29,7 @@ declare module 'o.js' { get(callback ?: (data : T) => void) : Q.Promise> save(callback ?: (data : T) => void) : Q.Promise> - + post(params : any) : OHandler patch(params : any) : OHandler put(params : any) : OHandler @@ -38,7 +38,7 @@ declare module 'o.js' { routes(path : string, callback ?: (data : T) => void) : OHandler route(path : string, callback ?: (data : T) => void) : OHandler triggerRoute(hash : string) : OHandler - beforeRouting(callback : (routeParams : any) => boolean) : OHandler + beforeRouting(callback : (routeParams : any) => boolean) : OHandler isEndpoint() : boolean loading(startFn : () => any | boolean, endFn : () => any) : OHandler diff --git a/o.js/tsconfig.json b/o.js/tsconfig.json new file mode 100644 index 0000000000..a630e4dee7 --- /dev/null +++ b/o.js/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "o.js.d.ts", + "o.js-tests.ts" + ] +} \ No newline at end of file diff --git a/passport-local-mongoose/passport-local-mongoose-tests.ts b/passport-local-mongoose/passport-local-mongoose-tests.ts index dcdf08bbe3..7b428561fe 100644 --- a/passport-local-mongoose/passport-local-mongoose-tests.ts +++ b/passport-local-mongoose/passport-local-mongoose-tests.ts @@ -1,8 +1,4 @@ -/// -/// -/// -/// -/// +/// /** * Created by Linus Brolin . diff --git a/passport-local-mongoose/passport-local-mongoose.d.ts b/passport-local-mongoose/passport-local-mongoose.d.ts index ab2539a709..9fafdd2f58 100644 --- a/passport-local-mongoose/passport-local-mongoose.d.ts +++ b/passport-local-mongoose/passport-local-mongoose.d.ts @@ -3,8 +3,8 @@ // Definitions by: Linus Brolin , simonxca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module 'mongoose' { import passportLocal = require('passport-local'); diff --git a/passport-local-mongoose/tsconfig.json b/passport-local-mongoose/tsconfig.json new file mode 100644 index 0000000000..96c1a13bf1 --- /dev/null +++ b/passport-local-mongoose/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "passport-local-mongoose.d.ts", + "passport-local-mongoose-tests.ts" + ] +} \ No newline at end of file diff --git a/pg-pool/pg-pool.d.ts b/pg-pool/pg-pool.d.ts index d25f5a9bb6..e0886d7c52 100644 --- a/pg-pool/pg-pool.d.ts +++ b/pg-pool/pg-pool.d.ts @@ -3,7 +3,7 @@ // Definitions by: Leo Liang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "pg-pool" { export {Pool, PoolConfig} from "pg"; diff --git a/pg-pool/tsconfig.json b/pg-pool/tsconfig.json new file mode 100644 index 0000000000..f7319af50a --- /dev/null +++ b/pg-pool/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "pg-pool.d.ts", + "pg-pool-tests.ts" + ] +} \ No newline at end of file diff --git a/pino/pino-tests.ts b/pino/pino-tests.ts index 4a1470db24..f6c308a706 100644 --- a/pino/pino-tests.ts +++ b/pino/pino-tests.ts @@ -1,5 +1,3 @@ -/// // only for require() -/// // This contains all of the code from the docs on https://www.npmjs.com/package/pino import PINO = require('pino') diff --git a/pino/pino.d.ts b/pino/pino.d.ts index 0a51c49275..9b4ec6d503 100644 --- a/pino/pino.d.ts +++ b/pino/pino.d.ts @@ -3,7 +3,7 @@ // Definitions by: Peter Snider // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// // only for require() +/// declare module 'pino' { diff --git a/pino/tsconfig.json b/pino/tsconfig.json new file mode 100644 index 0000000000..d1c0f04972 --- /dev/null +++ b/pino/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "pino.d.ts", + "pino-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown.d.ts b/pouchdb-adapter-fruitdown/index.d.ts similarity index 93% rename from pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown.d.ts rename to pouchdb-adapter-fruitdown/index.d.ts index e818121543..e1323d55bf 100644 --- a/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown.d.ts +++ b/pouchdb-adapter-fruitdown/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { namespace FruitDOWNAdapter { diff --git a/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown-tests.ts b/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown-tests.ts index ee6f70c59b..810cdc32c1 100644 --- a/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown-tests.ts +++ b/pouchdb-adapter-fruitdown/pouchdb-adapter-fruitdown-tests.ts @@ -1,6 +1,3 @@ -/// -/// - namespace PouchDBAdapterFruitdownTests { function testConstructor() { type MyModel = { numericProperty: number }; diff --git a/pouchdb-adapter-fruitdown/tsconfig.json b/pouchdb-adapter-fruitdown/tsconfig.json new file mode 100644 index 0000000000..013f05d069 --- /dev/null +++ b/pouchdb-adapter-fruitdown/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-adapter-fruitdown-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-adapter-http/pouchdb-adapter-http.d.ts b/pouchdb-adapter-http/index.d.ts similarity index 93% rename from pouchdb-adapter-http/pouchdb-adapter-http.d.ts rename to pouchdb-adapter-http/index.d.ts index f1a535be5e..44eeb955ac 100644 --- a/pouchdb-adapter-http/pouchdb-adapter-http.d.ts +++ b/pouchdb-adapter-http/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { namespace HttpAdapter { diff --git a/pouchdb-adapter-http/pouchdb-adapter-http-tests.ts b/pouchdb-adapter-http/pouchdb-adapter-http-tests.ts index bbd1b5ec69..6d1c41a8a4 100644 --- a/pouchdb-adapter-http/pouchdb-adapter-http-tests.ts +++ b/pouchdb-adapter-http/pouchdb-adapter-http-tests.ts @@ -1,6 +1,3 @@ -/// -/// - function testHttpDbCreation() { const basicDB = new PouchDB('basic', { adapter: 'http' diff --git a/pouchdb-adapter-http/tsconfig.json b/pouchdb-adapter-http/tsconfig.json new file mode 100644 index 0000000000..4f8d324b1b --- /dev/null +++ b/pouchdb-adapter-http/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-adapter-http-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-adapter-idb/pouchdb-adapter-idb.d.ts b/pouchdb-adapter-idb/index.d.ts similarity index 94% rename from pouchdb-adapter-idb/pouchdb-adapter-idb.d.ts rename to pouchdb-adapter-idb/index.d.ts index 34e75f6bdf..196739f486 100644 --- a/pouchdb-adapter-idb/pouchdb-adapter-idb.d.ts +++ b/pouchdb-adapter-idb/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { namespace Core { diff --git a/pouchdb-adapter-idb/pouchdb-adapter-idb-tests.ts b/pouchdb-adapter-idb/pouchdb-adapter-idb-tests.ts index 2256bfc6bc..429a2f0483 100644 --- a/pouchdb-adapter-idb/pouchdb-adapter-idb-tests.ts +++ b/pouchdb-adapter-idb/pouchdb-adapter-idb-tests.ts @@ -1,6 +1,3 @@ -/// -/// - function testIdbDbCreation() { const basicDB = new PouchDB('basic', { adapter: 'idb' diff --git a/pouchdb-adapter-idb/tsconfig.json b/pouchdb-adapter-idb/tsconfig.json new file mode 100644 index 0000000000..919e965de2 --- /dev/null +++ b/pouchdb-adapter-idb/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-adapter-idb-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb.d.ts b/pouchdb-adapter-leveldb/index.d.ts similarity index 93% rename from pouchdb-adapter-leveldb/pouchdb-adapter-leveldb.d.ts rename to pouchdb-adapter-leveldb/index.d.ts index fcdaaea65b..b335754619 100644 --- a/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb.d.ts +++ b/pouchdb-adapter-leveldb/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { namespace LevelDbAdapter { diff --git a/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb-tests.ts b/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb-tests.ts index a9a66df854..72eb790e48 100644 --- a/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb-tests.ts +++ b/pouchdb-adapter-leveldb/pouchdb-adapter-leveldb-tests.ts @@ -1,6 +1,3 @@ -/// -/// - namespace PouchDBAdapterLevelDBTests { function testConstructor() { type MyModel = { numericProperty: number }; diff --git a/pouchdb-adapter-leveldb/tsconfig.json b/pouchdb-adapter-leveldb/tsconfig.json new file mode 100644 index 0000000000..2f59e471e3 --- /dev/null +++ b/pouchdb-adapter-leveldb/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-adapter-leveldb-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage.d.ts b/pouchdb-adapter-localstorage/index.d.ts similarity index 87% rename from pouchdb-adapter-localstorage/pouchdb-adapter-localstorage.d.ts rename to pouchdb-adapter-localstorage/index.d.ts index 92f9b17752..207cda4899 100644 --- a/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage.d.ts +++ b/pouchdb-adapter-localstorage/index.d.ts @@ -3,11 +3,11 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { namespace LocalStorageAdapter { - interface LocalStorageAdapterConfiguration + interface LocalStorageAdapterConfiguration extends Configuration.LocalDatabaseConfiguration { adapter: 'localstorage'; } diff --git a/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage-tests.ts b/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage-tests.ts index 06fe1f9a0b..8588420f78 100644 --- a/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage-tests.ts +++ b/pouchdb-adapter-localstorage/pouchdb-adapter-localstorage-tests.ts @@ -1,6 +1,3 @@ -/// -/// - namespace PouchDBAdapterLocalStorageyTests { function testConstructor() { type MyModel = { numericProperty: number }; diff --git a/pouchdb-adapter-localstorage/tsconfig.json b/pouchdb-adapter-localstorage/tsconfig.json new file mode 100644 index 0000000000..b252775f49 --- /dev/null +++ b/pouchdb-adapter-localstorage/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-adapter-localstorage-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-adapter-memory/pouchdb-adapter-memory.d.ts b/pouchdb-adapter-memory/index.d.ts similarity index 93% rename from pouchdb-adapter-memory/pouchdb-adapter-memory.d.ts rename to pouchdb-adapter-memory/index.d.ts index 75c89509ba..ae14dfdef8 100644 --- a/pouchdb-adapter-memory/pouchdb-adapter-memory.d.ts +++ b/pouchdb-adapter-memory/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { namespace MemoryAdapter { diff --git a/pouchdb-adapter-memory/pouchdb-adapter-memory-tests.ts b/pouchdb-adapter-memory/pouchdb-adapter-memory-tests.ts index b234915648..9f59922fbc 100644 --- a/pouchdb-adapter-memory/pouchdb-adapter-memory-tests.ts +++ b/pouchdb-adapter-memory/pouchdb-adapter-memory-tests.ts @@ -1,6 +1,3 @@ -/// -/// - namespace PouchDBAdapterMemoryTests { function testConstructor() { type MyModel = { numericProperty: number }; diff --git a/pouchdb-adapter-memory/tsconfig.json b/pouchdb-adapter-memory/tsconfig.json new file mode 100644 index 0000000000..4fddbceb6a --- /dev/null +++ b/pouchdb-adapter-memory/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-adapter-memory-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql.d.ts b/pouchdb-adapter-node-websql/index.d.ts similarity index 75% rename from pouchdb-adapter-node-websql/pouchdb-adapter-node-websql.d.ts rename to pouchdb-adapter-node-websql/index.d.ts index 57a0407a5e..f77a1ebd57 100644 --- a/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql.d.ts +++ b/pouchdb-adapter-node-websql/index.d.ts @@ -3,8 +3,8 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module 'pouchdb-adapter-node-websql' { const plugin: PouchDB.Plugin; diff --git a/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql-tests.ts b/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql-tests.ts index 4f751d3395..17ae2f4ec9 100644 --- a/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql-tests.ts +++ b/pouchdb-adapter-node-websql/pouchdb-adapter-node-websql-tests.ts @@ -1,6 +1,3 @@ -/// -/// - namespace PouchDBAdapterNodeWebSQLTests { function isBoolean(someBoolean: boolean) { } diff --git a/pouchdb-adapter-node-websql/tsconfig.json b/pouchdb-adapter-node-websql/tsconfig.json new file mode 100644 index 0000000000..83eeea81cb --- /dev/null +++ b/pouchdb-adapter-node-websql/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-adapter-node-websql-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-adapter-websql/pouchdb-adapter-websql.d.ts b/pouchdb-adapter-websql/index.d.ts similarity index 94% rename from pouchdb-adapter-websql/pouchdb-adapter-websql.d.ts rename to pouchdb-adapter-websql/index.d.ts index 64b732d482..4e0ee1cfe9 100644 --- a/pouchdb-adapter-websql/pouchdb-adapter-websql.d.ts +++ b/pouchdb-adapter-websql/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { namespace Core { diff --git a/pouchdb-adapter-websql/pouchdb-adapter-websql-tests.ts b/pouchdb-adapter-websql/pouchdb-adapter-websql-tests.ts index 1c0242a17c..51916a3472 100644 --- a/pouchdb-adapter-websql/pouchdb-adapter-websql-tests.ts +++ b/pouchdb-adapter-websql/pouchdb-adapter-websql-tests.ts @@ -1,6 +1,3 @@ -/// -/// - namespace PouchDBAdapterWebSQLTests { function isBoolean(someBoolean: boolean) { } diff --git a/pouchdb-adapter-websql/tsconfig.json b/pouchdb-adapter-websql/tsconfig.json new file mode 100644 index 0000000000..84a38d4f5c --- /dev/null +++ b/pouchdb-adapter-websql/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-adapter-websql-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-browser/pouchdb-browser.d.ts b/pouchdb-browser/index.d.ts similarity index 53% rename from pouchdb-browser/pouchdb-browser.d.ts rename to pouchdb-browser/index.d.ts index 3fb6dc9f2e..cab27f1e94 100644 --- a/pouchdb-browser/pouchdb-browser.d.ts +++ b/pouchdb-browser/index.d.ts @@ -3,11 +3,11 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// declare module 'pouchdb-browser' { const PouchDb: PouchDB.Static; diff --git a/pouchdb-browser/pouchdb-browser-tests.ts b/pouchdb-browser/pouchdb-browser-tests.ts index 82575efada..8e5f1c913e 100644 --- a/pouchdb-browser/pouchdb-browser-tests.ts +++ b/pouchdb-browser/pouchdb-browser-tests.ts @@ -1,6 +1,3 @@ -/// -/// - namespace PouchDBBrowserTests { function testConstructor() { type MyModel = { numericProperty: number }; diff --git a/pouchdb-browser/tsconfig.json b/pouchdb-browser/tsconfig.json new file mode 100644 index 0000000000..d37324cfad --- /dev/null +++ b/pouchdb-browser/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-browser-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-core/pouchdb-core.d.ts b/pouchdb-core/index.d.ts similarity index 100% rename from pouchdb-core/pouchdb-core.d.ts rename to pouchdb-core/index.d.ts diff --git a/pouchdb-core/pouchdb-core-tests.ts b/pouchdb-core/pouchdb-core-tests.ts index b46bce834d..451c9837f8 100644 --- a/pouchdb-core/pouchdb-core-tests.ts +++ b/pouchdb-core/pouchdb-core-tests.ts @@ -1,5 +1,3 @@ -/// - namespace PouchDBCoreTests { function isString(someString: string) { } diff --git a/pouchdb-core/tsconfig.json b/pouchdb-core/tsconfig.json new file mode 100644 index 0000000000..f78c553ea9 --- /dev/null +++ b/pouchdb-core/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-core-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-http/pouchdb-http.d.ts b/pouchdb-http/index.d.ts similarity index 74% rename from pouchdb-http/pouchdb-http.d.ts rename to pouchdb-http/index.d.ts index 0fb6d2963c..e2e6043138 100644 --- a/pouchdb-http/pouchdb-http.d.ts +++ b/pouchdb-http/index.d.ts @@ -3,8 +3,8 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module 'pouchdb-http' { const PouchDb: PouchDB.Static; diff --git a/pouchdb-http/pouchdb-http-tests.ts b/pouchdb-http/pouchdb-http-tests.ts index b3378e68b1..17d28c81ea 100644 --- a/pouchdb-http/pouchdb-http-tests.ts +++ b/pouchdb-http/pouchdb-http-tests.ts @@ -1,6 +1,3 @@ -/// -/// - namespace PouchDBHttpTests { function testConstructor() { type MyModel = { numericProperty: number }; diff --git a/pouchdb-http/tsconfig.json b/pouchdb-http/tsconfig.json new file mode 100644 index 0000000000..dbd65e738b --- /dev/null +++ b/pouchdb-http/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-http-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-mapreduce/pouchdb-mapreduce.d.ts b/pouchdb-mapreduce/index.d.ts similarity index 94% rename from pouchdb-mapreduce/pouchdb-mapreduce.d.ts rename to pouchdb-mapreduce/index.d.ts index 1c04ddceaf..fdcd1fee74 100644 --- a/pouchdb-mapreduce/pouchdb-mapreduce.d.ts +++ b/pouchdb-mapreduce/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { export interface Database { diff --git a/pouchdb-mapreduce/pouchdb-mapreduce-tests.ts b/pouchdb-mapreduce/pouchdb-mapreduce-tests.ts index a42f8178ee..50d7979fd6 100644 --- a/pouchdb-mapreduce/pouchdb-mapreduce-tests.ts +++ b/pouchdb-mapreduce/pouchdb-mapreduce-tests.ts @@ -1,5 +1,3 @@ -/// - namespace PouchDBBrowserTests { function testConstructor() { type MyModel = { numericProperty: number }; diff --git a/pouchdb-mapreduce/tsconfig.json b/pouchdb-mapreduce/tsconfig.json new file mode 100644 index 0000000000..1851efca0f --- /dev/null +++ b/pouchdb-mapreduce/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-mapreduce-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-node/pouchdb-node.d.ts b/pouchdb-node/index.d.ts similarity index 63% rename from pouchdb-node/pouchdb-node.d.ts rename to pouchdb-node/index.d.ts index deac5a0140..fe25d5d7b3 100644 --- a/pouchdb-node/pouchdb-node.d.ts +++ b/pouchdb-node/index.d.ts @@ -3,11 +3,11 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// declare namespace PouchDB { namespace Core { diff --git a/pouchdb-node/pouchdb-node-tests.ts b/pouchdb-node/pouchdb-node-tests.ts index ec9c338092..caa7f9d091 100644 --- a/pouchdb-node/pouchdb-node-tests.ts +++ b/pouchdb-node/pouchdb-node-tests.ts @@ -1,6 +1,3 @@ -/// -/// - namespace PouchDBBrowserTests { function testConstructor() { type MyModel = { numericProperty: number }; diff --git a/pouchdb-node/tsconfig.json b/pouchdb-node/tsconfig.json new file mode 100644 index 0000000000..1aeb6b5d46 --- /dev/null +++ b/pouchdb-node/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-node-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-replication/pouchdb-replication.d.ts b/pouchdb-replication/index.d.ts similarity index 92% rename from pouchdb-replication/pouchdb-replication.d.ts rename to pouchdb-replication/index.d.ts index 3dddb04f85..71b6ed3bf4 100644 --- a/pouchdb-replication/pouchdb-replication.d.ts +++ b/pouchdb-replication/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { namespace Replication { diff --git a/pouchdb-replication/pouchdb-replication-tests.ts b/pouchdb-replication/pouchdb-replication-tests.ts index 4e51bdea95..e69de29bb2 100644 --- a/pouchdb-replication/pouchdb-replication-tests.ts +++ b/pouchdb-replication/pouchdb-replication-tests.ts @@ -1 +0,0 @@ -/// diff --git a/pouchdb-replication/tsconfig.json b/pouchdb-replication/tsconfig.json new file mode 100644 index 0000000000..ef11e1f646 --- /dev/null +++ b/pouchdb-replication/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pouchdb-replication-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb-upsert/pouchdb-upsert.d.ts b/pouchdb-upsert/pouchdb-upsert.d.ts index b0a4e760a3..03f415ea90 100644 --- a/pouchdb-upsert/pouchdb-upsert.d.ts +++ b/pouchdb-upsert/pouchdb-upsert.d.ts @@ -3,7 +3,7 @@ // Definitions by: Keith D. Moore , Andrew Mitchell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace PouchDB { diff --git a/pouchdb-upsert/tsconfig.json b/pouchdb-upsert/tsconfig.json new file mode 100644 index 0000000000..a88f26d221 --- /dev/null +++ b/pouchdb-upsert/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "pouchdb-upsert.d.ts", + "pouchdb-upsert-tests.ts" + ] +} \ No newline at end of file diff --git a/pouchdb/index.d.ts b/pouchdb/index.d.ts index 2d40feb2ec..5822e631a8 100644 --- a/pouchdb/index.d.ts +++ b/pouchdb/index.d.ts @@ -3,20 +3,20 @@ // Definitions by: Andy Brown , Brian Geppert , Frederico Galvão // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// declare module 'pouchdb' { const plugin: PouchDB.Static; diff --git a/rc-tooltip/rc-tooltip-tests.tsx b/rc-tooltip/rc-tooltip-tests.tsx index d1f4db339a..751ffc43ec 100644 --- a/rc-tooltip/rc-tooltip-tests.tsx +++ b/rc-tooltip/rc-tooltip-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as Tooltip from 'rc-tooltip'; diff --git a/rc-tooltip/rc-tooltip.d.ts b/rc-tooltip/rc-tooltip.d.ts index a2a5c67314..91904c623a 100644 --- a/rc-tooltip/rc-tooltip.d.ts +++ b/rc-tooltip/rc-tooltip.d.ts @@ -3,11 +3,9 @@ // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Tooltip { - import React = __React; - export type Trigger = "hover" | "click" | "focus"; export type Placement = "left" | "right" | "top" | "bottom" | @@ -34,7 +32,7 @@ declare namespace Tooltip { } } -declare class Tooltip extends __React.Component {} +declare class Tooltip extends React.Component {} declare module "rc-tooltip" { export = Tooltip diff --git a/rc-tooltip/tsconfig.json b/rc-tooltip/tsconfig.json new file mode 100644 index 0000000000..3ad29fc103 --- /dev/null +++ b/rc-tooltip/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "rc-tooltip.d.ts", + "rc-tooltip-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-autosuggest/react-autosuggest-tests.tsx b/react-autosuggest/react-autosuggest-tests.tsx index 2190b9a443..5a107fe525 100644 --- a/react-autosuggest/react-autosuggest-tests.tsx +++ b/react-autosuggest/react-autosuggest-tests.tsx @@ -1,9 +1,3 @@ -// React-Autosuggest Test -// ================================================================================ -/// -/// -/// - //region Imports import React = require('react'); import ReactDOM = require('react-dom'); @@ -69,7 +63,7 @@ export class ReactAutosuggestBasicTest extends React.Component { inputProps={inputProps}/>; } - protected onSuggestionsSelected(event: React.FormEvent, data: ReactAutosuggest.ExplicitSuggestionSelectedEventData): void { + protected onSuggestionsSelected(event: React.FormEvent, data: ReactAutosuggest.ExplicitSuggestionSelectedEventData): void { alert(`Selected language is ${data.suggestion.name} (${data.suggestion.year}).`); } @@ -79,13 +73,13 @@ export class ReactAutosuggestBasicTest extends React.Component { //endregion //region Event handlers - protected onChange(event: React.FormEvent, {newValue, method}): void { + protected onChange(event: React.FormEvent, {newValue, method}: any): void { this.setState({ value: newValue }); } - protected onSuggestionsUpdateRequested({ value }): void { + protected onSuggestionsUpdateRequested({ value }: any): void { this.setState({ suggestions: this.getSuggestions(value) }); @@ -194,7 +188,7 @@ export class ReactAutosuggestMultipleTest extends React.Component { inputProps={inputProps} />; } - protected onSuggestionSelected(event: React.FormEvent, data: ReactAutosuggest.SuggestionSelectedEventData): void { + protected onSuggestionSelected(event: React.FormEvent, data: ReactAutosuggest.SuggestionSelectedEventData): void { const language = data.suggestion as Language; alert(`Selected language is ${language.name} (${language.year}).`); @@ -210,13 +204,13 @@ export class ReactAutosuggestMultipleTest extends React.Component { //endregion //region Event handlers - protected onChange(event: React.FormEvent, { newValue, method }): void { + protected onChange(event: React.FormEvent, { newValue, method }: any): void { this.setState({ value: newValue }); } - protected onSuggestionsUpdateRequested({ value }): void { + protected onSuggestionsUpdateRequested({ value }: any): void { this.setState({ suggestions: this.getSuggestions(value) }); @@ -298,7 +292,7 @@ export class ReactAutosuggestCustomTest extends React.Component { inputProps={inputProps} />; } - protected renderSuggestion(suggestion: IPerson, { value, valueBeforeUpDown }): JSX.Element { + protected renderSuggestion(suggestion: IPerson, { value, valueBeforeUpDown }: any): JSX.Element { const suggestionText = `${suggestion.first} ${suggestion.last}`; const query = (valueBeforeUpDown || value).trim(); const parts = suggestionText.split(' ').map((part: string) => { @@ -323,13 +317,13 @@ export class ReactAutosuggestCustomTest extends React.Component { //endregion //region Event handlers - protected onChange(event: React.FormEvent, {newValue, method}): void { + protected onChange(event: React.FormEvent, {newValue, method}: any): void { this.setState({ value: newValue }); } - protected onSuggestionsUpdateRequested({ value }): void { + protected onSuggestionsUpdateRequested({ value }: any): void { this.setState({ suggestions: this.getSuggestions(value) }); diff --git a/react-autosuggest/react-autosuggest.d.ts b/react-autosuggest/react-autosuggest.d.ts index eb6892adb2..cfec62d047 100644 --- a/react-autosuggest/react-autosuggest.d.ts +++ b/react-autosuggest/react-autosuggest.d.ts @@ -3,11 +3,9 @@ // Definitions by: Nicolas Schmitt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace ReactAutosuggest { - import React = __React; - interface SuggestionUpdateRequest { value: string; reason: string; @@ -18,9 +16,9 @@ declare namespace ReactAutosuggest { valueBeforeUpDown?: string; } - interface InputProps extends React.HTMLAttributes { + interface InputProps extends React.HTMLAttributes { value: string; - onChange: (event: React.FormEvent, params?: {newValue: string, method: string}) => void; + onChange: (event: React.FormEvent, params?: {newValue: string, method: string}) => void; } interface ExplicitSuggestionSelectedEventData { @@ -55,7 +53,7 @@ declare namespace ReactAutosuggest { multiSection?: boolean; renderSectionTitle?: (section: any, inputValues: InputValues) => JSX.Element; getSectionSuggestions?: (section: any) => any[]; - onSuggestionSelected?: (event: React.FormEvent, data: SuggestionSelectedEventData | ExplicitSuggestionSelectedEventData) => void; + onSuggestionSelected?: (event: React.FormEvent, data: SuggestionSelectedEventData | ExplicitSuggestionSelectedEventData) => void; focusInputOnSuggestionClick?: boolean; theme?: Theme; id?: string; diff --git a/react-autosuggest/tsconfig.json b/react-autosuggest/tsconfig.json new file mode 100644 index 0000000000..3f2805e714 --- /dev/null +++ b/react-autosuggest/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-autosuggest.d.ts", + "react-autosuggest-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-big-calendar/react-big-calendar-tests.tsx b/react-big-calendar/react-big-calendar-tests.tsx index 8e7bca7a9d..38c6f9da0a 100644 --- a/react-big-calendar/react-big-calendar-tests.tsx +++ b/react-big-calendar/react-big-calendar-tests.tsx @@ -1,12 +1,9 @@ -/// -/// -/// -/// - import * as React from "react"; import * as ReactDOM from "react-dom"; import * as ReactDOMServer from "react-dom/server"; import BigCalendar from 'react-big-calendar'; +// Don't want to add this as a dependency, because it is only used for tests. +declare const moment: any; // Init localizer BigCalendar.momentLocalizer(moment); diff --git a/react-big-calendar/react-big-calendar.d.ts b/react-big-calendar/react-big-calendar.d.ts index 3886a4ca59..26ca723cb4 100644 --- a/react-big-calendar/react-big-calendar.d.ts +++ b/react-big-calendar/react-big-calendar.d.ts @@ -3,8 +3,6 @@ // Definitions by: Piotr Witek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module 'react-big-calendar' { import * as React from 'react'; diff --git a/react-big-calendar/tsconfig.json b/react-big-calendar/tsconfig.json new file mode 100644 index 0000000000..ef22e3c080 --- /dev/null +++ b/react-big-calendar/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-big-calendar.d.ts", + "react-big-calendar-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-breadcrumbs/react-breadcrumbs-tests.tsx b/react-breadcrumbs/react-breadcrumbs-tests.tsx index b5e7621b35..d81877fccf 100644 --- a/react-breadcrumbs/react-breadcrumbs-tests.tsx +++ b/react-breadcrumbs/react-breadcrumbs-tests.tsx @@ -1,9 +1,5 @@ -/// -/// -/// - - import * as React from 'react'; +import * as ReactRouter from "react-router"; import * as Breadcrumbs from 'react-breadcrumbs'; diff --git a/react-breadcrumbs/react-breadcrumbs.d.ts b/react-breadcrumbs/react-breadcrumbs.d.ts index 885a883c6d..1d247f215d 100644 --- a/react-breadcrumbs/react-breadcrumbs.d.ts +++ b/react-breadcrumbs/react-breadcrumbs.d.ts @@ -3,13 +3,10 @@ // Definitions by: Kostya Esmukov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare namespace ReactBreadcrumbs { - import React = __React; - - interface BreadcrumbsProps extends React.Props { separator?: string | JSX.Element; displayMissing?: boolean; @@ -25,7 +22,7 @@ declare namespace ReactBreadcrumbs { activeItemClass?: string; excludes?: string[]; hideNoPath?: boolean; - routes: ReactRouter.RouteConfig; + routes: ReactRouter.Router.RouteConfig; setDocumentTitle?: boolean; params?: any; // todo make it compatible with params of the ReactRouter.RouteComponentProps } diff --git a/react-breadcrumbs/tsconfig.json b/react-breadcrumbs/tsconfig.json new file mode 100644 index 0000000000..5fc6650176 --- /dev/null +++ b/react-breadcrumbs/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-breadcrumbs.d.ts", + "react-breadcrumbs-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-calendar-timeline/react-calendar-timeline-tests.tsx b/react-calendar-timeline/react-calendar-timeline-tests.tsx index 7ce99f1ddf..f2bd8efab4 100644 --- a/react-calendar-timeline/react-calendar-timeline-tests.tsx +++ b/react-calendar-timeline/react-calendar-timeline-tests.tsx @@ -1,10 +1,7 @@ -/// -/// -/// - import * as React from "react"; -import * as moment from 'moment'; import ReactCalendarTimeline from 'react-calendar-timeline'; +// Don't want to add this as a dependency, because it is only used for tests. +declare const moment: any; const groups = [ {id: 1, title: 'group 1'}, @@ -29,5 +26,5 @@ class ExampleOfUsingReactCalendarTimeline extends React.Component<{}, {}> { /> ); - } + } }; \ No newline at end of file diff --git a/react-calendar-timeline/react-calendar-timeline.d.ts b/react-calendar-timeline/react-calendar-timeline.d.ts index f377d29610..029ea8b65b 100644 --- a/react-calendar-timeline/react-calendar-timeline.d.ts +++ b/react-calendar-timeline/react-calendar-timeline.d.ts @@ -3,18 +3,18 @@ // Definitions by: Rajab Shakirov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "react-calendar-timeline" { interface ReactCalendarTimeline { groups: { id: number; - title: any; // string | Element (__React.ClassicComponentClass); + title: any; // string | Element (React.ClassicComponentClass); }[]; items:{ id: number; group: number; - title?: any; // string | Element (__React.ClassicComponentClass); + title?: any; // string | Element (React.ClassicComponentClass); start_time: any; end_time: any; canMove?: boolean; @@ -65,6 +65,6 @@ declare module "react-calendar-timeline" { onBoundsChange?(canvasTimeStart:any, canvasTimeEnd:any): any; children?: any; } - let ReactCalendarTimeline : __React.ClassicComponentClass; + let ReactCalendarTimeline : React.ClassicComponentClass; export default ReactCalendarTimeline; } diff --git a/react-calendar-timeline/tsconfig.json b/react-calendar-timeline/tsconfig.json new file mode 100644 index 0000000000..4bd69bf193 --- /dev/null +++ b/react-calendar-timeline/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-calendar-timeline.d.ts", + "react-calendar-timeline-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-codemirror/react-codemirror-tests.tsx b/react-codemirror/react-codemirror-tests.tsx index 185f3b229d..2924ae4d5c 100644 --- a/react-codemirror/react-codemirror-tests.tsx +++ b/react-codemirror/react-codemirror-tests.tsx @@ -1,7 +1,4 @@ -/// -/// -/// - +import * as CodeMirror from "codemirror"; import * as React from "react"; import * as ReactDOM from "react-dom"; import * as Codemirror from "react-codemirror"; diff --git a/react-codemirror/react-codemirror.d.ts b/react-codemirror/react-codemirror.d.ts index 12311a2665..20176c2ae3 100644 --- a/react-codemirror/react-codemirror.d.ts +++ b/react-codemirror/react-codemirror.d.ts @@ -3,11 +3,11 @@ // Definitions by: Vicky Lai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare namespace ReactCodeMirror { - interface ReactCodeMirrorProps extends __React.Props { + interface ReactCodeMirrorProps extends React.Props { onChange?: (newValue: string) => any; // called when a change is made onFocusChange?: (focused: boolean) => any; // called when the editor is focused or loses focus onScroll?: (scrollInfo: CodeMirror.ScrollInfo) => any; // called when the editor is scrolled @@ -18,7 +18,7 @@ declare namespace ReactCodeMirror { codeMirrorInstance?: CodeMirror.Editor; // the CodeMirror instance } - interface ReactCodeMirror extends __React.Component { + interface ReactCodeMirror extends React.Component { /** Focuses the CodeMirror instance. */ focus(): void; @@ -26,7 +26,7 @@ declare namespace ReactCodeMirror { getCodeMirror(): CodeMirror.Editor; } - interface ReactCodeMirrorClass extends __React.ComponentClass { } + interface ReactCodeMirrorClass extends React.ComponentClass { } } declare module "react-codemirror" { diff --git a/react-codemirror/tsconfig.json b/react-codemirror/tsconfig.json new file mode 100644 index 0000000000..2c0e4d2ad5 --- /dev/null +++ b/react-codemirror/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-codemirror.d.ts", + "react-codemirror-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-data-grid/react-data-grid.d.ts b/react-data-grid/index.d.ts similarity index 98% rename from react-data-grid/react-data-grid.d.ts rename to react-data-grid/index.d.ts index 0748270a57..c76ab540b8 100644 --- a/react-data-grid/react-data-grid.d.ts +++ b/react-data-grid/index.d.ts @@ -3,12 +3,9 @@ // Definitions by: Simon Gellis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - +/// declare namespace AdazzleReactDataGrid { - import React = __React; - interface GridProps { /** * Gets the data to render in each row. Required. @@ -248,7 +245,7 @@ declare namespace AdazzleReactDataGrid { * @param ev The react event * @param args The row and column coordinates of the cell, and the name of the event. */ - (ev: React.SyntheticEvent, args: {rowIdx: number, idx: number, name: string}): void + (ev: React.SyntheticEvent, args: {rowIdx: number, idx: number, name: string}): void } /** @@ -314,7 +311,7 @@ declare namespace AdazzleReactDataGrid { /** * The double click event. */ - e: React.SyntheticEvent + e: React.SyntheticEvent } /** @@ -414,8 +411,6 @@ declare namespace AdazzleReactDataGrid { } declare namespace AdazzleReactDataGridPlugins { - import React = __React; - // TODO: refine types for these addons export namespace Editors { export class AutoComplete extends React.Component { } diff --git a/react-data-grid/react-data-grid-tests.tsx b/react-data-grid/react-data-grid-tests.tsx index 1b95fa8cc7..4c2598c87c 100644 --- a/react-data-grid/react-data-grid-tests.tsx +++ b/react-data-grid/react-data-grid-tests.tsx @@ -1,11 +1,7 @@ -/// -/// -/// - import * as React from 'react'; import * as ReactDataGrid from 'react-data-grid'; import * as ReactDataGridPlugins from 'react-data-grid/addons'; -import * as faker from 'faker'; +import faker = require('faker'); var Editors = ReactDataGridPlugins.Editors; var Toolbar = ReactDataGridPlugins.Toolbar; @@ -202,7 +198,7 @@ class Example extends React.Component { getColumns() { var clonedColumns = columns.slice(); clonedColumns[2].events = { - onClick: function (ev:React.SyntheticEvent, args:{idx:number, rowIdx:number}) { + onClick: function (ev:React.SyntheticEvent, args:{idx:number, rowIdx:number}) { var idx = args.idx; var rowIdx = args.rowIdx; this.refs.grid.openCellEditor(rowIdx, idx); diff --git a/react-data-grid/tsconfig.json b/react-data-grid/tsconfig.json new file mode 100644 index 0000000000..0abfd403ad --- /dev/null +++ b/react-data-grid/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-data-grid-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-datepicker/package.json b/react-datepicker/package.json new file mode 100644 index 0000000000..992b24d513 --- /dev/null +++ b/react-datepicker/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "moment": "2.14.*" + } +} \ No newline at end of file diff --git a/react-datepicker/react-datepicker-tests.tsx b/react-datepicker/react-datepicker-tests.tsx index 6858e04335..53cd4723b5 100644 --- a/react-datepicker/react-datepicker-tests.tsx +++ b/react-datepicker/react-datepicker-tests.tsx @@ -1,34 +1,30 @@ -/// -/// -/// - import * as React from "react"; import * as moment from 'moment'; import * as DatePicker from 'react-datepicker'; -class ReactDatePicker extends React.Component<{}, {startDate:any,displayName:string}> { +class ReactDatePicker extends React.Component<{}, {startDate:any,displayName:string}> { constructor(props:any) { super(); - this.state = { + this.state = { startDate: moment(), - displayName: 'Example' + displayName: 'Example' } this.handleChange = this.handleChange.bind(this); } - + handleChange = function(date?:any) { this.setState({ startDate: date }); } - + render(){ return (
    -
    + ); - } + } }; \ No newline at end of file diff --git a/react-datepicker/react-datepicker.d.ts b/react-datepicker/react-datepicker.d.ts index 733f783faa..1d8cdc89cc 100644 --- a/react-datepicker/react-datepicker.d.ts +++ b/react-datepicker/react-datepicker.d.ts @@ -3,7 +3,7 @@ // Definitions by: Rajab Shakirov , Andrey Balokha // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "react-datepicker" { interface ReactDatePicker { @@ -41,6 +41,6 @@ declare module "react-datepicker" { todayButton?: string; fixedHeight?: boolean; } - let ReactDatePicker: __React.ClassicComponentClass; + let ReactDatePicker: React.ClassicComponentClass; export = ReactDatePicker; } diff --git a/react-datepicker/tsconfig.json b/react-datepicker/tsconfig.json new file mode 100644 index 0000000000..60fcd89c5f --- /dev/null +++ b/react-datepicker/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-datepicker.d.ts", + "react-datepicker-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-daterange-picker/index.d.ts b/react-daterange-picker/index.d.ts new file mode 100644 index 0000000000..102b8bac16 --- /dev/null +++ b/react-daterange-picker/index.d.ts @@ -0,0 +1,65 @@ +// Type definitions for React Daterange Picker v1.1.0 +// Project: https://github.com/onefinestay/react-daterange-picker +// Definitions by: UNCOVER TRUTH Inc. +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +import * as React from "react"; +import * as moment from "moment-range"; + +export default class DateRangePicker extends React.Component {} +export as namespace ReactDateRangePicker; + +interface Props extends React.Props<{}> { + bemBlock?: string; + bemNamespace?: string; + dateStates?: DateState[]; + defaultState?: string; + disableNavigation?: boolean; + // Use Number Literal Types after TypeScript 2.0 GA released. + firstOfWeek?: number; // React.PropTypes.oneOf([0, 1, 2, 3, 4, 5, 6]) + helpMessage?: string; + initialFromValue?: boolean; + initialDate?: Date; + initialMonth?: number; + initialYear?: number; + initialRange?: {}; + maximumDate?: Date; + minimumDate?: Date; + numberOfCalendars?: number; + onHighlightDate?(date: Date): void; + onHighlightRange?(date: Date): void; + onSelect?(value: Props): void; + onSelectStart?(value: moment.Moment): void; + paginationArrowComponent?: PaginationArrow; + selectedLabel?: string; + selectionType?: 'single' |'range'; + singleDateRange?: boolean; + showLegend?: boolean; + stateDefinitions?: StateDefinitions; + value?: moment.Moment | moment.Range; +} + +interface DateState { + state: string; + range: moment.Range; +} + +interface StateDefinitions { + [key: string]: StateDefinition; +} + +interface StateDefinition { + color: string; + label: string; + selectable?: boolean; +} + +interface PaginationArrowProps extends React.Props<{}> { + disabled?: boolean; + onTrigger?(): void; + direction?: 'next' | 'previous'; +} + +declare class PaginationArrow extends React.Component { +} + diff --git a/react-daterange-picker/package.json b/react-daterange-picker/package.json new file mode 100644 index 0000000000..992b24d513 --- /dev/null +++ b/react-daterange-picker/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "moment": "2.14.*" + } +} \ No newline at end of file diff --git a/react-daterange-picker/react-daterange-picker-tests.tsx b/react-daterange-picker/react-daterange-picker-tests.tsx index 98665fddb6..1bb372d4db 100644 --- a/react-daterange-picker/react-daterange-picker-tests.tsx +++ b/react-daterange-picker/react-daterange-picker-tests.tsx @@ -1,12 +1,9 @@ -/// -/// - // Test app from https://github.com/onefinestay/react-daterange-picker/blob/master/example/index.jsx import * as React from 'react'; import * as ReactDOM from 'react-dom'; -import * as moment from 'moment'; -import 'moment-range'; -import * as DateRangePicker from 'react-daterange-picker'; +import * as moment from 'moment-range'; +import DateRangePicker from "react-daterange-picker"; +import * as ReactDateRangePicker from "react-daterange-picker"; interface AppProps extends ReactDateRangePicker.Props { } diff --git a/react-daterange-picker/react-daterange-picker.d.ts b/react-daterange-picker/react-daterange-picker.d.ts deleted file mode 100644 index 4754e77140..0000000000 --- a/react-daterange-picker/react-daterange-picker.d.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Type definitions for React Daterange Picker v1.1.0 -// Project: https://github.com/onefinestay/react-daterange-picker -// Definitions by: UNCOVER TRUTH Inc. -// Definitions: https://github.com/borisyankov/DefinitelyTyped - -/// -/// -/// - -declare module 'react-daterange-picker' { - import DateRangePicker = ReactDateRangePicker.DateRangePicker; - export = DateRangePicker; -} - -declare namespace ReactDateRangePicker { - import React = __React; - - interface Props extends React.Props<{}> { - bemBlock?: string; - bemNamespace?: string; - dateStates?: DateState[]; - defaultState?: string; - disableNavigation?: boolean; - // Use Number Literal Types after TypeScript 2.0 GA released. - firstOfWeek?: number; // React.PropTypes.oneOf([0, 1, 2, 3, 4, 5, 6]) - helpMessage?: string; - initialFromValue?: boolean; - initialDate?: Date; - initialMonth?: number; - initialYear?: number; - initialRange?: {}; - maximumDate?: Date; - minimumDate?: Date; - numberOfCalendars?: number; - onHighlightDate?(date: Date): void; - onHighlightRange?(date: Date): void; - onSelect?(value: Props): void; - onSelectStart?(value: moment.Moment): void; - paginationArrowComponent?: PaginationArrow; - selectedLabel?: string; - selectionType?: 'single' |'range'; - singleDateRange?: boolean; - showLegend?: boolean; - stateDefinitions?: StateDefinitions; - value?: moment.Moment | moment.Range; - } - - interface DateState { - state: string; - range: moment.Range; - } - - interface StateDefinitions { - [key: string]: StateDefinition; - } - - interface StateDefinition { - color: string; - label: string; - selectable?: boolean; - } - - interface PaginationArrowProps extends React.Props<{}> { - disabled?: boolean; - onTrigger?(): void; - direction?: 'next' | 'previous'; - } - - class PaginationArrow extends React.Component { - } - - class DateRangePicker extends React.Component { - } - - namespace DateRangePicker { - } -} diff --git a/react-daterange-picker/tsconfig.json b/react-daterange-picker/tsconfig.json new file mode 100644 index 0000000000..a4828d6b09 --- /dev/null +++ b/react-daterange-picker/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-daterange-picker-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-dnd-html5-backend/react-dnd-html5-backend.d.ts b/react-dnd-html5-backend/react-dnd-html5-backend.d.ts index a635814842..5b9267b789 100644 --- a/react-dnd-html5-backend/react-dnd-html5-backend.d.ts +++ b/react-dnd-html5-backend/react-dnd-html5-backend.d.ts @@ -3,12 +3,10 @@ // Definitions by: Pedro Pereira // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module "react-dnd-html5-backend" { - import ReactDnd = __ReactDnd; - export enum NativeTypes { FILE, URL, TEXT } export function getEmptyImage(): any; // Image export default class HTML5Backend implements __ReactDnd.Backend {} diff --git a/react-dnd-html5-backend/tsconfig.json b/react-dnd-html5-backend/tsconfig.json new file mode 100644 index 0000000000..b7ef8e9789 --- /dev/null +++ b/react-dnd-html5-backend/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "react-dnd-html5-backend.d.ts", + "react-dnd-html5-backend-tests.ts" + ] +} \ No newline at end of file diff --git a/react-file-input/react-file-input-tests.tsx b/react-file-input/react-file-input-tests.tsx index 208a8d29ed..857a86d4e2 100644 --- a/react-file-input/react-file-input-tests.tsx +++ b/react-file-input/react-file-input-tests.tsx @@ -1,11 +1,8 @@ -/// -/// - import * as React from "react"; import FileInput = require('react-file-input'); class Form extends React.Component<{}, {}> { - handleChange = (event: React.SyntheticEvent) => { + handleChange = (event: React.SyntheticEvent) => { const target: any = event.target; console.log('Selected file:', target.files[0]); } diff --git a/react-file-input/react-file-input.d.ts b/react-file-input/react-file-input.d.ts index ca0cac594b..9ec64fc1ec 100644 --- a/react-file-input/react-file-input.d.ts +++ b/react-file-input/react-file-input.d.ts @@ -3,18 +3,16 @@ // Definitions by: Dmitry Rogozhny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "react-file-input" { - import React = __React; - interface FileInputProps { name: string; className: string; accept: string; placeholder: string; disabled?: boolean; - onChange: (event: React.SyntheticEvent) => void; + onChange: (event: React.SyntheticEvent) => void; } class FileInput extends React.Component { diff --git a/react-file-input/tsconfig.json b/react-file-input/tsconfig.json new file mode 100644 index 0000000000..6e2b25f0d2 --- /dev/null +++ b/react-file-input/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-file-input.d.ts", + "react-file-input-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-file-reader-input/react-file-reader-input-tests.tsx b/react-file-reader-input/react-file-reader-input-tests.tsx index 0f8b70a35a..0b21edfd71 100644 --- a/react-file-reader-input/react-file-reader-input-tests.tsx +++ b/react-file-reader-input/react-file-reader-input-tests.tsx @@ -1,11 +1,8 @@ -/// -/// - import * as React from "react"; import FileReaderInput = require("react-file-reader-input"); class MyComponent extends React.Component<{}, {}> { - handleChange = (event: React.SyntheticEvent, results: any) => { + handleChange = (event: React.SyntheticEvent, results: any) => { results.forEach((result: any) => { const [event, file] = result; console.log(`Selected file ${file.name}!`); diff --git a/react-file-reader-input/react-file-reader-input.d.ts b/react-file-reader-input/react-file-reader-input.d.ts index 094e690aa1..649f0f688c 100644 --- a/react-file-reader-input/react-file-reader-input.d.ts +++ b/react-file-reader-input/react-file-reader-input.d.ts @@ -3,14 +3,12 @@ // Definitions by: Dmitry Rogozhny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "react-file-reader-input" { - import React = __React; - interface FileInputProps { as?: string; - onChange?: (event: React.SyntheticEvent, results: any) => void; + onChange?: (event: React.SyntheticEvent, results: any) => void; } class FileInput extends React.Component { diff --git a/react-file-reader-input/tsconfig.json b/react-file-reader-input/tsconfig.json new file mode 100644 index 0000000000..ec09339b0e --- /dev/null +++ b/react-file-reader-input/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-file-reader-input.d.ts", + "react-file-reader-input-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-flexr/react-flexr-tests.tsx b/react-flexr/react-flexr-tests.tsx index 3d7c155386..224ceb686c 100644 --- a/react-flexr/react-flexr-tests.tsx +++ b/react-flexr/react-flexr-tests.tsx @@ -1,5 +1,4 @@ -/// -/// +/// import * as React from "react"; import * as ReactDOMServer from "react-dom/server"; diff --git a/react-flexr/react-flexr.d.ts b/react-flexr/react-flexr.d.ts index 3871abee74..6b24685087 100644 --- a/react-flexr/react-flexr.d.ts +++ b/react-flexr/react-flexr.d.ts @@ -3,11 +3,9 @@ // Definitions by: Jeffery Grajkowski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +// declare namespace __ReactFlexr { - export import React = __React; - interface GridProps extends React.Props { /** * Vertical Align Sub Cells: top, center, bottom diff --git a/react-flexr/tsconfig.json b/react-flexr/tsconfig.json new file mode 100644 index 0000000000..658fa94b63 --- /dev/null +++ b/react-flexr/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-flexr.d.ts", + "react-flexr-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-fontawesome/react-fontawesome-tests.tsx b/react-fontawesome/react-fontawesome-tests.tsx index d283e033fa..69bdeaf2c1 100644 --- a/react-fontawesome/react-fontawesome-tests.tsx +++ b/react-fontawesome/react-fontawesome-tests.tsx @@ -1,7 +1,3 @@ -/// -/// -/// - import * as React from "react"; import * as ReactDOM from "react-dom"; import FontAwesome = require('react-fontawesome'); diff --git a/react-fontawesome/react-fontawesome.d.ts b/react-fontawesome/react-fontawesome.d.ts index a790ad70ea..fc75fdfbd3 100644 --- a/react-fontawesome/react-fontawesome.d.ts +++ b/react-fontawesome/react-fontawesome.d.ts @@ -3,8 +3,6 @@ // Definitions by: Timur Rustamov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "react-fontawesome" { //Import react diff --git a/react-fontawesome/tsconfig.json b/react-fontawesome/tsconfig.json new file mode 100644 index 0000000000..9d1784f8a7 --- /dev/null +++ b/react-fontawesome/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-fontawesome.d.ts", + "react-fontawesome-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-i18next/index.d.ts b/react-i18next/index.d.ts new file mode 100644 index 0000000000..85c8e8851c --- /dev/null +++ b/react-i18next/index.d.ts @@ -0,0 +1,57 @@ +// Type definitions for react-i18next 1.7.0 +// Project: https://github.com/i18next/react-i18next +// Definitions by: Kostya Esmukov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as I18next from "i18next"; +import * as React from "react"; +import * as ReactRouter from "react-router"; + +export type TranslationFunction = I18next.TranslationFunction; + +// Extend your component's Prop interface with this one to get access to `this.props.t` +// +// Please note that if you use the `translateFuncName` option, you should create +// your own interface just like this one, but with your name of the translation function. +// +// interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} +export interface InjectedTranslateProps { + t?: TranslationFunction; +} + +interface I18nextProviderProps { + i18n: I18next.I18n; + children?: React.ReactElement; +} + +export class I18nextProvider extends React.Component { } + + +type InterpolateValue = string | JSX.Element; + +interface InterpolateProps { + i18nKey: string; + + parent?: string; + regexp?: RegExp; + options?: I18next.TranslationOptions; + + useDangerouslySetInnerHTML?: boolean; + dangerouslySetInnerHTMLPartElement?: string; + + [regexKey: string]: InterpolateValue | RegExp | I18next.TranslationOptions | boolean; +} + +export class Interpolate extends React.Component { } + +interface TranslateOptions { + withRef?: boolean; + wait?: boolean; + translateFuncName?: string; +} + +export function translate(namespaces?: string[] | string, options?: TranslateOptions): (WrappedComponent: C) => C; + +export function loadNamespaces({ components, i18n }: { components: ReactRouter.RouteComponent[], i18n: I18next.I18n }): Promise; + +export as namespace ReactI18Next; diff --git a/react-i18next/react-i18next-tests.tsx b/react-i18next/react-i18next-tests.tsx index dd013002d4..012f920bc9 100644 --- a/react-i18next/react-i18next-tests.tsx +++ b/react-i18next/react-i18next-tests.tsx @@ -1,9 +1,3 @@ -/// -/// -/// -/// - - import * as ReactDOM from 'react-dom'; import * as React from 'react'; import * as i18n from 'i18next'; diff --git a/react-i18next/react-i18next.d.ts b/react-i18next/react-i18next.d.ts deleted file mode 100644 index 8993ab61cb..0000000000 --- a/react-i18next/react-i18next.d.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Type definitions for react-i18next 1.7.0 -// Project: https://github.com/i18next/react-i18next -// Definitions by: Kostya Esmukov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -/// -/// - - -declare namespace ReactI18next { - import React = __React; - - export type TranslationFunction = I18next.TranslationFunction; - - // Extend your component's Prop interface with this one to get access to `this.props.t` - // - // Please note that if you use the `translateFuncName` option, you should create - // your own interface just like this one, but with your name of the translation function. - // - // interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} - export interface InjectedTranslateProps { - t?: TranslationFunction; - } - - interface I18nextProviderProps { - i18n: I18next.I18n; - children?: React.ReactElement; - } - - export class I18nextProvider extends React.Component { } - - - type InterpolateValue = string | JSX.Element; - - interface InterpolateProps { - i18nKey: string; - - parent?: string; - regexp?: RegExp; - options?: I18next.TranslationOptions; - - useDangerouslySetInnerHTML?: boolean; - dangerouslySetInnerHTMLPartElement?: string; - - [regexKey: string]: InterpolateValue | RegExp | I18next.TranslationOptions | boolean; - } - - export class Interpolate extends React.Component { } - - interface TranslateOptions { - withRef?: boolean; - wait?: boolean; - translateFuncName?: string; - } - - export function translate(namespaces?: string[] | string, options?: TranslateOptions): (WrappedComponent: C) => C; - - export function loadNamespaces({ components, i18n }: { components: ReactRouter.RouteComponent[], i18n: I18next.I18n }): Promise; - -} - -declare module 'react-i18next' { - export = ReactI18next; -} diff --git a/react-i18next/tsconfig.json b/react-i18next/tsconfig.json new file mode 100644 index 0000000000..ba4f230166 --- /dev/null +++ b/react-i18next/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react", + "experimentalDecorators": true + }, + "files": [ + "index.d.ts", + "react-i18next-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-imageloader/react-imageloader-tests.tsx b/react-imageloader/react-imageloader-tests.tsx index 9a1ddf0204..a6d845825f 100644 --- a/react-imageloader/react-imageloader-tests.tsx +++ b/react-imageloader/react-imageloader-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import ImageLoader = require('react-imageloader'); import * as React from 'react'; diff --git a/react-imageloader/react-imageloader.d.ts b/react-imageloader/react-imageloader.d.ts index 1ba1ba38d0..8132058aa0 100644 --- a/react-imageloader/react-imageloader.d.ts +++ b/react-imageloader/react-imageloader.d.ts @@ -3,10 +3,10 @@ // Definitions by: Stephen Jelfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "react-imageloader" { - interface ImageLoaderProps extends __React.Props { + interface ImageLoaderProps extends React.Props { /** An optional class name for the wrapper component. */ className?: string; @@ -20,19 +20,19 @@ declare module "react-imageloader" { onLoad?: (event: any) => void; /** An optional function that returns a React element to be shown while the image loads. */ - preloader?: (params: any) => __React.ReactElement; + preloader?: (params: any) => React.ReactElement; /** The URL of the image to be loaded. */ src: string; /** An optional object containing styles for the wrapper component. */ - style?: __React.CSSProperties; + style?: React.CSSProperties; /** A function that takes a props argument and returns a React element to be used as the wrapper component. Defaults to React.DOM.span. */ - wrapper?: (props: any) => __React.ReactElement; + wrapper?: (props: any) => React.ReactElement; } - class ImageLoader extends __React.Component {} + class ImageLoader extends React.Component {} export = ImageLoader; } diff --git a/react-imageloader/tsconfig.json b/react-imageloader/tsconfig.json new file mode 100644 index 0000000000..ce35e9adb2 --- /dev/null +++ b/react-imageloader/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-imageloader.d.ts", + "react-imageloader-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-is-deprecated/react-is-deprecated-tests.ts b/react-is-deprecated/react-is-deprecated-tests.ts index f5574e44cf..2f01286189 100644 --- a/react-is-deprecated/react-is-deprecated-tests.ts +++ b/react-is-deprecated/react-is-deprecated-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import { PropTypes } from 'react'; import { deprecate, addIsDeprecated } from 'react-is-deprecated'; diff --git a/react-is-deprecated/react-is-deprecated.d.ts b/react-is-deprecated/react-is-deprecated.d.ts index 88a34306a5..a896b68619 100644 --- a/react-is-deprecated/react-is-deprecated.d.ts +++ b/react-is-deprecated/react-is-deprecated.d.ts @@ -3,8 +3,6 @@ // Definitions by: Sean Kelley // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module 'react-is-deprecated' { import { Validator, Requireable, ValidationMap, ReactPropTypes } from 'react'; diff --git a/react-is-deprecated/tsconfig.json b/react-is-deprecated/tsconfig.json new file mode 100644 index 0000000000..08b45699ce --- /dev/null +++ b/react-is-deprecated/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-is-deprecated.d.ts", + "react-is-deprecated-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-jsonschema-form/react-jsonschema-form-tests.tsx b/react-jsonschema-form/react-jsonschema-form-tests.tsx index 5fa0fd914a..0e4e8eeef9 100644 --- a/react-jsonschema-form/react-jsonschema-form-tests.tsx +++ b/react-jsonschema-form/react-jsonschema-form-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react"; import Form from "react-jsonschema-form"; diff --git a/react-jsonschema-form/react-jsonschema-form.d.ts b/react-jsonschema-form/react-jsonschema-form.d.ts index 5004bb132d..a12c95b26d 100644 --- a/react-jsonschema-form/react-jsonschema-form.d.ts +++ b/react-jsonschema-form/react-jsonschema-form.d.ts @@ -3,8 +3,6 @@ // Definitions by: Dan Fox // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "react-jsonschema-form" { import * as React from "react"; diff --git a/react-jsonschema-form/tsconfig.json b/react-jsonschema-form/tsconfig.json new file mode 100644 index 0000000000..b70a03d4ba --- /dev/null +++ b/react-jsonschema-form/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-jsonschema-form.d.ts", + "react-jsonschema-form-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-measure/react-measure-tests.tsx b/react-measure/react-measure-tests.tsx index 9b1a8e2f91..da2a551a04 100644 --- a/react-measure/react-measure-tests.tsx +++ b/react-measure/react-measure-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react"; import * as Measure from "react-measure"; diff --git a/react-measure/react-measure.d.ts b/react-measure/react-measure.d.ts index 7e4a30c39b..8735747bac 100644 --- a/react-measure/react-measure.d.ts +++ b/react-measure/react-measure.d.ts @@ -3,8 +3,6 @@ // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "react-measure" { import * as React from "react"; diff --git a/react-measure/tsconfig.json b/react-measure/tsconfig.json new file mode 100644 index 0000000000..0a0e3ad58e --- /dev/null +++ b/react-measure/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "experimentalDecorators": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "react-measure.d.ts", + "react-measure-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-modal/react-modal-tests.tsx b/react-modal/react-modal-tests.tsx index 40fc2a637e..b153fa0573 100644 --- a/react-modal/react-modal-tests.tsx +++ b/react-modal/react-modal-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react"; import * as ReactModal from 'react-modal'; diff --git a/react-modal/react-modal.d.ts b/react-modal/react-modal.d.ts index 2aac95eacb..4950870b7c 100644 --- a/react-modal/react-modal.d.ts +++ b/react-modal/react-modal.d.ts @@ -3,7 +3,7 @@ // Definitions by: Rajab Shakirov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "react-modal" { interface ReactModal { @@ -23,6 +23,6 @@ declare module "react-modal" { ariaHideApp?: boolean, shouldCloseOnOverlayClick?: boolean } - let ReactModal: __React.ClassicComponentClass; + let ReactModal: React.ClassicComponentClass; export = ReactModal; } diff --git a/react-modal/tsconfig.json b/react-modal/tsconfig.json new file mode 100644 index 0000000000..87f956ff88 --- /dev/null +++ b/react-modal/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "react-modal.d.ts", + "react-modal-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-motion-slider/react-motion-slider-tests.tsx b/react-motion-slider/react-motion-slider-tests.tsx index b51f57fc3b..783f2356a3 100644 --- a/react-motion-slider/react-motion-slider-tests.tsx +++ b/react-motion-slider/react-motion-slider-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react"; import Slider from "react-motion-slider"; diff --git a/react-motion-slider/react-motion-slider.d.ts b/react-motion-slider/react-motion-slider.d.ts index 939500150d..e6046079b7 100644 --- a/react-motion-slider/react-motion-slider.d.ts +++ b/react-motion-slider/react-motion-slider.d.ts @@ -3,10 +3,6 @@ // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// - - declare module "react-motion-slider" { import * as React from "react"; import { OpaqueConfig } from "react-motion"; diff --git a/react-motion-slider/tsconfig.json b/react-motion-slider/tsconfig.json new file mode 100644 index 0000000000..09a7065508 --- /dev/null +++ b/react-motion-slider/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-motion-slider.d.ts", + "react-motion-slider-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-relay/react-relay-test.tsx b/react-relay/react-relay-test.tsx index e6632e76f9..dce5435105 100644 --- a/react-relay/react-relay-test.tsx +++ b/react-relay/react-relay-test.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react" import * as Relay from "react-relay" diff --git a/react-relay/react-relay.d.ts b/react-relay/react-relay.d.ts index 1a0ae89069..08833c8bc5 100644 --- a/react-relay/react-relay.d.ts +++ b/react-relay/react-relay.d.ts @@ -3,8 +3,6 @@ // Definitions by: Johannes Schickling // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "react-relay" { import * as React from "react"; diff --git a/react-relay/tsconfig.json b/react-relay/tsconfig.json new file mode 100644 index 0000000000..c3b3c4e209 --- /dev/null +++ b/react-relay/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-relay.d.ts", + "react-relay-test.tsx" + ] +} \ No newline at end of file diff --git a/react-responsive/react-responsive-tests.tsx b/react-responsive/react-responsive-tests.tsx index 3c1d25c62c..02b948c8a4 100644 --- a/react-responsive/react-responsive-tests.tsx +++ b/react-responsive/react-responsive-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react"; import * as MediaQuery from "react-responsive"; diff --git a/react-responsive/react-responsive.d.ts b/react-responsive/react-responsive.d.ts index 2c92b38413..126a27f5b7 100644 --- a/react-responsive/react-responsive.d.ts +++ b/react-responsive/react-responsive.d.ts @@ -3,8 +3,6 @@ // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "react-responsive" { import * as React from "react"; diff --git a/react-responsive/tsconfig.json b/react-responsive/tsconfig.json new file mode 100644 index 0000000000..a15be69b1e --- /dev/null +++ b/react-responsive/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-responsive.d.ts", + "react-responsive-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-router-redux/index.d.ts b/react-router-redux/index.d.ts index c21622386e..7e8ef4c069 100644 --- a/react-router-redux/index.d.ts +++ b/react-router-redux/index.d.ts @@ -34,7 +34,7 @@ declare namespace ReactRouterRedux { type: string payload?: any } - + interface RouteActions { push: PushAction; replace: ReplaceAction; @@ -45,7 +45,7 @@ declare namespace ReactRouterRedux { interface ReactRouterReduxHistory extends History.History { unsubscribe(): void; } - + interface DefaultSelectLocationState extends Function { (state: any): any; } diff --git a/react-router/index.d.ts b/react-router/index.d.ts index 88edfc846f..7435e492ef 100644 --- a/react-router/index.d.ts +++ b/react-router/index.d.ts @@ -6,7 +6,7 @@ export as namespace ReactRouter; import * as React from 'react'; - + export const routerShape: React.Requireable export const locationShape: React.Requireable @@ -45,6 +45,7 @@ export type EnterHook = Router.EnterHook; export type LeaveHook = Router.LeaveHook; export type ParseQueryString = Router.ParseQueryString; export type RedirectFunction = Router.RedirectFunction; +export type RouteComponent = Router.RouteComponent; export type RouteComponentProps = Router.RouteComponentProps; export type RouteHook = Router.RouteHook; export type StringifyQuery = Router.StringifyQuery; diff --git a/react-router/lib/Router.d.ts b/react-router/lib/Router.d.ts index c885954425..790ec18486 100644 --- a/react-router/lib/Router.d.ts +++ b/react-router/lib/Router.d.ts @@ -93,7 +93,7 @@ declare namespace Router { // push and other functions. // // https://github.com/reactjs/react-router/blob/v2.4.0/upgrade-guides/v2.4.0.md - + interface InjectedRouter { push: (pathOrLoc: History.LocationDescriptor) => void replace: (pathOrLoc: History.LocationDescriptor) => void diff --git a/react-scrollbar/react-scrollbar-tests.tsx b/react-scrollbar/react-scrollbar-tests.tsx index 784a44d899..a782d7b83c 100644 --- a/react-scrollbar/react-scrollbar-tests.tsx +++ b/react-scrollbar/react-scrollbar-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import ScrollArea = require('react-scrollbar'); import * as React from 'react'; diff --git a/react-scrollbar/react-scrollbar.d.ts b/react-scrollbar/react-scrollbar.d.ts index 8df2435678..1abc23921b 100644 --- a/react-scrollbar/react-scrollbar.d.ts +++ b/react-scrollbar/react-scrollbar.d.ts @@ -3,10 +3,10 @@ // Definitions by: Stephen Jelfs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "react-scrollbar" { - interface ScrollAreaProps extends __React.Props { + interface ScrollAreaProps extends React.Props { className?: string, style?: __React.CSSProperties, speed?: number, @@ -26,7 +26,7 @@ declare module "react-scrollbar" { swapWheelAxes?: boolean } - class ScrollArea extends __React.Component {} + class ScrollArea extends React.Component {} export = ScrollArea; } diff --git a/react-scrollbar/tsconfig.json b/react-scrollbar/tsconfig.json new file mode 100644 index 0000000000..1f4f102561 --- /dev/null +++ b/react-scrollbar/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "react-scrollbar.d.ts", + "react-scrollbar-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-slick/react-slick-test.tsx b/react-slick/react-slick-test.tsx index c351419401..7b51dbdf3a 100644 --- a/react-slick/react-slick-test.tsx +++ b/react-slick/react-slick-test.tsx @@ -1,7 +1,3 @@ -/// -/// -/// - import * as React from "react" import * as ReactDOM from "react-dom" import * as Slider from "react-slick" diff --git a/react-slick/react-slick.d.ts b/react-slick/react-slick.d.ts index 43c9cdcf69..9bd267cad1 100644 --- a/react-slick/react-slick.d.ts +++ b/react-slick/react-slick.d.ts @@ -3,7 +3,7 @@ // Definitions by: Andrey Balokha // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface __config { className?: string @@ -45,6 +45,6 @@ interface Slider extends __config { } declare module "react-slick" { - var Slider: __React.ClassicComponentClass; + var Slider: React.ClassicComponentClass; export = Slider; } diff --git a/react-slick/tsconfig.json b/react-slick/tsconfig.json new file mode 100644 index 0000000000..f29388a78f --- /dev/null +++ b/react-slick/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "react-slick.d.ts", + "react-slick-test.tsx" + ] +} \ No newline at end of file diff --git a/react-sortable-hoc/react-sortable-hoc-tests.tsx b/react-sortable-hoc/react-sortable-hoc-tests.tsx index 9c382c4855..0e90f9aa0a 100644 --- a/react-sortable-hoc/react-sortable-hoc-tests.tsx +++ b/react-sortable-hoc/react-sortable-hoc-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import React = require('react'); import ReactDOM = require('react-dom'); import ReactSortableHOC = require('react-sortable-hoc'); diff --git a/react-sortable-hoc/react-sortable-hoc.d.ts b/react-sortable-hoc/react-sortable-hoc.d.ts index a229eb6f43..b65bae7641 100644 --- a/react-sortable-hoc/react-sortable-hoc.d.ts +++ b/react-sortable-hoc/react-sortable-hoc.d.ts @@ -3,8 +3,6 @@ // Definitions by: Ivo Stratev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module 'react-sortable-hoc' { import React = require('react'); @@ -18,7 +16,7 @@ declare module 'react-sortable-hoc' { collection: Offset; } - export type SortEvent = React.MouseEvent | React.TouchEvent; + export type SortEvent = React.MouseEvent | React.TouchEvent; export type SortStartHandler = (sort: SortStart, event: SortEvent) => void; diff --git a/react-sortable-hoc/tsconfig.json b/react-sortable-hoc/tsconfig.json new file mode 100644 index 0000000000..595b57b362 --- /dev/null +++ b/react-sortable-hoc/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "react-sortable-hoc.d.ts", + "react-sortable-hoc-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-split-pane/react-split-pane-tests.tsx b/react-split-pane/react-split-pane-tests.tsx index 7aa6c006e6..46a13653fd 100644 --- a/react-split-pane/react-split-pane-tests.tsx +++ b/react-split-pane/react-split-pane-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react"; import * as SplitPane from "react-split-pane"; diff --git a/react-split-pane/react-split-pane.d.ts b/react-split-pane/react-split-pane.d.ts index e3d7f959de..3a6bc7bc6e 100644 --- a/react-split-pane/react-split-pane.d.ts +++ b/react-split-pane/react-split-pane.d.ts @@ -3,7 +3,7 @@ // Definitions by: Roger Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace ReactSplitPane { interface ReactSplitPaneProps { @@ -32,7 +32,7 @@ declare namespace ReactSplitPane { split?: string; } - interface ReactSplitPaneClass extends __React.ComponentClass { } + interface ReactSplitPaneClass extends React.ComponentClass { } } declare module "react-split-pane" { diff --git a/react-split-pane/tsconfig.json b/react-split-pane/tsconfig.json new file mode 100644 index 0000000000..e6db5fa417 --- /dev/null +++ b/react-split-pane/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "react-split-pane.d.ts", + "react-split-pane-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-swipeable/react-swipeable-tests.tsx b/react-swipeable/react-swipeable-tests.tsx index d28d6d348b..7e8682ade7 100644 --- a/react-swipeable/react-swipeable-tests.tsx +++ b/react-swipeable/react-swipeable-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import Swipeable = require('react-swipeable'); import React = require('react'); diff --git a/react-swipeable/react-swipeable.d.ts b/react-swipeable/react-swipeable.d.ts index db0d7b5e4f..97d2842d47 100644 --- a/react-swipeable/react-swipeable.d.ts +++ b/react-swipeable/react-swipeable.d.ts @@ -3,26 +3,23 @@ // Definitions by: Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace ReactSwipeableModule { - - import React = __React; - interface onSwipingCallback { - (event: React.TouchEvent, deltaX: number, deltaY: number, absX: number, absY: number, velocity: number): void; + (event: React.TouchEvent, deltaX: number, deltaY: number, absX: number, absY: number, velocity: number): void; } interface OnSwipedCallback { - (event: React.TouchEvent, deltaX: number, deltaY: number, isFlick: boolean): void; + (event: React.TouchEvent, deltaX: number, deltaY: number, isFlick: boolean): void; } interface OnSwipedDirectionCallback { - (event: React.TouchEvent, delta: number, isFlick: boolean): void; + (event: React.TouchEvent, delta: number, isFlick: boolean): void; } interface OnSwipingDirectionCallback { - (event: React.TouchEvent, delta: number): void; + (event: React.TouchEvent, delta: number): void; } interface Props { diff --git a/react-swipeable/tsconfig.json b/react-swipeable/tsconfig.json new file mode 100644 index 0000000000..02fd1d28d5 --- /dev/null +++ b/react-swipeable/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-swipeable.d.ts", + "react-swipeable-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-textarea-autosize/react-textarea-autosize-tests.tsx b/react-textarea-autosize/react-textarea-autosize-tests.tsx index d87117fa44..b10f92bc6f 100644 --- a/react-textarea-autosize/react-textarea-autosize-tests.tsx +++ b/react-textarea-autosize/react-textarea-autosize-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react"; import Textarea from "react-textarea-autosize"; diff --git a/react-textarea-autosize/react-textarea-autosize.d.ts b/react-textarea-autosize/react-textarea-autosize.d.ts index 6a4d290937..ebf589f873 100644 --- a/react-textarea-autosize/react-textarea-autosize.d.ts +++ b/react-textarea-autosize/react-textarea-autosize.d.ts @@ -3,9 +3,6 @@ // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - - declare module "react-textarea-autosize" { import * as React from "react"; @@ -21,7 +18,7 @@ declare module "react-textarea-autosize" { * Callback on value change * @param event */ - onChange?: (event: React.FormEvent) => void; + onChange?: (event: React.FormEvent) => void; /** * Callback on height change * @param height diff --git a/react-textarea-autosize/tsconfig.json b/react-textarea-autosize/tsconfig.json new file mode 100644 index 0000000000..5f7456c652 --- /dev/null +++ b/react-textarea-autosize/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-textarea-autosize.d.ts", + "react-textarea-autosize-tests.tsx" + ] +} \ No newline at end of file diff --git a/react-user-tour/react-user-tour-tests.tsx b/react-user-tour/react-user-tour-tests.tsx index 5cfe3f3dab..35b8067f55 100644 --- a/react-user-tour/react-user-tour-tests.tsx +++ b/react-user-tour/react-user-tour-tests.tsx @@ -3,9 +3,7 @@ // Definitions by: Carlo Cancellieri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// +/// import React = require('react'); import ReactDOM = require('react-dom'); @@ -46,7 +44,7 @@ class TestApp extends React.Component<{}, State> { ]} />; - return
    + return
    {Tour}
    ; } diff --git a/react-user-tour/react-user-tour-tests.tsx.tscparams b/react-user-tour/react-user-tour-tests.tsx.tscparams deleted file mode 100644 index b238f4f2a8..0000000000 --- a/react-user-tour/react-user-tour-tests.tsx.tscparams +++ /dev/null @@ -1 +0,0 @@ ---noImplicitAny --jsx react diff --git a/react-user-tour/react-user-tour.d.ts b/react-user-tour/react-user-tour.d.ts index 1237977dd1..f1a0de4d46 100644 --- a/react-user-tour/react-user-tour.d.ts +++ b/react-user-tour/react-user-tour.d.ts @@ -3,7 +3,7 @@ // Definitions by: Carlo Cancellieri // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'react-user-tour' { @@ -22,11 +22,11 @@ declare module 'react-user-tour' { /** a react element representing the header of the current step */ - title: string; + title: string | JSX.Element; /** a react element representing the main body message of the tour step */ - body: string; + body: string | JSX.Element; /** Optional properties horizontalOffset and verticalOffset values allow to move tooltip around pointed element. */ @@ -41,7 +41,7 @@ declare module 'react-user-tour' { position?: 'left' | 'right' | 'top' | 'topLeft' | 'bottom' | 'bottomLeft'; } - interface TourProps extends HTMLAttributes { + interface TourProps extends HTMLAttributes { /** A boolean value representing whether or not the tour should currently be displayed */ diff --git a/react-user-tour/tsconfig.json b/react-user-tour/tsconfig.json new file mode 100644 index 0000000000..6ba3336beb --- /dev/null +++ b/react-user-tour/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "react-user-tour.d.ts", + "react-user-tour-tests.tsx" + ] +} \ No newline at end of file diff --git a/redux-bootstrap/redux-bootstrap-tests.tsx b/redux-bootstrap/redux-bootstrap-tests.tsx index b769063e3e..1630e759a5 100644 --- a/redux-bootstrap/redux-bootstrap-tests.tsx +++ b/redux-bootstrap/redux-bootstrap-tests.tsx @@ -1,5 +1,3 @@ -/// - import bootstrap from "redux-bootstrap"; let routes: JSX.Element = null; diff --git a/redux-bootstrap/redux-bootstrap.d.ts b/redux-bootstrap/redux-bootstrap.d.ts index 2bfdc53f31..b01baa72cd 100644 --- a/redux-bootstrap/redux-bootstrap.d.ts +++ b/redux-bootstrap/redux-bootstrap.d.ts @@ -3,11 +3,11 @@ // Definitions by: Remo H. Jansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// +/// +/// declare module "redux-bootstrap" { + import ReactRouterRedux = require("react-router-redux"); interface BootstrapOptions { routes: JSX.Element; diff --git a/redux-bootstrap/tsconfig.json b/redux-bootstrap/tsconfig.json new file mode 100644 index 0000000000..e5e83c285f --- /dev/null +++ b/redux-bootstrap/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "redux-bootstrap.d.ts", + "redux-bootstrap-tests.tsx" + ] +} \ No newline at end of file diff --git a/redux-mock-store/redux-mock-store-tests.ts b/redux-mock-store/redux-mock-store-tests.ts index 960591f8fb..373a3f8fd1 100644 --- a/redux-mock-store/redux-mock-store-tests.ts +++ b/redux-mock-store/redux-mock-store-tests.ts @@ -1,5 +1,4 @@ -/// - +import * as Redux from 'redux'; import configureStore, {IStore} from 'redux-mock-store'; // Redux store API tests diff --git a/redux-mock-store/redux-mock-store.d.ts b/redux-mock-store/redux-mock-store.d.ts index 6cc463e2d1..ad37ad4e06 100644 --- a/redux-mock-store/redux-mock-store.d.ts +++ b/redux-mock-store/redux-mock-store.d.ts @@ -3,7 +3,7 @@ // Definitions by: Marian Palkus , Cap3 // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module 'redux-mock-store' { import * as Redux from 'redux' diff --git a/redux-mock-store/tsconfig.json b/redux-mock-store/tsconfig.json new file mode 100644 index 0000000000..9e015629bd --- /dev/null +++ b/redux-mock-store/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "redux-mock-store.d.ts", + "redux-mock-store-tests.ts" + ] +} \ No newline at end of file diff --git a/redux-optimistic-ui/redux-optimistic-ui-tests.ts b/redux-optimistic-ui/redux-optimistic-ui-tests.ts index a2e67fa4b6..77c3a72d0e 100644 --- a/redux-optimistic-ui/redux-optimistic-ui-tests.ts +++ b/redux-optimistic-ui/redux-optimistic-ui-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import { Action } from "redux"; import { OptimisticState, OptimisticAction, BEGIN, optimistic, ensureState } from "redux-optimistic-ui"; diff --git a/redux-optimistic-ui/redux-optimistic-ui.d.ts b/redux-optimistic-ui/redux-optimistic-ui.d.ts index f487a64ffd..0471712c6a 100644 --- a/redux-optimistic-ui/redux-optimistic-ui.d.ts +++ b/redux-optimistic-ui/redux-optimistic-ui.d.ts @@ -3,7 +3,7 @@ // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "redux-optimistic-ui" { import { Reducer } from "redux"; diff --git a/redux-optimistic-ui/tsconfig.json b/redux-optimistic-ui/tsconfig.json new file mode 100644 index 0000000000..8de339b93a --- /dev/null +++ b/redux-optimistic-ui/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "redux-optimistic-ui.d.ts", + "redux-optimistic-ui-tests.ts" + ] +} \ No newline at end of file diff --git a/redux-promise-middleware/redux-promise-middleware-tests.ts b/redux-promise-middleware/redux-promise-middleware-tests.ts index 64fde63170..788a3faee3 100644 --- a/redux-promise-middleware/redux-promise-middleware-tests.ts +++ b/redux-promise-middleware/redux-promise-middleware-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import { createStore, applyMiddleware, Store, Dispatch } from "redux"; import promiseMiddleware from "redux-promise-middleware"; @@ -38,7 +35,7 @@ const actionCreator1 = () => ({ const actionCreator2 = () => ({ type: "FIRST_ACTION_TYPE", payload: { - promise: Promise.resolve((action: string, dispatch: Redux.Dispatch, getState: Function) => { + promise: Promise.resolve((action: string, dispatch: Dispatch, getState: Function) => { dispatch({ type: "SECEOND_ACTION_TYPE", payload: "..." }); dispatch(someActionCreator()); }) diff --git a/redux-promise-middleware/redux-promise-middleware.d.ts b/redux-promise-middleware/redux-promise-middleware.d.ts index e1350cde0e..832d1d9725 100644 --- a/redux-promise-middleware/redux-promise-middleware.d.ts +++ b/redux-promise-middleware/redux-promise-middleware.d.ts @@ -3,7 +3,7 @@ // Definitions by: ianks // Definitions: https://github.com/borisyankov/DefinitelyTyped -/// +/// declare module "redux-promise-middleware" { function promiseMiddleware(config?: { promiseTypeSuffixes: string[] }): Redux.Middleware; diff --git a/redux-promise-middleware/tsconfig.json b/redux-promise-middleware/tsconfig.json new file mode 100644 index 0000000000..380792b821 --- /dev/null +++ b/redux-promise-middleware/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "redux-promise-middleware.d.ts", + "redux-promise-middleware-tests.ts" + ] +} \ No newline at end of file diff --git a/redux-storage/redux-storage-tests.ts b/redux-storage/redux-storage-tests.ts index 484366c925..2be0d91db2 100644 --- a/redux-storage/redux-storage-tests.ts +++ b/redux-storage/redux-storage-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import { Action, createStore, applyMiddleware } from "redux"; import { reducer, createMiddleware, createLoader } from "redux-storage"; import reduxStorageImmutableMerger from "redux-storage-merger-immutablejs"; diff --git a/redux-storage/redux-storage.d.ts b/redux-storage/redux-storage.d.ts index e9583d157b..dac23aeebc 100644 --- a/redux-storage/redux-storage.d.ts +++ b/redux-storage/redux-storage.d.ts @@ -3,7 +3,7 @@ // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "redux-storage" { import { Reducer, Store, Middleware } from "redux"; diff --git a/redux-storage/tsconfig.json b/redux-storage/tsconfig.json new file mode 100644 index 0000000000..2559181263 --- /dev/null +++ b/redux-storage/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "redux-storage.d.ts", + "redux-storage-tests.ts" + ] +} \ No newline at end of file diff --git a/redux-ui/redux-ui-tests.ts b/redux-ui/redux-ui-tests.ts index 5576a19b9d..63ac16c84e 100644 --- a/redux-ui/redux-ui-tests.ts +++ b/redux-ui/redux-ui-tests.ts @@ -1,7 +1,5 @@ -/// -/// - import * as React from 'react' +import * as Redux from 'redux' import ui, { ReduxUIProps, reducer } from 'redux-ui' type UIShape = { diff --git a/redux-ui/redux-ui.d.ts b/redux-ui/redux-ui.d.ts index 6114931320..f38cd16ec1 100644 --- a/redux-ui/redux-ui.d.ts +++ b/redux-ui/redux-ui.d.ts @@ -3,8 +3,6 @@ // Definitions by: Andy Shu Xin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare module "redux-ui" { import * as Redux from 'redux'; diff --git a/redux-ui/tsconfig.json b/redux-ui/tsconfig.json new file mode 100644 index 0000000000..7bfc0fc3b7 --- /dev/null +++ b/redux-ui/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "experimentalDecorators": true + }, + "files": [ + "redux-ui.d.ts", + "redux-ui-tests.ts" + ] +} \ No newline at end of file diff --git a/restler/restler.d.ts b/restler/restler.d.ts index 389203066d..f33bf3f24f 100644 --- a/restler/restler.d.ts +++ b/restler/restler.d.ts @@ -3,7 +3,7 @@ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "restler" { import * as http from "http"; diff --git a/restler/tsconfig.json b/restler/tsconfig.json new file mode 100644 index 0000000000..4d717eca0b --- /dev/null +++ b/restler/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "restler.d.ts", + "restler-tests.ts" + ] +} \ No newline at end of file diff --git a/rx-node/rx-node-tests.ts b/rx-node/rx-node-tests.ts index bd66ac10d5..13f6906107 100644 --- a/rx-node/rx-node-tests.ts +++ b/rx-node/rx-node-tests.ts @@ -3,9 +3,6 @@ // Definitions by: Andre Luiz dos Santos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// - { var source = Rx.Observable.return(42); var emitter = RxNode.toEventEmitter(source, 'data'); diff --git a/rx-node/rx-node.d.ts b/rx-node/rx-node.d.ts index 14af714359..8836fcee97 100644 --- a/rx-node/rx-node.d.ts +++ b/rx-node/rx-node.d.ts @@ -3,8 +3,8 @@ // Definitions by: Andre Luiz dos Santos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare namespace RxNode { diff --git a/rx-node/tsconfig.json b/rx-node/tsconfig.json new file mode 100644 index 0000000000..e3bd39f99b --- /dev/null +++ b/rx-node/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "rx-node.d.ts", + "rx-node-tests.ts" + ] +} \ No newline at end of file diff --git a/rx.wamp/rx-wamp.d.ts b/rx.wamp/index.d.ts similarity index 89% rename from rx.wamp/rx-wamp.d.ts rename to rx.wamp/index.d.ts index 839fa35120..1a8027c878 100644 --- a/rx.wamp/rx-wamp.d.ts +++ b/rx.wamp/index.d.ts @@ -3,8 +3,8 @@ // Definitions by: Elad Zelingher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +import autobahn = require("autobahn"); +import * as Rx from "rx"; interface IWampEvent { args?: any[]; @@ -40,8 +40,9 @@ interface IPubSubSubject extends Rx.Observable, Rx.Observer; } -// Patch ObservableStatic to contain observableWamp methods. -declare namespace Rx { - interface ObservableStatic extends IObservableWampStatic { - } -} \ No newline at end of file +export as namespace RxWamp; + +declare module "rx" { + // Patch ObservableStatic to contain observableWamp methods. + interface ObservableStatic extends IObservableWampStatic {} +} diff --git a/rx.wamp/rx-wamp-tests.ts b/rx.wamp/rx.wamp-tests.ts similarity index 97% rename from rx.wamp/rx-wamp-tests.ts rename to rx.wamp/rx.wamp-tests.ts index c51eff3744..31ec3bd442 100644 --- a/rx.wamp/rx-wamp-tests.ts +++ b/rx.wamp/rx.wamp-tests.ts @@ -1,5 +1,6 @@ -/// -/// +/// +import * as autobahn from "autobahn"; +import {IWampEvent} from "rx.wamp"; function nodeJS(session: autobahn.Session) { var sessionObservable = @@ -151,7 +152,7 @@ function weather_station_monitor(session: autobahn.Session) { .flatMap(readings => analyzer(readings)) .publish().refCount(); - //Warn of inclement weather coming in + //Warn of inclement weather coming in dailyForecast //only get warnings .filter(weather => (weather.warnings.length > 0)) diff --git a/rx.wamp/tsconfig.json b/rx.wamp/tsconfig.json new file mode 100644 index 0000000000..cbaff055f8 --- /dev/null +++ b/rx.wamp/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rx.wamp-tests.ts" + ] +} \ No newline at end of file diff --git a/rx/rx.aggregates.d.ts b/rx/rx.aggregates.d.ts index 8dfc17634a..68b2ed50ec 100644 --- a/rx/rx.aggregates.d.ts +++ b/rx/rx.aggregates.d.ts @@ -3,7 +3,7 @@ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { export interface Observable { diff --git a/rx/rx.all.d.ts b/rx/rx.all.d.ts index 52f66882e4..404b364fd0 100644 --- a/rx/rx.all.d.ts +++ b/rx/rx.all.d.ts @@ -3,15 +3,15 @@ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// -/// -/// -/// -/// -/// -/// +/// +/// +/// +/// +/// +/// +/// +/// +/// /// diff --git a/rx/rx.async.d.ts b/rx/rx.async.d.ts index ec7effa67b..582e94c723 100644 --- a/rx/rx.async.d.ts +++ b/rx/rx.async.d.ts @@ -3,7 +3,7 @@ // Definitions by: zoetrope , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare namespace Rx { diff --git a/rx/rx.binding.d.ts b/rx/rx.binding.d.ts index 3d6c3db48d..5dab889ca1 100644 --- a/rx/rx.binding.d.ts +++ b/rx/rx.binding.d.ts @@ -3,7 +3,7 @@ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare module "rx.binding" { diff --git a/rx/rx.coincidence.d.ts b/rx/rx.coincidence.d.ts index b39f9ac103..a39f224367 100644 --- a/rx/rx.coincidence.d.ts +++ b/rx/rx.coincidence.d.ts @@ -3,7 +3,7 @@ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare namespace Rx { diff --git a/rx/rx.experimental.d.ts b/rx/rx.experimental.d.ts index 9bfa2cc863..3f4dd40752 100644 --- a/rx/rx.experimental.d.ts +++ b/rx/rx.experimental.d.ts @@ -3,7 +3,7 @@ // Definitions by: Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { diff --git a/rx/rx.joinpatterns.d.ts b/rx/rx.joinpatterns.d.ts index fa3c46b2ec..49080f7058 100644 --- a/rx/rx.joinpatterns.d.ts +++ b/rx/rx.joinpatterns.d.ts @@ -3,7 +3,7 @@ // Definitions by: Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { diff --git a/rx/rx.testing.d.ts b/rx/rx.testing.d.ts index e654a33a2a..2415e3fe30 100644 --- a/rx/rx.testing.d.ts +++ b/rx/rx.testing.d.ts @@ -3,7 +3,7 @@ // Definitions by: Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare namespace Rx { diff --git a/rx/rx.time.d.ts b/rx/rx.time.d.ts index 2525756f7c..84f23b0cfe 100644 --- a/rx/rx.time.d.ts +++ b/rx/rx.time.d.ts @@ -3,7 +3,7 @@ // Definitions by: Carl de Billy , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /// declare namespace Rx { diff --git a/rx/rx.virtualtime.d.ts b/rx/rx.virtualtime.d.ts index 3297703862..908eeebb6d 100644 --- a/rx/rx.virtualtime.d.ts +++ b/rx/rx.virtualtime.d.ts @@ -3,7 +3,7 @@ // Definitions by: gsino , Igor Oleinikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Rx { export interface VirtualTimeScheduler extends Scheduler { diff --git a/samchon-collection/samchon-collection-tests.ts b/samchon-collection/samchon-collection-tests.ts index 5744f11a7a..30724c8904 100644 --- a/samchon-collection/samchon-collection-tests.ts +++ b/samchon-collection/samchon-collection-tests.ts @@ -1,4 +1,2 @@ -/// - import collection = require("samchon-collection"); console.log(collection); \ No newline at end of file diff --git a/samchon-collection/samchon-collection.d.ts b/samchon-collection/samchon-collection.d.ts index 0bff8791f9..5f62a81d42 100644 --- a/samchon-collection/samchon-collection.d.ts +++ b/samchon-collection/samchon-collection.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "samchon-collection" { diff --git a/samchon-collection/tsconfig.json b/samchon-collection/tsconfig.json new file mode 100644 index 0000000000..a429882ac7 --- /dev/null +++ b/samchon-collection/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "samchon-collection.d.ts", + "samchon-collection-tests.ts" + ] +} \ No newline at end of file diff --git a/samchon-framework/samchon-framework.d.ts b/samchon-framework/index.d.ts similarity index 99% rename from samchon-framework/samchon-framework.d.ts rename to samchon-framework/index.d.ts index a6d03758dd..a2e621b024 100644 --- a/samchon-framework/samchon-framework.d.ts +++ b/samchon-framework/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "samchon-framework" { @@ -4620,12 +4620,12 @@ declare namespace samchon.protocol { class MyServer extends Something implements IServer { private server_base: IServerBase = new WebServerBase(this); - + public addClient(driver: IClientDriver): void { // WHAT TO DO WHEN A CLIENT HAS CONNECTED } - + public open(port: number): void { this.server_base.open(); diff --git a/samchon-framework/samchon-framework-tests.ts b/samchon-framework/samchon-framework-tests.ts index 88c2632a37..5a35470d4b 100644 --- a/samchon-framework/samchon-framework-tests.ts +++ b/samchon-framework/samchon-framework-tests.ts @@ -1,4 +1,2 @@ -/// - import samchon = require("samchon-framework"); console.log(samchon); \ No newline at end of file diff --git a/samchon-framework/tsconfig.json b/samchon-framework/tsconfig.json new file mode 100644 index 0000000000..95b43d51d8 --- /dev/null +++ b/samchon-framework/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "samchon-framework-tests.ts" + ] +} \ No newline at end of file diff --git a/samchon-library/samchon-library-tests.ts b/samchon-library/samchon-library-tests.ts index 186a2f0348..9f60d43b11 100644 --- a/samchon-library/samchon-library-tests.ts +++ b/samchon-library/samchon-library-tests.ts @@ -1,4 +1,2 @@ -/// - import library = require("samchon-library"); console.log(library); \ No newline at end of file diff --git a/samchon-library/samchon-library.d.ts b/samchon-library/samchon-library.d.ts index 1ae5be40e5..305a9c63ca 100644 --- a/samchon-library/samchon-library.d.ts +++ b/samchon-library/samchon-library.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jeongho Nam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "samchon-library" { diff --git a/samchon-library/tsconfig.json b/samchon-library/tsconfig.json new file mode 100644 index 0000000000..e0415f7dce --- /dev/null +++ b/samchon-library/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "samchon-library.d.ts", + "samchon-library-tests.ts" + ] +} \ No newline at end of file diff --git a/samlp/samlp-tests.ts b/samlp/samlp-tests.ts index 7039e1c949..8bb3399062 100644 --- a/samlp/samlp-tests.ts +++ b/samlp/samlp-tests.ts @@ -1,7 +1,3 @@ -/// -/// -/// - import * as fs from 'fs'; import * as path from 'path'; import * as express from 'express'; diff --git a/samlp/samlp.d.ts b/samlp/samlp.d.ts index 5d0ffef0d5..81b8ae5b60 100644 --- a/samlp/samlp.d.ts +++ b/samlp/samlp.d.ts @@ -3,8 +3,8 @@ // Definitions by: horiuchi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module "samlp" { diff --git a/samlp/tsconfig.json b/samlp/tsconfig.json new file mode 100644 index 0000000000..b15ade33c8 --- /dev/null +++ b/samlp/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "samlp.d.ts", + "samlp-tests.ts" + ] +} \ No newline at end of file diff --git a/set-cookie-parser/set-cookie-parser-tests.ts b/set-cookie-parser/set-cookie-parser-tests.ts index 8734fdfcdb..91238ff929 100644 --- a/set-cookie-parser/set-cookie-parser-tests.ts +++ b/set-cookie-parser/set-cookie-parser-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as assert from "assert"; import * as http from "http"; import * as setCookie from "set-cookie-parser"; diff --git a/set-cookie-parser/set-cookie-parser.d.ts b/set-cookie-parser/set-cookie-parser.d.ts index 3cacde6043..9d78a76ce1 100644 --- a/set-cookie-parser/set-cookie-parser.d.ts +++ b/set-cookie-parser/set-cookie-parser.d.ts @@ -3,7 +3,7 @@ // Definitions by: Nick Paddock // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "set-cookie-parser" { import http = require("http"); diff --git a/set-cookie-parser/tsconfig.json b/set-cookie-parser/tsconfig.json new file mode 100644 index 0000000000..a913efaa2f --- /dev/null +++ b/set-cookie-parser/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "set-cookie-parser.d.ts", + "set-cookie-parser-tests.ts" + ] +} \ No newline at end of file diff --git a/sinon-as-promised/sinon-as-promised-tests.ts b/sinon-as-promised/sinon-as-promised-tests.ts index 97ff6aaa3c..b835fe9952 100644 --- a/sinon-as-promised/sinon-as-promised-tests.ts +++ b/sinon-as-promised/sinon-as-promised-tests.ts @@ -1,10 +1,11 @@ -/// +/// + function testResolve() { - sinon.stub().resolves('test val'); + Sinon.stub().resolves('test val'); } function testReject() { - sinon.stub().rejects('test val'); + Sinon.stub().rejects('test val'); } testResolve(); diff --git a/sinon-as-promised/sinon-as-promised.d.ts b/sinon-as-promised/sinon-as-promised.d.ts index 3a214ea254..ab75217011 100644 --- a/sinon-as-promised/sinon-as-promised.d.ts +++ b/sinon-as-promised/sinon-as-promised.d.ts @@ -3,11 +3,10 @@ // Definitions by: igrayson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as s from "sinon"; -declare namespace Sinon { - - export interface SinonStub { +declare module "sinon" { + interface SinonStub { /** * When called, the stub will return a "thenable" object which will return a promise for the provided value. Any Promises/A+ compliant library will handle this object properly. @@ -15,9 +14,9 @@ declare namespace Sinon { resolves(value:any):SinonStub; /** - * When called, the stub will return a thenable which will return a reject promise with the provided err. If err is a string, it will be set as the message on an Error object. + * When called, the stub will return a thenable which ill return a reject promise with the provided err. If err is a string, it will be set as the message on an Error object. */ rejects(err:any):SinonStub; - } + } } diff --git a/sinon-as-promised/tsconfig.json b/sinon-as-promised/tsconfig.json new file mode 100644 index 0000000000..401bb42813 --- /dev/null +++ b/sinon-as-promised/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "sinon-as-promised.d.ts", + "sinon-as-promised-tests.ts" + ] +} \ No newline at end of file diff --git a/sinon/index.d.ts b/sinon/index.d.ts index 7ea857019a..3991db8aac 100644 --- a/sinon/index.d.ts +++ b/sinon/index.d.ts @@ -431,3 +431,4 @@ declare namespace Sinon { declare var Sinon: Sinon.SinonStatic; export = Sinon; +export as namespace Sinon; diff --git a/socket.io-parser/socket.io-parser-tests.ts b/socket.io-parser/socket.io-parser-tests.ts index 917f72500f..07646f48ce 100644 --- a/socket.io-parser/socket.io-parser-tests.ts +++ b/socket.io-parser/socket.io-parser-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as parser from 'socket.io-parser'; var encoder = new parser.Encoder(); var packet = { diff --git a/socket.io-parser/socket.io-parser.d.ts b/socket.io-parser/socket.io-parser.d.ts index 0c4903fda4..5f1a7a104e 100644 --- a/socket.io-parser/socket.io-parser.d.ts +++ b/socket.io-parser/socket.io-parser.d.ts @@ -3,7 +3,7 @@ // Definitions by: York Yao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "socket.io-parser" { namespace Parser { diff --git a/socket.io-parser/tsconfig.json b/socket.io-parser/tsconfig.json new file mode 100644 index 0000000000..3f1b76a17d --- /dev/null +++ b/socket.io-parser/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "socket.io-parser.d.ts", + "socket.io-parser-tests.ts" + ] +} \ No newline at end of file diff --git a/spectacle/spectacle-tests.tsx b/spectacle/spectacle-tests.tsx index f8c84b6455..5f0c959a50 100644 --- a/spectacle/spectacle-tests.tsx +++ b/spectacle/spectacle-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - /** * Spectacle Test Examples * diff --git a/spectacle/spectacle.d.ts b/spectacle/spectacle.d.ts index 05f8d9d528..55227fbb2c 100644 --- a/spectacle/spectacle.d.ts +++ b/spectacle/spectacle.d.ts @@ -3,7 +3,8 @@ // Definitions by: Zachary Maybury // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// + declare module "spectacle" { import * as React from "react"; diff --git a/spectacle/tsconfig.json b/spectacle/tsconfig.json new file mode 100644 index 0000000000..3c7af053b3 --- /dev/null +++ b/spectacle/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "spectacle.d.ts", + "spectacle-tests.tsx" + ] +} \ No newline at end of file diff --git a/split2/split2-tests.ts b/split2/split2-tests.ts index 2e09612c3b..35d0b58684 100644 --- a/split2/split2-tests.ts +++ b/split2/split2-tests.ts @@ -1,5 +1,3 @@ -/// -/// import * as split from 'split2'; import * as fs from 'fs'; import { Transform, TransformOptions } from 'stream'; diff --git a/split2/split2.d.ts b/split2/split2.d.ts index 4ba12ae478..251bcb01b5 100644 --- a/split2/split2.d.ts +++ b/split2/split2.d.ts @@ -3,7 +3,7 @@ // Definitions by: TANAKA Koichi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "split2" { import { Transform, TransformOptions } from 'stream'; diff --git a/split2/tsconfig.json b/split2/tsconfig.json new file mode 100644 index 0000000000..c53b9e6d26 --- /dev/null +++ b/split2/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "split2.d.ts", + "split2-tests.ts" + ] +} \ No newline at end of file diff --git a/sqs-consumer/sqs-consumer-tests.ts b/sqs-consumer/sqs-consumer-tests.ts index 516aeb6adf..7b44cff23e 100644 --- a/sqs-consumer/sqs-consumer-tests.ts +++ b/sqs-consumer/sqs-consumer-tests.ts @@ -1,11 +1,9 @@ -/// - import * as Consumer from "sqs-consumer"; var app = Consumer.create({ queueUrl: 'https://sqs.eu-west-1.amazonaws.com/account-id/queue-name', handleMessage: function (message, done) { - // do some work with `message` + // do some work with `message` done(); } }); @@ -20,9 +18,9 @@ var app2 = Consumer.create({ visibilityTimeout: 50, waitTimeSeconds: 50 }); - + app.on('error', function (err: any) { console.log(err.message); }); - + app.start(); diff --git a/sqs-consumer/sqs-consumer.d.ts b/sqs-consumer/sqs-consumer.d.ts index 8c2315d083..9d5121944f 100644 --- a/sqs-consumer/sqs-consumer.d.ts +++ b/sqs-consumer/sqs-consumer.d.ts @@ -3,18 +3,18 @@ // Definitions by: Daniel Chao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "sqs-consumer" { - + import { SQS } from "aws-sdk"; - + module SQSConsumer { - + interface MessageHandler { (message: SQS.Message, done: Function): any; } - + interface ConsumerOpts { queueUrl: string; handleMessage: MessageHandler; @@ -27,17 +27,17 @@ declare module "sqs-consumer" { authenticationErrorTimeout?: number; sqs?: SQS; } - + interface Consumer extends NodeJS.EventEmitter { start (): void; stop (): void; } - + interface ConsumerFactory { create(opts: ConsumerOpts): Consumer; } } const Consumer: SQSConsumer.ConsumerFactory; export = Consumer; - + } diff --git a/sqs-consumer/tsconfig.json b/sqs-consumer/tsconfig.json new file mode 100644 index 0000000000..b485ab29dd --- /dev/null +++ b/sqs-consumer/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "sqs-consumer.d.ts", + "sqs-consumer-tests.ts" + ] +} \ No newline at end of file diff --git a/sqs-producer/sqs-producer-tests.ts b/sqs-producer/sqs-producer-tests.ts index f224ab11fb..9c4a7afbdb 100644 --- a/sqs-producer/sqs-producer-tests.ts +++ b/sqs-producer/sqs-producer-tests.ts @@ -1,8 +1,5 @@ // Taken straight from sqs-producer's README.md -/// - - import * as Producer from "sqs-producer"; var producer = Producer.create({ diff --git a/sqs-producer/sqs-producer.d.ts b/sqs-producer/sqs-producer.d.ts index 10638f90c5..de41b0a03b 100644 --- a/sqs-producer/sqs-producer.d.ts +++ b/sqs-producer/sqs-producer.d.ts @@ -3,7 +3,7 @@ // Definitions by: Daniel Chao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "sqs-producer" { diff --git a/sqs-producer/tsconfig.json b/sqs-producer/tsconfig.json new file mode 100644 index 0000000000..375eb798b3 --- /dev/null +++ b/sqs-producer/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "sqs-producer.d.ts", + "sqs-producer-tests.ts" + ] +} \ No newline at end of file diff --git a/ssh2-sftp-client/ssh2-sftp-client-tests.ts b/ssh2-sftp-client/ssh2-sftp-client-tests.ts index 0c2709bf61..0c6817a064 100644 --- a/ssh2-sftp-client/ssh2-sftp-client-tests.ts +++ b/ssh2-sftp-client/ssh2-sftp-client-tests.ts @@ -1,5 +1,3 @@ -/// - import * as Client from 'ssh2-sftp-client'; var client = new Client(); diff --git a/ssh2-sftp-client/ssh2-sftp-client.d.ts b/ssh2-sftp-client/ssh2-sftp-client.d.ts index 1676ad0077..587e8f97f0 100644 --- a/ssh2-sftp-client/ssh2-sftp-client.d.ts +++ b/ssh2-sftp-client/ssh2-sftp-client.d.ts @@ -3,7 +3,7 @@ // Definitions by: igrayson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "ssh2-sftp-client" { import * as ssh2 from 'ssh2'; diff --git a/ssh2-sftp-client/tsconfig.json b/ssh2-sftp-client/tsconfig.json new file mode 100644 index 0000000000..205f36fe68 --- /dev/null +++ b/ssh2-sftp-client/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "ssh2-sftp-client.d.ts", + "ssh2-sftp-client-tests.ts" + ] +} \ No newline at end of file diff --git a/suitescript/suitescript.d.ts b/suitescript/index.d.ts similarity index 100% rename from suitescript/suitescript.d.ts rename to suitescript/index.d.ts diff --git a/swagger-express-middleware/swagger-express-middleware-tests.ts b/swagger-express-middleware/swagger-express-middleware-tests.ts index 2af3ab4d0c..cc6854915d 100644 --- a/swagger-express-middleware/swagger-express-middleware-tests.ts +++ b/swagger-express-middleware/swagger-express-middleware-tests.ts @@ -1,5 +1,3 @@ -/// - import * as express from "express"; import * as SwaggerExpressMiddleware from "swagger-express-middleware"; @@ -27,9 +25,9 @@ SwaggerExpressMiddleware("PetStore.yaml", app, (err: any, middleware: SwaggerExp }, raw:{ inflate:false, - limit:100 + limit:100 } - + } app.use( diff --git a/swagger-express-middleware/swagger-express-middleware.d.ts b/swagger-express-middleware/swagger-express-middleware.d.ts index 21e8324ff2..a782fee0d1 100644 --- a/swagger-express-middleware/swagger-express-middleware.d.ts +++ b/swagger-express-middleware/swagger-express-middleware.d.ts @@ -26,7 +26,7 @@ app.listen(8000, function () { =============================================== */ -/// +/// declare module "swagger-express-middleware" { import {Application, Router, RequestHandler, Request, Response} from "express"; @@ -41,21 +41,21 @@ declare module "swagger-express-middleware" { (err: any, middleware: SwaggerMiddleware): void; } export interface SwaggerMiddleware { - /** + /** * Annotates the HTTP request (the `req` object) with Swagger metadata. * This middleware populates Request.swagger */ metadata: MetadataSignature; - /** - * Handles CORS preflight requests and sets CORS headers for all requests according the Swagger API definition. + /** + * Handles CORS preflight requests and sets CORS headers for all requests according the Swagger API definition. */ CORS: CORSSignature; - /** - * Serves the Swagger API file(s) in JSON and YAML formats, so they can be used with third-party front-end tools like Swagger UI and Swagger Editor. + /** + * Serves the Swagger API file(s) in JSON and YAML formats, so they can be used with third-party front-end tools like Swagger UI and Swagger Editor. */ files: FilesSignature; - /** - * Parses the HTTP request into typed values. + /** + * Parses the HTTP request into typed values. */ parseRequest: ParseRequestSignature; /** @@ -116,7 +116,7 @@ declare module "swagger-express-middleware" { options?: ParseRequestOptions): RequestHandler ( /** - * An Express Application or Router. + * An Express Application or Router. * If provided, this will be used to register path-param middleware via Router.Param */ router: Application | Router, @@ -158,7 +158,7 @@ declare module "swagger-express-middleware" { */ multipart?: MulterOptions } - + interface MulterOptions{ /** The destination directory for the uploaded files. */ dest?: string; @@ -183,14 +183,14 @@ declare module "swagger-express-middleware" { }; /** A function to control which files to upload and which to skip. */ fileFilter?: (req: Request, file: File, callback: (error: Error, acceptFile: boolean) => void) => void; - + } - + interface StorageEngine { _handleFile(req: Request, file: File, callback: (error?: any, info?: File) => void): void; _removeFile(req: Request, file: File, callback: (error: Error) => void): void; } - + export interface File { /** Field name specified in the form */ fieldname: string; @@ -218,15 +218,15 @@ declare module "swagger-express-middleware" { */ inflate?: boolean; /** - * Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; + * Controls the maximum request body size. If this is a number, then the value specifies the number of bytes; * if it is a string, the value is passed to the bytes library for parsing. Defaults to '100kb'. */ limit?: string | number; /** - * The type option is used to determine what media type the middleware will parse. - * This option can be a function or a string. + * The type option is used to determine what media type the middleware will parse. + * This option can be a function or a string. * If a string, type option is passed directly to the type-is library and this can be an extension name (like bin), a mime type (like application/octet-stream), or a mime type with a wildcard (like * /* or application/*). - * If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. + * If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. * Defaults to application/octet-stream. */ type?: ((req: Request) => string) | string @@ -238,10 +238,10 @@ declare module "swagger-express-middleware" { } interface CookieParserOptionItem { - /** - * A string or array used for signing cookies. - * This is optional and if not specified, will not parse signed cookies. - * If a string is provided, this is used as the secret. + /** + * A string or array used for signing cookies. + * This is optional and if not specified, will not parse signed cookies. + * If a string is provided, this is used as the secret. * If an array is provided, an attempt will be made to unsign the cookie with each secret in order. */ secret?: string | Array @@ -257,20 +257,20 @@ declare module "swagger-express-middleware" { */ inflate?: boolean; /** - * Controls the maximum request body size. - * If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. + * Controls the maximum request body size. + * If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. * Defaults to '100kb' */ limit?: string | number; /** - * The type option is used to determine what media type the middleware will parse. - * This option can be a function or a string. - * If a string, type option is passed directly to the type-is library and this can be an extension name (like json), a mime type (like application/json), or a mime * type with a wildcard (like * /* or * /json). + * The type option is used to determine what media type the middleware will parse. + * This option can be a function or a string. + * If a string, type option is passed directly to the type-is library and this can be an extension name (like json), a mime type (like application/json), or a mime * type with a wildcard (like * /* or * /json). * If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to application/json */ type?: ((req: Request) => string) | string /** - * The verify option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. + * The verify option, if supplied, is called as verify(req, res, buf, encoding), where buf is a Buffer of the raw request body and encoding is the encoding of the request. * The parsing can be aborted by throwing an error. */ verify?: (req: Request, res: Response, buf: Buffer, encoding: string) => void; @@ -290,15 +290,15 @@ declare module "swagger-express-middleware" { */ inflate?: boolean; /** - * Controls the maximum request body size. - * If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. + * Controls the maximum request body size. + * If this is a number, then the value specifies the number of bytes; if it is a string, the value is passed to the bytes library for parsing. * Defaults to '100kb' */ limit?: string | number; /** - * The type option is used to determine what media type the middleware will parse. - * This option can be a function or a string. - * If a string, type option is passed directly to the type-is library and this can be an extension name (like txt), a mime type (like text/plain), or a mime type * with a wildcard (like * /* or text/*). + * The type option is used to determine what media type the middleware will parse. + * This option can be a function or a string. + * If a string, type option is passed directly to the type-is library and this can be an extension name (like txt), a mime type (like text/plain), or a mime type * with a wildcard (like * /* or text/*). * If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. Defaults to text/plain. */ type?: ((req: Request) => string) | string @@ -318,17 +318,17 @@ declare module "swagger-express-middleware" { */ inflate?: boolean; /** - * Controls the maximum request body size. - * If this is a number, then the value specifies the number of bytes; - * if it is a string, the value is passed to the bytes library for parsing. + * Controls the maximum request body size. + * If this is a number, then the value specifies the number of bytes; + * if it is a string, the value is passed to the bytes library for parsing. * Defaults to '100kb'. */ limit?: string | number; /** - * The type option is used to determine what media type the middleware will parse. - * This option can be a function or a string. - * If a string, type option is passed directly to the type-is library and this can be an extension name (like urlencoded), a mime type (like application/x-www-form-urlencoded), - * or a mime type with a wildcard (like * /x-www-form-urlencoded). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. + * The type option is used to determine what media type the middleware will parse. + * This option can be a function or a string. + * If a string, type option is passed directly to the type-is library and this can be an extension name (like urlencoded), a mime type (like application/x-www-form-urlencoded), + * or a mime type with a wildcard (like * /x-www-form-urlencoded). If a function, the type option is called as fn(req) and the request is parsed if it returns a truthy value. * Defaults to application/x-www-form-urlencoded. */ type?: ((req: Request) => string) | string diff --git a/swagger-express-middleware/tsconfig.json b/swagger-express-middleware/tsconfig.json new file mode 100644 index 0000000000..b9091e6829 --- /dev/null +++ b/swagger-express-middleware/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "swagger-express-middleware.d.ts", + "swagger-express-middleware-tests.ts" + ] +} \ No newline at end of file diff --git a/tinder/tinder-tests.ts b/tinder/tinder-tests.ts index 12b8e6f071..03da9dec10 100644 --- a/tinder/tinder-tests.ts +++ b/tinder/tinder-tests.ts @@ -1,5 +1,3 @@ -/// - import tinder = require('tinder'); var client : tinder.TinderClient = new tinder.TinderClient(); @@ -7,7 +5,7 @@ client.authorize( '', '', function () { - + client.getRecommendations(10, (error, data) => { var results = data.results; results.forEach((recommendation) => { @@ -22,13 +20,13 @@ client.authorize( }) }); }); - + client.getHistory((error, history)=>{ if (history.matches && history.matches.length) { console.log(history.matches[0].messages); } }); - + client.getUpdates((error, updates)=>{ if (updates.matches && updates.matches.length) { console.log(updates.matches); diff --git a/tinder/tinder.d.ts b/tinder/tinder.d.ts index 9cbc19b360..94aa57fd62 100644 --- a/tinder/tinder.d.ts +++ b/tinder/tinder.d.ts @@ -1,9 +1,9 @@ -// Type definitions for tinder 1.19.0 +// Type definitions for tinder 1.19.0 // Project: https://github.com/tinderjs/tinderjs // Definitions by: Matej Drolc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module 'tinder' { @@ -91,14 +91,14 @@ declare module 'tinder' { unmatch(matchId: string, callback: Callback): void; /** - * Gets a list of new updates. This will be things like new messages, users who liked you, etc. + * Gets a list of new updates. This will be things like new messages, users who liked you, etc. * @param {Function} callback the callback to invoke when the request completes */ getUpdates(callback: Callback): void; /** * Gets the entire history for the current account (all matches, messages, blocks, etc.) - * + * * NOTE: Old messages seem to not be returned after a certain threshold. Not yet * sure what exactly that timeout is. The official client seems to get this update * once when the app is installed then cache the results and only rely on the @@ -108,7 +108,7 @@ declare module 'tinder' { getHistory(callback: Callback): void; /** - * Updates the geographical position for the current account + * Updates the geographical position for the current account * @param {Number} lon the longitude * @param {Number} lat the latitutde * @param {Function} callback the callback to invoke when the request completes @@ -219,7 +219,7 @@ declare module 'tinder' { /** * Get a share URL for a user - * + * * @param {String} userId the id of the user * @param {Function} callback the callback to invoke when the request completes */ @@ -227,7 +227,7 @@ declare module 'tinder' { /** * Report a user - * + * * @param {String} userId the id of the user * @param {Number} causeId one of 4 (inappropriate photos), 1 (spam), or 0 (other) * @param {String} causeText optional reason for report when causeId is 0 (other) @@ -237,7 +237,7 @@ declare module 'tinder' { /** * Create a web username for the current account - * + * * @param {String} userName the username to request be created * @param {Function} callback the callback to invoke when the request completes */ @@ -245,7 +245,7 @@ declare module 'tinder' { /** * Change a web username for the current account if it's already been set - * + * * @param {String} userName the username to request be created * @param {Function} callback the callback to invoke when the request completes */ @@ -253,21 +253,21 @@ declare module 'tinder' { /** * Deletes the existing web username for the current account - * + * * @param {Function} callback the callback to invoke when the request completes */ deleteUsername(username: string, callback: Callback): void; /** - * Update the passport location + * Update the passport location * @param {Number} lon the longitude * @param {Number} lat the latitutde * @param {Function} callback the callback to invoke when the request completes */ updatePassport(latitude: string, longitude: string, callback: Callback): void; - + /** - * Reset the passport location + * Reset the passport location * @param {Function} callback the callback to invoke when the request completes */ resetPassport(callback: Callback): void; diff --git a/tinder/tsconfig.json b/tinder/tsconfig.json new file mode 100644 index 0000000000..891c7e47a7 --- /dev/null +++ b/tinder/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "tinder.d.ts", + "tinder-tests.ts" + ] +} \ No newline at end of file diff --git a/torrent-stream/torrent-stream-tests.ts b/torrent-stream/torrent-stream-tests.ts index f69b7f968f..2b41b2e744 100644 --- a/torrent-stream/torrent-stream-tests.ts +++ b/torrent-stream/torrent-stream-tests.ts @@ -1,5 +1,3 @@ -/// - import * as torrentStream from "torrent-stream"; let engine: TorrentStream.TorrentEngine = torrentStream("magnet"); diff --git a/torrent-stream/torrent-stream.d.ts b/torrent-stream/torrent-stream.d.ts index bf804f1d73..468088642f 100644 --- a/torrent-stream/torrent-stream.d.ts +++ b/torrent-stream/torrent-stream.d.ts @@ -3,7 +3,7 @@ // Definitions by: Xavier Stouder // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace TorrentStream { interface TorrentEngine { @@ -16,7 +16,7 @@ declare namespace TorrentStream { listen(port: number, callback: () => void): void; swarm: Swarm; infoHash: string; - + // Events on(event: "ready" | "torrent" | "idle", callback: Function): void; on(event: "download", callback: (pieceIndex: number) => void): void; @@ -41,7 +41,7 @@ declare namespace TorrentStream { name: string; path: string; length: number; - + select(): void; deselect(): void; createReadStream(options?: ReadStreamOptions): any; diff --git a/torrent-stream/tsconfig.json b/torrent-stream/tsconfig.json new file mode 100644 index 0000000000..d19142a503 --- /dev/null +++ b/torrent-stream/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "torrent-stream.d.ts", + "torrent-stream-tests.ts" + ] +} \ No newline at end of file diff --git a/twilio/index.d.ts b/twilio/index.d.ts index 9d9316ba2b..62d0a390cd 100644 --- a/twilio/index.d.ts +++ b/twilio/index.d.ts @@ -3,9 +3,9 @@ // Definitions by: nickiannone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// +/// +/// +/// import * as express from 'express'; import * as Http from 'http'; @@ -166,7 +166,7 @@ declare module twilio { clientName: string; outgoingScopeParams: any; scopeParams: any; - + constructor(sid?: string, tkn?: string); allowClientIncoming(clientName: string): Capability; @@ -319,7 +319,7 @@ declare module twilio { allowWorkerActivityUpdates(): void; allowWorkerFetchAttributes(): void; allowTaskReservationUpdates(): void; - + addPolicy(url: string, method: string, allowed?: boolean, queryFilter?: any, postFilter?: any): void; allow(url: string, method: string, queryFilter?: any, postFilter?: any): void; deny(url: string, method: string, queryFilter?: any, postFilter?: any): void; @@ -380,7 +380,7 @@ declare module twilio { } export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } - + export interface TwimlCallback { (node?: Node): void; } export class Node implements NodeOptions { @@ -435,7 +435,7 @@ declare module twilio { export interface WebhookExpressOptions { // The full URL (with query string) you used to configure the webhook with Twilio - overrides host/protocol options url?: string; - + // manually specify the host name used by Twilio in a number's webhook config host?: string; diff --git a/twit/tsconfig.json b/twit/tsconfig.json new file mode 100644 index 0000000000..0b866f484a --- /dev/null +++ b/twit/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "twit.d.ts", + "twit-tests.ts" + ] +} \ No newline at end of file diff --git a/twit/twit-tests.ts b/twit/twit-tests.ts index b2d4dc83d9..e346771f35 100644 --- a/twit/twit-tests.ts +++ b/twit/twit-tests.ts @@ -1,5 +1,3 @@ -/// - import * as Twit from 'twit'; const t = new Twit( { diff --git a/twit/twit.d.ts b/twit/twit.d.ts index 612d4b3071..e5ad8b5962 100644 --- a/twit/twit.d.ts +++ b/twit/twit.d.ts @@ -3,8 +3,8 @@ // Definitions by: Volox // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module 'twit' { import { IncomingMessage } from 'http'; diff --git a/typescript-stl/typescript-stl.d.ts b/typescript-stl/index.d.ts similarity index 100% rename from typescript-stl/typescript-stl.d.ts rename to typescript-stl/index.d.ts diff --git a/v8-profiler/tsconfig.json b/v8-profiler/tsconfig.json new file mode 100644 index 0000000000..d7b22ff846 --- /dev/null +++ b/v8-profiler/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "v8-profiler.d.ts", + "v8-profiler-tests.ts" + ] +} \ No newline at end of file diff --git a/v8-profiler/v8-profiler.d.ts b/v8-profiler/v8-profiler.d.ts index ca22a60af7..2f5602b051 100644 --- a/v8-profiler/v8-profiler.d.ts +++ b/v8-profiler/v8-profiler.d.ts @@ -8,7 +8,7 @@ profiler.startProfiling(); =============================================== */ -/// +/// declare module "v8-profiler" { import * as fs from "fs"; diff --git a/victory/tsconfig.json b/victory/tsconfig.json new file mode 100644 index 0000000000..35f1bf290d --- /dev/null +++ b/victory/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + + "jsx": "react" + }, + "files": [ + "victory.d.ts", + "victory-tests.tsx" + ] +} \ No newline at end of file diff --git a/victory/victory-tests.tsx b/victory/victory-tests.tsx index 6be99c875a..7947f5f0ec 100644 --- a/victory/victory-tests.tsx +++ b/victory/victory-tests.tsx @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react"; import { VictoryAnimation, diff --git a/victory/victory.d.ts b/victory/victory.d.ts index 852fde5f7d..9be6990469 100644 --- a/victory/victory.d.ts +++ b/victory/victory.d.ts @@ -3,7 +3,8 @@ // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// + declare module "victory" { import * as React from "react"; /** @@ -108,7 +109,7 @@ declare module "victory" { * The events prop attaches arbitrary event handlers to the label component. * Event handlers are currently only called with their corresponding events. */ - events?: React.DOMAttributes; + events?: React.DOMAttributes; /** * All Victory components will pass a text prop to their label component. * This defines the content of the label when child nodes are absent. It will be ignored if children are provided. @@ -199,7 +200,7 @@ declare module "victory" { * data. `scale.x.invert(evt.offsetX)`. * @examples {{ onClick: (evt) => alert(`x: ${evt.clientX}, y: ${evt.clientY}`)}} */ - events?: React.DOMAttributes; + events?: React.DOMAttributes; /** * The title prop specifies the title to be applied to the SVG to assist * accessibility for screen readers. The more descriptive this title is, the more @@ -339,8 +340,8 @@ declare module "victory" { */ eventHandlers: { [key: string]: { - (event: React.SyntheticEvent): EventCallbackInterface } | - { (event: React.SyntheticEvent): EventCallbackInterface[] + (event: React.SyntheticEvent): EventCallbackInterface } | + { (event: React.SyntheticEvent): EventCallbackInterface[] } }; } diff --git a/watchify/index.d.ts b/watchify/index.d.ts new file mode 100644 index 0000000000..d4355f3efb --- /dev/null +++ b/watchify/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for watchify v3.7.0 +// Project: https://github.com/substack/watchify +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import Browserify = require("browserify"); + +declare var Watchify: Watchify.Constructor; + +/** Watch mode for browserify builds. + * Update any source file and your browserify bundle will be recompiled on the spot + */ +declare namespace Watchify { + + /** Watch mode for browserify builds. + * Update any source file and your browserify bundle will be recompiled on the spot + */ + export interface Constructor { + args: { cache: any; packageCache: any; }; + + (b: T, opts?: Watchify.Options): T; + (b: Browserify.BrowserifyObject, opts?: Watchify.Options): Browserify.BrowserifyObject; + } + + + export interface Options { + /** The amount of time in milliseconds to wait before emitting an "update" event after a change. + * Default: 100 + */ + delay?: number; + + /** Ignores monitoring files for changes. If set to true, then ** /node_modules/ ** will be ignored. For other possible values see Chokidar's documentation on "ignored" + * Also see anymatch package: https://github.com/es128/anymatch#usage + */ + ignoreWatch?: boolean | (string | RegExp | ((...values: any[]) => boolean) | (string | RegExp | ((...values: any[]) => boolean))[]); + + /** Enables polling to monitor for changes. If set to true, then a polling interval of 100 ms is used. + * If set to a number, then that amount of milliseconds will be the polling interval. For more info see + * Chokidar's documentation on "usePolling" and "interval". + * This option is useful if you're watching an NFS volume + * Also see chokidar package: https://github.com/paulmillr/chokidar#path-filtering + */ + poll?: number; + } + +} + +export = Watchify; diff --git a/watchify/tsconfig.json b/watchify/tsconfig.json new file mode 100644 index 0000000000..4ee0c6440e --- /dev/null +++ b/watchify/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "watchify-tests.ts" + ] +} \ No newline at end of file diff --git a/watchify/watchify-tests.ts b/watchify/watchify-tests.ts index 278697ca2e..5d3ff1dabf 100644 --- a/watchify/watchify-tests.ts +++ b/watchify/watchify-tests.ts @@ -1,5 +1,3 @@ -/// - import browserify = require("browserify"); import watchify = require("watchify"); diff --git a/watchify/watchify.d.ts b/watchify/watchify.d.ts deleted file mode 100644 index cad9cbf3af..0000000000 --- a/watchify/watchify.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -// Type definitions for watchify v3.7.0 -// Project: https://github.com/substack/watchify -// Definitions by: TeamworkGuy2 -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'watchify' { - - var Watchify: Watchify.Constructor; - - /** Watch mode for browserify builds. - * Update any source file and your browserify bundle will be recompiled on the spot - */ - module Watchify { - - /** Watch mode for browserify builds. - * Update any source file and your browserify bundle will be recompiled on the spot - */ - export interface Constructor { - args: { cache: any; packageCache: any; }; - - (b: T, opts?: Watchify.Options): T; - (b: Browserify.BrowserifyObject, opts?: Watchify.Options): Browserify.BrowserifyObject; - } - - - export interface Options { - /** The amount of time in milliseconds to wait before emitting an "update" event after a change. - * Default: 100 - */ - delay?: number; - - /** Ignores monitoring files for changes. If set to true, then ** /node_modules/ ** will be ignored. For other possible values see Chokidar's documentation on "ignored" - * Also see anymatch package: https://github.com/es128/anymatch#usage - */ - ignoreWatch?: boolean | (string | RegExp | ((...values: any[]) => boolean) | (string | RegExp | ((...values: any[]) => boolean))[]); - - /** Enables polling to monitor for changes. If set to true, then a polling interval of 100 ms is used. - * If set to a number, then that amount of milliseconds will be the polling interval. For more info see - * Chokidar's documentation on "usePolling" and "interval". - * This option is useful if you're watching an NFS volume - * Also see chokidar package: https://github.com/paulmillr/chokidar#path-filtering - */ - poll?: number; - } - - } - - export = Watchify; -} diff --git a/webpack-dev-server/tsconfig.json b/webpack-dev-server/tsconfig.json new file mode 100644 index 0000000000..2332ded163 --- /dev/null +++ b/webpack-dev-server/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "webpack-dev-server.d.ts", + "webpack-dev-server-tests.ts" + ] +} \ No newline at end of file diff --git a/webpack-dev-server/webpack-dev-server-tests.ts b/webpack-dev-server/webpack-dev-server-tests.ts index df805219f9..21af59885a 100644 --- a/webpack-dev-server/webpack-dev-server-tests.ts +++ b/webpack-dev-server/webpack-dev-server-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as webpack from 'webpack'; import * as WebpackDevServer from 'webpack-dev-server'; var compiler = webpack({}); @@ -21,7 +18,7 @@ server = new WebpackDevServer(compiler, { // Enable special support for Hot Module Replacement // Page is no longer updated, but a "webpackHotUpdate" message is send to the content // Use "webpack/hot/dev-server" as additional module in your entry point - // Note: this does _not_ add the `HotModuleReplacementPlugin` like the CLI option does. + // Note: this does _not_ add the `HotModuleReplacementPlugin` like the CLI option does. // Set this as true if you want to access dev server from arbitrary url. // This is handy if you are using a html5 router. diff --git a/webpack-dev-server/webpack-dev-server.d.ts b/webpack-dev-server/webpack-dev-server.d.ts index 41abe0f871..4be0870d7a 100644 --- a/webpack-dev-server/webpack-dev-server.d.ts +++ b/webpack-dev-server/webpack-dev-server.d.ts @@ -3,10 +3,6 @@ // Definitions by: maestroh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// -/// - declare module "webpack-dev-server" { import * as webpack from 'webpack'; import * as core from 'express-serve-static-core'; diff --git a/webpack-fail-plugin/tsconfig.json b/webpack-fail-plugin/tsconfig.json new file mode 100644 index 0000000000..b2dcb556ba --- /dev/null +++ b/webpack-fail-plugin/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "webpack-fail-plugin.d.ts", + "webpack-fail-plugin-tests.ts" + ] +} \ No newline at end of file diff --git a/webpack-fail-plugin/webpack-fail-plugin-tests.ts b/webpack-fail-plugin/webpack-fail-plugin-tests.ts index 4b7ab67b22..cda6265f33 100644 --- a/webpack-fail-plugin/webpack-fail-plugin-tests.ts +++ b/webpack-fail-plugin/webpack-fail-plugin-tests.ts @@ -1,4 +1,3 @@ -/// import * as Webpack from "webpack"; import FailPlugin = require("webpack-fail-plugin"); diff --git a/webpack-fail-plugin/webpack-fail-plugin.d.ts b/webpack-fail-plugin/webpack-fail-plugin.d.ts index abfaea11d6..d0436a3b89 100644 --- a/webpack-fail-plugin/webpack-fail-plugin.d.ts +++ b/webpack-fail-plugin/webpack-fail-plugin.d.ts @@ -3,7 +3,7 @@ // Definitions by: Simon Hartcher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "webpack-fail-plugin" { import {Plugin} from "webpack"; diff --git a/webpack-merge/tsconfig.json b/webpack-merge/tsconfig.json new file mode 100644 index 0000000000..9a790a0d67 --- /dev/null +++ b/webpack-merge/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "webpack-merge.d.ts", + "webpack-merge-tests.ts" + ] +} \ No newline at end of file diff --git a/webpack-merge/webpack-merge-tests.ts b/webpack-merge/webpack-merge-tests.ts index 1d39e0e7ab..bc40806a23 100644 --- a/webpack-merge/webpack-merge-tests.ts +++ b/webpack-merge/webpack-merge-tests.ts @@ -1,5 +1,3 @@ -/// - import merge = require("webpack-merge"); import {Configuration} from "webpack"; diff --git a/webpack-merge/webpack-merge.d.ts b/webpack-merge/webpack-merge.d.ts index 3d2683fa85..18aaca1f36 100644 --- a/webpack-merge/webpack-merge.d.ts +++ b/webpack-merge/webpack-merge.d.ts @@ -3,7 +3,7 @@ // Definitions by: Simon Hartcher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "webpack-merge" { import {Configuration} from "webpack"; diff --git a/webpack-stream/tsconfig.json b/webpack-stream/tsconfig.json new file mode 100644 index 0000000000..22cb00921f --- /dev/null +++ b/webpack-stream/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "webpack-stream.d.ts", + "webpack-stream-tests.ts" + ] +} \ No newline at end of file diff --git a/webpack-stream/webpack-stream-tests.ts b/webpack-stream/webpack-stream-tests.ts index bd57e1c735..9f13f53b02 100644 --- a/webpack-stream/webpack-stream-tests.ts +++ b/webpack-stream/webpack-stream-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import webpackStream = require("webpack-stream"); import webpack = require("webpack"); diff --git a/webpack-stream/webpack-stream.d.ts b/webpack-stream/webpack-stream.d.ts index c98c0372dd..9a36906a03 100644 --- a/webpack-stream/webpack-stream.d.ts +++ b/webpack-stream/webpack-stream.d.ts @@ -3,8 +3,8 @@ // Definitions by: Ian Clanton-Thuon // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -/// +/// +/// declare module "webpack-stream" { import webpack = require("webpack"); diff --git a/webpack-validator/tsconfig.json b/webpack-validator/tsconfig.json new file mode 100644 index 0000000000..6361cb196b --- /dev/null +++ b/webpack-validator/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "webpack-validator.d.ts", + "webpack-validator-tests.ts" + ] +} \ No newline at end of file diff --git a/webpack-validator/webpack-validator-tests.ts b/webpack-validator/webpack-validator-tests.ts index f64b478b2e..9635ae2060 100644 --- a/webpack-validator/webpack-validator-tests.ts +++ b/webpack-validator/webpack-validator-tests.ts @@ -1,5 +1,3 @@ -/// - import {Configuration} from "webpack"; import validate = require("webpack-validator"); diff --git a/webpack-validator/webpack-validator.d.ts b/webpack-validator/webpack-validator.d.ts index 3c03627bb3..850aadd654 100644 --- a/webpack-validator/webpack-validator.d.ts +++ b/webpack-validator/webpack-validator.d.ts @@ -3,7 +3,7 @@ // Definitions by: Simon Hartcher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "webpack-validator" { import {Configuration} from "webpack"; diff --git a/whatwg-fetch/index.d.ts b/whatwg-fetch/index.d.ts index 793244976e..6e0953656f 100644 --- a/whatwg-fetch/index.d.ts +++ b/whatwg-fetch/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ryan Graham , Kagami Sascha Rosylight // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface Window { fetch(url: RequestInfo, init?: RequestInit): Promise; diff --git a/whatwg-fetch/whatwg-fetch-tests.ts b/whatwg-fetch/whatwg-fetch-tests.ts index 7434c8372b..7e35c607b1 100644 --- a/whatwg-fetch/whatwg-fetch-tests.ts +++ b/whatwg-fetch/whatwg-fetch-tests.ts @@ -7,7 +7,7 @@ function test_HeadersCopiedFromHeaders1() { } function test_HeadersCopiedFromHash1() { - var source:HeadersMap = { + var source:HeadersInit = { 'Content-Type': 'application/json' }; return new Headers(source); @@ -20,7 +20,7 @@ function test_HeadersCopiedFromHeaders2() { } function test_HeadersCopiedFromHash2() { - var source:HeadersMap = { + var source:HeadersInit = { 'Content-Type': 'application/json' }; return new Headers(source); @@ -33,7 +33,7 @@ function test_HeadersCopiedFromHeaders3() { } function test_HeadersCopiedFromHash3() { - var source:HeadersMap = { + var source:HeadersInit = { 'Content-Type': 'application/json' }; return new Headers(source); diff --git a/whatwg-streams/whatwg-streams.d.ts b/whatwg-streams/index.d.ts similarity index 100% rename from whatwg-streams/whatwg-streams.d.ts rename to whatwg-streams/index.d.ts diff --git a/whatwg-streams/tsconfig.json b/whatwg-streams/tsconfig.json new file mode 100644 index 0000000000..9c6a6ad155 --- /dev/null +++ b/whatwg-streams/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "whatwg-streams-tests.ts" + ] +} \ No newline at end of file diff --git a/whatwg-streams/whatwg-streams-tests.ts b/whatwg-streams/whatwg-streams-tests.ts index d1e23eda98..ce5eb2b256 100644 --- a/whatwg-streams/whatwg-streams-tests.ts +++ b/whatwg-streams/whatwg-streams-tests.ts @@ -1,6 +1,4 @@ -/// - -function makeReadableWebSocketStream(url: string, protocols: string[]) { +function makeReadableWebSocketStream(url: string, protocols: string[]) { const ws = new WebSocket(url, protocols); ws.binaryType = "arraybuffer"; @@ -161,7 +159,7 @@ class WebSocketSink implements WritableStreamSink { this._ws.addEventListener("error", () => { controller.error(new Error("The WebSocket errored!")); }); - + return new Promise(resolve => this._ws.onopen = () => resolve()); } diff --git a/why-did-you-update/tsconfig.json b/why-did-you-update/tsconfig.json new file mode 100644 index 0000000000..4ce50757f7 --- /dev/null +++ b/why-did-you-update/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "why-did-you-update.d.ts", + "why-did-you-update-tests.ts" + ] +} \ No newline at end of file diff --git a/why-did-you-update/why-did-you-update-tests.ts b/why-did-you-update/why-did-you-update-tests.ts index 7c8432d61c..d628e796c6 100644 --- a/why-did-you-update/why-did-you-update-tests.ts +++ b/why-did-you-update/why-did-you-update-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import * as React from "react"; import {whyDidYouUpdate} from "why-did-you-update"; diff --git a/why-did-you-update/why-did-you-update.d.ts b/why-did-you-update/why-did-you-update.d.ts index da94eddb3e..09b2754438 100644 --- a/why-did-you-update/why-did-you-update.d.ts +++ b/why-did-you-update/why-did-you-update.d.ts @@ -3,13 +3,13 @@ // Definitions by: rhysd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module "why-did-you-update" { interface Options { include?: RegExp; exclude?: RegExp; } - export function whyDidYouUpdate(react: typeof __React, options?: Options): void; + export function whyDidYouUpdate(react: typeof React, options?: Options): void; } diff --git a/winston-dynamodb/tsconfig.json b/winston-dynamodb/tsconfig.json new file mode 100644 index 0000000000..c5b2035097 --- /dev/null +++ b/winston-dynamodb/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "winston-dynamodb.d.ts", + "winston-dynamodb-tests.ts" + ] +} \ No newline at end of file diff --git a/winston-dynamodb/winston-dynamodb-tests.ts b/winston-dynamodb/winston-dynamodb-tests.ts index 00f5cdfa59..a81cdf32e1 100644 --- a/winston-dynamodb/winston-dynamodb-tests.ts +++ b/winston-dynamodb/winston-dynamodb-tests.ts @@ -1,6 +1,3 @@ -/// -/// - import winston = require('winston'); require('winston-dynamodb').DynamoDB; diff --git a/winston-dynamodb/winston-dynamodb.d.ts b/winston-dynamodb/winston-dynamodb.d.ts index 7d4c2e9544..a9d7e9e713 100644 --- a/winston-dynamodb/winston-dynamodb.d.ts +++ b/winston-dynamodb/winston-dynamodb.d.ts @@ -3,7 +3,7 @@ // Definitions by: nickiannone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// import * as winston from 'winston'; import { TransportInstance } from 'winston'; diff --git a/xmlpoke/tsconfig.json b/xmlpoke/tsconfig.json new file mode 100644 index 0000000000..7157d9aad3 --- /dev/null +++ b/xmlpoke/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "xmlpoke.d.ts", + "xmlpoke-tests.ts" + ] +} \ No newline at end of file diff --git a/xmlpoke/xmlpoke-tests.ts b/xmlpoke/xmlpoke-tests.ts index b77463f164..3c82b846a6 100644 --- a/xmlpoke/xmlpoke-tests.ts +++ b/xmlpoke/xmlpoke-tests.ts @@ -1,5 +1,4 @@ -/// -/// +/// // tsc xmlpoke-tests.ts && node xmlpoke-tests.js @@ -13,7 +12,7 @@ result = xmlpoke('', xml => xml.add('/a/b', 'c')); assert.equal(result, 'c'); // add with xpath, Transform -const addfn: XmlPoke.Transform = (node, value) => 'c'; +const addfn: XmlPoke.Transform = (node, value) => 'c'; result = xmlpoke('', xml => xml.add('/a/b', addfn)); assert.equal(result, 'c'); @@ -78,6 +77,6 @@ result = xmlpoke('', xml => assert.equal(typeof node, 'object'); assert.equal((node.constructor as any).name, 'Element'); assert.equal(value, 'hello'); - return 'y'; + return 'y'; })); assert.equal(result, 'y'); diff --git a/xmlpoke/xmlpoke.d.ts b/xmlpoke/xmlpoke.d.ts index 4b8868be98..5e0b33948f 100644 --- a/xmlpoke/xmlpoke.d.ts +++ b/xmlpoke/xmlpoke.d.ts @@ -3,7 +3,7 @@ // Definitions by: Garth Kidd // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module XmlPoke { // ghost module interface Transform { From b5e3b1987f6cbee9627bdbd845e0e9bf71325125 Mon Sep 17 00:00:00 2001 From: Ulrich Buchgraber Date: Fri, 16 Sep 2016 18:17:22 +0200 Subject: [PATCH 105/212] Simplify typings by employing "polymorphic this types" for clone()/copy() methods Note: This also solves TS 2.0 --strictNullChecks errors. --- threejs/three-canvasrenderer.d.ts | 1 - threejs/three.d.ts | 221 +++++++++--------------------- 2 files changed, 63 insertions(+), 159 deletions(-) diff --git a/threejs/three-canvasrenderer.d.ts b/threejs/three-canvasrenderer.d.ts index 2d2d9e4930..7dba387da9 100644 --- a/threejs/three-canvasrenderer.d.ts +++ b/threejs/three-canvasrenderer.d.ts @@ -17,7 +17,6 @@ declare namespace THREE { color: Color; program(context: any, color: Color): void; - clone(): SpriteCanvasMaterial; } export interface CanvasRendererParameters { diff --git a/threejs/three.d.ts b/threejs/three.d.ts index 9e70f1e898..830edbf864 100644 --- a/threejs/three.d.ts +++ b/threejs/three.d.ts @@ -461,9 +461,6 @@ declare namespace THREE { * @param vector point to look at */ lookAt(vector: Vector3): void; - - clone(): Camera; - copy(camera?: Camera): Camera; } export class CubeCamera extends Object3D { @@ -540,8 +537,6 @@ declare namespace THREE { updateProjectionMatrix(): void; setViewOffset(fullWidth: number, fullHeight: number, offsetX: number, offsetY: number, width: number, height: number): void; clearViewOffset(): void; - clone(): OrthographicCamera; - copy(source: OrthographicCamera): OrthographicCamera; toJSON(meta?: any): any; } @@ -646,7 +641,6 @@ declare namespace THREE { * Updates the camera projection matrix. Must be called after change of parameters. */ updateProjectionMatrix(): void; - clone(): PerspectiveCamera; toJSON(meta?: any): any; // deprecated @@ -682,8 +676,8 @@ declare namespace THREE { count: number; setDynamic(dynamic: boolean): BufferAttribute; - clone(): BufferAttribute; - copy(source: BufferAttribute): BufferAttribute; + clone(): this; + copy(source: this): this; copyAt(index1: number, attribute: BufferAttribute, index2: number): BufferAttribute; copyArray(array: ArrayLike): BufferAttribute; copyColorsArray(colors: {r: number, g: number, b: number}[]): BufferAttribute; @@ -703,7 +697,6 @@ declare namespace THREE { setXY(index: number, x: number, y: number): BufferAttribute; setXYZ(index: number, x: number, y: number, z: number): BufferAttribute; setXYZW(index: number, x: number, y: number, z: number, w: number): BufferAttribute; - clone(): BufferAttribute; length: number; // deprecated, use count } @@ -834,8 +827,8 @@ declare namespace THREE { toNonIndexed(): BufferGeometry; toJSON(): any; - clone(): BufferGeometry; - copy(source: BufferGeometry): BufferGeometry; + clone(): this; + copy(source: this): this; /** * Disposes the object from memory. @@ -1086,8 +1079,8 @@ declare namespace THREE { */ materialIndex: number; - clone(): Face3; - copy(source: Face3): Face3; + clone(): this; + copy(source: this): this; } export class Face4 extends Face3 {} // deprecated, use Face3 @@ -1308,9 +1301,9 @@ declare namespace THREE { /** * Creates a new clone of the Geometry. */ - clone(): Geometry; + clone(): this; - copy(source: Geometry): Geometry; + copy(source: this): this; /** * Removes The object from memory. @@ -1343,9 +1336,6 @@ declare namespace THREE { constructor(data: ArrayLike, itemSize: number, meshPerAttribute?: number); meshPerAttribute: number; - - clone(): InstancedBufferAttribute; - copy(source: InstancedBufferAttribute): InstancedBufferAttribute; } /** @@ -1358,8 +1348,6 @@ declare namespace THREE { maxInstancedCount: number; addGroup(start: number, count: number, instances: number): void; - clone(): InstancedBufferGeometry; - copy(source: InstancedBufferGeometry): InstancedBufferGeometry; } /** @@ -1378,11 +1366,11 @@ declare namespace THREE { needsUpdate: boolean; setDynamic(dynamic: boolean): InterleavedBuffer; - clone(): InterleavedBuffer; - copy(source: InterleavedBuffer): InterleavedBuffer; + clone(): this; + copy(source: this): this; copyAt(index1: number, attribute: InterleavedBufferAttribute, index2: number): InterleavedBuffer; set(value: ArrayLike, index: number): InterleavedBuffer; - clone(): InterleavedBuffer; + clone(): this; } /** @@ -1392,9 +1380,6 @@ declare namespace THREE { constructor(array: ArrayLike, stride: number, meshPerAttribute?: number); meshPerAttribute: number; - - clone(): InstancedInterleavedBuffer; - copy(source: InstancedInterleavedBuffer): InstancedInterleavedBuffer; } /** @@ -1686,14 +1671,14 @@ declare namespace THREE { toJSON(meta?: { geometries: any, materials: any, textures: any, images: any }): any; - clone(recursive?: boolean): Object3D; + clone(recursive?: boolean): this; /** * * @param object * @param recursive */ - copy(source: Object3D, recursive?: boolean): Object3D; + copy(source: this, recursive?: boolean): this; // deprecated eulerOrder: string; @@ -1777,9 +1762,6 @@ declare namespace THREE { shadowBias: any; // deprecated, use shadow.bias shadowMapWidth: any; // deprecated, use shadow.mapSize.width shadowMapHeight: any; // deprecated, use shadow.mapSize.height - - copy(source: Light): Light; - clone(recursive?: boolean): Light; } export class LightShadow { @@ -1792,8 +1774,8 @@ declare namespace THREE { map: RenderTarget; matrix: Matrix4; - copy(source: LightShadow): LightShadow; - clone(recursive?: boolean): LightShadow; + copy(source: this): this; + clone(recursive?: boolean): this; toJSON(): any; } @@ -1814,9 +1796,6 @@ declare namespace THREE { constructor(hex?: number|string, intensity?: number); castShadow: boolean; - - copy(source: AmbientLight): AmbientLight; - clone(recursive?: boolean): AmbientLight; } /** @@ -1845,9 +1824,6 @@ declare namespace THREE { intensity: number; shadow: LightShadow; - - copy(source: DirectionalLight): DirectionalLight; - clone(recursive?: boolean): HemisphereLight; } export class DirectionalLightShadow extends LightShadow {} @@ -1857,9 +1833,6 @@ declare namespace THREE { groundColor: Color; intensity: number; - - copy(source: HemisphereLight): HemisphereLight; - clone(recursive?: boolean): HemisphereLight; } /** @@ -1888,9 +1861,6 @@ declare namespace THREE { decay: number; shadow: LightShadow; power: number; - - copy(source: PointLight): PointLight; - clone(recursive?: boolean): PointLight; } /** @@ -1933,9 +1903,6 @@ declare namespace THREE { shadow: SpotLightShadow; power: number; penumbra: number; - - clone(recursive?: boolean): SpotLight; - copy(source: PointLight): SpotLight; } export class SpotLightShadow extends LightShadow { @@ -2359,8 +2326,8 @@ declare namespace THREE { setValues(parameters: MaterialParameters): void; toJSON(meta?: any): any; - clone(): Material; - copy(source: Material): Material; + clone(): this; + copy(source: this): this; update(): void; dispose(): void; @@ -2384,8 +2351,6 @@ declare namespace THREE { linejoin: string; setValues(parameters: LineBasicMaterialParameters): void; - clone(): LineBasicMaterial; - copy(source: LineBasicMaterial): LineBasicMaterial; } export interface LineDashedMaterialParameters extends MaterialParameters { @@ -2406,8 +2371,6 @@ declare namespace THREE { gapSize: number; setValues(parameters: LineDashedMaterialParameters): void; - clone(): LineDashedMaterial; - copy(source: LineDashedMaterial): LineDashedMaterial; } /** @@ -2456,8 +2419,6 @@ declare namespace THREE { morphTargets: boolean; setValues(parameters: MeshBasicMaterialParameters): void; - clone(): MeshBasicMaterial; - copy(source: MeshBasicMaterial): MeshBasicMaterial; } export interface MeshDepthMaterialParameters extends MaterialParameters { @@ -2472,8 +2433,6 @@ declare namespace THREE { wireframeLinewidth: number; setValues(parameters: MeshDepthMaterialParameters): void; - clone(): MeshDepthMaterial; - copy(source: MeshDepthMaterial): MeshDepthMaterial; } export interface MeshLambertMaterialParameters extends MaterialParameters { @@ -2528,8 +2487,6 @@ declare namespace THREE { morphNormals: boolean; setValues(parameters: MeshLambertMaterialParameters): void; - clone(): MeshLambertMaterial; - copy(source: MeshLambertMaterial): MeshLambertMaterial; } export interface MeshStandardMaterialParameters extends MaterialParameters { @@ -2599,8 +2556,6 @@ declare namespace THREE { morphNormals: boolean; setValues(parameters: MeshStandardMaterialParameters): void; - clone(): MeshStandardMaterial; - copy(source: MeshStandardMaterial): MeshStandardMaterial; } export interface MeshNormalMaterialParameters extends MaterialParameters { @@ -2619,8 +2574,6 @@ declare namespace THREE { morphTargets: boolean; setValues(parameters: MeshNormalMaterialParameters): void; - clone(): MeshNormalMaterial; - copy(source: MeshNormalMaterial): MeshNormalMaterial; } export interface MeshPhongMaterialParameters extends MaterialParameters { @@ -2696,8 +2649,6 @@ declare namespace THREE { metal: boolean; // deprecated setValues(parameters: MeshPhongMaterialParameters): void; - clone(): MeshPhongMaterial; - copy(source: MeshPhongMaterial): MeshPhongMaterial; } export interface MeshPhysicalMaterialParameters extends MeshStandardMaterialParameters { @@ -2723,7 +2674,6 @@ declare namespace THREE { materials: Material[]; toJSON(meta: any): any; - clone(): MultiMaterial; } export class MeshFaceMaterial extends MultiMaterial {} // deprecated, use MultiMaterial @@ -2744,8 +2694,6 @@ declare namespace THREE { sizeAttenuation: boolean; setValues(parameters: PointsMaterialParameters): void; - clone(): PointsMaterial; - copy(source: PointsMaterial): PointsMaterial; } export class PointCloudMaterial extends PointsMaterial {} // deprecated @@ -2788,8 +2736,6 @@ declare namespace THREE { index0AttributeName: string; setValues(parameters: ShaderMaterialParameters): void; - clone(): ShaderMaterial; - copy(source: ShaderMaterial): ShaderMaterial; toJSON(meta: any): any; } @@ -2811,8 +2757,6 @@ declare namespace THREE { rotation: number; setValues(parameters: SpriteMaterialParameters): void; - clone(): SpriteMaterial; - copy(source: SpriteMaterial): SpriteMaterial; } export class ShadowMaterial extends ShaderMaterial { @@ -2830,8 +2774,8 @@ declare namespace THREE { set(min: Vector2, max: Vector2): Box2; setFromPoints(points: Vector2[]): Box2; setFromCenterAndSize(center: Vector2, size: Vector2): Box2; - clone(): Box2; - copy(box: Box2): Box2; + clone(): this; + copy(box: this): this; makeEmpty(): Box2; isEmpty(): boolean; center(optionalTarget?: Vector2): Vector2; @@ -2865,8 +2809,8 @@ declare namespace THREE { setFromPoints(points: Vector3[]): Box3; setFromCenterAndSize(center: Vector3, size: Vector3): Box3; setFromObject(object: Object3D): Box3; - clone(): Box3; - copy(box: Box3): Box3; + clone(): this; + copy(box: this): this; makeEmpty(): Box3; isEmpty(): boolean; center(optionalTarget?: Vector3): Vector3; @@ -2962,13 +2906,13 @@ declare namespace THREE { /** * Clones this color. */ - clone(): Color; + clone(): this; /** * Copies given color. * @param color Color to copy. */ - copy(color: Color): Color; + copy(color: this): this; /** * Copies given color making conversion from gamma to linear space. @@ -3184,8 +3128,8 @@ declare namespace THREE { onChangeCallback: Function; set(x: number, y: number, z: number, order?: string): Euler; - clone(): Euler; - copy(euler: Euler): Euler; + clone(): this; + copy(euler: this): this; setFromRotationMatrix(m: Matrix4, order?: string, update?: boolean): Euler; setFromQuaternion(q: Quaternion, order?: string, update?: boolean): Euler; setFromVector3( v: Vector3, order?: string ): Euler; @@ -3212,8 +3156,8 @@ declare namespace THREE { planes: Plane[]; set(p0?: number, p1?: number, p2?: number, p3?: number, p4?: number, p5?: number): Frustum; - clone(): Frustum; - copy(frustum: Frustum): Frustum; + clone(): this; + copy(frustum: this): this; setFromMatrix(m: Matrix4): Frustum; intersectsObject(object: Object3D): boolean; intersectsObject(sprite: Sprite): boolean; @@ -3229,8 +3173,8 @@ declare namespace THREE { end: Vector3; set(start?: Vector3, end?: Vector3): Line3; - clone(): Line3; - copy(line: Line3): Line3; + clone(): this; + copy(line: this): this; center(optionalTarget?: Vector3): Vector3; delta(optionalTarget?: Vector3): Vector3; distanceSq(): number; @@ -3326,7 +3270,7 @@ declare namespace THREE { /** * copy(m:T):T; */ - copy(m: Matrix): Matrix; + copy(m: this): this; /** * multiplyScalar(s:number):T; @@ -3348,7 +3292,7 @@ declare namespace THREE { /** * clone():T; */ - clone(): Matrix; + clone(): this; } /** @@ -3367,8 +3311,8 @@ declare namespace THREE { set(n11: number, n12: number, n13: number, n21: number, n22: number, n23: number, n31: number, n32: number, n33: number): Matrix3; identity(): Matrix3; - clone(): Matrix3; - copy(m: Matrix3): Matrix3; + clone(): this; + copy(m: this): this; setFromMatrix4(m: Matrix4): Matrix3; applyToVector3Array(array: ArrayLike, offset?: number, length?: number): ArrayLike; applyToBuffer(buffer: BufferAttribute, offset?: number, length?: number): BufferAttribute; @@ -3431,8 +3375,8 @@ declare namespace THREE { * Resets this matrix to identity. */ identity(): Matrix4; - clone(): Matrix4; - copy(m: Matrix4): Matrix4; + clone(): this; + copy(m: this): this; copyPosition(m: Matrix4): Matrix4; extractBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; makeBasis( xAxis: Vector3, yAxis: Vector3, zAxis: Vector3): Matrix4; @@ -3593,8 +3537,8 @@ declare namespace THREE { setComponents(x: number, y: number, z: number, w: number): Plane; setFromNormalAndCoplanarPoint(normal: Vector3, point: Vector3): Plane; setFromCoplanarPoints(a: Vector3, b: Vector3, c: Vector3): Plane; - clone(): Plane; - copy(plane: Plane): Plane; + clone(): this; + copy(plane: this): this; normalize(): Plane; negate(): Plane; distanceToPoint(point: Vector3): number; @@ -3617,8 +3561,8 @@ declare namespace THREE { constructor(radius?: number, phi?: number, theta?: number); set(radius: number, phi: number, theta: number): Spherical; - clone(): Spherical; - copy(other: Spherical): Spherical; + clone(): this; + copy(other: this): this; makeSafe(): void; setFromVector3(vec3: Vector3): Spherical; } @@ -3654,12 +3598,12 @@ declare namespace THREE { /** * Clones this quaternion. */ - clone(): Quaternion; + clone(): this; /** * Copies values of q to this quaternion. */ - copy(q: Quaternion): Quaternion; + copy(q: this): this; /** * Sets this quaternion from rotation specified by Euler angles. @@ -3739,8 +3683,8 @@ declare namespace THREE { direction: Vector3; set(origin: Vector3, direction: Vector3): Ray; - clone(): Ray; - copy(ray: Ray): Ray; + clone(): this; + copy(ray: this): this; at(t: number, optionalTarget?: Vector3): Vector3; lookAt(v: Vector3): Vector3; recast(t: number): Ray; @@ -3773,8 +3717,8 @@ declare namespace THREE { set(center: Vector3, radius: number): Sphere; setFromPoints(points: Vector3[], optionalCenter?: Vector3): Sphere; - clone(): Sphere; - copy(sphere: Sphere): Sphere; + clone(): this; + copy(sphere: this): this; empty(): boolean; containsPoint(point: Vector3): boolean; distanceToPoint(point: Vector3): number; @@ -3850,8 +3794,8 @@ declare namespace THREE { set(a: Vector3, b: Vector3, c: Vector3): Triangle; setFromPointsAndIndices(points: Vector3[], i0: number, i1: number, i2: number): Triangle; - clone(): Triangle; - copy(triangle: Triangle): Triangle; + clone(): this; + copy(triangle: this): this; area(): number; midpoint(optionalTarget?: Vector3): Vector3; normal(optionalTarget?: Vector3): Vector3; @@ -3885,7 +3829,7 @@ declare namespace THREE { /** * copy(v:T):T; */ - copy(v: Vector): Vector; + copy(v: this): this; /** * add(v:T):T; @@ -3974,7 +3918,7 @@ declare namespace THREE { /** * clone():T; */ - clone(): Vector; + clone(): this; } /** @@ -4019,11 +3963,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector2; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector2): Vector2; + copy(v: this): this; /** * Adds v to this vector. @@ -4185,11 +4129,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector3; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector3): Vector3; + copy(v: this): this; /** * Adds v to this vector. @@ -4381,11 +4325,11 @@ declare namespace THREE { /** * Clones this vector. */ - clone(): Vector4; + clone(): this; /** * Copies value of v to this vector. */ - copy(v: Vector4): Vector4; + copy(v: this): this; /** * Adds v to this vector. @@ -4533,9 +4477,6 @@ declare namespace THREE { constructor(skin: SkinnedMesh); skin: SkinnedMesh; - - clone(): Bone; - copy(source: Bone): Bone; } export class Group extends Object3D { @@ -4551,8 +4492,6 @@ declare namespace THREE { getObjectForDistance(distance: number): Object3D; raycast(raycaster: Raycaster, intersects: any): void; update(camera: Camera): void; - clone(): LOD; - copy(source: LOD): LOD; toJSON(meta: any): any; // deprecated @@ -4583,8 +4522,6 @@ declare namespace THREE { add(object: Object3D): void; add(texture: Texture, size?: number, distance?: number, blending?: Blending, color?: Color): void; updateLensFlares(): void; - clone(): LensFlare; - copy(source: LensFlare): LensFlare; } export class Line extends Object3D { @@ -4598,8 +4535,6 @@ declare namespace THREE { material: Material; // LineDashedMaterial or LineBasicMaterial or ShaderMaterial raycast(raycaster: Raycaster, intersects: any): void; - clone(): Line; - copy(source: Line): Line; } export const LineStrip: number; // deprecated @@ -4611,9 +4546,6 @@ declare namespace THREE { material?: LineDashedMaterial | LineBasicMaterial | ShaderMaterial, mode?: number ); - - clone(): LineSegments; - copy(source: LineSegments): LineSegments; } enum LineMode {} @@ -4630,8 +4562,6 @@ declare namespace THREE { updateMorphTargets(): void; getMorphTargetIndexByName(name: string): number; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Mesh; - copy(source: Mesh): Mesh; } /** @@ -4661,8 +4591,6 @@ declare namespace THREE { material: Material; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Points; - copy(source: Points): Points; } export class PointCloud extends Points {} // deprecated @@ -4683,7 +4611,7 @@ declare namespace THREE { calculateInverses(bone: Bone): void; pose(): void; update(): void; - clone(): Skeleton; + clone(): this; } export class SkinnedMesh extends Mesh { @@ -4704,8 +4632,6 @@ declare namespace THREE { pose(): void; normalizeSkinWeights(): void; updateMatrixWorld(force?: boolean): void; - clone(): SkinnedMesh; - copy(source: SkinnedMesh): SkinnedMesh; } export class Sprite extends Object3D { @@ -4715,8 +4641,6 @@ declare namespace THREE { material: SpriteMaterial; raycast(raycaster: Raycaster, intersects: any): void; - clone(): Sprite; - copy(source: Sprite): Sprite; } export class Particle extends Sprite {} // deprecated @@ -5048,8 +4972,8 @@ declare namespace THREE { generateMipmaps: any; // deprecated, use texture.generateMipmaps setSize(width: number, height: number): void; - clone(): WebGLRenderTarget; - copy(source: WebGLRenderTarget): WebGLRenderTarget; + clone(): this; + copy(source: this): this; dispose(): void; } @@ -5596,14 +5520,13 @@ declare namespace THREE { autoUpdate: boolean; background: any; - copy(source: Scene, recursive?: boolean): Scene; toJSON(meta?: any): any; } export interface IFog { name: string; color: Color; - clone(): IFog; + clone(): this; toJSON(): any; } @@ -5631,7 +5554,7 @@ declare namespace THREE { */ far: number; - clone(): Fog; + clone(): this; toJSON(): any; } @@ -5650,7 +5573,7 @@ declare namespace THREE { */ density: number; - clone(): FogExp2; + clone(): this; toJSON(): any; } @@ -5698,8 +5621,8 @@ declare namespace THREE { static DEFAULT_IMAGE: any; static DEFAULT_MAPPING: any; - clone(): Texture; - copy(source: Texture): Texture; + clone(): this; + copy(source: this): this; toJSON(meta: any): any; dispose(): void; transformUv(uv: Vector): void; @@ -5733,9 +5656,6 @@ declare namespace THREE { type?: TextureDataType, anisotropy?: number ); - - clone(): CanvasTexture; - copy(source: CanvasTexture): CanvasTexture; } export class CubeTexture extends Texture { @@ -5753,8 +5673,6 @@ declare namespace THREE { ); images: any; // returns and sets the value of Texture.image in the codde ? - - copy(source: CubeTexture): CubeTexture; } export class CompressedTexture extends Texture { @@ -5774,9 +5692,6 @@ declare namespace THREE { ); image: { width: number; height: number; }; - - clone(): CompressedTexture; - copy(source: CompressedTexture): CompressedTexture; } export class DataTexture extends Texture { @@ -5796,9 +5711,6 @@ declare namespace THREE { ); image: { data: ImageData; width: number; height: number; }; - - clone(): DataTexture; - copy(source: DataTexture): DataTexture; } export class VideoTexture extends Texture { @@ -5813,9 +5725,6 @@ declare namespace THREE { type?: TextureDataType, anisotropy?: number ); - - clone(): VideoTexture; - copy(source: VideoTexture): VideoTexture; } // Extras ///////////////////////////////////////////////////////////////////// @@ -6221,8 +6130,6 @@ declare namespace THREE { heightSegments: number; depthSegments: number; }; - - clone(): BoxGeometry; } export class CubeGeometry extends BoxGeometry {} // deprecated, use BoxGeometry @@ -6306,8 +6213,6 @@ declare namespace THREE { export class EdgesGeometry extends BufferGeometry { constructor(geometry: BufferGeometry, thresholdAngle: number); - - clone(): EdgesGeometry; } export class ExtrudeGeometry extends Geometry { From 823045554e3f3072c9dffeca1fdb8a8f1cb075cf Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 16 Sep 2016 11:14:30 -0700 Subject: [PATCH 106/212] Fix tests --- bowser/bowser-tests.ts | 12 +----------- bowser/index.d.ts | 6 +++--- cordova-plugin-contacts/index.d.ts | 6 +++--- cordova-plugin-file/index.d.ts | 2 +- esprima/esprima-tests.ts | 2 +- esprima/index.d.ts | 4 ---- .../{inversify-devtools.d.ts => index.d.ts} | 0 inversify-devtools/tsconfig.json | 2 +- karma-chai-sinon/karma-chai-sinon.d.ts | 2 +- masonry-layout/masonry-layout-tests.ts | 8 ++------ react-scrollbar/react-scrollbar.d.ts | 12 ++++++------ 11 files changed, 19 insertions(+), 37 deletions(-) rename inversify-devtools/{inversify-devtools.d.ts => index.d.ts} (100%) diff --git a/bowser/bowser-tests.ts b/bowser/bowser-tests.ts index 910b716e0f..e8b122a5a9 100644 --- a/bowser/bowser-tests.ts +++ b/bowser/bowser-tests.ts @@ -1,19 +1,9 @@ - - -import Bowser = require('bowser'); - -Bowser.msedge === true; -Bowser.test(['msie']) === true; -Bowser.a === Bowser.c; -Bowser.osversion > 10; -Bowser.osversion === '10.1A'; - bowser.msedge === true; bowser.test(['msie']) === true; bowser.a === bowser.c; bowser.osversion > 10; bowser.osversion === '10.1A'; bowser.compareVersions(['9.0', '10']); -bowser() === {android: true, x: true}; +bowser() === {android: true, x: true}; bowser.check({msie: "11"}, window.navigator.userAgent); bowser.isUnsupportedBrowser({msie: "10"}, window.navigator.userAgent); \ No newline at end of file diff --git a/bowser/index.d.ts b/bowser/index.d.ts index 360e7ddc63..163342a631 100644 --- a/bowser/index.d.ts +++ b/bowser/index.d.ts @@ -3,11 +3,11 @@ // Definitions by: Paulo Cesar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare var def: BowserModule.IBowser; -export = def; +declare const bowser: bowser.IBowser; +export = bowser; export as namespace bowser; -declare namespace BowserModule { +declare namespace bowser { export interface IBowserOS { mac: boolean; diff --git a/cordova-plugin-contacts/index.d.ts b/cordova-plugin-contacts/index.d.ts index 90b21ae2bb..6728b991d6 100644 --- a/cordova-plugin-contacts/index.d.ts +++ b/cordova-plugin-contacts/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for Apache Cordova Contacts plugin. +// Type definitions for Apache Cordova Contacts plugin // Project: https://github.com/apache/cordova-plugin-contacts // Definitions by: Microsoft Open Technologies, Inc. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// // Copyright (c) Microsoft Open Technologies, Inc. // Licensed under the MIT license. @@ -204,7 +204,7 @@ declare var ContactName: { * The ContactField object is a reusable component that represents contact fields generically. * Each ContactField object contains a value, type, and pref property. A Contact object stores * several properties in ContactField[] arrays, such as phone numbers and email addresses. - * + * * In most instances, there are no pre-determined values for a ContactField object's type attribute. * For example, a phone number can specify type values of home, work, mobile, iPhone, * or any other value that is supported by a particular device platform's contact database. diff --git a/cordova-plugin-file/index.d.ts b/cordova-plugin-file/index.d.ts index f9471eda72..3243632714 100644 --- a/cordova-plugin-file/index.d.ts +++ b/cordova-plugin-file/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Apache Cordova File System plugin. +// Type definitions for Apache Cordova File System plugin // Project: https://github.com/apache/cordova-plugin-file // Definitions by: Microsoft Open Technologies, Inc. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/esprima/esprima-tests.ts b/esprima/esprima-tests.ts index 07c8d3f6ad..95414197c2 100644 --- a/esprima/esprima-tests.ts +++ b/esprima/esprima-tests.ts @@ -5,7 +5,7 @@ import esprima = require('esprima'); import * as ESTree from 'estree'; var token: esprima.Token; -var comment: esprima.Comment; +var comment: ESTree.Comment; var program: ESTree.Program; var string: string; diff --git a/esprima/index.d.ts b/esprima/index.d.ts index 312392e4b5..2b89de4105 100644 --- a/esprima/index.d.ts +++ b/esprima/index.d.ts @@ -21,10 +21,6 @@ declare namespace esprima { value: string; } - interface Comment extends ESTree.Node { - value: string; - } - interface Options { loc?: boolean; range?: boolean; diff --git a/inversify-devtools/inversify-devtools.d.ts b/inversify-devtools/index.d.ts similarity index 100% rename from inversify-devtools/inversify-devtools.d.ts rename to inversify-devtools/index.d.ts diff --git a/inversify-devtools/tsconfig.json b/inversify-devtools/tsconfig.json index 7493d3ee13..9620cb1f86 100644 --- a/inversify-devtools/tsconfig.json +++ b/inversify-devtools/tsconfig.json @@ -14,7 +14,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "inversify-devtools.d.ts", + "index.d.ts", "inversify-devtools-test.ts" ] } \ No newline at end of file diff --git a/karma-chai-sinon/karma-chai-sinon.d.ts b/karma-chai-sinon/karma-chai-sinon.d.ts index 4d44d0ce2d..5f1395c583 100644 --- a/karma-chai-sinon/karma-chai-sinon.d.ts +++ b/karma-chai-sinon/karma-chai-sinon.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped /// -import Sinon = require("Sinon"); +import Sinon = require("sinon"); declare global { var should: Chai.Should; diff --git a/masonry-layout/masonry-layout-tests.ts b/masonry-layout/masonry-layout-tests.ts index 65f629db10..ac25f08db2 100644 --- a/masonry-layout/masonry-layout-tests.ts +++ b/masonry-layout/masonry-layout-tests.ts @@ -1,8 +1,4 @@ // test file for masonry-layout.d.ts - -/// -/// - //import {Masonry} from "./masonry-layout.d.ts"; // responsive layouts @@ -44,5 +40,5 @@ function testExtendedOptions() { transitionDuration: '0.4s', resize: true, initLayout: true - }); -} + }); +} diff --git a/react-scrollbar/react-scrollbar.d.ts b/react-scrollbar/react-scrollbar.d.ts index 1abc23921b..dcfc90d02e 100644 --- a/react-scrollbar/react-scrollbar.d.ts +++ b/react-scrollbar/react-scrollbar.d.ts @@ -8,16 +8,16 @@ declare module "react-scrollbar" { interface ScrollAreaProps extends React.Props { className?: string, - style?: __React.CSSProperties, + style?: React.CSSProperties, speed?: number, contentClassName?: string, - contentStyle?: __React.CSSProperties, + contentStyle?: React.CSSProperties, vertical?: boolean, - verticalContainerStyle?: __React.CSSProperties, - verticalScrollbarStyle?: __React.CSSProperties, + verticalContainerStyle?: React.CSSProperties, + verticalScrollbarStyle?: React.CSSProperties, horizontal?: boolean, - horizontalContainerStyle?: __React.CSSProperties, - horizontalScrollbarStyle?: __React.CSSProperties, + horizontalContainerStyle?: React.CSSProperties, + horizontalScrollbarStyle?: React.CSSProperties, onScroll?: (value: {leftPosition: number, topPosition: number, containerHeight: number, containerWidth: number, realHeight: number, realWidth: number}) => void, contentWindow?: any, ownerDocument?: any, From af3a57e16aa35e809b4b23ff21c507d8b040c749 Mon Sep 17 00:00:00 2001 From: zhengbli Date: Fri, 16 Sep 2016 11:36:37 -0700 Subject: [PATCH 107/212] Fix Types-2.0 CI --- ...bowser-tests.ts => bowser-tests-global.ts} | 13 +- bowser/bowser-tests-module.ts | 9 + bowser/tsconfig.json | 3 +- electron/index.d.ts | 2 +- esprima/index.d.ts | 2 +- gulp/index.d.ts | 2 + mongoose-promise/index.d.ts | 231 +++++++++--------- mongoose-promise/tsconfig.json | 2 +- whatwg-fetch/whatwg-fetch-tests.ts | 41 +--- 9 files changed, 134 insertions(+), 171 deletions(-) rename bowser/{bowser-tests.ts => bowser-tests-global.ts} (55%) create mode 100644 bowser/bowser-tests-module.ts diff --git a/bowser/bowser-tests.ts b/bowser/bowser-tests-global.ts similarity index 55% rename from bowser/bowser-tests.ts rename to bowser/bowser-tests-global.ts index 910b716e0f..490d02a254 100644 --- a/bowser/bowser-tests.ts +++ b/bowser/bowser-tests-global.ts @@ -1,19 +1,10 @@ - - -import Bowser = require('bowser'); - -Bowser.msedge === true; -Bowser.test(['msie']) === true; -Bowser.a === Bowser.c; -Bowser.osversion > 10; -Bowser.osversion === '10.1A'; - bowser.msedge === true; bowser.test(['msie']) === true; bowser.a === bowser.c; bowser.osversion > 10; bowser.osversion === '10.1A'; bowser.compareVersions(['9.0', '10']); -bowser() === {android: true, x: true}; + +bowser() === {android: true, x: true}; bowser.check({msie: "11"}, window.navigator.userAgent); bowser.isUnsupportedBrowser({msie: "10"}, window.navigator.userAgent); \ No newline at end of file diff --git a/bowser/bowser-tests-module.ts b/bowser/bowser-tests-module.ts new file mode 100644 index 0000000000..7d662b2f2b --- /dev/null +++ b/bowser/bowser-tests-module.ts @@ -0,0 +1,9 @@ + + +import Bowser = require('bowser'); + +Bowser.msedge === true; +Bowser.test(['msie']) === true; +Bowser.a === Bowser.c; +Bowser.osversion > 10; +Bowser.osversion === '10.1A'; \ No newline at end of file diff --git a/bowser/tsconfig.json b/bowser/tsconfig.json index 7716ba9fcc..5261c0e68b 100644 --- a/bowser/tsconfig.json +++ b/bowser/tsconfig.json @@ -14,6 +14,7 @@ }, "files": [ "index.d.ts", - "bowser-tests.ts" + "bowser-tests-module.ts", + "bowser-tests-global.ts" ] } \ No newline at end of file diff --git a/electron/index.d.ts b/electron/index.d.ts index 7d10fce465..cac4bab9b2 100644 --- a/electron/index.d.ts +++ b/electron/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace Electron { diff --git a/esprima/index.d.ts b/esprima/index.d.ts index 312392e4b5..920257abd3 100644 --- a/esprima/index.d.ts +++ b/esprima/index.d.ts @@ -21,7 +21,7 @@ declare namespace esprima { value: string; } - interface Comment extends ESTree.Node { + interface Comment extends ESTree.BaseNode { value: string; } diff --git a/gulp/index.d.ts b/gulp/index.d.ts index 0387e0962f..89b1a5dfa5 100644 --- a/gulp/index.d.ts +++ b/gulp/index.d.ts @@ -5,9 +5,11 @@ /// /// +/// import Orchestrator = require("orchestrator"); +import VinylFile = require("vinyl"); declare namespace gulp { interface Gulp extends Orchestrator { diff --git a/mongoose-promise/index.d.ts b/mongoose-promise/index.d.ts index d2622bb6f9..fe60fe73c3 100644 --- a/mongoose-promise/index.d.ts +++ b/mongoose-promise/index.d.ts @@ -3,126 +3,125 @@ // Definitions by: simonxca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/* - * These are the default promises included in the Mongoose v4.x - * definitions. They will be deprecated beginning Mongoose V5.x - * in favor of native ES6 Promises. - * - * You can switch the promise library that mongoose uses by: - * - * 1. Including this somewhere in your code: - * mongoose.Promise = YOUR_PROMISE; - * - * 2. Including this somewhere in your main .d.ts file: - * type MongoosePromise = YOUR_PROMISE; - */ +/// +/// /* * http://mongoosejs.com/docs/api.html#promise-js * - * Callback signatures are from the mPromise type definitions. + * mongoose.d.ts uses global.Promise by default. This is the MongooseJS + * mpromise implementation (which are deprecated). If you still want to + * use it, install these definitions in your project. */ -interface MongoosePromise { - /** - * Promise constructor. - * Promises are returned from executed queries. - * @param fn a function which will be called when the promise - * is resolved that accepts fn(err, ...){} as signature - * @event err Emits when the promise is rejected - * @event complete Emits when the promise is fulfilled - * @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native - * promises are not present) but still support plugging in your own ES6-compatible - * promises library. Mongoose 5.0 will not support mpromise. +import mpromise = require('mpromise'); +declare module 'mongoose' { + + type Promise = MongoosePromise; + + /* + * mpromise definitions. + * Callback signatures are from the mPromise type definitions. */ - new(fn?: (err: any, arg: T) => void): MongoosePromise; - new(fn?: (err: any, ...args: T[]) => void): MongoosePromise; + class MongoosePromise extends mpromise { + /** + * Promise constructor. + * Promises are returned from executed queries. + * @param fn a function which will be called when the promise + * is resolved that accepts fn(err, ...){} as signature + * @event err Emits when the promise is rejected + * @event complete Emits when the promise is fulfilled + * @deprecated Mongoose 5.0 will use native promises by default (or bluebird, if native + * promises are not present) but still support plugging in your own ES6-compatible + * promises library. Mongoose 5.0 will not support mpromise. + */ + constructor(fn?: (err: any, arg: T) => void); + constructor(fn?: (err: any, ...args: T[]) => void); + + /** + * Adds a single function as a listener to both err and complete. + * It will be executed with traditional node.js argument position when the promise is resolved. + * @deprecated Use onResolve instead. + */ + addBack(listener: (err: any, arg: T) => void): this; + addBack(listener: (err: any, ...args: T[]) => void): this; + + /** + * Adds a listener to the complete (success) event. + * @deprecated Adds a listener to the complete (success) event. + */ + addCallback(listener: (arg: T) => void): this; + addCallback(listener: (...args: T[]) => void): this; + + /** + * Adds a listener to the err (rejected) event. + * @deprecated Use onReject instead. + */ + addErrback(listener: (err: any) => void): this; + + /** ES6-style .catch() shorthand */ + catch(onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + + /** + * Signifies that this promise was the last in a chain of then()s: if a handler passed + * to the call to then which produced this promise throws, the exception will go uncaught. + */ + end(): void; + + /** + * Rejects this promise with err. + * If the promise has already been fulfilled or rejected, not action is taken. + * Differs from #reject by first casting err to an Error if it is not instanceof Error. + */ + error(err: any): this; + + /** + * Adds listener to the event. + * If event is either the success or failure event and the event has already been emitted, + * thelistener is called immediately and passed the results of the original emitted event. + */ + on(event: string, listener: Function): this; + + /** + * Rejects this promise with reason. + * If the promise has already been fulfilled or rejected, not action is taken. + */ + reject(reason: Object | string | Error): this; + + /** + * Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed. + * If the promise has already been fulfilled or rejected, not action is taken. + * err will be cast to an Error if not already instanceof Error. + * NOTE: overrides mpromise#resolve to provide error casting. + * @param err error or null + * @param val value to fulfill the promise with + */ + resolve(err?: any, val?: Object): this; + + /** + * Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as + * SUCCESS/ERROR callbacks to this promise after the nextTick. + * Conforms to promises/A+ specification. + */ + then(onFulFill: (arg: T) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + then(onFulfill: (...args: T[]) => void | TRes | PromiseLike, + onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; + + /** + * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. + * @deprecated Use fulfill instead. + */ + complete(args: T): this; + complete(...args: T[]): this; + + /** Fulfills this promise with passed arguments. */ + fulfill(...args: T[]): this; + fulfill(arg: T): this; + + /** ES6-style promise constructor wrapper around mpromise. */ + static ES6(resolver: ( + complete: (...args: TRes[]) => void | TRes | PromiseLike, + error: (e: any) => void | TRes | PromiseLike + ) => void): MongoosePromise; + } } - -declare class MongoosePromise { - /** - * Adds a single function as a listener to both err and complete. - * It will be executed with traditional node.js argument position when the promise is resolved. - * @deprecated Use onResolve instead. - */ - addBack(listener: (err: any, arg: T) => void): this; - addBack(listener: (err: any, ...args: T[]) => void): this; - - /** - * Adds a listener to the complete (success) event. - * @deprecated Adds a listener to the complete (success) event. - */ - addCallback(listener: (arg: T) => void): this; - addCallback(listener: (...args: T[]) => void): this; - - /** - * Adds a listener to the err (rejected) event. - * @deprecated Use onReject instead. - */ - addErrback(listener: (err: any) => void): this; - - /** ES6-style .catch() shorthand */ - catch(onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; - - /** - * Signifies that this promise was the last in a chain of then()s: if a handler passed - * to the call to then which produced this promise throws, the exception will go uncaught. - */ - end(): void; - - /** - * Rejects this promise with err. - * If the promise has already been fulfilled or rejected, not action is taken. - * Differs from #reject by first casting err to an Error if it is not instanceof Error. - */ - error(err: any): this; - - /** - * Adds listener to the event. - * If event is either the success or failure event and the event has already been emitted, - * thelistener is called immediately and passed the results of the original emitted event. - */ - on(event: string, listener: Function): this; - - /** - * Rejects this promise with reason. - * If the promise has already been fulfilled or rejected, not action is taken. - */ - reject(reason: Object | string | Error): this; - - /** - * Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed. - * If the promise has already been fulfilled or rejected, not action is taken. - * err will be cast to an Error if not already instanceof Error. - * NOTE: overrides mpromise#resolve to provide error casting. - * @param err error or null - * @param val value to fulfill the promise with - */ - resolve(err?: any, val?: Object): this; - - /** - * Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as - * SUCCESS/ERROR callbacks to this promise after the nextTick. - * Conforms to promises/A+ specification. - */ - then(onFulFill: (arg: T) => void | TRes | PromiseLike, - onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; - then(onFulfill: (...args: T[]) => void | TRes | PromiseLike, - onReject?: (err: any) => void | TRes | PromiseLike): MongoosePromise; - - /** - * Fulfills this promise with passed arguments. Alias of mpromise#fulfill. - * @deprecated Use fulfill instead. - */ - complete(args: T): this; - complete(...args: T[]): this; - - /** Fulfills this promise with passed arguments. */ - fulfill(...args: T[]): this; - fulfill(arg: T): this; - - /** ES6-style promise constructor wrapper around mpromise. */ - static ES6(resolver: ( - complete: (...args: TRes[]) => void | TRes | PromiseLike, - error: (e: any) => void | TRes | PromiseLike - ) => void): MongoosePromise; -} \ No newline at end of file diff --git a/mongoose-promise/tsconfig.json b/mongoose-promise/tsconfig.json index 45378dfc67..ea8993399c 100644 --- a/mongoose-promise/tsconfig.json +++ b/mongoose-promise/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "target": "es5", + "target": "es6", "noImplicitAny": true, "strictNullChecks": false, "baseUrl": "../", diff --git a/whatwg-fetch/whatwg-fetch-tests.ts b/whatwg-fetch/whatwg-fetch-tests.ts index 7434c8372b..aa6b90b8c8 100644 --- a/whatwg-fetch/whatwg-fetch-tests.ts +++ b/whatwg-fetch/whatwg-fetch-tests.ts @@ -1,44 +1,5 @@  -function test_HeadersCopiedFromHeaders1() { - var source = new Headers(); - source.append('Content-Type', 'application/json'); - return new Headers(source); -} - -function test_HeadersCopiedFromHash1() { - var source:HeadersMap = { - 'Content-Type': 'application/json' - }; - return new Headers(source); -} - -function test_HeadersCopiedFromHeaders2() { - var source = new Headers(); - source.append('Content-Type', 'application/json'); - return new Headers(source); -} - -function test_HeadersCopiedFromHash2() { - var source:HeadersMap = { - 'Content-Type': 'application/json' - }; - return new Headers(source); -} - -function test_HeadersCopiedFromHeaders3() { - var source = new Headers(); - source.append('Content-Type', 'application/json'); - return new Headers(source); -} - -function test_HeadersCopiedFromHash3() { - var source:HeadersMap = { - 'Content-Type': 'application/json' - }; - return new Headers(source); -} - function test_HeadersCopiedFromHeaders() { var source = new Headers(); source.append('Content-Type', 'application/json'); @@ -107,4 +68,4 @@ function handlePromise(promise: Promise) { }).then((text) => { console.log(text); }); -} +} \ No newline at end of file From 7c9f3114a756f052ca10caba615540d7b5eb19be Mon Sep 17 00:00:00 2001 From: Dave Dunkin Date: Fri, 16 Sep 2016 12:10:31 -0700 Subject: [PATCH 108/212] Fix elasticsearch get, mget, msearch responses. (#11259) * Fix elasticsearch get, mget, msearch responses. * Fix contributor github links. --- elasticsearch/elasticsearch.d.ts | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index e2079b19d0..d983817869 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -1,6 +1,6 @@ // Type definitions for elasticsearch // Project: https://www.elastic.co/guide/en/elasticsearch/client/javascript-api/current/index.html -// Definitions by: Casper Skydt , Blake Smith +// Definitions by: Casper Skydt , Blake Smith , Dave Dunkin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module Elasticsearch { @@ -15,14 +15,14 @@ declare module Elasticsearch { create(params: CreateDocumentParams, callback: (err: any, response: any, status: any) => void): void; delete(params: DeleteDocumentParams): PromiseLike; delete(params: DeleteDocumentParams, callback: (error: any, response: any) => void): void; - get(params: GetParams, callback: (error: any, response: any) => void): void; + get(params: GetParams, callback: (error: any, response: GetResponse) => void): void; get(params: GetParams): PromiseLike>; index(params: IndexDocumentParams): PromiseLike; index(params: IndexDocumentParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams, callback: (error: any, response: any) => void): void; - mget(params: MGetParams): PromiseLike>; - msearch(params: MSearchParams, callback: (error: any, response: any) => void): void; - msearch(params: MSearchParams): PromiseLike>; + mget(params: MGetParams, callback: (error: any, response: MGetResponse) => void): void; + mget(params: MGetParams): PromiseLike>; + msearch(params: MSearchParams, callback: (error: any, response: MSearchResponse) => void): void; + msearch(params: MSearchParams): PromiseLike>; ping(params: PingParams): PromiseLike; ping(params: PingParams, callback: (err: any, response: any, status: any) => void): void; scroll(params: ScrollParams): PromiseLike; @@ -196,7 +196,8 @@ declare module Elasticsearch { versionType?: string; } - export interface GetResponse extends GenericParams { + export interface GetResponse { + _index: string; _type: string; _id: string; _version: number; @@ -279,6 +280,10 @@ declare module Elasticsearch { search_type?: string; } + export interface MSearchResponse { + responses?: SearchResponse[]; + } + export interface MGetParams extends GenericParams { fields?: string | string[] | Boolean; preference?: string; @@ -290,6 +295,10 @@ declare module Elasticsearch { type?: string; } + export interface MGetResponse { + docs?: GetResponse[]; + } + export interface IndicesIndexExitsParams extends GenericParams { index: string | string[] | boolean; ignoreUnavailable?: boolean; From 27541f076b2e20514cb60456ccaeabf8c9958c88 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 16 Sep 2016 13:16:58 -0700 Subject: [PATCH 109/212] Fix header error: don't need periods at end of name --- cordova-plugin-contacts/index.d.ts | 6 +++--- cordova-plugin-file/index.d.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cordova-plugin-contacts/index.d.ts b/cordova-plugin-contacts/index.d.ts index 90b21ae2bb..6728b991d6 100644 --- a/cordova-plugin-contacts/index.d.ts +++ b/cordova-plugin-contacts/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for Apache Cordova Contacts plugin. +// Type definitions for Apache Cordova Contacts plugin // Project: https://github.com/apache/cordova-plugin-contacts // Definitions by: Microsoft Open Technologies, Inc. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// // Copyright (c) Microsoft Open Technologies, Inc. // Licensed under the MIT license. @@ -204,7 +204,7 @@ declare var ContactName: { * The ContactField object is a reusable component that represents contact fields generically. * Each ContactField object contains a value, type, and pref property. A Contact object stores * several properties in ContactField[] arrays, such as phone numbers and email addresses. - * + * * In most instances, there are no pre-determined values for a ContactField object's type attribute. * For example, a phone number can specify type values of home, work, mobile, iPhone, * or any other value that is supported by a particular device platform's contact database. diff --git a/cordova-plugin-file/index.d.ts b/cordova-plugin-file/index.d.ts index f9471eda72..3243632714 100644 --- a/cordova-plugin-file/index.d.ts +++ b/cordova-plugin-file/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Apache Cordova File System plugin. +// Type definitions for Apache Cordova File System plugin // Project: https://github.com/apache/cordova-plugin-file // Definitions by: Microsoft Open Technologies, Inc. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From e0a4b59de6eea0e2c70b0a403a6566d402f0e1d3 Mon Sep 17 00:00:00 2001 From: Julien Sergent Date: Sat, 17 Sep 2016 00:05:58 +0200 Subject: [PATCH 110/212] Update facebook-js-sdk.d.ts --- facebook-js-sdk/facebook-js-sdk.d.ts | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/facebook-js-sdk/facebook-js-sdk.d.ts b/facebook-js-sdk/facebook-js-sdk.d.ts index 5353353911..bee34f0a2c 100644 --- a/facebook-js-sdk/facebook-js-sdk.d.ts +++ b/facebook-js-sdk/facebook-js-sdk.d.ts @@ -8,10 +8,11 @@ declare var FB: fb.FacebookStatic; declare namespace facebook { interface FacebookStatic { - // api: any; - // AppEvents: any; - // Canvas: any; - // Event: any; + api: any; + AppEvents: any; + Canvas: any; + Event: any; + /** * The method FB.getAuthResponse() is a synchronous accessor for the current authResponse. * The synchronous nature of this method is what sets it apart from the other login methods. @@ -25,7 +26,7 @@ declare namespace facebook { * * @param callback function to handle the response. */ - getLoginStatus(callback: (response: AuthResponse) => void): void; + getLoginStatus(callback: (response: AuthResponse) => void, roundtrip?: boolean ): void; /** * The method FB.init() is used to initialize and setup the SDK. * @@ -49,8 +50,9 @@ declare namespace facebook { * @param callback function to handle the response */ logout(callback: (response: AuthResponse) => void): void; - // ui: any; - // XFBML: any; + + ui: any; + XFBML: any; } interface InitParams { From 915fd561991a100071ce072acb445344ba4001b8 Mon Sep 17 00:00:00 2001 From: Andy Hanson Date: Fri, 16 Sep 2016 15:48:23 -0700 Subject: [PATCH 111/212] Fix more header punctuation --- cordova-plugin-contacts/index.d.ts | 2 +- cordova-plugin-file/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cordova-plugin-contacts/index.d.ts b/cordova-plugin-contacts/index.d.ts index 6728b991d6..f0979ba6c2 100644 --- a/cordova-plugin-contacts/index.d.ts +++ b/cordova-plugin-contacts/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Apache Cordova Contacts plugin // Project: https://github.com/apache/cordova-plugin-contacts -// Definitions by: Microsoft Open Technologies, Inc. +// Definitions by: Microsoft Open Technologies Inc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // // Copyright (c) Microsoft Open Technologies, Inc. diff --git a/cordova-plugin-file/index.d.ts b/cordova-plugin-file/index.d.ts index 3243632714..6aadbf6fad 100644 --- a/cordova-plugin-file/index.d.ts +++ b/cordova-plugin-file/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Apache Cordova File System plugin // Project: https://github.com/apache/cordova-plugin-file -// Definitions by: Microsoft Open Technologies, Inc. +// Definitions by: Microsoft Open Technologies Inc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // // Copyright (c) Microsoft Open Technologies, Inc. From 9d4d9924f1a5562c61421d82d8f4f474a425fb04 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 14:10:19 +0800 Subject: [PATCH 112/212] [node] Clean up tls_tests and wrap in namespace (#11248) * Clean up tls_tests and wrap in namespace for v6.x * Clean up tls_tests and wrap in namespace for v4.x --- node/node-4-tests.ts | 28 +++++++++++++++------------- node/node-tests.ts | 28 +++++++++++++++------------- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 2de910db67..66fc18ce24 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -369,21 +369,23 @@ namespace crypto_tests { } } -//////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html /// +////////////////////////////////////////////////// -var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", -}); -var blah = ctx.context; +namespace tls_tests { + var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", + }); + var blah = ctx.context; -var tlsOpts: tls.TlsOptions = { - host: "127.0.0.1", - port: 55 -}; -var tlsSocket = tls.connect(tlsOpts); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); +} //////////////////////////////////////////////////// /// Http tests : http://nodejs.org/api/http.html /// diff --git a/node/node-tests.ts b/node/node-tests.ts index e0600d936d..06fb4a9bf7 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -544,21 +544,23 @@ namespace crypto_tests { } } -//////////////////////////////////////////////////// -/// TLS tests : http://nodejs.org/api/tls.html -//////////////////////////////////////////////////// +////////////////////////////////////////////////// +/// TLS tests : http://nodejs.org/api/tls.html /// +////////////////////////////////////////////////// -var ctx: tls.SecureContext = tls.createSecureContext({ - key: "NOT REALLY A KEY", - cert: "SOME CERTIFICATE", -}); -var blah = ctx.context; +namespace tls_tests { + var ctx: tls.SecureContext = tls.createSecureContext({ + key: "NOT REALLY A KEY", + cert: "SOME CERTIFICATE", + }); + var blah = ctx.context; -var connOpts: tls.ConnectionOptions = { - host: "127.0.0.1", - port: 55 -}; -var tlsSocket = tls.connect(connOpts); + var connOpts: tls.ConnectionOptions = { + host: "127.0.0.1", + port: 55 + }; + var tlsSocket = tls.connect(connOpts); +} //////////////////////////////////////////////////// /// Http tests : http://nodejs.org/api/http.html /// From 3e403832f65f64c1ad1b2e29e4e520838519e14b Mon Sep 17 00:00:00 2001 From: Tommy Frazier Date: Mon, 19 Sep 2016 02:10:41 -0400 Subject: [PATCH 113/212] Add httpsServerOptions to ServerOptions interface (#11155) --- restify/restify.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/restify/restify.d.ts b/restify/restify.d.ts index d8e1a37576..65b3f44d47 100644 --- a/restify/restify.d.ts +++ b/restify/restify.d.ts @@ -452,6 +452,7 @@ declare module "restify" { responseTimeFormatter ?: (durationInMilliseconds: number) => any; handleUpgrades ?: boolean; router ?: Router; + httpsServerOptions?: any; } interface ClientOptions { From 5e55876028163634704f9f73db4fce2314e02a7d Mon Sep 17 00:00:00 2001 From: Constantin Date: Mon, 19 Sep 2016 08:11:16 +0200 Subject: [PATCH 114/212] webix - added fail to Promise (#11250) --- webix/webix.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webix/webix.d.ts b/webix/webix.d.ts index 9c516654a1..7931ef83d9 100644 --- a/webix/webix.d.ts +++ b/webix/webix.d.ts @@ -9,6 +9,7 @@ type WebixTemplate = (...args: any[])=>string; type WebixCallback = (...args: any[])=>any; interface PromisedData { then(handler:(data:any)=>any):PromisedData; + fail(handler:(error:any)=>any):PromisedData; } function ajax():webix._ajax; @@ -8620,4 +8621,4 @@ interface window extends webix.ui.baseview{ }} -declare function $$(id: string | Event | HTMLElement): webix.ui.baseview; \ No newline at end of file +declare function $$(id: string | Event | HTMLElement): webix.ui.baseview; From 863fdd02c68c82696163f06d8d5b8ce40a10f64d Mon Sep 17 00:00:00 2001 From: Natan Vivo Date: Mon, 19 Sep 2016 03:13:38 -0300 Subject: [PATCH 115/212] Added component option to angular ui bootstrap modal settings. (#11249) --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index dd129d141d..1d0e28b859 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -329,6 +329,12 @@ declare namespace angular.ui.bootstrap { * @default false */ bindToController?: boolean; + + /** + * A string reference to the component to be rendered that is registered with Angular's compiler. + * If using a directive, the directive must have restrict: 'E' and a template or templateUrl set. + */ + component?: string; /** * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes From e69548d34035dbb8dfb11162c6e1b2df0a894a79 Mon Sep 17 00:00:00 2001 From: Martin D Date: Mon, 19 Sep 2016 02:15:00 -0400 Subject: [PATCH 116/212] Fixed arguments for tooltips value formatting (#11253) * Update c3.d.ts Fixed arguments for tooltips value formatting * Update c3.d.ts --- c3/c3.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/c3/c3.d.ts b/c3/c3.d.ts index 2838ba2675..e815b44391 100644 --- a/c3/c3.d.ts +++ b/c3/c3.d.ts @@ -681,7 +681,7 @@ declare namespace c3 { * Specified function receives name, ratio, id and index of the data point to show. ratio will be undefined if the chart is not donut/pie/gauge. * If undefined returned, the row of that value will be skipped. */ - value?: (name: string, ratio: number, id: string, index: number) => string; + value?: (value: any, ratio: number, id: string, index: number) => string; }; /** * Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left. From 83adc941d134189c3a55afb73e940ce70308b35b Mon Sep 17 00:00:00 2001 From: Zipeng WU Date: Mon, 19 Sep 2016 08:15:16 +0200 Subject: [PATCH 117/212] Support syncBrushing option on Focus component (#11204) --- nvd3/nvd3.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/nvd3/nvd3.d.ts b/nvd3/nvd3.d.ts index 769d900399..75e6693bdc 100644 --- a/nvd3/nvd3.d.ts +++ b/nvd3/nvd3.d.ts @@ -159,6 +159,8 @@ declare namespace nv { interpolate(value: string): this; rightAlignYAxis(): boolean; rightAlignYAxis(value: boolean): this; + syncBrushing(): boolean; + syncBrushing(value: boolean): this; } interface Nvd3Axis extends d3.svg.Axis { From c0ce167c104f2224111c87fb81c8be5c530916ba Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 02:15:35 -0400 Subject: [PATCH 118/212] Improve polylabel ES6 import syntax (#11260) Using `import * as polylabel from 'polylabel'` is now valid in Typescript vs. require('polylabel'). --- polylabel/polylabel-tests.ts | 12 +++++------- polylabel/polylabel.d.ts | 5 +++-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/polylabel/polylabel-tests.ts b/polylabel/polylabel-tests.ts index 9e23d20d38..e428dbfdb3 100644 --- a/polylabel/polylabel-tests.ts +++ b/polylabel/polylabel-tests.ts @@ -1,10 +1,8 @@ /// -/// -import polylabel = require('polylabel'); +import * as polylabel from 'polylabel'; const polygon = [[[3116,3071],[3118,3068],[3108,3102],[3751,927]]] -let p: number[] -p = polylabel(polygon) -p = polylabel(polygon, 1.0) -p = polylabel(polygon, 1.0, true) -p = polylabel(polygon, 1.0, false) +polylabel(polygon) +polylabel(polygon, 1.0) +polylabel(polygon, 1.0, true) +polylabel(polygon, 1.0, false) diff --git a/polylabel/polylabel.d.ts b/polylabel/polylabel.d.ts index 21f50d1b41..1fe6aec3df 100644 --- a/polylabel/polylabel.d.ts +++ b/polylabel/polylabel.d.ts @@ -15,7 +15,7 @@ * - guarantees finding global optimum within the given precision * - is many times faster (10-40x) */ -declare module 'polylabel' { +declare module "polylabel" { /** * Polylabel returns the pole of inaccessibility coordinate in [x, y] format. * @@ -28,6 +28,7 @@ declare module 'polylabel' { * @example * var p = polylabel(polygon, 1.0); */ - function polylabel (polygon: number[][][], precision?: number, debug?: boolean): number[]; + function polylabel(polygon: number[][][], precision?: number, debug?: boolean): number[]; + namespace polylabel {} export = polylabel; } From 50155318b25a75908cb1427ac8b1ab7a9108949c Mon Sep 17 00:00:00 2001 From: Nick Graef Date: Mon, 19 Sep 2016 01:16:16 -0500 Subject: [PATCH 119/212] fix function signatures (#11261) Documentation: https://github.com/mgonto/restangular#restangular-methods According to the documentation and source code, `all` and `allUrl` return collections, not elements. Additionally, the `post` signature without `subElement` is only available on collections, not elements. --- restangular/restangular.d.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/restangular/restangular.d.ts b/restangular/restangular.d.ts index 8daa5c0b08..b0ae6b7ca5 100644 --- a/restangular/restangular.d.ts +++ b/restangular/restangular.d.ts @@ -84,8 +84,8 @@ declare namespace restangular { one(route: string, id?: number): IElement; one(route: string, id?: string): IElement; oneUrl(route: string, url: string): IElement; - all(route: string): IElement; - allUrl(route: string, url: string): IElement; + all(route: string): ICollection; + allUrl(route: string, url: string): ICollection; copy(fromElement: any): IElement; withConfig(configurer: (RestangularProvider: IProvider) => any): IService; restangularizeElement(parent: any, element: any, route: string, collection?: any, reqParams?: any): IElement; @@ -104,8 +104,6 @@ declare namespace restangular { put(queryParams?: any, headers?: any): IPromise; post(subElement: any, elementToPost: any, queryParams?: any, headers?: any): IPromise; post(subElement: any, elementToPost: T, queryParams?: any, headers?: any): IPromise; - post(elementToPost: any, queryParams?: any, headers?: any): IPromise; - post(elementToPost: T, queryParams?: any, headers?: any): IPromise; remove(queryParams?: any, headers?: any): IPromise; head(queryParams?: any, headers?: any): IPromise; trace(queryParams?: any, headers?: any): IPromise; From 609f1f78e8e830c46cb3ac6876102c62d274821f Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 02:17:07 -0400 Subject: [PATCH 120/212] Implement concaveman definition (#11262) * Implement concaveman definition Author of concaveman module @mourner * remove console log --- concaveman/concaveman-tests.ts | 5 +++++ concaveman/concaveman.d.ts | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 concaveman/concaveman-tests.ts create mode 100644 concaveman/concaveman.d.ts diff --git a/concaveman/concaveman-tests.ts b/concaveman/concaveman-tests.ts new file mode 100644 index 0000000000..ddb1e6d125 --- /dev/null +++ b/concaveman/concaveman-tests.ts @@ -0,0 +1,5 @@ +/// +import * as concaveman from 'concaveman'; + +var points = [[10, 20], [30, 12.5]]; +var polygon = concaveman(points); \ No newline at end of file diff --git a/concaveman/concaveman.d.ts b/concaveman/concaveman.d.ts new file mode 100644 index 0000000000..a5b55c8fa3 --- /dev/null +++ b/concaveman/concaveman.d.ts @@ -0,0 +1,24 @@ +// Type definitions for concaveman 1.1.0 +// Project: https://github.com/mapbox/concaveman +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "concaveman" { + /** + * A very fast 2D concave hull algorithm in JavaScript (generates a general outline of a point set). + * + * @name concaveman + * @param {Array>} points is an array of [x, y] points. + * @param {number} [concavity=2] is a relative measure of concavity. 1 results in a relatively detailed shape, Infinity results in a convex hull. You can use values lower than 1, but they can produce pretty crazy shapes. + * @param {number} [lengthThreshold=0] when a segment length is under this threshold, it stops being considered for further detalization. Higher values result in simpler shapes. + * @return {Array>} + * @example + * var points = [[10, 20], [30, 12.5], ...]; + * var polygon = concaveman(points); + * + * //=hull + */ + function concaveman(points: number[][], concavity?: number, lengthThreshold?: number): number[][]; + namespace concaveman {} + export = concaveman; +} From 8a8a1396214462baab5b04c498d3b2d869d4c5ed Mon Sep 17 00:00:00 2001 From: Alexander Kalitenya Date: Mon, 19 Sep 2016 11:17:38 +0500 Subject: [PATCH 121/212] Update auth0.lock.d.ts (#11199) --- auth0.lock/auth0.lock.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts index 43d842aecc..2d74f6e6a5 100644 --- a/auth0.lock/auth0.lock.d.ts +++ b/auth0.lock/auth0.lock.d.ts @@ -92,7 +92,7 @@ interface Auth0LockConstructorOptions { initialScreen?: "login" | "signUp" | "forgotPassword"; language?: string; languageDictionary?: any; - loginAfterSignup?: boolean; + loginAfterSignUp?: boolean; mustAcceptTerms?: boolean; popupOptions?: Auth0LockPopupOptions; prefill?: { email?: string, username?: string}; From 18d656dda34aae2e331ab2c462c6aa328fbd387e Mon Sep 17 00:00:00 2001 From: ersimont Date: Mon, 19 Sep 2016 02:19:25 -0400 Subject: [PATCH 122/212] Update angular-ui-bootstrap.d.ts (#11263) Add `component` option for modals --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 1d0e28b859..71ef8b7363 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -406,6 +406,17 @@ declare namespace angular.ui.bootstrap { * @default 'body' */ appendTo?: angular.IAugmentedJQuery; + + /** + * A string reference to the component to be rendered that is registered with Angular's compiler. If using a directive, the directive must have `restrict: 'E'` and a template or templateUrl set. + * + * It supports these bindings: + * - `close` - A method that can be used to close a modal, passing a result. The result must be passed in this format: `{$value: myResult}` + * - `dismiss` - A method that can be used to dismiss a modal, passing a result. The result must be passed in this format: `{$value: myRejectedResult}` + * - `modalInstance` - The modal instance. This is the same `$uibModalInstance` injectable found when using `controller`. + * - `resolve` - An object of the modal resolve values. See [UI Router resolves] for details. + */ + component?: string; } interface IModalStackService { From b0a9f0e1dbf998308a54f7738b8779f83f00c3fc Mon Sep 17 00:00:00 2001 From: Endel Dreyer Date: Mon, 19 Sep 2016 08:24:20 +0200 Subject: [PATCH 123/212] Add totalFrames and duration properties to MovieClip (#11270) Official documentation for those properties: - http://www.createjs.com/docs/easeljs/classes/MovieClip.html#property_totalFrames - http://www.createjs.com/docs/easeljs/classes/MovieClip.html#property_duration --- easeljs/easeljs.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/easeljs/easeljs.d.ts b/easeljs/easeljs.d.ts index 3ddeabdef9..ab8cd5a0e1 100644 --- a/easeljs/easeljs.d.ts +++ b/easeljs/easeljs.d.ts @@ -650,6 +650,7 @@ declare namespace createjs { autoReset: boolean; static buildDate: string; currentFrame: number; + totalFrames: number; currentLabel: string; frameBounds: Rectangle[]; framerate: number; @@ -662,6 +663,7 @@ declare namespace createjs { startPosition: number; static SYNCHED: string; timeline: Timeline; + duration: number; static version: string; // methods From 48649b87187b5ff3448d291c847a35da65d12d93 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 14:29:20 +0800 Subject: [PATCH 124/212] [node] Add events and exitedAfterDisconnect in cluster.work (#11275) * Add events for cluster.worker * Add exitedAfterDisconnect for cluster.Worker --- node/node.d.ts | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 81b13e4e1d..54e826301a 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -778,6 +778,56 @@ declare module "cluster" { disconnect(): void; isConnected(): boolean; isDead(): boolean; + exitedAfterDisconnect: boolean; + + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: Function): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; } export interface Cluster extends events.EventEmitter { From 28d94377786d6da325b76614aa4c1849dc05703e Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 14:30:32 +0800 Subject: [PATCH 125/212] Add events for fs (#11277) --- node/node.d.ts | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/node/node.d.ts b/node/node.d.ts index 54e826301a..888da5cec4 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -1788,16 +1788,92 @@ declare module "fs" { interface FSWatcher extends events.EventEmitter { close(): void; + + /** + * events.EventEmitter + * 1. change + * 2. error + */ + addListener(event: string, listener: Function): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "error", listener: (code: number, signal: string) => void): this; + + on(event: string, listener: Function): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "error", listener: (code: number, signal: string) => void): this; + + once(event: string, listener: Function): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "error", listener: (code: number, signal: string) => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "error", listener: (code: number, signal: string) => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (code: number, signal: string) => void): this; } export interface ReadStream extends stream.Readable { close(): void; destroy(): void; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; } + export interface WriteStream extends stream.Writable { close(): void; bytesWritten: number; path: string | Buffer; + + /** + * events.EventEmitter + * 1. open + * 2. close + */ + addListener(event: string, listener: Function): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "close", listener: () => void): this; + + on(event: string, listener: Function): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "close", listener: () => void): this; + + once(event: string, listener: Function): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "close", listener: () => void): this; + + prependListener(event: string, listener: Function): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "close", listener: () => void): this; + + prependOnceListener(event: string, listener: Function): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; } /** From 93d269d6da3a675d49648330b412a6c7b6981c89 Mon Sep 17 00:00:00 2001 From: "Dmitry A. Efimenko" Date: Sun, 18 Sep 2016 23:49:21 -0700 Subject: [PATCH 126/212] added prop options and func timeFormatter (#11256) added property `options`, which can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L270). Even though it's not mentioned in the docs, it useful to be able to access these options after chart is initialized when you want to change appearance in real tme. added function `timeFormatter`, which is mentioned in [right here, in the definitions](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/smoothie/smoothie.d.ts#L127) and can be found in [the code](https://github.com/joewalnes/smoothie/blob/15fc4b62f5b23c8d5dd1784c820ae73f341626e6/smoothie.js#L795) --- smoothie/smoothie.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/smoothie/smoothie.d.ts b/smoothie/smoothie.d.ts index 98f205f598..c396261c52 100644 --- a/smoothie/smoothie.d.ts +++ b/smoothie/smoothie.d.ts @@ -141,6 +141,8 @@ declare module "smoothie" */ export class SmoothieChart { + options: IChartOptions; + constructor(chartOptions?: IChartOptions); /** @@ -188,5 +190,7 @@ declare module "smoothie" updateValueRange(): void; render(canvas?: HTMLCanvasElement, time?: number): void; + + static timeFormatter(date: Date): string; } } From 80e5c9b45b7ddd6442bcabbebf418fa1a658307b Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 02:50:52 -0400 Subject: [PATCH 127/212] Define Turf 3.5.2 definition (#11123) * Define Turf 3.5.2 definition Update all methods with newest JSDocs & tests based on the latest TurfJS library. AGGREGATION - [x] collect MEASUREMENT - [ ] along - [ ] area - [ ] bboxPolygon - [ ] bearing - [ ] center - [ ] centroid - [ ] destination - [ ] distance - [ ] envelope - [ ] lineDistance - [ ] midpoint - [ ] pointOnSurface - [ ] square TRANSFORMATION - [ ] bezier - [ ] buffer - [ ] concave - [ ] convex - [ ] difference - [ ] intersect - [ ] simplify - [ ] union MISC - [ ] combine - [ ] explode - [ ] flip - [ ] kinks - [ ] lineSlice - [ ] pointOnLine HELPER - [x] featureCollection - [x] feature - [x] lineString - [x] multiLineString - [x] point - [x] multiPoint - [x] polygon - [x] multiPolygon - [x] geometryCollection DATA - [x] random - [x] sample INTERPOLATION - [ ] isolines - [ ] planepoint - [ ] tin JOINS - [ ] inside - [ ] tag GRIDS - [ ] hexGrid - [ ] pointGrid - [ ] squareGrid - [ ] triangleGrid - [ ] within CLASSIFICATION - [ ] nearest META - [ ] propEach - [ ] coordEach - [ ] coordReduce - [ ] featureEach - [ ] getCoord ASSERTIONS - [ ] featureOf - [ ] collectionOf - [ ] bbox - [ ] circle - [ ] geojsonType - [ ] propReduce - [ ] coordAll - [ ] tesselate * Added Turf Grids functions - Added more variables to data initialisation. - Remove excess feature points. - Add URL in `@name` in function JSDocs GRIDS - [x] hexGrid - [x] pointGrid - [x] squareGrid - [x] triangleGrid * Use the latest Turf import - Added in test case how to import individal functions npm install in Node.js ``` npm install @turf/turf ``` https://github.com/Turfjs/turf * Change Turf functions into interfaces * Added Turf typeof units `units` is an optional parameter for all Turf functions with the following options `'miles' | 'nauticalmiles' | 'degrees' | 'radians' | 'inches' | 'yards' | 'meters' | 'metres' | 'kilometers' | 'kilometres'` * Update Turf `inside` & `tag` Add JSDocs & validate both methods * Add imports to Turf submodules * Add Author to Turf @vvakame followed the same syntax as Lodash * Simplify Turf `intersect` interface Turf only officially supports `poly,poly`, all other geometry input/outputs are valid, however can't control the outputs. https://github.com/Turfjs/turf/pull/479 * Comment Turf export default module Next release of Turf will have this implemented * Remove default export turf Was meant to be a comment instead, removed it for now to be safe, it will become available next release * Added Turf.bbox function --- turf/turf-2.0-tests.ts | 522 +++++++++++++++++ turf/turf-2.0.d.ts | 580 +++++++++++++++++++ turf/turf-tests.ts | 512 +++++++++-------- turf/turf.d.ts | 1203 ++++++++++++++++++++++++++++++---------- 4 files changed, 2265 insertions(+), 552 deletions(-) create mode 100644 turf/turf-2.0-tests.ts create mode 100644 turf/turf-2.0.d.ts diff --git a/turf/turf-2.0-tests.ts b/turf/turf-2.0-tests.ts new file mode 100644 index 0000000000..45d9dbcc42 --- /dev/null +++ b/turf/turf-2.0-tests.ts @@ -0,0 +1,522 @@ +/// + +/////////////////////////////////////////// +// Tests data initialisation +/////////////////////////////////////////// + +var point1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-75.343, 39.984] + } +}; + +var point2: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-75.534, 39.123] + } +}; + +var line: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "LineString", + "coordinates": [ + [-77.031669, 38.878605], + [-77.029609, 38.881946], + [-77.020339, 38.884084], + [-77.025661, 38.885821], + [-77.021884, 38.889563], + [-77.019824, 38.892368] + ] + } +}; + +var polygons: GeoJSON.FeatureCollection = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-67.031021, 10.458102], + [-67.031021, 10.53372], + [-66.929397, 10.53372], + [-66.929397, 10.458102], + [-67.031021, 10.458102] + ]] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-66.919784, 10.397325], + [-66.919784, 10.513467], + [-66.805114, 10.513467], + [-66.805114, 10.397325], + [-66.919784, 10.397325] + ]] + } + } + ] +}; + +var polygon1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [105.818939,21.004714], + [105.818939,21.061754], + [105.890007,21.061754], + [105.890007,21.004714], + [105.818939,21.004714] + ]] + } +}; + +var polygon2: GeoJSON.Feature = { + "type": "Feature", + "properties": { + "fill": "#00f" + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-122.520217, 45.535693], + [-122.64038, 45.553967], + [-122.720031, 45.526554], + [-122.669906, 45.507309], + [-122.723464, 45.446643], + [-122.532577, 45.408574], + [-122.487258, 45.477466], + [-122.520217, 45.535693] + ]] + } +} + +var features: GeoJSON.FeatureCollection = { + "type": "FeatureCollection", + "features": [ + { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.522259, 35.4691] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.502754, 35.463455] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.508269, 35.463245] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.516809, 35.465779] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.515372, 35.467072] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.509363, 35.463053] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.511123, 35.466601] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.518547, 35.469327] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.519706, 35.469659] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.517839, 35.466998] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.508678, 35.464942] + } + }, { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "Point", + "coordinates": [-97.514914, 35.463453] + } + } + ] +}; + +var triangle: GeoJSON.Feature = { + "type": "Feature", + "properties": { + "a": 11, + "b": 122, + "c": 44 + }, + "geometry": { + "type": "Polygon", + "coordinates": [[ + [-75.1221, 39.57], + [-75.58, 39.18], + [-75.97, 39.86], + [-75.1221, 39.57] + ]] + } +}; + +var aggregations = [ + { + aggregation: 'sum', + inField: 'population', + outField: 'pop_sum' + }, + { + aggregation: 'average', + inField: 'population', + outField: 'pop_avg' + }, + { + aggregation: 'median', + inField: 'population', + outField: 'pop_median' + }, + { + aggregation: 'min', + inField: 'population', + outField: 'pop_min' + }, + { + aggregation: 'max', + inField: 'population', + outField: 'pop_max' + }, + { + aggregation: 'deviation', + inField: 'population', + outField: 'pop_deviation' + }, + { + aggregation: 'variance', + inField: 'population', + outField: 'pop_variance' + }, + { + aggregation: 'count', + inField: '', + outField: 'point_count' + } +]; + +/////////////////////////////////////////// +// Tests Aggregation +/////////////////////////////////////////// + +// -- Test aggregate -- +var aggregated = turf.aggregate(polygons, points, aggregations); + +// -- Test average -- +var averaged = turf.average(polygons, points, 'population', 'pop_avg'); + +// -- Test count -- +var counted = turf.count(polygons, points, 'pt_count'); + +// -- Test deviation -- +var deviated = turf.deviation(polygons, points, 'population', 'pop_deviation'); + +// -- Test max -- +var aggregated = turf.max(polygons, points, 'population', 'max'); + +// -- Test median -- +var medians = turf.median(polygons, points, 'population', 'median'); + +// -- Test min -- +var minimums = turf.min(polygons, points, 'population', 'min'); + +// -- Test sum -- +var summed = turf.sum(polygons, points, 'population', 'sum'); + +// -- Test variance -- +var varianced = turf.variance(polygons, points, 'population', 'variance'); + +/////////////////////////////////////////// +// Tests Measurement +/////////////////////////////////////////// + +// -- Test along -- +var along = turf.along(line, 1, 'miles'); + +// -- Test area -- +var area = turf.area(polygons); + +// -- Test bboxPolygon -- +var bbox = [0, 0, 10, 10]; +var poly = turf.bboxPolygon(bbox); + +// -- Test bearing -- +var bearing = turf.bearing(point1, point2); + +// -- Test center +var centerPt = turf.center(features); + +// -- Test centroid -- +var centroidPt = turf.centroid(polygon1); + +// -- Test destination -- +var distance = 50; +var bearing = 90; +var units = 'miles'; +var destination = turf.destination(point1, distance, bearing, units); + +// -- Test distance -- +var units = "miles"; +var distance = turf.distance(point1, point2, units); + +// -- Test envelope -- +var enveloped = turf.envelope(polygons); + +// -- Test extent -- +var bbox = turf.extent(polygons); + +// -- Test lineDistance +var length = turf.lineDistance(line, 'miles'); + +// -- Test midpoint -- +var midpointed = turf.midpoint(point1, point2); + +// -- Test pointOnSurface -- +var pointOnPolygon = turf.pointOnSurface(polygon1); + +// -- Test size -- +var resized = turf.size(bbox, 2); + +// -- Test square -- +var squared = turf.square(bbox); + +/////////////////////////////////////////// +// Tests Transformation +/////////////////////////////////////////// + +// -- Test bezier -- +var curved = turf.bezier(line); + +// -- Test buffer -- +var buffered = turf.buffer(point1, 500, units); + +// -- Test concave -- +var hull = turf.concave(features, 1, 'miles'); + +// -- Test convex -- +var hull = turf.convex(features); + +// -- Test difference -- +var differenced = turf.difference(polygon1, polygon2); + +// -- Test intersect -- +var intersection = turf.intersect(polygon1, polygon2); + +// -- Test merge -- +var merged = turf.merge(polygons); + +// -- Test simplify -- +var tolerance = 0.01; +var simplified = turf.simplify(polygon1, tolerance, false); + +// -- Test union -- +var union = turf.union(polygon1, polygon2); + +/////////////////////////////////////////// +// Tests Misc +/////////////////////////////////////////// + +// -- Test combine -- +var combined = turf.combine(features); + +// -- Test explode -- +var points = turf.explode(polygon1); + +// -- Test flip -- +var flipedPoint = turf.flip(point1); + +// -- Test kinks -- +var kinks = turf.kinks(polygon1); + +// -- Test lineSlice -- +var sliced = turf.lineSlice(point1, point2, line); + +// -- Test pointOnLine -- +var snapped = turf.pointOnLine(line, point1); + +/////////////////////////////////////////// +// Tests Helper +/////////////////////////////////////////// + +// -- Test featurecollection -- +var fc = turf.featurecollection([point1, point2]); + +// -- Test linestring -- +var linestring1 = turf.linestring([ + [-21.964416, 64.148203], + [-21.956176, 64.141316], + [-21.93901, 64.135924], + [-21.927337, 64.136673] +]); +var linestring2 = turf.linestring([ + [-21.929054, 64.127985], + [-21.912918, 64.134726], + [-21.916007, 64.141016], + [-21.930084, 64.14446] +], {name: 'line 1', distance: 145}); + +// -- Test point -- +var pt1 = turf.point([-75.343, 39.984]); +var pt2 = turf.point([-75.343, 39.984], {name: 'point 1', distance: 145}); + +// -- Test polygon -- +var polygon = turf.polygon([[ + [-2.275543, 53.464547], + [-2.275543, 53.489271], + [-2.215118, 53.489271], + [-2.215118, 53.464547], + [-2.275543, 53.464547] +]], { name: 'poly1', population: 400}); + +/////////////////////////////////////////// +// Tests Data +/////////////////////////////////////////// + +// -- Test filter -- +var key = "species"; +var value = "oak"; +var filtered = turf.filter(features, key, value); + +// -- Test random -- +var randomPoints = turf.random('points', 100, { + bbox: [-70, 40, -60, 60] +}); + +var randomPoints = turf.random('points', 100, { + bbox: [-70, 40, -60, 60], + num_vertices: 2, + max_radial_length: 10 +}); + +// -- Test remove -- +var filtered = turf.remove(points, 'marker-color', '#00f'); + +// -- Test sample -- +var randomPoints = turf.random('points', 1000); +var sample = turf.sample(points, 10); + +/////////////////////////////////////////// +// Tests Interpolation +/////////////////////////////////////////// + +// -- Test hexGrid -- +var cellWidth = 50; +var hexgrid = turf.hexGrid(bbox, cellWidth, units); + +// -- Test isolines -- +var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; +var isolined = turf.isolines(points, 'z', 15, breaks); + +// -- Test planepoint -- +var zValue = turf.planepoint(point1, triangle); + +// -- Test pointGrid -- +var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; +var cellWidth = 3; +var grid = turf.pointGrid(extent, cellWidth, units); + +// -- Test squareGrid -- +var squareGrid = turf.squareGrid(extent, cellWidth, units); + +// -- Test tin -- +var tin = turf.tin(points, 'z'); + +// -- Test triangleGrid -- +var triangleGrid = turf.triangleGrid(extent, cellWidth, units); + +/////////////////////////////////////////// +// Tests Joins +/////////////////////////////////////////// + +// -- Test inside -- +var isInside1 = turf.inside(point1, polygon); + +// -- Test tag -- +var tagged = turf.tag(points, triangleGrid, 'fill', 'marker-color'); + +// -- Test within -- +var ptsWithin = turf.within(points, polygons); + +/////////////////////////////////////////// +// Tests Classification +/////////////////////////////////////////// + +// -- Test jenks -- +var breaks = turf.jenks(points, 'population', 3); + +// -- Test nearest -- +var nearest = turf.nearest(point1, points); + +// -- Test quantile -- +var breaks = turf.quantile(points, 'population', [25, 50, 75, 99]); + +// -- Test reclass -- +var translations = [ + [0, 200, "small"], + [200, 400, "medium"], + [400, 600, "large"] +]; +var reclassed = turf.reclass(points, 'population', 'size', translations); diff --git a/turf/turf-2.0.d.ts b/turf/turf-2.0.d.ts new file mode 100644 index 0000000000..647df93398 --- /dev/null +++ b/turf/turf-2.0.d.ts @@ -0,0 +1,580 @@ +// Type definitions for Turf 2.0 +// Project: http://turfjs.org/ +// Definitions by: Guillaume Croteau +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare module turf { + ////////////////////////////////////////////////////// + // Aggregation + ////////////////////////////////////////////////////// + + /** + * Calculates a series of aggregations for a set of points within a set of polygons. + * Sum, average, count, min, max, and deviation are supported. + * @param polygons Polygons with values on which to aggregate + * @param points Points to be aggregated + * @param aggregations An array of aggregation objects + * @returns Polygons with properties listed based on outField values in aggregations + */ + function aggregate(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, aggregations: Array<{aggregation: string, inField: string, outField: string}>): GeoJSON.FeatureCollection; + + /** + * Calculates the average value of a field for a set of points within a set of polygons. + * @param polygons Polygons with values on which to average + * @param points Points from which to calculate the average + * @param field The field in the points features from which to pull values to average + * @param outField The field in polygons to put results of the averages + * @returns Polygons with the value of outField set to the calculated averages + */ + function average(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, field: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and a set of polygons and calculates the number of points that fall within the set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param countField A field to append to the attributes of the Polygon features representing Point counts + * @returns Polygons with countField appended + */ + function count(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, countField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the standard deviation value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in points from which to aggregate + * @param outField The field to append to polygons representing deviation + * @returns Polygons with appended field representing deviation + */ + function deviation(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the maximum value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function max(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the median value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function median(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the minimum value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField values + */ + function min(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the sum of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField + */ + function sum(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + /** + * Calculates the variance value of a field for a set of points within a set of polygons. + * @param polygons Input polygons + * @param points Input points + * @param inField The field in input data to analyze + * @param outField The field in which to store results + * @returns Polygons with properties listed as outField + */ + function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Measurement + ////////////////////////////////////////////////////// + + /** + * Takes a line and returns a point at a specified distance along the line. + * @param line Input line + * @param distance Distance along the line + * @param [units=miles] 'miles', 'kilometers', 'radians' or 'degrees' + * @returns Point along the line + */ + function along(line: GeoJSON.Feature, distance: number, units?: string): GeoJSON.Feature; + + /** + * Takes one or more features and returns their area in square meters. + * @param input Input features + * @returns Area in square meters + */ + function area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + + /** + * Takes a bbox and returns an equivalent polygon. + * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] + * @returns A Polygon representation of the bounding box + */ + function bboxPolygon(bbox: Array): GeoJSON.Feature; + + /** + * Takes two points and finds the geographic bearing between them. + * @param start Starting Point + * @param end Ending point + * @returns Bearing in decimal degrees + */ + function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; + + /** + * Takes a FeatureCollection and returns the absolute center point of all features. + * @param features Input features + * @returns A Point feature at the absolute center point of all input features + */ + function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes one or more features and calculates the centroid using the arithmetic mean of all vertices. + * This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons. + * @param features Input features + * @returns The centroid of the input features + */ + function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. + * This uses the Haversine formula to account for global curvature. + * @param start Starting point + * @param distance Distance from the starting point + * @param bearing Ranging from -180 and 180 + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Destination point + */ + function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature; + + /** + * Calculates the distance between two points in degress, radians, miles, or kilometers. + * This uses the Haversine formula to account for global curvature. + * @param from Origin point + * @param to Destination point + * @param [units=kilometers] 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Distance between the two points + */ + function distance(from: GeoJSON.Feature, to: GeoJSON.Feature, units?: string): number; + + /** + * Takes any number of features and returns a rectangular Polygon that encompasses all vertices. + * @param fc Input features + * @returns A rectangular Polygon feature that encompasses all vertices + */ + function envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a set of features, calculates the extent of all input features, and returns a bounding box. + * @param input Input features + * @returns The bounding box of input given as an array in WSEN order (west, south, east, north) + */ + function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + + /** + * Takes a line and measures its length in the specified units. + * @param line Line to measure + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Length of the input line + */ + function lineDistance(line: GeoJSON.Feature, units: string): number; + + /** + * Takes two points and returns a point midway between them. + * @param pt1 First point + * @param pt2 Second point + * @returns A point midway between pt1 and pt2 + */ + function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes a feature and returns a Point guaranteed to be on the surface of the feature. Given a Polygon, the point will be in the area of the polygon. + * Given a LineString, the point will be along the string. Given a Point, the point will the same as the input. + * @param input Any feature or set of features + * @returns A point on the surface of input + */ + function pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a bounding box and returns a new bounding box with a size expanded or contracted by a factor of X. + * @param bbox A bounding box + * @param factor The ratio of the new bbox to the input bbox + * @returns The resized bbox + */ + function size(bbox: Array, factor: number): Array; + + /** + * Takes a bounding box and calculates the minimum square bounding box that would contain the input. + * @param bbox A bounding box + * @returns A square surrounding bbox + */ + function square(bbox: Array): Array; + + ////////////////////////////////////////////////////// + // Transformation + ////////////////////////////////////////////////////// + + /** + * Takes a line and returns a curved version by applying a Bezier spline algorithm. + * The bezier spline implementation is by Leszek Rybicki. + * @param line Input LineString + * @param [resolution=10000] Time in milliseconds between points + * @param [sharpness=0.85] A measure of how curvy the path should be between splines + * @returns Curved line + */ + function bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; + + /** + * Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees. + * @param feature Input to be buffered + * @param distance Distance to draw the buffer + * @param units 'miles', 'kilometers', 'radians', or 'degrees' + * @returns Buffered features + */ + function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.FeatureCollection | GeoJSON.FeatureCollection | GeoJSON.Polygon | GeoJSON.MultiPolygon; + + /** + * Takes a set of points and returns a concave hull polygon. Internally, this implements a Monotone chain algorithm. + * @param points Input points + * @param maxEdge The size of an edge necessary for part of the hull to become concave (in miles) + * @param units Used for maxEdge distance (miles or kilometers) + * @returns A concave hull + */ + function concave(points: GeoJSON.FeatureCollection, maxEdge: number, units: string): GeoJSON.Feature; + + /** + * Takes a set of points and returns a convex hull polygon. Internally this uses the convex-hull module that implements a monotone chain hull. + * @param input Input points + * @returns A convex hull + */ + function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Finds the difference between two polygons by clipping the second polygon from the first. + * @param poly1 Input Polygon feaure + * @param poly2 Polygon feature to difference from poly1 + * @returns A Polygon feature showing the area of poly1 excluding the area of poly2 + */ + function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes two polygons and finds their intersection. + * If they share a border, returns the border; if they don't intersect, returns undefined. + * @param poly1 The first polygon + * @param poly2 The second polygon + * @returns If poly1 and poly2 overlap, returns a Polygon feature representing the area they overlap; + * if poly1 and poly2 do not overlap, returns undefined; + * if poly1 and poly2 share a border, a MultiLineString of the locations where their borders are shared + */ + function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature | typeof undefined; + + /** + * Takes a set of polygons and returns a single merged polygon feature. + * If the input polygon features are not contiguous, this function returns a MultiPolygon feature. + * @param fc Input polygons + * @returns Merged polygon or multipolygon + */ + function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a LineString or Polygon and returns a simplified version. + * Internally uses simplify-js to perform simplification. + * @param feature Feature to be simplified + * @param tolerance Simplification tolerance + * @param highQuality Whether or not to spend more time to create a higher-quality simplification with a different algorithm + * @returns A simplified feature + */ + function simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; + + /** + * Takes two polygons and returns a combined polygon. + * If the input polygons are not contiguous, this function returns a MultiPolygon feature. + * @param poly1 Input polygon + * @param poly2 Another input polygon + * @returns A combined Polygon or MultiPolygon feature + */ + function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Misc + ////////////////////////////////////////////////////// + + /** + * Combines a FeatureCollection of Point, LineString, or Polygon features into MultiPoint, MultiLineString, or MultiPolygon features. + * @param fc A FeatureCollection of any type + * @returns A FeatureCollection of corresponding type to input + */ + function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + /** + * Takes a feature or set of features and returns all positions as points. + * @param input Input features + * @returns Points representing the exploded input features + */ + function explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + /** + * Takes input features and flips all of their coordinates from [x, y] to [y, x]. + * @param input Input features + * @returns A feature or set of features of the same type as input with flipped coordinates + */ + function flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; + + /** + * Takes a polygon and returns points at all self-intersections. + * @param polygon Input polygon + * @returns Self-intersections + */ + function kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; + + /** + * Takes a line, a start Point, and a stop point and returns the line in between those points. + * @param point1 Starting point + * @param point2 Stopping point + * @param line Line to slice + * @returns Sliced line + */ + function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; + + /** + * Takes a Point and a LineString and calculates the closest Point on the LineString. + * @param line Line to snap to + * @param point Point to snap from + * @returns Closest point on the line to point + */ + function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Helper + ////////////////////////////////////////////////////// + + /** + * Takes one or more Features and creates a FeatureCollection. + * @param features Input features + * @returns A FeatureCollection of input features + */ + function featurecollection(features: Array>): GeoJSON.FeatureCollection; + + /** + * Creates a LineString based on a coordinate array. Properties can be added optionally. + * @param coordinates An array of Positions + * @param [properties] An Object of key-value pairs to add as properties + * @returns A LineString feature + */ + function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; + + /** + * Takes coordinates and properties (optional) and returns a new Point feature. + * @param coordinates Longitude, latitude position (each in decimal degrees) + * @param [properties] An Object of key-value pairs to add as properties + * @returns A Point feature + */ + function point(coordinates: Array, properties?: any): GeoJSON.Feature; + + /** + * Takes an array of LinearRings and optionally an Object with properties and returns a Polygon feature. + * @param rings An array of LinearRings + * @param [properties] An Object of key-value pairs to add as properties + * @returns A Polygon feature + */ + function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; + + ////////////////////////////////////////////////////// + // Data + ////////////////////////////////////////////////////// + + /** + * Takes a FeatureCollection and filters it by a given property and value. + * @param features Input features + * @param key The property on which to filter + * @param value The value of that property on which to filter + * @returns A filtered collection with only features that match input key and value + */ + function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection; + + /** + * Generates random GeoJSON data, including Points and Polygons, for testing and experimentation. + * @param [type='point'] Type of features desired: 'points' or 'polygons' + * @param [count=1] How many geometries should be generated. + * @param [options] Options relevant to the feature desired. Can include: + * - A bounding box inside of which geometries are placed. In the case of Point features, they are guaranteed to be within this bounds, while Polygon features have their centroid within the bounds. + * - The number of vertices added to polygon features. Default is 10; + * - The total number of decimal degrees longitude or latitude that a polygon can extent outwards to from its center. Default is 10. + * @returns Generated random features + */ + function random(type?: string, count?: number, options?: {bbox?: Array; num_vertices?: number; max_radial_length?: number;}): GeoJSON.FeatureCollection; + + /** + * Takes a FeatureCollection of any type, a property, and a value and returns a FeatureCollection with features matching that property-value pair removed. + * @param features Set of input features + * @param property The property to remove + * @param value The value to remove + * @returns The resulting FeatureCollection without features that match the property-value pair + */ + function remove(features: GeoJSON.FeatureCollection, property: string, value: string): GeoJSON.FeatureCollection; + + /** + * Takes a FeatureCollection and returns a FeatureCollection with given number of features at random. + * @param features Set of input features + * @param n Number of features to select + * @returns A FeatureCollection with n features + */ + function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Interpolation + ////////////////////////////////////////////////////// + + /** + * Takes a bounding box and a cell size in degrees and returns a FeatureCollection of flat-topped hexagons (Polygon features) aligned in an "odd-q" vertical grid as described in Hexagonal Grids. + * @param bbox Bounding box in [minX, minY, maxX, maxY] order + * @param cellWidth Width of cell in specified units + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns A hexagonal grid + */ + function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes points with z-values and an array of value breaks and generates isolines. + * @param points Input points + * @param z The property name in points from which z-values will be pulled + * @param resolution Resolution of the underlying grid + * @param breaks Where to draw contours + * @returns Isolines + */ + function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; + + /** + * Takes a triangular plane as a Polygon and a Point within that triangle and returns the z-value at that point. + * The Polygon needs to have properties a, b, and c that define the values at its three corners. + * @param interpolatedPoint The Point for which a z-value will be calculated + * @param triangle A Polygon feature with three vertices + * @returns The z-value for interpolatedPoint + */ + function planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; + + /** + * Takes a bounding box and a cell depth and returns a set of points in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth The distance across each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of points + */ + function pointGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of square polygons in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth Width of each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of polygons + */ + function squareGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and the name of a z-value property and creates a Triangulated Irregular Network, or a TIN for short, returned as a collection of Polygons. + * These are often used for developing elevation contour maps or stepped heat visualizations. + * This triangulates the points, as well as adds properties called a, b, and c representing the value of the given propertyName at each of the points that represent the corners of the triangle. + * @param points Input points + * @param [propertyName] Name of the property from which to pull z values This is optional: if not given, then there will be no extra data added to the derived triangles. + * @returns TIN output + */ + function tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of triangular polygons in a grid. + * @param extent Extent in [minX, minY, maxX, maxY] order + * @param cellWidth Width of each cell + * @param units Used in calculating cellWidth ('miles' or 'kilometers') + * @returns Grid of triangles + */ + function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Joins + ////////////////////////////////////////////////////// + + /** + * Takes a Point and a Polygon or MultiPolygon and determines if the point resides inside the polygon. + * The polygon can be convex or concave. The function accounts for holes. + * @param point Input point + * @param polygon Input polygon or multipolygon + * @returns true if the Point is inside the Polygon; false if the Point is not inside the Polygon + */ + function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean; + + /** + * Takes a set of points and a set of polygons and performs a spatial join. + * @param points Input points + * @param polygons Input polygons + * @param polyId Property in polygons to add to joined Point features + * @param containingPolyId Property in points in which to store joined property from polygons + * @returns Points with containingPolyId property containing values from polyId + */ + function tag(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection, polyId: string, containingPolyId: string): GeoJSON.FeatureCollection; + + /** + * Takes a set of points and a set of polygons and returns the points that fall within the polygons. + * @param points Input points + * @param polygons Input polygons + * @returns Points that land within at least one polygon + */ + function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // Classification + ////////////////////////////////////////////////////// + + /** + * Takes a set of features and returns an array of the Jenks Natural breaks for a given property. + * @param input Input features + * @param field The property in input on which to calculate Jenks natural breaks + * @param numberOfBreaks Number of classes in which to group the data + * @returns The break number for each class plus the minimum and maximum values + */ + function jenks(input: GeoJSON.FeatureCollection, field: string, numberOfBreaks: number): Array; + + /** + * Takes a reference point and a set of points and returns the point from the set closest to the reference. + * @param point The reference point + * @param against Input point set + * @returns The closest point in the set to the reference point + */ + function nearest(point: GeoJSON.Feature, against: GeoJSON.FeatureCollection): GeoJSON.Feature; + + /** + * Takes a FeatureCollection, a property name, and a set of percentiles and returns a quantile array. + * @param input Set of features + * @param field The property in input from which to retrieve quantile values + * @param percentiles An Array of percentiles on which to calculate quantile values + * @returns An array of the break values + */ + function quantile(input: GeoJSON.FeatureCollection, field: string, percentiles: Array): Array; + + /** + * Takes a FeatureCollection, an input field, an output field, and an array of translations and outputs an identical FeatureCollection with the output field property populated. + * @param input Set of input features + * @param inField The field to translate + * @param outField The field in which to store translated results + * @param translations An array of translations + * @returns A FeatureCollection with identical geometries to input but with outField populated. + */ + function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; +} + +declare module 'turf' { + export= turf; +} diff --git a/turf/turf-tests.ts b/turf/turf-tests.ts index e671035892..31462adc51 100644 --- a/turf/turf-tests.ts +++ b/turf/turf-tests.ts @@ -1,28 +1,114 @@ /// +import * as turf from '@turf/turf' +// AGGREGATION +import * as collect from '@turf/collect' +// MEASUREMENT +import * as along from '@turf/along' +import * as area from '@turf/area' +import * as bboxPolygon from '@turf/bbox-polygon' +import * as bearing from '@turf/bearing' +import * as center from '@turf/center' +import * as centroid from '@turf/centroid' +import * as destination from '@turf/destination' +import * as envelope from '@turf/envelope' +import * as lineDistance from '@turf/line-distance' +import * as midpoint from '@turf/midpoint' +import * as pointOnSurce from '@turf/point-on-surface' +import * as square from '@turf/square' +// TRANSFORMATION +import * as bezier from '@turf/bezier' +import * as buffer from '@turf/buffer' +import * as concave from '@turf/concave' +import * as convex from '@turf/convex' +import * as difference from '@turf/difference' +import * as intersect from '@turf/intersect' +import * as simplify from '@turf/simplify' +import * as union from '@turf/union' +// MISC +import * as combine from '@turf/combine' +import * as explode from '@turf/explode' +import * as flip from '@turf/flip' +import * as kinks from '@turf/kinks' +import * as lineSlice from '@turf/line-slice' +import * as pointOnLine from '@turf/point-on-line' +// HELPER +import { + featureCollection, + feature, + lineString, + multiLineString, + point, + multiPoint, + polygon, + multiPolygon, + geometryCollection } from '@turf/helpers' +// DATA +import * as random from '@turf/random' +import * as sample from '@turf/sample' +// INTERPOLATION +import * as isolines from '@turf/isolines' +import * as planepoint from '@turf/planepoint' +import * as tin from '@turf/tin' +// JOINS +import * as inside from '@turf/inside' +import * as tag from '@turf/tag' +import * as within from '@turf/within' +// GRIDS +import * as hexGrid from '@turf/hex-grid' +import * as pointGrid from '@turf/point-grid' +import * as squareGrid from '@turf/square-grid' +import * as triangleGrid from '@turf/triangle-grid' +// CLASSIFICATION +import * as nearest from '@turf/nearest' +// // META +// import * as propEach from '@turf/propEach' +// import * as coordEach from '@turf/coordEach' +// import * as coordReduce from '@turf/coordReduce' +// import * as featureEach from '@turf/featureEach' +// import * as getCoord from '@turf/getCoord' +// // ASSERTIONS +// import * as featureOf from '@turf/featureOf' +// import * as collectionOf from '@turf/collectionOf' +import * as bboxAssertions from '@turf/bbox' +// import * as circle from '@turf/circle' +// import * as geojsonType from '@turf/geojsonType' +// import * as propReduce from '@turf/propReduce' +// import * as coordAll from '@turf/coordAll' +// import * as tesselate from '@turf/tesselate' /////////////////////////////////////////// // Tests data initialisation /////////////////////////////////////////// - -var point1: GeoJSON.Feature = { +const bbox = [0, 0, 10, 10] +const properties = {pop: 3000} +const point1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { "type": "Point", "coordinates": [-75.343, 39.984] } -}; +} -var point2: GeoJSON.Feature = { +const point2: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-75.534, 39.123] - } -}; + "coordinates": [-75.401, 39.884] + } +} -var line: GeoJSON.Feature = { +const multiPoint1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiPoint", + "coordinates": [ [100.0, 0.0], [101.0, 1.0] ] + } +} + +const lineString1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -36,9 +122,21 @@ var line: GeoJSON.Feature = { [-77.019824, 38.892368] ] } -}; +} -var polygons: GeoJSON.FeatureCollection = { +const multiLineString1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiLineString", + "coordinates": [ + [ [100.0, 0.0], [101.0, 1.0] ], + [ [102.0, 2.0], [103.0, 3.0] ] + ] + } +} + +const polygons: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -69,9 +167,9 @@ var polygons: GeoJSON.FeatureCollection = { } } ] -}; +} -var polygon1: GeoJSON.Feature = { +const polygon1: GeoJSON.Feature = { "type": "Feature", "properties": {}, "geometry": { @@ -84,13 +182,11 @@ var polygon1: GeoJSON.Feature = { [105.818939,21.004714] ]] } -}; +} -var polygon2: GeoJSON.Feature = { +const polygon2: GeoJSON.Feature = { "type": "Feature", - "properties": { - "fill": "#00f" - }, + "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[ @@ -106,7 +202,20 @@ var polygon2: GeoJSON.Feature = { } } -var features: GeoJSON.FeatureCollection = { +const multiPolygon1: GeoJSON.Feature = { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "MultiPolygon", + "coordinates": [ + [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], + [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] + ] + } +} + +const points: GeoJSON.FeatureCollection = { "type": "FeatureCollection", "features": [ { @@ -114,96 +223,50 @@ var features: GeoJSON.FeatureCollection = { "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.522259, 35.4691] + "coordinates": [-63.601226, 44.642643] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.502754, 35.463455] + "coordinates": [-63.591442, 44.651436] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.508269, 35.463245] + "coordinates": [-63.580799, 44.648749] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.516809, 35.465779] + "coordinates": [-63.573589, 44.641788] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.515372, 35.467072] + "coordinates": [-63.587665, 44.64533] } }, { "type": "Feature", "properties": {}, "geometry": { "type": "Point", - "coordinates": [-97.509363, 35.463053] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.511123, 35.466601] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.518547, 35.469327] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.519706, 35.469659] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.517839, 35.466998] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.508678, 35.464942] - } - }, { - "type": "Feature", - "properties": {}, - "geometry": { - "type": "Point", - "coordinates": [-97.514914, 35.463453] + "coordinates": [-63.595218, 44.64765] } } ] -}; +} -var triangle: GeoJSON.Feature = { +const triangle: GeoJSON.Feature = { "type": "Feature", - "properties": { - "a": 11, - "b": 122, - "c": 44 - }, + "properties": {}, "geometry": { "type": "Polygon", "coordinates": [[ @@ -213,310 +276,231 @@ var triangle: GeoJSON.Feature = { [-75.1221, 39.57] ]] } -}; - -var aggregations = [ - { - aggregation: 'sum', - inField: 'population', - outField: 'pop_sum' - }, - { - aggregation: 'average', - inField: 'population', - outField: 'pop_avg' - }, - { - aggregation: 'median', - inField: 'population', - outField: 'pop_median' - }, - { - aggregation: 'min', - inField: 'population', - outField: 'pop_min' - }, - { - aggregation: 'max', - inField: 'population', - outField: 'pop_max' - }, - { - aggregation: 'deviation', - inField: 'population', - outField: 'pop_deviation' - }, - { - aggregation: 'variance', - inField: 'population', - outField: 'pop_variance' - }, - { - aggregation: 'count', - inField: '', - outField: 'point_count' - } -]; - -/////////////////////////////////////////// -// Tests Aggregation -/////////////////////////////////////////// - -// -- Test aggregate -- -var aggregated = turf.aggregate(polygons, points, aggregations); - -// -- Test average -- -var averaged = turf.average(polygons, points, 'population', 'pop_avg'); - -// -- Test count -- -var counted = turf.count(polygons, points, 'pt_count'); - -// -- Test deviation -- -var deviated = turf.deviation(polygons, points, 'population', 'pop_deviation'); - -// -- Test max -- -var aggregated = turf.max(polygons, points, 'population', 'max'); - -// -- Test median -- -var medians = turf.median(polygons, points, 'population', 'median'); - -// -- Test min -- -var minimums = turf.min(polygons, points, 'population', 'min'); - -// -- Test sum -- -var summed = turf.sum(polygons, points, 'population', 'sum'); - -// -- Test variance -- -var varianced = turf.variance(polygons, points, 'population', 'variance'); +} /////////////////////////////////////////// // Tests Measurement /////////////////////////////////////////// // -- Test along -- -var along = turf.along(line, 1, 'miles'); +turf.along(lineString1, 50) +turf.along(lineString1, 50, 'miles') // -- Test area -- -var area = turf.area(polygons); +turf.area(polygons) // -- Test bboxPolygon -- -var bbox = [0, 0, 10, 10]; -var poly = turf.bboxPolygon(bbox); +turf.bboxPolygon(bbox) // -- Test bearing -- -var bearing = turf.bearing(point1, point2); +turf.bearing(point1, point2) // -- Test center -var centerPt = turf.center(features); +turf.center(points) // -- Test centroid -- -var centroidPt = turf.centroid(polygon1); +turf.centroid(polygon1) // -- Test destination -- -var distance = 50; -var bearing = 90; -var units = 'miles'; -var destination = turf.destination(point1, distance, bearing, units); +turf.destination(point1, 50, 90) +turf.destination(point1, 50, 90, 'miles') // -- Test distance -- -var units = "miles"; -var distance = turf.distance(point1, point2, units); +turf.distance(point1, point2) +turf.distance(point1, point2, 'miles') // -- Test envelope -- -var enveloped = turf.envelope(polygons); - -// -- Test extent -- -var bbox = turf.extent(polygons); +turf.envelope(polygons) // -- Test lineDistance -var length = turf.lineDistance(line, 'miles'); +turf.lineDistance(lineString1) +turf.lineDistance(lineString1, 'miles') // -- Test midpoint -- -var midpointed = turf.midpoint(point1, point2); +turf.midpoint(point1, point2) // -- Test pointOnSurface -- -var pointOnPolygon = turf.pointOnSurface(polygon1); - -// -- Test size -- -var resized = turf.size(bbox, 2); +turf.pointOnSurface(polygon1) // -- Test square -- -var squared = turf.square(bbox); +turf.square(bbox) /////////////////////////////////////////// // Tests Transformation /////////////////////////////////////////// // -- Test bezier -- -var curved = turf.bezier(line); +turf.bezier(lineString1) // -- Test buffer -- -var buffered = turf.buffer(point1, 500, units); +turf.buffer(point1, 50) +turf.buffer(point1, 50, 'miles') // -- Test concave -- -var hull = turf.concave(features, 1, 'miles'); +turf.concave(points, 1, 'miles') // -- Test convex -- -var hull = turf.convex(features); +turf.convex(points) // -- Test difference -- -var differenced = turf.difference(polygon1, polygon2); +turf.difference(polygon1, polygon2) // -- Test intersect -- -var intersection = turf.intersect(polygon1, polygon2); - -// -- Test merge -- -var merged = turf.merge(polygons); +turf.intersect(polygon1, polygon2) +turf.intersect(point1, polygon1) +turf.intersect(point1, point1) +turf.intersect(polygon1, point1) +turf.intersect(polygon1, lineString1) +turf.intersect(lineString1, point1) // -- Test simplify -- -var tolerance = 0.01; -var simplified = turf.simplify(polygon1, tolerance, false); + +turf.simplify(polygon1, 0.01, false) // -- Test union -- -var union = turf.union(polygon1, polygon2); +turf.union(polygon1, polygon2) /////////////////////////////////////////// // Tests Misc /////////////////////////////////////////// // -- Test combine -- -var combined = turf.combine(features); +turf.combine(points) // -- Test explode -- -var points = turf.explode(polygon1); +turf.explode(polygon1) // -- Test flip -- -var flipedPoint = turf.flip(point1); +turf.flip(point1) // -- Test kinks -- -var kinks = turf.kinks(polygon1); +turf.kinks(polygon1) // -- Test lineSlice -- -var sliced = turf.lineSlice(point1, point2, line); +turf.lineSlice(point1, point2, lineString1) // -- Test pointOnLine -- -var snapped = turf.pointOnLine(line, point1); +turf.pointOnLine(lineString1, point1) /////////////////////////////////////////// // Tests Helper /////////////////////////////////////////// // -- Test featurecollection -- -var fc = turf.featurecollection([point1, point2]); +turf.featureCollection([point1, point2]) +turf.featureCollection([point1, polygon1]) +turf.featureCollection([polygon1, polygon2]) +turf.featureCollection([lineString1, polygon1]) +turf.featureCollection([lineString1, point1]) -// -- Test linestring -- -var linestring1 = turf.linestring([ - [-21.964416, 64.148203], - [-21.956176, 64.141316], - [-21.93901, 64.135924], - [-21.927337, 64.136673] -]); -var linestring2 = turf.linestring([ - [-21.929054, 64.127985], - [-21.912918, 64.134726], - [-21.916007, 64.141016], - [-21.930084, 64.14446] -], {name: 'line 1', distance: 145}); +// -- Test feature -- +turf.feature(point1) +turf.feature(polygon1) +turf.feature(lineString1) + +// -- Test lineString -- +turf.lineString(lineString1.geometry.coordinates) +turf.lineString(lineString1.geometry.coordinates, properties) + +// -- Test multiLineString -- +turf.multiLineString(multiLineString1.geometry.coordinates) // -- Test point -- -var pt1 = turf.point([-75.343, 39.984]); -var pt2 = turf.point([-75.343, 39.984], {name: 'point 1', distance: 145}); +turf.point(point1.geometry.coordinates) +turf.point(point1.geometry.coordinates, properties) + +// -- Test multiPoint -- +turf.multiPoint(multiPoint1.geometry.coordinates) // -- Test polygon -- -var polygon = turf.polygon([[ - [-2.275543, 53.464547], - [-2.275543, 53.489271], - [-2.215118, 53.489271], - [-2.215118, 53.464547], - [-2.275543, 53.464547] -]], { name: 'poly1', population: 400}); +turf.polygon(polygon1.geometry.coordinates, properties) + +// -- Test multiPolygon -- +turf.multiPolygon(multiPolygon1.geometry.coordinates, properties) + +// -- Test geometryCollection -- +turf.geometryCollection([point1.geometry, lineString1.geometry]); /////////////////////////////////////////// // Tests Data /////////////////////////////////////////// -// -- Test filter -- -var key = "species"; -var value = "oak"; -var filtered = turf.filter(features, key, value); - // -- Test random -- -var randomPoints = turf.random('points', 100, { - bbox: [-70, 40, -60, 60] -}); - -var randomPoints = turf.random('points', 100, { - bbox: [-70, 40, -60, 60], - num_vertices: 2, +turf.random('points', 100) +turf.random('points', 100, { bbox }) +turf.random('polygons', 100, { + bbox, + num_vertices: 10, max_radial_length: 10 -}); - -// -- Test remove -- -var filtered = turf.remove(points, 'marker-color', '#00f'); +}) // -- Test sample -- -var randomPoints = turf.random('points', 1000); -var sample = turf.sample(points, 10); +turf.random('points', 100) +turf.sample(points, 10) /////////////////////////////////////////// // Tests Interpolation /////////////////////////////////////////// // -- Test hexGrid -- -var cellWidth = 50; -var hexgrid = turf.hexGrid(bbox, cellWidth, units); - -// -- Test isolines -- -var breaks = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; -var isolined = turf.isolines(points, 'z', 15, breaks); - -// -- Test planepoint -- -var zValue = turf.planepoint(point1, triangle); +turf.hexGrid(bbox, 50) +turf.hexGrid(bbox, 50, 'miles') // -- Test pointGrid -- -var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; -var cellWidth = 3; -var grid = turf.pointGrid(extent, cellWidth, units); +turf.pointGrid(bbox, 50) +turf.pointGrid(bbox, 50, 'miles') // -- Test squareGrid -- -var squareGrid = turf.squareGrid(extent, cellWidth, units); - -// -- Test tin -- -var tin = turf.tin(points, 'z'); +turf.squareGrid(bbox, 50) +turf.squareGrid(bbox, 50, 'miles') // -- Test triangleGrid -- -var triangleGrid = turf.triangleGrid(extent, cellWidth, units); +turf.triangleGrid(bbox, 50) +turf.triangleGrid(bbox, 50, 'miles') + +/////////////////////////////////////////// +// Tests Interpolation +/////////////////////////////////////////// + +// -- Test isolines -- +turf.isolines(points, 'z', 15, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) + +// -- Test planepoint -- +turf.planepoint(point1, triangle) + +// -- Test tin -- +turf.tin(points, 'z') /////////////////////////////////////////// // Tests Joins /////////////////////////////////////////// // -- Test inside -- -var isInside1 = turf.inside(point1, polygon); +turf.inside(point1, polygon1) // -- Test tag -- -var tagged = turf.tag(points, triangleGrid, 'fill', 'marker-color'); +turf.tag(points, polygons, 'pop', 'population') // -- Test within -- -var ptsWithin = turf.within(points, polygons); +turf.within(points, polygons) /////////////////////////////////////////// // Tests Classification /////////////////////////////////////////// -// -- Test jenks -- -var breaks = turf.jenks(points, 'population', 3); - // -- Test nearest -- -var nearest = turf.nearest(point1, points); +turf.nearest(point1, points) -// -- Test quantile -- -var breaks = turf.quantile(points, 'population', [25, 50, 75, 99]); +/////////////////////////////////////////// +// Tests Aggregation +/////////////////////////////////////////// +turf.collect(polygons, points, 'population', 'values') -// -- Test reclass -- -var translations = [ - [0, 200, "small"], - [200, 400, "medium"], - [400, 600, "large"] -]; -var reclassed = turf.reclass(points, 'population', 'size', translations); +/////////////////////////////////////////// +// Tests Assertions +/////////////////////////////////////////// +turf.bbox(polygon1) +turf.bbox(point1) +turf.bbox(lineString1) +turf.bbox(multiLineString1) +turf.bbox(multiPolygon1) \ No newline at end of file diff --git a/turf/turf.d.ts b/turf/turf.d.ts index 647df93398..e90cf69276 100644 --- a/turf/turf.d.ts +++ b/turf/turf.d.ts @@ -1,103 +1,130 @@ -// Type definitions for Turf 2.0 +// Type definitions for Turf 3.5.2 // Project: http://turfjs.org/ -// Definitions by: Guillaume Croteau +// Definitions by: Guillaume Croteau , Denis Carriere // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/** +#### TODO: + +Update all methods with newest JSDocs & tests based on the latest TurfJS library. + +AGGREGATION +- [x] collect +MEASUREMENT +- [ ] along +- [ ] area +- [ ] bboxPolygon +- [ ] bearing +- [ ] center +- [ ] centroid +- [ ] destination +- [ ] distance +- [ ] envelope +- [ ] lineDistance +- [ ] midpoint +- [ ] pointOnSurface +- [ ] square +TRANSFORMATION +- [ ] bezier +- [ ] buffer +- [ ] concave +- [ ] convex +- [ ] difference +- [ ] intersect +- [ ] simplify +- [ ] union +MISC +- [ ] combine +- [ ] explode +- [ ] flip +- [ ] kinks +- [ ] lineSlice +- [ ] pointOnLine +HELPER +- [x] featureCollection +- [x] feature +- [x] lineString +- [x] multiLineString +- [x] point +- [x] multiPoint +- [x] polygon +- [x] multiPolygon +- [x] geometryCollection +DATA +- [x] random +- [x] sample +INTERPOLATION +- [ ] isolines +- [ ] planepoint +- [ ] tin +JOINS +- [x] inside +- [x] tag +- [ ] within +GRIDS +- [x] hexGrid +- [x] pointGrid +- [x] squareGrid +- [x] triangleGrid +CLASSIFICATION +- [ ] nearest +META +- [ ] propEach +- [ ] coordEach +- [ ] coordReduce +- [ ] featureEach +- [ ] getCoord +ASSERTIONS +- [ ] featureOf +- [ ] collectionOf +- [x] bbox +- [ ] circle +- [ ] geojsonType +- [ ] propReduce +- [ ] coordAll +- [ ] tesselate + */ + +declare const turf: turf.TurfStatic; +declare const TemplateUnits: 'miles' | 'nauticalmiles' | 'degrees' | 'radians' | 'inches' | 'yards' | 'meters' | 'metres' | 'kilometers' | 'kilometres' +declare const TemplateType: 'point'| 'points' | 'polygon' | 'polygons' declare module turf { + interface TurfStatic { ////////////////////////////////////////////////////// // Aggregation ////////////////////////////////////////////////////// /** - * Calculates a series of aggregations for a set of points within a set of polygons. - * Sum, average, count, min, max, and deviation are supported. - * @param polygons Polygons with values on which to aggregate - * @param points Points to be aggregated - * @param aggregations An array of aggregation objects - * @returns Polygons with properties listed based on outField values in aggregations - */ - function aggregate(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, aggregations: Array<{aggregation: string, inField: string, outField: string}>): GeoJSON.FeatureCollection; - - /** - * Calculates the average value of a field for a set of points within a set of polygons. - * @param polygons Polygons with values on which to average - * @param points Points from which to calculate the average - * @param field The field in the points features from which to pull values to average - * @param outField The field in polygons to put results of the averages - * @returns Polygons with the value of outField set to the calculated averages - */ - function average(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, field: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Takes a set of points and a set of polygons and calculates the number of points that fall within the set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param countField A field to append to the attributes of the Polygon features representing Point counts - * @returns Polygons with countField appended - */ - function count(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, countField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the standard deviation value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in points from which to aggregate - * @param outField The field to append to polygons representing deviation - * @returns Polygons with appended field representing deviation - */ - function deviation(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the maximum value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function max(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the median value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function median(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the minimum value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField values - */ - function min(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the sum of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField - */ - function sum(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; - - /** - * Calculates the variance value of a field for a set of points within a set of polygons. - * @param polygons Input polygons - * @param points Input points - * @param inField The field in input data to analyze - * @param outField The field in which to store results - * @returns Polygons with properties listed as outField - */ - function variance(polygons: GeoJSON.FeatureCollection, points: GeoJSON.FeatureCollection, inField: string, outField: string): GeoJSON.FeatureCollection; + * Merges a specified property from a FeatureCollection of points into a FeatureCollection of polygons. Given an `inProperty` on points and an `outProperty` for polygons, this finds every point that lies within each polygon, collects the `inProperty` values from those points, and adds them as an array to `outProperty` on the polygon. + * + * @name [collect](http://turfjs.org/docs/#collect) + * @param {FeatureCollection} polygons polygons with values on which to aggregate + * @param {FeatureCollection} points points to be aggregated + * @param {string} inProperty property to be nested from + * @param {string} outProperty property to be nested into + * @return {FeatureCollection} polygons with properties listed based on `outField` + * @example + * var poly1 = polygon([[[0,0],[10,0],[10,10],[0,10],[0,0]]]) + * var poly2 = polygon([[[10,0],[20,10],[20,20],[20,0],[10,0]]]) + * var polyFC = featurecollection([poly1, poly2]) + * var pt1 = point([5,5], {population: 200}) + * var pt2 = point([1,3], {population: 600}) + * var pt3 = point([14,2], {population: 100}) + * var pt4 = point([13,1], {population: 200}) + * var pt5 = point([19,7], {population: 300}) + * var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5]) + * var aggregated = aggregate(polyFC, ptFC, 'population', 'values') + * + * aggregated.features[0].properties.values // => [200, 600]) + */ + collect( + polygons: GeoJSON.FeatureCollection, + points: GeoJSON.FeatureCollection, + inProperty: string, + outProperty: string + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Measurement @@ -110,21 +137,49 @@ declare module turf { * @param [units=miles] 'miles', 'kilometers', 'radians' or 'degrees' * @returns Point along the line */ - function along(line: GeoJSON.Feature, distance: number, units?: string): GeoJSON.Feature; + along( + line: GeoJSON.Feature, + distance: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Takes one or more features and returns their area in square meters. * @param input Input features * @returns Area in square meters */ - function area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + area(input: GeoJSON.Feature | GeoJSON.FeatureCollection): number; + + /** + * Takes a set of features, calculates the bbox of all input features, and returns a bounding box. + * + * @name bbox + * @param {(Feature|FeatureCollection)} geojson input features + * @return {Array} bbox extent in [minX, minY, maxX, maxY] order + * @example + * var pt1 = point([114.175329, 22.2524]) + * var pt2 = point([114.170007, 22.267969]) + * var pt3 = point([114.200649, 22.274641]) + * var pt4 = point([114.200649, 22.274641]) + * var pt5 = point([114.186744, 22.265745]) + * var features = featureCollection([pt1, pt2, pt3, pt4, pt5]) + * + * var bbox = turf.bbox(features); + * + * var bboxPolygon = turf.bboxPolygon(bbox); + * + * //=bbox + * + * //=bboxPolygon + */ + bbox(bbox: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; /** * Takes a bbox and returns an equivalent polygon. * @param bbox An Array of bounding box coordinates in the form: [xLow, yLow, xHigh, yHigh] * @returns A Polygon representation of the bounding box */ - function bboxPolygon(bbox: Array): GeoJSON.Feature; + bboxPolygon(bbox: Array): GeoJSON.Feature; /** * Takes two points and finds the geographic bearing between them. @@ -132,14 +187,14 @@ declare module turf { * @param end Ending point * @returns Bearing in decimal degrees */ - function bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; + bearing(start: GeoJSON.Feature, end: GeoJSON.Feature): number; /** * Takes a FeatureCollection and returns the absolute center point of all features. * @param features Input features * @returns A Point feature at the absolute center point of all input features */ - function center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; + center(features: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes one or more features and calculates the centroid using the arithmetic mean of all vertices. @@ -147,10 +202,10 @@ declare module turf { * @param features Input features * @returns The centroid of the input features */ - function centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; + centroid(features: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; /** - * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. + * Takes a Point and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers and bearing in degrees. * This uses the Haversine formula to account for global curvature. * @param start Starting point * @param distance Distance from the starting point @@ -158,7 +213,12 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Destination point */ - function destination(start: GeoJSON.Feature, distance: number, bearing: number, units: string): GeoJSON.Feature; + destination( + start: GeoJSON.Feature, + distance: number, + bearing: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Calculates the distance between two points in degress, radians, miles, or kilometers. @@ -168,21 +228,18 @@ declare module turf { * @param [units=kilometers] 'miles', 'kilometers', 'radians', or 'degrees' * @returns Distance between the two points */ - function distance(from: GeoJSON.Feature, to: GeoJSON.Feature, units?: string): number; + distance( + from: GeoJSON.Feature, + to: GeoJSON.Feature, + units?: typeof TemplateUnits + ): number; /** * Takes any number of features and returns a rectangular Polygon that encompasses all vertices. * @param fc Input features * @returns A rectangular Polygon feature that encompasses all vertices */ - function envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a set of features, calculates the extent of all input features, and returns a bounding box. - * @param input Input features - * @returns The bounding box of input given as an array in WSEN order (west, south, east, north) - */ - function extent(input: GeoJSON.Feature | GeoJSON.FeatureCollection): Array; + envelope(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes a line and measures its length in the specified units. @@ -190,7 +247,10 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Length of the input line */ - function lineDistance(line: GeoJSON.Feature, units: string): number; + lineDistance( + line: GeoJSON.Feature, + units?: typeof TemplateUnits + ): number; /** * Takes two points and returns a point midway between them. @@ -198,7 +258,7 @@ declare module turf { * @param pt2 Second point * @returns A point midway between pt1 and pt2 */ - function midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; + midpoint(pt1: GeoJSON.Feature, pt2: GeoJSON.Feature): GeoJSON.Feature; /** * Takes a feature and returns a Point guaranteed to be on the surface of the feature. Given a Polygon, the point will be in the area of the polygon. @@ -206,22 +266,14 @@ declare module turf { * @param input Any feature or set of features * @returns A point on the surface of input */ - function pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a bounding box and returns a new bounding box with a size expanded or contracted by a factor of X. - * @param bbox A bounding box - * @param factor The ratio of the new bbox to the input bbox - * @returns The resized bbox - */ - function size(bbox: Array, factor: number): Array; + pointOnSurface(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature; /** * Takes a bounding box and calculates the minimum square bounding box that would contain the input. * @param bbox A bounding box * @returns A square surrounding bbox */ - function square(bbox: Array): Array; + square(bbox: Array): Array; ////////////////////////////////////////////////////// // Transformation @@ -235,7 +287,7 @@ declare module turf { * @param [sharpness=0.85] A measure of how curvy the path should be between splines * @returns Curved line */ - function bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; + bezier(line: GeoJSON.Feature, resolution?: number, sharpness?: number): GeoJSON.Feature; /** * Calculates a buffer for input features for a given radius. Units supported are miles, kilometers, and degrees. @@ -244,7 +296,14 @@ declare module turf { * @param units 'miles', 'kilometers', 'radians', or 'degrees' * @returns Buffered features */ - function buffer(feature: GeoJSON.Feature | GeoJSON.FeatureCollection, distance: number, units: string): GeoJSON.FeatureCollection | GeoJSON.FeatureCollection | GeoJSON.Polygon | GeoJSON.MultiPolygon; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.Feature, distance: number, units?: typeof TemplateUnits): GeoJSON.Feature; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; + buffer(feature: GeoJSON.FeatureCollection, distance: number, units?: typeof TemplateUnits): GeoJSON.FeatureCollection; /** * Takes a set of points and returns a concave hull polygon. Internally, this implements a Monotone chain algorithm. @@ -253,14 +312,20 @@ declare module turf { * @param units Used for maxEdge distance (miles or kilometers) * @returns A concave hull */ - function concave(points: GeoJSON.FeatureCollection, maxEdge: number, units: string): GeoJSON.Feature; + concave( + points: GeoJSON.FeatureCollection, + maxEdge: number, + units?: typeof TemplateUnits + ): GeoJSON.Feature; /** * Takes a set of points and returns a convex hull polygon. Internally this uses the convex-hull module that implements a monotone chain hull. * @param input Input points * @returns A convex hull */ - function convex(input: GeoJSON.FeatureCollection): GeoJSON.Feature; + convex( + input: GeoJSON.FeatureCollection + ): GeoJSON.Feature; /** * Finds the difference between two polygons by clipping the second polygon from the first. @@ -268,26 +333,54 @@ declare module turf { * @param poly2 Polygon feature to difference from poly1 * @returns A Polygon feature showing the area of poly1 excluding the area of poly2 */ - function difference(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + difference( + poly1: GeoJSON.Feature, + poly2: GeoJSON.Feature + ): GeoJSON.Feature; /** - * Takes two polygons and finds their intersection. - * If they share a border, returns the border; if they don't intersect, returns undefined. - * @param poly1 The first polygon - * @param poly2 The second polygon - * @returns If poly1 and poly2 overlap, returns a Polygon feature representing the area they overlap; - * if poly1 and poly2 do not overlap, returns undefined; - * if poly1 and poly2 share a border, a MultiLineString of the locations where their borders are shared - */ - function intersect(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature | typeof undefined; - - /** - * Takes a set of polygons and returns a single merged polygon feature. - * If the input polygon features are not contiguous, this function returns a MultiPolygon feature. - * @param fc Input polygons - * @returns Merged polygon or multipolygon - */ - function merge(fc: GeoJSON.FeatureCollection): GeoJSON.Feature; + * Takes two Features and finds their intersection. + * If they share a border, returns the border if they don't intersect, returns undefined. + * + * @name [intersect](http://turfjs.org/docs/#intersect) + * @param {Feature} poly1 + * @param {Feature} poly2 + * @returns {Feature|undefined} A feature representing the point(s) they share (in case of a {Point} or {MultiPoint}), the borders they share (in case of a {LineString} or a {MultiLineString}), the area they share (in case of {Polygon} or {MultiPolygon}). If they do not share any point, returns `undefined`. + * @example + * var poly1 = polygon([[ + * [-122.801742, 45.48565], + * [-122.801742, 45.60491], + * [-122.584762, 45.60491], + * [-122.584762, 45.48565], + * [-122.801742, 45.48565] + * ]]); + * + * var poly2 = polygon([[ + * [-122.520217, 45.535693], + * [-122.64038, 45.553967], + * [-122.720031, 45.526554], + * [-122.669906, 45.507309], + * [-122.723464, 45.446643], + * [-122.532577, 45.408574], + * [-122.487258, 45.477466], + * [-122.520217, 45.535693] + * ]]); + * var polygons = featureCollection([poly1, poly2]); + * + * var intersection = turf.intersect(poly1, poly2); + * + * //=polygons + * + * //=intersection + */ + intersect( + feature1: GeoJSON.Feature, + feature2: GeoJSON.Feature + ): GeoJSON.Feature; + intersect( + feature1: GeoJSON.Feature, + feature2: GeoJSON.Feature + ): GeoJSON.Feature; /** * Takes a LineString or Polygon and returns a simplified version. @@ -297,16 +390,16 @@ declare module turf { * @param highQuality Whether or not to spend more time to create a higher-quality simplification with a different algorithm * @returns A simplified feature */ - function simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; + simplify(feature: GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection, tolerance: number, highQuality: boolean): GeoJSON.Feature | GeoJSON.FeatureCollection | GeoJSON.GeometryCollection; /** * Takes two polygons and returns a combined polygon. - * If the input polygons are not contiguous, this function returns a MultiPolygon feature. + * If the input polygons are not contiguous, this function returns a MultiPolygon feature.; * @param poly1 Input polygon * @param poly2 Another input polygon * @returns A combined Polygon or MultiPolygon feature */ - function union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; + union(poly1: GeoJSON.Feature, poly2: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Misc @@ -317,28 +410,28 @@ declare module turf { * @param fc A FeatureCollection of any type * @returns A FeatureCollection of corresponding type to input */ - function combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + combine(fc: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; /** * Takes a feature or set of features and returns all positions as points. * @param input Input features * @returns Points representing the exploded input features */ - function explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + explode(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; /** * Takes input features and flips all of their coordinates from [x, y] to [y, x]. * @param input Input features * @returns A feature or set of features of the same type as input with flipped coordinates */ - function flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; + flip(input: GeoJSON.Feature | GeoJSON.FeatureCollection): GeoJSON.Feature | GeoJSON.FeatureCollection; /** * Takes a polygon and returns points at all self-intersections. * @param polygon Input polygon * @returns Self-intersections */ - function kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; + kinks(polygon: GeoJSON.Feature): GeoJSON.FeatureCollection; /** * Takes a line, a start Point, and a stop point and returns the line in between those points. @@ -347,7 +440,7 @@ declare module turf { * @param line Line to slice * @returns Sliced line */ - function lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; + lineSlice(point1: GeoJSON.Feature, point2: GeoJSON.Feature, line: GeoJSON.Feature): GeoJSON.Feature; /** * Takes a Point and a LineString and calculates the closest Point on the LineString. @@ -355,98 +448,348 @@ declare module turf { * @param point Point to snap from * @returns Closest point on the line to point */ - function pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; + pointOnLine(line: GeoJSON.Feature, point: GeoJSON.Feature): GeoJSON.Feature; ////////////////////////////////////////////////////// // Helper ////////////////////////////////////////////////////// /** - * Takes one or more Features and creates a FeatureCollection. - * @param features Input features - * @returns A FeatureCollection of input features - */ - function featurecollection(features: Array>): GeoJSON.FeatureCollection; + * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}. + * + * @name [featureCollection](http://turfjs.org/docs/#featurecollection) + * @param {Feature[]} features input features + * @returns {FeatureCollection} a FeatureCollection of input features + * @example + * var features = [ + * turf.point([-75.343, 39.984], {name: 'Location A'}), + * turf.point([-75.833, 39.284], {name: 'Location B'}), + * turf.point([-75.534, 39.123], {name: 'Location C'}) + * ] + * + * var fc = turf.featureCollection(features) + * + * //=fc + */ + featureCollection(features: Array>): GeoJSON.FeatureCollection; /** - * Creates a LineString based on a coordinate array. Properties can be added optionally. - * @param coordinates An array of Positions - * @param [properties] An Object of key-value pairs to add as properties - * @returns A LineString feature - */ - function linestring(coordinates: Array>, properties?: any): GeoJSON.Feature; + * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}. + * + * @name [feature](http://turfjs.org/docs/#feature) + * @param {Geometry} geometry input geometry + * @param {Object} properties properties + * @returns {FeatureCollection} a FeatureCollection of input features + * @example + * var geometry = { + * "type": "Point", + * "coordinates": [ + * 67.5, + * 32.84267363195431 + * ] + * } + * + * var feature = turf.feature(geometry) + * + * //=feature + */ + feature(geometry:GeoJSON.Feature, properties?: any): GeoJSON.Feature; /** - * Takes coordinates and properties (optional) and returns a new Point feature. - * @param coordinates Longitude, latitude position (each in decimal degrees) - * @param [properties] An Object of key-value pairs to add as properties - * @returns A Point feature - */ - function point(coordinates: Array, properties?: any): GeoJSON.Feature; + * Creates a {@link LineString} based on a coordinate array. Properties can be added optionally. + * + * @name [lineString](http://turfjs.org/docs/#linestring) + * @param {Array>} coordinates an array of Positions + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a LineString feature + * @throws {Error} if no coordinates are passed + * @example + * var linestring1 = turf.lineString([ + * [-21.964416, 64.148203], + * [-21.956176, 64.141316], + * [-21.93901, 64.135924], + * [-21.927337, 64.136673] + * ]) + * var linestring2 = turf.lineString([ + * [-21.929054, 64.127985], + * [-21.912918, 64.134726], + * [-21.916007, 64.141016], + * [-21.930084, 64.14446] + * ], {name: 'line 1', distance: 145}) + * + * //=linestring1 + * + * //=linestring2 + */ + lineString(coordinates: Array>, properties?: any): GeoJSON.Feature; /** - * Takes an array of LinearRings and optionally an Object with properties and returns a Polygon feature. - * @param rings An array of LinearRings - * @param [properties] An Object of key-value pairs to add as properties - * @returns A Polygon feature - */ - function polygon(rings: Array>>, properties?: any): GeoJSON.Feature; + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiLineString](http://turfjs.org/docs/#multilinestring) + * @param {Array>>} coordinates an array of LineStrings + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a MultiLineString feature + * @throws {Error} if no coordinates are passed + * @example + * var multiLine = turf.multiLineString([[[0,0],[10,10]]]) + * + * //=multiLine + * + */ + multiLineString(coordinates: Array>>, properties?: any): GeoJSON.Feature; + + /** + * Takes coordinates and properties (optional) and returns a new {@link Point} feature. + * + * @name [point](http://turfjs.org/docs/#point) + * @param {Array} coordinates longitude, latitude position (each in decimal degrees) + * @param {Object=} properties an Object that is used as the {@link Feature}'s + * properties + * @returns {Feature} a Point feature + * @example + * var pt1 = turf.point([-75.343, 39.984]); + * + * //=pt1 + */ + point(coordinates: Array, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiPoint](http://turfjs.org/docs/#multipoint) + * @param {Array>} coordinates an array of Positions + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a MultiPoint feature + * @throws {Error} if no coordinates are passed + * @example + * var multiPt = turf.multiPoint([[0,0],[10,10]]) + * + * //=multiPt + * + */ + multiPoint(coordinates: Array>, properties?: any): GeoJSON.Feature; + + /** + * Takes an array of LinearRings and optionally an {@link Object} with properties and returns a {@link Polygon} feature. + * + * @name [polygon](http://turfjs.org/docs/#polygon) + * @param {Array>>} coordinates an array of LinearRings + * @param {Object=} properties a properties object + * @returns {Feature} a Polygon feature + * @throws {Error} throw an error if a LinearRing of the polygon has too few positions + * or if a LinearRing of the Polygon does not have matching Positions at the + * beginning & end. + * @example + * var polygon = turf.polygon([[ + * [-2.275543, 53.464547], + * [-2.275543, 53.489271], + * [-2.215118, 53.489271], + * [-2.215118, 53.464547], + * [-2.275543, 53.464547] + * ]], { name: 'poly1', population: 400}); + * + * //=polygon + */ + polygon(coordinates: Array>>, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on a coordinate array. Properties can be added optionally. + * + * @name [multiPolygon](http://turfjs.org/docs/#multipolygon) + * @param {Array>>>} coordinates an array of Polygons + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a multipolygon feature + * @throws {Error} if no coordinates are passed + * @example + * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]); + * + * //=multiPoly + * + */ + multiPolygon(coordinates: Array>>>, properties?: any): GeoJSON.Feature; + + /** + * Creates a {@link Feature} based on acoordinate array. Properties can be added optionally. + * + * @name [geometryCollection](http://turfjs.org/docs/#geometrycollection) + * @param {Array<{Geometry}>} geometries an array of GeoJSON Geometries + * @param {Object=} properties an Object of key-value pairs to add as properties + * @returns {Feature} a GeoJSON GeometryCollection Feature + * @example + * var point = { + * "type": "Point", + * "coordinates": [100, 0] + * }; + * var line = { + * "type": "LineString", + * "coordinates": [ [101, 0], [102, 1] ] + * }; + * var collection = turf.geometryCollection([point, line]); + * + * //=collection + */ + geometryCollection(geometries: Array, properties?: any): GeoJSON.GeometryCollection; ////////////////////////////////////////////////////// // Data ////////////////////////////////////////////////////// /** - * Takes a FeatureCollection and filters it by a given property and value. - * @param features Input features - * @param key The property on which to filter - * @param value The value of that property on which to filter - * @returns A filtered collection with only features that match input key and value - */ - function filter(features: GeoJSON.FeatureCollection, key: string, value: string): GeoJSON.FeatureCollection; + * Generates random {@link GeoJSON} data, including {@link Point|Points} and {@link Polygon|Polygons}, for testing and experimentation. + * + * @name [random](http://turfjs.org/docs/#random) + * @param {String} [type='point'] type of features desired: 'points' or 'polygons' + * @param {Number} [count=1] how many geometries should be generated. + * @param {Object} options options relevant to the feature desired. Can include: + * @param {Array} options.bbox a bounding box inside of which geometries + * are placed. In the case of {@link Point} features, they are guaranteed to be within this bounds, + * while {@link Polygon} features have their centroid within the bounds. + * @param {Number} [options.num_vertices=10] options.vertices the number of vertices added + * to polygon features. + * @param {Number} [options.max_radial_length=10] the total number of decimal + * degrees longitude or latitude that a polygon can extent outwards to + * from its center. + * @return {FeatureCollection} generated random features + * @example + * var points = turf.random('points', 100, { + * bbox: [-70, 40, -60, 60] + * }) + * + * //=points + * + * var polygons = turf.random('polygons', 4, { + * bbox: [-70, 40, -60, 60] + * }) + * + * //=polygons + */ + random(type?: typeof TemplateType, count?: number, options?: { + bbox?: Array + num_vertices?: number + max_radial_length?: number + }): GeoJSON.FeatureCollection; /** - * Generates random GeoJSON data, including Points and Polygons, for testing and experimentation. - * @param [type='point'] Type of features desired: 'points' or 'polygons' - * @param [count=1] How many geometries should be generated. - * @param [options] Options relevant to the feature desired. Can include: - * - A bounding box inside of which geometries are placed. In the case of Point features, they are guaranteed to be within this bounds, while Polygon features have their centroid within the bounds. - * - The number of vertices added to polygon features. Default is 10; - * - The total number of decimal degrees longitude or latitude that a polygon can extent outwards to from its center. Default is 10. - * @returns Generated random features - */ - function random(type?: string, count?: number, options?: {bbox?: Array; num_vertices?: number; max_radial_length?: number;}): GeoJSON.FeatureCollection; + * Takes a {@link FeatureCollection} and returns a FeatureCollection with given number of {@link Feature|features} at random. + * + * @name [sample](http://turfjs.org/docs/#sample) + * @param {FeatureCollection} featurecollection set of input features + * @param {number} num number of features to select + * @return {FeatureCollection} a FeatureCollection with `n` features + * @example + * var points = turf.random('points', 1000); + * + * //=points + * + * var sample = turf.sample(points, 10); + * + * //=sample + */ + sample(featurecollection: GeoJSON.FeatureCollection, num: number): GeoJSON.FeatureCollection; + + ////////////////////////////////////////////////////// + // GRIDS + ////////////////////////////////////////////////////// /** - * Takes a FeatureCollection of any type, a property, and a value and returns a FeatureCollection with features matching that property-value pair removed. - * @param features Set of input features - * @param property The property to remove - * @param value The value to remove - * @returns The resulting FeatureCollection without features that match the property-value pair - */ - function remove(features: GeoJSON.FeatureCollection, property: string, value: string): GeoJSON.FeatureCollection; + * Takes a bounding box and a cell size in degrees and returns a {@link FeatureCollection} of flat-topped hexagons ({@link Polygon} features) aligned in an "odd-q" vertical grid as described in [Hexagonal Grids](http://www.redblobgames.com/grids/hexagons/). + * + * @name [hexGrid](http://turfjs.org/docs/#hexgrid) + * @param {Array} bbox bounding box in [minX, minY, maxX, maxY] order + * @param {number} cellSize dimension of cell in specified units + * @param {string} units used in calculating cellSize ('miles' or 'kilometers') + * @param {boolean} triangles whether to return as triangles instead of hexagons + * @return {FeatureCollection} a hexagonal grid + * @example + * var bbox = [-96,31,-84,40]; + * var cellSize = 50; + * var units = 'miles'; + * + * var hexgrid = turf.hexGrid(bbox, cellSize, units); + * + * //=hexgrid + */ + hexGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits, + triangles?: boolean + ): GeoJSON.FeatureCollection; /** - * Takes a FeatureCollection and returns a FeatureCollection with given number of features at random. - * @param features Set of input features - * @param n Number of features to select - * @returns A FeatureCollection with n features - */ - function sample(features: GeoJSON.FeatureCollection, n: number): GeoJSON.FeatureCollection; + * Takes a bounding box and a cell depth and returns a set of {@link Point|points} in a grid. + * + * @name [pointGrid](http://turfjs.org/docs/#pointgrid) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize the distance across each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid of points + * @example + * var extent = [-70.823364, -33.553984, -70.473175, -33.302986]; + * var cellSize = 3; + * var units = 'miles'; + * + * var grid = turf.pointGrid(extent, cellSize, units); + * + * //=grid + */ + pointGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of square {@link Polygon|polygons} in a grid. + * + * @name [squareGrid](http://turfjs.org/docs/#squaregrid) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize width of each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid a grid of polygons + * @example + * var bbox = [-96,31,-84,40] + * var cellSize = 10 + * var units = 'miles' + * + * var squareGrid = turf.squareGrid(bbox, cellSize, units) + * + * //=squareGrid + */ + squareGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; + + /** + * Takes a bounding box and a cell depth and returns a set of triangular {@link Polygon|polygons} in a grid. + * + * @name [triangleGrid](http://turfjs.org/docs/#trianglegrid)) + * @param {Array} bbox extent in [minX, minY, maxX, maxY] order + * @param {number} cellSize dimension of each cell + * @param {string} [units=kilometers] used in calculating cellSize, can be degrees, radians, miles, or kilometers + * @return {FeatureCollection} grid of polygons + * @example + * var bbox = [-96,31,-84,40] + * var cellSize = 10; + * var units = 'miles'; + * + * var triangleGrid = turf.triangleGrid(extent, cellSize, units); + * + * //=triangleGrid + */ + triangleGrid( + bbox: Array, + cellSize: number, + units?: typeof TemplateUnits + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Interpolation ////////////////////////////////////////////////////// - /** - * Takes a bounding box and a cell size in degrees and returns a FeatureCollection of flat-topped hexagons (Polygon features) aligned in an "odd-q" vertical grid as described in Hexagonal Grids. - * @param bbox Bounding box in [minX, minY, maxX, maxY] order - * @param cellWidth Width of cell in specified units - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns A hexagonal grid - */ - function hexGrid(bbox: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; - /** * Takes points with z-values and an array of value breaks and generates isolines. * @param points Input points @@ -455,7 +798,7 @@ declare module turf { * @param breaks Where to draw contours * @returns Isolines */ - function isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; + isolines(points: GeoJSON.FeatureCollection, z: string, resolution: number, breaks: Array): GeoJSON.FeatureCollection; /** * Takes a triangular plane as a Polygon and a Point within that triangle and returns the z-value at that point. @@ -464,25 +807,7 @@ declare module turf { * @param triangle A Polygon feature with three vertices * @returns The z-value for interpolatedPoint */ - function planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; - - /** - * Takes a bounding box and a cell depth and returns a set of points in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth The distance across each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of points - */ - function pointGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; - - /** - * Takes a bounding box and a cell depth and returns a set of square polygons in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth Width of each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of polygons - */ - function squareGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + planepoint(interpolatedpoint: GeoJSON.Feature, triangle: GeoJSON.Feature): number; /** * Takes a set of points and the name of a z-value property and creates a Triangulated Irregular Network, or a TIN for short, returned as a collection of Polygons. @@ -492,39 +817,59 @@ declare module turf { * @param [propertyName] Name of the property from which to pull z values This is optional: if not given, then there will be no extra data added to the derived triangles. * @returns TIN output */ - function tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; - - /** - * Takes a bounding box and a cell depth and returns a set of triangular polygons in a grid. - * @param extent Extent in [minX, minY, maxX, maxY] order - * @param cellWidth Width of each cell - * @param units Used in calculating cellWidth ('miles' or 'kilometers') - * @returns Grid of triangles - */ - function triangleGrid(extent: Array, cellWidth: number, units: string): GeoJSON.FeatureCollection; + tin(points: GeoJSON.FeatureCollection, propertyName?: string): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Joins ////////////////////////////////////////////////////// /** - * Takes a Point and a Polygon or MultiPolygon and determines if the point resides inside the polygon. - * The polygon can be convex or concave. The function accounts for holes. - * @param point Input point - * @param polygon Input polygon or multipolygon - * @returns true if the Point is inside the Polygon; false if the Point is not inside the Polygon - */ - function inside(point: GeoJSON.Feature, polygon: GeoJSON.Feature): boolean; + * Takes a {} and a {} or {} and determines if the point resides inside the polygon. The polygon can be convex or concave. The function accounts for holes. + * + * @name [inside](http://turfjs.org/docs/#inside) + * @param {Feature} point input point + * @param {Feature<(Polygon|MultiPolygon)>} polygon input polygon or multipolygon + * @return {Boolean} `true` if the Point is inside the Polygon; `false` if the Point is not inside the Polygon + * @example + * var pt = point([-77, 44]) + * var poly = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]]) + * + * var isInside = turf.inside(pt, poly) + * + * //=isInside + */ + inside( + point: GeoJSON.Feature, + polygon: GeoJSON.Feature + ): boolean; /** - * Takes a set of points and a set of polygons and performs a spatial join. - * @param points Input points - * @param polygons Input polygons - * @param polyId Property in polygons to add to joined Point features - * @param containingPolyId Property in points in which to store joined property from polygons - * @returns Points with containingPolyId property containing values from polyId - */ - function tag(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection, polyId: string, containingPolyId: string): GeoJSON.FeatureCollection; + * Takes a {FeatureCollection} and a {FeatureCollection} and performs a spatial join. + * + * @name [tag](http://turfjs.org/docs/#inside) + * @param {FeatureCollection} points input points + * @param {FeatureCollection} polygons input polygons + * @param {string} field property in `polygons` to add to joined {} features + * @param {string} outField property in `points` in which to store joined property from `polygons` + * @return {FeatureCollection} points with `containingPolyId` property containing values from `polyId` + * @example + * var pt1 = point([-77, 44]) + * var pt2 = point([-77, 38]) + * var poly1 = polygon([[[-81, 41], [-81, 47], [-72, 47], [-72, 41], [-81, 41]]], {pop: 1000}) + * var poly2 = polygon([[[-81, 35], [-81, 41], [-72, 41], [-72, 35], [-81, 35]]], {pop: 3000}) + * + * var points = featureCollection([pt1, pt2]) + * var polygons = featureCollection([poly1, poly2]) + * + * var tagged = turf.tag(points, polygons, 'pop', 'population') + * //=tagged + */ + tag( + points: GeoJSON.FeatureCollection, + polygons: GeoJSON.FeatureCollection, + field: string, + outField: string + ): GeoJSON.FeatureCollection; /** * Takes a set of points and a set of polygons and returns the points that fall within the polygons. @@ -532,49 +877,331 @@ declare module turf { * @param polygons Input polygons * @returns Points that land within at least one polygon */ - function within(points: GeoJSON.FeatureCollection, polygons: GeoJSON.FeatureCollection): GeoJSON.FeatureCollection; + within( + points: GeoJSON.FeatureCollection, + polygons: GeoJSON.FeatureCollection + ): GeoJSON.FeatureCollection; ////////////////////////////////////////////////////// // Classification ////////////////////////////////////////////////////// - /** - * Takes a set of features and returns an array of the Jenks Natural breaks for a given property. - * @param input Input features - * @param field The property in input on which to calculate Jenks natural breaks - * @param numberOfBreaks Number of classes in which to group the data - * @returns The break number for each class plus the minimum and maximum values - */ - function jenks(input: GeoJSON.FeatureCollection, field: string, numberOfBreaks: number): Array; - /** * Takes a reference point and a set of points and returns the point from the set closest to the reference. * @param point The reference point * @param against Input point set * @returns The closest point in the set to the reference point */ - function nearest(point: GeoJSON.Feature, against: GeoJSON.FeatureCollection): GeoJSON.Feature; - - /** - * Takes a FeatureCollection, a property name, and a set of percentiles and returns a quantile array. - * @param input Set of features - * @param field The property in input from which to retrieve quantile values - * @param percentiles An Array of percentiles on which to calculate quantile values - * @returns An array of the break values - */ - function quantile(input: GeoJSON.FeatureCollection, field: string, percentiles: Array): Array; - - /** - * Takes a FeatureCollection, an input field, an output field, and an array of translations and outputs an identical FeatureCollection with the output field property populated. - * @param input Set of input features - * @param inField The field to translate - * @param outField The field in which to store translated results - * @param translations An array of translations - * @returns A FeatureCollection with identical geometries to input but with outField populated. - */ - function reclass(input: GeoJSON.FeatureCollection, inField: string, outField: string, translations: Array): GeoJSON.FeatureCollection; + nearest( + point: GeoJSON.Feature, + against: GeoJSON.FeatureCollection + ): GeoJSON.Feature; + } } -declare module 'turf' { - export= turf; +// NPM Stable version of Turf +declare module "turf" { + export = turf } + +// Latest version of Turf +declare module "@turf/turf" { + export = turf +} + +// AGGREGATION +declare module "@turf/collect" { + const collect: typeof turf.collect; + export = collect; +} + +// MEASUREMENT +declare module "@turf/along" { + const along: typeof turf.along; + export = along; +} + +declare module "@turf/area" { + const area: typeof turf.area; + export = area; +} + +declare module "@turf/bbox-polygon" { + const bboxPolygon: typeof turf.bboxPolygon; + export = bboxPolygon; +} + +declare module "@turf/bearing" { + const bearing: typeof turf.bearing; + export = bearing; +} + +declare module "@turf/center" { + const center: typeof turf.center; + export = center; +} + +declare module "@turf/centroid" { + const centroid: typeof turf.centroid; + export = centroid; +} + +declare module "@turf/destination" { + const destination: typeof turf.destination; + export = destination; +} + +declare module "@turf/distance" { + const distance: typeof turf.distance; + export = distance; +} + +declare module "@turf/envelope" { + const envelope: typeof turf.envelope; + export = envelope; +} + +declare module "@turf/line-distance" { + const lineDistance: typeof turf.lineDistance; + export = lineDistance; +} + +declare module "@turf/midpoint" { + const midpoint: typeof turf.midpoint; + export = midpoint; +} + +declare module "@turf/point-on-surface" { + const pointOnSurface: typeof turf.pointOnSurface; + export = pointOnSurface; +} + +declare module "@turf/square" { + const square: typeof turf.square; + export = square; +} + +// TRANSFORMATION +declare module "@turf/bezier" { + const bezier: typeof turf.bezier; + export = bezier; +} + +declare module "@turf/buffer" { + const buffer: typeof turf.buffer; + export = buffer; +} + +declare module "@turf/concave" { + const concave: typeof turf.concave; + export = concave; +} + +declare module "@turf/convex" { + const convex: typeof turf.convex; + export = convex; +} + +declare module "@turf/difference" { + const difference: typeof turf.difference; + export = difference; +} + +declare module "@turf/intersect" { + const intersect: typeof turf.intersect; + export = intersect; +} + +declare module "@turf/simplify" { + const simplify: typeof turf.simplify; + export = simplify; +} + +declare module "@turf/union" { + const union: typeof turf.union; + export = union; +} + +// MISC +declare module "@turf/combine" { + const combine: typeof turf.combine; + export = combine; +} + +declare module "@turf/explode" { + const explode: typeof turf.explode; + export = explode; +} + +declare module "@turf/flip" { + const flip: typeof turf.flip; + export = flip; +} + +declare module "@turf/kinks" { + const kinks: typeof turf.kinks; + export = kinks; +} + +declare module "@turf/line-slice" { + const lineSlice: typeof turf.lineSlice; + export = lineSlice; +} + +declare module "@turf/point-on-line" { + const pointOnLine: typeof turf.pointOnLine; + export = pointOnLine; +} + +// HELPER +declare module "@turf/helpers" { + const helpers: { + featureCollection: typeof turf.featureCollection, + feature: typeof turf.feature, + lineString: typeof turf.lineString, + multiLineString: typeof turf.multiLineString, + point: typeof turf.point, + multiPoint: typeof turf.multiPoint, + polygon: typeof turf.polygon, + multiPolygon: typeof turf.multiPolygon, + geometryCollection: typeof turf.geometryCollection, + }; + export = helpers; +} + +// DATA +declare module "@turf/random" { + const random: typeof turf.random; + export = random; +} + +declare module "@turf/sample" { + const sample: typeof turf.sample; + export = sample; +} + +// INTERPOLATION +declare module "@turf/isolines" { + const isolines: typeof turf.isolines; + export = isolines; +} + +declare module "@turf/planepoint" { + const planepoint: typeof turf.planepoint; + export = planepoint; +} + +declare module "@turf/tin" { + const tin: typeof turf.tin; + export = tin; +} + +// JOINS +declare module "@turf/inside" { + const inside: typeof turf.inside; + export = inside; +} + +declare module "@turf/tag" { + const tag: typeof turf.tag; + export = tag; +} + +declare module "@turf/within" { + const within: typeof turf.within; + export = within; +} + +// GRIDS +declare module "@turf/hex-grid" { + const hexGrid: typeof turf.hexGrid; + export = hexGrid; +} + +declare module "@turf/point-grid" { + const pointGrid: typeof turf.pointGrid; + export = pointGrid; +} + +declare module "@turf/square-grid" { + const squareGrid: typeof turf.squareGrid; + export = squareGrid; +} + +declare module "@turf/triangle-grid" { + const triangleGrid: typeof turf.triangleGrid; + export = triangleGrid; +} + +// CLASSIFICATION +declare module "@turf/nearest" { + const nearest: typeof turf.nearest; + export = nearest; +} + +// // META +// declare module "@turf/propEach" { +// const propEach: typeof turf.propEach; +// export = propEach; +// } + +// declare module "@turf/coordEach" { +// const coordEach: typeof turf.coordEach; +// export = coordEach; +// } + +// declare module "@turf/coordReduce" { +// const coordReduce: typeof turf.coordReduce; +// export = coordReduce; +// } + +// declare module "@turf/featureEach" { +// const featureEach: typeof turf.featureEach; +// export = featureEach; +// } + +// declare module "@turf/getCoord" { +// const getCoord: typeof turf.getCoord; +// export = getCoord; +// } + +// // ASSERTIONS +// declare module "@turf/featureOf" { +// const featureOf: typeof turf.featureOf; +// export = featureOf; +// } + +// declare module "@turf/collectionOf" { +// const collectionOf: typeof turf.collectionOf; +// export = collectionOf; +// } + +declare module "@turf/bbox" { + const bbox: typeof turf.bbox; + export = bbox; +} + +// declare module "@turf/circle" { +// const circle: typeof turf.circle; +// export = circle; +// } + +// declare module "@turf/geojsonType" { +// const geojsonType: typeof turf.geojsonType; +// export = geojsonType; +// } + +// declare module "@turf/propReduce" { +// const propReduce: typeof turf.propReduce; +// export = propReduce; +// } + +// declare module "@turf/coordAll" { +// const coordAll: typeof turf.coordAll; +// export = coordAll; +// } + +// declare module "@turf/tesselate" { +// const tesselate: typeof turf.tesselate; +// export = tesselate; +// } From ee9a6159396bdfde7d345df6e6b5cdf57fdb9bcc Mon Sep 17 00:00:00 2001 From: Borislav Zhivkov Date: Mon, 19 Sep 2016 09:51:04 +0300 Subject: [PATCH 128/212] Add angular-feature-flags definitions (#11283) --- .../angular-feature-flags-tests.ts | 31 +++++++++++++++ .../angular-feature-flags.d.ts | 38 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 angular-feature-flags/angular-feature-flags-tests.ts create mode 100644 angular-feature-flags/angular-feature-flags.d.ts diff --git a/angular-feature-flags/angular-feature-flags-tests.ts b/angular-feature-flags/angular-feature-flags-tests.ts new file mode 100644 index 0000000000..a36eaba3d0 --- /dev/null +++ b/angular-feature-flags/angular-feature-flags-tests.ts @@ -0,0 +1,31 @@ +/// + +let myApp = angular.module('myApp', ['feature-flags']); + +const flagsData: Array = [ + { + key: '1', + active: true, + name: 'flag1', + description: 'This is the first flag' + }, + { + key: '2', + active: false, + name: 'flag2', + description: 'This is the second flag' + } +]; + +myApp.config(function (featureFlagsProvider: angular.featureflags.FeatureFlagsProvider) { + featureFlagsProvider.setInitialFlags(flagsData); +}); + +myApp.run(function ($q: angular.IQService, $http: angular.IHttpService, featureFlags: angular.featureflags.FeatureFlagsService) { + let deferred = $q.defer(); + deferred.resolve(flagsData); + + featureFlags.set(deferred.promise); + + featureFlags.set($http.get('/data/flags.json')); +}); \ No newline at end of file diff --git a/angular-feature-flags/angular-feature-flags.d.ts b/angular-feature-flags/angular-feature-flags.d.ts new file mode 100644 index 0000000000..99ef300976 --- /dev/null +++ b/angular-feature-flags/angular-feature-flags.d.ts @@ -0,0 +1,38 @@ +// Type definitions for angular-feature-flags 1.4.0 +// Project: https://github.com/mjt01/angular-feature-flags +// Definitions by: Borislav Zhivkov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace angular.featureflags { + export interface FlagData { + /** + * Unique key that is used from the markup to resolve whether a flag is active or not. + */ + key: string; + + /** + * Boolean value for enabling/disabling the feature + */ + active: boolean; + + /** + * A short name of the flag (only visible in the list of flags) + */ + name: string; + + /** + * A long description of the flag to further explain the feature being toggled (only visible in the list of flags) + */ + description: string; + } + + export interface FeatureFlagsProvider { + setInitialFlags(flags: Array): void; + } + + export interface FeatureFlagsService { + set(flagsPromise: angular.IPromise | angular.IHttpPromise): void; + } +} \ No newline at end of file From 4b8264149240480dec8d6d6b2dd97ddaedba4142 Mon Sep 17 00:00:00 2001 From: Milan Burda Date: Sun, 18 Sep 2016 23:56:50 -0700 Subject: [PATCH 129/212] Update to Electron 1.3.6 (#11229) --- github-electron/github-electron.d.ts | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/github-electron/github-electron.d.ts b/github-electron/github-electron.d.ts index 3dc72d7075..64b7cf6a02 100644 --- a/github-electron/github-electron.d.ts +++ b/github-electron/github-electron.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Electron v1.3.5 +// Type definitions for Electron v1.3.6 // Project: http://electron.atom.io/ // Definitions by: jedmao , rhysd , Milan Burda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -62,7 +62,7 @@ declare namespace Electron { /** * Emitted when Electron has finished initialization. */ - on(event: 'ready', listener: Function): this; + on(event: 'ready', listener: (event: Event, launchInfo: Object) => void): this; /** * Emitted when all windows have been closed. * @@ -218,6 +218,10 @@ declare namespace Electron { args?: string[], execPath?: string }): void; + /** + * @returns Whether Electron has finished initializing. + */ + isReady(): boolean; /** * On Linux, focuses on the first visible window. * On macOS, makes the application the active app. @@ -1367,6 +1371,12 @@ declare namespace Electron { } interface WebPreferences { + /** + * Whether to enable DevTools. + * If it is set to false, can not use BrowserWindow.webContents.openDevTools() to open DevTools. + * Default: true. + */ + devTools?: boolean; /** * Whether node integration is enabled. * Default: true. @@ -1957,7 +1967,7 @@ declare namespace Electron { interface CrashReporterStartOptions { /** - * Default: Electron + * Default: app.getName() */ productName?: string; companyName: string; @@ -3392,16 +3402,18 @@ declare namespace Electron { interface Shell { /** * Show the given file in a file manager. If possible, select the file. + * @returns Whether the item was successfully shown. */ - showItemInFolder(fullPath: string): void; + showItemInFolder(fullPath: string): boolean; /** * Open the given file in the desktop's default manner. + * @returns Whether the item was successfully shown. */ - openItem(fullPath: string): void; + openItem(fullPath: string): boolean; /** * Open the given external protocol URL in the desktop's default manner * (e.g., mailto: URLs in the default mail user agent). - * @returns true if an application was available to open the URL, false otherwise. + * @returns Whether an application was available to open the URL. */ openExternal(url: string, options?: { /** @@ -3412,7 +3424,7 @@ declare namespace Electron { }): boolean; /** * Move the given file to trash. - * @returns boolean status for the operation. + * @returns Whether the item was successfully moved to the trash. */ moveItemToTrash(fullPath: string): boolean; /** From 1adaa22d7a6cc83ce09638e2cae00fc6f6589857 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alejandro=20S=C3=A1nchez?= Date: Mon, 19 Sep 2016 01:07:25 -0600 Subject: [PATCH 130/212] [WIP] Add type definitions for Leaflet 1.0 (#11165) * Rename leaflet.d.ts to leaflet-0.7.d.ts * Defined several important interfaces and the skeleton of some others * Started adding tests * Added more interfaces, factory methods and tests * Implemented other interfaces and nested namespaces * Added more types --- heatmap.js/heatmap.d.ts | 2 +- leaflet-curve/leaflet-curve-tests.ts | 2 +- leaflet-curve/leaflet-curve.d.ts | 2 +- leaflet-draw/leaflet-draw-tests.ts | 4 +- leaflet-draw/leaflet-draw.d.ts | 2 +- leaflet-editable/leaflet-editable.d.ts | 2 +- .../leaflet-geocoder-mapzen-tests.ts | 2 +- .../leaflet-geocoder-mapzen.d.ts | 2 +- leaflet-label/leaflet-label.d.ts | 2 +- .../leaflet-markercluster.d.ts | 8 +- .../leaflet.awesome-markers.d.ts | 2 +- leaflet.fullscreen/leaflet.fullscreen.d.ts | 2 +- leaflet/leaflet-0.7-tests.ts | 427 ++ leaflet/leaflet-0.7.d.ts | 4382 ++++++++++++++ leaflet/leaflet-tests.ts | 690 +-- leaflet/leaflet.d.ts | 5095 +++-------------- mapbox/mapbox.d.ts | 2 +- 17 files changed, 5911 insertions(+), 4717 deletions(-) create mode 100644 leaflet/leaflet-0.7-tests.ts create mode 100644 leaflet/leaflet-0.7.d.ts diff --git a/heatmap.js/heatmap.d.ts b/heatmap.js/heatmap.d.ts index 7cd14fc214..fb2b4eea3d 100644 --- a/heatmap.js/heatmap.d.ts +++ b/heatmap.js/heatmap.d.ts @@ -3,7 +3,7 @@ // Definitions by: Yang Guan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// /* * Configuration object of a heatmap diff --git a/leaflet-curve/leaflet-curve-tests.ts b/leaflet-curve/leaflet-curve-tests.ts index 2c5bb6b8f1..9864e71252 100644 --- a/leaflet-curve/leaflet-curve-tests.ts +++ b/leaflet-curve/leaflet-curve-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// diff --git a/leaflet-curve/leaflet-curve.d.ts b/leaflet-curve/leaflet-curve.d.ts index 32358c08ac..7bd64215b9 100644 --- a/leaflet-curve/leaflet-curve.d.ts +++ b/leaflet-curve/leaflet-curve.d.ts @@ -3,7 +3,7 @@ // Definitions by: Onikiienko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { /** diff --git a/leaflet-draw/leaflet-draw-tests.ts b/leaflet-draw/leaflet-draw-tests.ts index 9a1ed09306..396f5119d3 100644 --- a/leaflet-draw/leaflet-draw-tests.ts +++ b/leaflet-draw/leaflet-draw-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// @@ -44,4 +44,4 @@ map.on('draw:created', function (e: L.DrawEvents.Created) { layer = e.layer; drawnItems.addLayer(layer); -}); \ No newline at end of file +}); diff --git a/leaflet-draw/leaflet-draw.d.ts b/leaflet-draw/leaflet-draw.d.ts index 253d6c3a11..7c80f17ef2 100644 --- a/leaflet-draw/leaflet-draw.d.ts +++ b/leaflet-draw/leaflet-draw.d.ts @@ -3,7 +3,7 @@ // Definitions by: Matt Guest // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { export interface MapOptions { diff --git a/leaflet-editable/leaflet-editable.d.ts b/leaflet-editable/leaflet-editable.d.ts index 0d7b2bcc0f..f559917b62 100644 --- a/leaflet-editable/leaflet-editable.d.ts +++ b/leaflet-editable/leaflet-editable.d.ts @@ -3,7 +3,7 @@ // Definitions by: Dominic Alie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { /** diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts index c6519ab371..d623120a73 100644 --- a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen-tests.ts @@ -1,4 +1,4 @@ -/// +/// /// var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', diff --git a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts index 8809472e43..3e388ff515 100644 --- a/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts +++ b/leaflet-geocoder-mapzen/leaflet-geocoder-mapzen.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { namespace Control { diff --git a/leaflet-label/leaflet-label.d.ts b/leaflet-label/leaflet-label.d.ts index 009ded17f8..ea18df3cea 100644 --- a/leaflet-label/leaflet-label.d.ts +++ b/leaflet-label/leaflet-label.d.ts @@ -3,7 +3,7 @@ // Definitions by: Wim Looman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { export interface IconOptions { diff --git a/leaflet-markercluster/leaflet-markercluster.d.ts b/leaflet-markercluster/leaflet-markercluster.d.ts index 7d8757be03..b756389275 100644 --- a/leaflet-markercluster/leaflet-markercluster.d.ts +++ b/leaflet-markercluster/leaflet-markercluster.d.ts @@ -3,7 +3,7 @@ // Definitions by: Robert Imig // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { export interface MarkerClusterGroupOptions { @@ -51,7 +51,7 @@ declare namespace L { /* * The maximum radius that a cluster will cover from the central marker (in pixels). Default 80. - * Decreasing will make more, smaller clusters. You can also use a function that accepts + * Decreasing will make more, smaller clusters. You can also use a function that accepts * the current map zoom and returns the maximum cluster radius in pixels */ maxClusterRadius?: number | ((zoom: number) => number); @@ -134,9 +134,9 @@ declare namespace L { getAllChildMarkers(): Marker[]; /* - * Zooms to show the given marker (spiderfying if required), + * Zooms to show the given marker (spiderfying if required), * calls the callback when the marker is visible on the map. - */ + */ zoomToShowLayer(layer: any, callback: () => void): void; } } diff --git a/leaflet.awesome-markers/leaflet.awesome-markers.d.ts b/leaflet.awesome-markers/leaflet.awesome-markers.d.ts index 6fa754ad8d..4364743d48 100644 --- a/leaflet.awesome-markers/leaflet.awesome-markers.d.ts +++ b/leaflet.awesome-markers/leaflet.awesome-markers.d.ts @@ -3,7 +3,7 @@ // Definitions by: Egor Komarov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare module L { module AwesomeMarkers { diff --git a/leaflet.fullscreen/leaflet.fullscreen.d.ts b/leaflet.fullscreen/leaflet.fullscreen.d.ts index b8be6604dc..f094c307dc 100644 --- a/leaflet.fullscreen/leaflet.fullscreen.d.ts +++ b/leaflet.fullscreen/leaflet.fullscreen.d.ts @@ -3,7 +3,7 @@ // Definitions by: William Comartin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// declare namespace L { diff --git a/leaflet/leaflet-0.7-tests.ts b/leaflet/leaflet-0.7-tests.ts new file mode 100644 index 0000000000..1a88096002 --- /dev/null +++ b/leaflet/leaflet-0.7-tests.ts @@ -0,0 +1,427 @@ +/// + +// initialize the map on the "map" div with a given center and zoom + +var div = document.getElementById('map'); + +var map : L.Map = L.map(div, { + center: L.latLng([51.505, -0.09]), + zoom: 13, + minZoom: 3, + maxZoom: 8, + maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]), + dragging: true, + touchZoom: true, + scrollWheelZoom: true, + boxZoom: true, + tap: true, + + tapTolerance: 30, + trackResize: true, + worldCopyJump: false, + closePopupOnClick: true, + bounceAtZoomLimits: true, + + keyboard: true, + keyboardPanOffset: 80, + keyboardZoomOffset: 1, + + inertia: true, + inertiaDeceleration: 3000, + inertiaMaxSpeed: 1500, + inertiaThreshold: 32, + + zoomControl: true, + attributionControl: true, + + fadeAnimation: true, + zoomAnimation: true, + zoomAnimationThreshold: 4, + markerZoomAnimation: true + +}); + +map.dragging.enable(); +map.touchZoom.enable(); +map.scrollWheelZoom.enable(); +map.doubleClickZoom.enable(); +map.boxZoom.enable(); +map.tap.enable(); + +map.setView(new L.LatLng(42, 51)); +map.setView(L.latLng(42, 51)); + +map.setView(L.latLng(42, 51), 12); +map.setView(L.latLng(42, 51), 12, { + reset: true, + pan: { + animate: true, + duration: 0.25, + easeLinearity: 0.25, + noMoveStart: false + }, + zoom: { + animate: true + } +}); + +map.setZoom(50); +map.setZoom(50, {}); + +map.zoomIn(); +map.zoomOut(); + +map.zoomIn(2); +map.zoomOut(2); + +map.zoomIn(2, { animate: true }); +map.zoomOut(2, { animate: true }); + +map.setZoomAround(L.latLng(42, 51), 8, { animate: false }); + +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); +map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), { + paddingTopLeft: L.point(20, 20), + paddingBottomRight: L.point(20, 20), + padding: L.point(0, 0), + maxZoom: null +}); + +map.fitWorld(); + +map.fitWorld({ + animate: false +}); + +map.panTo(L.latLng(42, 42)); +map.panTo(L.latLng(42, 42), { + animate: true +}); + +map.invalidateSize(true); +map.invalidateSize({ reset: true }); + +map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); + +map.locate(); +map.locate({ + watch: false, + setView: false, + maxZoom: 18, + timeout: 10000, + maximumAge: 0, + enableHighAccuracy: false +}); + +map.stopLocate(); + +map.remove(); + +var center : L.LatLng = map.getCenter(); +var zoom : number = map.getZoom(); +var minZoom: number = map.getMinZoom(); +var maxZoom: number = map.getMaxZoom(); +var bounds: L.LatLngBounds = map.getBounds(); +var boundsZoom: number = map.getBoundsZoom(bounds, true); +var size: L.Point = map.getSize(); +var pixelBounds: L.Bounds = map.getPixelBounds(); +var pixelOrigin: L.Point = map.getPixelOrigin(); + +var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png"); + +map.addLayer(layer); +map.addLayer(layer, false); +map.eachLayer(l => {}); + +map.removeLayer(layer); +map.hasLayer(layer); + +map.openPopup("canard", L.latLng(42, 51)); + +var popup = L.popup({ + autoPan: true +}); + +map.openPopup(popup); +map.closePopup(popup); +map.closePopup(); + +map.addControl(L.control.attribution({position: 'bottomright'})); +map.removeControl(L.control.attribution({ position: 'bottomright' })); + +L.control.layers({'Base': layer}).addTo(map); +map.on('baseLayerChange', function(e: L.LeafletLayersControlEvent) { + alert(e.name); +}); + +map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0))); +map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0))); +map.containerPointToLayerPoint(L.point(0, 0)); +map.layerPointToContainerPoint(L.point(0, 0)); + +map.project(map.unproject(L.point(10, 20))); +map.project(map.unproject(L.point(10, 20), 12), 12); + +var mouseEvent: L.LeafletMouseEvent; +map.mouseEventToContainerPoint(mouseEvent); +map.mouseEventToLayerPoint(mouseEvent); +map.mouseEventToLatLng(mouseEvent); + +map.getContainer().classList.add('roger'); +map.getPanes().mapPane.classList.add('roger'); +map.getPanes().markerPane.classList.add('roger'); +map.getPanes().objectsPane.classList.add('roger'); +map.getPanes().overlayPane.classList.add('roger'); +map.getPanes().popupPane.classList.add('roger'); +map.getPanes().shadowPane.classList.add('roger'); +map.getPanes().tilePane.classList.add('roger'); + +map.whenReady((m: L.Map) => { + m.zoomOut(); +}); + +map.on('click', () => { + map.zoomOut(); +}); + +map.off('dblclick', L.Util.falseFn); + +map.once('contextmenu', (e: L.LeafletMouseEvent) => { + map.openPopup('contextmenu', e.latlng); +}); + +var marker = L.marker(L.latLng(42, 51), { + icon: L.icon({ + iconUrl: 'roger.png', + iconRetinaUrl: 'roger-retina.png', + iconSize: L.point(40, 40), + iconAnchor: L.point(20, 0), + shadowUrl: 'roger-shadow.png', + shadowRetinaUrl: 'roger-shadow-retina.png', + shadowSize: L.point(44, 44), + shadowAnchor: L.point(22, 0), + popupAnchor: L.point(0, 0), + className: 'roger-icon' + }), + clickable: true, + draggable: false, + keyboard: true, + title: 'this is an icon', + alt: '', + zIndexOffset: 0, + opacity: 1.0, + riseOnHover: false, + riseOffset: 250 +}); + +marker.addTo(map); + +marker.on('click', (e: L.LeafletMouseEvent) => { + map.setView(e.latlng); +}); + +marker.once('mouseover', () => { + marker.openPopup(); +}) + +marker.setLatLng(marker.getLatLng()); + +marker.setIcon(L.icon({})); + +marker.setZIndexOffset(30); +marker.setOpacity(0.8); + +marker.bindPopup(popup); +marker.unbindPopup(); +marker.bindPopup('hello', { + closeOnClick: true +}); + +marker.openPopup(); +marker.closePopup(); +marker.togglePopup(); +marker.togglePopup(); +marker.setPopupContent('hello 3') +marker.getPopup().setContent('hello 2'); +marker.update(); + +marker.toGeoJSON(); + +marker.dragging.enable(); + +popup = L.popup({ + maxWidth: 300, + minWidth: 50, + maxHeight: null, + autoPan: true, + keepInView: false, + closeButton: true, + offset: L.point(0, 6), + autoPanPaddingTopLeft: null, + autoPanPaddingBottomRight: L.point(20, 20), + autoPanPadding: L.point(5, 5), + zoomAnimation: true, + closeOnClick: null, + className: 'roger' +}); + +popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map); + +popup.update(); + +var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', { + minZoom: 0, + maxZoom: 18, + maxNativeZoom: 17, + tileSize: 256, + subdomains: ['a','b','c'], + errorTileUrl: '', + attribution: '', + tms: false, + continuousWorld: false, + noWrap: false, + zoomOffset: 0, + zoomReverse: false, + opacity: 1.0, + zIndex: null, + unloadInvisibleTiles: false, + updateWhenIdle: false, + detectRetina: true, + reuseTiles: true, + bounds: null +}); + +tileLayer.on('loading', L.Util.falseFn) + .off('loading', L.Util.falseFn) + .once('tileload', L.Util.falseFn); + +tileLayer.addTo(map); + +tileLayer.bringToBack() + .bringToFront() + .setOpacity(0.7) + .setZIndex(9) + .redraw() + .setUrl('http://perdu.com') + .getContainer(); + +namespace CustomControl { + export interface Options { + title: string; + position?: string; + } +} +interface CustomControl extends L.Control { + getTitle(): string; + setTitle(title: string): CustomControl; +} +var CustomControl: { new(options: CustomControl.Options): CustomControl }; +CustomControl = L.Control.extend({ + initialize: function(options: CustomControl.Options) { + L.Control.prototype.initialize.call(this, { + position: options.position || 'bottomleft', + }); + this.title = options.title; + }, + getTitle: function() { + return this.title; + }, + setTitle: function(title: string) { + this.title = title; + }, +}); + +// Different latLng and latLngBounds expressions +var latLngLiteral = [10, 20]; +var latLngObjectLiteral = { lat: 10, lng: 10 }; +var boundsLiteral = [[10, 20], [20, 20]]; +var boundLiteralOfLatLngObjects = [latLngObjectLiteral, latLngObjectLiteral]; + +var circle: L.Circle = L.circle(latLngLiteral, 4); +circle = new L.Circle(latLngLiteral, 4); +circle.setLatLng(latLngLiteral); + +circle = L.circle(latLngObjectLiteral, 4); +circle = new L.Circle(latLngObjectLiteral, 4); +circle.setLatLng(latLngObjectLiteral); + +var circleMarker: L.CircleMarker = L.circleMarker(latLngLiteral); +circleMarker = new L.CircleMarker(latLngLiteral); +circleMarker.setLatLng(latLngLiteral); + +circleMarker = L.circleMarker(latLngObjectLiteral); +circleMarker = new L.CircleMarker(latLngObjectLiteral); +circleMarker.setLatLng(latLngObjectLiteral); + +var latLng: L.LatLng = L.latLng(latLngLiteral); +latLng = new L.LatLng(latLngLiteral); +latLng.distanceTo(latLngLiteral); +latLng.equals(latLngLiteral); + +latLng = L.latLng(latLngObjectLiteral); +latLng = new L.LatLng(latLngObjectLiteral); +latLng.distanceTo(latLngObjectLiteral); +latLng.equals(latLngObjectLiteral); + +var bounds: L.LatLngBounds = L.latLngBounds(boundsLiteral); +bounds = L.latLngBounds(boundLiteralOfLatLngObjects); +bounds = new L.LatLngBounds(boundsLiteral); +bounds = new L.LatLngBounds(boundLiteralOfLatLngObjects); +bounds = new L.LatLngBounds(latLngLiteral, latLngLiteral); + +bounds.extend(latLngLiteral); +bounds.extend(latLngObjectLiteral); +bounds.extend(boundsLiteral); +bounds.extend(boundLiteralOfLatLngObjects); + +bounds.contains(latLngLiteral); +bounds.contains(boundLiteralOfLatLngObjects); +bounds.contains(boundsLiteral); + +bounds.intersects(boundsLiteral); +bounds.intersects(boundLiteralOfLatLngObjects); + +bounds.equals(boundsLiteral); +bounds.equals(boundLiteralOfLatLngObjects); + +map.setView(latLngLiteral); +map.setView(latLngObjectLiteral); +map.setZoomAround(latLngLiteral, 15); +map.setZoomAround(latLngObjectLiteral, 15); +map.panTo(latLngLiteral); +map.panTo(latLngObjectLiteral); +map.openPopup('test', latLngLiteral); +map.openPopup('test', latLngObjectLiteral); +map.latLngToLayerPoint(latLngLiteral); +map.latLngToLayerPoint(latLngObjectLiteral); +map.latLngToContainerPoint(latLngLiteral); +map.latLngToContainerPoint(latLngObjectLiteral); +map.project(latLngLiteral); +map.project(latLngObjectLiteral); + +marker.setLatLng(latLngLiteral); +marker.setLatLng(latLngObjectLiteral); + +var polygon: L.Polygon = L.polygon(boundsLiteral); +polygon = L.polygon(boundLiteralOfLatLngObjects); +polygon = new L.Polygon(boundsLiteral); +polygon = new L.Polygon(boundLiteralOfLatLngObjects); + +var polyline: L.Polyline = L.polyline(boundsLiteral); +polyline = L.polyline(boundLiteralOfLatLngObjects); +polyline = new L.Polyline(boundsLiteral); +polyline = new L.Polyline(boundLiteralOfLatLngObjects); +polyline.setLatLngs(boundsLiteral); +polyline.setLatLngs(boundLiteralOfLatLngObjects); +polyline.addLatLng(latLngLiteral); +polyline.addLatLng(latLngObjectLiteral); + +var popup: L.Popup = L.popup(); +popup.setLatLng(latLngLiteral); +popup.setLatLng(latLngObjectLiteral); + +var zoomCtrl = L.control.zoom({ + position: "topleft", + zoomInText: '+', + zoomOutText: '-' +}); diff --git a/leaflet/leaflet-0.7.d.ts b/leaflet/leaflet-0.7.d.ts new file mode 100644 index 0000000000..0c4bca15a6 --- /dev/null +++ b/leaflet/leaflet-0.7.d.ts @@ -0,0 +1,4382 @@ +// Type definitions for Leaflet.js 0.7.x +// Project: https://github.com/Leaflet/Leaflet +// Definitions by: Vladimir Zotov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace L { + type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) + type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; + type PositionString = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; +} + +declare namespace L { + + export interface AttributionOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomright'. + */ + position?: PositionString; + + /** + * The HTML text shown before the attributions. Pass false to disable. + * Default value: 'Powered by Leaflet'. + */ + prefix?: string; + + } +} + +declare namespace L { + + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + export function bounds(topLeft: Point, bottomRight: Point): Bounds; + + /** + * Creates a Bounds object defined by the points it contains. + */ + export function bounds(points: Point[]): Bounds; + + + export interface BoundsStatic { + /** + * Creates a Bounds object from two coordinates (usually top-left and bottom-right + * corners). + */ + new(topLeft: Point, bottomRight: Point): Bounds; + + /** + * Creates a Bounds object defined by the points it contains. + */ + new(points: Point[]): Bounds; + } + export var Bounds: BoundsStatic; + + export interface Bounds { + /** + * Extends the bounds to contain the given point. + */ + extend(point: Point): void; + + /** + * Returns the center point of the bounds. + */ + getCenter(): Point; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: Bounds): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(point: Point): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: Bounds): boolean; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + /** + * Returns the size of the given bounds. + */ + getSize(): Point; + + /** + * The top left corner of the rectangle. + */ + min: Point; + + /** + * The bottom right corner of the rectangle. + */ + max: Point; + } +} + +declare namespace L { + + namespace Browser { + + /** + * true for all Internet Explorer versions. + */ + export var ie: boolean; + + /** + * true for Internet Explorer 6. + */ + export var ie6: boolean; + + /** + * true for Internet Explorer 6. + */ + export var ie7: boolean; + + /** + * true for webkit-based browsers like Chrome and Safari (including mobile + * versions). + */ + export var webkit: boolean; + + /** + * true for webkit-based browsers that support CSS 3D transformations. + */ + export var webkit3d: boolean; + + /** + * true for Android mobile browser. + */ + export var android: boolean; + + /** + * true for old Android stock browsers (2 and 3). + */ + export var android23: boolean; + + /** + * true for modern mobile browsers (including iOS Safari and different Android + * browsers). + */ + export var mobile: boolean; + + /** + * true for mobile webkit-based browsers. + */ + export var mobileWebkit: boolean; + + /** + * true for mobile Opera. + */ + export var mobileOpera: boolean; + + /** + * true for all browsers on touch devices. + */ + export var touch: boolean; + + /** + * true for browsers with Microsoft touch model (e.g. IE10). + */ + export var msTouch: boolean; + + /** + * true for devices with Retina screens. + */ + export var retina: boolean; + + } +} + + +declare namespace L { + + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + function circle(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; + + export interface CircleStatic extends ClassStatic { + /** + * Instantiates a circle object given a geographical point, a radius in meters + * and optionally an options object. + */ + new(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; + } + export var Circle: CircleStatic; + + export interface Circle extends Path { + /** + * Returns the current geographical position of the circle. + */ + getLatLng(): LatLng; + + /** + * Returns the current radius of a circle. Units are in meters. + */ + getRadius(): number; + + /** + * Sets the position of a circle to a new location. + */ + setLatLng(latlng: LatLngExpression): Circle; + + /** + * Sets the radius of a circle. Units are in meters. + */ + setRadius(radius: number): Circle; + + /** + * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). + */ + toGeoJSON(): GeoJSON.Feature; + + } +} + +declare namespace L { + + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + function circleMarker(latlng: LatLngExpression, options?: PathOptions): CircleMarker; + + + export interface CircleMarkerStatic extends ClassStatic { + /** + * Instantiates a circle marker given a geographical point and optionally + * an options object. The default radius is 10 and can be altered by passing a + * "radius" member in the path options object. + */ + new(latlng: LatLngExpression, options?: PathOptions): CircleMarker; + } + export var CircleMarker: CircleMarkerStatic; + + export interface CircleMarker extends Circle { + /** + * Sets the position of a circle marker to a new location. + */ + setLatLng(latlng: LatLngExpression): CircleMarker; + + /** + * Sets the radius of a circle marker. Units are in pixels. + */ + setRadius(radius: number): CircleMarker; + } +} + +declare namespace L { + export interface ClassExtendOptions { + /** + * Your class's constructor function, meaning that it gets called when you do 'new MyClass(...)'. + */ + initialize?: Function; + + /** + * options is a special property that unlike other objects that you pass + * to extend will be merged with the parent one instead of overriding it + * completely, which makes managing configuration of objects and default + * values convenient. + */ + options?: any; + + /** + * includes is a special class property that merges all specified objects + * into the class (such objects are called mixins). A good example of this + * is L.Mixin.Events that event-related methods like on, off and fire + * to the class. + */ + includes?: any; + + /** + * statics is just a convenience property that injects specified object + * properties as the static properties of the class, useful for defining + * constants. + */ + static?: any; + + [prop: string]: any; + } + + export interface ClassStatic { + /** + * You use L.Class.extend to define new classes, but you can use the + * same method on any class to inherit from it. + */ + extend(options: ClassExtendOptions): any; + extend(options: ClassExtendOptions): { new(options?: Options): NewClass }; + + /** + * You can also use the following shortcut when you just need to make + * one additional method call. + */ + addInitHook(methodName: string, ...args: any[]): void; + } + + + /** + * L.Class powers the OOP facilities of Leaflet and is used to create + * almost all of the Leaflet classes documented. + */ + namespace Class { + /** + * You use L.Class.extend to define new classes, but you can use the + * same method on any class to inherit from it. + */ + function extend(options: ClassExtendOptions): any; + } + +} + +declare namespace L { + export interface ControlStatic extends ClassStatic { + /** + * Creates a control with the given options. + */ + new(options?: ControlOptions): Control; + + Zoom: Control.ZoomStatic; + Attribution: Control.AttributionStatic; + Layers: Control.LayersStatic; + Scale: Control.ScaleStatic; + } + export var Control: ControlStatic; + + export interface Control extends IControl { + /** + * Sets the position of the control. See control positions. + */ + setPosition(position: PositionString): Control; + + /** + * Returns the current position of the control. + */ + getPosition(): PositionString; + + /** + * Adds the control to the map. + */ + addTo(map: Map): Control; + + /** + * Removes the control from the map. + */ + removeFrom(map: Map): Control; + + /** + * Returns the HTML container of the control. + */ + getContainer(): HTMLElement; + + // IControl members + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } + + namespace Control { + export interface ZoomStatic extends ClassStatic { + /** + * Creates a zoom control. + */ + new (options?: ZoomOptions): Zoom; + } + + export interface Zoom extends L.Control { + } + + export interface ZoomOptions { + /** + * The position of the control (one of the map corners). + * Can be 'topleft', 'topright', 'bottomleft', or 'bottomright'. + * + * Default value: 'topright'. + */ + position?: PositionString; + + /** + * The text set on the zoom in button. + * + * Default value: '+' + */ + zoomInText?: string; + + /** + * The text set on the zoom out button. + * + * Default value: '-' + */ + zoomOutText?: string; + + /** + * The title set on the zoom in button. + * + * Default value: 'Zoom in' + */ + zoomInTitle?: string; + + /** + * The title set on the zoom out button. + * + * Default value: 'Zoom out' + */ + zoomOutTitle?: string; + } + + export interface AttributionStatic extends ClassStatic { + /** + * Creates an attribution control. + */ + new(options?: AttributionOptions): Attribution; + } + + export interface Attribution extends L.Control { + /** + * Sets the text before the attributions. + */ + setPrefix(prefix: string): Attribution; + + /** + * Adds an attribution text (e.g. 'Vector data © CloudMade'). + */ + addAttribution(text: string): Attribution; + + /** + * Removes an attribution text. + */ + removeAttribution(text: string): Attribution; + + } + + export interface LayersStatic extends ClassStatic { + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + new(baseLayers?: any, overlays?: any, options?: LayersOptions): Layers; + } + + export interface Layers extends L.Control, IEventPowered { + /** + * Adds a base layer (radio button entry) with the given name to the control. + */ + addBaseLayer(layer: ILayer, name: string): Layers; + + /** + * Adds an overlay (checkbox entry) with the given name to the control. + */ + addOverlay(layer: ILayer, name: string): Layers; + + /** + * Remove the given layer from the control. + */ + removeLayer(layer: ILayer): Layers; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Layers; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; + fire(type: string, data?: any): Layers; + addEventListener(eventMap: any, context?: any): Layers; + removeEventListener(eventMap?: any, context?: any): Layers; + clearAllEventListeners(): Layers; + on(eventMap: any, context?: any): Layers; + off(eventMap?: any, context?: any): Layers; + } + + export interface ScaleStatic extends ClassStatic { + /** + * Creates an scale control with the given options. + */ + new(options?: ScaleOptions): Scale; + } + + export interface Scale extends L.Control { + } + } + + export interface control { + /** + * Creates a control with the given options. + */ + (options?: ControlOptions): Control; + } + + export namespace control { + + /** + * Creates a zoom control. + */ + export function zoom(options?: Control.ZoomOptions): L.Control.Zoom; + + /** + * Creates an attribution control. + */ + export function attribution(options?: AttributionOptions): L.Control.Attribution; + + /** + * Creates an attribution control with the given layers. Base layers will be + * switched with radio buttons, while overlays will be switched with checkboxes. + */ + export function layers(baseLayers?: any, overlays?: any, options?: LayersOptions): L.Control.Layers; + + /** + * Creates an scale control with the given options. + */ + export function scale(options?: ScaleOptions): L.Control.Scale; + } +} + +declare namespace L { + + export interface ControlOptions { + + /** + * The initial position of the control (one of the map corners). See control + * positions. + * Default value: 'topright'. + */ + position?: PositionString; + + } +} + +declare namespace L { + + namespace CRS { + + /** + * The most common CRS for online maps, used by almost all free and commercial + * tile providers. Uses Spherical Mercator projection. Set in by default in + * Map's crs option. + */ + export var EPSG3857: ICRS; + + /** + * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. + */ + export var EPSG4326: ICRS; + + /** + * Rarely used by some commercial tile providers. Uses Elliptical Mercator + * projection. + */ + export var EPSG3395: ICRS; + + /** + * A simple CRS that maps longitude and latitude into x and y directly. May be + * used for maps of flat surfaces (e.g. game maps). Note that the y axis should + * still be inverted (going from bottom to top). + */ + export var Simple: ICRS; + + } +} + +declare namespace L { + + /** + * Creates a div icon instance with the given options. + */ + function divIcon(options: DivIconOptions): DivIcon; + + export interface DivIconStatic extends ClassStatic { + /** + * Creates a div icon instance with the given options. + */ + new(options: DivIconOptions): DivIcon; + } + export var DivIcon: DivIconStatic; + + export interface DivIcon extends Icon { + } +} + +declare namespace L { + + export interface DivIconOptions { + + /** + * Size of the icon in pixels. Can be also set through CSS. + */ + iconSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point|[number, number]; + + /** + * A custom class name to assign to the icon. + * + * Default value: 'leaflet-div-icon'. + */ + className?: string; + + /** + * A custom HTML code to put inside the div element. + * + * Default value: ''. + */ + html?: string; + + /** + * The coordinates of the point from which popups will "open", relative to the + * icon anchor. + */ + popupAnchor?: Point|[number, number]; + + } +} + +declare namespace L { + + export interface DomEvent { + + /** + * Adds a listener fn to the element's DOM event of the specified type. this keyword + * inside the listener will point to context, or to the element if not specified. + */ + addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + + /** + * Removes an event listener from the element. + */ + removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; + + /** + * Stop the given event from propagation to parent elements. Used inside the + * listener functions: + * L.DomEvent.addListener(div, 'click', function + * (e) { + * L.DomEvent.stopPropagation(e); + * }); + */ + stopPropagation(e: Event): DomEvent; + + /** + * Prevents the default action of the event from happening (such as following + * a link in the href of the a element, or doing a POST request with page reload + * when form is submitted). Use it inside listener functions. + */ + preventDefault(e: Event): DomEvent; + + /** + * Does stopPropagation and preventDefault at the same time. + */ + stop(e: Event): DomEvent; + + /** + * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' + * and 'touchstart' events. + */ + disableClickPropagation(el: HTMLElement): DomEvent; + + /** + * Gets normalized mouse position from a DOM event relative to the container + * or to the whole page if not specified. + */ + getMousePosition(e: Event, container?: HTMLElement): Point; + + /** + * Gets normalized wheel delta from a mousewheel DOM event. + */ + getWheelDelta(e: Event): number; + + } + + export var DomEvent: DomEvent; +} + +declare namespace L { + + namespace DomUtil { + + /** + * Returns an element with the given id if a string was passed, or just returns + * the element if it was passed directly. + */ + export function get(id: string): HTMLElement; + + /** + * Returns the value for a certain style attribute on an element, including + * computed values or values set through CSS. + */ + export function getStyle(el: HTMLElement, style: string): string; + + /** + * Returns the offset to the viewport for the requested element. + */ + export function getViewportOffset(el: HTMLElement): Point; + + /** + * Creates an element with tagName, sets the className, and optionally appends + * it to container element. + */ + export function create(tagName: string, className: string, container?: HTMLElement): HTMLElement; + + /** + * Makes sure text cannot be selected, for example during dragging. + */ + export function disableTextSelection(): void; + + /** + * Makes text selection possible again. + */ + export function enableTextSelection(): void; + + /** + * Returns true if the element class attribute contains name. + */ + export function hasClass(el: HTMLElement, name: string): boolean; + + /** + * Adds name to the element's class attribute. + */ + export function addClass(el: HTMLElement, name: string): void; + + /** + * Removes name from the element's class attribute. + */ + export function removeClass(el: HTMLElement, name: string): void; + + /** + * Set the opacity of an element (including old IE support). Value must be from + * 0 to 1. + */ + export function setOpacity(el: HTMLElement, value: number): void; + + /** + * Goes through the array of style names and returns the first name that is a valid + * style name for an element. If no such name is found, it returns false. Useful + * for vendor-prefixed styles like transform. + */ + export function testProp(props: string[]): any; + + /** + * Returns a CSS transform string to move an element by the offset provided in + * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms + * and 2D on other browsers. + */ + export function getTranslateString(point: Point): string; + + /** + * Returns a CSS transform string to scale an element (with the given scale origin). + */ + export function getScaleString(scale: number, origin: Point): string; + + /** + * Sets the position of an element to coordinates specified by point, using + * CSS translate or top/left positioning depending on the browser (used by + * Leaflet internally to position its layers). Forces top/left positioning + * if disable3D is true. + */ + export function setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; + + /** + * Returns the coordinates of an element previously positioned with setPosition. + */ + export function getPosition(el: HTMLElement): Point; + + /** + * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). + */ + export var TRANSITION: string; + + /** + * Vendor-prefixed transform style name. + */ + export var TRANSFORM: string; + + } +} + +declare namespace L { + export interface DraggableStatic extends ClassStatic { + /** + * Creates a Draggable object for moving the given element when you start dragging + * the dragHandle element (equals the element itself by default). + */ + new(element: HTMLElement, dragHandle?: HTMLElement): Draggable; + } + export var Draggable: DraggableStatic; + + + export interface Draggable extends IEventPowered { + /** + * Enables the dragging ability. + */ + enable(): void; + + /** + * Disables the dragging ability. + */ + disable(): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Draggable; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; + fire(type: string, data?: any): Draggable; + addEventListener(eventMap: any, context?: any): Draggable; + removeEventListener(eventMap?: any, context?: any): Draggable; + clearAllEventListeners(): Draggable; + on(eventMap: any, context?: any): Draggable; + off(eventMap?: any, context?: any): Draggable; + } +} + + + +declare namespace L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function featureGroup(layers?: T[]): FeatureGroup; + + + export interface FeatureGroupStatic extends ClassStatic { + /** + * Create a layer group, optionally given an initial set of layers. + */ + new(layers?: T[]): FeatureGroup; + } + export var FeatureGroup: FeatureGroupStatic; + + export interface FeatureGroup extends LayerGroup, ILayer, IEventPowered> { + /** + * Binds a popup with a particular HTML content to a click on any layer from the + * group that has a bindPopup method. + */ + bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; + + /** + * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates + * of its children). + */ + getBounds(): LatLngBounds; + + /** + * Sets the given path options to each layer of the group that has a setStyle method. + */ + setStyle(style: PathOptions): FeatureGroup; + + /** + * Brings the layer group to the top of all other layers. + */ + bringToFront(): FeatureGroup; + + /** + * Brings the layer group to the bottom of all other layers. + */ + bringToBack(): FeatureGroup; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): FeatureGroup; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; + fire(type: string, data?: any): FeatureGroup; + addEventListener(eventMap: any, context?: any): FeatureGroup; + removeEventListener(eventMap?: any, context?: any): FeatureGroup; + clearAllEventListeners(): FeatureGroup; + on(eventMap: any, context?: any): FeatureGroup; + off(eventMap?: any, context?: any): FeatureGroup; + } +} + +declare namespace L { + + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; + + export interface GeoJSONStatic extends ClassStatic { + /** + * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format + * to display on the map (you can alternatively add it later with addData method) + * and an options object. + */ + new(geojson?: any, options?: GeoJSONOptions): GeoJSON; + + /** + * Creates a layer from a given GeoJSON feature. + */ + geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; + + /** + * Creates a LatLng object from an array of 2 numbers (latitude, longitude) + * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted + * as (longitude, latitude). + */ + coordsToLatLng(coords: number[], reverse?: boolean): LatLng; + + /** + * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates + * array. levelsDeep specifies the nesting level (0 is for an array of points, + * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to + * true, the numbers will be interpreted as (longitude, latitude). + */ + coordsToLatLngs(coords: any[], levelsDeep?: number, reverse?: boolean): any[]; + } + export var GeoJSON: GeoJSONStatic; + + export interface GeoJSON extends FeatureGroup { + /** + * Adds a GeoJSON object to the layer. + */ + addData(data: any): boolean; + + /** + * Changes styles of GeoJSON vector layers with the given style function. + */ + setStyle(style: (featureData: any) => any): GeoJSON; + + /** + * Changes styles of GeoJSON vector layers with the given style options. + */ + setStyle(style: PathOptions): GeoJSON; + + /** + * Resets the the given vector layer's style to the original GeoJSON style, + * useful for resetting style after hover events. + */ + resetStyle(layer: Path): GeoJSON; + } +} + +declare namespace L { + export interface GeoJSONOptions { + /** + * Function that will be used for creating layers for GeoJSON points (if not + * specified, simple markers will be created). + */ + pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; + + /** + * Function that will be used to get style options for vector layers created + * for GeoJSON features. + */ + style?: (featureData: any) => any; + + /** + * Function that will be called on each created feature layer. Useful for attaching + * events and popups to features. + */ + onEachFeature?: (featureData: any, layer: ILayer) => void; + + /** + * Function that will be used to decide whether to show a feature or not. + */ + filter?: (featureData: any, layer: ILayer) => boolean; + + /** + * Function that will be used for converting GeoJSON coordinates to LatLng points + * (if not specified, coords will be assumed to be WGS84 � standard[longitude, latitude] + * values in degrees). + */ + coordsToLatLng?: (coords: any[]) => LatLng[]; + } +} + + + + +declare namespace L { + + /** + * Creates an icon instance with the given options. + */ + function icon(options: IconOptions): Icon; + + export interface IconStatic extends ClassStatic { + /** + * Creates an icon instance with the given options. + */ + new(options: IconOptions): Icon; + + Default: { + /** + * Creates a default icon instance with the given options. + */ + new(options?: IconOptions): Icon.Default; + + imagePath: string; + }; + } + export var Icon: IconStatic; + + export interface Icon { + } + + namespace Icon { + /** + * L.Icon.Default extends L.Icon and is the blue icon Leaflet uses + * for markers by default. + */ + export interface Default extends Icon { + } + } +} + +declare namespace L { + + export interface IconOptions { + + /** + * (required) The URL to the icon image (absolute or relative to your script + * path). + */ + iconUrl?: string; + + /** + * The URL to a retina sized version of the icon image (absolute or relative to + * your script path). Used for Retina screen devices. + */ + iconRetinaUrl?: string; + + /** + * Size of the icon image in pixels. + */ + iconSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the icon (relative to its top left corner). + * The icon will be aligned so that this point is at the marker's geographical + * location. Centered by default if size is specified, also can be set in CSS + * with negative margins. + */ + iconAnchor?: Point|[number, number]; + + /** + * The URL to the icon shadow image. If not specified, no shadow image will be + * created. + */ + shadowUrl?: string; + + /** + * The URL to the retina sized version of the icon shadow image. If not specified, + * no shadow image will be created. Used for Retina screen devices. + */ + shadowRetinaUrl?: string; + + /** + * Size of the shadow image in pixels. + */ + shadowSize?: Point|[number, number]; + + /** + * The coordinates of the "tip" of the shadow (relative to its top left corner) + * (the same as iconAnchor if not specified). + */ + shadowAnchor?: Point|[number, number]; + + /** + * The coordinates of the point from which popups will "open", relative to the + * icon anchor. + */ + popupAnchor?: Point|[number, number]; + + /** + * A custom class name to assign to both icon and shadow images. Empty by default. + */ + className?: string; + } +} + +declare namespace L { + + export interface IControl { + + /** + * Should contain code that creates all the neccessary DOM elements for the + * control, adds listeners on relevant map events, and returns the element + * containing the control. Called on map.addControl(control) or control.addTo(map). + */ + onAdd(map: Map): HTMLElement; + + /** + * Optional, should contain all clean up code (e.g. removes control's event + * listeners). Called on map.removeControl(control) or control.removeFrom(map). + * The control's DOM container is removed automatically. + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + + export interface ICRS { + + /** + * Projection that this CRS uses. + */ + projection: IProjection; + + /** + * Transformation that this CRS uses to turn projected coordinates into screen + * coordinates for a particular tile service. + */ + transformation: Transformation; + + /** + * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). + */ + code: string; + + /** + * Projects geographical coordinates on a given zoom into pixel coordinates. + */ + latLngToPoint(latlng: LatLng, zoom: number): Point; + + /** + * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom + * into geographical coordinates. + */ + pointToLatLng(point: Point, zoom: number): LatLng; + + /** + * Projects geographical coordinates into coordinates in units accepted + * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). + */ + project(latlng: LatLng): Point; + + /** + * Returns the scale used when transforming projected coordinates into pixel + * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for + * Mercator-based CRS. + */ + scale(zoom: number): number; + + /** + * Returns the size of the world in pixels for a particular zoom. + */ + getSize(zoom: number): Point; + + } +} + +declare namespace L { + + export interface IEventPowered { + + /** + * Adds a listener function (fn) to a particular event type of the object. You + * can optionally specify the context of the listener (object the this keyword + * will point to). You can also pass several space-separated types (e.g. 'click + * dblclick'). + */ + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * The same as above except the listener will only get fired once and then removed. + */ + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + /** + * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} + */ + addEventListener(eventMap: any, context?: any): T; + + /** + * Removes a previously added listener function. If no function is specified, + * it will remove all the listeners of that particular event from the object. + */ + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Removes a set of type/listener pairs. + */ + removeEventListener(eventMap?: any, context?: any): T; + + /** + * Returns true if a particular event type has some listeners attached to it. + */ + hasEventListeners(type: string): boolean; + + /** + * Fires an event of the specified type. You can optionally provide an data object + * — the first argument of the listener function will contain its properties. + */ + fireEvent(type: string, data?: any): T; + + /** + * Removes all listeners to all events on the object. + */ + clearAllEventListeners(): T; + + /** + * Alias to addEventListener. + */ + on(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to addEventListener. + */ + on(eventMap: any, context?: any): T; + + /** + * Alias to addOneTimeEventListener. + */ + once(type: string, fn: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; + + /** + * Alias to removeEventListener. + */ + off(eventMap?: any, context?: any): T; + + /** + * Alias to fireEvent. + */ + fire(type: string, data?: any): T; + } +} + +declare namespace L { + + export interface IHandler { + + /** + * Enables the handler. + */ + enable(): void; + + /** + * Disables the handler. + */ + disable(): void; + + /** + * Returns true if the handler is enabled. + */ + enabled(): boolean; + } + + export interface Handler { + initialize(map: Map): void; + } +} + +declare namespace L { + + export interface ILayer { + + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + namespace Mixin { + export interface LeafletMixinEvents extends IEventPowered { + } + + export var Events: LeafletMixinEvents; + } +} + +declare namespace L { + + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + function imageOverlay(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; + + export interface ImageOverlayStatic extends ClassStatic { + /** + * Instantiates an image overlay object given the URL of the image and the geographical + * bounds it is tied to. + */ + new(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; + } + export var ImageOverlay: ImageOverlayStatic; + + export interface ImageOverlay extends ILayer { + /** + * Adds the overlay to the map. + */ + addTo(map: Map): ImageOverlay; + + /** + * Sets the opacity of the overlay. + */ + setOpacity(opacity: number): ImageOverlay; + + /** + * Changes the URL of the image. + */ + setUrl(imageUrl: string): ImageOverlay; + + /** + * Brings the layer to the top of all overlays. + */ + bringToFront(): ImageOverlay; + + /** + * Brings the layer to the bottom of all overlays. + */ + bringToBack(): ImageOverlay; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + +declare namespace L { + + export interface ImageOverlayOptions { + + /** + * The opacity of the image overlay. + */ + opacity?: number; + } +} + +declare namespace L { + + export interface IProjection { + + /** + * Projects geographical coordinates into a 2D point. + */ + project(latlng: LatLng): Point; + + /** + * The inverse of project. Projects a 2D point into geographical location. + */ + unproject(point: Point): LatLng; + } +} + +declare namespace L { + + /** + * A constant that represents the Leaflet version in use. + */ + export var version: string; + + /** + * This method restores the L global variale to the original value it had + * before Leaflet inclusion, and returns the real Leaflet namespace. + */ + export function noConflict(): typeof L; +} + +declare namespace L { + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(latitude: number, longitude: number): LatLng; + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + function latLng(coords: LatLngExpression): LatLng; + + export interface LatLngStatic { + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + new(latitude: number, longitude: number): LatLng; + + /** + * Creates an object representing a geographical point with the given latitude + * and longitude. + */ + new(coords: LatLngExpression): LatLng; + + /** + * A multiplier for converting degrees into radians. + * + * Value: Math.PI / 180. + */ + DEG_TO_RAD: number; + + /** + * A multiplier for converting radians into degrees. + * + * Value: 180 / Math.PI. + */ + RAD_TO_DEG: number; + + /** + * Max margin of error for the equality check. + * + * Value: 1.0E-9. + */ + MAX_MARGIN: number; + } + export var LatLng: LatLngStatic; + + export interface LatLng { + /** + * Returns the distance (in meters) to the given LatLng calculated using the + * Haversine formula. See description on wikipedia + */ + distanceTo(otherLatlng: LatLngExpression): number; + + /** + * Returns true if the given LatLng point is at the same position (within a small + * margin of error). + */ + equals(otherLatlng: LatLngExpression): boolean; + + /** + * Returns a string representation of the point (for debugging purposes). + */ + toString(): string; + + /** + * Returns a new LatLng object with the longitude wrapped around left and right + * boundaries (-180 to 180 by default). + */ + wrap(left?: number, right?: number): LatLng; + + /** + * Latitude in degrees. + */ + lat: number; + + /** + * Longitude in degrees. + */ + lng: number; + } +} + +declare namespace L { + + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + function latLngBounds(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + function latLngBounds(latlngs: LatLngBoundsExpression): LatLngBounds; + + export interface LatLngBoundsStatic { + /** + * Creates a LatLngBounds object by defining south-west and north-east corners + * of the rectangle. + */ + new(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + + /** + * Creates a LatLngBounds object defined by the geographical points it contains. + * Very useful for zooming the map to fit a particular set of locations with fitBounds. + */ + new(latlngs: LatLngBoundsExpression): LatLngBounds; + } + export var LatLngBounds: LatLngBoundsStatic; + + export interface LatLngBounds { + /** + * Extends the bounds to contain the given point. + */ + extend(latlng: LatLngExpression): LatLngBounds; + + /** + * Extends the bounds to contain the given bounds. + */ + extend(latlng: LatLngBoundsExpression): LatLngBounds; + + /** + * Returns the south-west point of the bounds. + */ + getSouthWest(): LatLng; + + /** + * Returns the north-east point of the bounds. + */ + getNorthEast(): LatLng; + + /** + * Returns the north-west point of the bounds. + */ + getNorthWest(): LatLng; + + /** + * Returns the south-east point of the bounds. + */ + getSouthEast(): LatLng; + + /** + * Returns the west longitude in degrees of the bounds. + */ + getWest(): number; + + /** + * Returns the east longitude in degrees of the bounds. + */ + getEast(): number; + + /** + * Returns the north latitude in degrees of the bounds. + */ + getNorth(): number; + + /** + * Returns the south latitude in degrees of the bounds. + */ + getSouth(): number; + + /** + * Returns the center point of the bounds. + */ + getCenter(): LatLng; + + /** + * Returns true if the rectangle contains the given one. + */ + contains(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns true if the rectangle contains the given point. + */ + contains(latlng: LatLngExpression): boolean; + + /** + * Returns true if the rectangle intersects the given bounds. + */ + intersects(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns true if the rectangle is equivalent (within a small margin of error) + * to the given bounds. + */ + equals(otherBounds: LatLngBoundsExpression): boolean; + + /** + * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' + * format. Useful for sending requests to web services that return geo data. + */ + toBBoxString(): string; + + /** + * Returns bigger bounds created by extending the current bounds by a given + * percentage in each direction. + */ + pad(bufferRatio: number): LatLngBounds; + + /** + * Returns true if the bounds are properly initialized. + */ + isValid(): boolean; + + } +} + +declare namespace L { + + /** + * Create a layer group, optionally given an initial set of layers. + */ + function layerGroup(layers?: T[]): LayerGroup; + + + export interface LayerGroupStatic extends ClassStatic { + /** + * Create a layer group, optionally given an initial set of layers. + */ + new(layers?: T[]): LayerGroup; + } + export var LayerGroup: LayerGroupStatic; + + export interface LayerGroup extends ILayer { + /** + * Adds the group of layers to the map. + */ + addTo(map: Map): LayerGroup; + + /** + * Adds a given layer to the group. + */ + addLayer(layer: T): LayerGroup; + + /** + * Removes a given layer from the group. + */ + removeLayer(layer: T): LayerGroup; + + /** + * Removes a given layer of the given id from the group. + */ + removeLayer(id: string): LayerGroup; + + /** + * Returns true if the given layer is currently added to the group. + */ + hasLayer(layer: T): boolean; + + /** + * Returns the layer with the given id. + */ + getLayer(id: string): T; + + /** + * Returns an array of all the layers added to the group. + */ + getLayers(): T[]; + + /** + * Removes all the layers from the group. + */ + clearLayers(): LayerGroup; + + /** + * Iterates over the layers of the group, optionally specifying context of + * the iterator function. + */ + eachLayer(fn: (layer: T) => void, context?: any): LayerGroup; + + /** + * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). + * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s + */ + toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + } +} + + +declare namespace L { + + export interface LayersOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * + * Default value: 'topright'. + */ + position?: PositionString; + + /** + * If true, the control will be collapsed into an icon and expanded on mouse hover + * or touch. + * + * Default value: true. + */ + collapsed?: boolean; + + /** + * If true, the control will assign zIndexes in increasing order to all of its + * layers so that the order is preserved when switching them on/off. + * + * Default value: true. + */ + autoZIndex?: boolean; + + } +} + +declare namespace L { + + export interface LeafletErrorEvent extends LeafletEvent { + + /** + * Error message. + */ + message: string; + + /** + * Error code (if applicable). + */ + code: number; + } +} + +declare namespace L { + + export interface LeafletEvent { + + /** + * The event type (e.g. 'click'). + */ + type: string; + + /** + * The object that fired the event. + */ + target: any; + } +} + +declare namespace L { + + export interface LeafletGeoJSONEvent extends LeafletEvent { + + /** + * The layer for the GeoJSON feature that is being added to the map. + */ + layer: ILayer; + + /** + * GeoJSON properties of the feature. + */ + properties: any; + + /** + * GeoJSON geometry type of the feature. + */ + geometryType: string; + + /** + * GeoJSON ID of the feature (if present). + */ + id: string; + } +} + +declare namespace L { + + export interface LeafletLayerEvent extends LeafletEvent { + + /** + * The layer that was added or removed. + */ + layer: ILayer; + } +} + +declare namespace L { + + export interface LeafletLayersControlEvent extends LeafletEvent { + + /** + * The layer that was added or removed. + */ + layer: ILayer; + + /** + * The name of the layer that was added or removed. + */ + name: string; + } +} + +declare namespace L { + + export interface LeafletLocationEvent extends LeafletEvent { + + /** + * Detected geographical location of the user. + */ + latlng: LatLng; + + /** + * Geographical bounds of the area user is located in (with respect to the accuracy + * of location). + */ + bounds: LatLngBounds; + + /** + * Accuracy of location in meters. + */ + accuracy: number; + + /** + * Height of the position above the WGS84 ellipsoid in meters. + */ + altitude: number; + + /** + * Accuracy of altitude in meters. + */ + altitudeAccuracy: number; + + /** + * The direction of travel in degrees counting clockwise from true North. + */ + heading: number; + + /** + * Current velocity in meters per second. + */ + speed: number; + + /** + * The time when the position was acquired. + */ + timestamp: number; + + } +} + +declare namespace L { + + export interface LeafletMouseEvent extends LeafletEvent { + + /** + * The geographical point where the mouse event occured. + */ + latlng: LatLng; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map layer. + */ + layerPoint: Point; + + /** + * Pixel coordinates of the point where the mouse event occured relative to + * the map сontainer. + */ + containerPoint: Point; + + /** + * The original DOM mouse event fired by the browser. + */ + originalEvent: MouseEvent; + } +} + +declare namespace L { + + export interface LeafletPopupEvent extends LeafletEvent { + + /** + * The popup that was opened or closed. + */ + popup: Popup; + } +} + +declare namespace L { + + export interface LeafletDragEndEvent extends LeafletEvent { + + /** + * The distance in pixels the draggable element was moved by. + */ + distance: number; + } +} + +declare namespace L { + + export interface LeafletResizeEvent extends LeafletEvent { + + /** + * The old size before resize event. + */ + oldSize: Point; + + /** + * The new size after the resize event. + */ + newSize: Point; + } +} + +declare namespace L { + + export interface LeafletTileEvent extends LeafletEvent { + + /** + * The tile element (image). + */ + tile: HTMLElement; + + /** + * The source URL of the tile. + */ + url: string; + } +} + +declare namespace L { + + namespace LineUtil { + + /** + * Dramatically reduces the number of points in a polyline while retaining + * its shape and returns a new array of simplified points. Used for a huge performance + * boost when processing/displaying Leaflet polylines for each zoom level + * and also reducing visual noise. tolerance affects the amount of simplification + * (lesser value means higher quality but slower and with more points). Also + * released as a separated micro-library Simplify.js. + */ + export function simplify(points: Point[], tolerance: number): Point[]; + + /** + * Returns the distance between point p and segment p1 to p2. + */ + export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; + + /** + * Returns the closest point from a point p on a segment p1 to p2. + */ + export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; + + /** + * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show + * polyline points that are on the screen or near, increasing performance. Returns + * either false or a length-2 array of clipped points. + */ + export function clipSegment(a: Point, b: Point, bounds: Bounds): Point[] | boolean; + + } +} + +declare namespace L { + + export interface LocateOptions { + + /** + * If true, starts continous watching of location changes (instead of detecting + * it once) using W3C watchPosition method. You can later stop watching using + * map.stopLocate() method. + * + * Default value: false. + */ + watch?: boolean; + + /** + * If true, automatically sets the map view to the user location with respect + * to detection accuracy, or to world view if geolocation failed. + * + * Default value: false. + */ + setView?: boolean; + + /** + * The maximum zoom for automatic view setting when using `setView` option. + * + * Default value: Infinity. + */ + maxZoom?: number; + + /** + * Number of millisecond to wait for a response from geolocation before firing + * a locationerror event. + * + * Default value: 10000. + */ + timeout?: number; + + /** + * Maximum age of detected location. If less than this amount of milliseconds + * passed since last geolocation response, locate will return a cached location. + * + * Default value: 0. + */ + maximumAge?: number; + + /** + * Enables high accuracy, see description in the W3C spec. + * + * Default value: false. + */ + enableHighAccuracy?: boolean; + } +} + +declare namespace L { + + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + */ + function map(id: HTMLElement, options?: Map.MapOptions): Map; + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + */ + function map(id: string, options?: Map.MapOptions): Map; + + + export interface MapStatic extends ClassStatic { + /** + * Instantiates a map object given a div element and optionally an + * object literal with map options described below. + * + * @constructor + */ + new(id: HTMLElement, options?: Map.MapOptions): Map; + + /** + * Instantiates a map object given a div element id and optionally an + * object literal with map options described below. + * + * @constructor + */ + new(id: string, options?: Map.MapOptions): Map; + } + export var Map: MapStatic; + + export interface Map extends IEventPowered { + // Methods for Modifying Map State + + /** + * Sets the view of the map (geographical center and zoom) with the given + * animation options. + */ + setView(center: LatLngExpression, zoom?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Sets the zoom of the map. + */ + setZoom(zoom: number, options?: Map.ZoomPanOptions): Map; + + /** + * Increases the zoom of the map by delta (1 by default). + */ + zoomIn(delta?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Decreases the zoom of the map by delta (1 by default). + */ + zoomOut(delta?: number, options?: Map.ZoomPanOptions): Map; + + /** + * Zooms the map while keeping a specified point on the map stationary + * (e.g. used internally for scroll zoom and double-click zoom). + */ + setZoomAround(latlng: LatLngExpression, zoom: number, options?: Map.ZoomPanOptions): Map; + + /** + * Sets a map view that contains the given geographical bounds with the maximum + * zoom level possible. + */ + fitBounds(bounds: LatLngBounds, options?: Map.FitBoundsOptions): Map; + + /** + * Sets a map view that mostly contains the whole world with the maximum zoom + * level possible. + */ + fitWorld(options?: Map.FitBoundsOptions): Map; + + /** + * Pans the map to a given center. Makes an animated pan if new center is not more + * than one screen away from the current one. + */ + panTo(latlng: LatLngExpression, options?: PanOptions): Map; + + /** + * Pans the map to the closest view that would lie inside the given bounds (if + * it's not already). + */ + panInsideBounds(bounds: LatLngBounds): Map; + + /** + * Pans the map by a given number of pixels (animated). + */ + panBy(point: Point, options?: PanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + * If options.pan is false, panning will not occur. + */ + invalidateSize(options: Map.ZoomPanOptions): Map; + + /** + * Checks if the map container size changed and updates the map if so — call it + * after you've changed the map size dynamically, also animating pan by default. + */ + invalidateSize(animate: boolean): Map; + + /** + * Restricts the map view to the given bounds (see map maxBounds option), + * passing the given animation options through to `setView`, if required. + */ + setMaxBounds(bounds: LatLngBounds, options?: Map.ZoomPanOptions): Map; + + /** + * Tries to locate the user using Geolocation API, firing locationfound event + * with location data on success or locationerror event on failure, and optionally + * sets the map view to the user location with respect to detection accuracy + * (or to the world view if geolocation failed). See Locate options for more + * details. + */ + locate(options?: LocateOptions): Map; + + /** + * Stops watching location previously initiated by map.locate({watch: true}) + * and aborts resetting the map view if map.locate was called with {setView: true}. + */ + stopLocate(): Map; + + /** + * Destroys the map and clears all related event listeners. + */ + remove(): Map; + + // Methods for Getting Map State + + /** + * Returns the geographical center of the map view. + */ + getCenter(): LatLng; + + /** + * Returns the current zoom of the map view. + */ + getZoom(): number; + + /** + * Returns the minimum zoom level of the map. + */ + getMinZoom(): number; + + /** + * Returns the maximum zoom level of the map. + */ + getMaxZoom(): number; + + /** + * Returns the LatLngBounds of the current map view. + */ + getBounds(): LatLngBounds; + + /** + * Returns the maximum zoom level on which the given bounds fit to the map view + * in its entirety. If inside (optional) is set to true, the method instead returns + * the minimum zoom level on which the map view fits into the given bounds in its + * entirety. + */ + getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; + + /** + * Returns the current size of the map container. + */ + getSize(): Point; + + /** + * Returns the bounds of the current map view in projected pixel coordinates + * (sometimes useful in layer and overlay implementations). + */ + getPixelBounds(): Bounds; + + /** + * Returns the projected pixel coordinates of the top left point of the map layer + * (useful in custom layer and overlay implementations). + */ + getPixelOrigin(): Point; + + // Methods for Layers and Controls + + /** + * Adds the given layer to the map. If optional insertAtTheBottom is set to true, + * the layer is inserted under all others (useful when switching base tile layers). + */ + addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; + + /** + * Removes the given layer from the map. + */ + removeLayer(layer: ILayer): Map; + + /** + * Returns true if the given layer is currently added to the map. + */ + hasLayer(layer: ILayer): boolean; + + /** + * Opens the specified popup while closing the previously opened (to make sure + * only one is opened at one time for usability). + */ + openPopup(popup: Popup): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(html: string, latlng: LatLngExpression, options?: PopupOptions): Map; + + /** + * Creates a popup with the specified options and opens it in the given point + * on a map. + */ + openPopup(el: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): Map; + + /** + * Closes the popup previously opened with openPopup (or the given one). + */ + closePopup(popup?: Popup): Map; + + /** + * Adds the given control to the map. + */ + addControl(control: IControl): Map; + + /** + * Removes the given control from the map. + */ + removeControl(control: IControl): Map; + + // Conversion Methods + + /** + * Returns the map layer point that corresponds to the given geographical coordinates + * (useful for placing overlays on the map). + */ + latLngToLayerPoint(latlng: LatLngExpression): Point; + + /** + * Returns the geographical coordinates of a given map layer point. + */ + layerPointToLatLng(point: Point): LatLng; + + /** + * Converts the point relative to the map container to a point relative to the + * map layer. + */ + containerPointToLayerPoint(point: Point): Point; + + /** + * Converts the point relative to the map layer to a point relative to the map + * container. + */ + layerPointToContainerPoint(point: Point): Point; + + /** + * Returns the map container point that corresponds to the given geographical + * coordinates. + */ + latLngToContainerPoint(latlng: LatLngExpression): Point; + + /** + * Returns the geographical coordinates of a given map container point. + */ + containerPointToLatLng(point: Point): LatLng; + + /** + * Projects the given geographical coordinates to absolute pixel coordinates + * for the given zoom level (current zoom level by default). + */ + project(latlng: LatLngExpression, zoom?: number): Point; + + /** + * Projects the given absolute pixel coordinates to geographical coordinates + * for the given zoom level (current zoom level by default). + */ + unproject(point: Point, zoom?: number): LatLng; + + /** + * Returns the pixel coordinates of a mouse click (relative to the top left corner + * of the map) given its event object. + */ + mouseEventToContainerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the pixel coordinates of a mouse click relative to the map layer given + * its event object. + */ + mouseEventToLayerPoint(event: LeafletMouseEvent): Point; + + /** + * Returns the geographical coordinates of the point the mouse clicked on given + * the click's event object. + */ + mouseEventToLatLng(event: LeafletMouseEvent): LatLng; + + // Other Methods + + /** + * Returns the container element of the map. + */ + getContainer(): HTMLElement; + + /** + * Returns an object with different map panes (to render overlays in). + */ + getPanes(): MapPanes; + + // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? + /** + * Runs the given callback when the map gets initialized with a place and zoom, + * or immediately if it happened already, optionally passing a function context. + */ + whenReady(fn: (map: Map) => void, context?: any): Map; + + // Properties + + /** + * Map dragging handler (by both mouse and touch). + */ + dragging: IHandler; + + /** + * Touch zoom handler. + */ + touchZoom: IHandler; + + /** + * Double click zoom handler. + */ + doubleClickZoom: IHandler; + + /** + * Scroll wheel zoom handler. + */ + scrollWheelZoom: IHandler; + + /** + * Box (shift-drag with mouse) zoom handler. + */ + boxZoom: IHandler; + + /** + * Keyboard navigation handler. + */ + keyboard: IHandler; + + /** + * Mobile touch hacks (quick tap and touch hold) handler. + */ + tap: IHandler; + + /** + * Zoom control. + */ + zoomControl: Control.Zoom; + + /** + * Attribution control. + */ + attributionControl: Control.Attribution; + + /** + * Map state options + */ + options: Map.MapOptions; + + /** + * Iterates over the layers of the map, optionally specifying context + * of the iterator function. + */ + eachLayer(fn: (layer: ILayer) => void, context?: any): Map; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Map; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; + fire(type: string, data?: any): Map;addEventListener(eventMap: any, context?: any): Map; + removeEventListener(eventMap?: any, context?: any): Map; + clearAllEventListeners(): Map; + on(eventMap: any, context?: any): Map; + off(eventMap?: any, context?: any): Map; + } +} + +declare namespace L.Map { + + export interface MapOptions { + + // Map State Options + + /** + * Initial geographical center of the map. + */ + center?: LatLng; + + /** + * Initial map zoom. + */ + zoom?: number; + + /** + * Layers that will be added to the map initially. + */ + layers?: ILayer[]; + + /** + * Minimum zoom level of the map. Overrides any minZoom set on map layers. + */ + minZoom?: number; + + /** + * Maximum zoom level of the map. This overrides any maxZoom set on map layers. + */ + maxZoom?: number; + + /** + * When this option is set, the map restricts the view to the given geographical + * bounds, bouncing the user back when he tries to pan outside the view, and also + * not allowing to zoom out to a view that's larger than the given bounds (depending + * on the map size). To set the restriction dynamically, use setMaxBounds method + */ + maxBounds?: LatLngBounds; + + /** + * Coordinate Reference System to use. Don't change this if you're not sure + * what it means. + * + * Default value: L.CRS.EPSG3857. + */ + crs?: ICRS; + + // Interaction Options + + /** + * Whether the map be draggable with mouse/touch or not. + * + * Default value: true. + */ + dragging?: boolean; + + /** + * Whether the map can be zoomed by touch-dragging with two fingers. + * + * Default value: true. + */ + touchZoom?: boolean; + + /** + * Whether the map can be zoomed by using the mouse wheel. + * If passed 'center', it will zoom to the center of the view regardless of + * where the mouse was. + * + * Default value: true. + */ + scrollWheelZoom?: boolean; + + /** + * Whether the map can be zoomed in by double clicking on it and zoomed out + * by double clicking while holding shift. + * If passed 'center', double-click zoom will zoom to the center of the view + * regardless of where the mouse was. + * + * Default value: true. + */ + doubleClickZoom?: boolean; + + /** + * Whether the map can be zoomed to a rectangular area specified by dragging + * the mouse while pressing shift. + * + * Default value: true. + */ + boxZoom?: boolean; + + /** + * Enables mobile hacks for supporting instant taps (fixing 200ms click delay + * on iOS/Android) and touch holds (fired as contextmenu events). + * + * Default value: true. + */ + tap?: boolean; + + /** + * The max number of pixels a user can shift his finger during touch for it + * to be considered a valid tap. + * + * Default value: 15. + */ + tapTolerance?: number; + + /** + * Whether the map automatically handles browser window resize to update itself. + * + * Default value: true. + */ + trackResize?: boolean; + + /** + * With this option enabled, the map tracks when you pan to another "copy" of + * the world and seamlessly jumps to the original one so that all overlays like + * markers and vector layers are still visible. + * + * Default value: false. + */ + worldCopyJump?: boolean; + + /** + * Set it to false if you don't want popups to close when user clicks the map. + * + * Default value: true. + */ + closePopupOnClick?: boolean; + + // Keyboard Navigation Options + + /** + * Makes the map focusable and allows users to navigate the map with keyboard + * arrows and +/- keys. + * + * Default value: true. + */ + keyboard?: boolean; + + /** + * Amount of pixels to pan when pressing an arrow key. + * + * Default value: 80. + */ + keyboardPanOffset?: number; + + /** + * Number of zoom levels to change when pressing + or - key. + * + * Default value: 1. + */ + keyboardZoomOffset?: number; + + // Panning Inertia Options + + /** + * If enabled, panning of the map will have an inertia effect where the map builds + * momentum while dragging and continues moving in the same direction for some + * time. Feels especially nice on touch devices. + * + * Default value: true. + */ + inertia?: boolean; + + /** + * The rate with which the inertial movement slows down, in pixels/second2. + * + * Default value: 3000. + */ + inertiaDeceleration?: number; + + /** + * Max speed of the inertial movement, in pixels/second. + * + * Default value: 1500. + */ + inertiaMaxSpeed?: number; + + /** + * Amount of milliseconds that should pass between stopping the movement and + * releasing the mouse or touch to prevent inertial movement. + * + * Default value: 32 for touch devices and 14 for the rest. + */ + inertiaThreshold?: number; + + // Control options + + /** + * Whether the zoom control is added to the map by default. + * + * Default value: true. + */ + zoomControl?: boolean; + + /** + * Whether the attribution control is added to the map by default. + * + * Default value: true. + */ + attributionControl?: boolean; + + // Animation options + + /** + * Whether the tile fade animation is enabled. By default it's enabled in all + * browsers that support CSS3 Transitions except Android. + */ + fadeAnimation?: boolean; + + /** + * Whether the tile zoom animation is enabled. By default it's enabled in all + * browsers that support CSS3 Transitions except Android. + */ + zoomAnimation?: boolean; + + /** + * Won't animate zoom if the zoom difference exceeds this value. + * + * Default value: 4. + */ + zoomAnimationThreshold?: number; + + /** + * Whether markers animate their zoom with the zoom animation, if disabled + * they will disappear for the length of the animation. By default it's enabled + * in all browsers that support CSS3 Transitions except Android. + */ + markerZoomAnimation?: boolean; + + /** + * Set it to false if you don't want the map to zoom beyond min/max zoom + * and then bounce back when pinch-zooming. + * + * Default value: true. + */ + bounceAtZoomLimits?: boolean; + } + + export interface ZoomOptions { + /** + * If not specified, zoom animation will happen if the zoom origin is inside the current view. + * If true, the map will attempt animating zoom disregarding where zoom origin is. + * Setting false will make it always reset the view completely without animation. + */ + animate?: boolean; + } + + export interface ZoomPanOptions { + + /** + * If true, the map view will be completely reset (without any animations). + * + * Default value: false. + */ + reset?: boolean; + + /** + * Sets the options for the panning (without the zoom change) if it occurs. + */ + pan?: PanOptions; + + /** + * Sets the options for the zoom change if it occurs. + */ + zoom?: ZoomOptions; + + /** + * An equivalent of passing animate to both zoom and pan options (see below). + */ + animate?: boolean; + + /** + * If true, it will delay moveend event so that it doesn't happen many times in a row. + */ + debounceMoveend?: boolean; + + /** + * Duration of animated panning, in seconds. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). + * 1.0 means linear animation, the less the more bowed the curve. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + */ + noMoveStart?: boolean; + } + + export interface FitBoundsOptions extends ZoomPanOptions { + + /** + * Sets the amount of padding in the top left corner of a map container that + * shouldn't be accounted for when setting the view to fit bounds. Useful if + * you have some control overlays on the map like a sidebar and you don't + * want them to obscure objects you're zooming to. + * + * Default value: [0, 0]. + */ + paddingTopLeft?: Point; + + /** + * The same for bottom right corner of the map. + * + * Default value: [0, 0]. + */ + paddingBottomRight?: Point; + + /** + * Equivalent of setting both top left and bottom right padding to the same value. + * + * Default value: [0, 0]. + */ + padding?: Point; + + /** + * The maximum possible zoom to use. + * + * Default value: null + */ + maxZoom?: number; + } +} + +declare namespace L { + + export interface MapPanes { + + /** + * Pane that contains all other map panes. + */ + mapPane: HTMLElement; + + /** + * Pane for tile layers. + */ + tilePane: HTMLElement; + + /** + * Pane that contains all the panes except tile pane. + */ + objectsPane: HTMLElement; + + /** + * Pane for overlay shadows (e.g. marker shadows). + */ + shadowPane: HTMLElement; + + /** + * Pane for overlays like polylines and polygons. + */ + overlayPane: HTMLElement; + + /** + * Pane for marker icons. + */ + markerPane: HTMLElement; + + /** + * Pane for popups. + */ + popupPane: HTMLElement; + } +} + +declare namespace L { + + /** + * Instantiates a Marker object given a geographical point and optionally + * an options object. + */ + function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; + + var Marker: { + /** + * Instantiates a Marker object given a geographical point and optionally + * an options object. + */ + new(latlng: LatLngExpression, options?: MarkerOptions): Marker; + }; + + export interface Marker extends ILayer, IEventPowered { + /** + * Adds the marker to the map. + */ + addTo(map: Map): Marker; + + /** + * Returns the current geographical position of the marker. + */ + getLatLng(): LatLng; + + /** + * Changes the marker position to the given point. + */ + setLatLng(latlng: LatLngExpression): Marker; + + /** + * Changes the marker icon. + */ + setIcon(icon: Icon): Marker; + + /** + * Changes the zIndex offset of the marker. + */ + setZIndexOffset(offset: number): Marker; + + /** + * Changes the opacity of the marker. + */ + setOpacity(opacity: number): Marker; + + /** + * Updates the marker position, useful if coordinates of its latLng object + * were changed directly. + */ + update(): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(html: string, options?: PopupOptions): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Marker; + + /** + * Binds a popup with a particular HTML content to a click on this marker. You + * can also open the bound popup with the Marker openPopup method. + */ + bindPopup(popup: Popup, options?: PopupOptions): Marker; + + /** + * Unbinds the popup previously bound to the marker with bindPopup. + */ + unbindPopup(): Marker; + + /** + * Opens the popup previously bound by the bindPopup method. + */ + openPopup(): Marker; + + /** + * Returns the popup previously bound by the bindPopup method. + */ + getPopup(): Popup; + + /** + * Closes the bound popup of the marker if it's opened. + */ + closePopup(): Marker; + + /** + * Toggles the popup previously bound by the bindPopup method. + */ + togglePopup(): Marker; + + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(html: string, options?: PopupOptions): Marker; + + /** + * Sets an HTML content of the popup of this marker. + */ + setPopupContent(el: HTMLElement, options?: PopupOptions): Marker; + + /** + * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). + */ + toGeoJSON(): GeoJSON.Feature; + + /** + * Marker dragging handler (by both mouse and touch). + */ + dragging: IHandler; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Marker; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; + fire(type: string, data?: any): Marker; + addEventListener(eventMap: any, context?: any): Marker; + removeEventListener(eventMap?: any, context?: any): Marker; + clearAllEventListeners(): Marker; + on(eventMap: any, context?: any): Marker; + off(eventMap?: any, context?: any): Marker; + } +} + +declare namespace L { + + export interface MarkerOptions { + + /** + * Icon class to use for rendering the marker. See Icon documentation for details + * on how to customize the marker icon. + * + * Default value: new L.Icon.Default(). + */ + icon?: Icon; + + /** + * If false, the marker will not emit mouse events and will act as a part of the + * underlying map. + * + * Default value: true. + */ + clickable?: boolean; + + /** + * Whether the marker is draggable with mouse/touch or not. + * + * Default value: false. + */ + draggable?: boolean; + + /** + * Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. + * + * Default value: true. + */ + keyboard?: boolean; + + /** + * Text for the browser tooltip that appear on marker hover (no tooltip by default). + * + * Default value: ''. + */ + title?: string; + + /** + * Text for the alt attribute of the icon image (useful for accessibility). + * + * Default value: ''. + */ + alt?: string; + + /** + * By default, marker images zIndex is set automatically based on its latitude. + * You this option if you want to put the marker on top of all others (or below), + * specifying a high value like 1000 (or high negative value, respectively). + * + * Default value: 0. + */ + zIndexOffset?: number; + + /** + * The opacity of the marker. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * If true, the marker will get on top of others when you hover the mouse over it. + * + * Default value: false. + */ + riseOnHover?: boolean; + + /** + * The z-index offset used for the riseOnHover feature. + * + * Default value: 250. + */ + riseOffset?: number; + } +} + +declare namespace L { + + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + + export interface MultiPolygonStatic extends ClassStatic { + /** + * Instantiates a multi-polyline object given an array of latlngs arrays (one + * for each individual polygon) and optionally an options object (the same + * as for MultiPolyline). + */ + new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + } + export var MultiPolygon: MultiPolygonStatic; + + export interface MultiPolygon extends FeatureGroup { + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolygon; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolygon; + + /** + * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). + */ + toGeoJSON(): GeoJSON.Feature; + } +} + +declare namespace L { + + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; + + export interface MultiPolylineStatic extends ClassStatic { + /** + * Instantiates a multi-polyline object given an array of arrays of geographical + * points (one for each individual polyline) and optionally an options object. + */ + new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; + } + export var MultiPolyline: MultiPolylineStatic; + + export interface MultiPolyline extends FeatureGroup { + /** + * Replace all polygons and their paths with the given array of arrays + * of geographical points. + */ + setLatLngs(latlngs: LatLng[][]): MultiPolyline; + + /** + * Returns an array of arrays of geographical points in each polygon. + */ + getLatLngs(): LatLng[][]; + + /** + * Opens the popup previously bound by bindPopup. + */ + openPopup(): MultiPolyline; + + /** + * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). + */ + toGeoJSON(): GeoJSON.Feature; + } +} + +declare namespace L { + + export interface PanOptions { + + /** + * If true, panning will always be animated if possible. If false, it will not + * animate panning, either resetting the map view if panning more than a screen + * away, or just setting a new offset for the map pane (except for `panBy` + * which always does the latter). + */ + animate?: boolean; + + /** + * Duration of animated panning. + * + * Default value: 0.25. + */ + duration?: number; + + /** + * The curvature factor of panning animation easing (third parameter of the Cubic + * Bezier curve). 1.0 means linear animation, the less the more bowed the curve. + * + * Default value: 0.25. + */ + easeLinearity?: number; + + /** + * If true, panning won't fire movestart event on start (used internally for panning inertia). + * + * Default value: false. + */ + noMoveStart?: boolean; + } +} + +declare namespace L { + + export interface Path extends ILayer, IEventPowered { + + /** + * Adds the layer to the map. + */ + addTo(map: Map): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(html: string, options?: PopupOptions): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(el: HTMLElement, options?: PopupOptions): Path; + + /** + * Binds a popup with a particular HTML content to a click on this path. + */ + bindPopup(popup: Popup, options?: PopupOptions): Path; + + /** + * Unbinds the popup previously bound to the path with bindPopup. + */ + unbindPopup(): Path; + + /** + * Opens the popup previously bound by the bindPopup method in the given point, + * or in one of the path's points if not specified. + */ + openPopup(latlng?: LatLngExpression): Path; + + /** + * Closes the path's bound popup if it is opened. + */ + closePopup(): Path; + + /** + * Changes the appearance of a Path based on the options in the Path options object. + */ + setStyle(object: PathOptions): Path; + + /** + * Returns the LatLngBounds of the path. + */ + getBounds(): LatLngBounds; + + /** + * Brings the layer to the top of all path layers. + */ + bringToFront(): Path; + + /** + * Brings the layer to the bottom of all path layers. + */ + bringToBack(): Path; + + /** + * Redraws the layer. Sometimes useful after you changed the coordinates that + * the path uses. + */ + redraw(): Path; + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): Path; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; + fire(type: string, data?: any): Path; + addEventListener(eventMap: any, context?: any): Path; + removeEventListener(eventMap?: any, context?: any): Path; + clearAllEventListeners(): Path; + on(eventMap: any, context?: any): Path; + off(eventMap?: any, context?: any): Path; + } + + export namespace Path { + /** + * True if SVG is used for vector rendering (true for most modern browsers). + */ + export var SVG: boolean; + + /** + * True if VML is used for vector rendering (IE 6-8). + */ + export var VML: boolean; + + /** + * True if Canvas is used for vector rendering (Android 2). You can also force + * this by setting global variable L_PREFER_CANVAS to true before the Leaflet + * include on your page — sometimes it can increase performance dramatically + * when rendering thousands of circle markers, but currently suffers from + * a bug that causes removing such layers to be extremely slow. + */ + export var CANVAS: boolean; + + /** + * How much to extend the clip area around the map view (relative to its size, + * e.g. 0.5 is half the screen in each direction). Smaller values mean that you + * will see clipped ends of paths while you're dragging the map, and bigger values + * decrease drawing performance. + */ + export var CLIP_PADDING: number; + } +} + +declare namespace L { + + export interface PathOptions { + + /** + * Whether to draw stroke along the path. Set it to false to disable borders on + * polygons or circles. + * + * Default value: true. + */ + stroke?: boolean; + + /** + * Stroke color. + * + * Default value: '#03f'. + */ + color?: string; + + /** + * Stroke width in pixels. + * + * Default value: 5. + */ + weight?: number; + + /** + * Stroke opacity. + * + * Default value: 0.5. + */ + opacity?: number; + + /** + * Whether to fill the path with color. Set it to false to disable filling on polygons + * or circles. + */ + fill?: boolean; + + /** + * Fill color. + * + * Default value: same as color. + */ + fillColor?: string; + + /** + * Fill opacity. + * + * Default value: 0.2. + */ + fillOpacity?: number; + + /** + * A string that defines the stroke dash pattern. Doesn't work on canvas-powered + * layers (e.g. Android 2). + */ + dashArray?: string; + + /** + * A string that defines shape to be used at the end of the stroke. + * + * Default: null. + */ + lineCap?: string; + + /** + * A string that defines shape to be used at the corners of the stroke. + * + * Default: null. + */ + lineJoin?: string; + + /** + * If false, the vector will not emit mouse events and will act as a part of the + * underlying map. + * + * Default value: true. + */ + clickable?: boolean; + + /** + * Sets the pointer-events attribute on the path if SVG backend is used. + */ + pointerEvents?: string; + + /** + * Custom class name set on an element. + * + * Default value: ''. + */ + className?: string; + + /** + * Sets the radius of a circle marker. + */ + radius?: number; + + } +} + +declare namespace L { + + /** + * Creates a Point object with the given x and y coordinates. If optional round + * is set to true, rounds the x and y values. + */ + function point(x: number, y: number, round?: boolean): Point; + + export interface PointStatic { + /** + * Creates a Point object with the given x and y coordinates. If optional round + * is set to true, rounds the x and y values. + */ + new(x: number, y: number, round?: boolean): Point; + } + export var Point: PointStatic; + + export interface Point { + /** + * Returns the result of addition of the current and the given points. + */ + add(otherPoint: Point): Point; + + /** + * Returns the result of subtraction of the given point from the current. + */ + subtract(otherPoint: Point): Point; + + /** + * Returns the result of multiplication of the current point by the given number. + */ + multiplyBy(number: number): Point; + + /** + * Returns the result of division of the current point by the given number. If + * optional round is set to true, returns a rounded result. + */ + divideBy(number: number, round?: boolean): Point; + + /** + * Returns the distance between the current and the given points. + */ + distanceTo(otherPoint: Point): number; + + /** + * Returns a copy of the current point. + */ + clone(): Point; + + /** + * Returns a copy of the current point with rounded coordinates. + */ + round(): Point; + + /** + * Returns true if the given point has the same coordinates. + */ + equals(otherPoint: Point): boolean; + + /** + * Returns a string representation of the point for debugging purposes. + */ + toString(): string; + + /** + * The x coordinate. + */ + x: number; + + /** + * The y coordinate. + */ + y: number; + } +} + +declare namespace L { + + /** + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. + */ + function polygon(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; + + + export interface PolygonStatic extends ClassStatic { + /** + * Instantiates a polygon object given an array of geographical points and + * optionally an options object (the same as for Polyline). You can also create + * a polygon with holes by passing an array of arrays of latlngs, with the first + * latlngs array representing the exterior ring while the remaining represent + * the holes inside. + */ + new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; + } + export var Polygon: PolygonStatic; + + export interface Polygon extends Polyline { + } +} + +declare namespace L { + + /** + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. + */ + function polyline(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; + + export interface PolylineStatic extends ClassStatic { + /** + * Instantiates a polyline object given an array of geographical points and + * optionally an options object. + */ + new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; + } + export var Polyline: PolylineStatic; + + export interface Polyline extends Path { + /** + * Adds a given point to the polyline. + */ + addLatLng(latlng: LatLngExpression): Polyline; + + /** + * Replaces all the points in the polyline with the given array of geographical + * points. + */ + setLatLngs(latlngs: LatLngBoundsExpression): Polyline; + + /** + * Returns an array of the points in the path. + */ + getLatLngs(): LatLng[]; + + /** + * Allows adding, removing or replacing points in the polyline. Syntax is the + * same as in Array#splice. Returns the array of removed points (if any). + */ + spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; + + /** + * Returns the LatLngBounds of the polyline. + */ + getBounds(): LatLngBounds; + + /** + * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). + */ + toGeoJSON(): GeoJSON.Feature; + } +} + +declare namespace L { + + export interface PolylineOptions extends PathOptions { + + /** + * How much to simplify the polyline on each zoom level. More means better performance + * and smoother look, and less means more accurate representation. + * + * Default value: 1.0. + */ + smoothFactor?: number; + + /** + * Disabled polyline clipping. + * + * Default value: false. + */ + noClip?: boolean; + } +} + +declare namespace L { + + namespace PolyUtil { + + /** + * Clips the polygon geometry defined by the given points by rectangular bounds. + * Used by Leaflet to only show polygon points that are on the screen or near, + * increasing performance. Note that polygon points needs different algorithm + * for clipping than polyline, so there's a seperate method for it. + */ + export function clipPolygon(points: Point[], bounds: Bounds): Point[]; + } +} + +declare namespace L { + + /** + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. + */ + function popup(options?: PopupOptions, source?: any): Popup; + + export interface PopupStatic extends ClassStatic { + /** + * Instantiates a Popup object given an optional options object that describes + * its appearance and location and an optional object that is used to tag the + * popup with a reference to the source object to which it refers. + */ + new(options?: PopupOptions, source?: any): Popup; + } + export var Popup: PopupStatic; + + export interface Popup extends ILayer { + /** + * Adds the popup to the map. + */ + addTo(map: Map): Popup; + + /** + * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). + */ + openOn(map: Map): Popup; + + /** + * Sets the geographical point where the popup will open. + */ + setLatLng(latlng: LatLngExpression): Popup; + + /** + * Returns the geographical point of popup. + */ + getLatLng(): LatLng; + + /** + * Sets the HTML content of the popup. + */ + setContent(html: string): Popup; + + /** + * Sets the HTML content of the popup. + */ + setContent(el: HTMLElement): Popup; + + /** + * Returns the content of the popup. + */ + getContent(): HTMLElement; + //getContent(): string; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + /** + * Updates the popup content, layout and position. Useful for updating the popup after + * something inside changed, e.g. image loaded. + */ + update(): Popup; + } +} + +declare namespace L { + + export interface PopupOptions { + + /** + * Max width of the popup. + * + * Default value: 300. + */ + maxWidth?: number; + + /** + * Min width of the popup. + * + * Default value: 50. + */ + minWidth?: number; + + /** + * If set, creates a scrollable container of the given height inside a popup + * if its content exceeds it. + */ + maxHeight?: number; + + /** + * Set it to false if you don't want the map to do panning animation to fit the opened + * popup. + * + * Default value: true. + */ + autoPan?: boolean; + + /** + * Set it to true if you want to prevent users from panning the popup off of the screen while it is open. + */ + keepInView?: boolean; + + /** + * Controls the presense of a close button in the popup. + * + * Default value: true. + */ + closeButton?: boolean; + + /** + * The offset of the popup position. Useful to control the anchor of the popup + * when opening it on some overlays. + * + * Default value: new Point(0, 6). + */ + offset?: Point; + + /** + * The margin between the popup and the top left corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingTopLeft?: Point; + + /** + * The margin between the popup and the bottom right corner of the map view after + * autopanning was performed. + * + * Default value: null. + */ + autoPanPaddingBottomRight?: Point; + + /** + * The margin between the popup and the edges of the map view after autopanning + * was performed. + * + * Default value: new Point(5, 5). + */ + autoPanPadding?: Point; + + /** + * Whether to animate the popup on zoom. Disable it if you have problems with + * Flash content inside popups. + * + * Default value: true. + */ + zoomAnimation?: boolean; + + /** + * Set it to false if you want to override the default behavior of the popup + * closing when user clicks the map (set globally by the Map closePopupOnClick + * option). + */ + closeOnClick?: boolean; + + /** + * A custom class name to assign to the popup. + */ + className?: string; + } +} + +declare namespace L { + + export interface PosAnimationStatic extends ClassStatic { + /** + * Creates a PosAnimation object. + */ + new(): PosAnimation; + } + export var PosAnimation: PosAnimationStatic; + + export interface PosAnimation extends IEventPowered { + /** + * Run an animation of a given element to a new position, optionally setting + * duration in seconds (0.25 by default) and easing linearity factor (3rd argument + * of the cubic bezier curve, 0.5 by default) + */ + run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): PosAnimation; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; + fire(type: string, data?: any): PosAnimation; + addEventListener(eventMap: any, context?: any): PosAnimation; + removeEventListener(eventMap?: any, context?: any): PosAnimation; + clearAllEventListeners(): PosAnimation; + on(eventMap: any, context?: any): PosAnimation; + off(eventMap?: any, context?: any): PosAnimation; + } +} + +declare namespace L { + + namespace Projection { + + /** + * Spherical Mercator projection — the most common projection for online maps, + * used by almost all free and commercial tile providers. Assumes that Earth + * is a sphere. Used by the EPSG:3857 CRS. + */ + export var SphericalMercator: IProjection; + + /** + * Elliptical Mercator projection — more complex than Spherical Mercator. + * Takes into account that Earth is a geoid, not a perfect sphere. Used by the + * EPSG:3395 CRS. + */ + export var Mercator: IProjection; + + /** + * Equirectangular, or Plate Carree projection — the most simple projection, + * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. + * Also suitable for flat worlds, e.g. game maps. Used by the EPSG:3395 and Simple + * CRS. + */ + export var LonLat: IProjection; + } +} + +declare namespace L { + + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + function rectangle(bounds: LatLngBounds, options?: PathOptions): Rectangle; + + export interface RectangleStatic extends ClassStatic { + /** + * Instantiates a rectangle object with the given geographical bounds and + * optionally an options object. + */ + new(bounds: LatLngBounds, options?: PathOptions): Rectangle; + } + export var Rectangle: RectangleStatic; + + export interface Rectangle extends Polygon { + /** + * Redraws the rectangle with the passed bounds. + */ + setBounds(bounds: LatLngBounds): Rectangle; + } +} + + +declare namespace L { + + export interface ScaleOptions { + + /** + * The position of the control (one of the map corners). See control positions. + * Default value: 'bottomleft'. + */ + position?: PositionString; + + /** + * Maximum width of the control in pixels. The width is set dynamically to show + * round values (e.g. 100, 200, 500). + * Default value: 100. + */ + maxWidth?: number; + + /** + * Whether to show the metric scale line (m/km). + * Default value: true. + */ + metric?: boolean; + + /** + * Whether to show the imperial scale line (mi/ft). + * Default value: true. + */ + imperial?: boolean; + + /** + * If true, the control is updated on moveend, otherwise it's always up-to-date + * (updated on move). + * Default value: false. + */ + updateWhenIdle?: boolean; + } +} + +declare namespace L { + + export interface TileLayerStatic extends ClassStatic { + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + new(urlTemplate: string, options?: TileLayerOptions): TileLayer; + + WMS: { + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + new(baseUrl: string, options: WMSOptions): TileLayer.WMS; + }; + + Canvas: { + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + new(options?: TileLayerOptions): TileLayer.Canvas; + }; + } + export var TileLayer: TileLayerStatic; + + export interface TileLayer extends ILayer, IEventPowered { + /** + * Adds the layer to the map. + */ + addTo(map: Map): TileLayer; + + /** + * Brings the tile layer to the top of all tile layers. + */ + bringToFront(): TileLayer; + + /** + * Brings the tile layer to the bottom of all tile layers. + */ + bringToBack(): TileLayer; + + /** + * Changes the opacity of the tile layer. + */ + setOpacity(opacity: number): TileLayer; + + /** + * Sets the zIndex of the tile layer. + */ + setZIndex(zIndex: number): TileLayer; + + /** + * Causes the layer to clear all the tiles and request them again. + */ + redraw(): TileLayer; + + /** + * Updates the layer's URL template and redraws it. + */ + setUrl(urlTemplate: string): TileLayer; + + /** + * Returns the HTML element that contains the tiles for this layer. + */ + getContainer(): HTMLElement; + + //////////// + //////////// + /** + * Should contain code that creates DOM elements for the overlay, adds them + * to map panes where they should belong and puts listeners on relevant map events. + * Called on map.addLayer(layer). + */ + onAdd(map: Map): void; + + /** + * Should contain all clean up code that removes the overlay's elements from + * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). + */ + onRemove(map: Map): void; + + //////////////// + //////////////// + addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + hasEventListeners(type: string): boolean; + fireEvent(type: string, data?: any): TileLayer; + on(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + once(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; + off(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; + fire(type: string, data?: any): TileLayer; + addEventListener(eventMap: any, context?: any): TileLayer; + removeEventListener(eventMap?: any, context?: any): TileLayer; + clearAllEventListeners(): TileLayer; + on(eventMap: any, context?: any): TileLayer; + off(eventMap?: any, context?: any): TileLayer; + } + + namespace TileLayer { + export interface WMS extends TileLayer { + /** + * Merges an object with the new parameters and re-requests tiles on the current + * screen (unless noRedraw was set to true). + */ + setParams(params: WMS, noRedraw?: boolean): WMS; + } + + export interface Canvas extends TileLayer { + /** + * You need to define this method after creating the instance to draw tiles; + * canvas is the actual canvas tile on which you can draw, tilePoint represents + * the tile numbers, and zoom is the current zoom. + */ + drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; + + /** + * Calling redraw will cause the drawTile method to be called for all tiles. + * May be used for updating dynamic content drawn on the Canvas + */ + redraw(): Canvas; + } + } + + export interface TileLayerFactory { + + /** + * Instantiates a tile layer object given a URL template and optionally an options + * object. + */ + (urlTemplate: string, options?: TileLayerOptions): TileLayer; + + /** + * Instantiates a WMS tile layer object given a base URL of the WMS service and + * a WMS parameters/options object. + */ + wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; + + /** + * Instantiates a Canvas tile layer object given an options object (optionally). + */ + canvas(options?: TileLayerOptions): L.TileLayer.Canvas; + } + + export var tileLayer: TileLayerFactory; +} + +declare namespace L { + + export interface TileLayerOptions { + + /** + * Minimum zoom number. + * + * Default value: 0. + */ + minZoom?: number; + + /** + * Maximum zoom number. + * + * Default value: 18. + */ + maxZoom?: number; + + /** + * Maximum zoom number the tiles source has available. If it is specified, + * the tiles on all zoom levels higher than maxNativeZoom will be loaded from + * maxZoom level and auto-scaled. + * + * Default value: null. + */ + maxNativeZoom?: number; + + /** + * Tile size (width and height in pixels, assuming tiles are square). + * + * Default value: 256. + */ + tileSize?: number; + + /** + * Subdomains of the tile service. Can be passed in the form of one string (where + * each letter is a subdomain name) or an array of strings. + * + * Default value: 'abc'. + */ + subdomains?: string|string[]; + + /** + * URL to the tile image to show in place of the tile that failed to load. + * + * Default value: ''. + */ + errorTileUrl?: string; + + /** + * e.g. "© CloudMade" — the string used by the attribution control, describes + * the layer data. + * + * Default value: ''. + */ + attribution?: string; + + /** + * If true, inverses Y axis numbering for tiles (turn this on for TMS services). + * + * Default value: false. + */ + tms?: boolean; + + /** + * If set to true, the tile coordinates won't be wrapped by world width (-180 + * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this + * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor + * or photo maps). + * + * Default value: false. + */ + continuousWorld?: boolean; + + /** + * If set to true, the tiles just won't load outside the world width (-180 to 180 + * longitude) instead of repeating. + * + * Default value: false. + */ + noWrap?: boolean; + + /** + * The zoom number used in tile URLs will be offset with this value. + * + * Default value: 0. + */ + zoomOffset?: number; + + /** + * If set to true, the zoom number used in tile URLs will be reversed (maxZoom + * - zoom instead of zoom) + * + * Default value: false. + */ + zoomReverse?: boolean; + + /** + * The opacity of the tile layer. + * + * Default value: 1.0. + */ + opacity?: number; + + /** + * The explicit zIndex of the tile layer. Not set by default. + */ + zIndex?: number; + + /** + * If true, all the tiles that are not visible after panning are removed (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + unloadInvisibleTiles?: boolean; + + /** + * If false, new tiles are loaded during panning, otherwise only after it (for + * better performance). true by default on mobile WebKit, otherwise false. + */ + updateWhenIdle?: boolean; + + /** + * If true and user is on a retina display, it will request four tiles of half the + * specified size and a bigger zoom level in place of one to utilize the high resolution. + * + * Default value: false. + */ + detectRetina?: boolean; + + /** + * If true, all the tiles that are not visible after panning are placed in a reuse + * queue from which they will be fetched when new tiles become visible (as opposed + * to dynamically creating new ones). This will in theory keep memory usage + * low and eliminate the need for reserving new memory whenever a new tile is + * needed. + * + * Default value: false. + */ + reuseTiles?: boolean; + + /** + * When this option is set, the TileLayer only loads tiles that are in the given geographical bounds. + */ + bounds?: LatLngBounds; + + /** + * Custom keys may be specified in TileLayerOptions so they can be used in a provided URL template. + */ + [additionalKeys: string]: any; + } +} + +declare namespace L { + export interface TransformationStatic { + /** + * Creates a transformation object with the given coefficients. + */ + new(a: number, b: number, c: number, d: number): Transformation; + } + export var Transformation: TransformationStatic; + + export interface Transformation { + /** + * Returns a transformed point, optionally multiplied by the given scale. + * Only accepts real L.Point instances, not arrays. + */ + transform(point: Point, scale?: number): Point; + + /** + * Returns the reverse transformation of the given point, optionally divided + * by the given scale. Only accepts real L.Point instances, not arrays. + */ + untransform(point: Point, scale?: number): Point; + } +} + +declare namespace L { + + namespace Util { + + /** + * Merges the properties of the src object (or multiple objects) into dest object + * and returns the latter. Has an L.extend shortcut. + */ + export function extend(dest: any, ...sources: any[]): any; + + /** + * Returns a function which executes function fn with the given scope obj (so + * that this keyword refers to obj inside the function code). Has an L.bind shortcut. + */ + export function bind(fn: T, obj: any): T; + + /** + * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. + */ + export function stamp(obj: any): string; + + /** + * Returns a wrapper around the function fn that makes sure it's called not more + * often than a certain time interval time, but as fast as possible otherwise + * (for example, it is used for checking and requesting new tiles while dragging + * the map), optionally passing the scope (context) in which the function will + * be called. + */ + export function limitExecByInterval(fn: T, time: number, context?: any): T; + + /** + * Returns a function which always returns false. + */ + export function falseFn(): () => boolean; + + /** + * Returns the number num rounded to digits decimals. + */ + export function formatNum(num: number, digits: number): number; + + /** + * Trims and splits the string on whitespace and returns the array of parts. + */ + export function splitWords(str: string): string[]; + + /** + * Merges the given properties to the options of the obj object, returning the + * resulting options. See Class options. Has an L.setOptions shortcut. + */ + export function setOptions(obj: any, options: any): any; + + /** + * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} + * translates to '?a=foo&b=bar'. + */ + export function getParamString(obj: any): string; + + /** + * Simple templating facility, creates a string by applying the values of the + * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form + * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. + */ + export function template(str: string, data: any): string; + + /** + * Returns true if the given object is an array. + */ + export function isArray(obj: any): boolean; + + /** + * Trims the whitespace from both ends of the string and returns the result. + */ + export function trim(str: string): string; + + /** + * Data URI string containing a base64-encoded empty GIF image. Used as a hack + * to free memory from unused images on WebKit-powered mobile devices (by setting + * image src to this string). + */ + export var emptyImageUrl: string; + } +} + + +declare namespace L { + + export interface WMSOptions { + + /** + * (required) Comma-separated list of WMS layers to show. + * + * Default value: ''. + */ + layers?: string; + + /** + * Comma-separated list of WMS styles. + * + * Default value: 'image/jpeg'. + */ + styles?: string; + + /** + * WMS image format (use 'image/png' for layers with transparency). + * + * Default value: false. + */ + format?: string; + + /** + * If true, the WMS service will return images with transparency. + * + * Default value: '1.1.1'. + */ + transparent?: boolean; + + /** + * Version of the WMS service to use. + */ + version?: string; + + } +} + +/** + * Forces Leaflet to use the Canvas back-end (if available) for vector layers + * instead of SVG. This can increase performance considerably in some cases + * (e.g. many thousands of circle markers on the map). + */ +declare var L_PREFER_CANVAS: boolean; + +/** + * Forces Leaflet to not use touch events even if it detects them. + */ +declare var L_NO_TOUCH: boolean; + +/** + * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning + * (which may cause glitches in some rare environments) even if they're supported. + */ +declare var L_DISABLE_3D: boolean; + +declare module "leaflet" { + export = L; +} + +// vim: et ts=4 sw=4 diff --git a/leaflet/leaflet-tests.ts b/leaflet/leaflet-tests.ts index b0568b216a..9b07b8fd03 100644 --- a/leaflet/leaflet-tests.ts +++ b/leaflet/leaflet-tests.ts @@ -1,427 +1,267 @@ /// -// initialize the map on the "map" div with a given center and zoom - -var div = document.getElementById('map'); - -var map : L.Map = L.map(div, { - center: L.latLng([51.505, -0.09]), - zoom: 13, - minZoom: 3, - maxZoom: 8, - maxBounds: L.latLngBounds([L.latLng(-60, -60), L.latLng(60, 60)]), - dragging: true, - touchZoom: true, - scrollWheelZoom: true, - boxZoom: true, - tap: true, - - tapTolerance: 30, - trackResize: true, - worldCopyJump: false, - closePopupOnClick: true, - bounceAtZoomLimits: true, - - keyboard: true, - keyboardPanOffset: 80, - keyboardZoomOffset: 1, - - inertia: true, - inertiaDeceleration: 3000, - inertiaMaxSpeed: 1500, - inertiaThreshold: 32, - - zoomControl: true, - attributionControl: true, - - fadeAnimation: true, - zoomAnimation: true, - zoomAnimationThreshold: 4, - markerZoomAnimation: true - -}); - -map.dragging.enable(); -map.touchZoom.enable(); -map.scrollWheelZoom.enable(); -map.doubleClickZoom.enable(); -map.boxZoom.enable(); -map.tap.enable(); - -map.setView(new L.LatLng(42, 51)); -map.setView(L.latLng(42, 51)); - -map.setView(L.latLng(42, 51), 12); -map.setView(L.latLng(42, 51), 12, { - reset: true, - pan: { - animate: true, - duration: 0.25, - easeLinearity: 0.25, - noMoveStart: false - }, - zoom: { - animate: true - } -}); - -map.setZoom(50); -map.setZoom(50, {}); - -map.zoomIn(); -map.zoomOut(); - -map.zoomIn(2); -map.zoomOut(2); - -map.zoomIn(2, { animate: true }); -map.zoomOut(2, { animate: true }); - -map.setZoomAround(L.latLng(42, 51), 8, { animate: false }); - -map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); -map.fitBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20)), { - paddingTopLeft: L.point(20, 20), - paddingBottomRight: L.point(20, 20), - padding: L.point(0, 0), - maxZoom: null -}); - -map.fitWorld(); - -map.fitWorld({ - animate: false -}); - -map.panTo(L.latLng(42, 42)); -map.panTo(L.latLng(42, 42), { - animate: true -}); - -map.invalidateSize(true); -map.invalidateSize({ reset: true }); - -map.setMaxBounds(L.latLngBounds(L.latLng(10, 10), L.latLng(20, 20))); - -map.locate(); -map.locate({ - watch: false, - setView: false, - maxZoom: 18, - timeout: 10000, - maximumAge: 0, - enableHighAccuracy: false -}); - -map.stopLocate(); - -map.remove(); - -var center : L.LatLng = map.getCenter(); -var zoom : number = map.getZoom(); -var minZoom: number = map.getMinZoom(); -var maxZoom: number = map.getMaxZoom(); -var bounds: L.LatLngBounds = map.getBounds(); -var boundsZoom: number = map.getBoundsZoom(bounds, true); -var size: L.Point = map.getSize(); -var pixelBounds: L.Bounds = map.getPixelBounds(); -var pixelOrigin: L.Point = map.getPixelOrigin(); - -var layer = L.tileLayer("http://{s}.example.net/{x}/{y}/{z}.png"); - -map.addLayer(layer); -map.addLayer(layer, false); -map.eachLayer(l => {}); - -map.removeLayer(layer); -map.hasLayer(layer); - -map.openPopup("canard", L.latLng(42, 51)); - -var popup = L.popup({ - autoPan: true -}); - -map.openPopup(popup); -map.closePopup(popup); -map.closePopup(); - -map.addControl(L.control.attribution({position: 'bottomright'})); -map.removeControl(L.control.attribution({ position: 'bottomright' })); - -L.control.layers({'Base': layer}).addTo(map); -map.on('baseLayerChange', function(e: L.LeafletLayersControlEvent) { - alert(e.name); -}); - -map.latLngToLayerPoint(map.layerPointToLatLng(L.point(0, 0))); -map.latLngToContainerPoint(map.containerPointToLatLng(L.point(0, 0))); -map.containerPointToLayerPoint(L.point(0, 0)); -map.layerPointToContainerPoint(L.point(0, 0)); - -map.project(map.unproject(L.point(10, 20))); -map.project(map.unproject(L.point(10, 20), 12), 12); - -var mouseEvent: L.LeafletMouseEvent; -map.mouseEventToContainerPoint(mouseEvent); -map.mouseEventToLayerPoint(mouseEvent); -map.mouseEventToLatLng(mouseEvent); - -map.getContainer().classList.add('roger'); -map.getPanes().mapPane.classList.add('roger'); -map.getPanes().markerPane.classList.add('roger'); -map.getPanes().objectsPane.classList.add('roger'); -map.getPanes().overlayPane.classList.add('roger'); -map.getPanes().popupPane.classList.add('roger'); -map.getPanes().shadowPane.classList.add('roger'); -map.getPanes().tilePane.classList.add('roger'); - -map.whenReady((m: L.Map) => { - m.zoomOut(); -}); - -map.on('click', () => { - map.zoomOut(); -}); - -map.off('dblclick', L.Util.falseFn); - -map.once('contextmenu', (e: L.LeafletMouseEvent) => { - map.openPopup('contextmenu', e.latlng); -}); - -var marker = L.marker(L.latLng(42, 51), { - icon: L.icon({ - iconUrl: 'roger.png', - iconRetinaUrl: 'roger-retina.png', - iconSize: L.point(40, 40), - iconAnchor: L.point(20, 0), - shadowUrl: 'roger-shadow.png', - shadowRetinaUrl: 'roger-shadow-retina.png', - shadowSize: L.point(44, 44), - shadowAnchor: L.point(22, 0), - popupAnchor: L.point(0, 0), - className: 'roger-icon' - }), - clickable: true, - draggable: false, - keyboard: true, - title: 'this is an icon', - alt: '', - zIndexOffset: 0, - opacity: 1.0, - riseOnHover: false, - riseOffset: 250 -}); - -marker.addTo(map); - -marker.on('click', (e: L.LeafletMouseEvent) => { - map.setView(e.latlng); -}); - -marker.once('mouseover', () => { - marker.openPopup(); -}) - -marker.setLatLng(marker.getLatLng()); - -marker.setIcon(L.icon({})); - -marker.setZIndexOffset(30); -marker.setOpacity(0.8); - -marker.bindPopup(popup); -marker.unbindPopup(); -marker.bindPopup('hello', { - closeOnClick: true -}); - -marker.openPopup(); -marker.closePopup(); -marker.togglePopup(); -marker.togglePopup(); -marker.setPopupContent('hello 3') -marker.getPopup().setContent('hello 2'); -marker.update(); - -marker.toGeoJSON(); - -marker.dragging.enable(); - -popup = L.popup({ - maxWidth: 300, - minWidth: 50, - maxHeight: null, - autoPan: true, - keepInView: false, - closeButton: true, - offset: L.point(0, 6), - autoPanPaddingTopLeft: null, - autoPanPaddingBottomRight: L.point(20, 20), - autoPanPadding: L.point(5, 5), - zoomAnimation: true, - closeOnClick: null, - className: 'roger' -}); - -popup.setLatLng(L.latLng(12, 54)).setContent('this is nice popup').openOn(map); - -popup.update(); - -var tileLayer = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png?{foo}', { - minZoom: 0, - maxZoom: 18, - maxNativeZoom: 17, - tileSize: 256, - subdomains: ['a','b','c'], - errorTileUrl: '', - attribution: '', - tms: false, - continuousWorld: false, - noWrap: false, - zoomOffset: 0, - zoomReverse: false, - opacity: 1.0, - zIndex: null, - unloadInvisibleTiles: false, - updateWhenIdle: false, - detectRetina: true, - reuseTiles: true, - bounds: null -}); - -tileLayer.on('loading', L.Util.falseFn) - .off('loading', L.Util.falseFn) - .once('tileload', L.Util.falseFn); - -tileLayer.addTo(map); - -tileLayer.bringToBack() - .bringToFront() - .setOpacity(0.7) - .setZIndex(9) - .redraw() - .setUrl('http://perdu.com') - .getContainer(); - -namespace CustomControl { - export interface Options { - title: string; - position?: string; - } -} -interface CustomControl extends L.Control { - getTitle(): string; - setTitle(title: string): CustomControl; -} -var CustomControl: { new(options: CustomControl.Options): CustomControl }; -CustomControl = L.Control.extend({ - initialize: function(options: CustomControl.Options) { - L.Control.prototype.initialize.call(this, { - position: options.position || 'bottomleft', - }); - this.title = options.title; - }, - getTitle: function() { - return this.title; - }, - setTitle: function(title: string) { - this.title = title; - }, -}); - -// Different latLng and latLngBounds expressions -var latLngLiteral = [10, 20]; -var latLngObjectLiteral = { lat: 10, lng: 10 }; -var boundsLiteral = [[10, 20], [20, 20]]; -var boundLiteralOfLatLngObjects = [latLngObjectLiteral, latLngObjectLiteral]; - -var circle: L.Circle = L.circle(latLngLiteral, 4); -circle = new L.Circle(latLngLiteral, 4); -circle.setLatLng(latLngLiteral); - -circle = L.circle(latLngObjectLiteral, 4); -circle = new L.Circle(latLngObjectLiteral, 4); -circle.setLatLng(latLngObjectLiteral); - -var circleMarker: L.CircleMarker = L.circleMarker(latLngLiteral); -circleMarker = new L.CircleMarker(latLngLiteral); -circleMarker.setLatLng(latLngLiteral); - -circleMarker = L.circleMarker(latLngObjectLiteral); -circleMarker = new L.CircleMarker(latLngObjectLiteral); -circleMarker.setLatLng(latLngObjectLiteral); - -var latLng: L.LatLng = L.latLng(latLngLiteral); -latLng = new L.LatLng(latLngLiteral); -latLng.distanceTo(latLngLiteral); -latLng.equals(latLngLiteral); - -latLng = L.latLng(latLngObjectLiteral); -latLng = new L.LatLng(latLngObjectLiteral); -latLng.distanceTo(latLngObjectLiteral); -latLng.equals(latLngObjectLiteral); - -var bounds: L.LatLngBounds = L.latLngBounds(boundsLiteral); -bounds = L.latLngBounds(boundLiteralOfLatLngObjects); -bounds = new L.LatLngBounds(boundsLiteral); -bounds = new L.LatLngBounds(boundLiteralOfLatLngObjects); -bounds = new L.LatLngBounds(latLngLiteral, latLngLiteral); - -bounds.extend(latLngLiteral); -bounds.extend(latLngObjectLiteral); -bounds.extend(boundsLiteral); -bounds.extend(boundLiteralOfLatLngObjects); - -bounds.contains(latLngLiteral); -bounds.contains(boundLiteralOfLatLngObjects); -bounds.contains(boundsLiteral); - -bounds.intersects(boundsLiteral); -bounds.intersects(boundLiteralOfLatLngObjects); - -bounds.equals(boundsLiteral); -bounds.equals(boundLiteralOfLatLngObjects); - -map.setView(latLngLiteral); -map.setView(latLngObjectLiteral); -map.setZoomAround(latLngLiteral, 15); -map.setZoomAround(latLngObjectLiteral, 15); -map.panTo(latLngLiteral); -map.panTo(latLngObjectLiteral); -map.openPopup('test', latLngLiteral); -map.openPopup('test', latLngObjectLiteral); -map.latLngToLayerPoint(latLngLiteral); -map.latLngToLayerPoint(latLngObjectLiteral); -map.latLngToContainerPoint(latLngLiteral); -map.latLngToContainerPoint(latLngObjectLiteral); -map.project(latLngLiteral); -map.project(latLngObjectLiteral); - -marker.setLatLng(latLngLiteral); -marker.setLatLng(latLngObjectLiteral); - -var polygon: L.Polygon = L.polygon(boundsLiteral); -polygon = L.polygon(boundLiteralOfLatLngObjects); -polygon = new L.Polygon(boundsLiteral); -polygon = new L.Polygon(boundLiteralOfLatLngObjects); - -var polyline: L.Polyline = L.polyline(boundsLiteral); -polyline = L.polyline(boundLiteralOfLatLngObjects); -polyline = new L.Polyline(boundsLiteral); -polyline = new L.Polyline(boundLiteralOfLatLngObjects); -polyline.setLatLngs(boundsLiteral); -polyline.setLatLngs(boundLiteralOfLatLngObjects); -polyline.addLatLng(latLngLiteral); -polyline.addLatLng(latLngObjectLiteral); - -var popup: L.Popup = L.popup(); -popup.setLatLng(latLngLiteral); -popup.setLatLng(latLngObjectLiteral); - -var zoomCtrl = L.control.zoom({ - position: "topleft", - zoomInText: '+', - zoomOutText: '-' -}); +import L = require('leaflet'); + +const latLngLiteral: L.LatLngLiteral = {lat: 12, lng: 13}; +const latLngTuple: L.LatLngTuple = [12, 13]; + +let latLng: L.LatLng; +latLng = L.latLng(12, 13); +latLng = L.latLng(12, 13, 0); +latLng = L.latLng(latLngLiteral); +latLng = L.latLng({lat: 12, lng: 13, alt: 0}); +latLng = L.latLng(latLngTuple); +latLng = L.latLng([12, 13, 0]); + +const latLngBoundsLiteral: L.LatLngBoundsLiteral = [[12, 13], latLngTuple]; + +let latLngBounds: L.LatLngBounds; +latLngBounds = L.latLngBounds(latLng, latLng); +latLngBounds = L.latLngBounds(latLngLiteral, latLngLiteral); +latLngBounds = L.latLngBounds(latLngTuple, latLngTuple); + +const pointTuple: L.PointTuple = [0, 0]; + +let point: L.Point; +point = L.point(12, 13); +point = L.point(12, 13, true); +point = L.point(pointTuple); +point = L.point({x: 12, y: 13}); + +const boundsLiteral: L.BoundsLiteral = [[1, 1], pointTuple]; + +let bounds: L.Bounds; +bounds = L.bounds(point, point); +bounds = L.bounds(pointTuple, pointTuple); +bounds = L.bounds([point, point]); +bounds = L.bounds(boundsLiteral); + +let mapOptions: L.MapOptions = {}; +mapOptions = { + preferCanvas: true, + attributionControl: false, + zoomControl: true, + closePopupOnClick: false, + zoomSnap: 1, + zoomDelta: 1, + trackResize: false, + boxZoom: true, + dragging: true, + // CRS + zoom: 12, + minZoom: 10, + maxZoom: 14, + fadeAnimation: true, + markerZoomAnimation: false, + transform3DLimit: 123, + zoomAnimation: false, + zoomAnimationThreshold: 4, + inertia: false, + inertiaDeceleration: 2000, + inertiaMaxSpeed: 1000, + easeLinearity: 0.5, + worldCopyJump: true, + maxBoundsViscosity: 1.0, + keyboard: false, + keyboardPanDelta: 100, + wheelDebounceTime: 30, + wheelPxPerZoomLevel: 25, + tap: false, + tapTolerance: 10, + bounceAtZoomLimits: false +}; + +mapOptions.doubleClickZoom = true; +mapOptions.doubleClickZoom = 'center'; + +mapOptions.center = latLng; +mapOptions.center = latLngLiteral; +mapOptions.center = latLngTuple; + +mapOptions.layers = []; +mapOptions.layers = [L.tileLayer('')]; // add layers of other types + +mapOptions.maxBounds = latLngBounds; +mapOptions.maxBounds = []; +mapOptions.maxBounds = latLngBoundsLiteral; + +// mapOptions.renderer = ? + +mapOptions.scrollWheelZoom = true; +mapOptions.scrollWheelZoom = 'center'; + +mapOptions.touchZoom = false; +mapOptions.touchZoom = 'center'; + +let layer: L.Layer; + +const htmlElement = document.getElementById('foo'); + +let popupOptions: L.PopupOptions = {}; + +let tooltipOptions: L.TooltipOptions = {}; + +let zoomPanOptions: L.ZoomPanOptions = {}; +zoomPanOptions = { + animate: false, + duration: 0.5, + easeLinearity: 0.6, + noMoveStart: true +}; + +let zoomOptions: L.ZoomOptions = {}; + +let panOptions: L.PanOptions = {}; + +let fitBoundsOptions: L.FitBoundsOptions = {}; + +let map = L.map('foo'); +map = L.map('foo', mapOptions); +map = L.map(htmlElement); +map = L.map(htmlElement, mapOptions); + +let doesItHaveLayer: boolean; +doesItHaveLayer = map.hasLayer(L.tileLayer('')); + +// map.getRenderer + +let html: HTMLElement; +html = map.createPane('foo'); +html = map.createPane('foo', htmlElement) +html = map.getPane('foo'); +html = map.getPane(htmlElement); +html = map.getContainer(); + +const panes = map.getPanes(); +html = panes.mapPane; +html = panes.tilePane; +html = panes.overlayPane; +html = panes.shadowPane; +html = panes.markerPane; +html = panes.tooltipPane; +html = panes.popupPane; +html = panes['foo']; + +let coordinates: L.LatLng; +coordinates = map.getCenter(); + +let zoom: number; +zoom = map.getZoom(); +zoom = map.getMinZoom(); +zoom = map.getMaxZoom(); +zoom = map.getBoundsZoom(latLngBounds); +zoom = map.getBoundsZoom(latLngBounds, true); +zoom = map.getBoundsZoom(latLngBoundsLiteral); +zoom = map.getBoundsZoom(latLngBoundsLiteral, true); + +let mapLatLngBounds: L.LatLngBounds; +mapLatLngBounds = map.getBounds(); + +let mapPoint: L.Point; +mapPoint = map.getSize(); +mapPoint = map.getPixelOrigin(); + +let mapPixelBounds: L.Bounds; +mapPixelBounds = map.getPixelBounds(); +mapPixelBounds = map.getPixelWorldBounds(); +mapPixelBounds = map.getPixelWorldBounds(12); + +map = map + // addControl + // removeControl + .addLayer(L.tileLayer('')) + .removeLayer(L.tileLayer('')) // use a different type of layer + .eachLayer((currentLayer) => { + layer = currentLayer; + }) + .eachLayer((currentLayer) => { + layer = currentLayer; + }, {}) + .openPopup(L.popup()) + .openPopup('Hello World', latLng) + .openPopup('Hello World', latLng, popupOptions) + .openPopup('Hello World', latLngLiteral) + .openPopup('Hello World', latLngLiteral, popupOptions) + .openPopup('Hello World', latLngTuple) + .openPopup('Hello World', latLngTuple, popupOptions) + .openPopup(htmlElement, latLng) + .openPopup(htmlElement, latLng, popupOptions) + .openPopup(htmlElement, latLngLiteral) + .openPopup(htmlElement, latLngLiteral, popupOptions) + .openPopup(htmlElement, latLngTuple) + .openPopup(htmlElement, latLngTuple, popupOptions) + .closePopup() + .closePopup(L.popup()) + .openTooltip(L.tooltip()) + .openTooltip('Hello Word', latLng) + .openTooltip('Hello World', latLng, tooltipOptions) + .openTooltip('Hello World', latLngLiteral) + .openTooltip('Hello World', latLngLiteral, tooltipOptions) + .openTooltip('Hello World', latLngTuple) + .openTooltip('Hello World', latLngTuple, tooltipOptions) + .openTooltip(htmlElement, latLng) + .openTooltip(htmlElement, latLng, tooltipOptions) + .openTooltip(htmlElement, latLngLiteral) + .openTooltip(htmlElement, latLngLiteral, tooltipOptions) + .openTooltip(htmlElement, latLngTuple) + .openTooltip(htmlElement, latLngTuple, tooltipOptions) + .closeTooltip() + .closeTooltip(L.tooltip()) + .setView(latLng, 12) + .setView(latLng, 12, zoomPanOptions) + .setView(latLngLiteral, 12) + .setView(latLngLiteral, 12, zoomPanOptions) + .setView(latLngTuple, 12) + .setView(latLngTuple, 12, zoomPanOptions) + .setZoom(12, zoomPanOptions) // investigate if zoomPanOptions are really required + .zoomIn() + .zoomIn(1) + .zoomIn(1, zoomOptions) + .zoomOut() + .zoomOut(1) + .zoomOut(1, zoomOptions) + .setZoomAround(latLng, 12, zoomOptions) // investigate if zoom options are really required + .setZoomAround(latLngLiteral, 12, zoomOptions) + .setZoomAround(latLngTuple, 12, zoomOptions) + .setZoomAround(point, 12, zoomOptions) + .setZoomAround(pointTuple, 11, zoomOptions) + .fitBounds(latLngBounds, fitBoundsOptions) // investigate if fit bounds options are really required + .fitBounds(latLngBoundsLiteral, fitBoundsOptions) + .fitWorld() + .fitWorld(fitBoundsOptions) + .panTo(latLng) + .panTo(latLng, panOptions) + .panTo(latLngLiteral) + .panTo(latLngLiteral, panOptions) + .panTo(latLngTuple) + .panTo(latLngTuple, panOptions) + .panBy(point) + .panBy(pointTuple) + .setMaxBounds(bounds) // investigate if this really receives Bounds instead of LatLngBounds + .setMaxBounds(boundsLiteral) + .setMinZoom(5) + .setMaxZoom(10) + .panInsideBounds(latLngBounds) + .panInsideBounds(latLngBounds, panOptions) + .panInsideBounds(latLngBoundsLiteral) + .panInsideBounds(latLngBoundsLiteral, panOptions) + .invalidateSize(zoomPanOptions) + .invalidateSize(false) + .stop() + .flyTo(latLng) + .flyTo(latLng, 12) + .flyTo(latLng, 12, zoomOptions) + .flyTo(latLngLiteral) + .flyTo(latLngLiteral, 12) + .flyTo(latLngLiteral, 12, zoomPanOptions) + .flyTo(latLngTuple) + .flyTo(latLngTuple, 12) + .flyTo(latLngTuple, 12, zoomPanOptions) + .flyToBounds(latLngBounds) + .flyToBounds(latLngBounds, fitBoundsOptions) + .flyToBounds(latLngBoundsLiteral) + .flyToBounds(latLngBoundsLiteral, fitBoundsOptions) + // addHandler + .remove() + .whenReady(() => {}) + .whenReady(() => {}, {}); diff --git a/leaflet/leaflet.d.ts b/leaflet/leaflet.d.ts index 3bf19a1771..87f33576e6 100644 --- a/leaflet/leaflet.d.ts +++ b/leaflet/leaflet.d.ts @@ -1,4382 +1,927 @@ -// Type definitions for Leaflet.js 1.0.0 +// Type definitions for Leaflet.js 1.0.0-rc3 // Project: https://github.com/Leaflet/Leaflet -// Definitions by: Vladimir Zotov +// Definitions by: Alejandro Sánchez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// - declare namespace L { - type LatLngExpression = LatLng | number[] | ({ lat: number; lng: number }) - type LatLngBoundsExpression = LatLngBounds | LatLngExpression[]; - type PositionString = 'topleft' | 'topright' | 'bottomleft' | 'bottomright'; -} - -declare namespace L { - - export interface AttributionOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * Default value: 'bottomright'. - */ - position?: PositionString; - - /** - * The HTML text shown before the attributions. Pass false to disable. - * Default value: 'Powered by Leaflet'. - */ - prefix?: string; - - } -} - -declare namespace L { - - /** - * Creates a Bounds object from two coordinates (usually top-left and bottom-right - * corners). - */ - export function bounds(topLeft: Point, bottomRight: Point): Bounds; - - /** - * Creates a Bounds object defined by the points it contains. - */ - export function bounds(points: Point[]): Bounds; - - - export interface BoundsStatic { - /** - * Creates a Bounds object from two coordinates (usually top-left and bottom-right - * corners). - */ - new(topLeft: Point, bottomRight: Point): Bounds; - - /** - * Creates a Bounds object defined by the points it contains. - */ - new(points: Point[]): Bounds; - } - export var Bounds: BoundsStatic; - - export interface Bounds { - /** - * Extends the bounds to contain the given point. - */ - extend(point: Point): void; - - /** - * Returns the center point of the bounds. - */ - getCenter(): Point; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: Bounds): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(point: Point): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: Bounds): boolean; - - /** - * Returns true if the bounds are properly initialized. - */ - isValid(): boolean; - - /** - * Returns the size of the given bounds. - */ - getSize(): Point; - - /** - * The top left corner of the rectangle. - */ - min: Point; - - /** - * The bottom right corner of the rectangle. - */ - max: Point; - } -} - -declare namespace L { - - namespace Browser { - - /** - * true for all Internet Explorer versions. - */ - export var ie: boolean; - - /** - * true for Internet Explorer 6. - */ - export var ie6: boolean; - - /** - * true for Internet Explorer 6. - */ - export var ie7: boolean; - - /** - * true for webkit-based browsers like Chrome and Safari (including mobile - * versions). - */ - export var webkit: boolean; - - /** - * true for webkit-based browsers that support CSS 3D transformations. - */ - export var webkit3d: boolean; - - /** - * true for Android mobile browser. - */ - export var android: boolean; - - /** - * true for old Android stock browsers (2 and 3). - */ - export var android23: boolean; - - /** - * true for modern mobile browsers (including iOS Safari and different Android - * browsers). - */ - export var mobile: boolean; - - /** - * true for mobile webkit-based browsers. - */ - export var mobileWebkit: boolean; - - /** - * true for mobile Opera. - */ - export var mobileOpera: boolean; - - /** - * true for all browsers on touch devices. - */ - export var touch: boolean; - - /** - * true for browsers with Microsoft touch model (e.g. IE10). - */ - export var msTouch: boolean; - - /** - * true for devices with Retina screens. - */ - export var retina: boolean; - - } -} - - -declare namespace L { - - /** - * Instantiates a circle object given a geographical point, a radius in meters - * and optionally an options object. - */ - function circle(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; - - export interface CircleStatic extends ClassStatic { - /** - * Instantiates a circle object given a geographical point, a radius in meters - * and optionally an options object. - */ - new(latlng: LatLngExpression, radius: number, options?: PathOptions): Circle; - } - export var Circle: CircleStatic; - - export interface Circle extends Path { - /** - * Returns the current geographical position of the circle. - */ - getLatLng(): LatLng; - - /** - * Returns the current radius of a circle. Units are in meters. - */ - getRadius(): number; - - /** - * Sets the position of a circle to a new location. - */ - setLatLng(latlng: LatLngExpression): Circle; - - /** - * Sets the radius of a circle. Units are in meters. - */ - setRadius(radius: number): Circle; - - /** - * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). - */ - toGeoJSON(): GeoJSON.Feature; - - } -} - -declare namespace L { - - /** - * Instantiates a circle marker given a geographical point and optionally - * an options object. The default radius is 10 and can be altered by passing a - * "radius" member in the path options object. - */ - function circleMarker(latlng: LatLngExpression, options?: PathOptions): CircleMarker; - - - export interface CircleMarkerStatic extends ClassStatic { - /** - * Instantiates a circle marker given a geographical point and optionally - * an options object. The default radius is 10 and can be altered by passing a - * "radius" member in the path options object. - */ - new(latlng: LatLngExpression, options?: PathOptions): CircleMarker; - } - export var CircleMarker: CircleMarkerStatic; - - export interface CircleMarker extends Circle { - /** - * Sets the position of a circle marker to a new location. - */ - setLatLng(latlng: LatLngExpression): CircleMarker; - - /** - * Sets the radius of a circle marker. Units are in pixels. - */ - setRadius(radius: number): CircleMarker; - } -} - -declare namespace L { - export interface ClassExtendOptions { - /** - * Your class's constructor function, meaning that it gets called when you do 'new MyClass(...)'. - */ - initialize?: Function; - - /** - * options is a special property that unlike other objects that you pass - * to extend will be merged with the parent one instead of overriding it - * completely, which makes managing configuration of objects and default - * values convenient. - */ - options?: any; - - /** - * includes is a special class property that merges all specified objects - * into the class (such objects are called mixins). A good example of this - * is L.Mixin.Events that event-related methods like on, off and fire - * to the class. - */ - includes?: any; - - /** - * statics is just a convenience property that injects specified object - * properties as the static properties of the class, useful for defining - * constants. - */ - static?: any; - - [prop: string]: any; - } - - export interface ClassStatic { - /** - * You use L.Class.extend to define new classes, but you can use the - * same method on any class to inherit from it. - */ - extend(options: ClassExtendOptions): any; - extend(options: ClassExtendOptions): { new(options?: Options): NewClass }; - - /** - * You can also use the following shortcut when you just need to make - * one additional method call. - */ - addInitHook(methodName: string, ...args: any[]): void; - } - - - /** - * L.Class powers the OOP facilities of Leaflet and is used to create - * almost all of the Leaflet classes documented. - */ - namespace Class { - /** - * You use L.Class.extend to define new classes, but you can use the - * same method on any class to inherit from it. - */ - function extend(options: ClassExtendOptions): any; - } - -} - -declare namespace L { - export interface ControlStatic extends ClassStatic { - /** - * Creates a control with the given options. - */ - new(options?: ControlOptions): Control; - - Zoom: Control.ZoomStatic; - Attribution: Control.AttributionStatic; - Layers: Control.LayersStatic; - Scale: Control.ScaleStatic; - } - export var Control: ControlStatic; - - export interface Control extends IControl { - /** - * Sets the position of the control. See control positions. - */ - setPosition(position: PositionString): Control; - - /** - * Returns the current position of the control. - */ - getPosition(): PositionString; - - /** - * Adds the control to the map. - */ - addTo(map: Map): Control; - - /** - * Removes the control from the map. - */ - removeFrom(map: Map): Control; - - /** - * Returns the HTML container of the control. - */ - getContainer(): HTMLElement; - - // IControl members - - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; - - /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. - */ - onRemove(map: Map): void; - } - - namespace Control { - export interface ZoomStatic extends ClassStatic { - /** - * Creates a zoom control. - */ - new (options?: ZoomOptions): Zoom; - } - - export interface Zoom extends L.Control { - } - - export interface ZoomOptions { - /** - * The position of the control (one of the map corners). - * Can be 'topleft', 'topright', 'bottomleft', or 'bottomright'. - * - * Default value: 'topright'. - */ - position?: PositionString; - - /** - * The text set on the zoom in button. - * - * Default value: '+' - */ - zoomInText?: string; - - /** - * The text set on the zoom out button. - * - * Default value: '-' - */ - zoomOutText?: string; - - /** - * The title set on the zoom in button. - * - * Default value: 'Zoom in' - */ - zoomInTitle?: string; - - /** - * The title set on the zoom out button. - * - * Default value: 'Zoom out' - */ - zoomOutTitle?: string; - } - - export interface AttributionStatic extends ClassStatic { - /** - * Creates an attribution control. - */ - new(options?: AttributionOptions): Attribution; - } - - export interface Attribution extends L.Control { - /** - * Sets the text before the attributions. - */ - setPrefix(prefix: string): Attribution; - - /** - * Adds an attribution text (e.g. 'Vector data © CloudMade'). - */ - addAttribution(text: string): Attribution; - - /** - * Removes an attribution text. - */ - removeAttribution(text: string): Attribution; - - } - - export interface LayersStatic extends ClassStatic { - /** - * Creates an attribution control with the given layers. Base layers will be - * switched with radio buttons, while overlays will be switched with checkboxes. - */ - new(baseLayers?: any, overlays?: any, options?: LayersOptions): Layers; - } - - export interface Layers extends L.Control, IEventPowered { - /** - * Adds a base layer (radio button entry) with the given name to the control. - */ - addBaseLayer(layer: ILayer, name: string): Layers; - - /** - * Adds an overlay (checkbox entry) with the given name to the control. - */ - addOverlay(layer: ILayer, name: string): Layers; - - /** - * Remove the given layer from the control. - */ - removeLayer(layer: ILayer): Layers; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Layers; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Layers; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Layers; - fire(type: string, data?: any): Layers; - addEventListener(eventMap: any, context?: any): Layers; - removeEventListener(eventMap?: any, context?: any): Layers; - clearAllEventListeners(): Layers; - on(eventMap: any, context?: any): Layers; - off(eventMap?: any, context?: any): Layers; - } - - export interface ScaleStatic extends ClassStatic { - /** - * Creates an scale control with the given options. - */ - new(options?: ScaleOptions): Scale; - } - - export interface Scale extends L.Control { - } - } - - export interface control { - /** - * Creates a control with the given options. - */ - (options?: ControlOptions): Control; - } - - export namespace control { - - /** - * Creates a zoom control. - */ - export function zoom(options?: Control.ZoomOptions): L.Control.Zoom; - - /** - * Creates an attribution control. - */ - export function attribution(options?: AttributionOptions): L.Control.Attribution; - - /** - * Creates an attribution control with the given layers. Base layers will be - * switched with radio buttons, while overlays will be switched with checkboxes. - */ - export function layers(baseLayers?: any, overlays?: any, options?: LayersOptions): L.Control.Layers; - - /** - * Creates an scale control with the given options. - */ - export function scale(options?: ScaleOptions): L.Control.Scale; - } -} - -declare namespace L { - - export interface ControlOptions { - - /** - * The initial position of the control (one of the map corners). See control - * positions. - * Default value: 'topright'. - */ - position?: PositionString; - - } -} - -declare namespace L { - - namespace CRS { - - /** - * The most common CRS for online maps, used by almost all free and commercial - * tile providers. Uses Spherical Mercator projection. Set in by default in - * Map's crs option. - */ - export var EPSG3857: ICRS; - - /** - * A common CRS among GIS enthusiasts. Uses simple Equirectangular projection. - */ - export var EPSG4326: ICRS; - - /** - * Rarely used by some commercial tile providers. Uses Elliptical Mercator - * projection. - */ - export var EPSG3395: ICRS; - - /** - * A simple CRS that maps longitude and latitude into x and y directly. May be - * used for maps of flat surfaces (e.g. game maps). Note that the y axis should - * still be inverted (going from bottom to top). - */ - export var Simple: ICRS; - - } -} - -declare namespace L { - - /** - * Creates a div icon instance with the given options. - */ - function divIcon(options: DivIconOptions): DivIcon; - - export interface DivIconStatic extends ClassStatic { - /** - * Creates a div icon instance with the given options. - */ - new(options: DivIconOptions): DivIcon; - } - export var DivIcon: DivIconStatic; - - export interface DivIcon extends Icon { - } -} - -declare namespace L { - - export interface DivIconOptions { - - /** - * Size of the icon in pixels. Can be also set through CSS. - */ - iconSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point|[number, number]; - - /** - * A custom class name to assign to the icon. - * - * Default value: 'leaflet-div-icon'. - */ - className?: string; - - /** - * A custom HTML code to put inside the div element. - * - * Default value: ''. - */ - html?: string; - - /** - * The coordinates of the point from which popups will "open", relative to the - * icon anchor. - */ - popupAnchor?: Point|[number, number]; - - } -} - -declare namespace L { - - export interface DomEvent { - - /** - * Adds a listener fn to the element's DOM event of the specified type. this keyword - * inside the listener will point to context, or to the element if not specified. - */ - addListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - on(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - - /** - * Removes an event listener from the element. - */ - removeListener(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - off(el: HTMLElement, type: string, fn: (e: Event) => void, context?: any): DomEvent; - - /** - * Stop the given event from propagation to parent elements. Used inside the - * listener functions: - * L.DomEvent.addListener(div, 'click', function - * (e) { - * L.DomEvent.stopPropagation(e); - * }); - */ - stopPropagation(e: Event): DomEvent; - - /** - * Prevents the default action of the event from happening (such as following - * a link in the href of the a element, or doing a POST request with page reload - * when form is submitted). Use it inside listener functions. - */ - preventDefault(e: Event): DomEvent; - - /** - * Does stopPropagation and preventDefault at the same time. - */ - stop(e: Event): DomEvent; - - /** - * Adds stopPropagation to the element's 'click', 'doubleclick', 'mousedown' - * and 'touchstart' events. - */ - disableClickPropagation(el: HTMLElement): DomEvent; - - /** - * Gets normalized mouse position from a DOM event relative to the container - * or to the whole page if not specified. - */ - getMousePosition(e: Event, container?: HTMLElement): Point; - - /** - * Gets normalized wheel delta from a mousewheel DOM event. - */ - getWheelDelta(e: Event): number; - - } - - export var DomEvent: DomEvent; -} - -declare namespace L { - - namespace DomUtil { - - /** - * Returns an element with the given id if a string was passed, or just returns - * the element if it was passed directly. - */ - export function get(id: string): HTMLElement; - - /** - * Returns the value for a certain style attribute on an element, including - * computed values or values set through CSS. - */ - export function getStyle(el: HTMLElement, style: string): string; - - /** - * Returns the offset to the viewport for the requested element. - */ - export function getViewportOffset(el: HTMLElement): Point; - - /** - * Creates an element with tagName, sets the className, and optionally appends - * it to container element. - */ - export function create(tagName: string, className: string, container?: HTMLElement): HTMLElement; - - /** - * Makes sure text cannot be selected, for example during dragging. - */ - export function disableTextSelection(): void; - - /** - * Makes text selection possible again. - */ - export function enableTextSelection(): void; - - /** - * Returns true if the element class attribute contains name. - */ - export function hasClass(el: HTMLElement, name: string): boolean; - - /** - * Adds name to the element's class attribute. - */ - export function addClass(el: HTMLElement, name: string): void; - - /** - * Removes name from the element's class attribute. - */ - export function removeClass(el: HTMLElement, name: string): void; - - /** - * Set the opacity of an element (including old IE support). Value must be from - * 0 to 1. - */ - export function setOpacity(el: HTMLElement, value: number): void; - - /** - * Goes through the array of style names and returns the first name that is a valid - * style name for an element. If no such name is found, it returns false. Useful - * for vendor-prefixed styles like transform. - */ - export function testProp(props: string[]): any; - - /** - * Returns a CSS transform string to move an element by the offset provided in - * the given point. Uses 3D translate on WebKit for hardware-accelerated transforms - * and 2D on other browsers. - */ - export function getTranslateString(point: Point): string; - - /** - * Returns a CSS transform string to scale an element (with the given scale origin). - */ - export function getScaleString(scale: number, origin: Point): string; - - /** - * Sets the position of an element to coordinates specified by point, using - * CSS translate or top/left positioning depending on the browser (used by - * Leaflet internally to position its layers). Forces top/left positioning - * if disable3D is true. - */ - export function setPosition(el: HTMLElement, point: Point, disable3D?: boolean): void; - - /** - * Returns the coordinates of an element previously positioned with setPosition. - */ - export function getPosition(el: HTMLElement): Point; - - /** - * Vendor-prefixed transition style name (e.g. 'webkitTransition' for WebKit). - */ - export var TRANSITION: string; - - /** - * Vendor-prefixed transform style name. - */ - export var TRANSFORM: string; - - } -} - -declare namespace L { - export interface DraggableStatic extends ClassStatic { - /** - * Creates a Draggable object for moving the given element when you start dragging - * the dragHandle element (equals the element itself by default). - */ - new(element: HTMLElement, dragHandle?: HTMLElement): Draggable; - } - export var Draggable: DraggableStatic; - - - export interface Draggable extends IEventPowered { - /** - * Enables the dragging ability. - */ - enable(): void; - - /** - * Disables the dragging ability. - */ - disable(): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Draggable; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Draggable; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Draggable; - fire(type: string, data?: any): Draggable; - addEventListener(eventMap: any, context?: any): Draggable; - removeEventListener(eventMap?: any, context?: any): Draggable; - clearAllEventListeners(): Draggable; - on(eventMap: any, context?: any): Draggable; - off(eventMap?: any, context?: any): Draggable; - } -} - - - -declare namespace L { - - /** - * Create a layer group, optionally given an initial set of layers. - */ - function featureGroup(layers?: T[]): FeatureGroup; - - - export interface FeatureGroupStatic extends ClassStatic { - /** - * Create a layer group, optionally given an initial set of layers. - */ - new(layers?: T[]): FeatureGroup; - } - export var FeatureGroup: FeatureGroupStatic; - - export interface FeatureGroup extends LayerGroup, ILayer, IEventPowered> { - /** - * Binds a popup with a particular HTML content to a click on any layer from the - * group that has a bindPopup method. - */ - bindPopup(htmlContent: string, options?: PopupOptions): FeatureGroup; - - /** - * Returns the LatLngBounds of the Feature Group (created from bounds and coordinates - * of its children). - */ - getBounds(): LatLngBounds; - - /** - * Sets the given path options to each layer of the group that has a setStyle method. - */ - setStyle(style: PathOptions): FeatureGroup; - - /** - * Brings the layer group to the top of all other layers. - */ - bringToFront(): FeatureGroup; - - /** - * Brings the layer group to the bottom of all other layers. - */ - bringToBack(): FeatureGroup; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): FeatureGroup; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): FeatureGroup; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): FeatureGroup; - fire(type: string, data?: any): FeatureGroup; - addEventListener(eventMap: any, context?: any): FeatureGroup; - removeEventListener(eventMap?: any, context?: any): FeatureGroup; - clearAllEventListeners(): FeatureGroup; - on(eventMap: any, context?: any): FeatureGroup; - off(eventMap?: any, context?: any): FeatureGroup; - } -} - -declare namespace L { - - /** - * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format - * to display on the map (you can alternatively add it later with addData method) - * and an options object. - */ - function geoJson(geojson?: any, options?: GeoJSONOptions): GeoJSON; - - export interface GeoJSONStatic extends ClassStatic { - /** - * Creates a GeoJSON layer. Optionally accepts an object in GeoJSON format - * to display on the map (you can alternatively add it later with addData method) - * and an options object. - */ - new(geojson?: any, options?: GeoJSONOptions): GeoJSON; - - /** - * Creates a layer from a given GeoJSON feature. - */ - geometryToLayer(featureData: GeoJSON, pointToLayer?: (featureData: any, latlng: LatLng) => ILayer): ILayer; - - /** - * Creates a LatLng object from an array of 2 numbers (latitude, longitude) - * used in GeoJSON for points. If reverse is set to true, the numbers will be interpreted - * as (longitude, latitude). - */ - coordsToLatLng(coords: number[], reverse?: boolean): LatLng; - - /** - * Creates a multidimensional array of LatLng objects from a GeoJSON coordinates - * array. levelsDeep specifies the nesting level (0 is for an array of points, - * 1 for an array of arrays of points, etc., 0 by default). If reverse is set to - * true, the numbers will be interpreted as (longitude, latitude). - */ - coordsToLatLngs(coords: any[], levelsDeep?: number, reverse?: boolean): any[]; - } - export var GeoJSON: GeoJSONStatic; - - export interface GeoJSON extends FeatureGroup { - /** - * Adds a GeoJSON object to the layer. - */ - addData(data: any): boolean; - - /** - * Changes styles of GeoJSON vector layers with the given style function. - */ - setStyle(style: (featureData: any) => any): GeoJSON; - - /** - * Changes styles of GeoJSON vector layers with the given style options. - */ - setStyle(style: PathOptions): GeoJSON; - - /** - * Resets the the given vector layer's style to the original GeoJSON style, - * useful for resetting style after hover events. - */ - resetStyle(layer: Path): GeoJSON; - } -} - -declare namespace L { - export interface GeoJSONOptions { - /** - * Function that will be used for creating layers for GeoJSON points (if not - * specified, simple markers will be created). - */ - pointToLayer?: (featureData: any, latlng: LatLng) => ILayer; - - /** - * Function that will be used to get style options for vector layers created - * for GeoJSON features. - */ - style?: (featureData: any) => any; - - /** - * Function that will be called on each created feature layer. Useful for attaching - * events and popups to features. - */ - onEachFeature?: (featureData: any, layer: ILayer) => void; - - /** - * Function that will be used to decide whether to show a feature or not. - */ - filter?: (featureData: any, layer: ILayer) => boolean; - - /** - * Function that will be used for converting GeoJSON coordinates to LatLng points - * (if not specified, coords will be assumed to be WGS84 � standard[longitude, latitude] - * values in degrees). - */ - coordsToLatLng?: (coords: any[]) => LatLng[]; - } -} - - - - -declare namespace L { - - /** - * Creates an icon instance with the given options. - */ - function icon(options: IconOptions): Icon; - - export interface IconStatic extends ClassStatic { - /** - * Creates an icon instance with the given options. - */ - new(options: IconOptions): Icon; - - Default: { - /** - * Creates a default icon instance with the given options. - */ - new(options?: IconOptions): Icon.Default; - - imagePath: string; - }; - } - export var Icon: IconStatic; - - export interface Icon { - } - - namespace Icon { - /** - * L.Icon.Default extends L.Icon and is the blue icon Leaflet uses - * for markers by default. - */ - export interface Default extends Icon { - } - } -} - -declare namespace L { - - export interface IconOptions { - - /** - * (required) The URL to the icon image (absolute or relative to your script - * path). - */ - iconUrl?: string; - - /** - * The URL to a retina sized version of the icon image (absolute or relative to - * your script path). Used for Retina screen devices. - */ - iconRetinaUrl?: string; - - /** - * Size of the icon image in pixels. - */ - iconSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the icon (relative to its top left corner). - * The icon will be aligned so that this point is at the marker's geographical - * location. Centered by default if size is specified, also can be set in CSS - * with negative margins. - */ - iconAnchor?: Point|[number, number]; - - /** - * The URL to the icon shadow image. If not specified, no shadow image will be - * created. - */ - shadowUrl?: string; - - /** - * The URL to the retina sized version of the icon shadow image. If not specified, - * no shadow image will be created. Used for Retina screen devices. - */ - shadowRetinaUrl?: string; - - /** - * Size of the shadow image in pixels. - */ - shadowSize?: Point|[number, number]; - - /** - * The coordinates of the "tip" of the shadow (relative to its top left corner) - * (the same as iconAnchor if not specified). - */ - shadowAnchor?: Point|[number, number]; - - /** - * The coordinates of the point from which popups will "open", relative to the - * icon anchor. - */ - popupAnchor?: Point|[number, number]; - - /** - * A custom class name to assign to both icon and shadow images. Empty by default. - */ - className?: string; - } -} - -declare namespace L { - - export interface IControl { - - /** - * Should contain code that creates all the neccessary DOM elements for the - * control, adds listeners on relevant map events, and returns the element - * containing the control. Called on map.addControl(control) or control.addTo(map). - */ - onAdd(map: Map): HTMLElement; - - /** - * Optional, should contain all clean up code (e.g. removes control's event - * listeners). Called on map.removeControl(control) or control.removeFrom(map). - * The control's DOM container is removed automatically. - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - - export interface ICRS { - - /** - * Projection that this CRS uses. - */ - projection: IProjection; - - /** - * Transformation that this CRS uses to turn projected coordinates into screen - * coordinates for a particular tile service. - */ - transformation: Transformation; - - /** - * Standard code name of the CRS passed into WMS services (e.g. 'EPSG:3857'). - */ - code: string; - - /** - * Projects geographical coordinates on a given zoom into pixel coordinates. - */ + export interface CRS { latLngToPoint(latlng: LatLng, zoom: number): Point; - - /** - * The inverse of latLngToPoint. Projects pixel coordinates on a given zoom - * into geographical coordinates. - */ - pointToLatLng(point: Point, zoom: number): LatLng; - - /** - * Projects geographical coordinates into coordinates in units accepted - * for this CRS (e.g. meters for EPSG:3857, for passing it to WMS services). - */ + latLngToPoint(latlng: LatLngLiteral, zoom: number): Point; + latLngToPoint(latlng: LatLngTuple, zoom: number): Point; + pointToLatLng(point: Point): LatLng; + pointToLatLng(point: PointTuple): LatLng; project(latlng: LatLng): Point; - - /** - * Returns the scale used when transforming projected coordinates into pixel - * coordinates for a particular zoom. For example, it returns 256 * 2^zoom for - * Mercator-based CRS. - */ - scale(zoom: number): number; - - /** - * Returns the size of the world in pixels for a particular zoom. - */ - getSize(zoom: number): Point; - - } -} - -declare namespace L { - - export interface IEventPowered { - - /** - * Adds a listener function (fn) to a particular event type of the object. You - * can optionally specify the context of the listener (object the this keyword - * will point to). You can also pass several space-separated types (e.g. 'click - * dblclick'). - */ - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * The same as above except the listener will only get fired once and then removed. - */ - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - /** - * Adds a set of type/listener pairs, e.g. {click: onClick, mousemove: onMouseMove} - */ - addEventListener(eventMap: any, context?: any): T; - - /** - * Removes a previously added listener function. If no function is specified, - * it will remove all the listeners of that particular event from the object. - */ - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; - - /** - * Removes a set of type/listener pairs. - */ - removeEventListener(eventMap?: any, context?: any): T; - - /** - * Returns true if a particular event type has some listeners attached to it. - */ - hasEventListeners(type: string): boolean; - - /** - * Fires an event of the specified type. You can optionally provide an data object - * — the first argument of the listener function will contain its properties. - */ - fireEvent(type: string, data?: any): T; - - /** - * Removes all listeners to all events on the object. - */ - clearAllEventListeners(): T; - - /** - * Alias to addEventListener. - */ - on(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to addEventListener. - */ - on(eventMap: any, context?: any): T; - - /** - * Alias to addOneTimeEventListener. - */ - once(type: string, fn: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to removeEventListener. - */ - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): T; - - /** - * Alias to removeEventListener. - */ - off(eventMap?: any, context?: any): T; - - /** - * Alias to fireEvent. - */ - fire(type: string, data?: any): T; - } -} - -declare namespace L { - - export interface IHandler { - - /** - * Enables the handler. - */ - enable(): void; - - /** - * Disables the handler. - */ - disable(): void; - - /** - * Returns true if the handler is enabled. - */ - enabled(): boolean; - } - - export interface Handler { - initialize(map: Map): void; - } -} - -declare namespace L { - - export interface ILayer { - - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - namespace Mixin { - export interface LeafletMixinEvents extends IEventPowered { - } - - export var Events: LeafletMixinEvents; - } -} - -declare namespace L { - - /** - * Instantiates an image overlay object given the URL of the image and the geographical - * bounds it is tied to. - */ - function imageOverlay(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; - - export interface ImageOverlayStatic extends ClassStatic { - /** - * Instantiates an image overlay object given the URL of the image and the geographical - * bounds it is tied to. - */ - new(imageUrl: string, bounds: LatLngBounds, options?: ImageOverlayOptions): ImageOverlay; - } - export var ImageOverlay: ImageOverlayStatic; - - export interface ImageOverlay extends ILayer { - /** - * Adds the overlay to the map. - */ - addTo(map: Map): ImageOverlay; - - /** - * Sets the opacity of the overlay. - */ - setOpacity(opacity: number): ImageOverlay; - - /** - * Changes the URL of the image. - */ - setUrl(imageUrl: string): ImageOverlay; - - /** - * Brings the layer to the top of all overlays. - */ - bringToFront(): ImageOverlay; - - /** - * Brings the layer to the bottom of all overlays. - */ - bringToBack(): ImageOverlay; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - -declare namespace L { - - export interface ImageOverlayOptions { - - /** - * The opacity of the image overlay. - */ - opacity?: number; - } -} - -declare namespace L { - - export interface IProjection { - - /** - * Projects geographical coordinates into a 2D point. - */ - project(latlng: LatLng): Point; - - /** - * The inverse of project. Projects a 2D point into geographical location. - */ + project(latlng: LatLngLiteral): Point; + project(latlng: LatLngTuple): Point; unproject(point: Point): LatLng; + unproject(point: PointTuple): LatLng; + scale(zoom: number): number; + zoom(scale: number): number; + getProjectedBounds(zoom: number): Bounds; + distance(latlng1: LatLng, latlng2: LatLng): number; + distance(latlng1: LatLngLiteral, latlng2: LatLngLiteral): number; + distance(latlng1: LatLngTuple, latlng2: LatLngTuple): number; + wrapLatLng(latlng: LatLng): LatLng; + wrapLatLng(latlng: LatLngLiteral): LatLng; + wrapLatLng(latlng: LatLngTuple): LatLng; + + code: string; + wrapLng: [number, number]; + wrapLat: [number, number]; + infinite: boolean; } -} -declare namespace L { - - /** - * A constant that represents the Leaflet version in use. - */ - export var version: string; - - /** - * This method restores the L global variale to the original value it had - * before Leaflet inclusion, and returns the real Leaflet namespace. - */ - export function noConflict(): typeof L; -} - -declare namespace L { - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - function latLng(latitude: number, longitude: number): LatLng; - - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - function latLng(coords: LatLngExpression): LatLng; - - export interface LatLngStatic { - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - new(latitude: number, longitude: number): LatLng; - - /** - * Creates an object representing a geographical point with the given latitude - * and longitude. - */ - new(coords: LatLngExpression): LatLng; - - /** - * A multiplier for converting degrees into radians. - * - * Value: Math.PI / 180. - */ - DEG_TO_RAD: number; - - /** - * A multiplier for converting radians into degrees. - * - * Value: 180 / Math.PI. - */ - RAD_TO_DEG: number; - - /** - * Max margin of error for the equality check. - * - * Value: 1.0E-9. - */ - MAX_MARGIN: number; + export namespace CRS { + export const EPSG3395: CRS; + export const EPSG3857: CRS; + export const EPSG4326: CRS; + export const Earth: CRS; + export const Simple: CRS; + } + + export interface Projection { + project(latlng: LatLng): Point; + project(latlng: LatLngLiteral): Point; + project(latlng: LatLngTuple): Point; + unproject(point: Point): LatLng; + unproject(point: PointTuple): LatLng; + + bounds: LatLngBounds; + } + + export namespace Projection { + export const LonLat: Projection; + export const Mercator: Projection; + export const SphericalMercator: Projection; } - export var LatLng: LatLngStatic; export interface LatLng { - /** - * Returns the distance (in meters) to the given LatLng calculated using the - * Haversine formula. See description on wikipedia - */ - distanceTo(otherLatlng: LatLngExpression): number; - - /** - * Returns true if the given LatLng point is at the same position (within a small - * margin of error). - */ - equals(otherLatlng: LatLngExpression): boolean; - - /** - * Returns a string representation of the point (for debugging purposes). - */ + equals(otherLatLng: LatLng, maxMargin?: number): boolean; + equals(otherLatLng: LatLngLiteral, maxMargin?: number): boolean; + equals(otherLatLng: LatLngTuple, maxMargin?: number): boolean; toString(): string; + distanceTo(otherLatLng: LatLng): number; + distanceTo(otherLatLng: LatLngLiteral): number; + distanceTo(otherLatLng: LatLngTuple): number; + wrap(): LatLng; + toBounds(sizeInMeters: number): LatLngBounds; - /** - * Returns a new LatLng object with the longitude wrapped around left and right - * boundaries (-180 to 180 by default). - */ - wrap(left?: number, right?: number): LatLng; - - /** - * Latitude in degrees. - */ lat: number; + lng: number; + alt: number; + } - /** - * Longitude in degrees. - */ + export interface LatLngLiteral { + lat: number; lng: number; } -} -declare namespace L { + export type LatLngTuple = [number, number]; - /** - * Creates a LatLngBounds object by defining south-west and north-east corners - * of the rectangle. - */ - function latLngBounds(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + type LatLngExpression = LatLng | LatLngLiteral | LatLngTuple; - /** - * Creates a LatLngBounds object defined by the geographical points it contains. - * Very useful for zooming the map to fit a particular set of locations with fitBounds. - */ - function latLngBounds(latlngs: LatLngBoundsExpression): LatLngBounds; + export function latLng(latitude: number, longitude: number, altitude?: number): LatLng; - export interface LatLngBoundsStatic { - /** - * Creates a LatLngBounds object by defining south-west and north-east corners - * of the rectangle. - */ - new(southWest: LatLngExpression, northEast: LatLngExpression): LatLngBounds; + export function latLng(coords: LatLngTuple): LatLng; - /** - * Creates a LatLngBounds object defined by the geographical points it contains. - * Very useful for zooming the map to fit a particular set of locations with fitBounds. - */ - new(latlngs: LatLngBoundsExpression): LatLngBounds; - } - export var LatLngBounds: LatLngBoundsStatic; + export function latLng(coords: [number, number, number]): LatLng; + + export function latLng(coords: LatLngLiteral): LatLng; + + export function latLng(coords: {lat: number, lng: number, alt: number}): LatLng; export interface LatLngBounds { - /** - * Extends the bounds to contain the given point. - */ - extend(latlng: LatLngExpression): LatLngBounds; - - /** - * Extends the bounds to contain the given bounds. - */ - extend(latlng: LatLngBoundsExpression): LatLngBounds; - - /** - * Returns the south-west point of the bounds. - */ + extend(latlng: LatLng): this; + extend(latlng: LatLngLiteral): this; + extend(latlng: LatLngTuple): this; + extend(otherBounds: LatLngBounds): this; + extend(otherBounds: LatLngBoundsLiteral): this; + pad(bufferRatio: number): LatLngBounds; // does this modify the current instance or does it return a new one? + getCenter(): LatLng; getSouthWest(): LatLng; - - /** - * Returns the north-east point of the bounds. - */ getNorthEast(): LatLng; - - /** - * Returns the north-west point of the bounds. - */ getNorthWest(): LatLng; - - /** - * Returns the south-east point of the bounds. - */ getSouthEast(): LatLng; - - /** - * Returns the west longitude in degrees of the bounds. - */ - getWest(): number; - - /** - * Returns the east longitude in degrees of the bounds. - */ - getEast(): number; - - /** - * Returns the north latitude in degrees of the bounds. - */ - getNorth(): number; - - /** - * Returns the south latitude in degrees of the bounds. - */ - getSouth(): number; - - /** - * Returns the center point of the bounds. - */ - getCenter(): LatLng; - - /** - * Returns true if the rectangle contains the given one. - */ - contains(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns true if the rectangle contains the given point. - */ - contains(latlng: LatLngExpression): boolean; - - /** - * Returns true if the rectangle intersects the given bounds. - */ - intersects(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns true if the rectangle is equivalent (within a small margin of error) - * to the given bounds. - */ - equals(otherBounds: LatLngBoundsExpression): boolean; - - /** - * Returns a string with bounding box coordinates in a 'southwest_lng,southwest_lat,northeast_lng,northeast_lat' - * format. Useful for sending requests to web services that return geo data. - */ + getWest(): number; + getSouth(): number; + getEast(): number; + getNorth(): number; + contains(otherBounds: LatLngBounds): boolean; + contains(otherBounds: LatLngBoundsLiteral): boolean; + contains(latlng: LatLng): boolean; + contains(latlng: LatLngLiteral): boolean; + contains(latlng: LatLngTuple): boolean; + intersects(otherBounds: LatLngBounds): boolean; + intersects(otherBounds: LatLngLiteral): boolean; + overlaps(otherBounds: Bounds): boolean; // investigate if this is really bounds and not latlngbounds + overlaps(otherBounds: BoundsLiteral): boolean; toBBoxString(): string; - - /** - * Returns bigger bounds created by extending the current bounds by a given - * percentage in each direction. - */ - pad(bufferRatio: number): LatLngBounds; - - /** - * Returns true if the bounds are properly initialized. - */ + equals(otherBounds: LatLngBounds): boolean; + equals(otherBounds: LatLngBoundsLiteral): boolean; isValid(): boolean; - } -} -declare namespace L { + export type LatLngBoundsLiteral = Array; - /** - * Create a layer group, optionally given an initial set of layers. - */ - function layerGroup(layers?: T[]): LayerGroup; + type LatLngBoundsExpression = LatLngBounds | LatLngBoundsLiteral; + export function latLngBounds(southWest: LatLng, northEast: LatLng): LatLngBounds; - export interface LayerGroupStatic extends ClassStatic { - /** - * Create a layer group, optionally given an initial set of layers. - */ - new(layers?: T[]): LayerGroup; + export function latLngBounds(southWest: LatLngLiteral, northEast: LatLngLiteral): LatLngBounds; + + export function latLngBounds(southWest: LatLngTuple, northEast: LatLngTuple): LatLngBounds; + + export function latLngBounds(latlngs: LatLngBoundsLiteral): LatLngBounds; + + export type PointTuple = [number, number]; + + export interface Point { + clone(): Point; + add(otherPoint: Point): Point; // investigate if this mutates or returns a new instance + add(otherPoint: PointTuple): Point; + subtract(otherPoint: Point): Point; + subtract(otherPoint: PointTuple): Point; + divideBy(num: number): Point; + multiplyBy(num: number): Point; + scaleBy(scale: Point): Point; + scaleBy(scale: PointTuple): Point; + unscaleBy(scale: Point): Point; + unscaleBy(scale: PointTuple): Point; + round(): Point; + floor(): Point; + ceil(): Point; + distanceTo(otherPoint: Point): Point; + distanceTo(otherPoint: PointTuple): Point; + equals(otherPoint: Point): boolean; + equals(otherPoint: PointTuple): boolean; + contains(otherPoint: Point): boolean; + contains(otherPoint: PointTuple): boolean; + toString(): string; } - export var LayerGroup: LayerGroupStatic; - export interface LayerGroup extends ILayer { - /** - * Adds the group of layers to the map. - */ - addTo(map: Map): LayerGroup; + type PointExpression = Point | PointTuple; - /** - * Adds a given layer to the group. - */ - addLayer(layer: T): LayerGroup; + export function point(x: number, y: number, round?: boolean): Point; - /** - * Removes a given layer from the group. - */ - removeLayer(layer: T): LayerGroup; + export function point(coords: PointTuple): Point; - /** - * Removes a given layer of the given id from the group. - */ - removeLayer(id: string): LayerGroup; + export function point(coords: {x: number, y: number}): Point; - /** - * Returns true if the given layer is currently added to the group. - */ - hasLayer(layer: T): boolean; + export type BoundsLiteral = Array; - /** - * Returns the layer with the given id. - */ - getLayer(id: string): T; - - /** - * Returns an array of all the layers added to the group. - */ - getLayers(): T[]; - - /** - * Removes all the layers from the group. - */ - clearLayers(): LayerGroup; - - /** - * Iterates over the layers of the group, optionally specifying context of - * the iterator function. - */ - eachLayer(fn: (layer: T) => void, context?: any): LayerGroup; - - /** - * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). - * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s - */ - toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - } -} - - -declare namespace L { - - export interface LayersOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * - * Default value: 'topright'. - */ - position?: PositionString; - - /** - * If true, the control will be collapsed into an icon and expanded on mouse hover - * or touch. - * - * Default value: true. - */ - collapsed?: boolean; - - /** - * If true, the control will assign zIndexes in increasing order to all of its - * layers so that the order is preserved when switching them on/off. - * - * Default value: true. - */ - autoZIndex?: boolean; - - } -} - -declare namespace L { - - export interface LeafletErrorEvent extends LeafletEvent { - - /** - * Error message. - */ - message: string; - - /** - * Error code (if applicable). - */ - code: number; - } -} - -declare namespace L { - - export interface LeafletEvent { - - /** - * The event type (e.g. 'click'). - */ - type: string; - - /** - * The object that fired the event. - */ - target: any; - } -} - -declare namespace L { - - export interface LeafletGeoJSONEvent extends LeafletEvent { - - /** - * The layer for the GeoJSON feature that is being added to the map. - */ - layer: ILayer; - - /** - * GeoJSON properties of the feature. - */ - properties: any; - - /** - * GeoJSON geometry type of the feature. - */ - geometryType: string; - - /** - * GeoJSON ID of the feature (if present). - */ - id: string; - } -} - -declare namespace L { - - export interface LeafletLayerEvent extends LeafletEvent { - - /** - * The layer that was added or removed. - */ - layer: ILayer; - } -} - -declare namespace L { - - export interface LeafletLayersControlEvent extends LeafletEvent { - - /** - * The layer that was added or removed. - */ - layer: ILayer; - - /** - * The name of the layer that was added or removed. - */ - name: string; - } -} - -declare namespace L { - - export interface LeafletLocationEvent extends LeafletEvent { - - /** - * Detected geographical location of the user. - */ - latlng: LatLng; - - /** - * Geographical bounds of the area user is located in (with respect to the accuracy - * of location). - */ - bounds: LatLngBounds; - - /** - * Accuracy of location in meters. - */ - accuracy: number; - - /** - * Height of the position above the WGS84 ellipsoid in meters. - */ - altitude: number; - - /** - * Accuracy of altitude in meters. - */ - altitudeAccuracy: number; - - /** - * The direction of travel in degrees counting clockwise from true North. - */ - heading: number; - - /** - * Current velocity in meters per second. - */ - speed: number; - - /** - * The time when the position was acquired. - */ - timestamp: number; - - } -} - -declare namespace L { - - export interface LeafletMouseEvent extends LeafletEvent { - - /** - * The geographical point where the mouse event occured. - */ - latlng: LatLng; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map layer. - */ - layerPoint: Point; - - /** - * Pixel coordinates of the point where the mouse event occured relative to - * the map сontainer. - */ - containerPoint: Point; - - /** - * The original DOM mouse event fired by the browser. - */ - originalEvent: MouseEvent; - } -} - -declare namespace L { - - export interface LeafletPopupEvent extends LeafletEvent { - - /** - * The popup that was opened or closed. - */ - popup: Popup; - } -} - -declare namespace L { - - export interface LeafletDragEndEvent extends LeafletEvent { - - /** - * The distance in pixels the draggable element was moved by. - */ - distance: number; - } -} - -declare namespace L { - - export interface LeafletResizeEvent extends LeafletEvent { - - /** - * The old size before resize event. - */ - oldSize: Point; - - /** - * The new size after the resize event. - */ - newSize: Point; - } -} - -declare namespace L { - - export interface LeafletTileEvent extends LeafletEvent { - - /** - * The tile element (image). - */ - tile: HTMLElement; - - /** - * The source URL of the tile. - */ - url: string; - } -} - -declare namespace L { - - namespace LineUtil { - - /** - * Dramatically reduces the number of points in a polyline while retaining - * its shape and returns a new array of simplified points. Used for a huge performance - * boost when processing/displaying Leaflet polylines for each zoom level - * and also reducing visual noise. tolerance affects the amount of simplification - * (lesser value means higher quality but slower and with more points). Also - * released as a separated micro-library Simplify.js. - */ - export function simplify(points: Point[], tolerance: number): Point[]; - - /** - * Returns the distance between point p and segment p1 to p2. - */ - export function pointToSegmentDistance(p: Point, p1: Point, p2: Point): number; - - /** - * Returns the closest point from a point p on a segment p1 to p2. - */ - export function closestPointOnSegment(p: Point, p1: Point, p2: Point): Point; - - /** - * Clips the segment a to b by rectangular bounds. Used by Leaflet to only show - * polyline points that are on the screen or near, increasing performance. Returns - * either false or a length-2 array of clipped points. - */ - export function clipSegment(a: Point, b: Point, bounds: Bounds): Point[] | boolean; - - } -} - -declare namespace L { - - export interface LocateOptions { - - /** - * If true, starts continous watching of location changes (instead of detecting - * it once) using W3C watchPosition method. You can later stop watching using - * map.stopLocate() method. - * - * Default value: false. - */ - watch?: boolean; - - /** - * If true, automatically sets the map view to the user location with respect - * to detection accuracy, or to world view if geolocation failed. - * - * Default value: false. - */ - setView?: boolean; - - /** - * The maximum zoom for automatic view setting when using `setView` option. - * - * Default value: Infinity. - */ - maxZoom?: number; - - /** - * Number of millisecond to wait for a response from geolocation before firing - * a locationerror event. - * - * Default value: 10000. - */ - timeout?: number; - - /** - * Maximum age of detected location. If less than this amount of milliseconds - * passed since last geolocation response, locate will return a cached location. - * - * Default value: 0. - */ - maximumAge?: number; - - /** - * Enables high accuracy, see description in the W3C spec. - * - * Default value: false. - */ - enableHighAccuracy?: boolean; - } -} - -declare namespace L { - - /** - * Instantiates a map object given a div element and optionally an - * object literal with map options described below. - */ - function map(id: HTMLElement, options?: Map.MapOptions): Map; - - /** - * Instantiates a map object given a div element id and optionally an - * object literal with map options described below. - */ - function map(id: string, options?: Map.MapOptions): Map; - - - export interface MapStatic extends ClassStatic { - /** - * Instantiates a map object given a div element and optionally an - * object literal with map options described below. - * - * @constructor - */ - new(id: HTMLElement, options?: Map.MapOptions): Map; - - /** - * Instantiates a map object given a div element id and optionally an - * object literal with map options described below. - * - * @constructor - */ - new(id: string, options?: Map.MapOptions): Map; - } - export var Map: MapStatic; - - export interface Map extends IEventPowered { - // Methods for Modifying Map State - - /** - * Sets the view of the map (geographical center and zoom) with the given - * animation options. - */ - setView(center: LatLngExpression, zoom?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Sets the zoom of the map. - */ - setZoom(zoom: number, options?: Map.ZoomPanOptions): Map; - - /** - * Increases the zoom of the map by delta (1 by default). - */ - zoomIn(delta?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Decreases the zoom of the map by delta (1 by default). - */ - zoomOut(delta?: number, options?: Map.ZoomPanOptions): Map; - - /** - * Zooms the map while keeping a specified point on the map stationary - * (e.g. used internally for scroll zoom and double-click zoom). - */ - setZoomAround(latlng: LatLngExpression, zoom: number, options?: Map.ZoomPanOptions): Map; - - /** - * Sets a map view that contains the given geographical bounds with the maximum - * zoom level possible. - */ - fitBounds(bounds: LatLngBounds, options?: Map.FitBoundsOptions): Map; - - /** - * Sets a map view that mostly contains the whole world with the maximum zoom - * level possible. - */ - fitWorld(options?: Map.FitBoundsOptions): Map; - - /** - * Pans the map to a given center. Makes an animated pan if new center is not more - * than one screen away from the current one. - */ - panTo(latlng: LatLngExpression, options?: PanOptions): Map; - - /** - * Pans the map to the closest view that would lie inside the given bounds (if - * it's not already). - */ - panInsideBounds(bounds: LatLngBounds): Map; - - /** - * Pans the map by a given number of pixels (animated). - */ - panBy(point: Point, options?: PanOptions): Map; - - /** - * Checks if the map container size changed and updates the map if so — call it - * after you've changed the map size dynamically, also animating pan by default. - * If options.pan is false, panning will not occur. - */ - invalidateSize(options: Map.ZoomPanOptions): Map; - - /** - * Checks if the map container size changed and updates the map if so — call it - * after you've changed the map size dynamically, also animating pan by default. - */ - invalidateSize(animate: boolean): Map; - - /** - * Restricts the map view to the given bounds (see map maxBounds option), - * passing the given animation options through to `setView`, if required. - */ - setMaxBounds(bounds: LatLngBounds, options?: Map.ZoomPanOptions): Map; - - /** - * Tries to locate the user using Geolocation API, firing locationfound event - * with location data on success or locationerror event on failure, and optionally - * sets the map view to the user location with respect to detection accuracy - * (or to the world view if geolocation failed). See Locate options for more - * details. - */ - locate(options?: LocateOptions): Map; - - /** - * Stops watching location previously initiated by map.locate({watch: true}) - * and aborts resetting the map view if map.locate was called with {setView: true}. - */ - stopLocate(): Map; - - /** - * Destroys the map and clears all related event listeners. - */ - remove(): Map; - - // Methods for Getting Map State - - /** - * Returns the geographical center of the map view. - */ - getCenter(): LatLng; - - /** - * Returns the current zoom of the map view. - */ - getZoom(): number; - - /** - * Returns the minimum zoom level of the map. - */ - getMinZoom(): number; - - /** - * Returns the maximum zoom level of the map. - */ - getMaxZoom(): number; - - /** - * Returns the LatLngBounds of the current map view. - */ - getBounds(): LatLngBounds; - - /** - * Returns the maximum zoom level on which the given bounds fit to the map view - * in its entirety. If inside (optional) is set to true, the method instead returns - * the minimum zoom level on which the map view fits into the given bounds in its - * entirety. - */ - getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; - - /** - * Returns the current size of the map container. - */ + export interface Bounds { + extend(point: Point): this; + extend(point: PointTuple): this; + getCenter(round?: boolean): Point; + getBottomLeft(): Point; + getTopRight(): Point; getSize(): Point; + contains(otherBounds: Bounds): boolean; + contains(otherBounds: BoundsLiteral): boolean; + contains(point: Point): boolean; + contains(point: PointTuple): boolean; + intersects(otherBounds: Bounds): boolean; + intersects(otherBounds: BoundsLiteral): boolean; + overlaps(otherBounds: Bounds): boolean; + overlaps(otherBounds: BoundsLiteral): boolean; - /** - * Returns the bounds of the current map view in projected pixel coordinates - * (sometimes useful in layer and overlay implementations). - */ - getPixelBounds(): Bounds; - - /** - * Returns the projected pixel coordinates of the top left point of the map layer - * (useful in custom layer and overlay implementations). - */ - getPixelOrigin(): Point; - - // Methods for Layers and Controls - - /** - * Adds the given layer to the map. If optional insertAtTheBottom is set to true, - * the layer is inserted under all others (useful when switching base tile layers). - */ - addLayer(layer: ILayer, insertAtTheBottom?: boolean): Map; - - /** - * Removes the given layer from the map. - */ - removeLayer(layer: ILayer): Map; - - /** - * Returns true if the given layer is currently added to the map. - */ - hasLayer(layer: ILayer): boolean; - - /** - * Opens the specified popup while closing the previously opened (to make sure - * only one is opened at one time for usability). - */ - openPopup(popup: Popup): Map; - - /** - * Creates a popup with the specified options and opens it in the given point - * on a map. - */ - openPopup(html: string, latlng: LatLngExpression, options?: PopupOptions): Map; - - /** - * Creates a popup with the specified options and opens it in the given point - * on a map. - */ - openPopup(el: HTMLElement, latlng: LatLngExpression, options?: PopupOptions): Map; - - /** - * Closes the popup previously opened with openPopup (or the given one). - */ - closePopup(popup?: Popup): Map; - - /** - * Adds the given control to the map. - */ - addControl(control: IControl): Map; - - /** - * Removes the given control from the map. - */ - removeControl(control: IControl): Map; - - // Conversion Methods - - /** - * Returns the map layer point that corresponds to the given geographical coordinates - * (useful for placing overlays on the map). - */ - latLngToLayerPoint(latlng: LatLngExpression): Point; - - /** - * Returns the geographical coordinates of a given map layer point. - */ - layerPointToLatLng(point: Point): LatLng; - - /** - * Converts the point relative to the map container to a point relative to the - * map layer. - */ - containerPointToLayerPoint(point: Point): Point; - - /** - * Converts the point relative to the map layer to a point relative to the map - * container. - */ - layerPointToContainerPoint(point: Point): Point; - - /** - * Returns the map container point that corresponds to the given geographical - * coordinates. - */ - latLngToContainerPoint(latlng: LatLngExpression): Point; - - /** - * Returns the geographical coordinates of a given map container point. - */ - containerPointToLatLng(point: Point): LatLng; - - /** - * Projects the given geographical coordinates to absolute pixel coordinates - * for the given zoom level (current zoom level by default). - */ - project(latlng: LatLngExpression, zoom?: number): Point; - - /** - * Projects the given absolute pixel coordinates to geographical coordinates - * for the given zoom level (current zoom level by default). - */ - unproject(point: Point, zoom?: number): LatLng; - - /** - * Returns the pixel coordinates of a mouse click (relative to the top left corner - * of the map) given its event object. - */ - mouseEventToContainerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the pixel coordinates of a mouse click relative to the map layer given - * its event object. - */ - mouseEventToLayerPoint(event: LeafletMouseEvent): Point; - - /** - * Returns the geographical coordinates of the point the mouse clicked on given - * the click's event object. - */ - mouseEventToLatLng(event: LeafletMouseEvent): LatLng; - - // Other Methods - - /** - * Returns the container element of the map. - */ - getContainer(): HTMLElement; - - /** - * Returns an object with different map panes (to render overlays in). - */ - getPanes(): MapPanes; - - // REVIEW: Should we make it more flexible declaring parameter 'fn' as Function? - /** - * Runs the given callback when the map gets initialized with a place and zoom, - * or immediately if it happened already, optionally passing a function context. - */ - whenReady(fn: (map: Map) => void, context?: any): Map; - - // Properties - - /** - * Map dragging handler (by both mouse and touch). - */ - dragging: IHandler; - - /** - * Touch zoom handler. - */ - touchZoom: IHandler; - - /** - * Double click zoom handler. - */ - doubleClickZoom: IHandler; - - /** - * Scroll wheel zoom handler. - */ - scrollWheelZoom: IHandler; - - /** - * Box (shift-drag with mouse) zoom handler. - */ - boxZoom: IHandler; - - /** - * Keyboard navigation handler. - */ - keyboard: IHandler; - - /** - * Mobile touch hacks (quick tap and touch hold) handler. - */ - tap: IHandler; - - /** - * Zoom control. - */ - zoomControl: Control.Zoom; - - /** - * Attribution control. - */ - attributionControl: Control.Attribution; - - /** - * Map state options - */ - options: Map.MapOptions; - - /** - * Iterates over the layers of the map, optionally specifying context - * of the iterator function. - */ - eachLayer(fn: (layer: ILayer) => void, context?: any): Map; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Map; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Map; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Map; - fire(type: string, data?: any): Map;addEventListener(eventMap: any, context?: any): Map; - removeEventListener(eventMap?: any, context?: any): Map; - clearAllEventListeners(): Map; - on(eventMap: any, context?: any): Map; - off(eventMap?: any, context?: any): Map; + min: Point; + max: Point; } -} -declare namespace L.Map { + type BoundsExpression = Bounds | BoundsLiteral; + + export function bounds(topLeft: Point, bottomRight: Point): Bounds; + + export function bounds(topLeft: PointTuple, bottomRight: PointTuple): Bounds; + + export function bounds(points: Array): Bounds; + + export function bounds(points: BoundsLiteral): Bounds; + + export interface Evented { + + } + + interface LayerOptions { + pane?: string; + } + + interface InteractiveLayerOptions extends LayerOptions { + interactive?: boolean; + } + + export interface Layer extends Evented { + addTo(map: Map): this; + remove(): this; + removeFrom(map: Map): this; + getPane(name?: string): HTMLElement; + + // Popup methods + bindPopup(content: string, options?: PopupOptions): this; + bindPopup(content: HTMLElement, options?: PopupOptions): this; + bindPopup(content: (layer: Layer) => Content, options?: PopupOptions): this; + bindPopup(content: Popup): this; + unbindPopup(): this; + openPopup(): this; + openPopup(latlng: LatLng): this; + openPopup(latlng: LatLngLiteral): this; + openPopup(latlng: LatLngTuple): this; + closePopup(): this; + togglePopup(): this; + isPopupOpen(): boolean; + setPopupContent(content: string): this; + setPopupContent(content: HTMLElement): this; + setPopupContent(content: Popup): this; + getPopup(): Popup; + + // Tooltip methods + bindTooltip(content: string, options?: TooltipOptions): this; + bindTooltip(content: HTMLElement, options?: TooltipOptions): this; + bindTooltip(content: (layer: Layer) => Content, options?: TooltipOptions): this; + bindTooltip(content: Tooltip, options?: TooltipOptions): this; + unbindTooltip(): this; + openTooltip(): this; + openTooltip(latlng: LatLng): this; + openTooltip(latlng: LatLngLiteral): this; + openTooltip(latlng: LatLngTuple): this; + closeTooltip(): this; + toggleTooltip(): this; + isTooltipOpen(): boolean; + setTooltipContent(content: string): this; + setTooltipContent(content: HTMLElement): this; + setTooltipContent(content: Tooltip): this; + getTooltip(): Tooltip; + + // Extension methods + onAdd(map: Map): this; + onRemove(map: Map): this; + getEvents(): {[name: string]: (event: Event) => void}; + getAttribution(): string; + beforeAdd(map: Map): this; + } + + export interface GridLayerOptions { + tileSize?: number | Point; + opacity?: number; + updateWhenIdle?: boolean; + updateWhenZooming?: boolean; + updateInterval?: number; + attribution?: string; + zIndex?: number; + bounds?: LatLngBoundsExpression; + minZoom?: number; + maxZoom?: number; + noWrap?: boolean; + pane?: string; + className?: string; + keepBuffer?: number; + } + + export interface GridLayer extends Layer { + bringToFront(): this; + bringToBack(): this; + getAttribution(): string; + getContainer(): HTMLElement; + setOpacity(opacity: number): this; + setZIndex(zIndex: number): this; + isLoading(): boolean; + redraw(): this; + getTileSize(): Point; + } + + export function gridLayer(options?: GridLayerOptions): GridLayer; + + export interface TileLayerOptions extends GridLayerOptions { + minZoom?: number; + maxZoom?: number; + maxNativeZoom?: number; + subdomains?: string | Array; + errorTileUrl?: string; + zoomOffset?: number; + tms?: boolean; + zoomReverse?: boolean; + detectRetina?: boolean; + crossOrigin?: boolean; + } + + export interface TileLayer extends GridLayer { + setUrl(url: string, noRedraw?: boolean): this; + } + + export function tileLayer(urlTemplate: string, options?: TileLayerOptions): TileLayer; + + export interface WMSOptions extends TileLayerOptions { + layers: string; + styles?: string; + format?: string; + transparent?: boolean; + version?: string; + crs?: CRS; + uppercase?: boolean; + } + + export interface WMS extends TileLayer { + setParams(params: Object, noRedraw?: boolean): this; + } + + export namespace tileLayer { + export function wms(baseUrl: string, options: WMSOptions): WMS; + } + + export interface ImageOverlayOptions extends LayerOptions { + opacity?: number; + alt?: string; + interactive?: boolean; + attribution?: string; + crossOrigin?: boolean; + } + + export interface ImageOverlay extends Layer { + setOpacity(opacity: number): this; + bringToFront(): this; + bringToBack(): this; + setUrl(url: string): this; + } + + export function imageOverlay(imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions): ImageOverlay; + + export type LineCapShape = 'butt' | 'round' | 'square' | 'inherit'; + + export type LineJoinShape = 'miter' | 'round' | 'bevel' | 'inherit'; + + export type FillRule = 'nonzero' | 'evenodd' | 'inherit'; + + export interface PathOptions extends InteractiveLayerOptions { + stroke?: boolean; + color?: string; + wight?: number; + opacity?: number; + lineCap?: LineCapShape; + lineJoin?: LineJoinShape; + dashArray?: string; + dashOffset?: string; + fill?: boolean; + fillColor?: string; + fillOpacity?: number; + fillRule?: FillRule; + renderer?: Renderer; + className: string; + } + + export interface Path extends Layer { + redraw(): this; + setStyle(style: PathOptions): this; + bringToFront(): this; + bringToBack(): this; + } + + export interface PolylineOptions extends PathOptions { + smoothFactor?: number; + noClip?: boolean; + } + + export interface Polyline extends Path { + toGeoJSON(): Object; // should import GeoJSON typings + getLatLngs(): Array; + setLatLngs(latlngs: Array): this; + setLatLngs(latlngs: Array): this; + setLatLngs(latlngs: Array): this; + isEmpty(): boolean; + getCenter(): LatLng; + getBounds(): LatLngBounds; + addLatLng(latlng: LatLng): this; + addLatLng(latlng: LatLngLiteral): this; + addLatLng(latlng: LatLngTuple): this; + addLatLng(latlng: Array): this; // these three overloads aren't explicitly noted in the docs + addLatLng(latlng: Array): this; + addLatLng(latlng: Array): this; + } + + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + + export function polyline(latlngs: Array>, options?: PolylineOptions): Polyline; + + export interface Polygon extends Polyline { + toGeoJSON(): Object; // should import GeoJSON typings + } + + export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; + + export function polygon(latlngs: Array>, options?: PolylineOptions): Polygon; + + export interface Rectangle extends Polygon { + setBounds(latLngBounds: LatLngBounds): this; + setBounds(latLngBounds: LatLngBoundsLiteral): this; + } + + export function rectangle(latLngBounds: LatLngBounds, options?: PolylineOptions): Rectangle; + + export function rectangle(latLngBounds: LatLngBoundsLiteral, options?: PolylineOptions): Rectangle; + + export interface CircleMarkerOptions extends PathOptions { + radius?: number; + } + + export interface CircleMarker extends Path { + toGeoJSON(): Object; // should import GeoJSON typings + setLatLng(latLng: LatLng): this; + setLatLng(latLng: LatLngLiteral): this; + setLatLng(latLng: LatLngTuple): this; + getLatLng(): LatLng; + setRadius(radius: number): this; + getRadius(): number; + } + + export function circleMarker(latlng: LatLng, options?: CircleMarkerOptions): CircleMarker; + + export function circleMarker(latlng: LatLngLiteral, options?: CircleMarkerOptions): CircleMarker; + + export function circleMarker(latlng: LatLngLiteral, options?: CircleMarkerOptions): CircleMarker; + + export interface CircleOptions extends PathOptions { + radius?: number; + } + + export interface Circle extends CircleMarker { + setRadius(radius: number): this; + getRadius(): number; + getBounds(): LatLngBounds; + } + + export function circle(latlng: LatLng, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngLiteral, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngTuple, options?: CircleOptions): Circle; + + export function circle(latlng: LatLng, radius: number, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngLiteral, radius: number, options?: CircleOptions): Circle; + + export function circle(latlng: LatLngTuple, radius: number, options?: CircleOptions): Circle; + + export interface RendererOptions extends LayerOptions { + padding?: number; + } + + export interface Renderer extends Layer {} + + export interface SVG extends Renderer {} + + type Zoom = boolean | 'center'; export interface MapOptions { - - // Map State Options - - /** - * Initial geographical center of the map. - */ - center?: LatLng; - - /** - * Initial map zoom. - */ - zoom?: number; - - /** - * Layers that will be added to the map initially. - */ - layers?: ILayer[]; - - /** - * Minimum zoom level of the map. Overrides any minZoom set on map layers. - */ - minZoom?: number; - - /** - * Maximum zoom level of the map. This overrides any maxZoom set on map layers. - */ - maxZoom?: number; - - /** - * When this option is set, the map restricts the view to the given geographical - * bounds, bouncing the user back when he tries to pan outside the view, and also - * not allowing to zoom out to a view that's larger than the given bounds (depending - * on the map size). To set the restriction dynamically, use setMaxBounds method - */ - maxBounds?: LatLngBounds; - - /** - * Coordinate Reference System to use. Don't change this if you're not sure - * what it means. - * - * Default value: L.CRS.EPSG3857. - */ - crs?: ICRS; - - // Interaction Options - - /** - * Whether the map be draggable with mouse/touch or not. - * - * Default value: true. - */ - dragging?: boolean; - - /** - * Whether the map can be zoomed by touch-dragging with two fingers. - * - * Default value: true. - */ - touchZoom?: boolean; - - /** - * Whether the map can be zoomed by using the mouse wheel. - * If passed 'center', it will zoom to the center of the view regardless of - * where the mouse was. - * - * Default value: true. - */ - scrollWheelZoom?: boolean; - - /** - * Whether the map can be zoomed in by double clicking on it and zoomed out - * by double clicking while holding shift. - * If passed 'center', double-click zoom will zoom to the center of the view - * regardless of where the mouse was. - * - * Default value: true. - */ - doubleClickZoom?: boolean; - - /** - * Whether the map can be zoomed to a rectangular area specified by dragging - * the mouse while pressing shift. - * - * Default value: true. - */ - boxZoom?: boolean; - - /** - * Enables mobile hacks for supporting instant taps (fixing 200ms click delay - * on iOS/Android) and touch holds (fired as contextmenu events). - * - * Default value: true. - */ - tap?: boolean; - - /** - * The max number of pixels a user can shift his finger during touch for it - * to be considered a valid tap. - * - * Default value: 15. - */ - tapTolerance?: number; - - /** - * Whether the map automatically handles browser window resize to update itself. - * - * Default value: true. - */ - trackResize?: boolean; - - /** - * With this option enabled, the map tracks when you pan to another "copy" of - * the world and seamlessly jumps to the original one so that all overlays like - * markers and vector layers are still visible. - * - * Default value: false. - */ - worldCopyJump?: boolean; - - /** - * Set it to false if you don't want popups to close when user clicks the map. - * - * Default value: true. - */ - closePopupOnClick?: boolean; - - // Keyboard Navigation Options - - /** - * Makes the map focusable and allows users to navigate the map with keyboard - * arrows and +/- keys. - * - * Default value: true. - */ - keyboard?: boolean; - - /** - * Amount of pixels to pan when pressing an arrow key. - * - * Default value: 80. - */ - keyboardPanOffset?: number; - - /** - * Number of zoom levels to change when pressing + or - key. - * - * Default value: 1. - */ - keyboardZoomOffset?: number; - - // Panning Inertia Options - - /** - * If enabled, panning of the map will have an inertia effect where the map builds - * momentum while dragging and continues moving in the same direction for some - * time. Feels especially nice on touch devices. - * - * Default value: true. - */ - inertia?: boolean; - - /** - * The rate with which the inertial movement slows down, in pixels/second2. - * - * Default value: 3000. - */ - inertiaDeceleration?: number; - - /** - * Max speed of the inertial movement, in pixels/second. - * - * Default value: 1500. - */ - inertiaMaxSpeed?: number; - - /** - * Amount of milliseconds that should pass between stopping the movement and - * releasing the mouse or touch to prevent inertial movement. - * - * Default value: 32 for touch devices and 14 for the rest. - */ - inertiaThreshold?: number; + preferCanvas?: boolean; // Control options - - /** - * Whether the zoom control is added to the map by default. - * - * Default value: true. - */ + attributionControl?: boolean; zoomControl?: boolean; - /** - * Whether the attribution control is added to the map by default. - * - * Default value: true. - */ - attributionControl?: boolean; + // Interaction options + closePopupOnClick?: boolean; + zoomSnap?: number; + zoomDelta?: number; + trackResize?: boolean; + boxZoom?: boolean; + doubleClickZoom?: Zoom; + dragging?: boolean; + + // Map state options + crs?: CRS; + center?: LatLngExpression; + zoom?: number; + minZoom?: number; + maxZoom?: number; + layers?: Array; + maxBounds?: LatLngBoundsExpression; + renderer?: Renderer; // Animation options - - /** - * Whether the tile fade animation is enabled. By default it's enabled in all - * browsers that support CSS3 Transitions except Android. - */ fadeAnimation?: boolean; - - /** - * Whether the tile zoom animation is enabled. By default it's enabled in all - * browsers that support CSS3 Transitions except Android. - */ + markerZoomAnimation?: boolean; + transform3DLimit?: number; zoomAnimation?: boolean; - - /** - * Won't animate zoom if the zoom difference exceeds this value. - * - * Default value: 4. - */ zoomAnimationThreshold?: number; - /** - * Whether markers animate their zoom with the zoom animation, if disabled - * they will disappear for the length of the animation. By default it's enabled - * in all browsers that support CSS3 Transitions except Android. - */ - markerZoomAnimation?: boolean; + // Panning inertia options + inertia?: boolean; + inertiaDeceleration?: number; + inertiaMaxSpeed?: number; + easeLinearity?: number; + worldCopyJump?: boolean; + maxBoundsViscosity?: number; - /** - * Set it to false if you don't want the map to zoom beyond min/max zoom - * and then bounce back when pinch-zooming. - * - * Default value: true. - */ + // Keyboard navigation options + keyboard?: boolean; + keyboardPanDelta?: number; + + // Mousewheel options + scrollWheelZoom?: Zoom; + wheelDebounceTime?: number; + wheelPxPerZoomLevel?: number; + + // Touch interaction options + tap?: boolean; + tapTolerance?: number; + touchZoom?: Zoom; bounceAtZoomLimits?: boolean; } - export interface ZoomOptions { - /** - * If not specified, zoom animation will happen if the zoom origin is inside the current view. - * If true, the map will attempt animating zoom disregarding where zoom origin is. - * Setting false will make it always reset the view completely without animation. - */ - animate?: boolean; + export interface Control { + } - export interface ZoomPanOptions { - - /** - * If true, the map view will be completely reset (without any animations). - * - * Default value: false. - */ - reset?: boolean; - - /** - * Sets the options for the panning (without the zoom change) if it occurs. - */ - pan?: PanOptions; - - /** - * Sets the options for the zoom change if it occurs. - */ - zoom?: ZoomOptions; - - /** - * An equivalent of passing animate to both zoom and pan options (see below). - */ - animate?: boolean; - - /** - * If true, it will delay moveend event so that it doesn't happen many times in a row. - */ - debounceMoveend?: boolean; - - /** - * Duration of animated panning, in seconds. - */ - duration?: number; - - /** - * The curvature factor of panning animation easing (third parameter of the Cubic Bezier curve). - * 1.0 means linear animation, the less the more bowed the curve. - */ - easeLinearity?: number; - - /** - * If true, panning won't fire movestart event on start (used internally for panning inertia). - */ - noMoveStart?: boolean; + interface DivOverlayOptions { + offset?: PointExpression; + zoomAnimation?: boolean; + className?: string; + pane?: string; } - export interface FitBoundsOptions extends ZoomPanOptions { - - /** - * Sets the amount of padding in the top left corner of a map container that - * shouldn't be accounted for when setting the view to fit bounds. Useful if - * you have some control overlays on the map like a sidebar and you don't - * want them to obscure objects you're zooming to. - * - * Default value: [0, 0]. - */ - paddingTopLeft?: Point; - - /** - * The same for bottom right corner of the map. - * - * Default value: [0, 0]. - */ - paddingBottomRight?: Point; - - /** - * Equivalent of setting both top left and bottom right padding to the same value. - * - * Default value: [0, 0]. - */ - padding?: Point; - - /** - * The maximum possible zoom to use. - * - * Default value: null - */ - maxZoom?: number; + export interface PopupOptions extends DivOverlayOptions { + maxWidth?: number; + minWidth?: number; + maxHeight?: number; + autoPan?: boolean; + autoPanPaddingTopLeft?: PointExpression; + autoPanPaddingBottomRight?: PointExpression; + autoPanPadding?: PointExpression; + keepInView?: boolean; + closeButton?: boolean; + autoClose?: boolean; } -} -declare namespace L { + type Content = string | HTMLElement; - export interface MapPanes { - - /** - * Pane that contains all other map panes. - */ - mapPane: HTMLElement; - - /** - * Pane for tile layers. - */ - tilePane: HTMLElement; - - /** - * Pane that contains all the panes except tile pane. - */ - objectsPane: HTMLElement; - - /** - * Pane for overlay shadows (e.g. marker shadows). - */ - shadowPane: HTMLElement; - - /** - * Pane for overlays like polylines and polygons. - */ - overlayPane: HTMLElement; - - /** - * Pane for marker icons. - */ - markerPane: HTMLElement; - - /** - * Pane for popups. - */ - popupPane: HTMLElement; - } -} - -declare namespace L { - - /** - * Instantiates a Marker object given a geographical point and optionally - * an options object. - */ - function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; - - var Marker: { - /** - * Instantiates a Marker object given a geographical point and optionally - * an options object. - */ - new(latlng: LatLngExpression, options?: MarkerOptions): Marker; - }; - - export interface Marker extends ILayer, IEventPowered { - /** - * Adds the marker to the map. - */ - addTo(map: Map): Marker; - - /** - * Returns the current geographical position of the marker. - */ + export interface Popup extends Layer { getLatLng(): LatLng; - - /** - * Changes the marker position to the given point. - */ - setLatLng(latlng: LatLngExpression): Marker; - - /** - * Changes the marker icon. - */ - setIcon(icon: Icon): Marker; - - /** - * Changes the zIndex offset of the marker. - */ - setZIndexOffset(offset: number): Marker; - - /** - * Changes the opacity of the marker. - */ - setOpacity(opacity: number): Marker; - - /** - * Updates the marker position, useful if coordinates of its latLng object - * were changed directly. - */ - update(): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(html: string, options?: PopupOptions): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(el: HTMLElement, options?: PopupOptions): Marker; - - /** - * Binds a popup with a particular HTML content to a click on this marker. You - * can also open the bound popup with the Marker openPopup method. - */ - bindPopup(popup: Popup, options?: PopupOptions): Marker; - - /** - * Unbinds the popup previously bound to the marker with bindPopup. - */ - unbindPopup(): Marker; - - /** - * Opens the popup previously bound by the bindPopup method. - */ - openPopup(): Marker; - - /** - * Returns the popup previously bound by the bindPopup method. - */ - getPopup(): Popup; - - /** - * Closes the bound popup of the marker if it's opened. - */ - closePopup(): Marker; - - /** - * Toggles the popup previously bound by the bindPopup method. - */ - togglePopup(): Marker; - - /** - * Sets an HTML content of the popup of this marker. - */ - setPopupContent(html: string, options?: PopupOptions): Marker; - - /** - * Sets an HTML content of the popup of this marker. - */ - setPopupContent(el: HTMLElement, options?: PopupOptions): Marker; - - /** - * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). - */ - toGeoJSON(): GeoJSON.Feature; - - /** - * Marker dragging handler (by both mouse and touch). - */ - dragging: IHandler; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Marker; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Marker; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Marker; - fire(type: string, data?: any): Marker; - addEventListener(eventMap: any, context?: any): Marker; - removeEventListener(eventMap?: any, context?: any): Marker; - clearAllEventListeners(): Marker; - on(eventMap: any, context?: any): Marker; - off(eventMap?: any, context?: any): Marker; + setLatLng(latlng: LatLngExpression): this; + getContent(): Content; + setContent(htmlContent: string): this; + setContent(htmlContent: HTMLElement): this; + setContent(htmlContent: (source: Layer) => Content): this; + getElement(): Content; + update(): void; + isOpen(): boolean; + bringToFront(): this; + bringToBack(): this; + openOn(map: Map): this; } -} -declare namespace L { + export function popup(options?: PopupOptions, source?: Layer): Popup; - export interface MarkerOptions { + export type Direction = 'right' | 'left' | 'top' | 'bottom' | 'center' | 'auto'; - /** - * Icon class to use for rendering the marker. See Icon documentation for details - * on how to customize the marker icon. - * - * Default value: new L.Icon.Default(). - */ - icon?: Icon; - - /** - * If false, the marker will not emit mouse events and will act as a part of the - * underlying map. - * - * Default value: true. - */ - clickable?: boolean; - - /** - * Whether the marker is draggable with mouse/touch or not. - * - * Default value: false. - */ - draggable?: boolean; - - /** - * Whether the marker can be tabbed to with a keyboard and clicked by pressing enter. - * - * Default value: true. - */ - keyboard?: boolean; - - /** - * Text for the browser tooltip that appear on marker hover (no tooltip by default). - * - * Default value: ''. - */ - title?: string; - - /** - * Text for the alt attribute of the icon image (useful for accessibility). - * - * Default value: ''. - */ - alt?: string; - - /** - * By default, marker images zIndex is set automatically based on its latitude. - * You this option if you want to put the marker on top of all others (or below), - * specifying a high value like 1000 (or high negative value, respectively). - * - * Default value: 0. - */ - zIndexOffset?: number; - - /** - * The opacity of the marker. - * - * Default value: 1.0. - */ + export interface TooltipOptions extends DivOverlayOptions { + pane?: string; + offset?: PointExpression; + direction?: Direction; + permanent?: boolean; + sticky?: boolean; + interactive?: boolean; opacity?: number; - - /** - * If true, the marker will get on top of others when you hover the mouse over it. - * - * Default value: false. - */ - riseOnHover?: boolean; - - /** - * The z-index offset used for the riseOnHover feature. - * - * Default value: 250. - */ - riseOffset?: number; } -} -declare namespace L { + export interface Tooltip extends Layer {} - /** - * Instantiates a multi-polyline object given an array of latlngs arrays (one - * for each individual polygon) and optionally an options object (the same - * as for MultiPolyline). - */ - function multiPolygon(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + export function tooltip(options?: TooltipOptions, source?: Layer): Tooltip; - export interface MultiPolygonStatic extends ClassStatic { - /** - * Instantiates a multi-polyline object given an array of latlngs arrays (one - * for each individual polygon) and optionally an options object (the same - * as for MultiPolyline). - */ - new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolygon; + export interface ZoomOptions { + animate?: boolean; } - export var MultiPolygon: MultiPolygonStatic; - - export interface MultiPolygon extends FeatureGroup { - /** - * Replace all polygons and their paths with the given array of arrays - * of geographical points. - */ - setLatLngs(latlngs: LatLng[][]): MultiPolygon; - - /** - * Returns an array of arrays of geographical points in each polygon. - */ - getLatLngs(): LatLng[][]; - - /** - * Opens the popup previously bound by bindPopup. - */ - openPopup(): MultiPolygon; - - /** - * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). - */ - toGeoJSON(): GeoJSON.Feature; - } -} - -declare namespace L { - - /** - * Instantiates a multi-polyline object given an array of arrays of geographical - * points (one for each individual polyline) and optionally an options object. - */ - function multiPolyline(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; - - export interface MultiPolylineStatic extends ClassStatic { - /** - * Instantiates a multi-polyline object given an array of arrays of geographical - * points (one for each individual polyline) and optionally an options object. - */ - new(latlngs: LatLng[][], options?: PolylineOptions): MultiPolyline; - } - export var MultiPolyline: MultiPolylineStatic; - - export interface MultiPolyline extends FeatureGroup { - /** - * Replace all polygons and their paths with the given array of arrays - * of geographical points. - */ - setLatLngs(latlngs: LatLng[][]): MultiPolyline; - - /** - * Returns an array of arrays of geographical points in each polygon. - */ - getLatLngs(): LatLng[][]; - - /** - * Opens the popup previously bound by bindPopup. - */ - openPopup(): MultiPolyline; - - /** - * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). - */ - toGeoJSON(): GeoJSON.Feature; - } -} - -declare namespace L { export interface PanOptions { - - /** - * If true, panning will always be animated if possible. If false, it will not - * animate panning, either resetting the map view if panning more than a screen - * away, or just setting a new offset for the map pane (except for `panBy` - * which always does the latter). - */ animate?: boolean; - - /** - * Duration of animated panning. - * - * Default value: 0.25. - */ duration?: number; - - /** - * The curvature factor of panning animation easing (third parameter of the Cubic - * Bezier curve). 1.0 means linear animation, the less the more bowed the curve. - * - * Default value: 0.25. - */ easeLinearity?: number; - - /** - * If true, panning won't fire movestart event on start (used internally for panning inertia). - * - * Default value: false. - */ noMoveStart?: boolean; } -} -declare namespace L { + export interface ZoomPanOptions extends ZoomOptions, PanOptions {} - export interface Path extends ILayer, IEventPowered { - - /** - * Adds the layer to the map. - */ - addTo(map: Map): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(html: string, options?: PopupOptions): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(el: HTMLElement, options?: PopupOptions): Path; - - /** - * Binds a popup with a particular HTML content to a click on this path. - */ - bindPopup(popup: Popup, options?: PopupOptions): Path; - - /** - * Unbinds the popup previously bound to the path with bindPopup. - */ - unbindPopup(): Path; - - /** - * Opens the popup previously bound by the bindPopup method in the given point, - * or in one of the path's points if not specified. - */ - openPopup(latlng?: LatLngExpression): Path; - - /** - * Closes the path's bound popup if it is opened. - */ - closePopup(): Path; - - /** - * Changes the appearance of a Path based on the options in the Path options object. - */ - setStyle(object: PathOptions): Path; - - /** - * Returns the LatLngBounds of the path. - */ - getBounds(): LatLngBounds; - - /** - * Brings the layer to the top of all path layers. - */ - bringToFront(): Path; - - /** - * Brings the layer to the bottom of all path layers. - */ - bringToBack(): Path; - - /** - * Redraws the layer. Sometimes useful after you changed the coordinates that - * the path uses. - */ - redraw(): Path; - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): Path; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): Path; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): Path; - fire(type: string, data?: any): Path; - addEventListener(eventMap: any, context?: any): Path; - removeEventListener(eventMap?: any, context?: any): Path; - clearAllEventListeners(): Path; - on(eventMap: any, context?: any): Path; - off(eventMap?: any, context?: any): Path; - } - - export namespace Path { - /** - * True if SVG is used for vector rendering (true for most modern browsers). - */ - export var SVG: boolean; - - /** - * True if VML is used for vector rendering (IE 6-8). - */ - export var VML: boolean; - - /** - * True if Canvas is used for vector rendering (Android 2). You can also force - * this by setting global variable L_PREFER_CANVAS to true before the Leaflet - * include on your page — sometimes it can increase performance dramatically - * when rendering thousands of circle markers, but currently suffers from - * a bug that causes removing such layers to be extremely slow. - */ - export var CANVAS: boolean; - - /** - * How much to extend the clip area around the map view (relative to its size, - * e.g. 0.5 is half the screen in each direction). Smaller values mean that you - * will see clipped ends of paths while you're dragging the map, and bigger values - * decrease drawing performance. - */ - export var CLIP_PADDING: number; - } -} - -declare namespace L { - - export interface PathOptions { - - /** - * Whether to draw stroke along the path. Set it to false to disable borders on - * polygons or circles. - * - * Default value: true. - */ - stroke?: boolean; - - /** - * Stroke color. - * - * Default value: '#03f'. - */ - color?: string; - - /** - * Stroke width in pixels. - * - * Default value: 5. - */ - weight?: number; - - /** - * Stroke opacity. - * - * Default value: 0.5. - */ - opacity?: number; - - /** - * Whether to fill the path with color. Set it to false to disable filling on polygons - * or circles. - */ - fill?: boolean; - - /** - * Fill color. - * - * Default value: same as color. - */ - fillColor?: string; - - /** - * Fill opacity. - * - * Default value: 0.2. - */ - fillOpacity?: number; - - /** - * A string that defines the stroke dash pattern. Doesn't work on canvas-powered - * layers (e.g. Android 2). - */ - dashArray?: string; - - /** - * A string that defines shape to be used at the end of the stroke. - * - * Default: null. - */ - lineCap?: string; - - /** - * A string that defines shape to be used at the corners of the stroke. - * - * Default: null. - */ - lineJoin?: string; - - /** - * If false, the vector will not emit mouse events and will act as a part of the - * underlying map. - * - * Default value: true. - */ - clickable?: boolean; - - /** - * Sets the pointer-events attribute on the path if SVG backend is used. - */ - pointerEvents?: string; - - /** - * Custom class name set on an element. - * - * Default value: ''. - */ - className?: string; - - /** - * Sets the radius of a circle marker. - */ - radius?: number; - - } -} - -declare namespace L { - - /** - * Creates a Point object with the given x and y coordinates. If optional round - * is set to true, rounds the x and y values. - */ - function point(x: number, y: number, round?: boolean): Point; - - export interface PointStatic { - /** - * Creates a Point object with the given x and y coordinates. If optional round - * is set to true, rounds the x and y values. - */ - new(x: number, y: number, round?: boolean): Point; - } - export var Point: PointStatic; - - export interface Point { - /** - * Returns the result of addition of the current and the given points. - */ - add(otherPoint: Point): Point; - - /** - * Returns the result of subtraction of the given point from the current. - */ - subtract(otherPoint: Point): Point; - - /** - * Returns the result of multiplication of the current point by the given number. - */ - multiplyBy(number: number): Point; - - /** - * Returns the result of division of the current point by the given number. If - * optional round is set to true, returns a rounded result. - */ - divideBy(number: number, round?: boolean): Point; - - /** - * Returns the distance between the current and the given points. - */ - distanceTo(otherPoint: Point): number; - - /** - * Returns a copy of the current point. - */ - clone(): Point; - - /** - * Returns a copy of the current point with rounded coordinates. - */ - round(): Point; - - /** - * Returns true if the given point has the same coordinates. - */ - equals(otherPoint: Point): boolean; - - /** - * Returns a string representation of the point for debugging purposes. - */ - toString(): string; - - /** - * The x coordinate. - */ - x: number; - - /** - * The y coordinate. - */ - y: number; - } -} - -declare namespace L { - - /** - * Instantiates a polygon object given an array of geographical points and - * optionally an options object (the same as for Polyline). You can also create - * a polygon with holes by passing an array of arrays of latlngs, with the first - * latlngs array representing the exterior ring while the remaining represent - * the holes inside. - */ - function polygon(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; - - - export interface PolygonStatic extends ClassStatic { - /** - * Instantiates a polygon object given an array of geographical points and - * optionally an options object (the same as for Polyline). You can also create - * a polygon with holes by passing an array of arrays of latlngs, with the first - * latlngs array representing the exterior ring while the remaining represent - * the holes inside. - */ - new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polygon; - } - export var Polygon: PolygonStatic; - - export interface Polygon extends Polyline { - } -} - -declare namespace L { - - /** - * Instantiates a polyline object given an array of geographical points and - * optionally an options object. - */ - function polyline(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; - - export interface PolylineStatic extends ClassStatic { - /** - * Instantiates a polyline object given an array of geographical points and - * optionally an options object. - */ - new(latlngs: LatLngBoundsExpression, options?: PolylineOptions): Polyline; - } - export var Polyline: PolylineStatic; - - export interface Polyline extends Path { - /** - * Adds a given point to the polyline. - */ - addLatLng(latlng: LatLngExpression): Polyline; - - /** - * Replaces all the points in the polyline with the given array of geographical - * points. - */ - setLatLngs(latlngs: LatLngBoundsExpression): Polyline; - - /** - * Returns an array of the points in the path. - */ - getLatLngs(): LatLng[]; - - /** - * Allows adding, removing or replacing points in the polyline. Syntax is the - * same as in Array#splice. Returns the array of removed points (if any). - */ - spliceLatLngs(index: number, pointsToRemove: number, ...latlngs: LatLng[]): LatLng[]; - - /** - * Returns the LatLngBounds of the polyline. - */ - getBounds(): LatLngBounds; - - /** - * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). - */ - toGeoJSON(): GeoJSON.Feature; - } -} - -declare namespace L { - - export interface PolylineOptions extends PathOptions { - - /** - * How much to simplify the polyline on each zoom level. More means better performance - * and smoother look, and less means more accurate representation. - * - * Default value: 1.0. - */ - smoothFactor?: number; - - /** - * Disabled polyline clipping. - * - * Default value: false. - */ - noClip?: boolean; - } -} - -declare namespace L { - - namespace PolyUtil { - - /** - * Clips the polygon geometry defined by the given points by rectangular bounds. - * Used by Leaflet to only show polygon points that are on the screen or near, - * increasing performance. Note that polygon points needs different algorithm - * for clipping than polyline, so there's a seperate method for it. - */ - export function clipPolygon(points: Point[], bounds: Bounds): Point[]; - } -} - -declare namespace L { - - /** - * Instantiates a Popup object given an optional options object that describes - * its appearance and location and an optional object that is used to tag the - * popup with a reference to the source object to which it refers. - */ - function popup(options?: PopupOptions, source?: any): Popup; - - export interface PopupStatic extends ClassStatic { - /** - * Instantiates a Popup object given an optional options object that describes - * its appearance and location and an optional object that is used to tag the - * popup with a reference to the source object to which it refers. - */ - new(options?: PopupOptions, source?: any): Popup; - } - export var Popup: PopupStatic; - - export interface Popup extends ILayer { - /** - * Adds the popup to the map. - */ - addTo(map: Map): Popup; - - /** - * Adds the popup to the map and closes the previous one. The same as map.openPopup(popup). - */ - openOn(map: Map): Popup; - - /** - * Sets the geographical point where the popup will open. - */ - setLatLng(latlng: LatLngExpression): Popup; - - /** - * Returns the geographical point of popup. - */ - getLatLng(): LatLng; - - /** - * Sets the HTML content of the popup. - */ - setContent(html: string): Popup; - - /** - * Sets the HTML content of the popup. - */ - setContent(el: HTMLElement): Popup; - - /** - * Returns the content of the popup. - */ - getContent(): HTMLElement; - //getContent(): string; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - /** - * Updates the popup content, layout and position. Useful for updating the popup after - * something inside changed, e.g. image loaded. - */ - update(): Popup; - } -} - -declare namespace L { - - export interface PopupOptions { - - /** - * Max width of the popup. - * - * Default value: 300. - */ - maxWidth?: number; - - /** - * Min width of the popup. - * - * Default value: 50. - */ - minWidth?: number; - - /** - * If set, creates a scrollable container of the given height inside a popup - * if its content exceeds it. - */ - maxHeight?: number; - - /** - * Set it to false if you don't want the map to do panning animation to fit the opened - * popup. - * - * Default value: true. - */ - autoPan?: boolean; - - /** - * Set it to true if you want to prevent users from panning the popup off of the screen while it is open. - */ - keepInView?: boolean; - - /** - * Controls the presense of a close button in the popup. - * - * Default value: true. - */ - closeButton?: boolean; - - /** - * The offset of the popup position. Useful to control the anchor of the popup - * when opening it on some overlays. - * - * Default value: new Point(0, 6). - */ - offset?: Point; - - /** - * The margin between the popup and the top left corner of the map view after - * autopanning was performed. - * - * Default value: null. - */ - autoPanPaddingTopLeft?: Point; - - /** - * The margin between the popup and the bottom right corner of the map view after - * autopanning was performed. - * - * Default value: null. - */ - autoPanPaddingBottomRight?: Point; - - /** - * The margin between the popup and the edges of the map view after autopanning - * was performed. - * - * Default value: new Point(5, 5). - */ - autoPanPadding?: Point; - - /** - * Whether to animate the popup on zoom. Disable it if you have problems with - * Flash content inside popups. - * - * Default value: true. - */ - zoomAnimation?: boolean; - - /** - * Set it to false if you want to override the default behavior of the popup - * closing when user clicks the map (set globally by the Map closePopupOnClick - * option). - */ - closeOnClick?: boolean; - - /** - * A custom class name to assign to the popup. - */ - className?: string; - } -} - -declare namespace L { - - export interface PosAnimationStatic extends ClassStatic { - /** - * Creates a PosAnimation object. - */ - new(): PosAnimation; - } - export var PosAnimation: PosAnimationStatic; - - export interface PosAnimation extends IEventPowered { - /** - * Run an animation of a given element to a new position, optionally setting - * duration in seconds (0.25 by default) and easing linearity factor (3rd argument - * of the cubic bezier curve, 0.5 by default) - */ - run(element: HTMLElement, newPos: Point, duration?: number, easeLinearity?: number): PosAnimation; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): PosAnimation; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): PosAnimation; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): PosAnimation; - fire(type: string, data?: any): PosAnimation; - addEventListener(eventMap: any, context?: any): PosAnimation; - removeEventListener(eventMap?: any, context?: any): PosAnimation; - clearAllEventListeners(): PosAnimation; - on(eventMap: any, context?: any): PosAnimation; - off(eventMap?: any, context?: any): PosAnimation; - } -} - -declare namespace L { - - namespace Projection { - - /** - * Spherical Mercator projection — the most common projection for online maps, - * used by almost all free and commercial tile providers. Assumes that Earth - * is a sphere. Used by the EPSG:3857 CRS. - */ - export var SphericalMercator: IProjection; - - /** - * Elliptical Mercator projection — more complex than Spherical Mercator. - * Takes into account that Earth is a geoid, not a perfect sphere. Used by the - * EPSG:3395 CRS. - */ - export var Mercator: IProjection; - - /** - * Equirectangular, or Plate Carree projection — the most simple projection, - * mostly used by GIS enthusiasts. Directly maps x as longitude, and y as latitude. - * Also suitable for flat worlds, e.g. game maps. Used by the EPSG:3395 and Simple - * CRS. - */ - export var LonLat: IProjection; - } -} - -declare namespace L { - - /** - * Instantiates a rectangle object with the given geographical bounds and - * optionally an options object. - */ - function rectangle(bounds: LatLngBounds, options?: PathOptions): Rectangle; - - export interface RectangleStatic extends ClassStatic { - /** - * Instantiates a rectangle object with the given geographical bounds and - * optionally an options object. - */ - new(bounds: LatLngBounds, options?: PathOptions): Rectangle; - } - export var Rectangle: RectangleStatic; - - export interface Rectangle extends Polygon { - /** - * Redraws the rectangle with the passed bounds. - */ - setBounds(bounds: LatLngBounds): Rectangle; - } -} - - -declare namespace L { - - export interface ScaleOptions { - - /** - * The position of the control (one of the map corners). See control positions. - * Default value: 'bottomleft'. - */ - position?: PositionString; - - /** - * Maximum width of the control in pixels. The width is set dynamically to show - * round values (e.g. 100, 200, 500). - * Default value: 100. - */ - maxWidth?: number; - - /** - * Whether to show the metric scale line (m/km). - * Default value: true. - */ - metric?: boolean; - - /** - * Whether to show the imperial scale line (mi/ft). - * Default value: true. - */ - imperial?: boolean; - - /** - * If true, the control is updated on moveend, otherwise it's always up-to-date - * (updated on move). - * Default value: false. - */ - updateWhenIdle?: boolean; - } -} - -declare namespace L { - - export interface TileLayerStatic extends ClassStatic { - /** - * Instantiates a tile layer object given a URL template and optionally an options - * object. - */ - new(urlTemplate: string, options?: TileLayerOptions): TileLayer; - - WMS: { - /** - * Instantiates a WMS tile layer object given a base URL of the WMS service and - * a WMS parameters/options object. - */ - new(baseUrl: string, options: WMSOptions): TileLayer.WMS; - }; - - Canvas: { - /** - * Instantiates a Canvas tile layer object given an options object (optionally). - */ - new(options?: TileLayerOptions): TileLayer.Canvas; - }; - } - export var TileLayer: TileLayerStatic; - - export interface TileLayer extends ILayer, IEventPowered { - /** - * Adds the layer to the map. - */ - addTo(map: Map): TileLayer; - - /** - * Brings the tile layer to the top of all tile layers. - */ - bringToFront(): TileLayer; - - /** - * Brings the tile layer to the bottom of all tile layers. - */ - bringToBack(): TileLayer; - - /** - * Changes the opacity of the tile layer. - */ - setOpacity(opacity: number): TileLayer; - - /** - * Sets the zIndex of the tile layer. - */ - setZIndex(zIndex: number): TileLayer; - - /** - * Causes the layer to clear all the tiles and request them again. - */ - redraw(): TileLayer; - - /** - * Updates the layer's URL template and redraws it. - */ - setUrl(urlTemplate: string): TileLayer; - - /** - * Returns the HTML element that contains the tiles for this layer. - */ - getContainer(): HTMLElement; - - //////////// - //////////// - /** - * Should contain code that creates DOM elements for the overlay, adds them - * to map panes where they should belong and puts listeners on relevant map events. - * Called on map.addLayer(layer). - */ - onAdd(map: Map): void; - - /** - * Should contain all clean up code that removes the overlay's elements from - * the DOM and removes listeners previously added in onAdd. Called on map.removeLayer(layer). - */ - onRemove(map: Map): void; - - //////////////// - //////////////// - addEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - addOneTimeEventListener(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - removeEventListener(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; - hasEventListeners(type: string): boolean; - fireEvent(type: string, data?: any): TileLayer; - on(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - once(type: string, fn: (e: LeafletEvent) => void, context?: any): TileLayer; - off(type: string, fn?: (e: LeafletEvent) => void, context?: any): TileLayer; - fire(type: string, data?: any): TileLayer; - addEventListener(eventMap: any, context?: any): TileLayer; - removeEventListener(eventMap?: any, context?: any): TileLayer; - clearAllEventListeners(): TileLayer; - on(eventMap: any, context?: any): TileLayer; - off(eventMap?: any, context?: any): TileLayer; - } - - namespace TileLayer { - export interface WMS extends TileLayer { - /** - * Merges an object with the new parameters and re-requests tiles on the current - * screen (unless noRedraw was set to true). - */ - setParams(params: WMS, noRedraw?: boolean): WMS; - } - - export interface Canvas extends TileLayer { - /** - * You need to define this method after creating the instance to draw tiles; - * canvas is the actual canvas tile on which you can draw, tilePoint represents - * the tile numbers, and zoom is the current zoom. - */ - drawTile(canvas: HTMLCanvasElement, tilePoint: Point, zoom: number): Canvas; - - /** - * Calling redraw will cause the drawTile method to be called for all tiles. - * May be used for updating dynamic content drawn on the Canvas - */ - redraw(): Canvas; - } - } - - export interface TileLayerFactory { - - /** - * Instantiates a tile layer object given a URL template and optionally an options - * object. - */ - (urlTemplate: string, options?: TileLayerOptions): TileLayer; - - /** - * Instantiates a WMS tile layer object given a base URL of the WMS service and - * a WMS parameters/options object. - */ - wms(baseUrl: string, options: WMSOptions): L.TileLayer.WMS; - - /** - * Instantiates a Canvas tile layer object given an options object (optionally). - */ - canvas(options?: TileLayerOptions): L.TileLayer.Canvas; - } - - export var tileLayer: TileLayerFactory; -} - -declare namespace L { - - export interface TileLayerOptions { - - /** - * Minimum zoom number. - * - * Default value: 0. - */ - minZoom?: number; - - /** - * Maximum zoom number. - * - * Default value: 18. - */ + export interface FitBoundsOptions extends ZoomOptions, PanOptions { + paddingTopLeft?: PointExpression; + paddingBottomRight?: PointExpression; + padding?: PointExpression; maxZoom?: number; + } - /** - * Maximum zoom number the tiles source has available. If it is specified, - * the tiles on all zoom levels higher than maxNativeZoom will be loaded from - * maxZoom level and auto-scaled. - * - * Default value: null. - */ - maxNativeZoom?: number; + export interface LocateOptions { + watch?: boolean; + setView?: boolean; + maxZoom?: number; + timeout?: number; + maximumAge?: number; + enableHighAccuracy?: boolean; + } - /** - * Tile size (width and height in pixels, assuming tiles are square). - * - * Default value: 256. - */ - tileSize?: number; + export interface Handler { + enable(): this; + disable(): this; + enabled(): boolean; - /** - * Subdomains of the tile service. Can be passed in the form of one string (where - * each letter is a subdomain name) or an array of strings. - * - * Default value: 'abc'. - */ - subdomains?: string|string[]; + // Extension methods + addHooks(): void; + removeHooks(): void; + } - /** - * URL to the tile image to show in place of the tile that failed to load. - * - * Default value: ''. - */ - errorTileUrl?: string; + export interface Event { + type: string; + target: any; // should this be Object and have users cast? + } - /** - * e.g. "© CloudMade" — the string used by the attribution control, describes - * the layer data. - * - * Default value: ''. - */ - attribution?: string; + export interface MouseEvent extends Event { + latlng: LatLng; + layerPoint: Point; + containerPoint: Point; + originalEvent: MouseEvent; // how can I reference the global MouseEvent? + } - /** - * If true, inverses Y axis numbering for tiles (turn this on for TMS services). - * - * Default value: false. - */ - tms?: boolean; + export interface LocationEvent extends Event { + latlng: LatLng; + bounds: LatLngBounds; + accuracy: number; + altitude: number; + altitudeAccuracy: number; + heading: number; + speed: number; + timestamp: number; + } - /** - * If set to true, the tile coordinates won't be wrapped by world width (-180 - * to 180 longitude) or clamped to lie within world height (-90 to 90). Use this - * if you use Leaflet for maps that don't reflect the real world (e.g. game, indoor - * or photo maps). - * - * Default value: false. - */ - continuousWorld?: boolean; + export interface ErrorEvent extends Event { + message: string; + code: number; + } - /** - * If set to true, the tiles just won't load outside the world width (-180 to 180 - * longitude) instead of repeating. - * - * Default value: false. - */ - noWrap?: boolean; + export interface LayerEvent extends Event { + layer: Layer; + } - /** - * The zoom number used in tile URLs will be offset with this value. - * - * Default value: 0. - */ - zoomOffset?: number; + export interface LayersControlEvent extends LayerEvent { + name: string; + } - /** - * If set to true, the zoom number used in tile URLs will be reversed (maxZoom - * - zoom instead of zoom) - * - * Default value: false. - */ - zoomReverse?: boolean; + export interface TileEvent extends Event { + tile: HTMLImageElement; + coords: Point; // apparently not a normal point, since docs say it has z (zoom) + } - /** - * The opacity of the tile layer. - * - * Default value: 1.0. - */ + export interface TileErrorEvent extends TileEvent { + error: Error; + } + + export interface ResizeEvent extends Event { + oldSize: Point; + newSize: Point; + } + + export interface GeoJSONEvent extends Event { + layer: Layer; + properties: any; // any or Object? + geometryType: string; + id: string; + } + + export interface PopupEvent extends Event { + popup: Popup; + } + + export interface TooltipEvent extends Event { + tooltip: Tooltip; + } + + export interface DragEndEvent extends Event { + distance: number; + } + + interface DefaultMapPanes { + mapPane: HTMLElement; + tilePane: HTMLElement; + overlayPane: HTMLElement; + shadowPane: HTMLElement; + markerPane: HTMLElement; + tooltipPane: HTMLElement; + popupPane: HTMLElement; + } + + export interface Map extends Evented { + getRenderer(layer: Path): Renderer; + + // Methods for layers and controls + addControl(control: Control): this; + removeControl(control: Control): this; + addLayer(layer: Layer): this; + removeLayer(layer: Layer): this; + hasLayer(layer: Layer): boolean; + eachLayer(fn: (layer: Layer) => void, context?: Object): this; + openPopup(popup: Popup): this; + openPopup(content: string, latlng: LatLng, options?: PopupOptions): this; + openPopup(content: string, latlng: LatLngLiteral, options?: PopupOptions): this; + openPopup(content: string, latlng: LatLngTuple, options?: PopupOptions): this; + openPopup(content: HTMLElement, latlng: LatLng, options?: PopupOptions): this; + openPopup(content: HTMLElement, latlng: LatLngLiteral, options?: PopupOptions): this; + openPopup(content: HTMLElement, latlng: LatLngTuple, options?: PopupOptions): this; + closePopup(popup?: Popup): this; + openTooltip(tooltip: Tooltip): this; + openTooltip(content: string, latlng: LatLng, options?: TooltipOptions): this; + openTooltip(content: string, latlng: LatLngLiteral, options?: TooltipOptions): this; + openTooltip(content: string, latlng: LatLngTuple, options?: TooltipOptions): this; + openTooltip(content: HTMLElement, latlng: LatLng, options?: TooltipOptions): this; + openTooltip(content: HTMLElement, latlng: LatLngLiteral, options?: TooltipOptions): this; + openTooltip(content: HTMLElement, latlng: LatLngTuple, options?: TooltipOptions): this; + closeTooltip(tooltip?: Tooltip): this; + + // Methods for modifying map state + setView(center: LatLng, zoom: number, options?: ZoomPanOptions): this; + setView(center: LatLngLiteral, zoom: number, options?: ZoomPanOptions): this; + setView(center: LatLngTuple, zoom: number, options?: ZoomPanOptions): this; + setZoom(zoom: number, options: ZoomPanOptions): this; + zoomIn(delta?: number, options?: ZoomOptions): this; + zoomOut(delta?: number, options?: ZoomOptions): this; + setZoomAround(latlng: LatLng, zoom: number, options: ZoomOptions): this; + setZoomAround(latlng: LatLngLiteral, zoom: number, options: ZoomOptions): this; + setZoomAround(latlng: LatLngTuple, zoom: number, options: ZoomOptions): this; // will the latlng version using tuple take precedence or will the point tuple version? + setZoomAround(offset: Point, zoom: number, options: ZoomOptions): this; + fitBounds(bounds: LatLngBounds, options: FitBoundsOptions): this; + fitBounds(bounds: LatLngBoundsLiteral, options: FitBoundsOptions): this; + fitWorld(options?: FitBoundsOptions): this; + panTo(latlng: LatLng, options?: PanOptions): this; + panTo(latlng: LatLngLiteral, options?: PanOptions): this; + panTo(latlng: LatLngTuple, options?: PanOptions): this; + panBy(offset: Point): this; + panBy(offset: PointTuple): this; + setMaxBounds(bounds: Bounds): this; // is this really bounds and not lanlngbounds? + setMaxBounds(bounds: BoundsLiteral): this; + setMinZoom(zoom: number): this; + setMaxZoom(zoom: number): this; + panInsideBounds(bounds: LatLngBounds, options?: PanOptions): this; + panInsideBounds(bounds: LatLngBoundsLiteral, options?: PanOptions): this; + invalidateSize(options: ZoomPanOptions): this; + invalidateSize(animate: boolean): this; + stop(): this; + flyTo(latlng: LatLng, zoom?: number, options?: ZoomPanOptions): this; + flyTo(latlng: LatLngLiteral, zoom?: number, options?: ZoomPanOptions): this; + flyTo(latlng: LatLngTuple, zoom?: number, options?: ZoomPanOptions): this; + flyToBounds(bounds: LatLngBounds, options?: FitBoundsOptions): this; + flyToBounds(bounds: LatLngBoundsLiteral, options?: FitBoundsOptions): this; + + // Other methods + addHandler(name: string, HandlerClass: () => Handler): this; // HandlerClass is actually a constructor function, is this the right way? + remove(): this; + createPane(name: string, container?: HTMLElement): HTMLElement; + getPane(pane: string): HTMLElement; + getPane(pane: HTMLElement): HTMLElement; + getPanes(): {[name: string]: HTMLElement} & DefaultMapPanes; + getContainer(): HTMLElement; + whenReady(fn: () => void, context?: Object): this; + + // Methods for getting map state + getCenter(): LatLng; + getZoom(): number; + getBounds(): LatLngBounds; + getMinZoom(): number; + getMaxZoom(): number; + getBoundsZoom(bounds: LatLngBounds, inside?: boolean): number; + getBoundsZoom(bounds: LatLngBoundsLiteral, inside?: boolean): number; + getSize(): Point; + getPixelBounds(): Bounds; + getPixelOrigin(): Point; + getPixelWorldBounds(zoom?: number): Bounds; + + // Conversion methods + getZoomScale(toZoom: number, fromZoom: number): number; + getScaleZoom(scale: number, fromZoom: number): number; + project(latlng: LatLng, zoom: number): Point; + project(latlng: LatLngLiteral, zoom: number): Point; + project(latlng: LatLngTuple, zoom: number): Point; + unproject(point: Point, zoom: number): LatLng; + unproject(point: PointTuple, zoom: number): LatLng; + layerPointToLatLng(point: Point): LatLng; + layerPointToLatLng(point: PointTuple): LatLng; + latLngToLayerPoint(latlng: LatLng): Point; + latLngToLayerPoint(latlng: LatLngLiteral): Point; + latLngToLayerPoint(latlng: LatLngTuple): Point; + wrapLatLng(latlng: LatLng): LatLng; + wrapLatLng(latlng: LatLngLiteral): LatLng; + wrapLatLng(latlng: LatLngTuple): LatLng; + distance(latlng1: LatLng, latlng2: LatLng): number; + distance(latlng1: LatLngLiteral, latlng2: LatLngLiteral): number; + distance(latlng1: LatLngTuple, latlng2: LatLngTuple): number; + containerPointToLayerPoint(point: Point): Point; + containerPointToLayerPoint(point: PointTuple): Point; + layerPointToContainerPoint(point: Point): Point; + layerPointToContainerPoint(point: PointTuple): Point; + latLngToContainerPoint(latlng: LatLng): Point; + latLngToContainerPoint(latlng: LatLngLiteral): Point; + latLngToContainerPoint(latlng: LatLngTuple): Point; + mouseEventToContainerPoint(ev: MouseEvent): Point; + mouseEventToLayerPoint(ev: MouseEvent): Point; + mouseEventToLatLng(ev: MouseEvent): LatLng; + + // Geolocation methods + locate(options?: LocateOptions): this; + stopLocate(): this; + + // Properties + boxZoom: Handler; + doubleClickZoom: Handler; + dragging: Handler; + keyboard: Handler; + scrollWheelZoom: Handler; + tap: Handler; + touchZoom: Handler; + } + + export function map(id: string, options?: MapOptions): Map; + + export function map(el: HTMLElement, options?: MapOptions): Map; + + export interface IconOptions extends LayerOptions { + iconUrl: string; + iconRetinaUrl?: string; + iconSize?: PointExpression; + iconAnchor?: PointExpression; + popupAnchor?: PointExpression; + shadowUrl?: string; + shadowRetinaUrl?: string; + shadowSize?: PointExpression; + shadowAnchor?: PointExpression; + className?: string; + } + + export interface Icon extends Layer { + createIcon(oldIcon?: HTMLElement): HTMLElement; + createShadow(oldIcon?: HTMLElement): HTMLElement; + } + + export namespace Icon { + export const Default: Icon; + } + + export function icon(options: IconOptions): Icon; + + export interface DivIconOptions extends LayerOptions { + html?: string; + bgPos?: PointExpression; + iconSize?: PointExpression; + iconAnchor?: PointExpression; + popupAnchor?: PointExpression; + className?: string; + } + + export interface DivIcon extends Icon {} + + export function divIcon(options: DivIconOptions): DivIcon; + + export interface MarkerOptions extends InteractiveLayerOptions { + icon?: Icon; + draggable?: boolean; + keyboard?: boolean; + title?: string; + alt?: string; + zIndexOffset?: number; opacity?: number; - - /** - * The explicit zIndex of the tile layer. Not set by default. - */ - zIndex?: number; - - /** - * If true, all the tiles that are not visible after panning are removed (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - unloadInvisibleTiles?: boolean; - - /** - * If false, new tiles are loaded during panning, otherwise only after it (for - * better performance). true by default on mobile WebKit, otherwise false. - */ - updateWhenIdle?: boolean; - - /** - * If true and user is on a retina display, it will request four tiles of half the - * specified size and a bigger zoom level in place of one to utilize the high resolution. - * - * Default value: false. - */ - detectRetina?: boolean; - - /** - * If true, all the tiles that are not visible after panning are placed in a reuse - * queue from which they will be fetched when new tiles become visible (as opposed - * to dynamically creating new ones). This will in theory keep memory usage - * low and eliminate the need for reserving new memory whenever a new tile is - * needed. - * - * Default value: false. - */ - reuseTiles?: boolean; - - /** - * When this option is set, the TileLayer only loads tiles that are in the given geographical bounds. - */ - bounds?: LatLngBounds; - - /** - * Custom keys may be specified in TileLayerOptions so they can be used in a provided URL template. - */ - [additionalKeys: string]: any; + riseOnHover?: boolean; + riseOffset?: number; } + + export interface Marker extends Layer { + getLatLng(): LatLng; + setLatLng(latlng: LatLng): this; + setLatLng(latlng: LatLngLiteral): this; + setLatLng(latlng: LatLngTuple): this; + setZIndexOffset(offset: number): this; + setIcon(icon: Icon): this; + setOpacity(opacity: number): this; + + // Properties + dragging: Handler; + } + + export function marker(latlng: LatLng, options?: MarkerOptions): Marker; + + export function marker(latlng: LatLngLiteral, options?: MarkerOptions): Marker; + + export function marker(latlng: LatLngTuple, options?: MarkerOptions): Marker; } -declare namespace L { - export interface TransformationStatic { - /** - * Creates a transformation object with the given coefficients. - */ - new(a: number, b: number, c: number, d: number): Transformation; - } - export var Transformation: TransformationStatic; - - export interface Transformation { - /** - * Returns a transformed point, optionally multiplied by the given scale. - * Only accepts real L.Point instances, not arrays. - */ - transform(point: Point, scale?: number): Point; - - /** - * Returns the reverse transformation of the given point, optionally divided - * by the given scale. Only accepts real L.Point instances, not arrays. - */ - untransform(point: Point, scale?: number): Point; - } +declare module 'leaflet' { + export = L; } - -declare namespace L { - - namespace Util { - - /** - * Merges the properties of the src object (or multiple objects) into dest object - * and returns the latter. Has an L.extend shortcut. - */ - export function extend(dest: any, ...sources: any[]): any; - - /** - * Returns a function which executes function fn with the given scope obj (so - * that this keyword refers to obj inside the function code). Has an L.bind shortcut. - */ - export function bind(fn: T, obj: any): T; - - /** - * Applies a unique key to the object and returns that key. Has an L.stamp shortcut. - */ - export function stamp(obj: any): string; - - /** - * Returns a wrapper around the function fn that makes sure it's called not more - * often than a certain time interval time, but as fast as possible otherwise - * (for example, it is used for checking and requesting new tiles while dragging - * the map), optionally passing the scope (context) in which the function will - * be called. - */ - export function limitExecByInterval(fn: T, time: number, context?: any): T; - - /** - * Returns a function which always returns false. - */ - export function falseFn(): () => boolean; - - /** - * Returns the number num rounded to digits decimals. - */ - export function formatNum(num: number, digits: number): number; - - /** - * Trims and splits the string on whitespace and returns the array of parts. - */ - export function splitWords(str: string): string[]; - - /** - * Merges the given properties to the options of the obj object, returning the - * resulting options. See Class options. Has an L.setOptions shortcut. - */ - export function setOptions(obj: any, options: any): any; - - /** - * Converts an object into a parameter URL string, e.g. {a: "foo", b: "bar"} - * translates to '?a=foo&b=bar'. - */ - export function getParamString(obj: any): string; - - /** - * Simple templating facility, creates a string by applying the values of the - * data object of a form {a: 'foo', b: 'bar', …} to a template string of the form - * 'Hello {a}, {b}' — in this example you will get 'Hello foo, bar'. - */ - export function template(str: string, data: any): string; - - /** - * Returns true if the given object is an array. - */ - export function isArray(obj: any): boolean; - - /** - * Trims the whitespace from both ends of the string and returns the result. - */ - export function trim(str: string): string; - - /** - * Data URI string containing a base64-encoded empty GIF image. Used as a hack - * to free memory from unused images on WebKit-powered mobile devices (by setting - * image src to this string). - */ - export var emptyImageUrl: string; - } -} - - -declare namespace L { - - export interface WMSOptions { - - /** - * (required) Comma-separated list of WMS layers to show. - * - * Default value: ''. - */ - layers?: string; - - /** - * Comma-separated list of WMS styles. - * - * Default value: 'image/jpeg'. - */ - styles?: string; - - /** - * WMS image format (use 'image/png' for layers with transparency). - * - * Default value: false. - */ - format?: string; - - /** - * If true, the WMS service will return images with transparency. - * - * Default value: '1.1.1'. - */ - transparent?: boolean; - - /** - * Version of the WMS service to use. - */ - version?: string; - - } -} - -/** - * Forces Leaflet to use the Canvas back-end (if available) for vector layers - * instead of SVG. This can increase performance considerably in some cases - * (e.g. many thousands of circle markers on the map). - */ -declare var L_PREFER_CANVAS: boolean; - -/** - * Forces Leaflet to not use touch events even if it detects them. - */ -declare var L_NO_TOUCH: boolean; - -/** - * Forces Leaflet to not use hardware-accelerated CSS 3D transforms for positioning - * (which may cause glitches in some rare environments) even if they're supported. - */ -declare var L_DISABLE_3D: boolean; - -declare module "leaflet" { - export = L; -} - -// vim: et ts=4 sw=4 diff --git a/mapbox/mapbox.d.ts b/mapbox/mapbox.d.ts index 9d341174ea..83e51ebf0e 100644 --- a/mapbox/mapbox.d.ts +++ b/mapbox/mapbox.d.ts @@ -3,7 +3,7 @@ // Definitions by: Maxime Fabre // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// ////////////////////////////////////////////////////////////////////// ///////////////////////////// MAP OBJECT ///////////////////////////// From 549f6a3fa9c51e15d9c0529d1e0b9ca3cf059376 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Mon, 19 Sep 2016 10:09:32 +0300 Subject: [PATCH 131/212] Add svgIcon to MuiTheme (#11293) https://github.com/callemall/material-ui/blob/master/src/styles/getMuiTheme.js#L249-L251 --- material-ui/material-ui.d.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/material-ui/material-ui.d.ts b/material-ui/material-ui.d.ts index 2430923d9d..af69e80b1f 100644 --- a/material-ui/material-ui.d.ts +++ b/material-ui/material-ui.d.ts @@ -344,6 +344,9 @@ declare namespace __MaterialUI { disabledTextColor?: string; connectorLineColor?: string; }; + svgIcon?: { + color?: string, + }; table?: { backgroundColor?: string; }; From cf6fef6e8a8d68211e6d05196c658926c213e3b8 Mon Sep 17 00:00:00 2001 From: iskandersierra Date: Mon, 19 Sep 2016 09:14:34 +0200 Subject: [PATCH 132/212] Added typings for change-emitter@0.1.2 (#11295) --- change-emitter/change-emitter-tests.ts | 124 +++++++++++++++++++++++++ change-emitter/change-emitter.d.ts | 58 ++++++++++++ 2 files changed, 182 insertions(+) create mode 100644 change-emitter/change-emitter-tests.ts create mode 100644 change-emitter/change-emitter.d.ts diff --git a/change-emitter/change-emitter-tests.ts b/change-emitter/change-emitter-tests.ts new file mode 100644 index 0000000000..379c7636a5 --- /dev/null +++ b/change-emitter/change-emitter-tests.ts @@ -0,0 +1,124 @@ +/// + +import { createChangeEmitter, ChangeEmitterOf0 } from "change-emitter"; + +function usage() { + // https://github.com/acdlite/change-emitter#usage + + const emitter = createChangeEmitter() + + // Called `listen` instead of `subscribe` to avoid confusion with observable spec + const unlisten = emitter.listen((...args) => { + console.log(args) + }) + + emitter.emit(1, 2, 3) // logs `[1, 2, 3]` + unlisten() + emitter.emit(4, 5, 6) // doesn't log +} + +function largerExample() { + // https://github.com/acdlite/change-emitter#larger-example + + const createStore = (reducer: Function, initialState: any) => { + let state = initialState + const emitter = createChangeEmitter() + + function dispatch(action: any) { + state = reducer(state, action) + emitter.emit() + return action + } + + function getState() { + return state + } + + return { + dispatch, + getState, + subscribe: emitter.listen + } + } +} + +function untypedEmitter() { + const { emit, listen } = createChangeEmitter(); + + const unlisten0 = listen(() => {/* do something */}); + const unlisten1 = listen(value => {/* do something with value */}); + const unlisten2 = listen((value1, value2) => {/* do something with values */}); + const unlistenArgs = listen((...args: any[]) => {/* do something with values */}); + + emit(); + emit("hello"); + emit("hello", "world"); + emit(1, 2, 3, 4, 5); + + unlisten0(); + unlisten1(); + unlisten2(); + unlistenArgs(); +} + +function emitterOf0Args() { + const { emit, listen }: ChangeEmitterOf0 = createChangeEmitter(); + + const unlisten = listen(() => { }); + // const unlisten = listen(value => {}); // SYNTAX ERROR + + emit(); + // emit("hello"); // SYNTAX ERROR + + unlisten(); +} + +function emitterOf1Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen(value => { value.length }); + + emit("hello"); + + unlisten(); +} + +function emitterOf2Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((value, success) => { value.length > 0 === success }); + + emit("hello", true); + + unlisten(); +} + +function emitterOf3Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((value, success, count) => { value.length > count === success }); + + emit("hello", true, 3); + + unlisten(); +} + +function emitterOf4Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((v1, v2, v3, v4) => { }); + + emit("hello", true, 3, new Date()); + + unlisten(); +} + +function emitterOf5Args() { + const { emit, listen } = createChangeEmitter(); + + const unlisten = listen((v1, v2, v3, v4, v5) => { }); + + emit("hello", true, 3, new Date(), "world"); + + unlisten(); +} diff --git a/change-emitter/change-emitter.d.ts b/change-emitter/change-emitter.d.ts new file mode 100644 index 0000000000..85abf116ed --- /dev/null +++ b/change-emitter/change-emitter.d.ts @@ -0,0 +1,58 @@ +// Type definitions for change-emitter v0.1.2 +// Project: https://github.com/acdlite/change-emitter +// Definitions by: Iskander Sierra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'change-emitter' { + + type Unlisten = () => void; + type Listener = (...args: any[]) => void; + type ListenerOf0 = () => void; + type ListenerOf1 = (value: T) => void; + type ListenerOf2 = (value1: T1, value2: T2) => void; + type ListenerOf3 = (value1: T1, value2: T2, value3: T3) => void; + type ListenerOf4 = (value1: T1, value2: T2, value3: T3, value4: T4) => void; + type ListenerOf5 = (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) => void; + + interface ChangeEmitter { + listen(listener: Listener): Unlisten; + emit(...args: any[]): void; + } + + interface ChangeEmitterOf1 { + listen(listener: ListenerOf1): Unlisten; + emit(value: T): void; + } + + interface ChangeEmitterOf0 { + listen(listener: ListenerOf0): Unlisten; + emit(): void; + } + + interface ChangeEmitterOf2 { + listen(listener: ListenerOf2): Unlisten; + emit(value1: T1, value2: T2): void; + } + + interface ChangeEmitterOf3 { + listen(listener: ListenerOf3): Unlisten; + emit(value1: T1, value2: T2, value3: T3): void; + } + + interface ChangeEmitterOf4 { + listen(listener: ListenerOf4): Unlisten; + emit(value1: T1, value2: T2, value3: T3, value4: T4): void; + } + + interface ChangeEmitterOf5 { + listen(listener: ListenerOf5): Unlisten; + emit(value1: T1, value2: T2, value3: T3, value4: T4, value5: T5): void; + } + + export function createChangeEmitter(): ChangeEmitter; + export function createChangeEmitter(): ChangeEmitterOf1; + export function createChangeEmitter(): ChangeEmitterOf2; + export function createChangeEmitter(): ChangeEmitterOf3; + export function createChangeEmitter(): ChangeEmitterOf4; + export function createChangeEmitter(): ChangeEmitterOf5; +} From e0e86e35352adab42fe829936c199863a6e28d27 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 15:16:55 +0800 Subject: [PATCH 133/212] [express] http.createServer can take express app (#11292) * Create pug-test.ts * Test http.createServer can take express app * Delete this --- express/express-tests.ts | 179 +++++++++++++++++++++------------------ 1 file changed, 96 insertions(+), 83 deletions(-) diff --git a/express/express-tests.ts b/express/express-tests.ts index 439ef95012..92cef00b85 100644 --- a/express/express-tests.ts +++ b/express/express-tests.ts @@ -1,101 +1,114 @@ /// /// - import * as express from 'express'; -var app = express(); - -app.engine('jade', require('jade').__express); -app.engine('html', require('ejs').renderFile); - -express.static.mime.define({ - 'application/fx': ['fx'] -}); -app.use('/static', express.static(__dirname + '/public')); - -// simple logger -app.use(function(req, res, next){ - console.log('%s %s', req.method, req.url); - next(); -}); - -app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { - console.error(err); - next(err); -}); -app.get('/', function(req, res){ - res.send('hello world'); -}); +namespace express_tests { -const router = express.Router(); + var app = express(); + app.engine('jade', require('jade').__express); + app.engine('html', require('ejs').renderFile); -const pathStr : string = 'test'; -const pathRE : RegExp = /test/; -const path = true? pathStr : pathRE; + express.static.mime.define({ + 'application/fx': ['fx'] + }); + app.use('/static', express.static(__dirname + '/public')); -router.get(path); -router.put(path) -router.post(path); -router.delete(path); -router.get(pathStr); -router.put(pathStr) -router.post(pathStr); -router.delete(pathStr); -router.get(pathRE); -router.put(pathRE) -router.post(pathRE); -router.delete(pathRE); - -router.use((req, res, next) => { next(); }) -router.route('/users') - .get((req, res, next) => { - let types: string[] = req.accepts(); - let type: string | boolean = req.accepts('json'); - type = req.accepts(['json', 'text']); - type = req.accepts('json', 'text'); - - let charsets: string[] = req.acceptsCharsets(); - let charset: string | boolean = req.acceptsCharsets('utf-8'); - charset = req.acceptsCharsets(['utf-8', 'utf-16']); - charset = req.acceptsCharsets('utf-8', 'utf-16'); - - let encodings: string[] = req.acceptsEncodings(); - let encoding: string | boolean = req.acceptsEncodings('gzip'); - encoding = req.acceptsEncodings(['gzip', 'deflate']); - encoding = req.acceptsEncodings('gzip', 'deflate'); - - let languages: string[] = req.acceptsLanguages(); - let language: string | boolean = req.acceptsLanguages('en'); - language = req.acceptsLanguages(['en', 'ja']); - language = req.acceptsLanguages('en', 'ja'); - - res.send(req.query['token']); + // simple logger + app.use(function(req, res, next) { + console.log('%s %s', req.method, req.url); + next(); }); -router.get('/user/:id', function(req, res, next) { - if (req.params.id == 0) next('route'); - else next(); -}, function(req, res, next) { - res.render('regular'); -}); + app.use(function(err: any, req: express.Request, res: express.Response, next: express.NextFunction) { + console.error(err); + next(err); + }); -app.use((req, res, next) => { - // hacky trick, router is just a handler - router(req, res, next); -}); -app.use(router); + app.get('/', function(req, res) { + res.send('hello world'); + }); -app.listen(3000); + const router = express.Router(); -const next: express.NextFunction = () => {}; -const nextWithArgument: express.NextFunction = (err: any) => {}; -/** - * The express.Application is compatible with http.createServer - */ + const pathStr: string = 'test'; + const pathRE: RegExp = /test/; + const path = true ? pathStr : pathRE; + router.get(path); + router.put(path) + router.post(path); + router.delete(path); + router.get(pathStr); + router.put(pathStr) + router.post(pathStr); + router.delete(pathStr); + router.get(pathRE); + router.put(pathRE) + router.post(pathRE); + router.delete(pathRE); + + router.use((req, res, next) => { next(); }) + router.route('/users') + .get((req, res, next) => { + let types: string[] = req.accepts(); + let type: string | boolean = req.accepts('json'); + type = req.accepts(['json', 'text']); + type = req.accepts('json', 'text'); + + let charsets: string[] = req.acceptsCharsets(); + let charset: string | boolean = req.acceptsCharsets('utf-8'); + charset = req.acceptsCharsets(['utf-8', 'utf-16']); + charset = req.acceptsCharsets('utf-8', 'utf-16'); + + let encodings: string[] = req.acceptsEncodings(); + let encoding: string | boolean = req.acceptsEncodings('gzip'); + encoding = req.acceptsEncodings(['gzip', 'deflate']); + encoding = req.acceptsEncodings('gzip', 'deflate'); + + let languages: string[] = req.acceptsLanguages(); + let language: string | boolean = req.acceptsLanguages('en'); + language = req.acceptsLanguages(['en', 'ja']); + language = req.acceptsLanguages('en', 'ja'); + + res.send(req.query['token']); + }); + + router.get('/user/:id', function(req, res, next) { + if (req.params.id == 0) next('route'); + else next(); + }, function(req, res, next) { + res.render('regular'); + }); + + app.use((req, res, next) => { + // hacky trick, router is just a handler + router(req, res, next); + }); + + app.use(router); + + app.listen(3000); + + const next: express.NextFunction = () => { }; +} + +/*************************** + * * + * Test with other modules * + * * + ***************************/ import * as http from 'http'; -http.createServer(app); + + +namespace node_tests { + + { + // http.createServer can take express application + const app: express.Application = express(); + http.createServer(app).listen(5678); + } +} From 6fbe7a4242ee73c416397e7d54c85f2eab0058ce Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 03:18:09 -0400 Subject: [PATCH 134/212] Implemented Proj4 definition (#11303) * Implement Proj4 definition * Add proj4 tests --- proj4/proj4-tests.ts | 50 +++++++++++++++++++ proj4/proj4.d.ts | 116 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 166 insertions(+) create mode 100644 proj4/proj4-tests.ts create mode 100644 proj4/proj4.d.ts diff --git a/proj4/proj4-tests.ts b/proj4/proj4-tests.ts new file mode 100644 index 0000000000..c2d5a286b3 --- /dev/null +++ b/proj4/proj4-tests.ts @@ -0,0 +1,50 @@ +/// +import * as proj4 from 'proj4' + +/////////////////////////////////////////// +// Tests data initialisation +/////////////////////////////////////////// +const name = 'WGS84' +const epsg = { + 4269: '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees', + 4326: '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees', +} +const point1 = [-71, 41] +const point2 = {x: 2, y: 5} +const mgrs = "24XWT783908" + +/////////////////////////////////////////// +// Tests Measurement +/////////////////////////////////////////// +proj4(epsg['4269'], epsg['4326'], point1) +proj4(epsg['4269'], point1) +proj4(epsg['4269'], epsg['4326']).forward(point2) +proj4(epsg['4269'], epsg['4326']).inverse(point2) + +/////////////////////////////////// +// Named Projections +/////////////////////////////////// +proj4.defs('WGS84', epsg['4326']) +proj4.defs([ + ['EPSG:4326', epsg['4326']], + ['EPSG:4269', epsg['4269']] +]) +proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')) + +/////////////////////////////////// +// Utils +/////////////////////////////////// +// WGS84 +proj4.WGS84 + +// Proj +proj4.Proj('WGS84') + +// toPoint +proj4.toPoint([1, 2]) +proj4.toPoint([1, 2, 3]) +proj4.toPoint([1, 2, 3, 4]) + +// Point +// WARNING: Deprecated in v3 +proj4.Point([1, 2, 3, 4]) \ No newline at end of file diff --git a/proj4/proj4.d.ts b/proj4/proj4.d.ts new file mode 100644 index 0000000000..70de08b5a6 --- /dev/null +++ b/proj4/proj4.d.ts @@ -0,0 +1,116 @@ +// Type definitions for proj4 2.3.15 +// Project: https://github.com/proj4js/proj4js +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "proj4" { + const TemplateCoordinates: Array | InterfaceCoordinates; + + interface InterfaceCoordinates { + x: number, + y: number, + z?: number, + m?: number + } + + interface InterfaceDatum { + datum_type: number + a: number + b: number + es: number + ep2: number + } + + interface Proj4Static { + forward(coordinates: typeof TemplateCoordinates): Array + inverse(coordinates: typeof TemplateCoordinates): Array + } + + interface InterfaceProjection { + title: string + projName: string + ellps: string + datumCode: string + units: string + a: number + rf: number + ellipseName: string + b: number + a2: number + b2: number + es: number + e: number + ep2: number + k0: number + axis: string + datum: InterfaceDatum + init: typeof proj4.Proj, + forward(coordinates: typeof TemplateCoordinates): Array + inverse(coordinates: typeof TemplateCoordinates): Array + names: Array + to_meter(value: number): any + from_greenwich(value: number): any + } + + namespace proj4 { + /** + * @name defaultDatum + */ + export const defaultDatum: string; + + /** + * @name Proj + */ + export function Proj(srsCode:any, callback?: any): InterfaceProjection; + + /** + * @name WGS84 + */ + export const WGS84: any; + + /** + * Depecrated v3 + * @name Point + */ + export function Point(x: number, y: number, z?: number): InterfaceCoordinates; + export function Point(coordinates: Array): InterfaceCoordinates; + export function Point(coordinates: InterfaceCoordinates): InterfaceCoordinates; + export function Point(coordinates: string): InterfaceCoordinates; + + /** + * @name toPoint + */ + export function toPoint(array: Array): InterfaceCoordinates; + + /** + * @name defs + */ + export function defs(name: string): any; + export function defs(name: string, projection: string): any; + export function defs(name: Array>): any; + + /** + * @name transform + */ + export function transform(source: InterfaceProjection, dest: InterfaceProjection, point: typeof TemplateCoordinates): any; + + /** + * @name mgrs + */ + export function mgrs(coordinates: Array, accuracy: number): string; + + /** + * @name version + */ + export const version: string; + } + + /** + * @name proj4 + */ + function proj4(fromProjection: string): Proj4Static; + function proj4(fromProjection: string, toProjection: string): Proj4Static; + function proj4(fromProjection: string, coordinates: typeof TemplateCoordinates): Array; + function proj4(fromProjection: string, toProjection: string, coordinates: typeof TemplateCoordinates): Array; + export = proj4 +} From 4fd81af1e812fc860fd7acc844f9fac5247372e6 Mon Sep 17 00:00:00 2001 From: Jay Anslow Date: Mon, 19 Sep 2016 08:18:23 +0100 Subject: [PATCH 135/212] Use bluebird@3 instead of @2 (#11299) --- fs-extra-promise/fs-extra-promise.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fs-extra-promise/fs-extra-promise.d.ts b/fs-extra-promise/fs-extra-promise.d.ts index bdf8360b77..2243a4d1c5 100644 --- a/fs-extra-promise/fs-extra-promise.d.ts +++ b/fs-extra-promise/fs-extra-promise.d.ts @@ -6,7 +6,7 @@ // Imported from: https://github.com/soywiz/typescript-node-definitions/fs-extra.d.ts via TSD fs-extra definition /// -/// +/// declare module "fs-extra-promise" { import stream = require("stream"); From 1ce244c131e77a19c72952cab39e7deba645f6df Mon Sep 17 00:00:00 2001 From: Mitchell Wills Date: Mon, 19 Sep 2016 00:19:32 -0700 Subject: [PATCH 136/212] Correct the Angular Material IToastService updateContent typings (#11305) --- angular-material/angular-material-tests.ts | 5 ++++- angular-material/angular-material.d.ts | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index c3ebcbaf99..552ba7a95e 100644 --- a/angular-material/angular-material-tests.ts +++ b/angular-material/angular-material-tests.ts @@ -132,7 +132,10 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia }); myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => { - $scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!')); + $scope['openToast'] = () => { + $mdToast.show($mdToast.simple().textContent('Hello!')); + $mdToast.updateTextContent('New Content'); + } $scope['customToast'] = () => { var options = { diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 66852586da..3fa0290904 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -177,7 +177,8 @@ declare namespace angular.material { showSimple(content: string): angular.IPromise; simple(): ISimpleToastPreset; build(): IToastPreset; - updateContent(): void; + updateContent(newContent: string): void; + updateTextContent(newContent: string): void hide(response?: any): void; cancel(response?: any): void; } From 4c7b1220e0266d0f7eae7b78ecfbb0823e1d9315 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 03:22:08 -0400 Subject: [PATCH 137/212] Implemented shapefile definition (#11307) * Implement shapefile definition * Implement shapefile definition * Shapefile remove Promise reference --- shapefile/shapefile-tests.ts | 19 +++++++++++++++++++ shapefile/shapefile.d.ts | 31 +++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 shapefile/shapefile-tests.ts create mode 100644 shapefile/shapefile.d.ts diff --git a/shapefile/shapefile-tests.ts b/shapefile/shapefile-tests.ts new file mode 100644 index 0000000000..1a827d2706 --- /dev/null +++ b/shapefile/shapefile-tests.ts @@ -0,0 +1,19 @@ +/// +import * as shapefile from 'shapefile' + +shapefile.open('./example.shp') + .then(source => { + source.bbox + source.read() + .then(result => { + result.value + result.done + }) + }) + +shapefile.read("example.shp") + .then(result => { + result.bbox + result.features + result.type + }) diff --git a/shapefile/shapefile.d.ts b/shapefile/shapefile.d.ts new file mode 100644 index 0000000000..20a0b85c7b --- /dev/null +++ b/shapefile/shapefile.d.ts @@ -0,0 +1,31 @@ +// Type definitions for shapefile 0.5.6 +// Project: https://github.com/mbostock/shapefile +// Definitions by: Denis Carriere +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare const shapefile: shapefile.ShapefileStatic; + +declare namespace shapefile { + interface Options { + encoding: string + highWaterMark: number + } + interface Feature { + done: boolean + value: GeoJSON.Feature + } + interface Shapefile { + bbox: Array + read(): Promise; + } + interface ShapefileStatic { + open(shp: any, dbf?: any, options?: Options): Promise; + read(shp: any, dbf?: any, options?: Options): Promise>; + } +} + +declare module "shapefile" { + export = shapefile +} From b36bf17397d104c12df35f44b75cda262946b140 Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 15:23:24 +0800 Subject: [PATCH 138/212] [pug] Create pug definition (#11258) * Create pug.d.ts * Create pug-test.ts * Add project in comments * Rename --- pug/pug-tests.ts | 103 +++++++++++++++++++++++++++++++++++++++++++++++ pug/pug.d.ts | 50 +++++++++++++++++++++++ 2 files changed, 153 insertions(+) create mode 100644 pug/pug-tests.ts create mode 100644 pug/pug.d.ts diff --git a/pug/pug-tests.ts b/pug/pug-tests.ts new file mode 100644 index 0000000000..5ba7d9ad06 --- /dev/null +++ b/pug/pug-tests.ts @@ -0,0 +1,103 @@ +/// +import * as pug from 'pug'; + + +//////////////////////////////////////////////////////////// +/// Options https://pugjs.org/api/reference.html#options /// +//////////////////////////////////////////////////////////// +namespace options_tests { + let opts: pug.Options; + let str = 'string' + let bool = false; + let strArray = ['string']; + + opts.filename = str; + + opts.basedir = str; + + opts.doctype = str; + + opts.pretty = str; + opts.pretty = bool; + + opts.filters = {}; + + opts.self = bool; + + opts.debug = bool; + opts.compileDebug = bool; + + opts.globals = strArray; + + opts.cache = bool; + + opts.inlineRuntimeFunctions = bool; + + opts.name = str; +} + +//////////////////////////////////////////////////////////// +/// Methods https://pugjs.org/api/reference.html#methods /// +//////////////////////////////////////////////////////////// +namespace methods_tests { + let source = `p #{ name } 's Pug source code!`; + let path = "foo.pug"; + let compileTemplate: pug.compileTemplate; + let template: string; + let clientFunctionString: pug.ClientFunctionString; + let str: string; + + { + /// pug.compile(source, ?options) https://pugjs.org/api/reference.html#pugcompilesource-options + compileTemplate = pug.compile(source); + template = compileTemplate(); + } + + { + /// pug.compileFile(path, ?options) https://pugjs.org/api/reference.html#pugcompilefilepath-options + compileTemplate = pug.compileFile(path); + template = compileTemplate(); + } + + { + /// pug.compileClient(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientsource-options + clientFunctionString = pug.compileClient(path); + str = pug.compileClient(path); + } + + { + /// pug.compileClientWithDependenciesTracked(source, ?options) https://pugjs.org/api/reference.html#pugcompileclientwithdependenciestrackedsource-options + let obj = pug.compileClientWithDependenciesTracked(source); + clientFunctionString = obj.body; + str = obj.body; + let strArray: string[] = obj.dependencies; + } + + { + /// pug.compileFileClient(path, ?options) https://pugjs.org/api/reference.html#pugcompilefileclientpath-options + clientFunctionString = pug.compileFileClient(path); + str = pug.compileFileClient(path); + } + + { + /// pug.render(source, ?options, ?callback) https://pugjs.org/api/reference.html#pugrendersource-options-callback + str = pug.render(source); + + // test type for callback paraments + pug.render(source, {}, (err, html) => { + let e: Error = err; + str = html; + }); + } + + { + /// pug.renderFile(path, ?options, ?callback) https://pugjs.org/api/reference.html#pugrenderfilepath-options-callback + str = pug.renderFile(path); + + // test type for callback paraments + pug.renderFile(path, {}, (err, html) => { + let e: Error = err; + str = html; + }); + } +} diff --git a/pug/pug.d.ts b/pug/pug.d.ts new file mode 100644 index 0000000000..8902aa7cf4 --- /dev/null +++ b/pug/pug.d.ts @@ -0,0 +1,50 @@ +// Type definitions for pug 2.0.0-beta6 +// Project: https://github.com/pugjs/pug +// Definitions by: TonyYang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Table of Contents + * + * - Options https://pugjs.org/api/reference.html#options + * - Methods https://pugjs.org/api/reference.html#methods + * + * The order of contents is according to pugjs API document. + */ +declare module 'pug' { + //////////////////////////////////////////////////////////// + /// Options https://pugjs.org/api/reference.html#options /// + //////////////////////////////////////////////////////////// + export interface Options { + filename?: string; + basedir?: string; + doctype?: string; + pretty?: boolean | string; + filters?: any; + self?: boolean; + debug?: boolean; + compileDebug?: boolean; + globals?: string[]; + cache?: boolean; + inlineRuntimeFunctions?: boolean; + name?: string; + } + + //////////////////////////////////////////////////////////// + /// Methods https://pugjs.org/api/reference.html#methods /// + //////////////////////////////////////////////////////////// + export function compile(source: string, options?: Options): (locals?: any) => string; + export function compileFile(path: string, options?: Options): (locals?: any) => string; + export function compileClient(source: string, options?: Options): ClientFunctionString; + export function compileClientWithDependenciesTracked(source: string, options?: Options): { + body: ClientFunctionString; + dependencies: string[]; + }; + export function compileFileClient(path: string, options?: Options): ClientFunctionString; + export function render(source: string, options?: Options, callback?: (err: Error, html: string) => void): string; + export function renderFile(path: string, options?: Options, callback?: (err: Error, html: string) => void): string; + + // else + export type ClientFunctionString = string; // ex: 'function (locals) {...}' + export type compileTemplate = (locals?: any) => string; +} From 150546f73b24ed9569e22f88a28fcbaf7be51402 Mon Sep 17 00:00:00 2001 From: doronbrikman Date: Mon, 19 Sep 2016 10:23:35 +0300 Subject: [PATCH 139/212] Update enzyme.d.ts (#11252) add render method to ReactWrapper --- enzyme/enzyme.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/enzyme/enzyme.d.ts b/enzyme/enzyme.d.ts index 4a5bf2beac..31ffce8923 100644 --- a/enzyme/enzyme.d.ts +++ b/enzyme/enzyme.d.ts @@ -458,6 +458,7 @@ declare module "enzyme" { export interface ReactWrapper extends CommonWrapper { unmount(): ReactWrapper; mount(): ReactWrapper; + render(): CheerioWrapper; /** * Returns a wrapper of the node that matches the provided reference name. From 012b7f1072c1e9bd5d0b309b4d194a014a02ed5f Mon Sep 17 00:00:00 2001 From: TonyYang Date: Mon, 19 Sep 2016 15:24:01 +0800 Subject: [PATCH 140/212] [node] Format test definition (#11308) * Format test definition in v4.x * Format test definition in v6.x --- node/node-4-tests.ts | 108 ++++++++++++------------ node/node-tests.ts | 192 +++++++++++++++++++++---------------------- 2 files changed, 150 insertions(+), 150 deletions(-) diff --git a/node/node-4-tests.ts b/node/node-4-tests.ts index 66fc18ce24..26e201c910 100644 --- a/node/node-4-tests.ts +++ b/node/node-4-tests.ts @@ -28,36 +28,36 @@ import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer /// Assert Tests : https://nodejs.org/api/assert.html /// ////////////////////////////////////////////////////////// -namespace assert_tests{ +namespace assert_tests { { assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - + assert.doesNotThrow(() => { const b = false; if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - + assert.equal(3, "3", "uses == comparator"); assert.fail(1, 2, undefined, '>'); - + assert.ifError(0); - + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - + assert.notEqual(1, 2, "uses != comparator"); - + assert.notStrictEqual(2, "2", "uses === comparator"); - + assert.ok(true); assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - + + assert.strictEqual(1, 1, "uses === comparator"); + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } } @@ -108,7 +108,7 @@ namespace events_tests { result = emitter.emit(event, any, any); result = emitter.emit(event, any, any, any); } - + { class Networker extends events.EventEmitter { constructor() { @@ -145,13 +145,13 @@ namespace fs_tests { var buffer: Buffer; content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', {encoding : 'utf8'}); + content = fs.readFileSync('testfile', { encoding: 'utf8' }); buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', {flag : 'r'}); + buffer = fs.readFileSync('testfile', { flag: 'r' }); fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); + fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); } { @@ -183,7 +183,7 @@ namespace fs_tests { function bufferTests() { var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('','base64'); + var base64Buffer = new Buffer('', 'base64'); var octets: Uint8Array = null; var octetBuffer = new Buffer(octets); var sharedBuffer = new Buffer(octets.buffer); @@ -197,7 +197,7 @@ function bufferTests() { // Class Method: Buffer.from(array) { - const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + const buf: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -262,8 +262,8 @@ function bufferTests() { // Buffer has Uint8Array's buffer field (an ArrayBuffer). { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); + let buffer = new Buffer('123'); + let octets = new Uint8Array(buffer.buffer); } } @@ -275,14 +275,14 @@ function bufferTests() { namespace url_tests { { url.format(url.parse('http://www.example.com/xyz')); - + // https://google.com/search?q=you're%20a%20lizard%2C%20gary url.format({ protocol: 'https', host: "google.com", pathname: 'search', query: { q: "you're a lizard, gary" } - }); + }); } { @@ -299,7 +299,7 @@ namespace util_tests { { // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); } } @@ -324,17 +324,17 @@ namespace crypto_tests { { var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); } - + { let hmac: crypto.Hmac; (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { let hash: Buffer | string = hmac.read(); }); } - + { //crypto_cipher_decipher_string_test - let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); let clearText: string = "This is the clear text."; let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); let cipherText: string = cipher.update(clearText, "utf8", "hex"); @@ -399,26 +399,26 @@ namespace http_tests { } { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); - var agent: http.Agent = http.globalAgent; + var agent: http.Agent = http.globalAgent; - http.request({agent: false}); - http.request({agent: agent}); - http.request({agent: undefined}); + http.request({ agent: false }); + http.request({ agent: agent }); + http.request({ agent: undefined }); } - + { // Make sure .listen() and .close() retuern a Server instance http.createServer().listen(0).close().address(); net.createServer().listen(0).close().address(); } - + { var request = http.request('http://0.0.0.0'); request.once('error', function() { }); @@ -487,7 +487,7 @@ namespace dgram_tests { //////////////////////////////////////////////////// namespace querystring_tests { - type SampleObject = {a: string; b: number;} + type SampleObject = { a: string; b: number; } { let obj: SampleObject; @@ -540,7 +540,7 @@ namespace path_tests { try { path.join('foo', {}, 'bar'); } - catch(error) { + catch (error) { } @@ -654,11 +654,11 @@ namespace path_tests { // } path.format({ - root : "/", - dir : "/home/user/dir", - base : "file.txt", - ext : ".txt", - name : "file" + root: "/", + dir: "/home/user/dir", + base: "file.txt", + ext: ".txt", + name: "file" }); // returns // '/home/user/dir/file.txt' @@ -724,7 +724,7 @@ namespace readline_tests { } { - let data: string|Buffer; + let data: string | Buffer; let key: readline.Key; rl.write(data); @@ -741,8 +741,8 @@ namespace readline_tests { { let stream: NodeJS.WritableStream; - let dx: number|string; - let dy: number|string; + let dx: number | string; + let dy: number | string; readline.moveCursor(stream, dx, dy); } @@ -780,7 +780,7 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test"); } } @@ -788,7 +788,7 @@ namespace child_process_tests { /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// -namespace cluster_tests { +namespace cluster_tests  { { cluster.fork(); Object.keys(cluster.workers).forEach(key => { @@ -840,7 +840,7 @@ namespace os_tests { } { - let result: {[index: string]: os.NetworkInterfaceInfo[]}; + let result: { [index: string]: os.NetworkInterfaceInfo[] }; result = os.networkInterfaces(); } @@ -918,7 +918,7 @@ namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... - + var _p: NodeJS.Process = process; _p = p; } diff --git a/node/node-tests.ts b/node/node-tests.ts index 06fb4a9bf7..1fcf149e99 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -30,36 +30,36 @@ import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer /// Assert Tests : https://nodejs.org/api/assert.html /// ////////////////////////////////////////////////////////// -namespace assert_tests{ +namespace assert_tests { { assert(1 + 1 - 2 === 0, "The universe isn't how it should."); - + assert.deepEqual({ x: { y: 3 } }, { x: { y: 3 } }, "DEEP WENT DERP"); - + assert.deepStrictEqual({ a: 1 }, { a: 1 }, "uses === comparator"); - + assert.doesNotThrow(() => { const b = false; if (b) { throw "a hammer at your face"; } }, undefined, "What the...*crunch*"); - + assert.equal(3, "3", "uses == comparator"); assert.fail(1, 2, undefined, '>'); - + assert.ifError(0); - + assert.notDeepStrictEqual({ x: { y: "3" } }, { x: { y: 3 } }, "uses !== comparator"); - + assert.notEqual(1, 2, "uses != comparator"); - + assert.notStrictEqual(2, "2", "uses === comparator"); - + assert.ok(true); assert.ok(1); - - assert.strictEqual(1, 1, "uses === comparator"); - + + assert.strictEqual(1, 1, "uses === comparator"); + assert.throws(() => { throw "a hammer at your face"; }, undefined, "DODGED IT"); } } @@ -118,7 +118,7 @@ namespace events_tests { result = emitter.eventNames(); } - + { class Networker extends events.EventEmitter { constructor() { @@ -139,31 +139,31 @@ namespace fs_tests { fs.writeFile("thebible.txt", "Do unto others as you would have them do unto you.", assert.ifError); - + fs.write(1234, "test"); - + fs.writeFile("Harry Potter", "\"You be wizzing, Harry,\" jived Dumbledore.", { encoding: "ascii" }, - assert.ifError); + assert.ifError); } { var content: string; var buffer: Buffer; - + content = fs.readFileSync('testfile', 'utf8'); - content = fs.readFileSync('testfile', {encoding : 'utf8'}); + content = fs.readFileSync('testfile', { encoding: 'utf8' }); buffer = fs.readFileSync('testfile'); - buffer = fs.readFileSync('testfile', {flag : 'r'}); + buffer = fs.readFileSync('testfile', { flag: 'r' }); fs.readFile('testfile', 'utf8', (err, data) => content = data); - fs.readFile('testfile', {encoding : 'utf8'}, (err, data) => content = data); + fs.readFile('testfile', { encoding: 'utf8' }, (err, data) => content = data); fs.readFile('testfile', (err, data) => buffer = data); - fs.readFile('testfile', {flag : 'r'}, (err, data) => buffer = data); + fs.readFile('testfile', { flag: 'r' }, (err, data) => buffer = data); } - + { var errno: string; fs.readFile('testfile', (err, data) => { @@ -172,52 +172,52 @@ namespace fs_tests { } }); } - + { fs.mkdtemp('/tmp/foo-', (err, folder) => { console.log(folder); // Prints: /tmp/foo-itXde2 }); } - + { var tempDir: string; tempDir = fs.mkdtempSync('/tmp/foo-'); } - + { fs.watch('/tmp/foo-', (event, filename) => { - console.log(event, filename); + console.log(event, filename); }); - + fs.watch('/tmp/foo-', 'utf8', (event, filename) => { - console.log(event, filename); + console.log(event, filename); }); - + fs.watch('/tmp/foo-', { - recursive: true, - persistent: true, - encoding: 'utf8' + recursive: true, + persistent: true, + encoding: 'utf8' }, (event, filename) => { - console.log(event, filename); + console.log(event, filename); }); } - + { - fs.access('/path/to/folder', (err) => {}); - - fs.access(Buffer.from(''), (err) => {}); - - fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => {}); - - fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => {}); - + fs.access('/path/to/folder', (err) => { }); + + fs.access(Buffer.from(''), (err) => { }); + + fs.access('/path/to/folder', fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + + fs.access(Buffer.from(''), fs.constants.F_OK | fs.constants.R_OK, (err) => { }); + fs.accessSync('/path/to/folder'); - + fs.accessSync(Buffer.from('')); - + fs.accessSync('path/to/folder', fs.constants.W_OK | fs.constants.X_OK); - + fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); } } @@ -228,7 +228,7 @@ namespace fs_tests { function bufferTests() { var utf8Buffer = new Buffer('test'); - var base64Buffer = new Buffer('','base64'); + var base64Buffer = new Buffer('', 'base64'); var octets: Uint8Array = null; var octetBuffer = new Buffer(octets); var sharedBuffer = new Buffer(octets.buffer); @@ -250,7 +250,7 @@ function bufferTests() { // Class Method: Buffer.from(array) { - const buf: Buffer = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + const buf: Buffer = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); } // Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) @@ -373,8 +373,8 @@ function bufferTests() { // Buffer has Uint8Array's buffer field (an ArrayBuffer). { - let buffer = new Buffer('123'); - let octets = new Uint8Array(buffer.buffer); + let buffer = new Buffer('123'); + let octets = new Uint8Array(buffer.buffer); } } @@ -386,14 +386,14 @@ function bufferTests() { namespace url_tests { { url.format(url.parse('http://www.example.com/xyz')); - + // https://google.com/search?q=you're%20a%20lizard%2C%20gary url.format({ protocol: 'https', host: "google.com", pathname: 'search', query: { q: "you're a lizard, gary" } - }); + }); } { @@ -410,7 +410,7 @@ namespace util_tests { { // Old and new util.inspect APIs util.inspect(["This is nice"], false, 5); - util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); + util.inspect(["This is nice"], { colors: true, depth: 5, customInspect: false }); } } @@ -430,18 +430,18 @@ function stream_readable_pipe_test() { // Simplified constructors function simplified_stream_ctor_test() { new stream.Readable({ - read: function (size) { + read: function(size) { size.toFixed(); } }); new stream.Writable({ - write: function (chunk, enc, cb) { + write: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb() }, - writev: function (chunks, cb) { + writev: function(chunks, cb) { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); @@ -449,15 +449,15 @@ function simplified_stream_ctor_test() { }); new stream.Duplex({ - read: function (size) { + read: function(size) { size.toFixed(); }, - write: function (chunk, enc, cb) { + write: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb() }, - writev: function (chunks, cb) { + writev: function(chunks, cb) { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); @@ -467,23 +467,23 @@ function simplified_stream_ctor_test() { }); new stream.Transform({ - transform: function (chunk, enc, cb) { + transform: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb(); }, - flush: function (cb) { + flush: function(cb) { cb() }, - read: function (size) { + read: function(size) { size.toFixed(); }, - write: function (chunk, enc, cb) { + write: function(chunk, enc, cb) { chunk.slice(1); enc.charAt(0); cb() }, - writev: function (chunks, cb) { + writev: function(chunks, cb) { chunks[0].chunk.slice(0); chunks[0].encoding.charAt(0); cb(); @@ -499,17 +499,17 @@ namespace crypto_tests { { var hmacResult: string = crypto.createHmac('md5', 'hello').update('world').digest('hex'); } - + { let hmac: crypto.Hmac; (hmac = crypto.createHmac('md5', 'hello')).end('world', 'utf8', () => { let hash: Buffer | string = hmac.read(); }); } - + { //crypto_cipher_decipher_string_test - let key:Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); + let key: Buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7]); let clearText: string = "This is the clear text."; let cipher: crypto.Cipher = crypto.createCipher("aes-128-ecb", key); let cipherText: string = cipher.update(clearText, "utf8", "hex"); @@ -574,26 +574,26 @@ namespace http_tests { } { - var agent: http.Agent = new http.Agent({ - keepAlive: true, - keepAliveMsecs: 10000, - maxSockets: Infinity, - maxFreeSockets: 256 - }); + var agent: http.Agent = new http.Agent({ + keepAlive: true, + keepAliveMsecs: 10000, + maxSockets: Infinity, + maxFreeSockets: 256 + }); - var agent: http.Agent = http.globalAgent; + var agent: http.Agent = http.globalAgent; - http.request({agent: false}); - http.request({agent: agent}); - http.request({agent: undefined}); + http.request({ agent: false }); + http.request({ agent: agent }); + http.request({ agent: undefined }); } - + { // Make sure .listen() and .close() retuern a Server instance http.createServer().listen(0).close().address(); net.createServer().listen(0).close().address(); } - + { var request = http.request('http://0.0.0.0'); request.once('error', function() { }); @@ -665,7 +665,7 @@ namespace dgram_tests { //////////////////////////////////////////////////// namespace querystring_tests { - type SampleObject = {a: string; b: number;} + type SampleObject = { a: string; b: number; } { let obj: SampleObject; @@ -718,7 +718,7 @@ namespace path_tests { try { path.join('foo', {}, 'bar'); } - catch(error) { + catch (error) { } @@ -832,11 +832,11 @@ namespace path_tests { // } path.format({ - root : "/", - dir : "/home/user/dir", - base : "file.txt", - ext : ".txt", - name : "file" + root: "/", + dir: "/home/user/dir", + base: "file.txt", + ext: ".txt", + name: "file" }); // returns // '/home/user/dir/file.txt' @@ -902,7 +902,7 @@ namespace readline_tests { } { - let data: string|Buffer; + let data: string | Buffer; let key: readline.Key; rl.write(data); @@ -919,8 +919,8 @@ namespace readline_tests { { let stream: NodeJS.WritableStream; - let dx: number|string; - let dy: number|string; + let dx: number | string; + let dy: number | string; readline.moveCursor(stream, dx, dy); } @@ -961,7 +961,7 @@ namespace string_decoder_tests { namespace child_process_tests { { childProcess.exec("echo test"); - childProcess.spawnSync("echo test"); + childProcess.spawnSync("echo test"); } } @@ -969,7 +969,7 @@ namespace child_process_tests { /// cluster tests: https://nodejs.org/api/cluster.html /// ////////////////////////////////////////////////////////////////////// -namespace cluster_tests { +namespace cluster_tests  { { cluster.fork(); Object.keys(cluster.workers).forEach(key => { @@ -1021,7 +1021,7 @@ namespace os_tests { } { - let result: {[index: string]: os.NetworkInterfaceInfo[]}; + let result: { [index: string]: os.NetworkInterfaceInfo[] }; result = os.networkInterfaces(); } @@ -1082,19 +1082,19 @@ namespace vm_tests { namespace timers_tests { { - let immediateId = timers.setImmediate(function(){ console.log("immediate"); }); + let immediateId = timers.setImmediate(function() { console.log("immediate"); }); timers.clearImmediate(immediateId); } { let counter = 0; - let timeout = timers.setInterval(function(){ console.log("interval"); }, 20); + let timeout = timers.setInterval(function() { console.log("interval"); }, 20); timeout.unref(); timeout.ref(); timers.clearInterval(timeout); } { let counter = 0; - let timeout = timers.setTimeout(function(){ console.log("timeout"); }, 20); + let timeout = timers.setTimeout(function() { console.log("timeout"); }, 20); timeout.unref(); timeout.ref(); timers.clearTimeout(timeout); @@ -1124,7 +1124,7 @@ namespace process_tests { { var eventEmitter: events.EventEmitter; eventEmitter = process; // Test that process implements EventEmitter... - + var _p: NodeJS.Process = process; _p = p; } From 993a644034bdd1d1ce18478e6ef0e166abf1fd36 Mon Sep 17 00:00:00 2001 From: Mykhailo Stadnyk Date: Mon, 19 Sep 2016 10:36:28 +0300 Subject: [PATCH 141/212] Added new type definitions for canvas-gauges (#11251) --- canvas-gauges/canvas-gauges-tests.ts | 20 ++ canvas-gauges/canvas-gauges.d.ts | 263 +++++++++++++++++++++++++++ 2 files changed, 283 insertions(+) create mode 100644 canvas-gauges/canvas-gauges-tests.ts create mode 100644 canvas-gauges/canvas-gauges.d.ts diff --git a/canvas-gauges/canvas-gauges-tests.ts b/canvas-gauges/canvas-gauges-tests.ts new file mode 100644 index 0000000000..d0f04e1082 --- /dev/null +++ b/canvas-gauges/canvas-gauges-tests.ts @@ -0,0 +1,20 @@ +/// + +import { + LinearGaugeOptions, + RadialGaugeOptions, + LinearGauge, + RadialGauge +} from 'canvas-gauges'; + +let linearOptions: LinearGaugeOptions = { + renderTo: document.createElement('canvas') +}; +let radialOptions: RadialGaugeOptions = { + renderTo: 'gauge-id' +}; + +new LinearGauge(linearOptions); +new RadialGauge(radialOptions); + +console.log(document.gauges.length); diff --git a/canvas-gauges/canvas-gauges.d.ts b/canvas-gauges/canvas-gauges.d.ts new file mode 100644 index 0000000000..53858e566e --- /dev/null +++ b/canvas-gauges/canvas-gauges.d.ts @@ -0,0 +1,263 @@ +// Type definitions for canvas-gauges +// Project: https://github.com/Mikhus/canvas-gauges +// Definitions by: Mikhus +// Definitions: https://github.com/Mikhus/DefinitelyTyped + +declare namespace CanvasGauges { + export type RenderTarget = string|HTMLElement; + + export interface AnimationRule { + (percent: number): number; + } + + export interface Highlight { + from: number, + to: number, + color: string + } + + export type MajorTicks = string[]|number[]; + + export interface GenericOptions { + renderTo: RenderTarget, + width?: number, + height?: number, + minValue?: number, + maxValue?: number, + value?: number, + units?: string|boolean, + majorTicks?: MajorTicks, + minorTicks?: number, + strokeTicks?: boolean, + animatedValue?: boolean, + title?: string|boolean, + borders?: boolean, + valueInt?: number, + valueDec?: number, + majorTicksInt?: number, + majorTicksDec?: number, + animation?: boolean, + animationDuration?: number, + animationRule?: string|AnimationRule, + colorPlate?: string, + colorMajorTicks?: string, + colorMinorTicks?: string, + colorTitle?: string, + colorUnits?: string, + colorNumbers?: string, + colorNeedle?: string, + colorNeedleEnd?: string, + colorValueText?: string, + colorValueTextShadow?: string, + colorBorderShadow?: string, + colorBorderOuter?: string, + colorBorderOuterEnd?: string, + colorBorderMiddle?: string, + colorBorderMiddleEnd?: string, + colorBorderInner?: string, + colorBorderInnerEnd?: string, + colorValueBoxRect?: string, + colorValueBoxRectEnd?: string, + colorValueBoxBackground?: string, + colorValueBoxShadow?: string, + colorNeedleShadowUp?: string, + colorNeedleShadowDown?: string, + needle?: boolean, + needleShadow?: boolean, + needleType?: string, + needleStart?: number, + needleEnd?: number, + needleWidth?: number, + borderOuterWidth?: number, + borderMiddleWidth?: number, + borderInnerWidth?: number, + borderShadowWidth?: number, + valueBox?: boolean, + valueBoxStroke?: number, + valueText?: string, + valueTextShadow?: boolean, + valueBoxBorderRadius?: number, + highlights?: Highlight[], + fontNumbers?: string, + fontTitle?: string, + fontUnits?: string, + fontValue?: string, + fontTitleSize?: number, + fontValueSize?: number, + fontUnitsSize?: number, + fontNumbersSize?: number + } + + export interface RadialGaugeOptions extends GenericOptions { + ticksAngle?: number, + startAngle?: number, + colorNeedleCircleOuter?: string, + colorNeedleCircleOuterEnd?: string, + colorNeedleCircleInner?: string, + colorNeedleCircleInnerEnd?: string, + needleCircleSize?: number, + needleCircleInner?: boolean, + needleCircleOuter?: boolean, + animationTarget?: string + } + + export interface LinearGaugeOptions extends GenericOptions { + borderRadius?: number, + barBeginCircle?: number, + barWidth?: number, + barStrokeWidth?: number, + barProgress?: boolean, + colorBar?: string, + colorBarEnd?: string, + colorBarStroke?: string, + colorBarProgress?: string, + colorBarProgressEnd?: string, + tickSide?: string, + needleSide?: string, + numberSide?: string, + ticksWidth?: number, + ticksWidthMinor?: number, + ticksPadding?: number, + barLength?: number + } + + export interface DrawEventCallback { + (percent: number): any; + } + + export interface EndEventCallback { + (): any; + } + + export interface rules { + linear: AnimationRule, + quad: AnimationRule, + dequad: AnimationRule, + quint: AnimationRule, + dequint: AnimationRule, + cycle: AnimationRule, + decycle: AnimationRule, + bounce: AnimationRule, + debounce: AnimationRule, + elastic: AnimationRule, + delastic: AnimationRule + } + + export class Animation { + public duration: number; + public rule: string|AnimationRule; + public draw: DrawEventCallback; + public end: EndEventCallback; + + public static rules: rules; + + constructor(rule?: string|AnimationRule, duration?: number, + draw?: DrawEventCallback, end?: EndEventCallback); + + public animate(draw?: DrawEventCallback, end?: EndEventCallback): any; + public destroy(): any; + } + + export class SmartCanvas { + public element: HTMLCanvasElement; + public elementClone: HTMLCanvasElement; + public context: CanvasRenderingContext2D; + public contextClone: CanvasRenderingContext2D; + public drawWidth: number; + public drawHeight: number; + public drawX: number; + public drawY: number; + public minSide: number; + public width: number; + public height: number; + + constructor(element: HTMLCanvasElement, + width?: number, + height?: number); + + public init(): any; + public onRedraw(): any; + public destroy(): any; + public commit(): SmartCanvas; + public redraw(): SmartCanvas; + + public pixelRatio: number; + public static redraw(): any; + public static collection: Array; + } + + export class DomObserver { + public Type: BaseGauge; + public mutationsObserved: boolean; + public isObservable: boolean; + public options: GenericOptions; + public element: string; + public type: string; + + constructor(options: GenericOptions, + element: string, + type: string); + + public isValidNode(node: Node|HTMLElement): boolean; + public traverse(): any; + public observe(records: MutationRecord[]): any; + public process(node: Node|HTMLElement): BaseGauge; + + public static parse(value: any): any; + public static toDashed(camelCase: string): string; + public static toAttributeName(str: string): string; + static domReady(handler: Function): any; + } + + export abstract class BaseGauge { + public type: BaseGauge; + public options: GenericOptions; + public canvas: SmartCanvas; + public animation: Animation; + public value: number; + + constructor(options: GenericOptions); + + public update(options: GenericOptions): BaseGauge; + public destroy(): any; + public abstract draw(): BaseGauge; + + public static initialize(type: string, options: GenericOptions): any; + } + + export class RadialGauge extends BaseGauge { + public type: RadialGauge; + public options: RadialGaugeOptions; + + constructor(options: RadialGaugeOptions); + + public draw(): RadialGauge; + } + + export class LinearGauge extends BaseGauge { + public type: LinearGauge; + public options: LinearGaugeOptions; + + constructor(options: LinearGaugeOptions); + + public draw(): LinearGauge; + } + + export interface Collection extends Array { + get: (id: number | string) => BaseGauge; + } +} + +declare module 'canvas-gauges' { + export = CanvasGauges; +} + +interface Document { + gauges: CanvasGauges.Collection; +} + +interface Window { + BaseGauge: CanvasGauges.BaseGauge; + RadialGauge: CanvasGauges.RadialGauge; + LinearGauge: CanvasGauges.LinearGauge; +} From 316a4a0c06b51fab3495216e863f8c1facb17a58 Mon Sep 17 00:00:00 2001 From: Andrey Kurdyumov Date: Mon, 19 Sep 2016 13:55:38 +0600 Subject: [PATCH 142/212] Add property available You could see usage of that property here. https://github.com/apache/cordova-plugin-device/blob/master/www/device.js#L55 --- cordova-plugin-device/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cordova-plugin-device/index.d.ts b/cordova-plugin-device/index.d.ts index 494b04f1e2..cb75703d1a 100644 --- a/cordova-plugin-device/index.d.ts +++ b/cordova-plugin-device/index.d.ts @@ -13,6 +13,8 @@ interface Device { /** Get the version of Cordova running on the device. */ cordova: string; + /** Indicates that Cordova initialize successfully. */ + available: boolean; /** * The device.model returns the name of the device's model or product. The value is set * by the device manufacturer and may be different across versions of the same product. @@ -31,4 +33,4 @@ interface Device { /** Get the device hardware serial number. */ serial: string;} -declare var device: Device; \ No newline at end of file +declare var device: Device; From 4f0bb211cf6daaaa8720ca2b598683a6951f81dc Mon Sep 17 00:00:00 2001 From: Julien Sergent Date: Mon, 19 Sep 2016 10:50:50 +0200 Subject: [PATCH 143/212] Update facebook-js-sdk-tests.ts --- facebook-js-sdk/facebook-js-sdk-tests.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/facebook-js-sdk/facebook-js-sdk-tests.ts b/facebook-js-sdk/facebook-js-sdk-tests.ts index 49e615f529..41c0eaff40 100644 --- a/facebook-js-sdk/facebook-js-sdk-tests.ts +++ b/facebook-js-sdk/facebook-js-sdk-tests.ts @@ -14,6 +14,12 @@ FB.getLoginStatus(function(response: fb.AuthResponse) { console.log(response.authResponse.accessToken); }); +FB.getLoginStatus(function(response: fb.AuthResponse) { + console.log(response); + console.log(response.status); + console.log(response.authResponse.accessToken); +}, true); + FB.getAuthResponse(function(response: fb.AuthResponse) { console.log(response); console.log(response.status); From a03bb7d3be1f19d9280330297e0456e632c9b71f Mon Sep 17 00:00:00 2001 From: sumit2chauhan Date: Mon, 19 Sep 2016 14:35:01 +0530 Subject: [PATCH 144/212] There is a typescript build error in this The property " component? " in IModalSettings is repeated. --- angular-ui-bootstrap/angular-ui-bootstrap.d.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts index 71ef8b7363..d6c389146b 100644 --- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts +++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts @@ -329,12 +329,6 @@ declare namespace angular.ui.bootstrap { * @default false */ bindToController?: boolean; - - /** - * A string reference to the component to be rendered that is registered with Angular's compiler. - * If using a directive, the directive must have restrict: 'E' and a template or templateUrl set. - */ - component?: string; /** * members that will be resolved and passed to the controller as locals; it is equivalent of the `resolve` property for AngularJS routes From 26bb1f5bc53e3ba493aa4269f94b9d3db18c32ca Mon Sep 17 00:00:00 2001 From: NoHomey Date: Mon, 19 Sep 2016 17:14:45 +0300 Subject: [PATCH 145/212] Updating jest.d.ts to be close to what @jwbay requested --- jest/jest-tests.ts | 1 + jest/jest.d.ts | 329 ++++++++++++++++++++++++++++++++++++--------- 2 files changed, 268 insertions(+), 62 deletions(-) diff --git a/jest/jest-tests.ts b/jest/jest-tests.ts index 04fba5ab09..b547bd40ad 100644 --- a/jest/jest-tests.ts +++ b/jest/jest-tests.ts @@ -1,4 +1,5 @@ /// +/// // Tests based on the Jest website jest.unmock('../sum'); diff --git a/jest/jest.d.ts b/jest/jest.d.ts index 506bd6533d..d0660193f6 100644 --- a/jest/jest.d.ts +++ b/jest/jest.d.ts @@ -1,55 +1,146 @@ // Type definitions for Jest 15.1.1 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana , Ivo Stratev +// Definitions by: Asana , Ivo Stratev , jwbay // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +declare var beforeAll: jest.Lifecycle; +declare var beforeEach: jest.Lifecycle; +declare var afterAll: jest.Lifecycle; +declare var afterEach: jest.Lifecycle; +declare var describe: jest.Describe; +declare var fdescribe: jest.Describe; +declare var xdescribe: jest.Describe; +declare var it: jest.It; +declare var fit: jest.It; +declare var xit: jest.It; +declare var test: jest.It; +declare var xtest: jest.It; -declare function afterEach(fn: () => any): void; -declare function beforeEach(fn: () => any): void; -declare function describe(name: string, fn: () => any): void; declare function expect(actual: any): jest.Matchers; -declare function it(name: string, fn: () => any): void; -declare function fit(name: string, fn: () => any): void; -declare function test(name: string, fn: () => any): void; -declare function xdescribe(name: string, fn: () => any): void; -declare function xit(name: string, fn: () => any): void; +interface NodeRequire { + /** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */ + requireActual(moduleName: string): any; + /** Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. */ + requireMock(moduleName: string): any; +} declare namespace jest { - interface Matchers { - lastCalledWith(...args: any[]): boolean; - not: Matchers; - toBe(expected: any): boolean; - toBeCalled(): boolean; - toBeCalledWith(...args: any[]): boolean; - toBeCloseTo(expected: number, delta: number): boolean; - toBeDefined(): boolean; - toBeFalsy(): boolean; - toBeGreaterThan(expected: number): boolean; - toBeGreaterThanOrEqual(expected: number): boolean; - toBeLessThan(expected: number): boolean; - toBeLessThanOrEqual(expected: number): boolean; - toBeNull(): boolean; - toBeTruthy(): boolean; - toBeUndefined(): boolean; - toContain(expected: string): boolean; - toEqual(expected: any): boolean; - toMatch(expected: RegExp): boolean; - toMatchSnapshot(): boolean; - toThrow(): boolean; - toThrowError(expected: string | RegExp): boolean; - toThrowError(expected: TFunction): boolean; - } - - interface MockContext { - calls: any[][]; - instances: T[]; + function addMatchers(matchers: jasmine.CustomMatcherFactories): void; + /** Disables automatic mocking in the module loader. */ + function autoMockOff(): void; + /** Enables automatic mocking in the module loader. */ + function autoMockOn(): void; + /** Removes any pending timers from the timer system. If any timers have been scheduled, they will be cleared and will never have the opportunity to execute in the future. */ + function clearAllTimers(): void; + /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ + function deepUnmock(moduleName: string): void; + /** Disables automatic mocking in the module loader. */ + function disableAutomock(): void; + /** Mocks a module with an auto-mocked version when it is being required. */ + function doMock(moduleName: string): void; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ + function dontMock(moduleName: string): void; + /** Enables automatic mocking in the module loader. */ + function enableAutomock(): void; + /** Creates a mock function. Optionally takes a mock implementation. */ + function fn(implementation?: Function): Mock; + /** Use the automatic mocking system to generate a mocked version of the given module. */ + function genMockFromModule(moduleName: string): T; + /** Returns whether the given function is a mock function. */ + function isMockFunction(fn: any): fn is Mock; + /** Mocks a module with an auto-mocked version when it is being required. */ + function mock(moduleName: string, factory?: any, options?: MockOptions): void; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModuleRegistry(): void; + /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + function resetModules(): void; + /** Exhausts tasks queued by setImmediate(). */ + function runAllImmediates(): void; + /** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */ + function runAllTicks(): void; + /** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */ + function runAllTimers(): void; + /** Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by setTimeout() or setInterval() up to this point). + * If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. */ + function runOnlyPendingTimers(): void; + /** Explicitly supplies the mock object that the module system should return for the specified module. */ + function setMock(moduleName: string, moduleExports: T): void; + /** Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module). */ + function unmock(moduleName: string): void; + /** Instructs Jest to use fake versions of the standard timer functions. */ + function useFakeTimers(): void; + /** Instructs Jest to use the real versions of the standard timer functions. */ + function useRealTimers(): void; + + interface MockOptions { + virtual?: boolean; } - interface Mock { + interface EmptyFunction { + (): void; + } + + interface DoneCallback { + (...args: any[]): any + fail(error?: string | { message: string }): any; + } + + interface ProvidesCallback { + (cb?: DoneCallback): any; + } + + interface Lifecycle { + (fn: ProvidesCallback): any; + } + + interface It { + (name: string, fn: ProvidesCallback): void; + only: It; + skip: It; + } + + interface Describe { + (name: string, fn: EmptyFunction): void + only: Describe; + skip: Describe; + } + + interface Matchers { + not: Matchers; + lastCalledWith(...args: any[]): void; + toBe(expected: any): void; + toBeCalled(): void; + toBeCalledWith(...args: any[]): void; + toBeCloseTo(expected: number, delta: number): void; + toBeDefined(): void; + toBeFalsy(): void; + toBeGreaterThan(expected: number): void; + toBeGreaterThanOrEqual(expected: number): void; + toBeInstanceOf(expected: any): void + toBeLessThan(expected: number): void; + toBeLessThanOrEqual(expected: number): void; + toBeNull(): void; + toBeTruthy(): void; + toBeUndefined(): void; + toContain(expected: any): void; + toEqual(expected: any): void; + toHaveBeenCalled(): boolean; + toHaveBeenCalledTimes(expected: number): boolean; + toHaveBeenCalledWith(...params: any[]): boolean; + toMatch(expected: string | RegExp): void; + toMatchSnapshot(): void; + toThrow(): void; + toThrowError(error?: string | Constructable | RegExp): void; + } + + interface Constructable { + new (...args: any[]): any + } + + interface Mock extends Function { new (): T; - (...args: any[]): any; // Making Mock Callable and fixing: Value of type 'Mock' is not callable. + (...args: any[]): any; mock: MockContext; mockClear(): void; mockImplementation(fn: Function): Mock; @@ -58,31 +149,145 @@ declare namespace jest { mockReturnValue(value: any): Mock; mockReturnValueOnce(value: any): Mock; } - - function clearAllTimers(): void; - function disableAutomock(): void; - function enableAutomock(): void; - function fn(implementation?: Function): Mock; - function isMockFunction(fn: Function): boolean; - function genMockFromModule(moduleName: string): T; - function mock(moduleName: string, factory?: Function, options?: {virtual: boolean}): void; - function resetModules(): void; - function runAllTicks(): void; - function runAllTimers(): void; - function runOnlyPendingTimers(): void; - function setMock(moduleName: string, moduleExports: T): void; - function unmock(moduleName: string): void; - function useFakeTimers(): void; - function useRealTimers(): void; - // taken from Jasmine which takes from TypeScript lib.core.es6.d.ts, applicable to CustomMatchers.contains() + interface MockContext { + calls: any[][]; + instances: T[]; + } +} + +//Jest ships with a copy of Jasmine. They monkey-patch its APIs and divergence/deprecation are expected. +//Relevant parts of Jasmine's API are below so they can be changed and removed over time. +//This file can't reference jasmine.d.ts since the globals aren't compatible. + +declare function spyOn(object: any, method: string): jasmine.Spy; +/** If you call the function pending anywhere in the spec body, no matter the expectations, the spec will be marked pending. */ +declare function pending(reason?: string): void; +/** Fails a test when called within one. */ +declare function fail(error?: any): void; +declare namespace jasmine { + var clock: () => Clock; + function any(aclass: any): Any; + function anything(): Any; + function arrayContaining(sample: any[]): ArrayContaining; + function objectContaining(sample: any): ObjectContaining; + function createSpy(name: string, originalFn?: Function): Spy; + function createSpyObj(baseName: string, methodNames: any[]): any; + function createSpyObj(baseName: string, methodNames: any[]): T; + function pp(value: any): string; + function addCustomEqualityTester(equalityTester: CustomEqualityTester): void; + function addMatchers(matchers: CustomMatcherFactories): void; + function stringMatching(value: string | RegExp): Any; + + interface Clock { + install(): void; + uninstall(): void; + /** Calls to any registered callback are triggered when the clock is ticked forward via the jasmine.clock().tick function, which takes a number of milliseconds. */ + tick(ms: number): void; + mockDate(date?: Date): void; + } + + interface Any { + new (expectedClass: any): any; + jasmineMatches(other: any): boolean; + jasmineToString(): string; + } + + interface ArrayContaining { + new (sample: any[]): any; + asymmetricMatch(other: any): boolean; + jasmineToString(): string; + } + + interface ObjectContaining { + new (sample: any): any; + jasmineMatches(other: any, mismatchKeys: any[], mismatchValues: any[]): boolean; + jasmineToString(): string; + } + + interface Spy { + (...params: any[]): any; + identity: string; + and: SpyAnd; + calls: Calls; + mostRecentCall: { args: any[]; }; + argsForCall: any[]; + wasCalled: boolean; + } + + interface SpyAnd { + /** By chaining the spy with and.callThrough, the spy will still track all calls to it but in addition it will delegate to the actual implementation. */ + callThrough(): Spy; + /** By chaining the spy with and.returnValue, all calls to the function will return a specific value. */ + returnValue(val: any): Spy; + /** By chaining the spy with and.returnValues, all calls to the function will return specific values in order until it reaches the end of the return values list. */ + returnValues(...values: any[]): Spy; + /** By chaining the spy with and.callFake, all calls to the spy will delegate to the supplied function. */ + callFake(fn: Function): Spy; + /** By chaining the spy with and.throwError, all calls to the spy will throw the specified value. */ + throwError(msg: string): Spy; + /** When a calling strategy is used for a spy, the original stubbing behavior can be returned at any time with and.stub. */ + stub(): Spy; + } + + interface Calls { + /** By chaining the spy with calls.any(), will return false if the spy has not been called at all, and then true once at least one call happens. */ + any(): boolean; + /** By chaining the spy with calls.count(), will return the number of times the spy was called */ + count(): number; + /** By chaining the spy with calls.argsFor(), will return the arguments passed to call number index */ + argsFor(index: number): any[]; + /** By chaining the spy with calls.allArgs(), will return the arguments to all calls */ + allArgs(): any[]; + /** By chaining the spy with calls.all(), will return the context (the this) and arguments passed all calls */ + all(): CallInfo[]; + /** By chaining the spy with calls.mostRecent(), will return the context (the this) and arguments for the most recent call */ + mostRecent(): CallInfo; + /** By chaining the spy with calls.first(), will return the context (the this) and arguments for the first call */ + first(): CallInfo; + /** By chaining the spy with calls.reset(), will clears all tracking for a spy */ + reset(): void; + } + + interface CallInfo { + /** The context (the this) for the call */ + object: any; + /** All arguments passed to the call */ + args: any[]; + /** The return value of the call */ + returnValue: any; + } + + interface CustomMatcherFactories { + [index: string]: CustomMatcherFactory; + } + + interface CustomMatcherFactory { + (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; + } + + interface MatchersUtil { + equals(a: any, b: any, customTesters?: Array): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: Array): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: Array): string; + } + + interface CustomEqualityTester { + (first: any, second: any): boolean; + } + + interface CustomMatcher { + compare(actual: T, expected: T): CustomMatcherResult; + compare(actual: any, expected: any): CustomMatcherResult; + } + + interface CustomMatcherResult { + pass: boolean; + message: string | (() => string); + } + interface ArrayLike { length: number; [n: number]: T; } } - -interface NodeRequire { - requireActual(moduleName: string): any; - requireMock(moduleName: string): any; -} From bb5916e6451594dbc565c8877dfcbfebde1c8976 Mon Sep 17 00:00:00 2001 From: pafflique Date: Mon, 19 Sep 2016 17:51:12 +0300 Subject: [PATCH 146/212] Concat second+ parameter can be plain value. --- lodash/lodash.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lodash/lodash.d.ts b/lodash/lodash.d.ts index eb24793955..3bdd09fab4 100644 --- a/lodash/lodash.d.ts +++ b/lodash/lodash.d.ts @@ -501,7 +501,7 @@ declare module _ { * console.log(array); * // => [1] */ - concat(...values: (T[]|List)[]) : T[]; + concat(array: T[]|List, ...values: (T|T[]|List)[]) : T[]; } //_.difference From 20bcf21d905410c359268df715a7c6a7771493b6 Mon Sep 17 00:00:00 2001 From: Denis Date: Mon, 19 Sep 2016 13:28:14 -0400 Subject: [PATCH 147/212] Removed extra constants Proj4 Projection --- proj4/proj4.d.ts | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/proj4/proj4.d.ts b/proj4/proj4.d.ts index 70de08b5a6..d59063f51b 100644 --- a/proj4/proj4.d.ts +++ b/proj4/proj4.d.ts @@ -27,29 +27,15 @@ declare module "proj4" { } interface InterfaceProjection { - title: string - projName: string - ellps: string - datumCode: string - units: string - a: number - rf: number - ellipseName: string + datum: string b: number - a2: number - b2: number + rf: number + sphere: number es: number e: number ep2: number - k0: number - axis: string - datum: InterfaceDatum - init: typeof proj4.Proj, forward(coordinates: typeof TemplateCoordinates): Array inverse(coordinates: typeof TemplateCoordinates): Array - names: Array - to_meter(value: number): any - from_greenwich(value: number): any } namespace proj4 { From 2ff803ff9187fc4837a79924435f2d98f8a3bdda Mon Sep 17 00:00:00 2001 From: feitzi Date: Mon, 19 Sep 2016 20:14:41 +0200 Subject: [PATCH 148/212] refactored: randomColor to randomcolor --- randomColor/randomColor.d.ts | 2 +- randomcolor/randomcolor-tests.ts | 40 ++++++++++++++++++++++++++++++++ randomcolor/randomcolor.d.ts | 28 ++++++++++++++++++++++ 3 files changed, 69 insertions(+), 1 deletion(-) create mode 100644 randomcolor/randomcolor-tests.ts create mode 100644 randomcolor/randomcolor.d.ts diff --git a/randomColor/randomColor.d.ts b/randomColor/randomColor.d.ts index 1c52f39be1..a92af51453 100644 --- a/randomColor/randomColor.d.ts +++ b/randomColor/randomColor.d.ts @@ -23,6 +23,6 @@ interface randomColorOptions { declare var randomColor: RandomColor.RandomColorStatic; -declare module 'randomColor' { +declare module 'randomcolor' { export = randomColor; } \ No newline at end of file diff --git a/randomcolor/randomcolor-tests.ts b/randomcolor/randomcolor-tests.ts new file mode 100644 index 0000000000..69b617615e --- /dev/null +++ b/randomcolor/randomcolor-tests.ts @@ -0,0 +1,40 @@ +/// + +// Returns a hex code for an attractive color +randomColor(); + +// Returns an array of ten green colors +randomColor({ + count: 10, + hue: 'green' +}); + +// Returns a hex code for a light blue +randomColor({ + luminosity: 'light', + hue: 'blue' +}); + +// Returns a hex code for a 'truly random' color +randomColor({ + luminosity: 'random', + hue: 'random' +}); + +// Returns a bright color in RGB +randomColor({ + luminosity: 'bright', + format: 'rgb' // e.g. 'rgb(225,200,20)' +}); + +// Returns a dark RGB color with random alpha +randomColor({ + luminosity: 'dark', + format: 'rgba' // e.g. 'rgba(9, 1, 107, 0.6482447960879654)' +}); + +// Returns a light HSL color with random alpha +randomColor({ + luminosity: 'light', + format: 'hsla' // e.g. 'hsla(27, 88.99%, 81.83%, 0.6450211517512798)' +}); \ No newline at end of file diff --git a/randomcolor/randomcolor.d.ts b/randomcolor/randomcolor.d.ts new file mode 100644 index 0000000000..a92af51453 --- /dev/null +++ b/randomcolor/randomcolor.d.ts @@ -0,0 +1,28 @@ +// Type definitions for randomColor 0.4.1 +// Project: https://github.com/davidmerfield/randomColor +// Definitions by: Mathias Feitzinger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace RandomColor { + + interface RandomColorStatic { + + () : string; + + (options : randomColorOptions): string; +} + +interface randomColorOptions { + hue? : string; + luminosity? : string; + count? : string | number; + seed?: string; + format?: string; + } +} + +declare var randomColor: RandomColor.RandomColorStatic; + +declare module 'randomcolor' { + export = randomColor; +} \ No newline at end of file From 8571feee2f68b8971ee02acbe60021d368ba4136 Mon Sep 17 00:00:00 2001 From: feitzi Date: Mon, 19 Sep 2016 20:18:33 +0200 Subject: [PATCH 149/212] fixed wrong reference path --- randomColor/randomColor-tests.ts | 2 +- randomcolor/randomcolor-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/randomColor/randomColor-tests.ts b/randomColor/randomColor-tests.ts index 69b617615e..4dfd6bed26 100644 --- a/randomColor/randomColor-tests.ts +++ b/randomColor/randomColor-tests.ts @@ -1,4 +1,4 @@ -/// +/// // Returns a hex code for an attractive color randomColor(); diff --git a/randomcolor/randomcolor-tests.ts b/randomcolor/randomcolor-tests.ts index 69b617615e..4dfd6bed26 100644 --- a/randomcolor/randomcolor-tests.ts +++ b/randomcolor/randomcolor-tests.ts @@ -1,4 +1,4 @@ -/// +/// // Returns a hex code for an attractive color randomColor(); From 24c81fd722b734b793ea7acd7aca0fddebe47c71 Mon Sep 17 00:00:00 2001 From: feitzi Date: Mon, 19 Sep 2016 20:36:32 +0200 Subject: [PATCH 150/212] fixed renaming folder --- {randomColor => randomcolor}/randomColor-tests.ts | 0 {randomColor => randomcolor}/randomColor.d.ts | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename {randomColor => randomcolor}/randomColor-tests.ts (100%) rename {randomColor => randomcolor}/randomColor.d.ts (100%) diff --git a/randomColor/randomColor-tests.ts b/randomcolor/randomColor-tests.ts similarity index 100% rename from randomColor/randomColor-tests.ts rename to randomcolor/randomColor-tests.ts diff --git a/randomColor/randomColor.d.ts b/randomcolor/randomColor.d.ts similarity index 100% rename from randomColor/randomColor.d.ts rename to randomcolor/randomColor.d.ts From 66c9d1c4ba7246540618d831355eaf2ced60d48e Mon Sep 17 00:00:00 2001 From: Marc Date: Mon, 19 Sep 2016 14:56:14 -0400 Subject: [PATCH 151/212] Fix asked by andy-ms --- requirejs/require.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirejs/require.d.ts b/requirejs/require.d.ts index 1c5b4088c1..ac116494f3 100644 --- a/requirejs/require.d.ts +++ b/requirejs/require.d.ts @@ -206,7 +206,7 @@ interface RequireConfig { * } * }); **/ - urlArgs?: string | { (id: string, url: string): string; }; + urlArgs?: string | ((id: string, url: string) => string); /** * Specify the value for the type="" attribute used for script From 0a9c6b435c24fa0f07a62beb2c7d43b98914bc21 Mon Sep 17 00:00:00 2001 From: David Poetzsch-Heffter Date: Tue, 20 Sep 2016 00:24:55 +0200 Subject: [PATCH 152/212] added typings for parse-mockdb --- parse-mockdb/parse-mockdb-tests.ts | 25 +++++++++++++++++++++++++ parse-mockdb/parse-mockdb.d.ts | 21 +++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 parse-mockdb/parse-mockdb-tests.ts create mode 100644 parse-mockdb/parse-mockdb.d.ts diff --git a/parse-mockdb/parse-mockdb-tests.ts b/parse-mockdb/parse-mockdb-tests.ts new file mode 100644 index 0000000000..89f586d9e8 --- /dev/null +++ b/parse-mockdb/parse-mockdb-tests.ts @@ -0,0 +1,25 @@ +/// + +ParseMockDB.mockDB(); // Mock the Parse RESTController + +// from parse-mockdb test suite +ParseMockDB.registerHook("Foo", "beforeSave", (request) => { + const object = request.object; + if (object.get('error')) { + return Parse.Promise.error('whoah'); + } + object.set('cool', true); + return Parse.Promise.as(object); +}); + +// from parse-mockdb test suite +ParseMockDB.registerHook("Foo", "beforeDelete", (request) => { + const object = request.object; + if (object.get('error')) { + return Parse.Promise.error('whoah'); + } + return Parse.Promise.as({}); +}); + +ParseMockDB.cleanUp(); // Clear the Database +ParseMockDB.unMockDB(); // Un-mock the Parse RESTController diff --git a/parse-mockdb/parse-mockdb.d.ts b/parse-mockdb/parse-mockdb.d.ts new file mode 100644 index 0000000000..c6b6e729d1 --- /dev/null +++ b/parse-mockdb/parse-mockdb.d.ts @@ -0,0 +1,21 @@ +// Type definitions for parse-mockdb v0.1.13 +// Project: https://github.com/HustleInc/parse-mockdb +// Definitions by: David Poetzsch-Heffter +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace ParseMockDB { + function mockDB(): void; + function unMockDB(): void; + function cleanUp(): void; + + function promiseResultSync(promise: Parse.IPromise): T; + + type HookType = "beforeSave" | "beforeDelete"; + function registerHook(className: string, hookType: HookType, hookFn: (request: Parse.Cloud.BeforeSaveRequest) => Parse.IPromise): void; +} + +declare module "parse-mockdb" { + export = ParseMockDB; +} From e822a596e4a68bd8a7e4a9f49f2ea95f6c25972d Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 18:54:46 -0400 Subject: [PATCH 153/212] Replace deprecated module keyword --- twilio/twilio.d.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index d6c2dfebf7..d6af461760 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -16,7 +16,7 @@ declare interface twilio { (sid?: string, tkn?: string, options?: twilio.ClientOptions): twilio.RestClient; } -declare module twilio { +declare namespace twilio { // Composite Classes: //============================== @@ -166,7 +166,7 @@ declare module twilio { clientName: string; outgoingScopeParams: any; scopeParams: any; - + constructor(sid?: string, tkn?: string); allowClientIncoming(clientName: string): Capability; @@ -319,7 +319,7 @@ declare module twilio { allowWorkerActivityUpdates(): void; allowWorkerFetchAttributes(): void; allowTaskReservationUpdates(): void; - + addPolicy(url: string, method: string, allowed?: boolean, queryFilter?: any, postFilter?: any): void; allow(url: string, method: string, queryFilter?: any, postFilter?: any): void; deny(url: string, method: string, queryFilter?: any, postFilter?: any): void; @@ -380,7 +380,7 @@ declare module twilio { } export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } - + export interface TwimlCallback { (node?: Node): void; } export class Node implements NodeOptions { @@ -435,7 +435,7 @@ declare module twilio { export interface WebhookExpressOptions { // The full URL (with query string) you used to configure the webhook with Twilio - overrides host/protocol options url?: string; - + // manually specify the host name used by Twilio in a number's webhook config host?: string; From d705c4e9da0030cc11387bca31e42ddc7809ff04 Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 18:55:03 -0400 Subject: [PATCH 154/212] Add missing `webhook()` signature --- twilio/twilio-tests.ts | 2 +- twilio/twilio.d.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index 30e9892078..d7f2c60993 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -228,5 +228,5 @@ twilio.validateRequest(token, str, 'http://example.herokuapp.com', { query: 'val twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN'); twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN', {}); twilio.webhook({ validate: false }); - +twilio.webhook("MYAUTHTOKEN", { validate: false }); diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index d6af461760..8bd6911113 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -446,7 +446,8 @@ declare namespace twilio { // For interop with node middleware chains export interface MiddlewareFunction { (request: Http.ClientRequest, response: Http.ClientResponse, next: MiddlewareFunction): void; } - export function webhook(options?: string | webhookOptions): MiddlewareFunction; + export function webhook(authToken: string, options?: webhookOptions): MiddlewareFunction; + export function webhook(options?: webhookOptions): MiddlewareFunction; export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; export function validateExpressRequest(request: express.Request, authToken: string, options?: WebhookExpressOptions): boolean; From 6164f95bb173936a3a10396a01a30242ebc54bfa Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 18:58:03 -0400 Subject: [PATCH 155/212] Fix MiddlewareFunction interface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Change client request/response to server request/response, because the client ones are for when node is acting as a client (making outgoing requests), whereas here it’s acting as a server. This change is needed to work with express. 2. Change the `next` argument, because next (in express) is a function called with 0 or 1 arguments, where that argument can be an any (for the error). Next is decidedly *not* a function with the MiddlewareFunction signature. 3. Import express with a capital E, for consistency with Http, since we’re using it for its namespace. --- twilio/twilio.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 8bd6911113..a13352b213 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -7,7 +7,7 @@ /// /// -import * as express from 'express'; +import * as Express from 'express'; import * as Http from 'http'; import q = require('q'); @@ -444,13 +444,13 @@ declare namespace twilio { } // For interop with node middleware chains - export interface MiddlewareFunction { (request: Http.ClientRequest, response: Http.ClientResponse, next: MiddlewareFunction): void; } + export interface MiddlewareFunction { (request: Http.ServerRequest, response: Http.ServerResponse, next: Express.NextFunction): void; } export function webhook(authToken: string, options?: webhookOptions): MiddlewareFunction; export function webhook(options?: webhookOptions): MiddlewareFunction; export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; - export function validateExpressRequest(request: express.Request, authToken: string, options?: WebhookExpressOptions): boolean; + export function validateExpressRequest(request: Express.Request, authToken: string, options?: WebhookExpressOptions): boolean; /// resources/Accounts.js export interface OutgoingCallerIdInstance extends InstanceResource { From ae92456e05814ba09d5d8d6770d17048dbb960e4 Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Tue, 13 Sep 2016 16:47:05 -0400 Subject: [PATCH 156/212] In TwimlCallback, Node shouldn't be optional Because the callback is always called with the Node. This change is based on the advice here: https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/decla ration%20files/Do's%20and%20Don'ts.md#optional-parameters-in-callbacks --- twilio/twilio.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index a13352b213..84c0d02394 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -381,7 +381,7 @@ declare namespace twilio { export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } - export interface TwimlCallback { (node?: Node): void; } + export interface TwimlCallback { (node: Node): void; } export class Node implements NodeOptions { name: string; From 3d032bd51037f5edfd008c1cfb3acf96a11138a1 Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Tue, 13 Sep 2016 17:02:08 -0400 Subject: [PATCH 157/212] Split up TwimlMethod signature By splitting up the union into an overload, we get much more useful typing than just (any, any) --- twilio/twilio.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 84c0d02394..8d5c44984b 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -379,7 +379,10 @@ declare namespace twilio { legalNodes: Array; } - export interface TwimlMethod { (arg1: any | string | TwimlCallback, arg2?: any | string | TwimlCallback): Node } + export interface TwimlMethod { + (arg1: TwimlCallback | string, arg2?: any): Node + (arg1: any, arg2?: TwimlCallback | string): Node + } export interface TwimlCallback { (node: Node): void; } From 92b719193832e5f4bcfdb529187176de675860ff Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 19:00:58 -0400 Subject: [PATCH 158/212] Allow TwimlMethods with no arguments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit E.g. hangup() doesn’t take any arguments. --- twilio/twilio-tests.ts | 2 ++ twilio/twilio.d.ts | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index d7f2c60993..1fb9afa0a4 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -212,6 +212,8 @@ resp.say('Your conference call is starting.', }); }); +resp.hangup(); + /// Capabilities var capability = new twilio.Capability(str, str); capability.allowClientIncoming('jenny'); diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index 8d5c44984b..c0f16211f5 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -380,8 +380,9 @@ declare namespace twilio { } export interface TwimlMethod { - (arg1: TwimlCallback | string, arg2?: any): Node - (arg1: any, arg2?: TwimlCallback | string): Node + (): Node; + (arg1: TwimlCallback | string, arg2?: any): Node; + (arg1: any, arg2?: TwimlCallback | string): Node; } export interface TwimlCallback { (node: Node): void; } From 4cf3256fe813b0121cc69f8b794ee6bb68905971 Mon Sep 17 00:00:00 2001 From: Craig Nishina Date: Wed, 14 Sep 2016 16:12:30 -0700 Subject: [PATCH 159/212] types(selenium): update selenium-webdriver to 2.53.1 - update from selenium-webdriver 2.44 to 2.53.1 - remove dependencies for selenium-webdriver 2.44: - protractor - protractor-helpers - protractor-http-mock --- protractor-helpers/index.d.ts | 111 - .../protractor-helpers-tests.ts | 116 - protractor-helpers/tsconfig.json | 19 - protractor-http-mock/index.d.ts | 284 -- .../protractor-http-mock-tests.ts | 302 -- protractor-http-mock/tsconfig.json | 19 - protractor/angular-protractor-tests.ts | 483 -- protractor/index.d.ts | 1849 -------- protractor/tsconfig.json | 19 - selenium-webdriver/index.d.ts | 4116 +++++++++++------ .../selenium-webdriver-tests.ts | 249 +- 11 files changed, 2726 insertions(+), 4841 deletions(-) delete mode 100644 protractor-helpers/index.d.ts delete mode 100644 protractor-helpers/protractor-helpers-tests.ts delete mode 100644 protractor-helpers/tsconfig.json delete mode 100644 protractor-http-mock/index.d.ts delete mode 100644 protractor-http-mock/protractor-http-mock-tests.ts delete mode 100644 protractor-http-mock/tsconfig.json delete mode 100644 protractor/angular-protractor-tests.ts delete mode 100644 protractor/index.d.ts delete mode 100644 protractor/tsconfig.json diff --git a/protractor-helpers/index.d.ts b/protractor-helpers/index.d.ts deleted file mode 100644 index 00df7cff98..0000000000 --- a/protractor-helpers/index.d.ts +++ /dev/null @@ -1,111 +0,0 @@ -// Type definitions for protractor-helpers v1.0.0 -// Project: https://github.com/wix/protractor-helpers -// Definitions by: John Cant -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - - -/// -/// - -// ElementArrayFinder - -declare namespace protractor { - interface ElementArrayFinder { - getByText(text: string) : protractor.ElementFinder; - $$data(hook: string) : protractor.ElementArrayFinder; - } - - interface ElementFinder { - $data(hook: string) : protractor.ElementFinder; - } -} - -// Globals - -declare function $data(hook: string) : protractor.ElementFinder; -declare function $$data(hook: string) : protractor.ElementArrayFinder; - - -// Locators - -// TODO - find out about result of querySelector and querySelector all. -// Are they Locator s? -declare namespace protractor { - interface IProtractorLocatorStrategy { - dataHook(hook: string, optParentElement?: protractor.ElementFinder, optRootSelector?: string) : webdriver.Locator; - dataHookAll(hook: string, optParentElement?: protractor.ElementFinder, optRootSelector?: string) : webdriver.Locator; - } -} - -// Matchers -// TODO - Typescript doesn't really help much here -// we don't know what type is being tested. -// Fixing this would require modifying the -// jasmine d.ts. - -declare namespace jasmine { - interface Matchers { - toBePresent() : boolean; - toBeDisplayed() : boolean; - toHaveCountOf(expectedCount : number) : boolean; - toHaveText(expectedText : string) : boolean; - toMatchRegex(regex : RegExp) : boolean; - toMatchMoney(expectedValue : number, currencySymbol? : string) : boolean; - toMatchMoneyWithFraction(expectedValue : number, currencySymbol?: string) : boolean; - toHaveValue(actual: string | number) : boolean; - toHaveClass(className : string) : boolean; - toHaveUrl(url : string) : boolean; - toBeDisabled() : boolean; - toBeChecked() : boolean; - toBeValid() : boolean; - toBeInvalid() : boolean; - toBeInvalidRequired() : boolean; - // Copied definitions from angular-translate. - toMatchTranslated(translationId : string, interpolateParams? : any) : boolean; - toMatchTranslated(translationId : string[], interpolateParams? : any) : boolean; - } -} - - -declare module "protractor-helpers" { - - function not(arg: webdriver.promise.IThenable) : webdriver.promise.IThenable; - - // Copied definitions from angular-translate. - function translate(translationId: string, interpolateParams?: any): webdriver.promise.IThenable; - function translate(translationId: string[], interpolateParams?: any): webdriver.promise.IThenable<{ [key: string]: string }>; - - function safeGet(url: string) : void; - - function maximizeWindow(width?: number, height?: number) : void; // TODO - function resetPosition() : void; - function moveToElement(hook: string) : void; - function displayHover(element: protractor.ElementFinder) : void; - - function waitForElement(element: protractor.ElementFinder, timeout?: number) : void; - function waitForElementToDisappear(element: protractor.ElementFinder, timeout?: number) : void; - - function selectOptionByText(select: protractor.ElementFinder, text: string) : void; - function selectOptionByIndex(select: protractor.ElementFinder, index: number) : void; - - function selectOption(option: protractor.ElementFinder) : void - - function isFirefox() : boolean; - function isIE() : boolean; - - function createMessage(actual : string, message : string, isNot : any) : string; // isNot : boolean too inflexible - function createMessage(actual : protractor.ElementFinder, message : string, isNot : any) : string; // isNot : boolean too inflexible - function createMessage(actual : protractor.ElementArrayFinder, message : string, isNot : any) : string; // isNot : boolean too inflexible - - function clearAndSetValue(input : protractor.ElementFinder, value : string) : void; // TODO - sendKeys(value) - - function hasClass(element: protractor.ElementFinder, className: string) : webdriver.promise.IThenable; - function hasValue(element: protractor.ElementFinder, expectedValue: string) : webdriver.promise.IThenable; - function hasValue(element: protractor.ElementFinder, expectedValue: number) : webdriver.promise.IThenable; - function hasLink(element: protractor.ElementFinder, url: string) : webdriver.promise.IThenable; - function isDisabled(element: protractor.ElementFinder) : webdriver.promise.IThenable; - function isChecked(element: protractor.ElementFinder) : webdriver.promise.IThenable; - function getFilteredConsoleErrors() : webdriver.promise.IThenable; // TODO - discuss handling in IE - -} - diff --git a/protractor-helpers/protractor-helpers-tests.ts b/protractor-helpers/protractor-helpers-tests.ts deleted file mode 100644 index 269390080e..0000000000 --- a/protractor-helpers/protractor-helpers-tests.ts +++ /dev/null @@ -1,116 +0,0 @@ - - -import helpers = require('protractor-helpers'); - -declare var $$: any, $: any, by: any, element: any; // ?? - -function testElementArrayFinder() { - - var single1 : protractor.ElementFinder = $$('.foo').getByText('Hello'); - var multiple : protractor.ElementArrayFinder = $$('.foo').$$data('Hello'); - -} - -function testElementFinder () { - var single2 : protractor.ElementFinder = $('.foo').$data('Hello'); -} - -function testGlobals() { - - var single : protractor.ElementFinder = $data('Hello'); - var multiple : protractor.ElementArrayFinder = $$data('Hello'); - -} - -function testHelpers() { - - var q0 : webdriver.promise.IThenable = helpers.not($('.foo').isDisplayed()); - // TODO - Check impl - var q1 : webdriver.promise.IThenable<{[key: string]:string}> = helpers.translate(["foo", "bar"]); - var q2 : webdriver.promise.IThenable<{[key: string]:string}> = helpers.translate(["foo", "bar"], {name: 'foo'}); - var q3 : webdriver.promise.IThenable = helpers.translate("foo"); - var q4 : webdriver.promise.IThenable = helpers.translate("foo", {name: 'foo'}); - - helpers.safeGet('https://foo/'); - - helpers.maximizeWindow(500, 500); - helpers.maximizeWindow(500); - helpers.maximizeWindow(undefined, 500); - helpers.maximizeWindow(); - - helpers.resetPosition(); - helpers.moveToElement(".foo"); // TODO - ? - - helpers.displayHover($('.foo')); - - helpers.waitForElement($('.foo')); - helpers.waitForElement($('.foo'), 1000); - helpers.waitForElementToDisappear($('.foo'));; - helpers.waitForElementToDisappear($('.foo'), 1000); - - helpers.selectOptionByText($('select'), "GB"); - helpers.selectOptionByIndex($('select'), 1); - - helpers.selectOption($$('select option').first()); - - var ff : boolean = helpers.isFirefox(); - var ie : boolean = helpers.isIE(); - - var msg : string = helpers.createMessage("actual", "message", true); - var msg : string = helpers.createMessage($('.foo'), "message", true); - var msg : string = helpers.createMessage($$('.foo'), "message", true); - - helpers.clearAndSetValue($('input'), 'Foo'); - - var hc : webdriver.promise.IThenable = helpers.hasClass($('.foo'), 'foo'); - - var hv : webdriver.promise.IThenable = helpers.hasValue($('input[type=text]'), 'foo'); - var hv1 : webdriver.promise.IThenable = helpers.hasValue($('input[type=numeric]'), 12); - var hl : webdriver.promise.IThenable = helpers.hasLink($('div'), 'http://foo.com'); - var disabled : webdriver.promise.IThenable = helpers.isDisabled($('foo')); - var checked : webdriver.promise.IThenable = helpers.isChecked($('foo')); - - var q5 : webdriver.promise.IThenable = helpers.getFilteredConsoleErrors(); - -} - -function testLocators() { - - element(by.dataHook("foo")); - element(by.dataHook("foo", $('.parentfoo'))); - element(by.dataHook("foo", undefined , ".foo")); - element(by.dataHook("foo", $('.parentfoo'), ".foo")); // TODO - This might not make much sense, but can technically be used in working code. Opinions welcome - - element.all(by.dataHook("foo")); - element.all(by.dataHook("foo", $('parentfoo'))); - element.all(by.dataHook("foo", undefined , ".foo")); - element.all(by.dataHook("foo", $('parentfoo'), ".foo")); // TODO - This might not make much sense, but can technically be used in working code. Opinions welcome - -} - -function testMatchers() { - - var expectResult : boolean; - expectResult = expect($('.foo')).toBePresent(); - expectResult = expect($('.foo')).toBeDisplayed(); - expectResult = expect($$('.foo').count()).toHaveCountOf(1); - expectResult = expect($('.foo')).toHaveText("bla"); - expectResult = expect($('.foo')).toMatchRegex(/bla/); - expectResult = expect($('.foo').getText()).toMatchMoney(123, "£"); - expectResult = expect($('.foo').getText()).toMatchMoneyWithFraction(123.45, "£"); - expectResult = expect($('input')).toHaveValue(12); - expectResult = expect($('input')).toHaveValue("bla"); - expectResult = expect($('.foo')).toHaveClass("foo"); - expectResult = expect($('.foo')).toHaveUrl('https://foo.com'); - expectResult = expect($('.foo')).toBeDisabled(); - expectResult = expect($('.foo')).toBeChecked(); - expectResult = expect($('.foo')).toBeValid(); - expectResult = expect($('.foo')).toBeInvalid(); - expectResult = expect($('.foo')).toBeInvalidRequired(); - expectResult = expect($('.foo')).toMatchTranslated("foo"); - expectResult = expect($('.foo')).toMatchTranslated("foo", {foo: "bar"}); - expectResult = expect($('.foo')).toMatchTranslated(["foo"]); - expectResult = expect($('.foo')).toMatchTranslated(["foo", "bla"], {foo: "bar"}); - -} - diff --git a/protractor-helpers/tsconfig.json b/protractor-helpers/tsconfig.json deleted file mode 100644 index e180a4d570..0000000000 --- a/protractor-helpers/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "protractor-helpers-tests.ts" - ] -} \ No newline at end of file diff --git a/protractor-http-mock/index.d.ts b/protractor-http-mock/index.d.ts deleted file mode 100644 index 5f9dbcd79a..0000000000 --- a/protractor-http-mock/index.d.ts +++ /dev/null @@ -1,284 +0,0 @@ -// Type definitions for protractor-http-mock -// Project: https://github.com/atecarlos/protractor-http-mock -// Definitions by: Crevil -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace mock { - interface ProtractorHttpMock { - /** - * Instantiate mock module. This must be done before the browser connects. - * - * @param mocks An array of mock modules to load into the application. - * @param plugins An array of Plugin objects. - * @param skipDefaults Set true to skip loading of default mocks. - */ - (mocks?: Array>, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; - - /** - * Instantiate mock module. This must be done before the browser connects. - * - * @param mocks An array of mock modules to load into the application. - * @param plugins An array of NPM modules as strings. - * @param skipDefaults Set true to skip loading of default mocks. - */ - (mocks?: Array>, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; - - /** - * Instantiate mock modules from files. This must be done before the browser connects. - * - * @param mocks An array of mock module names relative to the rootDirectory configuration. - * @param plugins An array of Plugin objects. - * @param skipDefaults Set true to skip loading of default mocks. - */ - (mocks: Array, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; - - /** - * Instantiate mock modules from files. This must be done before the browser connects. - * - * @param mocks An array of mock module names relative to the rootDirectory configuration. - * @param plugins An array of NPM modules as strings. - * @param skipDefaults Set true to skip loading of default mocks. - */ - (mocks: Array, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; - - /** - * Clean up. - * Typically done in the afterEach call to ensure the teardown - * is executed regardless of what happens in the test execution. - */ - teardown(): void; - - /** - * Returns a promise that will be resolved with an array of - * all matched HTTP requests. - */ - requestsMade(): webdriver.promise.Promise>; - - /** - * Returns a promise that will be resolved with a true boolean - * when all matched HTTP requests are cleared. - */ - clearRequests(): webdriver.promise.Promise; - - /** - * Module configuration to setup - */ - config: { - /** - * Mocks directory where mock files are located. - * Default: process.cwd() - */ - rootDirectory?: string; - - /** - * Path to protractor configuration file. - * Default: protractor.conf - */ - protractorConfig?: string; - }; - - /** - * Add mocks during test execution. - * Returns a promise that will be resolved with a true boolean - * when mocks are added. - * - * @param mocks An array of mock modules to load into the application. - */ - add(mocks: Array>): webdriver.promise.Promise; - - /** - * Remove mocks during test execution. - * Returns a promise that will be resolved with a true boolean - * when the supplied mocks are removed. - * - * @param mocks An array of mock modules to remove from the application. - */ - remove(mocks: Array>): webdriver.promise.Promise; - } - - /** - * Matched request. - */ - interface ReceivedRequest { - url: string; - method: requests.Method; - } - - /** - * Plugin for custom matching logic. - */ - interface Plugin { - /** - * Match function. - * Return a truthy value to indicate successfull match. - * - * @param mockRequest The mock to compare request with. - * @param requestConfig The request object to compare mock with. - */ - match(mockRequest: requests.AllRequests, requestConfig: requests.AllRequests): boolean; - } - - /** - * Plugin for custom matching logic. - */ - interface Plugin { - /** - * Match function. - * Return a truthy value to indicate successfull match. - * - * @param mockRequest The mock to compare request with. - * @param requestConfig The request object to compare mock with. - */ - match(mockRequest: requests.AllRequests, requestConfig: requests.AllRequests): boolean; - } - - namespace requests { - /** - * Request methods type - */ - type Method = "GET" | "POST" | "DELETE" | "PUT" | "HEAD" | "PATCH" | "JSONP"; - - /** - * All available request types. - */ - type AllRequests = Get | - PostData | - Post | - Head | - Delete | - Put | - Patch | - Jsonp; - - /** - * GET request mock. - */ - interface Get { - request: { - method: Method; - path: string; - regex?: boolean; - params?: Object; - queryString?: Object; - headers?: Object; - interceptedRequest?: boolean; - interceptedAnonymousRequest?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * POST request mock with payload. - */ - interface PostData { - request: { - method: Method; - path: string; - regex?: boolean; - data: TPayload; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * POST request mock. - */ - interface Post { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * HEAD request mock. - */ - interface Head { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * HTTP Delete request mock. - */ - interface Delete { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * PUT request mock. - */ - interface Put { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * PATCH request mock. - */ - interface Patch { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - - /** - * JSONP request mock. - */ - interface Jsonp { - request: { - method: Method; - path: string; - regex?: boolean; - }; - response: { - status?: number; - data: TResponse; - }; - } - } -} - -declare var mock: mock.ProtractorHttpMock; -export = mock; diff --git a/protractor-http-mock/protractor-http-mock-tests.ts b/protractor-http-mock/protractor-http-mock-tests.ts deleted file mode 100644 index 08b97fd09f..0000000000 --- a/protractor-http-mock/protractor-http-mock-tests.ts +++ /dev/null @@ -1,302 +0,0 @@ -import mock = require("protractor-http-mock"); - -function TestConfig() { - mock.config = { - rootDirectory: "root", - protractorConfig: "protractor.conf.js" - }; -} - -function TestCtorOverloads() { - let del: mock.requests.Delete = { - request: { - path: 'path', - method: 'DELETE' - }, - response: { - status: 400, - data: 1 - } - }; - let put: mock.requests.Put = { - request: { - path: 'path', - method: 'PUT' - }, - response: { - status: 400, - data: 1 - } - }; - let plugin: mock.Plugin = { - match: (mockRequest: mock.requests.Delete, requestConfig: mock.requests.AllRequests) => { - if (requestConfig.request.method && mockRequest.request.method) { - return true; - } - - return false; - } - }; - - let noParam: mock.ProtractorHttpMock = mock(); - let emptyArray: mock.ProtractorHttpMock = mock([]); - let mockFiles: mock.ProtractorHttpMock = mock(['mock1', 'mock2']); - let mocks: mock.ProtractorHttpMock = mock([del, put]); - - let mockFilesNpmPlugins: mock.ProtractorHttpMock = mock(['mock1'], ['plugin']); - let mocksWithNpmPlugins: mock.ProtractorHttpMock = mock([del, put], ['plugin']); - - let pluginMocks: mock.ProtractorHttpMock = mock([del, put], [plugin]); - - let mockFilesNpmPluginsSkipDefaults: mock.ProtractorHttpMock = mock(['mock1'], ['plugin'], true); - let skipDefaults: mock.ProtractorHttpMock = mock([del, put], [plugin], true); -} - -function TestTeardown() { - mock.teardown(); -} - -function TestRequestsMade() { - let values: Array; - mock.requestsMade().then(v => values = v); -} - -function TestClearRequests() { - let promiseValue: boolean; - mock.clearRequests().then(value => { - promiseValue = value; - }); -} - -function TestDynamicAdd() { - let put: mock.requests.Put = { - request: { - path: "path", - method: "PUT" - }, - response: { - status: 400, - data: 1 - } - }; - let resolved: boolean; - mock.add([put]).then(r => resolved = r); -} - -function TestDyanmicRemove() { - let put: mock.requests.Put = { - request: { - path: "path", - method: "PUT" - }, - response: { - status: 400, - data: 1 - } - }; - let resolved: boolean; - mock.remove([put]).then(r => resolved = r); -} - -function TestGetRequestDefinitions() { - let getMinium: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - regex: true - }, - response: { - data: 1, - status: 500 - } - }; - - let getParams: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - regex: true, - params: { - param1: 'param1', - param2: 2 - } - }, - response: { - data: 1, - status: 500 - } - }; - - let post: mock.requests.Post = { - request: { - path: 'path', - method: 'POST', - regex: true - }, - response: { - data: 1, - status: 500 - } - }; - - let getQueryString: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - regex: true, - queryString: { - query1: 'query1', - query2: 2 - } - }, - response: { - data: 1, - status: 500 - } - }; - - let getHeaders: mock.requests.Get = { - request: { - path: 'path', - method: 'GET', - regex: true, - headers: { - head1: 'head1', - head2: 'head2' - } - }, - response: { - data: 1, - status: 500 - } - }; -} - -function TestPostRequestDefinitions() { - let post: mock.requests.Post = { - request: { - path: 'path', - method: 'POST', - regex: true - }, - response: { - data: 1, - status: 500 - } - }; - - let postData: mock.requests.PostData = { - request: { - path: 'path', - method: 'POST', - data: 'data', - regex: true - }, - response: { - data: 1, - status: 500 - } - }; -} - -function TestHeadRequestDefinitions() { - let head: mock.requests.Head = { - request: { - path: 'path', - method: 'HEAD', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestDeleteRequestDefinitions() { - let del: mock.requests.Delete = { - request: { - path: 'path', - method: 'DELETE', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestPutRequestDefinitions() { - let put: mock.requests.Put = { - request: { - path: 'path', - method: 'PUT', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestPatchRequestDefinitions() { - let patch: mock.requests.Patch = { - request: { - path: 'path', - method: 'PATCH', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestJsonpRequestDefinitions() { - let jsonp: mock.requests.Jsonp = { - request: { - path: 'path', - method: 'JSONP', - regex: true - }, - response: { - status: 500, - data: 1 - } - }; -} - -function TestRuntimeMocks() { - mock.add([{ - request: { - path: '/users', - method: 'GET', - params: { - name: 'Charlie' - } - }, - response: { - data: { - name: 'Override' - } - } - }]); - - mock.remove([{ - request: { - path: '/users', - method: 'GET', - params: { - name: 'Charlie' - } - }, - response: { - data: { - name: 'Override' - } - } - }]); -} diff --git a/protractor-http-mock/tsconfig.json b/protractor-http-mock/tsconfig.json deleted file mode 100644 index 8d6b5822e4..0000000000 --- a/protractor-http-mock/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "protractor-http-mock-tests.ts" - ] -} \ No newline at end of file diff --git a/protractor/angular-protractor-tests.ts b/protractor/angular-protractor-tests.ts deleted file mode 100644 index 0a7ae85357..0000000000 --- a/protractor/angular-protractor-tests.ts +++ /dev/null @@ -1,483 +0,0 @@ - - -function TestWebDriverExports() { - var button: number = protractor.Button.LEFT; - - var key: string = protractor.Key.ADD; - var chord: string = protractor.Key.chord(protractor.Key.NUMPAD0, protractor.Key.NUMPAD1); - - var driver: protractor.WebDriver = new protractor.Builder(). - withCapabilities(protractor.Capabilities.chrome()). - build(); - var baseDriver: webdriver.WebDriver = driver; - - var action: protractor.ActionSequence = new protractor.ActionSequence(driver); - var baseAction: webdriver.ActionSequence = action; - - var browser: string = protractor.Browser.ANDROID; - - var builder: protractor.Builder = new protractor.Builder(); - var baseBuilder: webdriver.Builder = builder; - - var capability: string = protractor.Capability.BROWSER_NAME; - - var capabilities: protractor.Capabilities = protractor.Capabilities.chrome(); - var baseCapabilities: webdriver.Capabilities = capabilities; - - var commandName: string = protractor.CommandName.CLICK_ELEMENT; - - var command: protractor.Command = new protractor.Command(protractor.CommandName.CLICK); - var baseCommand: webdriver.Command = command; - - var eventEmitter: protractor.EventEmitter = new protractor.EventEmitter(); - var baseEventEmitter: webdriver.EventEmitter = eventEmitter; - - var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); - var baseWebElement: webdriver.WebElement = webElement; - - var locator: webdriver.Locator = by.id('abc'); - - var session: protractor.Session = new protractor.Session('ABC', webdriver.Capabilities.android()); - var baseSession: webdriver.Session = session; - - locator = protractor.By.name('name'); - - var driver: protractor.WebDriver = new protractor.WebDriver(session, {}); - driver = new protractor.WebDriver(session, {}, new webdriver.promise.ControlFlow()); - var baseDriver: webdriver.WebDriver = driver; - - var webElement: protractor.WebElement = new protractor.WebElement(driver, { ELEMENT: 'abc' }); - var baseWebElement: webdriver.WebElement = webElement; - - var webElementPromise: protractor.WebElementPromise = new protractor.WebElementPromise(driver, { ELEMENT: 'abc' }); - var baseWebElementPromise: webdriver.WebElementPromise = webElementPromise; -} - -function TestWebDriverErrorModule() { - var errorCode: number = protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE; - var error: protractor.error.Error = new protractor.error.Error(protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE); - var baseError: webdriver.error.Error = error; -} - -function TestWebDriverLoggingModule() { - var levelName: string = protractor.logging.Level.ALL.name; - var loggingType: string = protractor.logging.Type.CLIENT; - - var level: webdriver.logging.ILevel = protractor.logging.Level.ALL; - - var entry: protractor.logging.Entry = new protractor.logging.Entry(protractor.logging.Level.ALL, 'Message'); - var baseEntry: webdriver.logging.Entry = entry; - - level = protractor.logging.getLevel('DEBUG'); - - var prefs: protractor.logging.Preferences = new protractor.logging.Preferences(); -} - -function TestWebDriverPromiseModule() { - var cancelError: protractor.promise.CancellationError = new protractor.promise.CancellationError(); - cancelError = new protractor.promise.CancellationError('message'); - var baseCancelError: webdriver.promise.CancellationError = cancelError; - - var thenable: protractor.promise.Thenable = new protractor.promise.Thenable(); - var baseThenable: webdriver.promise.Thenable = thenable; - - var promise: protractor.promise.Promise = new protractor.promise.Promise(); - var basePromise: webdriver.promise.Promise = promise; - - var deferred: protractor.promise.Deferred = new protractor.promise.Deferred(); - var baseDeferred: webdriver.promise.Deferred = deferred; - - var flow: protractor.promise.ControlFlow = new protractor.promise.ControlFlow(); - var baseFlow: webdriver.promise.ControlFlow = flow; - - var arrayPromise: protractor.promise.Promise = protractor.promise.all([new protractor.promise.Promise(), new protractor.promise.Promise()]); - - protractor.promise.asap(promise, function (value: any) { return true; }); - protractor.promise.asap(promise, function (value: any) { }, function (err: any) { return 'ABC'; }); - - promise = protractor.promise.checkedNodeCall(function (err: any, value: any) { return 123; }); - - promise = protractor.promise.consume(function () { - return 5; - }); - promise = protractor.promise.consume(function () { - return 5; - }, this); - promise = protractor.promise.consume(function () { - return 5; - }, this, 1, 2, 3); - - flow = protractor.promise.controlFlow(); - - promise = protractor.promise.createFlow(function (newFlow: webdriver.promise.ControlFlow) { }); - - deferred = protractor.promise.defer(); - - promise = protractor.promise.delayed(123); - - var numbersPromise: protractor.promise.Promise = protractor.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { - return true; - }); - numbersPromise = protractor.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { - return true; - }, this); - numbersPromise = protractor.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { - return true; - }); - numbersPromise = protractor.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { - return true; - }, this); - - numbersPromise = protractor.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { - return true; - }); - numbersPromise = protractor.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { - return true; - }, this); - numbersPromise = protractor.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { - return true; - }); - numbersPromise = protractor.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { - return true; - }, this); - - promise = protractor.promise.fulfilled(); - promise = protractor.promise.fulfilled({ a: 123 }); - - promise = protractor.promise.fullyResolved({ a: 123 }); - - var bool: boolean = protractor.promise.isGenerator(function () { }); - var bool: boolean = protractor.promise.isPromise('ABC'); - - promise = protractor.promise.rejected({ a: 123 }); - - protractor.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); - - promise = protractor.promise.when(promise, function (value: any) { return 123; }, function (err: Error) { return 123; }); -} - -function TestWebDriverStacktraceModule() { - var bool: boolean = protractor.stacktrace.BROWSER_SUPPORTED; - - var frame: protractor.stacktrace.Frame = new protractor.stacktrace.Frame(); - var baseFrame: webdriver.stacktrace.Frame = frame; - - var snapshot: protractor.stacktrace.Snapshot = new protractor.stacktrace.Snapshot(); - var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; - - var err: Error = protractor.stacktrace.format(new Error("Error")); - var frames: protractor.stacktrace.Frame[] = protractor.stacktrace.get(); -} - -function TestWebDriverUntilModule() { - var conditionB: protractor.until.Condition = new protractor.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); - var conditionBBase: webdriver.until.Condition = conditionB; - var conditionWebElement: protractor.until.Condition; - var conditionWebElements: protractor.until.Condition; - - conditionB = protractor.until.ableToSwitchToFrame(5); - var conditionAlert: protractor.until.Condition = protractor.until.alertIsPresent(); - var el: protractor.ElementFinder = element(by.id('id')); - conditionB = protractor.until.elementIsDisabled(el); - conditionB = protractor.until.elementIsEnabled(el); - conditionB = protractor.until.elementIsNotSelected(el); - conditionB = protractor.until.elementIsNotVisible(el); - conditionB = protractor.until.elementIsSelected(el); - conditionB = protractor.until.elementIsVisible(el); - conditionB = protractor.until.elementTextContains(el, 'text'); - conditionB = protractor.until.elementTextIs(el, 'text'); - conditionB = protractor.until.elementTextMatches(el, /text/); - conditionB = protractor.until.stalenessOf(el); - conditionB = protractor.until.titleContains('text'); - conditionB = protractor.until.titleIs('text'); - conditionB = protractor.until.titleMatches(/text/); - - conditionWebElement = protractor.until.elementLocated(by.id('id')); - conditionWebElements = protractor.until.elementsLocated(by.className('class')); -} - -function TestWebDriverExpectedConditionsModule() { - var conditionB: protractor.until.Condition; - var el: protractor.ElementFinder = element(by.id('id')); - - conditionB = protractor.ExpectedConditions.alertIsPresent(); - conditionB = protractor.ExpectedConditions.elementToBeClickable(el); - conditionB = protractor.ExpectedConditions.textToBePresentInElement(el, 'text'); - conditionB = protractor.ExpectedConditions.textToBePresentInElementValue(el, 'text'); - conditionB = protractor.ExpectedConditions.titleContains('text'); - conditionB = protractor.ExpectedConditions.titleIs('text'); - conditionB = protractor.ExpectedConditions.presenceOf(el); - conditionB = protractor.ExpectedConditions.stalenessOf(el); - conditionB = protractor.ExpectedConditions.visibilityOf(el); - conditionB = protractor.ExpectedConditions.invisibilityOf(el); - conditionB = protractor.ExpectedConditions.elementToBeSelected(el); - - conditionB = protractor.ExpectedConditions.not(protractor.ExpectedConditions.alertIsPresent()); - conditionB = protractor.ExpectedConditions.and(protractor.ExpectedConditions.alertIsPresent(), protractor.ExpectedConditions.elementToBeClickable(el)); - conditionB = protractor.ExpectedConditions.or(protractor.ExpectedConditions.alertIsPresent(), protractor.ExpectedConditions.elementToBeClickable(el)); -} - -function TestProtractor() { - var ptor: protractor.Protractor; - var driver: webdriver.WebDriver = new webdriver.Builder(). - withCapabilities(webdriver.Capabilities.chrome()). - build(); - - ptor = protractor.wrapDriver(driver); - ptor = protractor.wrapDriver(driver, 'baseUrl'); - ptor = protractor.wrapDriver(driver, 'baseUrl', 'rootElement'); - - ptor = browser; - - var actions: protractor.ActionSequence = ptor.actions(); - - var promise: protractor.promise.Promise = ptor.call(function () { }); - var promise: protractor.promise.Promise = ptor.call(function () { }, this); - var promise: protractor.promise.Promise = ptor.call(function (a: number, b: number, c:number) { }, this, 1, 2,3); - - promise = ptor.executeAsyncScript('SomeScript'); - promise = ptor.executeAsyncScript('SomeScript', 1, 2, 3); - promise = ptor.executeAsyncScript(function () { }); - promise = ptor.executeAsyncScript(function (a: number, b: number, c: number) { }, 1, 2, 3); - - promise = ptor.executeScript('SomeScript'); - promise = ptor.executeScript('SomeScript', 1, 2, 3); - promise = ptor.executeScript(function () { }); - promise = ptor.executeScript(function (a: number, b: number, c: number) { }, 1, 2, 3); - - ptor = browser.forkNewDriverInstance(); - ptor = browser.forkNewDriverInstance(true); - ptor = browser.forkNewDriverInstance(true, false); - - driver = ptor.driver; - var baseUrl: string = ptor.baseUrl; - var rootEl: string = ptor.rootEl; - var ignoreSynchronization: boolean = ptor.ignoreSynchronization; - var params: any = ptor.params; - ptor.resetUrl = "url"; - - ptor.debugger(); - ptor.close(); - var controlFlow: protractor.promise.ControlFlow = ptor.controlFlow(); - - var webElement: protractor.WebElement = ptor.findElement(by.css('.class')); - ptor.findElements(by.css('.class')).then(function (elements: webdriver.WebElement[]) { }); - ptor.isElementPresent(by.css('.class')).then(function (present: boolean) { }); - ptor.isElementPresent(webElement).then(function (present: boolean) { }); - - ptor.clearMockModules(); - ptor.addMockModule('name', 'script'); - ptor.addMockModule('name', function() {}); - ptor.removeMockModule('name'); - ptor.waitForAngular(); - - var elementFinder: protractor.ElementFinder; - var elementArrayFinder: protractor.ElementArrayFinder; - - elementFinder = ptor.element(by.id('ABC')); - elementFinder = ptor.$('.class'); - - elementArrayFinder = ptor.$$('.class'); - - var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); - ptor.setLocation('webaddress.com'); - - var voidPromise: webdriver.promise.Promise = ptor.get('webaddress.com'); - voidPromise = ptor.get('webdaddress.com', 45); - voidPromise = ptor.quit(); - voidPromise = ptor.sleep(5000); - - ptor.refresh(); - ptor.refresh(45); - var navigation: webdriver.WebDriverNavigation = ptor.navigate(); - ptor.pause(); - ptor.pause(8080); - - ptor.getAllWindowHandles().then(function (handles: string[]) { }); - - var capabilities: protractor.promise.Promise = ptor.getCapabilities(); - - var stringPromise: webdriver.promise.Promise; - stringPromise = ptor.getCurrentUrl(); - stringPromise = ptor.getPageSource(); - stringPromise = ptor.getTitle(); - stringPromise = ptor.getWindowHandle(); - stringPromise = ptor.takeScreenshot(); - - ptor.getPageTimeout = 5000; - - var session: protractor.promise.Promise = ptor.getSession(); - - var options: webdriver.WebDriverOptions = ptor.manage(); - - promise = ptor.schedule(new protractor.Command(protractor.CommandName.ACCEPT_ALERT), 'asdf'); - - var targetLocator: webdriver.WebDriverTargetLocator = ptor.switchTo(); - - ptor.wait(protractor.until.elementLocated(by.id('id')), 5000).then(function (el: webdriver.IWebElement) { });; - ptor.wait(protractor.until.elementLocated(by.id('id')), 5000, 'message').then(function (el: webdriver.IWebElement) { });; -} - -function TestElement() { - var elementFinder: protractor.ElementFinder = element(by.id('id')); - var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.className('class')); -} - -function TestElementFinder() { - var elementFinder: protractor.ElementFinder = element(by.id('id')); - var voidPromise: webdriver.promise.Promise; - var stringPromise: webdriver.promise.Promise; - var booleanPromise: webdriver.promise.Promise; - - elementFinder.getId().then(function (id: webdriver.IWebElementId) { }); - voidPromise = elementFinder.click(); - elementFinder = elementFinder.allowAnimations('string'); - voidPromise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); - stringPromise = elementFinder.getTagName(); - stringPromise = elementFinder.getCssValue('display'); - stringPromise = elementFinder.getAttribute('atribute'); - stringPromise = elementFinder.getText(); - elementFinder.getSize().then(function (size: webdriver.ISize) { }); - elementFinder.getLocation().then(function (location: webdriver.ILocation) { }); - booleanPromise = elementFinder.isEnabled(); - booleanPromise = elementFinder.isSelected(); - voidPromise = elementFinder.submit(); - voidPromise = elementFinder.clear(); - booleanPromise = elementFinder.isDisplayed(); - stringPromise = elementFinder.getOuterHtml(); - stringPromise = elementFinder.getInnerHtml(); - booleanPromise = elementFinder.isElementPresent(by.id('id')); - elementFinder = elementFinder.$('.class'); - var finders: protractor.ElementArrayFinder = elementFinder.$$('.class'); - elementFinder = elementFinder.evaluate('expression'); - booleanPromise = elementFinder.isPresent(); - - var webElement: webdriver.WebElement = elementFinder.getWebElement(); - finders = elementFinder.all(by.className('class')); - elementFinder = elementFinder.allowAnimations('abc'); - elementFinder = elementFinder.clone(); - elementFinder = elementFinder.element(by.id('id')); - - var b: boolean = elementFinder.isPending(); - var locator: webdriver.Locator = elementFinder.locator(); -} - -function TestElementArrayFinder() { - var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.id('id')); - - var voidPromise: webdriver.promise.Promise; - var stringPromise: webdriver.promise.Promise; - var booleanPromise: webdriver.promise.Promise; - - elementArrayFinder.getId().then(function (id: webdriver.IWebElementId[]) { }); - voidPromise = elementArrayFinder.click(); - elementArrayFinder = elementArrayFinder.allowAnimations(true); - voidPromise = elementArrayFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); - stringPromise = elementArrayFinder.getTagName(); - stringPromise = elementArrayFinder.getCssValue('display'); - stringPromise = elementArrayFinder.getAttribute('atribute'); - stringPromise = elementArrayFinder.getText(); - elementArrayFinder.getSize().then(function (size: webdriver.ISize[]) { }); - elementArrayFinder.getLocation().then(function (location: webdriver.ILocation[]) { }); - booleanPromise = elementArrayFinder.isEnabled(); - booleanPromise = elementArrayFinder.isSelected(); - voidPromise = elementArrayFinder.submit(); - voidPromise = elementArrayFinder.clear(); - booleanPromise = elementArrayFinder.isDisplayed(); - stringPromise = elementArrayFinder.getOuterHtml(); - stringPromise = elementArrayFinder.getInnerHtml(); - var finders: protractor.ElementArrayFinder = elementArrayFinder.$$('.class'); - elementArrayFinder = elementArrayFinder.evaluate('expression'); - - finders = elementArrayFinder.all(by.className('class')); - elementArrayFinder = elementArrayFinder.clone(); - - var b: boolean = elementArrayFinder.isPending(); - var locator: webdriver.Locator = elementArrayFinder.locator(); - - var findersArrayPromise: protractor.promise.Promise = elementArrayFinder.asElementFinders_(); - - var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements(); - var elementFinder: protractor.ElementFinder = elementArrayFinder.get(42); - elementFinder = elementArrayFinder.first(); - elementFinder = elementArrayFinder.last(); - elementFinder = elementArrayFinder.toElementFinder_() - var numberPromise: protractor.promise.Promise = elementArrayFinder.count(); - elementArrayFinder.each(function(element: protractor.ElementFinder){ - // nothing - }); - - stringPromise = elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){ - return 'abc'; - }); - - stringPromise = elementArrayFinder.map(function(element: protractor.ElementFinder, index: number): string { - return 'abc'; - }); - - stringPromise = elementArrayFinder.map>(function(element: protractor.ElementFinder, index: number): webdriver.promise.Promise { - return element.getText(); - }); - - elementArrayFinder = elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){ - return element.getText().then((text: string) => { - return text === "foo"; - }); - }); - elementArrayFinder.reduce(function (accumulator: string, element: protractor.ElementFinder) { - return element.getText().then((text: string) => { - return accumulator + ',' + text; - }); - }, '').then(function (result: string) { }); - elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder, index: number, array: protractor.ElementFinder[]){ - return element.getText().then((text: string) => { - return accumulator + ',' + text; - }); - }, '').then(function (result: string) { }); - elementArrayFinder.then(function(underlyingElementFinders: protractor.ElementFinder[]){ - //nothing - }); -} - -// This function tests the locator strategies. -function TestLocatorStrategies() { - var ptor: protractor.Protractor = browser; - var webElement: webdriver.WebElement; - - protractor.By.addLocator('customLocator', 'script'); - protractor.By.addLocator('customLocator2', function(){ - // nothing - }); - - // Angular specific locators. - webElement = ptor.findElement(protractor.By.binding('binding')); - webElement = ptor.findElement(protractor.By.exactBinding('exactBinding')); - webElement = ptor.findElement(protractor.By.model('model')); - webElement = ptor.findElement(protractor.By.repeater('repeater')); - webElement = ptor.findElement(protractor.By.repeater('repeater').column(0)); - webElement = ptor.findElement(protractor.By.repeater('repeater').row(0)); - webElement = ptor.findElement(protractor.By.repeater('repeater').row(0).column(0)); - webElement = ptor.findElement(protractor.By.buttonText('buttonText')); - webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); - webElement = ptor.findElement(protractor.By.cssContainingText('cssSelector', 'search text')); - webElement = ptor.findElement(protractor.By.options('options')); - // One standard locator for good measure. - webElement = ptor.findElement(protractor.By.id('id')); - - var el: protractor.ElementFinder; - - // Angular specific locators. - el = element(by.binding('binding')); - el = element(by.exactBinding('exactBinding')); - el = element(by.model('model')); - el = element(by.repeater('repeater')); - el = element(by.repeater('repeater').column(0)); - el = element(by.repeater('repeater').row(0)); - el = element(by.repeater('repeater').row(0).column(0)); - el = element(by.buttonText('buttonText')); - el = element(by.partialButtonText('partialButtonText')); - el = element(by.cssContainingText('cssSelector', 'search text')); - el = element(by.options('options')); - // One standard locator for good measure. - el = element(by.id('id')); -} diff --git a/protractor/index.d.ts b/protractor/index.d.ts deleted file mode 100644 index 86f00898a1..0000000000 --- a/protractor/index.d.ts +++ /dev/null @@ -1,1849 +0,0 @@ -// Type definitions for Angular Protractor 1.5.0 -// Project: https://github.com/angular/protractor -// Definitions by: Bill Armstrong -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare namespace protractor { - //region Wrapped webdriver Items - - class ActionSequence extends webdriver.ActionSequence {} - class Builder extends webdriver.Builder {} - class Capabilities extends webdriver.Capabilities {} - class Command extends webdriver.Command {} - class EventEmitter extends webdriver.EventEmitter {} - class Session extends webdriver.Session {} - class WebDriver extends webdriver.WebDriver {} - class WebElement extends webdriver.WebElement {} - class WebElementPromise extends webdriver.WebElementPromise { } - - var Browser: webdriver.IBrowser; - var Button: webdriver.IButton; - var Capability: webdriver.ICapability; - var CommandName: webdriver.ICommandName; - var Key: webdriver.IKey; - - namespace error { - class Error extends webdriver.error.Error {} - var ErrorCode: webdriver.error.IErrorCode; - } - - namespace logging { - class Preferences extends webdriver.logging.Preferences { } - class Entry extends webdriver.logging.Entry { } - - var Type: webdriver.logging.IType; - var Level: webdriver.logging.ILevelValues; - - function getLevel(nameOrValue: string): webdriver.logging.ILevel; - function getLevel(nameOrValue: number): webdriver.logging.ILevel; - } - - namespace promise { - class Thenable extends webdriver.promise.Thenable { } - class Promise extends webdriver.promise.Promise { } - class Deferred extends webdriver.promise.Deferred { } - class ControlFlow extends webdriver.promise.ControlFlow { } - class CancellationError extends webdriver.promise.CancellationError { } - - /** - * Given an array of promises, will return a promise that will be fulfilled - * with the fulfillment values of the input array's values. If any of the - * input array's promises are rejected, the returned promise will be rejected - * with the same reason. - * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of - * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is - * fulfilled with an array containing the fulfilled values of the - * input array, or rejected with the same reason as the first - * rejected value. - * @template T - */ - function all(arr: webdriver.promise.Promise[]): webdriver.promise.Promise; - - /** - * Invokes the appropriate callback function as soon as a promised - * {@code value} is resolved. This function is similar to - * {@link webdriver.promise.when}, except it does not return a new promise. - * @param {*} value The value to observe. - * @param {Function} callback The function to call when the value is - * resolved successfully. - * @param {Function=} opt_errback The function to call when the value is - * rejected. - */ - function asap(value: any, callback: Function, opt_errback?: Function): void; - - /** - * @return {!webdriver.promise.ControlFlow} The currently active control flow. - */ - function controlFlow(): webdriver.promise.ControlFlow; - - /** - * Creates a new control flow. The provided callback will be invoked as the - * first task within the new flow, with the flow as its sole argument. Returns - * a promise that resolves to the callback result. - * @param {function(!webdriver.promise.ControlFlow)} callback The entry point - * to the newly created flow. - * @return {!webdriver.promise.Promise} A promise that resolves to the callback - * result. - */ - function createFlow(callback: (flow: webdriver.promise.ControlFlow) => R): webdriver.promise.Promise; - - /** - * Determines whether a {@code value} should be treated as a promise. - * Any object whose "then" property is a function will be considered a promise. - * - * @param {*} value The value to test. - * @return {boolean} Whether the value is a promise. - */ - function isPromise(value: any): boolean; - - /** - * Tests is a function is a generator. - * @param {!Function} fn The function to test. - * @return {boolean} Whether the function is a generator. - */ - function isGenerator(fn: Function): boolean; - - /** - * Creates a promise that will be resolved at a set time in the future. - * @param {number} ms The amount of time, in milliseconds, to wait before - * resolving the promise. - * @return {!webdriver.promise.Promise} The promise. - */ - function delayed(ms: number): webdriver.promise.Promise; - - /** - * Calls a function for each element in an array, and if the function returns - * true adds the element to a new array. - * - *

    If the return value of the filter function is a promise, this function - * will wait for it to be fulfilled before determining whether to insert the - * element into the new array. - * - *

    If the filter function throws or returns a rejected promise, the promise - * returned by this function will be rejected with the same reason. Only the - * first failure will be reported; all subsequent errors will be silently - * ignored. - * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ( - * boolean|webdriver.promise.Promise.)} fn The function - * to call for each element in the array. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise; - function filter(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise - - /** - * Creates a new deferred object. - * @return {!webdriver.promise.Deferred} The new deferred object. - */ - function defer(): webdriver.promise.Deferred; - - /** - * Creates a promise that has been resolved with the given value. - * @param {*=} opt_value The resolved value. - * @return {!webdriver.promise.Promise} The resolved promise. - */ - function fulfilled(opt_value?: T): webdriver.promise.Promise; - - /** - * Calls a function for each element in an array and inserts the result into a - * new array, which is used as the fulfillment value of the promise returned - * by this function. - * - *

    If the return value of the mapping function is a promise, this function - * will wait for it to be fulfilled before inserting it into the new array. - * - *

    If the mapping function throws or returns a rejected promise, the - * promise returned by this function will be rejected with the same reason. - * Only the first failure will be reported; all subsequent errors will be - * silently ignored. - * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The - * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The - * function to call for each element in the array. This function should - * expect three arguments (the element, the index, and the array itself. - * @param {SELF=} opt_self The object to be used as the value of 'this' within - * {@code fn}. - * @template TYPE, SELF - */ - function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise - function map(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise - - /** - * Creates a promise that has been rejected with the given reason. - * @param {*=} opt_reason The rejection reason; may be any value, but is - * usually an Error or a string. - * @return {!webdriver.promise.Promise} The rejected promise. - */ - function rejected(opt_reason?: any): webdriver.promise.Promise; - - /** - * Wraps a function that is assumed to be a node-style callback as its final - * argument. This callback takes two arguments: an error value (which will be - * null if the call succeeded), and the success value as the second argument. - * If the call fails, the returned promise will be rejected, otherwise it will - * be resolved with the result. - * @param {!Function} fn The function to wrap. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * result of the provided function's callback. - */ - function checkedNodeCall(fn: Function, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Consumes a {@code GeneratorFunction}. Each time the generator yields a - * promise, this function will wait for it to be fulfilled before feeding the - * fulfilled value back into {@code next}. Likewise, if a yielded promise is - * rejected, the rejection error will be passed to {@code throw}. - * - *

    Example 1: the Fibonacci Sequence. - *

    
    -         * webdriver.promise.consume(function* fibonacci() {
    -         *   var n1 = 1, n2 = 1;
    -         *   for (var i = 0; i < 4; ++i) {
    -         *     var tmp = yield n1 + n2;
    -         *     n1 = n2;
    -         *     n2 = tmp;
    -         *   }
    -         *   return n1 + n2;
    -         * }).then(function(result) {
    -         *   console.log(result);  // 13
    -         * });
    -         * 
    - * - *

    Example 2: a generator that throws. - *

    
    -         * webdriver.promise.consume(function* () {
    -         *   yield webdriver.promise.delayed(250).then(function() {
    -         *     throw Error('boom');
    -         *   });
    -         * }).thenCatch(function(e) {
    -         *   console.log(e.toString());  // Error: boom
    -         * });
    -         * 
    - * - * @param {!Function} generatorFn The generator function to execute. - * @param {Object=} opt_self The object to use as "this" when invoking the - * initial generator. - * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the - * generator's final result. - * @throws {TypeError} If the given function is not a generator. - */ - function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): webdriver.promise.Promise; - - /** - * Registers an observer on a promised {@code value}, returning a new promise - * that will be resolved when the value is. If {@code value} is not a promise, - * then the return promise will be immediately resolved. - * @param {*} value The value to observe. - * @param {Function=} opt_callback The function to call when the value is - * resolved successfully. - * @param {Function=} opt_errback The function to call when the value is - * rejected. - * @return {!webdriver.promise.Promise} A new promise. - */ - function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; - function when(value: webdriver.promise.Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; - - /** - * Returns a promise that will be resolved with the input value in a - * fully-resolved state. If the value is an array, each element will be fully - * resolved. Likewise, if the value is an object, all keys will be fully - * resolved. In both cases, all nested arrays and objects will also be - * fully resolved. All fields are resolved in place; the returned promise will - * resolve on {@code value} and not a copy. - * - * Warning: This function makes no checks against objects that contain - * cyclical references: - * - * var value = {}; - * value['self'] = value; - * webdriver.promise.fullyResolved(value); // Stack overflow. - * - * @param {*} value The value to fully resolve. - * @return {!webdriver.promise.Promise} A promise for a fully resolved version - * of the input value. - */ - function fullyResolved(value: any): webdriver.promise.Promise; - - /** - * Changes the default flow to use when no others are active. - * @param {!webdriver.promise.ControlFlow} flow The new default flow. - * @throws {Error} If the default flow is not currently active. - */ - function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; - } - - namespace stacktrace { - class Frame extends webdriver.stacktrace.Frame { } - class Snapshot extends webdriver.stacktrace.Snapshot { } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): webdriver.stacktrace.Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - - namespace until { - class Condition extends webdriver.until.Condition { } - - /** - * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as: - *
      - *
    1. A numeric index into {@code window.frames} for the currently selected - * frame. - *
    2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - *
    3. A locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - *
    - * - *

    Upon successful resolution of this condition, the driver will be left - * focused on the new frame. - * - * @param {!(number|webdriver.WebElement| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame - * The frame identifier. - * @return {!until.Condition.} A new condition. - */ - function ableToSwitchToFrame(frame: number): webdriver.until.Condition; - function ableToSwitchToFrame(frame: webdriver.IWebElement): webdriver.until.Condition; - function ableToSwitchToFrame(frame: webdriver.Locator): webdriver.until.Condition; - function ableToSwitchToFrame(frame: (webdriver: webdriver.WebDriver) => webdriver.IWebElement): webdriver.until.Condition; - function ableToSwitchToFrame(frame: any): webdriver.until.Condition; - - /** - * Creates a condition that waits for an alert to be opened. Upon success, the - * returned promise will be fulfilled with the handle for the opened alert. - * - * @return {!until.Condition.} The new condition. - */ - function alertIsPresent(): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be disabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsDisabled(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be enabled. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isEnabled - */ - function elementIsEnabled(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be deselected. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsNotSelected(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be in the DOM, - * yet not visible to the user. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsNotVisible(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to be selected. - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isSelected - */ - function elementIsSelected(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to become visible. - * - * @param {!webdriver.WebElement} element The element to test. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#isDisplayed - */ - function elementIsVisible(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. - * @return {!until.Condition.} The new condition. - */ - function elementLocated(locator: webdriver.Locator): webdriver.until.Condition; - function elementLocated(locator: any): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to contain the given - * substring. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} substr The substring to search for. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextContains(element: webdriver.IWebElement, substr: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match the given - * {@code text} exactly. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {string} text The expected text. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextIs(element: webdriver.IWebElement, text: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element's - * {@link webdriver.WebDriver#getText visible text} to match a regular - * expression. - * - * @param {!webdriver.WebElement} element The element to test. - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. - * @see webdriver.WebDriver#getText - */ - function elementTextMatches(element: webdriver.IWebElement, regex: RegExp): webdriver.until.Condition; - - /** - * Creates a condition that will loop until at least one element is - * {@link webdriver.WebDriver#findElement found} with the given locator. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. - * @return {!until.Condition.>} The new - * condition. - */ - function elementsLocated(locator: webdriver.Locator): webdriver.until.Condition; - function elementsLocated(locator: any): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the given element to become stale. An - * element is considered stale once it is removed from the DOM, or a new page - * has loaded. - * - * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. - */ - function stalenessOf(element: webdriver.IWebElement): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the current page's title to contain - * the given substring. - * - * @param {string} substr The substring that should be present in the page - * title. - * @return {!until.Condition.} The new condition. - */ - function titleContains(substr: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given value. - * - * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. - */ - function titleIs(title: string): webdriver.until.Condition; - - /** - * Creates a condition that will wait for the current page's title to match the - * given regular expression. - * - * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. - */ - function titleMatches(regex: RegExp): webdriver.until.Condition; - } - - namespace ExpectedConditions { - /** - * Negates the result of a promise. - * - * @param {webdriver.until.Condition} expectedCondition - * @return {!webdriver.until.Condition} An expected condition that returns the negated value. - */ - function not(expectedCondition: webdriver.until.Condition): webdriver.until.Condition; - - /** - * Chain a number of expected conditions using logical_and, short circuiting at the - * first expected condition that evaluates to false. - * - * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'and' together. - * @return {!webdriver.until.Condition} An expected condition that returns a promise which evaluates - * to the result of the logical and. - */ - function and(...fns: webdriver.until.Condition[]): webdriver.until.Condition; - - /** - * Chain a number of expected conditions using logical_or, short circuiting at the - * first expected condition that evaluates to true. - * - * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'or' together. - * @return {!webdriver.until.Condition} An expected condition that returns a promise which - * evaluates to the result of the logical or. - */ - function or(...fns: webdriver.until.Condition[]): webdriver.until.Condition; - - /** - * Expect an alert to be present. - * - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether an alert is present. - */ - function alertIsPresent(): webdriver.until.Condition; - - /** - * An Expectation for checking an element is visible and enabled such that you can click it. - * - * @param {ElementFinder} element The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is clickable. - */ - function elementToBeClickable(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking if the given text is present in the element. - * Returns false if the elementFinder does not find an element. - * - * @param {ElementFinder} element The element to check - * @param {string} text The text to verify against - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the text is present in the element. - */ - function textToBePresentInElement(element: ElementFinder, text: string): webdriver.until.Condition; - - /** - * An expectation for checking if the given text is present in the element’s value. - * Returns false if the elementFinder does not find an element. - * - * @param {ElementFinder} element The element to check - * @param {string} text The text to verify against - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the text is present in the element's value. - */ - function textToBePresentInElementValue( - element: ElementFinder, text: string - ): webdriver.until.Condition; - - /** - * An expectation for checking that the title contains a case-sensitive substring. - * - * @param {string} title The fragment of title expected - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the title contains the string. - */ - function titleContains(title: string): webdriver.until.Condition; - - /** - * An expectation for checking the title of a page. - * - * @param {string} title The expected title, which must be an exact match. - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the title equals the string. - */ - function titleIs(title: string): webdriver.until.Condition; - - /** - * An expectation for checking that an element is present on the DOM of a page. This does not necessarily - * mean that the element is visible. This is the opposite of 'stalenessOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise - * representing whether the element is present. - */ - function presenceOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking that an element is not attached to the DOM of a page. - * This is the opposite of 'presenceOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is stale. - */ - function stalenessOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking that an element is present on the DOM of a page and visible. - * Visibility means that the element is not only displayed but also has a height and width that is - * greater than 0. This is the opposite of 'invisibilityOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is visible. - */ - function visibilityOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking that an element is present on the DOM of a page. This does not necessarily - * mean that the element is visible. This is the opposite of 'stalenessOf'. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is invisible. - */ - function invisibilityOf(element: ElementFinder): webdriver.until.Condition; - - /** - * An expectation for checking the selection is selected. - * - * @param {ElementFinder} elementFinder The element to check - * @return {!webdriver.until.Condition} An expected condition that returns a promise representing - * whether the element is selected. - */ - function elementToBeSelected(element: ElementFinder): webdriver.until.Condition; - } - - //endregion - - /** - * Use as: element(locator) - * - * The ElementFinder can be treated as a WebElement for most purposes, in - * particular, you may perform actions (i.e. click, getText) on them as you - * would a WebElement. ElementFinders extend Promise, and once an action - * is performed on an ElementFinder, the latest result from the chain can be - * accessed using then. Unlike a WebElement, an ElementFinder will wait for - * angular to settle before performing finds or actions. - * - * ElementFinder can be used to build a chain of locators that is used to find - * an element. An ElementFinder does not actually attempt to find the element - * until an action is called, which means they can be set up in helper files - * before the page is available. - * - * @param {webdriver.Locator} locator An element locator. - * @return {ElementFinder} - */ - interface Element { - (locator: webdriver.Locator): ElementFinder; - - /** - * ElementArrayFinder is used for operations on an array of elements (as opposed - * to a single element). - * - * @param {webdriver.Locator} locator An element locator. - * @return {ElementArrayFinder} - */ - all(locator: webdriver.Locator): ElementArrayFinder; - } - - interface ElementFinder extends webdriver.IWebElement, webdriver.promise.IThenable { - /** - * Calls to element may be chained to find elements within a parent. - * - * @alias element(locator).element(locator) - * @view - *

    - *
    - * Child text - *
    {{person.phone}}
    - *
    - *
    - * - * @example - * // Chain 2 element calls. - * var child = element(by.css('.parent')). - * element(by.css('.child')); - * expect(child.getText()).toBe('Child text\n555-123-4567'); - * - * // Chain 3 element calls. - * var triple = element(by.css('.parent')). - * element(by.css('.child')). - * element(by.binding('person.phone')); - * expect(triple.getText()).toBe('555-123-4567'); - * - * @param {webdriver.Locator} subLocator - * @return {ElementFinder} - */ - element(subLocator: webdriver.Locator): ElementFinder; - - /** - * Calls to element may be chained to find an array of elements within a parent. - * - * @alias element(locator).all(locator) - * @view - *
    - *
      - *
    • First
    • - *
    • Second
    • - *
    • Third
    • - *
    - *
    - * - * @example - * var items = element(by.css('.parent')).all(by.tagName('li')) - * - * @param {webdriver.Locator} subLocator - * @return {ElementArrayFinder} - */ - all(subLocator: webdriver.Locator): ElementArrayFinder; - - /** - * Shortcut for querying the document directly with css. - * - * @alias $(cssSelector) - * @view - *
    - * First - * Second - *
    - * - * @example - * var item = $('.count .two'); - * expect(item.getText()).toBe('Second'); - * - * @param {string} selector A css selector - * @return {ElementFinder} which identifies the located - * {@link webdriver.WebElement} - */ - $(selector: string): ElementFinder; - - /** - * Shortcut for querying the document directly with css. - * - * @alias $$(cssSelector) - * @view - *
    - * First - * Second - *
    - * - * @example - * // The following protractor expressions are equivalent. - * var list = element.all(by.css('.count span')); - * expect(list.count()).toBe(2); - * - * list = $$('.count span'); - * expect(list.count()).toBe(2); - * expect(list.get(0).getText()).toBe('First'); - * expect(list.get(1).getText()).toBe('Second'); - * - * @param {string} selector a css selector - * @return {ElementArrayFinder} which identifies the - * array of the located {@link webdriver.WebElement}s. - */ - $$(selector: string): ElementArrayFinder; - - /** - * Determine whether the element is present on the page. - * - * @view - * {{person.name}} - * - * @example - * // Element exists. - * expect(element(by.binding('person.name')).isPresent()).toBe(true); - * - * // Element not present. - * expect(element(by.binding('notPresent')).isPresent()).toBe(false); - * - * @return {ElementFinder} which resolves to whether - * the element is present on the page. - */ - isPresent(): webdriver.promise.Promise; - - /** - * Override for WebElement.prototype.isElementPresent so that protractor waits - * for Angular to settle before making the check. - * - * @see ElementFinder.isPresent - * - * @param {webdriver.Locator} subLocator Locator for element to look for. - * @return {ElementFinder} which resolves to whether - * the element is present on the page. - */ - isElementPresent(subLocator: webdriver.Locator): webdriver.promise.Promise; - - /** - * @see ElementArrayFinder.prototype.locator - * - * @return {webdriver.Locator} - */ - locator(): webdriver.Locator; - - /** - * Returns the WebElement represented by this ElementFinder. - * Throws the WebDriver error if the element doesn't exist. - * - * @example - * The following three expressions are equivalent. - * element(by.css('.parent')).getWebElement(); - * browser.waitForAngular(); browser.driver.findElement(by.css('.parent')); - * browser.findElement(by.css('.parent')); - * - * @alias element(locator).getWebElement() - * @return {webdriver.WebElement} - */ - getWebElement(): webdriver.WebElement; - - /** - * Evaluates the input as if it were on the scope of the current element. - * @see ElementArrayFinder.evaluate - * - * @param {string} expression - * - * @return {ElementFinder} which resolves to the evaluated expression. - */ - evaluate(expression: string): ElementFinder; - - /** - * @see ElementArrayFinder.prototype.allowAnimations. - * @param {string} value - * - * @return {ElementFinder} which resolves to whether animation is allowed. - */ - allowAnimations(value: string): ElementFinder; - - /** - * Create a shallow copy of ElementFinder. - * - * @return {!ElementFinder} A shallow copy of this. - */ - clone(): ElementFinder; - } - - interface ElementArrayFinder extends webdriver.promise.IThenable { - /** - * Returns the elements as an array of WebElements. - */ - getWebElements(): webdriver.WebElement[]; - - - /** - * Get an element within the ElementArrayFinder by index. The index starts at 0. - * Negative indices are wrapped (i.e. -i means ith element from last) - * This does not actually retrieve the underlying element. - * - * @alias element.all(locator).get(index) - * @view - *
      - *
    • First
    • - *
    • Second
    • - *
    • Third
    • - *
    - * - * @example - * var list = element.all(by.css('.items li')); - * expect(list.get(0).getText()).toBe('First'); - * expect(list.get(1).getText()).toBe('Second'); - * - * @param {number} index Element index. - * @return {ElementFinder} finder representing element at the given index. - */ - get(index: number): ElementFinder; - - /** - * Get the first matching element for the ElementArrayFinder. This does not - * actually retrieve the underlying element. - * - * @alias element.all(locator).first() - * @view - *
      - *
    • First
    • - *
    • Second
    • - *
    • Third
    • - *
    - * - * @example - * var first = element.all(by.css('.items li')).first(); - * expect(first.getText()).toBe('First'); - * - * @return {ElementFinder} finder representing the first matching element - */ - first(): ElementFinder; - - /** - * Get the last matching element for the ElementArrayFinder. This does not - * actually retrieve the underlying element. - * - * @alias element.all(locator).last() - * @view - *
      - *
    • First
    • - *
    • Second
    • - *
    • Third
    • - *
    - * - * @example - * var last = element.all(by.css('.items li')).last(); - * expect(last.getText()).toBe('Third'); - * - * @return {ElementFinder} finder representing the last matching element - */ - last(): ElementFinder; - - /** - * Count the number of elements represented by the ElementArrayFinder. - * - * @alias element.all(locator).count() - * @view - *
      - *
    • First
    • - *
    • Second
    • - *
    • Third
    • - *
    - * - * @example - * var list = element.all(by.css('.items li')); - * expect(list.count()).toBe(3); - * - * @return {!webdriver.promise.Promise} A promise which resolves to the - * number of elements matching the locator. - */ - count(): webdriver.promise.Promise; - - /** - * Calls the input function on each ElementFinder represented by the ElementArrayFinder. - * - * @alias element.all(locator).each(eachFunction) - * @view - *
      - *
    • First
    • - *
    • Second
    • - *
    • Third
    • - *
    - * - * @example - * element.all(by.css('.items li')).each(function(element) { - * // Will print First, Second, Third. - * element.getText().then(console.log); - * }); - * - * @param {function(ElementFinder)} fn Input function - */ - each(fn: (element: ElementFinder, index: number) => void): void; - - /** - * Apply a map function to each element within the ElementArrayFinder. The - * callback receives the ElementFinder as the first argument and the index as - * a second arg. - * - * @alias element.all(locator).map(mapFunction) - * @view - *
      - *
    • First
    • - *
    • Second
    • - *
    • Third
    • - *
    - * - * @example - * var items = element.all(by.css('.items li')).map(function(elm, index) { - * return { - * index: index, - * text: elm.getText(), - * class: elm.getAttribute('class') - * }; - * }); - * expect(items).toEqual([ - * {index: 0, text: 'First', class: 'one'}, - * {index: 1, text: 'Second', class: 'two'}, - * {index: 2, text: 'Third', class: 'three'} - * ]); - * - * @param {function(ElementFinder, number)} mapFn Map function that - * will be applied to each element. - * @return {!webdriver.promise.Promise} A promise that resolves to an array - * of values returned by the map function. - */ - map(mapFn: (element: ElementFinder, index: number) => T): webdriver.promise.Promise; - map(mapFn: (element: ElementFinder, index: number) => T2): webdriver.promise.Promise; - - /** - * Apply a filter function to each element within the ElementArrayFinder. Returns - * a new ElementArrayFinder with all elements that pass the filter function. The - * filter function receives the ElementFinder as the first argument - * and the index as a second arg. - * This does not actually retrieve the underlying list of elements, so it can - * be used in page objects. - * - * @alias element.all(locator).filter(filterFn) - * @view - *
      - *
    • First
    • - *
    • Second
    • - *
    • Third
    • - *
    - * - * @example - * element.all(by.css('.items li')).filter(function(elem, index) { - * return elem.getText().then(function(text) { - * return text === 'Third'; - * }); - * }).then(function(filteredElements) { - * filteredElements[0].click(); - * }); - * - * @param {function(ElementFinder, number): webdriver.WebElement.Promise} filterFn - * Filter function that will test if an element should be returned. - * filterFn can either return a boolean or a promise that resolves to a boolean. - * @return {!ElementArrayFinder} A ElementArrayFinder that represents an array - * of element that satisfy the filter function. - */ - filter(filterFn: (element: ElementFinder, index: number) => any): ElementArrayFinder; - - /** - * Apply a reduce function against an accumulator and every element found - * using the locator (from left-to-right). The reduce function has to reduce - * every element into a single value (the accumulator). Returns promise of - * the accumulator. The reduce function receives the accumulator, current - * ElementFinder, the index, and the entire array of ElementFinders, - * respectively. - * - * @alias element.all(locator).reduce(reduceFn) - * @view - *
      - *
    • First
    • - *
    • Second
    • - *
    • Third
    • - *
    - * - * @example - * var value = element.all(by.css('.items li')).reduce(function(acc, elem) { - * return elem.getText().then(function(text) { - * return acc + text + ' '; - * }); - * }); - * - * expect(value).toEqual('First Second Third '); - * - * @param {function(number, ElementFinder, number, Array.)} - * reduceFn Reduce function that reduces every element into a single value. - * @param {*} initialValue Initial value of the accumulator. - * @return {!webdriver.promise.Promise} A promise that resolves to the final - * value of the accumulator. - */ - reduce(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => webdriver.promise.Promise, initialValue: T): webdriver.promise.Promise; - reduce(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => T, initialValue: T): webdriver.promise.Promise; - - /** - * Represents the ElementArrayFinder as an array of ElementFinders. - * - * @return {Array.} Return a promise, which resolves to a list - * of ElementFinders specified by the locator. - */ - asElementFinders_(): webdriver.promise.Promise; - - /** - * Create a shallow copy of ElementArrayFinder. - * - * @return {!ElementArrayFinder} A shallow copy of this. - */ - clone(): ElementArrayFinder; - - /** - * Calls to ElementArrayFinder may be chained to find an array of elements - * using the current elements in this ElementArrayFinder as the starting point. - * This function returns a new ElementArrayFinder which would contain the - * children elements found (and could also be empty). - * - * @alias element.all(locator).all(locator) - * @view - *
    - *
      - *
    • 1a
    • - *
    • 1b
    • - *
    - *
    - *
    - *
      - *
    • 2a
    • - *
    • 2b
    • - *
    - *
    - * - * @example - * var foo = element.all(by.css('.parent')).all(by.css('.foo')) - * expect(foo.getText()).toEqual(['1a', '2a']) - * var baz = element.all(by.css('.parent')).all(by.css('.baz')) - * expect(baz.getText()).toEqual(['1b']) - * var nonexistent = element.all(by.css('.parent')).all(by.css('.NONEXISTENT')) - * expect(nonexistent.getText()).toEqual(['']) - * - * @param {webdriver.Locator} subLocator - * @return {ElementArrayFinder} - */ - all(locator: webdriver.Locator): ElementArrayFinder; - - /** - * Shorthand function for finding arrays of elements by css. - * - * @type {function(string): ElementArrayFinder} - */ - $$(selector: string): ElementArrayFinder; - - /** - * Returns an ElementFinder representation of ElementArrayFinder. It ensures - * that the ElementArrayFinder resolves to one and only one underlying element. - * - * @return {ElementFinder} An ElementFinder representation - * @private - */ - toElementFinder_(): ElementFinder; - - /** - * Returns the most relevant locator. - * - * @example - * $('#ID1').locator() // returns by.css('#ID1') - * $('#ID1').$('#ID2').locator() // returns by.css('#ID2') - * $$('#ID1').filter(filterFn).get(0).click().locator() // returns by.css('#ID1') - * - * @return {webdriver.Locator} - */ - locator(): webdriver.Locator; - - /** - * Evaluates the input as if it were on the scope of the current underlying - * elements. - * - * @view - * {{variableInScope}} - * - * @example - * var value = element(by.id('foo')).evaluate('variableInScope'); - * - * @param {string} expression - * - * @return {ElementArrayFinder} which resolves to the - * evaluated expression for each underlying element. - * The result will be resolved as in - * {@link webdriver.WebDriver.executeScript}. In summary - primitives will - * be resolved as is, functions will be converted to string, and elements - * will be returned as a WebElement. - */ - evaluate(expression: string): ElementArrayFinder; - - /** - * Determine if animation is allowed on the current underlying elements. - * @param {string} value - * - * @example - * // Turns off ng-animate animations for all elements in the - * element(by.css('body')).allowAnimations(false); - * - * @return {ElementArrayFinder} which resolves to whether animation is allowed. - */ - allowAnimations(value: boolean): ElementArrayFinder; - - /** - * Schedules a command to click on this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the click command has completed. - */ - click(): webdriver.promise.Promise; - - /** - * Schedules a command to type a sequence on the DOM element represented by this - * instance. - *

    - * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is - * processed in the keysequence, that key state is toggled until one of the - * following occurs: - *

      - *
    • The modifier key is encountered again in the sequence. At this point the - * state of the key is toggled (along with the appropriate keyup/down events). - *
    • - *
    • The {@code webdriver.Key.NULL} key is encountered in the sequence. When - * this key is encountered, all modifier keys current in the down state are - * released (with accompanying keyup events). The NULL key can be used to - * simulate common keyboard shortcuts: - * - * element.sendKeys("text was", - * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, - * "now text is"); - * // Alternatively: - * element.sendKeys("text was", - * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), - * "now text is"); - *
    • - *
    • The end of the keysequence is encountered. When there are no more keys - * to type, all depressed modifier keys are released (with accompanying keyup - * events). - *
    • - *
    - * Note: On browsers where native keyboard events are not yet - * supported (e.g. Firefox on OS X), key events will be synthesized. Special - * punctionation keys will be synthesized according to a standard QWERTY en-us - * keyboard layout. - * - * @param {...string} var_args The sequence of keys to - * type. All arguments will be joined into a single sequence (var_args is - * permitted for convenience). - * @return {!webdriver.promise.Promise} A promise that will be resolved when all - * keys have been typed. - */ - sendKeys(...var_args: string[]): webdriver.promise.Promise; - - /** - * Schedules a command to query for the tag/node name of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's tag name. - */ - getTagName(): webdriver.promise.Promise; - - /** - * Schedules a command to query for the computed style of the element - * represented by this instance. If the element inherits the named style from - * its parent, the parent will be queried for its value. Where possible, color - * values will be converted to their hex representation (e.g. #00ff00 instead of - * rgb(0, 255, 0)). - *

    - * Warning: the value returned will be as the browser interprets it, so - * it may be tricky to form a proper assertion. - * - * @param {string} cssStyleProperty The name of the CSS style property to look - * up. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * requested CSS value. - */ - getCssValue(cssStyleProperty: string): webdriver.promise.Promise; - - /** - * Schedules a command to query for the value of the given attribute of the - * element. Will return the current value even if it has been modified after the - * page has been loaded. More exactly, this method will return the value of the - * given attribute, unless that attribute is not present, in which case the - * value of the property with the same name is returned. If neither value is - * set, null is returned. The "style" attribute is converted as best can be to a - * text representation with a trailing semi-colon. The following are deemed to - * be "boolean" attributes and will be returned as thus: - * - *

    async, autofocus, autoplay, checked, compact, complete, controls, declare, - * defaultchecked, defaultselected, defer, disabled, draggable, ended, - * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, - * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, - * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, - * selected, spellcheck, truespeed, willvalidate - * - *

    Finally, the following commonly mis-capitalized attribute/property names - * are evaluated as expected: - *

      - *
    • "class" - *
    • "readonly" - *
    - * @param {string} attributeName The name of the attribute to query. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * attribute's value. - */ - getAttribute(attributeName: string): webdriver.promise.Promise; - - /** - * Get the visible (i.e. not hidden by CSS) innerText of this element, including - * sub-elements, without any leading or trailing whitespace. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's visible text. - */ - getText(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the size of this element's bounding box, in - * pixels. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's size as a {@code {width:number, height:number}} object. - */ - getSize(): webdriver.promise.Promise; - - /** - * Schedules a command to compute the location of this element in page space. - * @return {!webdriver.promise.Promise} A promise that will be resolved to the - * element's location as a {@code {x:number, y:number}} object. - */ - getLocation(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether the DOM element represented by this - * instance is enabled, as dicted by the {@code disabled} attribute. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently enabled. - */ - isEnabled(): webdriver.promise.Promise; - - /** - * Schedules a command to query whether this element is selected. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently selected. - */ - isSelected(): webdriver.promise.Promise; - - /** - * Schedules a command to submit the form containing this element (or this - * element if it is a FORM element). This command is a no-op if the element is - * not contained in a form. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the form has been submitted. - */ - submit(): webdriver.promise.Promise; - - /** - * Schedules a command to clear the {@code value} of this element. This command - * has no effect if the underlying DOM element is neither a text INPUT element - * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise} A promise that will be resolved when - * the element has been cleared. - */ - clear(): webdriver.promise.Promise; - - /** - * Schedules a command to test whether this element is currently displayed. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * whether this element is currently visible on the page. - */ - isDisplayed(): webdriver.promise.Promise; - - /** - * Schedules a command to retrieve the outer HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the element's outer HTML. - */ - getOuterHtml(): webdriver.promise.Promise; - - /** - * @return {!webdriver.promise.Promise.} A promise - * that resolves to this element's JSON representation as defined by the - * WebDriver wire protocol. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol - */ - getId(): webdriver.promise.Promise - - /** - * Schedules a command to retrieve the inner HTML of this element. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the - * element's inner HTML. - */ - getInnerHtml(): webdriver.promise.Promise; - } - - interface LocatorWithColumn extends webdriver.Locator { - column(index: number): webdriver.Locator; - column(name: string): webdriver.Locator; - } - - interface RepeaterLocator extends LocatorWithColumn { - row(index: number): LocatorWithColumn; - } - - interface IProtractorLocatorStrategy { - /** - * webdriver's By is an enum of locator functions, so we must set it to - * a prototype before inheriting from it. - */ - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - linkText: typeof webdriver.By.linkText; - js: typeof webdriver.By.js; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - - /** - * Add a locator to this instance of ProtractorBy. This locator can then be - * used with element(by.locatorName(args)). - * - * @view - * - * - * @example - * // Add the custom locator. - * by.addLocator('buttonTextSimple', - * function(buttonText, opt_parentElement, opt_rootSelector) { - * // This function will be serialized as a string and will execute in the - * // browser. The first argument is the text for the button. The second - * // argument is the parent element, if any. - * var using = opt_parentElement, - * buttons = using.querySelectorAll('button'); - * - * // Return an array of buttons with the text. - * return Array.prototype.filter.call(buttons, function(button) { - * return button.textContent === buttonText; - * }); - * }); - * - * // Use the custom locator. - * element(by.buttonTextSimple('Go!')).click(); - * - * @alias by.addLocator(locatorName, functionOrScript) - * @param {string} name The name of the new locator. - * @param {Function|string} script A script to be run in the context of - * the browser. This script will be passed an array of arguments - * that contains any args passed into the locator followed by the - * element scoping the search and the css selector for the root angular - * element. It should return an array of elements. - */ - addLocator(name: string, script: string): void; - addLocator(name: string, script: Function): void; - - /** - * Find an element by binding. - * - * @view - * {{person.name}} - * - * - * @example - * var span1 = element(by.binding('person.name')); - * expect(span1.getText()).toBe('Foo'); - * - * var span2 = element(by.binding('person.email')); - * expect(span2.getText()).toBe('foo@bar.com'); - * - * @param {string} bindingDescriptor - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - binding(bindingDescriptor: string): webdriver.Locator; - - /** - * Find an element by exact binding. - * - * @view - * {{ person.name }} - * - * {{person_phone|uppercase}} - * - * @example - * expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); - * expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); - * expect(element(by.exactBinding('person')).isPresent()).toBe(false); - * expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); - * expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); - * expect(element(by.exactBinding('phone')).isPresent()).toBe(false); - * - * @param {string} bindingDescriptor - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - exactBinding(bindingDescriptor: string): webdriver.Locator; - - /** - * Find an element by ng-model expression. - * - * @alias by.model(modelName) - * @view - * - * - * @example - * var input = element(by.model('person.name')); - * input.sendKeys('123'); - * expect(input.getAttribute('value')).toBe('Foo123'); - * - * @param {string} model ng-model expression. - */ - model(model: string): webdriver.Locator; - - /** - * Find a button by text. - * - * @view - * - * - * @example - * element(by.buttonText('Save')); - * - * @param {string} searchText - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - buttonText(searchText: string): webdriver.Locator; - - /** - * Find a button by partial text. - * - * @view - * - * - * @example - * element(by.partialButtonText('Save')); - * - * @param {string} searchText - * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} - */ - partialButtonText(searchText: string): webdriver.Locator; - - - /** - * Find elements inside an ng-repeat. - * - * @view - *
    - * {{cat.name}} - * {{cat.age}} - *
    - * - *
    - * {{$index}} - *
    - *
    - *

    {{book.name}}

    - *

    {{book.blurb}}

    - *
    - * - * @example - * // Returns the DIV for the second cat. - * var secondCat = element(by.repeater('cat in pets').row(1)); - * - * // Returns the SPAN for the first cat's name. - * var firstCatName = element(by.repeater('cat in pets'). - * row(0).column('{{cat.name}}')); - * - * // Returns a promise that resolves to an array of WebElements from a column - * var ages = element.all( - * by.repeater('cat in pets').column('{{cat.age}}')); - * - * // Returns a promise that resolves to an array of WebElements containing - * // all top level elements repeated by the repeater. For 2 pets rows resolves - * // to an array of 2 elements. - * var rows = element.all(by.repeater('cat in pets')); - * - * // Returns a promise that resolves to an array of WebElements containing all - * // the elements with a binding to the book's name. - * var divs = element.all(by.repeater('book in library').column('book.name')); - * - * // Returns a promise that resolves to an array of WebElements containing - * // the DIVs for the second book. - * var bookInfo = element.all(by.repeater('book in library').row(1)); - * - * // Returns the H4 for the first book's name. - * var firstBookName = element(by.repeater('book in library'). - * row(0).column('{{book.name}}')); - * - * // Returns a promise that resolves to an array of WebElements containing - * // all top level elements repeated by the repeater. For 2 books divs - * // resolves to an array of 4 elements. - * var divs = element.all(by.repeater('book in library')); - */ - repeater(repeatDescriptor: string): RepeaterLocator; - - /** - * Find elements by CSS which contain a certain string. - * - * @view - *
      - *
    • Dog
    • - *
    • Cat
    • - *
    - * - * @example - * // Returns the DIV for the dog, but not cat. - * var dog = element(by.cssContainingText('.pet', 'Dog')); - */ - cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; - - /** - * Find an element by ng-options expression. - * - * @alias by.options(optionsDescriptor) - * @view - * - * - * @example - * var allOptions = element.all(by.options('c for c in colors')); - * expect(allOptions.count()).toEqual(2); - * var firstOption = allOptions.first(); - * expect(firstOption.getText()).toEqual('red'); - * - * @param {string} optionsDescriptor ng-options expression. - */ - options(optionsDescriptor: string): webdriver.Locator; - } - - var By: IProtractorLocatorStrategy; - - interface Protractor extends webdriver.WebDriver { - - /** - * The wrapped webdriver instance. Use this to interact with pages that do - * not contain Angular (such as a log-in screen). - * - * @type {webdriver.WebDriver} - */ - driver: webdriver.WebDriver; - - /** - * Helper function for finding elements. - * - * @type {function(webdriver.Locator): ElementFinder} - */ - element(locator: webdriver.Locator): ElementFinder; - - /** - * Shorthand function for finding elements by css. - * - * @type {function(string): ElementFinder} - */ - $(selector: string): ElementFinder; - - /** - * Shorthand function for finding arrays of elements by css. - * - * @type {function(string): ElementArrayFinder} - */ - $$(selector: string): ElementArrayFinder; - - /** - * All get methods will be resolved against this base URL. Relative URLs are = - * resolved the way anchor tags resolve. - * - * @type {string} - */ - baseUrl: string; - - /** - * The css selector for an element on which to find Angular. This is usually - * 'body' but if your ng-app is on a subsection of the page it may be - * a subelement. - * - * @type {string} - */ - rootEl: string; - - /** - * If true, Protractor will not attempt to synchronize with the page before - * performing actions. This can be harmful because Protractor will not wait - * until $timeouts and $http calls have been processed, which can cause - * tests to become flaky. This should be used only when necessary, such as - * when a page continuously polls an API using $timeout. - * - * @type {boolean} - */ - ignoreSynchronization: boolean; - - /** - * Timeout in milliseconds to wait for pages to load when calling `get`. - * - * @type {number} - */ - getPageTimeout: number; - - /** - * An object that holds custom test parameters. - * - * @type {Object} - */ - params: any; - - /** - * The reset URL to use between page loads. - * - * @type {string} - */ - resetUrl: string; - - /** - * Instruct webdriver to wait until Angular has finished rendering and has - * no outstanding $http calls before continuing. - * - * @return {!webdriver.promise.Promise} A promise that will resolve to the - * scripts return value. - */ - waitForAngular(): webdriver.promise.Promise; - - /** - * Add a module to load before Angular whenever Protractor.get is called. - * Modules will be registered after existing modules already on the page, - * so any module registered here will override preexisting modules with the same - * name. - * - * @example - * browser.addMockModule('modName', function() { - * angular.module('modName', []).value('foo', 'bar'); - * }); - * - * @param {!string} name The name of the module to load or override. - * @param {!string|Function} script The JavaScript to load the module. - * @param {...*} varArgs Any additional arguments will be provided to - * the script and may be referenced using the `arguments` object. - */ - addMockModule(name: string, script: string, ...varArgs: any[]): void; - addMockModule(name: string, script: Function, ...varArgs: any[]): void; - - /** - * Clear the list of registered mock modules. - */ - clearMockModules(): void; - - /** - * Remove a registered mock module. - * - * @example - * browser.removeMockModule('modName'); - * - * @param {!string} name The name of the module to remove. - */ - removeMockModule(name: string): void; - - /** - * @see webdriver.WebDriver.get - * - * Navigate to the given destination and loads mock modules before - * Angular. Assumes that the page being loaded uses Angular. - * If you need to access a page which does not have Angular on load, use - * the wrapped webdriver directly. - * - * @param {string} destination Destination URL. - * @param {number=} opt_timeout Number of milliseconds to wait for Angular to - * start. - */ - get(destination: string, opt_timeout?: number): webdriver.promise.Promise; - - /** - * See webdriver.WebDriver.refresh - * - * Makes a full reload of the current page and loads mock modules before - * Angular. Assumes that the page being loaded uses Angular. - * If you need to access a page which does not have Angular on load, use - * the wrapped webdriver directly. - * - * @param {number=} opt_timeout Number of seconds to wait for Angular to start. - */ - refresh(opt_timeout?: number): webdriver.promise.Promise; - - /** - * Browse to another page using in-page navigation. - * - * @param {string} url In page URL using the same syntax as $location.url() - * @returns {!webdriver.promise.Promise} A promise that will resolve once - * page has been changed. - */ - setLocation(url: string): webdriver.promise.Promise; - - /** - * Returns the current absolute url from AngularJS. - */ - getLocationAbsUrl(): webdriver.promise.Promise; - - /** - * Pauses the test and injects some helper functions into the browser, so that - * debugging may be done in the browser console. - * - * This should be used under node in debug mode, i.e. with - * protractor debug - * - * @example - * While in the debugger, commands can be scheduled through webdriver by - * entering the repl: - * debug> repl - * Press Ctrl + C to leave rdebug repl - * > ptor.findElement(protractor.By.input('user').sendKeys('Laura')); - * > ptor.debugger(); - * debug> c - * - * This will run the sendKeys command as the next task, then re-enter the - * debugger. - */ - debugger(): void; - - /** - * Beta (unstable) pause function for debugging webdriver tests. Use - * browser.pause() in your test to enter the protractor debugger from that - * point in the control flow. - * Does not require changes to the command line (no need to add 'debug'). - * - * @example - * element(by.id('foo')).click(); - * browser.pause(); - * // Execution will stop before the next click action. - * element(by.id('bar')).click(); - * - * @param {number=} opt_debugPort Optional port to use for the debugging process - */ - pause(opt_debugPort?: number): void; - } - - // Interface for the global browser object. - interface IBrowser extends Protractor { - /** - * Fork another instance of protractor for use in interactive tests. - * - * @param {boolean} opt_useSameUrl Whether to navigate to current url on creation - * @param {boolean} opt_copyMockModules Whether to apply same mock modules on creation - * @return {Protractor} a protractor instance. - */ - forkNewDriverInstance(opt_useSameUrl?: boolean, opt_copyMockModules?: boolean): Protractor; - - /** - * Get the processed configuration object that is currently being run. This will contain - * the specs and capabilities properties of the current runner instance. - * - * Set by the runner. - * - * @return {webdriver.promise.Promise} A promise which resolves to the capabilities object. - */ - getProcessedConfig(): webdriver.promise.Promise; - } - - /** - * Create a new instance of Protractor by wrapping a webdriver instance. - * - * @param {webdriver.WebDriver} webdriver The configured webdriver instance. - * @param {string=} opt_baseUrl A URL to prepend to relative gets. - * @return {Protractor} - */ - function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; -} - -interface cssSelectorHelper { - (cssLocator: string): protractor.ElementFinder; -} - -interface cssArraySelectorHelper { - (cssLocator: string): protractor.ElementArrayFinder; -} - -declare var browser: protractor.IBrowser; -declare var by: protractor.IProtractorLocatorStrategy; -declare var By: protractor.IProtractorLocatorStrategy; -declare var element: protractor.Element; -declare var $: cssSelectorHelper; -declare var $$: cssArraySelectorHelper; - -declare module 'protractor' { - export = protractor; -} diff --git a/protractor/tsconfig.json b/protractor/tsconfig.json deleted file mode 100644 index c16efc5afc..0000000000 --- a/protractor/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "noImplicitAny": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "angular-protractor-tests.ts" - ] -} \ No newline at end of file diff --git a/selenium-webdriver/index.d.ts b/selenium-webdriver/index.d.ts index 548048b695..702ff68c33 100644 --- a/selenium-webdriver/index.d.ts +++ b/selenium-webdriver/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Selenium WebDriverJS 2.44.0 -// Project: https://code.google.com/p/selenium/ -// Definitions by: Bill Armstrong , Yuki Kokubun +// Type definitions for Selenium WebDriverJS 2.53.1 +// Project: https://github.com/SeleniumHQ/selenium/tree/master/javascript/node/selenium-webdriver +// Definitions by: Bill Armstrong , Yuki Kokubun , Craig Nishina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace chrome { @@ -19,8 +19,7 @@ declare namespace chrome { * {@code null} to use the currently active flow. * @constructor */ - constructor(opt_config?: webdriver.Capabilities, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: Options, opt_service?: any, opt_flow?: webdriver.promise.ControlFlow); + constructor(opt_config?: Options|webdriver.Capabilities, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); } interface IOptionsValues { @@ -240,6 +239,53 @@ declare namespace chrome { setChromeLogFile(path: string): Options; + /** + * Sets the directory to store Chrome minidumps in. This option is only + * supported when ChromeDriver is running on Linux. + * @param {string} path The directory path. + * @return {!Options} A self reference. + */ + setChromeMinidumpPath(path: string): Options; + + + /** + * Configures Chrome to emulate a mobile device. For more information, refer + * to the ChromeDriver project page on [mobile emulation][em]. Configuration + * options include: + * + * - `deviceName`: The name of a pre-configured [emulated device][devem] + * - `width`: screen width, in pixels + * - `height`: screen height, in pixels + * - `pixelRatio`: screen pixel ratio + * + * __Example 1: Using a Pre-configured Device__ + * + * let options = new chrome.Options().setMobileEmulation( + * {deviceName: 'Google Nexus 5'}); + * + * let driver = new chrome.Driver(options); + * + * __Example 2: Using Custom Screen Configuration__ + * + * let options = new chrome.Options().setMobileEmulation({ + * width: 360, + * height: 640, + * pixelRatio: 3.0 + * }); + * + * let driver = new chrome.Driver(options); + * + * + * [em]: https://sites.google.com/a/chromium.org/chromedriver/mobile-emulation + * [devem]: https://developer.chrome.com/devtools/docs/device-mode + * + * @param {?({deviceName: string}| + * {width: number, height: number, pixelRatio: number})} config The + * mobile emulation configuration, or `null` to disable emulation. + * @return {!Options} A self reference. + */ + setMobileEmulation(config: any): Options; + /** * Sets the proxy settings for the new session. * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. @@ -255,21 +301,6 @@ declare namespace chrome { * @return {!webdriver.Capabilities} The capabilities. */ toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; - - - /** - * Converts this instance to its JSON wire protocol representation. Note this - * function is an implementation not intended for general use. - * @return {{args: !Array., - * binary: (string|undefined), - * detach: boolean, - * extensions: !Array., - * localState: (Object|undefined), - * logFile: (string|undefined), - * prefs: (Object|undefined)}} The JSON wire protocol representation - * of this instance. - */ - toJSON(): IOptionsValues; } /** @@ -348,8 +379,7 @@ declare namespace chrome { * configuration to use. * @return {!ServiceBuilder} A self reference. */ - setStdio(config: string): ServiceBuilder; - setStdio(config: any[]): ServiceBuilder; + setStdio(config: string|Array): ServiceBuilder; /** @@ -368,7 +398,7 @@ declare namespace chrome { * @throws {Error} If the driver exectuable was not specified and a default * could not be found on the current PATH. */ - build(): any; + build(): remote.DriverService; } /** @@ -377,395 +407,1325 @@ declare namespace chrome { * a ChromeDriver executable found on the system PATH. * @return {!remote.DriverService} The default ChromeDriver service. */ - function getDefaultService(): any; + function getDefaultService(): remote.DriverService; /** * Sets the default service to use for new ChromeDriver instances. * @param {!remote.DriverService} service The service to use. * @throws {Error} If the default service is currently running. */ - function setDefaultService(service: any): void; + function setDefaultService(service: remote.DriverService): void; } -declare namespace firefox { - /** - * Manages a Firefox subprocess configured for use with WebDriver. - */ - class Binary { - /** - * @param {string=} opt_exe Path to the Firefox binary to use. If not - * specified, will attempt to locate Firefox on the current system. - * @constructor - */ - constructor(opt_exe?: string); +declare namespace edge { - /** - * Add arguments to the command line used to start Firefox. - * @param {...(string|!Array.)} var_args Either the arguments to add as - * varargs, or the arguments as an array. - */ - addArguments(...var_args: string[]): void; - - - /** - * Launches Firefox and eturns a promise that will be fulfilled when the process - * terminates. - * @param {string} profile Path to the profile directory to use. - * @return {!promise.Promise.} A promise for the process result. - * @throws {Error} If this instance has already been started. - */ - launch(profile: string): webdriver.promise.Promise; - - - /** - * Kills the managed Firefox process. - * @return {!promise.Promise} A promise for when the process has terminated. - */ - kill(): webdriver.promise.Promise; - } - - /** - * A WebDriver client for Firefox. - * - * @extends {webdriver.WebDriver} - */ class Driver extends webdriver.WebDriver { - /** - * @param {(Options|webdriver.Capabilities|Object)=} opt_config The - * configuration options for this driver, specified as either an - * {@link Options} or {@link webdriver.Capabilities}, or as a raw hash - * object. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to - * schedule commands through. Defaults to the active flow object. - * @constructor - */ - constructor(opt_config?: webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); - constructor(opt_config?: any, opt_flow?: webdriver.promise.ControlFlow); + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@linkplain #getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, or + * {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; } /** - * Configuration options for the FirefoxDriver. + * Class for managing MicrosoftEdgeDriver specific options. */ class Options { - /** - * @constructor - */ - constructor(); - /** - * Sets the profile to use. The profile may be specified as a - * {@link Profile} object or as the path to an existing Firefox profile to use - * as a template. - * - * @param {(string|!Profile)} profile The profile to use. - * @return {!Options} A self reference. - */ - setProfile(profile: string): Options; - setProfile(profile: Profile): Options; + /** + * Extracts the MicrosoftEdgeDriver specific options from the given + * capabilities object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The MicrosoftEdgeDriver options. + */ + static fromCapabilities(cap: webdriver.Capabilities): Options; + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; - /** - * Sets the binary to use. The binary may be specified as the path to a Firefox - * executable, or as a {@link Binary} object. - * - * @param {(string|!Binary)} binary The binary to use. - * @return {!Options} A self reference. - */ - setBinary(binary: string): Options; - setBinary(binary: Binary): Options; + /** + * Sets the page load strategy for Edge. + * Supported values are "normal", "eager", and "none"; + * + * @param {string} pageLoadStrategy The page load strategy to use. + * @return {!Options} A self reference. + */ + setPageLoadStrategy(pageLoadStrategy: string): Options; - - /** - * Sets the logging preferences for the new session. - * @param {webdriver.logging.Preferences} prefs The logging preferences. - * @return {!Options} A self reference. - */ - setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; - - - /** - * Sets the proxy to use. - * - * @param {webdriver.ProxyConfig} proxy The proxy configuration to use. - * @return {!Options} A self reference. - */ - setProxy(proxy: webdriver.ProxyConfig): Options; - - - /** - * Converts these options to a {@link webdriver.Capabilities} instance. - * - * @return {!webdriver.Capabilities} A new capabilities object. - */ - toCapabilities(opt_remote?: any): webdriver.Capabilities; + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; } /** - * Models a Firefox proifle directory for use with the FirefoxDriver. The - * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} - * is called. + * Creates {@link remote.DriverService} instances that manage a + * MicrosoftEdgeDriver server in a child process. */ - class Profile { - /** - * @param {string=} opt_dir Path to an existing Firefox profile directory to - * use a template for this profile. If not specified, a blank profile will - * be used. - * @constructor - */ - constructor(opt_dir?: string); + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the MicrosoftEdgeDriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the + * MicrosoftEdgeDriver cannot be found on the PATH. + */ + constructor(opt_exe?: string); - /** - * Registers an extension to be included with this profile. - * @param {string} extension Path to the extension to include, as either an - * unpacked extension directory or the path to a xpi file. - */ - addExtension(extension: string): void; + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array.)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + /** + * Sets the port to start the MicrosoftEdgeDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; - /** - * Sets a desired preference for this profile. - * @param {string} key The preference key. - * @param {(string|number|boolean)} value The preference value. - * @throws {Error} If attempting to set a frozen preference. - */ - setPreference(key: string, value: string): void; - setPreference(key: string, value: number): void; - setPreference(key: string, value: boolean): void; + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; - - /** - * Returns the currently configured value of a profile preference. This does - * not include any defaults defined in the profile's template directory user.js - * file (if a template were specified on construction). - * @param {string} key The desired preference. - * @return {(string|number|boolean|undefined)} The current value of the - * requested preference. - */ - getPreference(key: string): any; - - - /** - * @return {number} The port this profile is currently configured to use, or - * 0 if the port will be selected at random when the profile is written - * to disk. - */ - getPort(): number; - - - /** - * Sets the port to use for the WebDriver extension loaded by this profile. - * @param {number} port The desired port, or 0 to use any free port. - */ - setPort(port: number): void; - - - /** - * @return {boolean} Whether the FirefoxDriver is configured to automatically - * accept untrusted SSL certificates. - */ - acceptUntrustedCerts(): boolean; - - - /** - * Sets whether the FirefoxDriver should automatically accept untrusted SSL - * certificates. - * @param {boolean} value . - */ - setAcceptUntrustedCerts(value: boolean): void; - - - /** - * Sets whether to assume untrusted certificates come from untrusted issuers. - * @param {boolean} value . - */ - setAssumeUntrustedCertIssuer(value: boolean): void; - - - /** - * @return {boolean} Whether to assume untrusted certs come from untrusted - * issuers. - */ - assumeUntrustedCertIssuer(): boolean; - - - /** - * Sets whether to use native events with this profile. - * @param {boolean} enabled . - */ - setNativeEventsEnabled(enabled: boolean): void; - - - /** - * Returns whether native events are enabled in this profile. - * @return {boolean} . - */ - nativeEventsEnabled(): boolean; - - - /** - * Writes this profile to disk. - * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver - * extension from the generated profile. Used to reduce the size of an - * {@link #encode() encoded profile} since the server will always install - * the extension itself. - * @return {!promise.Promise.} A promise for the path to the new - * profile directory. - */ - writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; - - - /** - * Encodes this profile as a zipped, base64 encoded directory. - * @return {!promise.Promise.} A promise for the encoded profile. - */ - encode(): webdriver.promise.Promise; + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; } + + /** + * Returns the default MicrosoftEdgeDriver service. If such a service has + * not been configured, one will be constructed using the default configuration + * for an MicrosoftEdgeDriver executable found on the system PATH. + * @return {!remote.DriverService} The default MicrosoftEdgeDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Sets the default service to use for new MicrosoftEdgeDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): void; } declare namespace executors { /** * Creates a command executor that uses WebDriver's JSON wire protocol. - * @param url The server's URL, or a promise that will resolve to that URL. - * @returns {!webdriver.CommandExecutor} The new command executor. + * @param {(string|!promise.Promise)} url The server's URL, + * or a promise that will resolve to that URL. + * @param {?string=} opt_proxy (optional) The URL of the HTTP proxy for the + * client to use. + * @returns {!./lib/command.Executor} The new command executor. */ - function createExecutor(url: string): webdriver.CommandExecutor; - function createExecutor(url: webdriver.promise.Promise): webdriver.CommandExecutor; + function createExecutor(url: string|webdriver.promise.Promise, opt_agent?: string, opt_proxy?: string): webdriver.Executor; +} + +declare namespace firefox { + /** + * Manages a Firefox subprocess configured for use with WebDriver. + */ + class Binary { + /** + * @param {string=} opt_exe Path to the Firefox binary to use. If not + * specified, will attempt to locate Firefox on the current system. + * @constructor + */ + constructor(opt_exe?: string); + + /** + * Add arguments to the command line used to start Firefox. + * @param {...(string|!Array.)} var_args Either the arguments to add as + * varargs, or the arguments as an array. + */ + addArguments(...var_args: string[]): void; + + + /** + * Launches Firefox and eturns a promise that will be fulfilled when the process + * terminates. + * @param {string} profile Path to the profile directory to use. + * @return {!promise.Promise.} A promise for the process result. + * @throws {Error} If this instance has already been started. + */ + launch(profile: string): webdriver.promise.Promise; + + + /** + * Kills the managed Firefox process. + * @return {!promise.Promise} A promise for when the process has terminated. + */ + kill(): webdriver.promise.Promise; + } + + /** + * Models a Firefox proifle directory for use with the FirefoxDriver. The + * {@code Proifle} directory uses an in-memory model until {@link #writeToDisk} + * is called. + */ + class Profile { + /** + * @param {string=} opt_dir Path to an existing Firefox profile directory to + * use a template for this profile. If not specified, a blank profile will + * be used. + * @constructor + */ + constructor(opt_dir?: string); + + /** + * Registers an extension to be included with this profile. + * @param {string} extension Path to the extension to include, as either an + * unpacked extension directory or the path to a xpi file. + */ + addExtension(extension: string): void; + + + /** + * Sets a desired preference for this profile. + * @param {string} key The preference key. + * @param {(string|number|boolean)} value The preference value. + * @throws {Error} If attempting to set a frozen preference. + */ + setPreference(key: string, value: string): void; + setPreference(key: string, value: number): void; + setPreference(key: string, value: boolean): void; + + + /** + * Returns the currently configured value of a profile preference. This does + * not include any defaults defined in the profile's template directory user.js + * file (if a template were specified on construction). + * @param {string} key The desired preference. + * @return {(string|number|boolean|undefined)} The current value of the + * requested preference. + */ + getPreference(key: string): any; + + + /** + * @return {number} The port this profile is currently configured to use, or + * 0 if the port will be selected at random when the profile is written + * to disk. + */ + getPort(): number; + + + /** + * Sets the port to use for the WebDriver extension loaded by this profile. + * @param {number} port The desired port, or 0 to use any free port. + */ + setPort(port: number): void; + + + /** + * @return {boolean} Whether the FirefoxDriver is configured to automatically + * accept untrusted SSL certificates. + */ + acceptUntrustedCerts(): boolean; + + + /** + * Sets whether the FirefoxDriver should automatically accept untrusted SSL + * certificates. + * @param {boolean} value . + */ + setAcceptUntrustedCerts(value: boolean): void; + + + /** + * Sets whether to assume untrusted certificates come from untrusted issuers. + * @param {boolean} value . + */ + setAssumeUntrustedCertIssuer(value: boolean): void; + + + /** + * @return {boolean} Whether to assume untrusted certs come from untrusted + * issuers. + */ + assumeUntrustedCertIssuer(): boolean; + + + /** + * Sets whether to use native events with this profile. + * @param {boolean} enabled . + */ + setNativeEventsEnabled(enabled: boolean): void; + + + /** + * Returns whether native events are enabled in this profile. + * @return {boolean} . + */ + nativeEventsEnabled(): boolean; + + + /** + * Writes this profile to disk. + * @param {boolean=} opt_excludeWebDriverExt Whether to exclude the WebDriver + * extension from the generated profile. Used to reduce the size of an + * {@link #encode() encoded profile} since the server will always install + * the extension itself. + * @return {!promise.Promise.} A promise for the path to the new + * profile directory. + */ + writeToDisk(opt_excludeWebDriverExt?: boolean): webdriver.promise.Promise; + + + /** + * Encodes this profile as a zipped, base64 encoded directory. + * @return {!promise.Promise.} A promise for the encoded profile. + */ + encode(): webdriver.promise.Promise; + } + + /** + * Configuration options for the FirefoxDriver. + */ + class Options { + /** + * Sets the profile to use. The profile may be specified as a + * {@link Profile} object or as the path to an existing Firefox profile to use + * as a template. + * + * @param {(string|!Profile)} profile The profile to use. + * @return {!Options} A self reference. + */ + setProfile(profile: string|any): Options; + + /** + * Sets the binary to use. The binary may be specified as the path to a Firefox + * executable, or as a {@link Binary} object. + * + * @param {(string|!Binary)} binary The binary to use. + * @return {!Options} A self reference. + */ + setBinary(binary: string|any): Options; + + /** + * Sets the logging preferences for the new session. + * @param {logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPreferences(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy to use. + * + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Sets whether to use Mozilla's Marionette to drive the browser. + * + * @see https://developer.mozilla.org/en-US/docs/Mozilla/QA/Marionette/WebDriver + */ + useMarionette(marionette: any): Options; + + /** + * Converts these options to a {@link capabilities.Capabilities} instance. + * + * @return {!capabilities.Capabilities} A new capabilities object. + */ + toCapabilities(): webdriver.Capabilities; + } + + /** + * @return {string} . + * @throws {Error} + */ + function findWires(): string; + + /** + * @param {(string|!Binary)} binary . + * @return {!remote.DriverService} . + */ + function createWiresService(binary: string|any): remote.DriverService; + + /** + * @param {(Profile|string)} profile The profile to prepare. + * @param {number} port The port the FirefoxDriver should listen on. + * @return {!Promise} a promise for the path to the profile directory. + */ + function prepareProfile(profile: string|any, port: number): any; + + /** + * A WebDriver client for Firefox. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|capabilities.Capabilities|Object)=} opt_config The + * configuration options for this driver, specified as either an + * {@link Options} or {@link capabilities.Capabilities}, or as a raw hash + * object. + * @param {promise.ControlFlow=} opt_flow The flow to + * schedule commands through. Defaults to the active flow object. + */ + constructor(opt_config?: Options|webdriver.Capabilities|Object, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace http { + /** + * Converts a headers map to a HTTP header block string. + * @param {!Map} headers The map to convert. + * @return {string} The headers as a string. + */ + function headersToString(headers: any): string; + + /** + * Represents a HTTP request message. This class is a "partial" request and only + * defines the path on the server to send a request to. It is each client's + * responsibility to build the full URL for the final request. + * @final + */ + class HttpRequest { + /** + * @param {string} method The HTTP method to use for the request. + * @param {string} path The path on the server to send the request to. + * @param {Object=} opt_data This request's non-serialized JSON payload data. + */ + constructor(method: string, path: string, opt_data?: Object); + + /** @override */ + toString(): string; + } + + /** + * Represents a HTTP response message. + * @final + */ + class HttpResponse { + /** + * @param {number} status The response code. + * @param {!Object} headers The response headers. All header names + * will be converted to lowercase strings for consistent lookups. + * @param {string} body The response body. + */ + constructor(status: number, headers: Object, body: string); + + /** @override */ + toString(): string; + } + + + function post(path: string): any; + function del(path: string): any; + function get(path: string): any; + function resource(method: string, path: string): any; + + /** + * A basic HTTP client used to send messages to a remote end. + */ + class HttpClient { + /** + * @param {string} serverUrl URL for the WebDriver server to send commands to. + * @param {http.Agent=} opt_agent The agent to use for each request. + * Defaults to `http.globalAgent`. + * @param {?string=} opt_proxy The proxy to use for the connection to the + * server. Default is to use no proxy. + */ + constructor(serverUrl: string, opt_agent?: any, opt_proxy?: string); + + /** + * Sends a request to the server. The client will automatically follow any + * redirects returned by the server, fulfilling the returned promise with the + * final response. + * + * @param {!HttpRequest} httpRequest The request to send. + * @return {!promise.Promise} A promise that will be fulfilled + * with the server's response. + */ + send(httpRequest: HttpRequest): webdriver.promise.Promise; + } + + /** + * Sends a single HTTP request. + * @param {!Object} options The request options. + * @param {function(!HttpResponse)} onOk The function to call if the + * request succeeds. + * @param {function(!Error)} onError The function to call if the request fails. + * @param {?string=} opt_data The data to send with the request. + * @param {?string=} opt_proxy The proxy server to use for the request. + */ + function sendRequest(options: Object, onOk: any, onError: any, opt_data?: string, opt_proxy?: string): any; + + /** + * A command executor that communicates with the server using HTTP + JSON. + * + * By default, each instance of this class will use the legacy wire protocol + * from [Selenium project][json]. The executor will automatically switch to the + * [W3C wire protocol][w3c] if the remote end returns a compliant response to + * a new session command. + * + * [json]: https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * [w3c]: https://w3c.github.io/webdriver/webdriver-spec.html + * + * @implements {cmd.Executor} + */ + class Executor { + /** + * @param {!HttpClient} client The client to use for sending requests to the + * server. + */ + constructor(client: HttpClient); + + /** + * Defines a new command for use with this executor. When a command is sent, + * the {@code path} will be preprocessed using the command's parameters; any + * path segments prefixed with ":" will be replaced by the parameter of the + * same name. For example, given "/person/:name" and the parameters + * "{name: 'Bob'}", the final command path will be "/person/Bob". + * + * @param {string} name The command name. + * @param {string} method The HTTP method to use when sending this command. + * @param {string} path The path to send the command to, relative to + * the WebDriver server's command root and of the form + * "/path/:variable/segment". + */ + defineCommand(name: string, method: string, path: string): void; + + /** @override */ + execute(command: any): any; + } + + /** + * @param {string} str . + * @return {?} . + */ + function tryParse(str: string): any; + + /** + * Callback used to parse {@link HttpResponse} objects from a + * {@link HttpClient}. + * @param {!HttpResponse} httpResponse The HTTP response to parse. + * @param {boolean} w3c Whether the response should be processed using the + * W3C wire protocol. + * @return {{value: ?}} The parsed response. + * @throws {WebDriverError} If the HTTP response is an error. + */ + function parseHttpResponse(httpResponse: HttpResponse, w3c: boolean): any; + + /** + * Builds a fully qualified path using the given set of command parameters. Each + * path segment prefixed with ':' will be replaced by the value of the + * corresponding parameter. All parameters spliced into the path will be + * removed from the parameter map. + * @param {string} path The original resource path. + * @param {!Object<*>} parameters The parameters object to splice into the path. + * @return {string} The modified path. + */ + function buildPath(path: string, parameters: Object): string; +} + +declare namespace ie { + + /** + * A WebDriver client for Microsoft's Internet Explorer. + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } + + /** + * Class for managing IEDriver specific options. + */ + class Options { + constructor(); + + /** + * Extracts the IEDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The IEDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Whether to disable the protected mode settings check when the session is + * created. Disbling this setting may lead to significant instability as the + * browser may become unresponsive/hang. Only "best effort" support is provided + * when using this capability. + * + * For more information, refer to the IEDriver's + * [required system configuration](http://goo.gl/eH0Yi3). + * + * @param {boolean} ignoreSettings Whether to ignore protected mode settings. + * @return {!Options} A self reference. + */ + introduceFlakinessByIgnoringProtectedModeSettings(ignoreSettings: boolean): Options; + + /** + * Indicates whether to skip the check that the browser's zoom level is set to + * 100%. + * + * @param {boolean} ignore Whether to ignore the browser's zoom level settings. + * @return {!Options} A self reference. + */ + ignoreZoomSetting(ignore: boolean): Options; + + /** + * Sets the initial URL loaded when IE starts. This is intended to be used with + * {@link #ignoreProtectedModeSettings} to allow the user to initialize IE in + * the proper Protected Mode zone. Setting this option may cause browser + * instability or flaky and unresponsive code. Only "best effort" support is + * provided when using this option. + * + * @param {string} url The initial browser URL. + * @return {!Options} A self reference. + */ + initialBrowserUrl(url: string): Options; + + /** + * Configures whether to enable persistent mouse hovering (true by default). + * Persistent hovering is achieved by continuously firing mouse over events at + * the last location the mouse cursor has been moved to. + * + * @param {boolean} enable Whether to enable persistent hovering. + * @return {!Options} A self reference. + */ + enablePersistentHover(enable: boolean): Options; + + /** + * Configures whether the driver should attempt to remove obsolete + * {@linkplain webdriver.WebElement WebElements} from its internal cache on + * page navigation (true by default). Disabling this option will cause the + * driver to run with a larger memory footprint. + * + * @param {boolean} enable Whether to enable element reference cleanup. + * @return {!Options} A self reference. + */ + enableElementCacheCleanup(enable: boolean): Options; + + /** + * Configures whether to require the IE window to have input focus before + * performing any user interactions (i.e. mouse or keyboard events). This + * option is disabled by default, but delivers much more accurate interaction + * events when enabled. + * + * @param {boolean} require Whether to require window focus. + * @return {!Options} A self reference. + */ + requireWindowFocus(require: boolean): Options; + + /** + * Configures the timeout, in milliseconds, that the driver will attempt to + * located and attach to a newly opened instance of Internet Explorer. The + * default is zero, which indicates waiting indefinitely. + * + * @param {number} timeout How long to wait for IE. + * @return {!Options} A self reference. + */ + browserAttachTimeout(timeout: number): Options; + + /** + * Configures whether to launch Internet Explorer using the CreateProcess API. + * If this option is not specified, IE is launched using IELaunchURL, if + * available. For IE 8 and above, this option requires the TabProcGrowth + * registry value to be set to 0. + * + * @param {boolean} force Whether to use the CreateProcess API. + * @return {!Options} A self reference. + */ + forceCreateProcessApi(force: boolean): Options; + + /** + * Specifies command-line switches to use when launching Internet Explorer. + * This is only valid when used with {@link #forceCreateProcessApi}. + * + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Configures whether proxies should be configured on a per-process basis. If + * not set, setting a {@linkplain #setProxy proxy} will configure the system + * proxy. The default behavior is to use the system proxy. + * + * @param {boolean} enable Whether to enable per-process proxy settings. + * @return {!Options} A self reference. + */ + usePerProcessProxy(enable: boolean): Options; + + /** + * Configures whether to clear the cache, cookies, history, and saved form data + * before starting the browser. _Using this capability will clear session data + * for all running instances of Internet Explorer, including those started + * manually._ + * + * @param {boolean} cleanSession Whether to clear all session data on startup. + * @return {!Options} A self reference. + */ + ensureCleanSession(cleanSession: boolean): Options; + + /** + * Sets the path to the log file the driver should log to. + * @param {string} file The log file path. + * @return {!Options} A self reference. + */ + setLogFile(file: string): Options; + + /** + * Sets the IEDriverServer's logging {@linkplain Level level}. + * @param {Level} level The logging level. + * @return {!Options} A self reference. + */ + setLogLevel(level: webdriver.logging.Level): Options; + + /** + * Sets the IP address of the driver's host adapter. + * @param {string} host The IP address to use. + * @return {!Options} A self reference. + */ + setHost(host: string): Options; + + /** + * Sets the path of the temporary data directory to use. + * @param {string} path The log file path. + * @return {!Options} A self reference. + */ + setExtractPath(path: string): Options; + + /** + * Sets whether the driver should start in silent mode. + * @param {boolean} silent Whether to run in silent mode. + * @return {!Options} A self reference. + */ + silent(silent: boolean): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + +} + +declare namespace opera { + /** + * Creates {@link remote.DriverService} instances that manages an + * [OperaDriver](https://github.com/operasoftware/operachromiumdriver) + * server in a child process. + */ + class ServiceBuilder { + /** + * @param {string=} opt_exe Path to the server executable to use. If omitted, + * the builder will attempt to locate the operadriver on the current + * PATH. + * @throws {Error} If provided executable does not exist, or the operadriver + * cannot be found on the PATH. + */ + constructor(opt_exe?: string); + + /** + * Sets the port to start the OperaDriver on. + * @param {number} port The port to use, or 0 for any free port. + * @return {!ServiceBuilder} A self reference. + * @throws {Error} If the port is invalid. + */ + usingPort(port: number): ServiceBuilder; + + /** + * Sets the path of the log file the driver should log to. If a log file is + * not specified, the driver will log to stderr. + * @param {string} path Path of the log file to use. + * @return {!ServiceBuilder} A self reference. + */ + loggingTo(path: string): ServiceBuilder; + + /** + * Enables verbose logging. + * @return {!ServiceBuilder} A self reference. + */ + enableVerboseLogging(): ServiceBuilder; + + /** + * Silence sthe drivers output. + * @return {!ServiceBuilder} A self reference. + */ + silent(): ServiceBuilder; + + /** + * Defines the stdio configuration for the driver service. See + * {@code child_process.spawn} for more information. + * @param {(string|!Array)} + * config The configuration to use. + * @return {!ServiceBuilder} A self reference. + */ + setStdio(config: string|Array): ServiceBuilder; + + /** + * Defines the environment to start the server under. This settings will be + * inherited by every browser session started by the server. + * @param {!Object.} env The environment to use. + * @return {!ServiceBuilder} A self reference. + */ + withEnvironment(env: Object): ServiceBuilder; + + /** + * Creates a new DriverService using this instance's current configuration. + * @return {!remote.DriverService} A new driver service using this instance's + * current configuration. + * @throws {Error} If the driver exectuable was not specified and a default + * could not be found on the current PATH. + */ + build(): remote.DriverService; + } + + /** + * Sets the default service to use for new OperaDriver instances. + * @param {!remote.DriverService} service The service to use. + * @throws {Error} If the default service is currently running. + */ + function setDefaultService(service: remote.DriverService): any; + + /** + * Returns the default OperaDriver service. If such a service has not been + * configured, one will be constructed using the default configuration for + * a OperaDriver executable found on the system PATH. + * @return {!remote.DriverService} The default OperaDriver service. + */ + function getDefaultService(): remote.DriverService; + + /** + * Class for managing {@linkplain Driver OperaDriver} specific options. + */ + class Options { + /** + * Extracts the OperaDriver specific options from the given capabilities + * object. + * @param {!capabilities.Capabilities} caps The capabilities object. + * @return {!Options} The OperaDriver options. + */ + static fromCapabilities(caps: webdriver.Capabilities): Options; + + /** + * Add additional command line arguments to use when launching the Opera + * browser. Each argument may be specified with or without the "--" prefix + * (e.g. "--foo" and "foo"). Arguments with an associated value should be + * delimited by an "=": "foo=bar". + * @param {...(string|!Array.)} var_args The arguments to add. + * @return {!Options} A self reference. + */ + addArguments(...var_args: Array): Options; + + /** + * Add additional extensions to install when launching Opera. Each extension + * should be specified as the path to the packed CRX file, or a Buffer for an + * extension. + * @param {...(string|!Buffer|!Array.<(string|!Buffer)>)} var_args The + * extensions to add. + * @return {!Options} A self reference. + */ + addExtensions(...var_args: Array): Options; + + /** + * Sets the path to the Opera binary to use. On Mac OS X, this path should + * reference the actual Opera executable, not just the application binary. The + * binary path be absolute or relative to the operadriver server executable, but + * it must exist on the machine that will launch Opera. + * + * @param {string} path The path to the Opera binary to use. + * @return {!Options} A self reference. + */ + setOperaBinaryPath(path: string): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Sets the proxy settings for the new session. + * @param {capabilities.ProxyConfig} proxy The proxy configuration to use. + * @return {!Options} A self reference. + */ + setProxy(proxy: webdriver.ProxyConfig): Options; + + /** + * Converts this options instance to a {@link capabilities.Capabilities} + * object. + * @param {capabilities.Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!capabilities.Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities?: webdriver.Capabilities): webdriver.Capabilities; + } + + class Driver extends webdriver.WebDriver { + /** + * @param {(capabilities.Capabilities|Options)=} opt_config The configuration + * options. + * @param {remote.DriverService=} opt_service The session to use; will use + * the {@link getDefaultService default service} by default. + * @param {promise.ControlFlow=} opt_flow The control flow to use, + * or {@code null} to use the currently active flow. + */ + constructor(opt_config?: webdriver.Capabilities|Options, opt_service?: remote.DriverService, opt_flow?: webdriver.promise.ControlFlow); + + /** + * This function is a no-op as file detectors are not supported by this + * implementation. + * @override + */ + setFileDetector(): void; + } +} + +declare namespace remote { + /** + * A record object that defines the configuration options for a DriverService + * instance. + * + * @record + */ + interface ServiceOptions {} + + /** + * Manages the life and death of a native executable WebDriver server. + * + * It is expected that the driver server implements the + * https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol. + * Furthermore, the managed server should support multiple concurrent sessions, + * so that this class may be reused for multiple clients. + */ + class DriverService { + /** + * @param {string} executable Path to the executable to run. + * @param {!ServiceOptions} options Configuration options for the service. + */ + constructor(executable: string, options: ServiceOptions); + + /** + * @return {!promise.Promise} A promise that resolves to + * the server's address. + * @throws {Error} If the server has not been started. + */ + address(): webdriver.promise.Promise; + + /** + * Returns whether the underlying process is still running. This does not take + * into account whether the process is in the process of shutting down. + * @return {boolean} Whether the underlying service process is running. + */ + isRunning(): boolean; + + /** + * Starts the server if it is not already running. + * @param {number=} opt_timeoutMs How long to wait, in milliseconds, for the + * server to start accepting requests. Defaults to 30 seconds. + * @return {!promise.Promise} A promise that will resolve + * to the server's base URL when it has started accepting requests. If the + * timeout expires before the server has started, the promise will be + * rejected. + */ + start(opt_timeoutMs?: number): webdriver.promise.Promise; + + /** + * Stops the service if it is not currently running. This function will kill + * the server immediately. To synchronize with the active control flow, use + * {@link #stop()}. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + kill(): webdriver.promise.Promise; + + /** + * Schedules a task in the current control flow to stop the server if it is + * currently running. + * @return {!promise.Promise} A promise that will be resolved when + * the server has been stopped. + */ + stop(): webdriver.promise.Promise; + } +} + +declare namespace safari { + class Server {} + + /** + * @return {!Promise} A promise that will resolve with the path + * to Safari on the current system. + */ + function findSafariExecutable(): any; + + /** + * @param {string} serverUrl The URL to connect to. + * @return {!Promise} A promise for the path to a file that Safari can + * open on start-up to trigger a new connection to the WebSocket server. + */ + function createConnectFile(serverUrl: string): any; + + /** + * Deletes all session data files if so desired. + * @param {!Object} desiredCapabilities . + * @return {!Array} A list of promises for the deleted files. + */ + function cleanSession(desiredCapabilities: webdriver.Capabilities): any[]; + + /** @return {string} . */ + function getRandomString(): string; + + /** + * @implements {command.Executor} + */ + class CommandExecutor { + } + + /** + * Configuration options specific to the {@link Driver SafariDriver}. + */ + class Options { + /** + * Extracts the SafariDriver specific options from the given capabilities + * object. + * @param {!Capabilities} capabilities The capabilities object. + * @return {!Options} The ChromeDriver options. + */ + static fromCapabilities(capabilities: webdriver.Capabilities): Options; + + /** + * Sets whether to force Safari to start with a clean session. Enabling this + * option will cause all global browser data to be deleted. + * @param {boolean} clean Whether to make sure the session has no cookies, + * cache entries, local storage, or databases. + * @return {!Options} A self reference. + */ + setCleanSession(clean: boolean): Options; + + /** + * Sets the logging preferences for the new session. + * @param {!./lib/logging.Preferences} prefs The logging preferences. + * @return {!Options} A self reference. + */ + setLoggingPrefs(prefs: webdriver.logging.Preferences): Options; + + /** + * Converts this options instance to a {@link Capabilities} object. + * @param {Capabilities=} opt_capabilities The capabilities to + * merge these options into, if any. + * @return {!Capabilities} The capabilities. + */ + toCapabilities(opt_capabilities: webdriver.Capabilities): webdriver.Capabilities; + } + + /** + * A WebDriver client for Safari. This class should never be instantiated + * directly; instead, use the {@linkplain ./builder.Builder Builder}: + * + * var driver = new Builder() + * .forBrowser('safari') + * .build(); + * + */ + class Driver extends webdriver.WebDriver { + /** + * @param {(Options|Capabilities)=} opt_config The configuration + * options for the new session. + * @param {promise.ControlFlow=} opt_flow The control flow to create + * the driver under. + */ + constructor(opt_config?: Options|webdriver.Capabilities, opt_flow?: webdriver.promise.ControlFlow); + + } } declare namespace webdriver { namespace error { - interface IErrorCode { - SUCCESS: number; + class IError extends Error { + constructor(opt_error?: string); - NO_SUCH_ELEMENT: number; - NO_SUCH_FRAME: number; - UNKNOWN_COMMAND: number; - UNSUPPORTED_OPERATION: number; // Alias for UNKNOWN_COMMAND. - STALE_ELEMENT_REFERENCE: number; - ELEMENT_NOT_VISIBLE: number; - INVALID_ELEMENT_STATE: number; - UNKNOWN_ERROR: number; - ELEMENT_NOT_SELECTABLE: number; - JAVASCRIPT_ERROR: number; - XPATH_LOOKUP_ERROR: number; - TIMEOUT: number; - NO_SUCH_WINDOW: number; - INVALID_COOKIE_DOMAIN: number; - UNABLE_TO_SET_COOKIE: number; - MODAL_DIALOG_OPENED: number; - UNEXPECTED_ALERT_OPEN: number; - NO_SUCH_ALERT: number; - NO_MODAL_DIALOG_OPEN: number; - SCRIPT_TIMEOUT: number; - INVALID_ELEMENT_COORDINATES: number; - IME_NOT_AVAILABLE: number; - IME_ENGINE_ACTIVATION_FAILED: number; - INVALID_SELECTOR_ERROR: number; - SESSION_NOT_CREATED: number; - MOVE_TARGET_OUT_OF_BOUNDS: number; - SQL_DATABASE_ERROR: number; - INVALID_XPATH_SELECTOR: number; - INVALID_XPATH_SELECTOR_RETURN_TYPE: number; - // The following error codes are derived straight from HTTP return codes. - METHOD_NOT_ALLOWED: number; + code(): number; } - var ErrorCode: IErrorCode; + /** + * The base WebDriver error type. This error type is only used directly when a + * more appropriate category is not defined for the offending error. + */ + class WebDriverError extends IError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } /** - * Error extension that includes error status codes from the WebDriver wire - * protocol: - * http://code.google.com/p/selenium/wiki/JsonWireProtocol#Response_Status_Codes - * - * @extends {Error} + * An attempt was made to select an element that cannot be selected. */ - class Error { + class ElementNotSelectableError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Constructors + /** + * An element command could not be completed because the element is not visible + * on the page. + */ + class ElementNotVisibleError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * @param {!bot.ErrorCode} code The error's status code. - * @param {string=} opt_message Optional error message. - * @constructor - */ - constructor(code: number, opt_message?: string); + /** + * The arguments passed to a command are either invalid or malformed. + */ + class InvalidArgumentError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An illegal attempt was made to set a cookie under a different domain than + * the current page. + */ + class InvalidCookieDomainError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Static Properties + /** + * The coordinates provided to an interactions operation are invalid. + */ + class InvalidElementCoordinatesError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Status strings enumerated in the W3C WebDriver working draft. - * @enum {string} - * @see http://www.w3.org/TR/webdriver/#status-codes - */ - static State: { - ELEMENT_NOT_SELECTABLE: string; - ELEMENT_NOT_VISIBLE: string; - IME_ENGINE_ACTIVATION_FAILED: string; - IME_NOT_AVAILABLE: string; - INVALID_COOKIE_DOMAIN: string; - INVALID_ELEMENT_COORDINATES: string; - INVALID_ELEMENT_STATE: string; - INVALID_SELECTOR: string; - JAVASCRIPT_ERROR: string; - MOVE_TARGET_OUT_OF_BOUNDS: string; - NO_SUCH_ALERT: string; - NO_SUCH_DOM: string; - NO_SUCH_ELEMENT: string; - NO_SUCH_FRAME: string; - NO_SUCH_WINDOW: string; - SCRIPT_TIMEOUT: string; - SESSION_NOT_CREATED: string; - STALE_ELEMENT_REFERENCE: string; - SUCCESS: string; - TIMEOUT: string; - UNABLE_TO_SET_COOKIE: string; - UNEXPECTED_ALERT_OPEN: string; - UNKNOWN_COMMAND: string; - UNKNOWN_ERROR: string; - UNSUPPORTED_OPERATION: string; - }; + /** + * An element command could not be completed because the element is in an + * invalid state, e.g. attempting to click an element that is no longer attached + * to the document. + */ + class InvalidElementStateError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * Argument was an invalid selector. + */ + class InvalidSelectorError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Properties + /** + * Occurs when a command is directed to a session that does not exist. + */ + class NoSuchSessionError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * This error's status code. - * @type {!bot.ErrorCode} - */ - code: number; + /** + * An error occurred while executing JavaScript supplied by the user. + */ + class JavascriptError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @type {string} */ - state: string; + /** + * The target for mouse interaction is not in the browser’s viewport and cannot + * be brought into that viewport. + */ + class MoveTargetOutOfBoundsError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - message: string; + /** + * An attempt was made to operate on a modal dialog when one was not open. + */ + class NoSuchAlertError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - name: string; + /** + * An element could not be located on the page using the given search + * parameters. + */ + class NoSuchElementError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @override */ - stack: string; + /** + * A request to switch to a frame could not be satisfied because the frame + * could not be found. + */ + class NoSuchFrameError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** - * Flag used for duck-typing when this code is embedded in a Firefox extension. - * This is required since an Error thrown in one component and then reported - * to another will fail instanceof checks in the second component. - * @type {boolean} - */ - isAutomationError: boolean; + /** + * A request to switch to a window could not be satisfied because the window + * could not be found. + */ + class NoSuchWindowError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * A script did not complete before its timeout expired. + */ + class ScriptTimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //region Methods + /** + * A new session could not be created. + */ + class SessionNotCreatedError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - /** @return {string} The string representation of this error. */ - toString(): string; + /** + * An element command failed because the referenced element is no longer + * attached to the DOM. + */ + class StaleElementReferenceError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } - //endregion + /** + * An operation did not completErrorCodee before its timeout expired. + */ + class TimeoutError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A request to set a cookie’s value could not be satisfied. + */ + class UnableToSetCookieError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A screen capture operation was not possible. + */ + class UnableToCaptureScreenError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * A modal dialog was open, blocking this operation. + */ + class UnexpectedAlertOpenError extends WebDriverError { + /** + * @param {string=} opt_error the error message, if any. + * @param {string=} opt_text the text of the open dialog, if available. + */ + constructor(opt_error?: string, opt_text?: string); + + /** + * @return {(string|undefined)} The text displayed with the unhandled alert, + * if available. + */ + getAlertText(): string; + } + + /** + * A command could not be executed because the remote end is not aware of it. + */ + class UnknownCommandError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * The requested command matched a known URL but did not match an method for + * that URL. + */ + class UnknownMethodError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); + } + + /** + * Reports an unsupport operation. + */ + class UnsupportedOperationError extends WebDriverError { + /** @param {string=} opt_error the error message, if any. */ + constructor(opt_error?: string); } } @@ -776,48 +1736,96 @@ declare namespace webdriver { * @typedef {Object.} */ class Preferences { - setLevel(type: string, level: ILevel): void; + setLevel(type: string|Type, level: Level|string|number): void; toJSON(): { [key: string]: string }; } - interface IType { - /** Logs originating from the browser. */ - BROWSER: string; - /** Logs from a WebDriver client. */ - CLIENT: string; - /** Logs from a WebDriver implementation. */ - DRIVER: string; - /** Logs related to performance. */ - PERFORMANCE: string; - /** Logs from the remote server. */ - SERVER: string; - } - /** * Common log types. * @enum {string} */ - var Type: IType; + enum Type { + /** Logs originating from the browser. */ + BROWSER, + /** Logs from a WebDriver client. */ + CLIENT, + /** Logs from a WebDriver implementation. */ + DRIVER, + /** Logs related to performance. */ + PERFORMANCE, + /** Logs from the remote server. */ + SERVER + } /** - * Logging levels. - * @enum {{value: number, name: webdriver.logging.LevelName}} + * Defines a message level that may be used to control logging output. + * + * @final */ - interface ILevel { - value: number; - name: string; - } + class Level { + name_: string; + value_: number; + /** + * @param {string} name the level's name. + * @param {number} level the level's numeric value. + */ + constructor(name: string, level: number); - interface ILevelValues { - ALL: ILevel; - DEBUG: ILevel; - INFO: ILevel; - WARNING: ILevel; - SEVERE: ILevel; - OFF: ILevel; - } + /** @override */ + toString(): string; - var Level: ILevelValues; + /** This logger's name. */ + name(): string; + + /** The numeric log level. */ + value(): number; + + /** + * Indicates no log messages should be recorded. + * @const + */ + static OFF: Level; + /** + * Log messages with a level of `1000` or higher. + * @const + */ + static SEVERE: Level; + /** + * Log messages with a level of `900` or higher. + * @const + */ + static WARNING: Level; + /** + * Log messages with a level of `800` or higher. + * @const + */ + static INFO: Level; + /** + * Log messages with a level of `700` or higher. + * @const + */ + static DEBUG: Level; + /** + * Log messages with a level of `500` or higher. + * @const + */ + static FINE: Level; + /** + * Log messages with a level of `400` or higher. + * @const + */ + static FINER: Level; + /** + * Log messages with a level of `300` or higher. + * @const + */ + static FINEST: Level; + /** + * Indicates all log messages should be recorded. + * @const + */ + static ALL: Level; + } /** * Converts a level name or value to a {@link webdriver.logging.Level} value. @@ -827,75 +1835,209 @@ declare namespace webdriver { * convert . * @return {!webdriver.logging.Level} The converted level. */ - function getLevel(nameOrValue: string): ILevel; - function getLevel(nameOrValue: number): ILevel; + function getLevel(nameOrValue: string|number): Level; interface IEntryJSON { - level: string; - message: string; - timestamp: number; - type: string; + level: string; + message: string; + timestamp: number; + type: string; } /** * A single log entry. */ class Entry { + /** + * @param {(!webdriver.logging.Level|string)} level The entry level. + * @param {string} message The log message. + * @param {number=} opt_timestamp The time this entry was generated, in + * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the + * current time will be used. + * @param {string=} opt_type The log type, if known. + * @constructor + */ + constructor(level: Level|string|number, message: string, opt_timestamp?:number, opt_type?:string|Type); - //region Constructors + /** @type {!webdriver.logging.Level} */ + level: Level; - /** - * @param {(!webdriver.logging.Level|string)} level The entry level. - * @param {string} message The log message. - * @param {number=} opt_timestamp The time this entry was generated, in - * milliseconds since 0:00:00, January 1, 1970 UTC. If omitted, the - * current time will be used. - * @param {string=} opt_type The log type, if known. - * @constructor - */ - constructor(level: ILevel, message: string, opt_timestamp?:number, opt_type?:string); - constructor(level: string, message: string, opt_timestamp?:number, opt_type?:string); + /** @type {string} */ + message: string; - //endregion + /** @type {number} */ + timestamp: number; - //region Public Properties + /** @type {string} */ + type: string; - /** @type {!webdriver.logging.Level} */ - level: ILevel; + /** + * @return {{level: string, message: string, timestamp: number, + * type: string}} The JSON representation of this entry. + */ + toJSON(): IEntryJSON; + } - /** @type {string} */ - message: string; + /** + * An object used to log debugging messages. Loggers use a hierarchical, + * dot-separated naming scheme. For instance, "foo" is considered the parent of + * the "foo.bar" and an ancestor of "foo.bar.baz". + * + * Each logger may be assigned a {@linkplain #setLevel log level}, which + * controls which level of messages will be reported to the + * {@linkplain #addHandler handlers} attached to this instance. If a log level + * is not explicitly set on a logger, it will inherit its parent. + * + * This class should never be directly instantiated. Instead, users should + * obtain logger references using the {@linkplain ./logging.getLogger() + * getLogger()} function. + * + * @final + */ + class Logger { + /** + * @param {string} name the name of this logger. + * @param {Level=} opt_level the initial level for this logger. + */ + constructor(name: string, opt_level?: Level); - /** @type {number} */ - timestamp: number; + /** @private {string} */ + name_: string; + /** @private {Level} */ + level_: Level; + /** @private {Logger} */ + parent_: Logger; + /** @private {Set} */ + handlers_: any; - /** @type {string} */ - type: string; + /** @return {string} the name of this logger. */ + getName(): string; - //endregion + /** + * @param {Level} level the new level for this logger, or `null` if the logger + * should inherit its level from its parent logger. + */ + setLevel(level: Level): void; - //region Static Methods + /** @return {Level} the log level for this logger. */ + getLevel(): Level; - /** - * Converts a {@link goog.debug.LogRecord} into a - * {@link webdriver.logging.Entry}. - * @param {!goog.debug.LogRecord} logRecord The record to convert. - * @param {string=} opt_type The log type. - * @return {!webdriver.logging.Entry} The converted entry. - */ - static fromClosureLogRecord(logRecord: any, opt_type?:string): Entry; + /** + * @return {!Level} the effective level for this logger. + */ + getEffectiveLevel(): Level; - //endregion + /** + * @param {!Level} level the level to check. + * @return {boolean} whether messages recorded at the given level are loggable + * by this instance. + */ + isLoggable(level: Level): boolean; - //region Methods + /** + * Adds a handler to this logger. The handler will be invoked for each message + * logged with this instance, or any of its descendants. + * + * @param {function(!Entry)} handler the handler to add. + */ + addHandler(handler: any): void; - /** - * @return {{level: string, message: string, timestamp: number, - * type: string}} The JSON representation of this entry. - */ - toJSON(): IEntryJSON; + /** + * Removes a handler from this logger. + * + * @param {function(!Entry)} handler the handler to remove. + * @return {boolean} whether a handler was successfully removed. + */ + removeHandler(handler: any): void; - //endregion + /** + * Logs a message at the given level. The message may be defined as a string + * or as a function that will return the message. If a function is provided, + * it will only be invoked if this logger's + * {@linkplain #getEffectiveLevel() effective log level} includes the given + * `level`. + * + * @param {!Level} level the level at which to log the message. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + log(level: Level, loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.SEVERE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + severe(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.WARNING} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + warning(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.INFO} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + info(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.DEBUG} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + debug(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINE} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + fine(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINER} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finer(loggable: string|Function): void; + + /** + * Logs a message at the {@link Level.FINEST} log level. + * @param {(string|function(): string)} loggable the message to log, or a + * function that will return the message. + */ + finest(loggable: string|Function): void; + } + + /** + * Maintains a collection of loggers. + * + * @final + */ + class LogManager { + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + getLogger(name: string): Logger; + + /** + * Creates a new logger. + * + * @param {string} name the logger's name. + * @param {!Logger} parent the logger's parent. + * @return {!Logger} the new logger. + * @private + */ + createLogger_(name: string, parent: Logger): Logger; } } @@ -908,15 +2050,15 @@ declare namespace webdriver { * input array's promises are rejected, the returned promise will be rejected * with the same reason. * - * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * @param {!Array<(T|!ManagedPromise)>} arr An array of * promises to wait on. - * @return {!webdriver.promise.Promise.>} A promise that is + * @return {!ManagedPromise>} A promise that is * fulfilled with an array containing the fulfilled values of the * input array, or rejected with the same reason as the first * rejected value. * @template T */ - function all(arr: Promise[]): Promise; + function all(arr: Array>): Promise; /** * Invokes the appropriate callback function as soon as a promised @@ -939,9 +2081,9 @@ declare namespace webdriver { * Creates a new control flow. The provided callback will be invoked as the * first task within the new flow, with the flow as its sole argument. Returns * a promise that resolves to the callback result. - * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * @param {function(!ControlFlow)} callback The entry point * to the newly created flow. - * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * @return {!ManagedPromise} A promise that resolves to the callback * result. */ function createFlow(callback: (flow: ControlFlow) => R): Promise; @@ -966,7 +2108,7 @@ declare namespace webdriver { * Creates a promise that will be resolved at a set time in the future. * @param {number} ms The amount of time, in milliseconds, to wait before * resolving the promise. - * @return {!webdriver.promise.Promise} The promise. + * @return {!ManagedPromise} The promise. */ function delayed(ms: number): Promise; @@ -974,26 +2116,25 @@ declare namespace webdriver { * Calls a function for each element in an array, and if the function returns * true adds the element to a new array. * - *

    If the return value of the filter function is a promise, this function + * If the return value of the filter function is a promise, this function * will wait for it to be fulfilled before determining whether to insert the * element into the new array. * - *

    If the filter function throws or returns a rejected promise, the promise + * If the filter function throws or returns a rejected promise, the promise * returned by this function will be rejected with the same reason. Only the * first failure will be reported; all subsequent errors will be silently * ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ( - * boolean|webdriver.promise.Promise.)} fn The function + * @param {function(this: SELF, TYPE, number, !Array): ( + * boolean|ManagedPromise)} fn The function * to call for each element in the array. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise; - function filter(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function filter(arr: Array|Promise>, fn: (element: T, type: any, index: number, array: T[]) => any, opt_self?: any): Promise; /** * Creates a new deferred object. @@ -1003,8 +2144,9 @@ declare namespace webdriver { /** * Creates a promise that has been resolved with the given value. - * @param {*=} opt_value The resolved value. - * @return {!webdriver.promise.Promise} The resolved promise. + * @param {T=} opt_value The resolved value. + * @return {!ManagedPromise} The resolved promise. + * @template T */ function fulfilled(opt_value?: T): Promise; @@ -1013,42 +2155,44 @@ declare namespace webdriver { * new array, which is used as the fulfillment value of the promise returned * by this function. * - *

    If the return value of the mapping function is a promise, this function + * If the return value of the mapping function is a promise, this function * will wait for it to be fulfilled before inserting it into the new array. * - *

    If the mapping function throws or returns a rejected promise, the + * If the mapping function throws or returns a rejected promise, the * promise returned by this function will be rejected with the same reason. * Only the first failure will be reported; all subsequent errors will be * silently ignored. * - * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * @param {!(Array|ManagedPromise>)} arr The * array to iterator over, or a promise that will resolve to said array. - * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * @param {function(this: SELF, TYPE, number, !Array): ?} fn The * function to call for each element in the array. This function should * expect three arguments (the element, the index, and the array itself. * @param {SELF=} opt_self The object to be used as the value of 'this' within * {@code fn}. * @template TYPE, SELF */ - function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise - function map(arr: Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): Promise + function map(arr: Array|Promise>, fn: (self: any, type: any, index: number, array: any[]) => any, opt_self?: any): Promise /** * Creates a promise that has been rejected with the given reason. * @param {*=} opt_reason The rejection reason; may be any value, but is * usually an Error or a string. - * @return {!webdriver.promise.Promise} The rejected promise. + * @return {!ManagedPromise} The rejected promise. + * @template T */ - function rejected(opt_reason?: any): Promise; + function rejected(opt_reason?: any): Promise; /** - * Wraps a function that is assumed to be a node-style callback as its final - * argument. This callback takes two arguments: an error value (which will be + * Wraps a function that expects a node-style callback as its final + * argument. This callback expects two arguments: an error value (which will be * null if the call succeeded), and the success value as the second argument. - * If the call fails, the returned promise will be rejected, otherwise it will - * be resolved with the result. + * The callback will the resolve or reject the returned promise, based on its + * arguments. * @param {!Function} fn The function to wrap. - * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * @param {...?} var_args The arguments to apply to the function, excluding the + * final callback. + * @return {!ManagedPromise} A promise that will be resolved with the * result of the provided function's callback. */ function checkedNodeCall(fn: Function, ...var_args: any[]): Promise; @@ -1059,37 +2203,35 @@ declare namespace webdriver { * fulfilled value back into {@code next}. Likewise, if a yielded promise is * rejected, the rejection error will be passed to {@code throw}. * - *

    Example 1: the Fibonacci Sequence. - *

    
    -         * webdriver.promise.consume(function* fibonacci() {
    -         *   var n1 = 1, n2 = 1;
    -         *   for (var i = 0; i < 4; ++i) {
    -         *     var tmp = yield n1 + n2;
    -         *     n1 = n2;
    -         *     n2 = tmp;
    -         *   }
    -         *   return n1 + n2;
    -         * }).then(function(result) {
    -         *   console.log(result);  // 13
    -         * });
    -         * 
    + * __Example 1:__ the Fibonacci Sequence. * - *

    Example 2: a generator that throws. - *

    
    -         * webdriver.promise.consume(function* () {
    -         *   yield webdriver.promise.delayed(250).then(function() {
    -         *     throw Error('boom');
    -         *   });
    -         * }).thenCatch(function(e) {
    -         *   console.log(e.toString());  // Error: boom
    -         * });
    -         * 
    + * promise.consume(function* fibonacci() { + * var n1 = 1, n2 = 1; + * for (var i = 0; i < 4; ++i) { + * var tmp = yield n1 + n2; + * n1 = n2; + * n2 = tmp; + * } + * return n1 + n2; + * }).then(function(result) { + * console.log(result); // 13 + * }); + * + * __Example 2:__ a generator that throws. + * + * promise.consume(function* () { + * yield promise.delayed(250).then(function() { + * throw Error('boom'); + * }); + * }).catch(function(e) { + * console.log(e.toString()); // Error: boom + * }); * * @param {!Function} generatorFn The generator function to execute. * @param {Object=} opt_self The object to use as "this" when invoking the * initial generator. * @param {...*} var_args Any arguments to pass to the initial generator. - * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * @return {!ManagedPromise} A promise that will resolve to the * generator's final result. * @throws {TypeError} If the given function is not a generator. */ @@ -1104,10 +2246,9 @@ declare namespace webdriver { * resolved successfully. * @param {Function=} opt_errback The function to call when the value is * rejected. - * @return {!webdriver.promise.Promise} A new promise. + * @return {!ManagedPromise} A new promise. */ - function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; - function when(value: Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; + function when(value: T|Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): Promise; /** * Returns a promise that will be resolved with the input value in a @@ -1120,19 +2261,19 @@ declare namespace webdriver { * Warning: This function makes no checks against objects that contain * cyclical references: * - * var value = {}; - * value['self'] = value; - * webdriver.promise.fullyResolved(value); // Stack overflow. + * var value = {}; + * value['self'] = value; + * promise.fullyResolved(value); // Stack overflow. * * @param {*} value The value to fully resolve. - * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * @return {!ManagedPromise} A promise for a fully resolved version * of the input value. */ function fullyResolved(value: any): Promise; /** * Changes the default flow to use when no others are active. - * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @param {!ControlFlow} flow The new default flow. * @throws {Error} If the default flow is not currently active. */ function setDefaultFlow(flow: ControlFlow): void; @@ -1141,265 +2282,181 @@ declare namespace webdriver { /** * Error used when the computation of a promise is cancelled. - * - * @extends {goog.debug.Error} - * @final */ - class CancellationError { - /** - * @param {string=} opt_msg The cancellation message. - * @constructor - */ - constructor(opt_msg?: string); - - name: string; - message: string; + class CancellationError extends Error { + /** + * @param {string=} opt_msg The cancellation message. + */ + constructor(opt_msg?: string); } interface IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } catch (ex) {
    -             *     console.error(ex);
    -             *   }
                  *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - - - /** - * Registers a listener to invoke when this promise is resolved, regardless - * of whether the promise's value was successfully computed. This function - * is synonymous with the {@code finally} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } finally {
    -             *     cleanUp();
    -             *   }
    -             *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenFinally(cleanUp);
    -             * 
    - * - * Note: similar to the {@code finally} clause, if the registered - * callback returns a rejected promise or throws an error, it will silently - * replace the rejection error (if any) from this promise: - *
    
    -             *   try {
    -             *     throw Error('one');
    -             *   } finally {
    -             *     throw Error('two');  // Hides Error: one
    -             *   }
    -             *
    -             *   webdriver.promise.rejected(Error('one'))
    -             *       .thenFinally(function() {
    -             *         throw Error('two');  // Hides Error: one
    -             *       });
    -             * 
    - * - * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled - * with the callback result. - * @template R - */ - thenFinally(callback: () => any): Promise; + catch(errback: Function): Promise; } /** - * Thenable is a promise-like object with a {@code then} method which may be - * used to schedule callbacks on a promised value. - * - * @interface - * @template T - */ + * Thenable is a promise-like object with a {@code then} method which may be + * used to schedule callbacks on a promised value. + * + * @interface + * @template T + */ class Thenable implements IThenable { /** - * Cancels the computation of this promise's value, rejecting the promise in the - * process. This method is a no-op if the promise has alreayd been resolved. + * Cancels the computation of this promise's value, rejecting the promise in + * the process. This method is a no-op if the promise has already been + * resolved. * - * @param {string=} opt_reason The reason this promise is being cancelled. + * @param {(string|Error)=} opt_reason The reason this promise is being + * cancelled. This value will be wrapped in a {@link CancellationError}. */ - cancel(opt_reason?: string): void; - + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; - /** * Registers listeners for when this instance is resolved. * - * @param opt_callback The + * @param {?(function(T): (R|IThenable))=} opt_callback The * function to call if this promise is successfully resolved. The function * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be + * @param {?(function(*): (R|IThenable))=} opt_errback + * The function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. + * @template R */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. - * - * @param opt_callback The - * function to call if this promise is successfully resolved. The function - * should expect a single argument: the promise's resolved value. - * @param opt_errback The - * function to call if this promise is rejected. The function should expect - * a single argument: the rejection reason. - * @return A new promise which will be - * resolved with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: (value: T) => R|IThenable, opt_errback?: (error: any) => R|IThenable): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous * with the {@code catch} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } catch (ex) {
    -             *     console.error(ex);
    -             *   }
                  *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenCatch(function(ex) {
    -             *     console.error(ex);
    -             *   });
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {function(*): (R|webdriver.promise.Promise.)} errback The function - * to call if this promise is rejected. The function should expect a single - * argument: the rejection reason. - * @return {!webdriver.promise.Promise.} A new promise which will be + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be * resolved with the result of the invoked callback. * @template R */ - thenCatch(errback: (error: any) => any): Promise; - + catch(errback: Function): Promise; /** * Registers a listener to invoke when this promise is resolved, regardless * of whether the promise's value was successfully computed. This function * is synonymous with the {@code finally} clause in a synchronous API: - *
    
    -             *   // Synchronous API:
    -             *   try {
    -             *     doSynchronousWork();
    -             *   } finally {
    -             *     cleanUp();
    -             *   }
                  *
    -             *   // Asynchronous promise API:
    -             *   doAsynchronousWork().thenFinally(cleanUp);
    -             * 
    + * // Synchronous API: + * try { + * doSynchronousWork(); + * } finally { + * cleanUp(); + * } * - * Note: similar to the {@code finally} clause, if the registered + * // Asynchronous promise API: + * doAsynchronousWork().finally(cleanUp); + * + * __Note:__ similar to the {@code finally} clause, if the registered * callback returns a rejected promise or throws an error, it will silently * replace the rejection error (if any) from this promise: - *
    
    -             *   try {
    -             *     throw Error('one');
    -             *   } finally {
    -             *     throw Error('two');  // Hides Error: one
    -             *   }
                  *
    -             *   webdriver.promise.rejected(Error('one'))
    -             *       .thenFinally(function() {
    -             *         throw Error('two');  // Hides Error: one
    -             *       });
    -             * 
    + * try { + * throw Error('one'); + * } finally { + * throw Error('two'); // Hides Error: one + * } * + * promise.rejected(Error('one')) + * .finally(function() { + * throw Error('two'); // Hides Error: one + * }); * - * @param {function(): (R|webdriver.promise.Promise.)} callback The function - * to call when this promise is resolved. - * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * @param {function(): (R|IThenable)} callback The function to call when + * this promise is resolved. + * @return {!ManagedPromise} A promise that will be fulfilled * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + finally(callback: Function): Promise; /** * Adds a property to a class prototype to allow runtime checks of whether - * instances of that class implement the Thenable interface. This function will - * also ensure the prototype's {@code then} function is exported from compiled - * code. - * @param {function(new: webdriver.promise.Thenable, ...[?])} ctor The + * instances of that class implement the Thenable interface. This function + * will also ensure the prototype's {@code then} function is exported from + * compiled code. + * @param {function(new: Thenable, ...?)} ctor The * constructor whose prototype to modify. */ static addImplementation(ctor: Function): void; - /** - * Checks if an object has been tagged for implementing the Thenable interface - * as defined by {@link webdriver.promise.Thenable.addImplementation}. + * Checks if an object has been tagged for implementing the Thenable + * interface as defined by {@link Thenable.addImplementation}. * @param {*} object The object to test. * @return {boolean} Whether the object is an implementation of the Thenable * interface. @@ -1432,12 +2489,11 @@ declare namespace webdriver { * function((T|IThenable|Thenable)=), * function(*=))} resolver * Function that is invoked immediately to begin computation of this - * promise's value. The function should accept a pair of callback functions, - * one for fulfilling the promise and another for rejecting it. - * @param {promise.ControlFlow=} opt_flow The control flow + * promise's value. The function should accept a pair of callback + * functions, one for fulfilling the promise and another for rejecting it. + * @param {ControlFlow=} opt_flow The control flow * this instance was created under. Defaults to the currently active flow. - * @constructor - */ + */ constructor(resolver: (onFulfilled: IFulfilledCallback, onRejected: IRejectedCallback)=>void, opt_flow?: ControlFlow); constructor(); // For angular-protractor/angular-protractor-tests.ts @@ -1450,7 +2506,7 @@ declare namespace webdriver { * {@code Error}, one will be created using the value's string * representation. */ - cancel(reason: any): void; + cancel(opt_reason?: string|Error): void; /** @return {boolean} Whether this promise's value is still being computed. */ isPending(): boolean; @@ -1468,23 +2524,7 @@ declare namespace webdriver { * @return A new promise which will be resolved * with the result of the invoked callback. */ - then(opt_callback?: (value: T) => Promise, opt_errback?: (error: any) => any): Promise; - - /** - * Registers listeners for when this instance is resolved. This function most - * overridden by subtypes. - * - * @param opt_callback The function to call if this promise is - * successfully resolved. The function should expect a single argument: the - * promise's resolved value. - * @param opt_errback The function to call if this promise is - * rejected. The function should expect a single argument: the rejection - * reason. - * @return A new promise which will be resolved - * with the result of the invoked callback. - */ - then(opt_callback?: (value: T) => R, opt_errback?: (error: any) => any): Promise; - + then(opt_callback?: Function, opt_errback?: Function): Promise; /** * Registers a listener for when this promise is rejected. This is synonymous @@ -1512,6 +2552,31 @@ declare namespace webdriver { */ thenCatch(errback: (error: any) => any): Promise; + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): Promise; + /** * Registers a listener to invoke when this promise is resolved, regardless @@ -1552,7 +2617,7 @@ declare namespace webdriver { * with the callback result. * @template R */ - thenFinally(callback: () => any): Promise; + thenFinally(callback: Function): Promise; //endregion } @@ -1791,107 +2856,6 @@ declare namespace webdriver { } } - namespace stacktrace { - /** - * Class representing one stack frame. - */ - class Frame { - /** - * @param {(string|undefined)} context Context object, empty in case of global - * functions or if the browser doesn't provide this information. - * @param {(string|undefined)} name Function name, empty in case of anonymous - * functions. - * @param {(string|undefined)} alias Alias of the function if available. For - * example the function name will be 'c' and the alias will be 'b' if the - * function is defined as a.b = function c() {};. - * @param {(string|undefined)} path File path or URL including line number and - * optionally column number separated by colons. - * @constructor - */ - constructor(context?: string, name?: string, alias?: string, path?: string); - - /** - * @return {string} The function name or empty string if the function is - * anonymous and the object field which it's assigned to is unknown. - */ - getName(): string; - - - /** - * @return {string} The url or empty string if it is unknown. - */ - getUrl(): string; - - - /** - * @return {number} The line number if known or -1 if it is unknown. - */ - getLine(): number; - - - /** - * @return {number} The column number if known and -1 if it is unknown. - */ - getColumn(): number; - - - /** - * @return {boolean} Whether the stack frame contains an anonymous function. - */ - isAnonymous(): boolean; - - - /** - * Converts this frame to its string representation using V8's stack trace - * format: http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi - * @return {string} The string representation of this frame. - * @override - */ - toString(): string; - } - - /** - * Stores a snapshot of the stack trace at the time this instance was created. - * The stack trace will always be adjusted to exclude this function call. - */ - class Snapshot { - /** - * @param {number=} opt_slice The number of frames to remove from the top of - * the generated stack trace. - * @constructor - */ - constructor(opt_slice?: number); - - /** - * @return {!Array.} The parsed stack trace. - */ - getStacktrace(): Frame[]; - } - - /** - * Formats an error's stack trace. - * @param {!(Error|goog.testing.JsUnitException)} error The error to format. - * @return {!(Error|goog.testing.JsUnitException)} The formatted error. - */ - function format(error: any): any; - - /** - * Gets the native stack trace if available otherwise follows the call chain. - * The generated trace will exclude all frames up to and including the call to - * this function. - * @return {!Array.} The frames of the stack trace. - */ - function get(): Frame[]; - - /** - * Whether the current browser supports stack traces. - * - * @type {boolean} - * @const - */ - var BROWSER_SUPPORTED: boolean; - } - namespace until { /** * Defines a condition to @@ -1915,32 +2879,31 @@ declare namespace webdriver { /** * Creates a condition that will wait until the input driver is able to switch - * to the designated frame. The target frame may be specified as: - *
      - *
    1. A numeric index into {@code window.frames} for the currently selected - * frame. - *
    2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME - * element on the current page. - *
    3. A locator which may be used to first locate a FRAME or IFRAME on the - * current page before attempting to switch to it. - *
    + * to the designated frame. The target frame may be specified as * - *

    Upon successful resolution of this condition, the driver will be left + * 1. a numeric index into + * [window.frames](https://developer.mozilla.org/en-US/docs/Web/API/Window.frames) + * for the currently selected frame. + * 2. a {@link ./webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + * 3. a locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + * + * Upon successful resolution of this condition, the driver will be left * focused on the new frame. * - * @param {!(number|webdriver.WebElement| - * webdriver.Locator|webdriver.By.Hash| - * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * @param {!(number|./webdriver.WebElement|By| + * function(!./webdriver.WebDriver): !./webdriver.WebElement)} frame * The frame identifier. - * @return {!until.Condition.} A new condition. + * @return {!Condition} A new condition. */ - function ableToSwitchToFrame(frame: number|WebElement|Locator|By.Hash|((webdriver: WebDriver)=>WebElement)): Condition; + function ableToSwitchToFrame(frame: number|WebElement|By|((webdriver: WebDriver)=>WebElement)): Condition; /** * Creates a condition that waits for an alert to be opened. Upon success, the * returned promise will be fulfilled with the handle for the opened alert. * - * @return {!until.Condition.} The new condition. + * @return {!Condition} The new condition. */ function alertIsPresent(): Condition; @@ -2000,13 +2963,12 @@ declare namespace webdriver { /** * Creates a condition that will loop until an element is - * {@link webdriver.WebDriver#findElement found} with the given locator. + * {@link ./webdriver.WebDriver#findElement found} with the given locator. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * to use. + * @param {!(By|Function)} locator The locator to use. * @return {!until.Condition.} The new condition. */ - function elementLocated(locator: Locator|By.Hash|Function): Condition; + function elementLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element's @@ -2039,7 +3001,7 @@ declare namespace webdriver { * * @param {!webdriver.WebElement} element The element to test. * @param {!RegExp} regex The regular expression to test against. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. * @see webdriver.WebDriver#getText */ function elementTextMatches(element: WebElement, regex: RegExp): Condition; @@ -2053,7 +3015,7 @@ declare namespace webdriver { * @return {!until.Condition.>} The new * condition. */ - function elementsLocated(locator: Locator|By.Hash|Function): Condition; + function elementsLocated(locator: By|Function): Condition; /** * Creates a condition that will wait for the given element to become stale. An @@ -2061,7 +3023,7 @@ declare namespace webdriver { * has loaded. * * @param {!webdriver.WebElement} element The element that should become stale. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function stalenessOf(element: WebElement): Condition; @@ -2080,7 +3042,7 @@ declare namespace webdriver { * given value. * * @param {string} title The expected page title. - * @return {!until.Condition.} The new condition. + * @return {!until.Condition} The new condition. */ function titleIs(title: string): Condition; @@ -2105,18 +3067,18 @@ declare namespace webdriver { } /** - * Enumeration of the buttons used in the advanced interactions API. - * NOTE: A TypeScript enum was not used so that this class could be extended in Protractor. - * @enum {number} + * Representations of pressable keys that aren't text. These are stored in + * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to + * http://www.google.com.au/search?&q=unicode+pua&btnG=Search + * + * @enum {string} */ - interface IButton { - LEFT: number; - MIDDLE: number; - RIGHT: number; + enum Button { + LEFT, + MIDDLE, + RIGHT, } - var Button: IButton; - /** * Representations of pressable keys that aren't text. These are stored in * the Unicode PUA (Private Use Area) code points, 0xE000-0xF8FF. Refer to @@ -2124,102 +3086,86 @@ declare namespace webdriver { * * @enum {string} */ - interface IKey { - NULL: string; - CANCEL: string; // ^break - HELP: string; - BACK_SPACE: string; - TAB: string; - CLEAR: string; - RETURN: string; - ENTER: string; - SHIFT: string; - CONTROL: string; - ALT: string; - PAUSE: string; - ESCAPE: string; - SPACE: string; - PAGE_UP: string; - PAGE_DOWN: string; - END: string; - HOME: string; - ARROW_LEFT: string; - LEFT: string; - ARROW_UP: string; - UP: string; - ARROW_RIGHT: string; - RIGHT: string; - ARROW_DOWN: string; - DOWN: string; - INSERT: string; - DELETE: string; - SEMICOLON: string; - EQUALS: string; + enum Key { + NULL, + CANCEL, // ^break + HELP, + BACK_SPACE, + TAB, + CLEAR, + RETURN, + ENTER, + SHIFT, + CONTROL, + ALT, + PAUSE, + ESCAPE, + SPACE, + PAGE_UP, + PAGE_DOWN, + END, + HOME, + ARROW_LEFT, + LEFT, + ARROW_UP, + UP, + ARROW_RIGHT, + RIGHT, + ARROW_DOWN, + DOWN, + INSERT, + DELETE, + SEMICOLON, + EQUALS, - NUMPAD0: string; // number pad keys - NUMPAD1: string; - NUMPAD2: string; - NUMPAD3: string; - NUMPAD4: string; - NUMPAD5: string; - NUMPAD6: string; - NUMPAD7: string; - NUMPAD8: string; - NUMPAD9: string; - MULTIPLY: string; - ADD: string; - SEPARATOR: string; - SUBTRACT: string; - DECIMAL: string; - DIVIDE: string; + NUMPAD0, // number pad keys + NUMPAD1, + NUMPAD2, + NUMPAD3, + NUMPAD4, + NUMPAD5, + NUMPAD6, + NUMPAD7, + NUMPAD8, + NUMPAD9, + MULTIPLY, + ADD, + SEPARATOR, + SUBTRACT, + DECIMAL, + DIVIDE, - F1: string; // function keys - F2: string; - F3: string; - F4: string; - F5: string; - F6: string; - F7: string; - F8: string; - F9: string; - F10: string; - F11: string; - F12: string; + F1, // function keys + F2, + F3, + F4, + F5, + F6, + F7, + F8, + F9, + F10, + F11, + F12, - COMMAND: string; // Apple command key - META: string; // alias for Windows key + COMMAND, // Apple command key + META // alias for Windows key - /** - * Simulate pressing many keys at once in a "chord". Takes a sequence of - * {@link webdriver.Key}s or strings, appends each of the values to a string, - * and adds the chord termination key ({@link webdriver.Key.NULL}) and returns - * the resultant string. - * - * Note: when the low-level webdriver key handlers see Keys.NULL, active - * modifier keys (CTRL/ALT/SHIFT/etc) release via a keyup event. - * - * @param {...string} var_args The key sequence to concatenate. - * @return {string} The null-terminated key sequence. - * @see http://code.google.com/p/webdriver/issues/detail?id=79 - */ - chord: (...var_args: string[]) => string; } - var Key: IKey; - /** * Class for defining sequences of complex user interactions. Each sequence * will not be executed until {@link #perform} is called. * - *

    Example:

    
    -     *   new webdriver.ActionSequence(driver).
    -     *       keyDown(webdriver.Key.SHIFT).
    -     *       click(element1).
    -     *       click(element2).
    -     *       dragAndDrop(element3, element4).
    -     *       keyUp(webdriver.Key.SHIFT).
    -     *       perform();
    -     * 
    + * Example: + * + * new ActionSequence(driver). + * keyDown(Key.SHIFT). + * click(element1). + * click(element2). + * dragAndDrop(element3, element4). + * keyUp(Key.SHIFT). + * perform(); * */ class ActionSequence { @@ -2247,14 +3193,18 @@ declare namespace webdriver { * Moves the mouse. The location to move to may be specified in terms of the * mouse's current location, an offset relative to the top-left corner of an * element, or an element (in which case the middle of the element is used). - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, as either another WebElement or an offset in pixels. - * @param {{x: number, y: number}=} opt_offset An optional offset, in pixels. - * Defaults to (0, 0). - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, as either another WebElement or an offset in + * pixels. + * @param {{x: number, y: number}=} opt_offset If the target {@code location} + * is defined as a {@link ./webdriver.WebElement}, this parameter defines + * an offset within that element. The offset should be specified in pixels + * relative to the top-left corner of the element's bounding box. If + * omitted, the element's center will be used as the target offset. + * @return {!ActionSequence} A self reference. */ - mouseMove(location: WebElement, opt_offset?: ILocation): ActionSequence; - mouseMove(location: ILocation): ActionSequence; + mouseMove(location: WebElement|ILocation, opt_offset?: ILocation): ActionSequence; /** * Presses a mouse button. The mouse button will not be released until @@ -2262,100 +3212,101 @@ declare namespace webdriver { * sequence or another. The behavior for out-of-order events (e.g. mouseDown, * click) is undefined. * - *

    If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

    sequence.mouseMove(element).mouseDown()
    * - *

    Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseDown() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseDown(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseDown(opt_elementOrButton?: number): ActionSequence; + mouseDown(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Releases a mouse button. Behavior is undefined for calling this function * without a previous call to {@link #mouseDown}. * - *

    If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

    sequence.mouseMove(element).mouseUp()
    * - *

    Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).mouseUp() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - mouseUp(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - mouseUp(opt_elementOrButton?: number): ActionSequence; + mouseUp(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Convenience function for performing a "drag and drop" manuever. The target * element may be moved to the location of another element, or by an offset (in * pixels). - * @param {!webdriver.WebElement} element The element to drag. - * @param {(!webdriver.WebElement|{x: number, y: number})} location The - * location to drag to, either as another WebElement or an offset in pixels. - * @return {!webdriver.ActionSequence} A self reference. + * + * @param {!./webdriver.WebElement} element The element to drag. + * @param {(!./webdriver.WebElement|{x: number, y: number})} location The + * location to drag to, either as another WebElement or an offset in + * pixels. + * @return {!ActionSequence} A self reference. */ - dragAndDrop(element: WebElement, location: WebElement): ActionSequence; - dragAndDrop(element: WebElement, location: ILocation): ActionSequence; + dragAndDrop(element: WebElement, location: WebElement|ILocation): ActionSequence; /** * Clicks a mouse button. * - *

    If an element is provided, the mouse will first be moved to the center + * If an element is provided, the mouse will first be moved to the center * of that element. This is equivalent to: - *

    sequence.mouseMove(element).click()
    * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * sequence.mouseMove(element).click() + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - click(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - click(opt_elementOrButton?: number): ActionSequence; + click(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Double-clicks a mouse button. * - *

    If an element is provided, the mouse will first be moved to the center of + * If an element is provided, the mouse will first be moved to the center of * that element. This is equivalent to: - *

    sequence.mouseMove(element).doubleClick()
    * - *

    Warning: this method currently only supports the left mouse button. See - * http://code.google.com/p/selenium/issues/detail?id=4047 + * sequence.mouseMove(element).doubleClick() * - * @param {(webdriver.WebElement|webdriver.Button)=} opt_elementOrButton Either + * Warning: this method currently only supports the left mouse button. See + * [issue 4047](http://code.google.com/p/selenium/issues/detail?id=4047). + * + * @param {(./webdriver.WebElement|input.Button)=} opt_elementOrButton Either * the element to interact with or the button to click with. - * Defaults to {@link webdriver.Button.LEFT} if neither an element nor + * Defaults to {@link input.Button.LEFT} if neither an element nor * button is specified. - * @param {webdriver.Button=} opt_button The button to use. Defaults to - * {@link webdriver.Button.LEFT}. Ignored if a button is provided as the + * @param {input.Button=} opt_button The button to use. Defaults to + * {@link input.Button.LEFT}. Ignored if a button is provided as the * first argument. - * @return {!webdriver.ActionSequence} A self reference. + * @return {!ActionSequence} A self reference. */ - doubleClick(opt_elementOrButton?: WebElement, opt_button?: number): ActionSequence; - doubleClick(opt_elementOrButton?: number): ActionSequence; + doubleClick(opt_elementOrButton?: WebElement|webdriver.Button, opt_button?: webdriver.Button): ActionSequence; /** * Performs a modifier key press. The modifier key is not released @@ -2366,7 +3317,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyDown(key: string): ActionSequence; + keyDown(key: Key): ActionSequence; /** * Performs a modifier key release. The release is targetted at the currently @@ -2376,7 +3327,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - keyUp(key: string): ActionSequence; + keyUp(key: Key): ActionSequence; /** * Simulates typing multiple keys. Each modifier key encountered in the @@ -2387,7 +3338,7 @@ declare namespace webdriver { * @return {!webdriver.ActionSequence} A self reference. * @throws {Error} If the key is not a valid modifier key. */ - sendKeys(...var_args: any[]): ActionSequence; + sendKeys(...var_args: Array): ActionSequence; //endregion } @@ -2483,7 +3434,6 @@ declare namespace webdriver { */ scroll(offset: IOffset): TouchSequence; - /** * Scrolls the touch screen, starting on `elem` and moving by the specified * offset. @@ -2494,7 +3444,6 @@ declare namespace webdriver { */ scrollFromElement(elem: WebElement, offset: IOffset): TouchSequence; - /** * Flick, starting anywhere on the screen, at speed xspeed and yspeed. * @@ -2504,7 +3453,6 @@ declare namespace webdriver { */ flick(speed: ISpeed): TouchSequence; - /** * Flick starting at elem and moving by x and y at specified speed. * @@ -2516,26 +3464,29 @@ declare namespace webdriver { flickElement(elem: WebElement, offset: IOffset, speed: number): TouchSequence; } - interface IOffset { x: number; y: number; } - interface ISpeed { xspeed: number; yspeed: number; } - /** * Represents a modal dialog such as {@code alert}, {@code confirm}, or * {@code prompt}. Provides functions to retrieve the message displayed with * the alert, accept or dismiss the alert, and set the response text (in the * case of {@code prompt}). */ - interface Alert { + class Alert { + /** + * @param {!WebDriver} driver The driver controlling the browser this alert + * is attached to. + * @param {string} text The message text displayed with this alert. + */ + constructor(driver: WebDriver, text: string); //region Methods @@ -2547,6 +3498,18 @@ declare namespace webdriver { */ getText(): webdriver.promise.Promise; + /** + * Sets the username and password in an alert prompting for credentials (such + * as a Basic HTTP Auth prompt). This method will implicitly + * {@linkplain #accept() submit} the dialog. + * + * @param {string} username The username to send. + * @param {string} password The password to send. + * @return {!promise.Promise} A promise that will be resolved when this + * command has completed. + */ + authenticateAs(username: string, password: string): webdriver.promise.Promise; + /** * Accepts this alert. * @return {!webdriver.promise.Promise} A promise that will be resolved when @@ -2580,47 +3543,149 @@ declare namespace webdriver { * serves as a forward proxy on an Alert, allowing calls to be scheduled * directly on this instance before the underlying Alert has been fulfilled. In * other words, the following two statements are equivalent: - *

    
    +     *
          *     driver.switchTo().alert().dismiss();
          *     driver.switchTo().alert().then(function(alert) {
          *       return alert.dismiss();
          *     });
    -     * 
    * - * @param {!webdriver.WebDriver} driver The driver controlling the browser this - * alert is attached to. - * @param {!webdriver.promise.Thenable.} alert A thenable - * that will be fulfilled with the promised alert. - * @constructor - * @extends {webdriver.Alert} - * @implements {webdriver.promise.Thenable.} + * @implements {promise.Thenable.} * @final */ - interface AlertPromise extends Alert, webdriver.promise.IThenable { + class AlertPromise extends Alert implements webdriver.promise.IThenable{ + /** + * @param {!WebDriver} driver The driver controlling the browser this + * alert is attached to. + * @param {!promise.Thenable} alert A thenable + * that will be fulfilled with the promised alert. + */ + constructor(driver: WebDriver, alert: webdriver.promise.Promise); + + //region Methods + + /** + * Cancels the computation of this promise's value, rejecting the promise in the + * process. + * @param {*} reason The reason this promise is being cancelled. If not an + * {@code Error}, one will be created using the value's string + * representation. + */ + cancel(opt_reason?: string|Error): void; + + /** @return {boolean} Whether this promise's value is still being computed. */ + isPending(): boolean; + + /** + * Registers listeners for when this instance is resolved. This function most + * overridden by subtypes. + * + * @param opt_callback The function to call if this promise is + * successfully resolved. The function should expect a single argument: the + * promise's resolved value. + * @param opt_errback The function to call if this promise is + * rejected. The function should expect a single argument: the rejection + * reason. + * @return A new promise which will be resolved + * with the result of the invoked callback. + */ + then(opt_callback?: Function, opt_errback?: Function): webdriver.promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } catch (ex) {
    +             *     console.error(ex);
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenCatch(function(ex) {
    +             *     console.error(ex);
    +             *   });
    +             * 
    + * + * @param {function(*): (R|webdriver.promise.Promise.)} errback The function + * to call if this promise is rejected. The function should expect a single + * argument: the rejection reason. + * @return {!webdriver.promise.Promise.} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + thenCatch(errback: (error: any) => any): webdriver.promise.Promise; + + /** + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: + * + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } + * + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); + * + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R + */ + catch(errback: Function): webdriver.promise.Promise; + + + /** + * Registers a listener to invoke when this promise is resolved, regardless + * of whether the promise's value was successfully computed. This function + * is synonymous with the {@code finally} clause in a synchronous API: + *
    
    +             *   // Synchronous API:
    +             *   try {
    +             *     doSynchronousWork();
    +             *   } finally {
    +             *     cleanUp();
    +             *   }
    +             *
    +             *   // Asynchronous promise API:
    +             *   doAsynchronousWork().thenFinally(cleanUp);
    +             * 
    + * + * Note: similar to the {@code finally} clause, if the registered + * callback returns a rejected promise or throws an error, it will silently + * replace the rejection error (if any) from this promise: + *
    
    +             *   try {
    +             *     throw Error('one');
    +             *   } finally {
    +             *     throw Error('two');  // Hides Error: one
    +             *   }
    +             *
    +             *   webdriver.promise.rejected(Error('one'))
    +             *       .thenFinally(function() {
    +             *         throw Error('two');  // Hides Error: one
    +             *       });
    +             * 
    + * + * + * @param {function(): (R|webdriver.promise.Promise.)} callback The function + * to call when this promise is resolved. + * @return {!webdriver.promise.Promise.} A promise that will be fulfilled + * with the callback result. + * @template R + */ + thenFinally(callback: Function): webdriver.promise.Promise; } - /** - * An error returned to indicate that there is an unhandled modal dialog on the - * current page. - * @extends {bot.Error} - */ - interface UnhandledAlertError extends webdriver.error.Error { - //region Methods - - /** - * @return {string} The text displayed with the unhandled alert. - */ - getAlertText(): string; - - /** - * @return {!webdriver.Alert} The open alert. - * @deprecated Use {@link #getAlertText}. This method will be removed in - * 2.45.0. - */ - getAlert(): Alert; - - - //endregion + /** @deprecated Use {@link error.UnexpectedAlertOpenError} instead. */ + class UnhandledAlertError extends webdriver.error.UnexpectedAlertOpenError { } /** @@ -2630,7 +3695,9 @@ declare namespace webdriver { interface IBrowser { ANDROID: string; CHROME: string; + EDGE: string; FIREFOX: string; + IE: string; INTERNET_EXPLORER: string; IPAD: string; IPHONE: string; @@ -2651,6 +3718,45 @@ declare namespace webdriver { noProxy?: string; } + /** + * Creates new {@link webdriver.WebDriver WebDriver} instances. The environment + * variables listed below may be used to override a builder's configuration, + * allowing quick runtime changes. + * + * - {@code SELENIUM_BROWSER}: defines the target browser in the form + * {@code browser[:version][:platform]}. + * + * - {@code SELENIUM_REMOTE_URL}: defines the remote URL for all builder + * instances. This environment variable should be set to a fully qualified + * URL for a WebDriver server (e.g. http://localhost:4444/wd/hub). This + * option always takes precedence over {@code SELENIUM_SERVER_JAR}. + * + * - {@code SELENIUM_SERVER_JAR}: defines the path to the + * + * standalone Selenium server jar to use. The server will be started the + * first time a WebDriver instance and be killed when the process exits. + * + * Suppose you had mytest.js that created WebDriver with + * + * var driver = new webdriver.Builder() + * .forBrowser('chrome') + * .build(); + * + * This test could be made to use Firefox on the local machine by running with + * `SELENIUM_BROWSER=firefox node mytest.js`. Rather than change the code to + * target Google Chrome on a remote machine, you can simply set the + * `SELENIUM_BROWSER` and `SELENIUM_REMOTE_URL` environment variables: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_REMOTE_URL=http://www.example.com:4444/wd/hub \ + * node mytest.js + * + * You could also use a local copy of the standalone Selenium server: + * + * SELENIUM_BROWSER=chrome:36:LINUX \ + * SELENIUM_SERVER_JAR=/path/to/selenium-server-standalone.jar \ + * node mytest.js + */ class Builder { //region Constructors @@ -2664,15 +3770,45 @@ declare namespace webdriver { //region Methods + /** + * Configures this builder to ignore any environment variable overrides and to + * only use the configuration specified through this instance's API. + * + * @return {!Builder} A self reference. + */ + disableEnvironmentOverrides(): Builder; + /** * Creates a new WebDriver client based on this builder's current * configuration. * + * While this method will immediately return a new WebDriver instance, any + * commands issued against it will be deferred until the associated browser + * has been fully initialized. Users may call {@link #buildAsync()} to obtain + * a promise that will not be fulfilled until the browser has been created + * (the difference is purely in style). + * * @return {!webdriver.WebDriver} A new WebDriver instance. * @throws {Error} If the current configuration is invalid. + * @see #buildAsync() */ build(): WebDriver; + /** + * Creates a new WebDriver client based on this builder's current + * configuration. This method returns a promise that will not be fulfilled + * until the new browser session has been fully initialized. + * + * __Note:__ this method is purely a convenience wrapper around + * {@link #build()}. + * + * @return {!promise.Promise} A promise that will be + * fulfilled with the newly created WebDriver instance once the browser + * has been fully initialized. + * @see #build() + */ + buildAsync(): webdriver.promise.Promise; + /** * Configures the target browser for clients created by this instance. * Any calls to {@link #withCapabilities} after this function will @@ -2705,6 +3841,12 @@ declare namespace webdriver { */ getServerUrl(): string; + /** + * @return {?string} The URL of the proxy server to use for the WebDriver's + * HTTP connections, or `null` if not set. + */ + getWebDriverProxy(): string; + /** * Sets the default action to take with an unexpected alert before returning * an error. @@ -2735,6 +3877,17 @@ declare namespace webdriver { */ setControlFlow(flow: webdriver.promise.ControlFlow): Builder; + /** + * Set {@linkplain edge.Options options} specific to Microsoft's Edge browser + * for drivers created by this builder. Any proxy settings defined on the + * given options will take precedence over those set through + * {@link #setProxy}. + * + * @param {!edge.Options} options The MicrosoftEdgeDriver options to use. + * @return {!Builder} A self reference. + */ + setEdgeOptions(options: edge.Options): Builder; + /** * Sets whether native events should be used. * @param {boolean} enabled Whether to enable native events. @@ -2753,6 +3906,16 @@ declare namespace webdriver { */ setFirefoxOptions(options: firefox.Options): Builder; + /** + * Set Internet Explorer specific {@linkplain ie.Options options} for drivers + * created by this builder. Any proxy settings defined on the given options + * will take precedence over those set through {@link #setProxy}. + * + * @param {!ie.Options} options The IEDriver options to use. + * @return {!Builder} A self reference. + */ + setIeOptions(options: ie.Options): Builder; + /** * Sets the logging preferences for the created session. Preferences may be * changed by repeated calls, or by calling {@link #withCapabilities}. @@ -2760,17 +3923,37 @@ declare namespace webdriver { * desired logging preferences. * @return {!Builder} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Builder; - setLoggingPrefs(prefs: { [key: string]: string }): Builder; + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Builder; + + /** + * Sets Opera specific {@linkplain opera.Options options} for drivers created + * by this builder. Any logging or proxy settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs} and + * {@link #setProxy}, respectively. + * + * @param {!opera.Options} options The OperaDriver options to use. + * @return {!Builder} A self reference. + */ + setOperaOptions(options: opera.Options): Builder; /** * Sets the proxy configuration to use for WebDriver clients created by this * builder. Any calls to {@link #withCapabilities} after this function will * overwrite these settings. - * @param {!webdriver.ProxyConfig} config The configuration to use. + * @param {!capabilities.ProxyConfig} config The configuration to use. * @return {!Builder} A self reference. */ - setProxy(config: ProxyConfig): Builder; + setProxy(config: webdriver.ProxyConfig): Builder; + + /** + * Sets Safari specific {@linkplain safari.Options options} for drivers + * created by this builder. Any logging settings defined on the given options + * will take precedence over those set through {@link #setLoggingPrefs}. + * + * @param {!safari.Options} options The Safari options to use. + * @return {!Builder} A self reference. + */ + setSafari(options: safari.Options): Builder; /** * Sets how elements should be scrolled into view for interaction. @@ -2793,6 +3976,16 @@ declare namespace webdriver { */ usingServer(url: string): Builder; + /** + * Sets the URL of the proxy to use for the WebDriver's HTTP connections. + * If this method is never called, the Builder will create a connection + * without a proxy. + * + * @param {string} proxy The URL of a proxy to use. + * @return {!Builder} A self reference. + */ + usingWebDriverProxy(proxy: string): Builder; + /** * Sets the desired capabilities when requesting a new session. This will * overwrite any previously set capabilities. @@ -2800,12 +3993,149 @@ declare namespace webdriver { * capabilities for a new session. * @return {!Builder} A self reference. */ - withCapabilities(capabilities: Capabilities): Builder; - withCapabilities(capabilities: any): Builder; + withCapabilities(capabilities: Object|Capabilities): Builder; //endregion } + /** + * Describes a mechanism for locating an element on the page. + * @final + */ + class By { + + /** + * @param {string} using the name of the location strategy to use. + * @param {string} value the value to search for. + */ + constructor(using: string, value: string); + + /** + * Locates elements that have a specific class name. + * + * @param {string} name The class name to search for. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * @see http://www.w3.org/TR/CSS2/selector.html#class-html + */ + static className(name: string): By; + + /** + * Locates elements using a CSS selector. + * + * @param {string} selector The CSS selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/CSS2/selector.html + */ + static css(selector: string): By; + + /** + * Locates eleemnts by the ID attribute. This locator uses the CSS selector + * `*[id="$ID"]`, _not_ `document.getElementById`. + * + * @param {string} id The ID to search for. + * @return {!By} The new locator. + */ + static id(id: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} matches the given + * string. + * + * @param {string} text The link text to search for. + * @return {!By} The new locator. + */ + static linkText(text: string): By; + + /** + * Locates an elements by evaluating a + * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. + * The result of this expression must be an element or list of elements. + * + * @param {!(string|Function)} script The script to execute. + * @param {...*} var_args The arguments to pass to the script. + * @return {function(!./webdriver.WebDriver): !./promise.Promise} + * A new JavaScript-based locator function. + */ + static js(script: string|Function, ...var_args: Array): (webdriver: webdriver.WebDriver) => webdriver.promise.Promise; + + /** + * Locates elements whose `name` attribute has the given value. + * + * @param {string} name The name attribute to search for. + * @return {!By} The new locator. + */ + static name(name: string): By; + + /** + * Locates link elements whose + * {@linkplain webdriver.WebElement#getText visible text} contains the given + * substring. + * + * @param {string} text The substring to check for in a link's visible text. + * @return {!By} The new locator. + */ + static partialLinkText(text: string): By; + + /** + * Locates elements with a given tag name. + * + * @param {string} name The tag name to search for. + * @return {!By} The new locator. + * @deprecated Use {@link By.css() By.css(tagName)} instead. + */ + static tagName(name: string): By; + + /** + * Locates elements matching a XPath selector. Care should be taken when + * using an XPath selector with a {@link webdriver.WebElement} as WebDriver + * will respect the context in the specified in the selector. For example, + * given the selector `//div`, WebDriver will search from the document root + * regardless of whether the locator was used with a WebElement. + * + * @param {string} xpath The XPath selector to use. + * @return {!By} The new locator. + * @see http://www.w3.org/TR/xpath/ + */ + static xpath(xpath: string): By; + + /** @override */ + toString(): string; + } + + /** + * Short-hand expressions for the primary element locator strategies. + * For example the following two statements are equivalent: + * + * var e1 = driver.findElement(webdriver.By.id('foo')); + * var e2 = driver.findElement({id: 'foo'}); + * + * Care should be taken when using JavaScript minifiers (such as the + * Closure compiler), as locator hashes will always be parsed using + * the un-obfuscated properties listed. + * + * @typedef {( + * {className: string}| + * {css: string}| + * {id: string}| + * {js: string}| + * {linkText: string}| + * {name: string}| + * {partialLinkText: string}| + * {tagName: string}| + * {xpath: string})} + */ + type ByHash = {className: string}| + {css: string}| + {id: string}| + {js: string}| + {linkText: string}| + {name: string}| + {partialLinkText: string}| + {tagName: string}| + {xpath: string}; + /** * Common webdriver capability keys. * @enum {string} @@ -2876,7 +4206,7 @@ declare namespace webdriver { SECURE_SSL: string; /** Whether the driver supports manipulating the app cache. */ - SUPPORTS_APPLICATION_CACHE: string; + SUPPORTS_APPLICATION_CACHE: string; /** Whether the driver supports locating elements with CSS selectors. */ SUPPORTS_CSS_SELECTORS: string; @@ -2910,8 +4240,7 @@ declare namespace webdriver { * capabilities to merge into this instance. * @constructor */ - constructor(opt_other?: Capabilities); - constructor(opt_other?: any); + constructor(opt_other?: Capabilities|Object); //endregion @@ -2927,8 +4256,7 @@ declare namespace webdriver { * merge into this instance. * @return {!webdriver.Capabilities} A self reference. */ - merge(other: Capabilities): Capabilities; - merge(other: any): Capabilities; + merge(other: Capabilities|Object): Capabilities; /** * @param {string} key The capability to set. @@ -2946,9 +4274,7 @@ declare namespace webdriver { * logging preferences. * @return {!webdriver.Capabilities} A self reference. */ - setLoggingPrefs(prefs: webdriver.logging.Preferences): Capabilities; - setLoggingPrefs(prefs: { [key: string]: string }): Capabilities; - + setLoggingPrefs(prefs: webdriver.logging.Preferences|Object): Capabilities; /** * Sets the proxy configuration for this instance. @@ -3010,6 +4336,11 @@ declare namespace webdriver { */ static chrome(): Capabilities; + /** + * @return {!Capabilities} A basic set of capabilities for Microsoft Edge. + */ + static edge(): Capabilities; + /** * @return {!webdriver.Capabilities} A basic set of capabilities for Firefox. */ @@ -3183,6 +4514,8 @@ declare namespace webdriver { GET_AVAILABLE_LOG_TYPES: string; GET_LOG: string; GET_SESSION_LOGS: string; + + UPLOAD_FILE: string; } var CommandName: ICommandName; @@ -3241,19 +4574,47 @@ declare namespace webdriver { } /** - * Handles the execution of {@code webdriver.Command} objects. + * Handles the execution of WebDriver {@link Command commands}. + * @interface */ - interface CommandExecutor { - /** - * Executes the given {@code command}. If there is an error executing the - * command, the provided callback will be invoked with the offending error. - * Otherwise, the callback will be invoked with a null Error and non-null - * {@link bot.response.ResponseObject} object. - * @param {!webdriver.Command} command The command to execute. - * @param {function(Error, !bot.response.ResponseObject=)} callback the function - * to invoke when the command response is ready. - */ - execute(command: Command, callback: (error: Error, responseObject: any) => any ): void; + class Executor { + /** + * Executes the given {@code command}. If there is an error executing the + * command, the provided callback will be invoked with the offending error. + * Otherwise, the callback will be invoked with a null Error and non-null + * response object. + * + * @param {!Command} command The command to execute. + * @return {!promise.Promise} A promise that will be fulfilled with + * the command result. + */ + execute(command: Command): webdriver.promise.Promise + } + + /** + * Wraps a promised {@link Executor}, ensuring no commands are executed until + * the wrapped executor has been fully resolved. + * @implements {Executor} + */ + class DeferredExecutor { + /** + * @param {!promise.Promise} delegate The promised delegate, which + * may be provided by any promise-like thenable object. + */ + constructor(delegate: webdriver.promise.Promise); + } + + /** + * Describes an event listener registered on an {@linkplain EventEmitter}. + */ + class Listener { + /** + * @param {!Function} fn The acutal listener function. + * @param {(Object|undefined)} scope The object in whose scope to invoke the + * listener. + * @param {boolean} oneshot Whether this listener should only be used once. + */ + constructor(fn: Function, scope: Object, oneshot: boolean); } /** @@ -3283,39 +4644,42 @@ declare namespace webdriver { /** * Returns a mutable list of listeners for a specific type of event. * @param {string} type The type of event to retrieve the listeners for. - * @return {!Array.<{fn: !Function, oneshot: boolean, - * scope: (Object|undefined)}>} The registered listeners for - * the given event type. + * @return {!Set} The registered listeners for the given event + * type. */ - listeners(type: string): Array<{fn: Function; oneshot: boolean; scope: any;}>; + listeners(type: string): any; /** * Registers a listener. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. - * @param {Object=} opt_scope The object in whose scope to invoke the listener. - * @return {!webdriver.EventEmitter} A self reference. + * @param {!Function} fn The function to invoke when the event is fired. + * @param {Object=} opt_self The object in whose scope to invoke the listener. + * @param {boolean=} opt_oneshot Whether the listener should b (e removed after + * the first event is fired. + * @return {!EventEmitter} A self reference. + * @private */ - addListener(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + addListener(type: string, fn: Function, opt_scope?:any, opt_oneshot?: boolean): EventEmitter; + /** * Registers a one-time listener which will be called only the first time an * event is emitted, after which it will be removed. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - once(type: string, listenerFn: any, opt_scope?: any): EventEmitter; + once(type: string, fn: any, opt_scope?: any): EventEmitter; /** * An alias for {@code #addListener()}. * @param {string} type The type of event to listen for. - * @param {!Function} listenerFn The function to invoke when the event is fired. + * @param {!Function} fn The function to invoke when the event is fired. * @param {Object=} opt_scope The object in whose scope to invoke the listener. * @return {!webdriver.EventEmitter} A self reference. */ - on(type: string, listenerFn: Function, opt_scope?:any): EventEmitter; + on(type: string, fn: Function, opt_scope?:any): EventEmitter; /** * Removes a previously registered event listener. @@ -3340,14 +4704,20 @@ declare namespace webdriver { /** * Interface for navigating back and forth in the browser history. */ - interface WebDriverNavigation { + class Navigation { //region Constructors /** - * @param {!webdriver.WebDriver} driver The parent driver. - * @constructor + * Interface for navigating back and forth in the browser history. + * + * This class should never be instantiated directly. Insead, obtain an instance + * with + * + * webdriver.navigate() + * + * @see WebDriver#navigate() */ - new (driver: WebDriver): WebDriverNavigation; + constructor(driver: WebDriver); //endregion @@ -3397,14 +4767,14 @@ declare namespace webdriver { /** * Provides methods for managing browser and driver state. */ - interface WebDriverOptions { + class Options { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: webdriver.WebDriver): WebDriverOptions; + constructor(driver: webdriver.WebDriver); //endregion @@ -3417,13 +4787,13 @@ declare namespace webdriver { * @param {string=} opt_path The cookie path. * @param {string=} opt_domain The cookie domain. * @param {boolean=} opt_isSecure Whether the cookie is secure. - * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified as - * a number, should be in milliseconds since midnight, January 1, 1970 UTC. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * cookie has been added to the page. + * @param {(number|!Date)=} opt_expiry When the cookie expires. If specified + * as a number, should be in milliseconds since midnight, + * January 1, 1970 UTC. + * @return {!promise.Promise} A promise that will be resolved + * when the cookie has been added to the page. */ - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number): webdriver.promise.Promise; - addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: Date): webdriver.promise.Promise; + addCookie(name: string, value: string, opt_path?: string, opt_domain?: string, opt_isSecure?: boolean, opt_expiry?: number|Date): webdriver.promise.Promise; /** * Schedules a command to delete all cookies visible to the current page. @@ -3467,19 +4837,19 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Logs} The interface for managing driver * logs. */ - logs(): WebDriverLogs; + logs(): webdriver.Logs; /** * @return {!webdriver.WebDriver.Timeouts} The interface for managing driver * timeouts. */ - timeouts(): WebDriverTimeouts; + timeouts(): webdriver.Timeouts; /** * @return {!webdriver.WebDriver.Window} The interface for managing the * current window. */ - window(): WebDriverWindow; + window(): webdriver.Window; //endregion } @@ -3487,14 +4857,14 @@ declare namespace webdriver { /** * An interface for managing timeout behavior for WebDriver instances. */ - interface WebDriverTimeouts { + class Timeouts { //region Constructors /** * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTimeouts; + constructor(driver: webdriver.WebDriver); //endregion @@ -3549,7 +4919,7 @@ declare namespace webdriver { /** * An interface for managing the current window. */ - interface WebDriverWindow { + class Window { //region Constructors @@ -3557,7 +4927,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverWindow; + constructor(driver: webdriver.WebDriver); //endregion @@ -3612,7 +4982,7 @@ declare namespace webdriver { /** * Interface for managing WebDriver log records. */ - interface WebDriverLogs { + class Logs { //region Constructors @@ -3620,7 +4990,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverLogs; + constructor(driver: webdriver.WebDriver); //endregion @@ -3640,7 +5010,7 @@ declare namespace webdriver { * promise that will resolve to a list of log entries for the specified * type. */ - get(type: string): webdriver.promise.Promise; + get(type: webdriver.logging.Type): webdriver.promise.Promise; /** * Retrieves the log types available to this driver. @@ -3655,7 +5025,7 @@ declare namespace webdriver { /** * An interface for changing the focus of the driver to another frame or window. */ - interface WebDriverTargetLocator { + class TargetLocator { //region Constructors @@ -3663,7 +5033,7 @@ declare namespace webdriver { * @param {!webdriver.WebDriver} driver The parent driver. * @constructor */ - new (driver: WebDriver): WebDriverTargetLocator; + constructor(driver: webdriver.WebDriver); //endregion @@ -3687,44 +5057,47 @@ declare namespace webdriver { /** * Schedules a command to switch the focus of all future commands to another - * frame on the page. - *

    - * If the frame is specified by a number, the command will switch to the frame - * by its (zero-based) index into the {@code window.frames} collection. - *

    - * If the frame is specified by a string, the command will select the frame by - * its name or ID. To select sub-frames, simply separate the frame names/IDs by - * dots. As an example, "main.child" will select the frame with the name "main" - * and then its child "child". - *

    - * If the specified frame can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_FRAME} error. - * @param {string|number} nameOrIndex The frame locator. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified frame. + * frame on the page. The target frame may be specified as one of the + * following: + * + * - A number that specifies a (zero-based) index into [window.frames]( + * https://developer.mozilla.org/en-US/docs/Web/API/Window.frames). + * - A {@link WebElement} reference, which correspond to a `frame` or `iframe` + * DOM element. + * - The `null` value, to select the topmost frame on the page. Passing `null` + * is the same as calling {@link #defaultContent defaultContent()}. + * + * If the specified frame can not be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchFrameError}. + * + * @param {(number|WebElement|null)} id The frame locator. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified frame. */ - frame(nameOrIndex: string): webdriver.promise.Promise; - frame(nameOrIndex: number): webdriver.promise.Promise; + frame(nameOrIndex: number|WebElement): webdriver.promise.Promise; /** * Schedules a command to switch the focus of all future commands to another * window. Windows may be specified by their {@code window.name} attribute or - * by its handle (as returned by {@code webdriver.WebDriver#getWindowHandles}). - *

    - * If the specificed window can not be found, the deferred result will errback - * with a {@code bot.ErrorCode.NO_SUCH_WINDOW} error. + * by its handle (as returned by {@link WebDriver#getWindowHandles}). + * + * If the specified window cannot be found, the returned promise will be + * rejected with a {@linkplain error.NoSuchWindowError}. + * * @param {string} nameOrHandle The name or window handle of the window to * switch focus to. - * @return {!webdriver.promise.Promise} A promise that will be resolved when the - * driver has changed focus to the specified window. + * @return {!promise.Promise} A promise that will be resolved + * when the driver has changed focus to the specified window. */ window(nameOrHandle: string): webdriver.promise.Promise; /** - * Schedules a command to change focus to the active alert dialog. This command - * will return a {@link bot.ErrorCode.NO_MODAL_DIALOG_OPEN} error if a modal - * dialog is not currently open. - * @return {!webdriver.Alert} The open alert. + * Schedules a command to change focus to the active modal dialog, such as + * those opened by `window.alert()`, `window.confirm()`, and + * `window.prompt()`. The returned promise will be rejected with a + * {@linkplain error.NoSuchAlertError} if there are no open alerts. + * + * @return {!AlertPromise} The open alert. */ alert(): AlertPromise; @@ -3789,27 +5162,14 @@ declare namespace webdriver { //region Constructors /** - * @param {!(webdriver.Session|webdriver.promise.Promise)} session Either a + * @param {!(Session|promise.Promise)} session Either a * known session or a promise that will be resolved to a session. - * @param {!webdriver.CommandExecutor} executor The executor to use when - * sending commands to the browser. - * @param {webdriver.promise.ControlFlow=} opt_flow The flow to + * @param {!command.Executor} executor The executor to use when sending + * commands to the browser. + * @param {promise.ControlFlow=} opt_flow The flow to * schedule commands through. Defaults to the active flow object. - * @constructor */ - constructor(session: Session, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - constructor(session: webdriver.promise.Promise, executor: CommandExecutor, opt_flow?: webdriver.promise.ControlFlow); - - //endregion - - //region Static Properties - - static Navigation: WebDriverNavigation; - static Options: WebDriverOptions; - static Timeouts: WebDriverTimeouts; - static Window: WebDriverWindow; - static Logs: WebDriverLogs; - static TargetLocator: WebDriverTargetLocator; + constructor(session: Session|webdriver.promise.Promise, executor: Executor, opt_flow?: webdriver.promise.ControlFlow); //endregion @@ -3817,29 +5177,29 @@ declare namespace webdriver { /** * Creates a new WebDriver client for an existing session. - * @param {!webdriver.CommandExecutor} executor Command executor to use when - * querying for session details. + * @param {!command.Executor} executor Command executor to use when querying + * for session details. * @param {string} sessionId ID of the session to attach to. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver - * commands should execute under. Defaults to the - * {@link webdriver.promise.controlFlow() currently active} control flow. - * @return {!webdriver.WebDriver} A new client for the specified session. + * @param {promise.ControlFlow=} opt_flow The control flow all + * driver commands should execute under. Defaults to the + * {@link promise.controlFlow() currently active} control flow. + * @return {!WebDriver} A new client for the specified session. */ - static attachToSession(executor: CommandExecutor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static attachToSession(executor: Executor, sessionId: string, opt_flow?: webdriver.promise.ControlFlow): WebDriver; /** * Creates a new WebDriver session. - * @param {!webdriver.CommandExecutor} executor The executor to create the new - * session with. - * @param {!webdriver.Capabilities} desiredCapabilities The desired + * @param {!command.Executor} executor The executor to create the new session + * with. + * @param {!./capabilities.Capabilities} desiredCapabilities The desired * capabilities for the new session. - * @param {webdriver.promise.ControlFlow=} opt_flow The control flow all driver + * @param {promise.ControlFlow=} opt_flow The control flow all driver * commands should execute under, including the initial session creation. - * Defaults to the {@link webdriver.promise.controlFlow() currently active} + * Defaults to the {@link promise.controlFlow() currently active} * control flow. - * @return {!webdriver.WebDriver} The driver for the newly created session. + * @return {!WebDriver} The driver for the newly created session. */ - static createSession(executor: CommandExecutor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; + static createSession(executor: Executor, desiredCapabilities: Capabilities, opt_flow?: webdriver.promise.ControlFlow): WebDriver; //endregion @@ -3852,20 +5212,22 @@ declare namespace webdriver { controlFlow(): webdriver.promise.ControlFlow; /** - * Schedules a {@code webdriver.Command} to be executed by this driver's - * {@code webdriver.CommandExecutor}. - * @param {!webdriver.Command} command The command to schedule. + * Schedules a {@link command.Command} to be executed by this driver's + * {@link command.Executor}. + * + * @param {!command.Command} command The command to schedule. * @param {string} description A description of the command for debugging. - * @return {!webdriver.promise.Promise} A promise that will be resolved with - * the command result. + * @return {!promise.Promise} A promise that will be resolved + * with the command result. + * @template T */ schedule(command: Command, description: string): webdriver.promise.Promise; /** - * Sets the {@linkplain webdriver.FileDetector file detector} that should be + * Sets the {@linkplain input.FileDetector file detector} that should be * used with this instance. - * @param {webdriver.FileDetector} detector The detector to use or {@code null}. + * @param {input.FileDetector} detector The detector to use or {@code null}. */ setFileDetector(detector: FileDetector): void; @@ -3895,23 +5257,23 @@ declare namespace webdriver { /** * Creates a new action sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.ActionSequence#perform} is + * scheduled for execution until {@link actions.ActionSequence#perform} is * called. Example: - *

    
    -         *   driver.actions().
    -         *       mouseDown(element1).
    -         *       mouseMove(element2).
    -         *       mouseUp().
    -         *       perform();
    -         * 
    - * @return {!webdriver.ActionSequence} A new action sequence for this instance. + * + * driver.actions(). + * mouseDown(element1). + * mouseMove(element2). + * mouseUp(). + * perform(); + * + * @return {!actions.ActionSequence} A new action sequence for this instance. */ actions(): ActionSequence; /** * Creates a new touch sequence using this driver. The sequence will not be - * scheduled for execution until {@link webdriver.TouchSequence#perform} is + * scheduled for execution until {@link actions.TouchSequence#perform} is * called. Example: * * driver.touchActions(). @@ -3919,7 +5281,7 @@ declare namespace webdriver { * doubleTap(element2). * perform(); * - * @return {!webdriver.TouchSequence} A new touch sequence for this instance. + * @return {!actions.TouchSequence} A new touch sequence for this instance. */ touchActions(): TouchSequence; @@ -3961,8 +5323,7 @@ declare namespace webdriver { * scripts return value. * @template T */ - executeScript(script: string, ...var_args: any[]): webdriver.promise.Promise; - executeScript(script: Function, ...var_args: any[]): webdriver.promise.Promise; + executeScript(script: string|Function, ...var_args: any[]): webdriver.promise.Promise; /** * Schedules a command to execute asynchronous JavaScript in the context of the @@ -4179,38 +5540,27 @@ declare namespace webdriver { * var e1 = driver.findElement(By.id('foo')); * var e2 = driver.findElement({id:'foo'}); * - * You may also provide a custom locator function, which takes as input - * this WebDriver instance and returns a {@link webdriver.WebElement}, or a - * promise that will resolve to a WebElement. For example, to find the first - * visible link on a page, you could write: + * You may also provide a custom locator function, which takes as input this + * instance and returns a {@link WebElement}, or a promise that will resolve + * to a WebElement. If the returned promise resolves to an array of + * WebElements, WebDriver will use the first element. For example, to find the + * first visible link on a page, you could write: * * var link = driver.findElement(firstVisibleLink); * * function firstVisibleLink(driver) { * var links = driver.findElements(By.tagName('a')); - * return webdriver.promise.filter(links, function(link) { - * return links.isDisplayed(); - * }).then(function(visibleLinks) { - * return visibleLinks[0]; + * return promise.filter(links, function(link) { + * return link.isDisplayed(); * }); * } * - * When running in the browser, a WebDriver cannot manipulate DOM elements - * directly; it may do so only through a {@link webdriver.WebElement} reference. - * This function may be used to generate a WebElement from a DOM element. A - * reference to the DOM element will be stored in a known location and this - * driver will attempt to retrieve it through {@link #executeScript}. If the - * element cannot be found (eg, it belongs to a different document than the - * one this instance is currently focused on), a - * {@link bot.ErrorCode.NO_SUCH_ELEMENT} error will be returned. - * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element|Function)} locator The - * locator to use. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator to use. + * @return {!WebElementPromise} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locatorOrElement: Locator|By.Hash|WebElement|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if an element is present on the page. @@ -4219,35 +5569,36 @@ declare namespace webdriver { * document the driver is currently focused on. Otherwise, the function will * test if at least one element can be found with the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Element| - * Function)} locatorOrElement The locator to use, or the actual - * DOM element to be located by the server. - * @return {!webdriver.promise.Promise.} A promise that will resolve + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise} A promise that will resolve * with whether the element is present on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * driver.findElements(locator).then(e => !!e.length); */ - isElementPresent(locatorOrElement: Locator|By.Hash|WebElement|Function): webdriver.promise.Promise; + isElementPresent(locatorOrElement: By|Function): webdriver.promise.Promise; /** * Schedule a command to search for multiple elements on the page. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator - * strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator to use. + * @return {!promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedule a command to take a screenshot. The driver makes a best effort to * return a screenshot of the following, in order of preference: - *
      - *
    1. Entire page - *
    2. Current window - *
    3. Visible portion of the current frame - *
    4. The screenshot of the entire display containing the browser - *
    * - * @return {!webdriver.promise.Promise.} A promise that will be + * 1. Entire page + * 2. Current window + * 3. Visible portion of the current frame + * 4. The entire display containing the browser + * + * @return {!promise.Promise} A promise that will be * resolved to the screenshot as a base-64 encoded PNG. */ takeScreenshot(): webdriver.promise.Promise; @@ -4256,45 +5607,25 @@ declare namespace webdriver { * @return {!webdriver.WebDriver.Options} The options interface for this * instance. */ - manage(): WebDriverOptions; + manage(): webdriver.Options; /** * @return {!webdriver.WebDriver.Navigation} The navigation interface for this * instance. */ - navigate(): WebDriverNavigation; + navigate(): Navigation; /** * @return {!webdriver.WebDriver.TargetLocator} The target locator interface for * this instance. */ - switchTo(): WebDriverTargetLocator; + switchTo(): webdriver.TargetLocator; //endregion } interface IWebElementId { - ELEMENT: string; - } - - /** - * Defines an object that can be asynchronously serialized to its WebDriver - * wire representation. - * - * @constructor - * @template T - */ - interface Serializable { - /** - * Returns either this instance's serialized represention, if immediately - * available, or a promise for its serialized representation. This function is - * conceptually equivalent to objects that have a {@code toJSON()} property, - * except the serialize() result may be a promise or an object containing a - * promise (which are not directly JSON friendly). - * - * @return {!(T|IThenable.)} This instance's serialized wire format. - */ - serialize(): T|webdriver.promise.IThenable; + [ELEMENT:string]: string; } /** @@ -4554,7 +5885,7 @@ declare namespace webdriver { * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this @@ -4565,7 +5896,7 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.} A promise that will be * resolved with whether an element could be located on the page. */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that @@ -4576,10 +5907,9 @@ declare namespace webdriver { * @return {!webdriver.promise.Promise.>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; } - /** * Defines an object that can be asynchronously serialized to its WebDriver * wire representation. @@ -4600,7 +5930,6 @@ declare namespace webdriver { serialize(): T|webdriver.promise.IThenable; } - /** * Represents a DOM element. WebElements can be found by searching from the * document root using a {@link webdriver.WebDriver} instance, or by searching @@ -4626,35 +5955,59 @@ declare namespace webdriver { */ class WebElement implements Serializable { /** - * @param {!webdriver.WebDriver} driver The parent WebDriver instance for this - * element. - * @param {!(webdriver.promise.Promise.| - * webdriver.WebElement.Id)} id The server-assigned opaque ID for the - * underlying DOM element. - * @constructor + * @param {!WebDriver} driver the parent WebDriver instance for this element. + * @param {(!IThenable|string)} id The server-assigned opaque ID for + * the underlying DOM element. */ - constructor(driver: WebDriver, id: webdriver.promise.Promise|IWebElementId); + constructor(driver: webdriver.WebDriver, id: webdriver.promise.Promise|string); /** - * Wire protocol definition of a WebElement ID. - * @typedef {{ELEMENT: string}} - * @see https://github.com/SeleniumHQ/selenium/wiki/JsonWireProtocol + * @param {string} id The raw ID. + * @param {boolean=} opt_noLegacy Whether to exclude the legacy element key. + * @return {!Object} The element ID for use with WebDriver's wire protocol. */ - static Id: IWebElementId; + static buildId(id: string, opt_noLegacy?: boolean): Object; /** - * The property key used in the wire protocol to indicate that a JSON object - * contains the ID of a WebElement. - * @type {string} - * @const + * Extracts the encoded WebElement ID from the object. + * + * @param {?} obj The object to extract the ID from. + * @return {string} the extracted ID. + * @throws {TypeError} if the object is not a valid encoded ID. */ - static ELEMENT_KEY: string; + static extractId(obj: IWebElementId): string; + /** + * @param {?} obj the object to test. + * @return {boolean} whether the object is a valid encoded WebElement ID. + */ + static isId(obj: IWebElementId): boolean; + + /** + * Compares two WebElements for equality. + * + * @param {!WebElement} a A WebElement. + * @param {!WebElement} b A WebElement. + * @return {!promise.Promise} A promise that will be + * resolved to whether the two WebElements are equal. + */ + static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; /** * @return {!webdriver.WebDriver} The parent driver for this instance. */ - getDriver(): WebDriver; + getDriver(): webdriver.WebDriver; + + /** + * @return {!promise.Promise} A promise that resolves to + * the server-assigned opaque ID assigned to this element. + */ + getId(): webdriver.promise.Promise; + + /** + * @deprecated Use {@link #getId()} instead. + */ + getRawId(): any; /** * Schedule a command to find a descendant of this element. If the element @@ -4688,35 +6041,40 @@ declare namespace webdriver { * }); * } * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.WebElement} A WebElement that can be used to issue + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!WebElementPromise} A WebElement that can be used to issue * commands against the located element. If the element is not found, the * element will be invalidated and all scheduled commands aborted. */ - findElement(locator: Locator|By.Hash|Function): WebElementPromise; + findElement(locator: By|Function): WebElementPromise; /** * Schedules a command to test if there is at least one descendant of this * element that matches the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the element. - * @return {!webdriver.promise.Promise.} A promise that will be + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise} A promise that will be * resolved with whether an element could be located on the page. + * @deprecated This method will be removed in Selenium 3.0 for consistency + * with the other Selenium language bindings. This method is equivalent + * to + * + * element.findElements(locator).then(e => !!e.length); */ - isElementPresent(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + isElementPresent(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to find all of the descendants of this element that * match the given search criteria. * - * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The - * locator strategy to use when searching for the elements. - * @return {!webdriver.promise.Promise.>} A + * @param {!(by.By|Function)} locator The locator strategy to use when + * searching for the element. + * @return {!promise.Promise>} A * promise that will resolve to an array of WebElements. */ - findElements(locator: Locator|By.Hash|Function): webdriver.promise.Promise; + findElements(locator: By|Function): webdriver.promise.Promise; /** * Schedules a command to click on this element. @@ -4727,7 +6085,7 @@ declare namespace webdriver { /** * Schedules a command to type a sequence on the DOM element represented by this - * instance. + * promsieinstance. * * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is * processed in the keysequence, that key state is toggled until one of the @@ -4799,7 +6157,7 @@ declare namespace webdriver { * * @param {string} cssStyleProperty The name of the CSS style property to look * up. - * @return {!webdriver.promise.Promise.} A promise that will be + * @return {!promise.Promise} A promise that will be * resolved with the requested CSS value. */ getCssValue(cssStyleProperty: string): webdriver.promise.Promise; @@ -4885,10 +6243,10 @@ declare namespace webdriver { submit(): webdriver.promise.Promise; /** - * Schedules a command to clear the {@code value} of this element. This command - * has no effect if the underlying DOM element is neither a text INPUT element + * Schedules a command to clear the `value` of this element. This command has + * no effect if the underlying DOM element is neither a text INPUT element * nor a TEXTAREA element. - * @return {!webdriver.promise.Promise.} A promise that will be resolved + * @return {!promise.Promise} A promise that will be resolved * when the element has been cleared. */ clear(): webdriver.promise.Promise; @@ -4900,6 +6258,18 @@ declare namespace webdriver { */ isDisplayed(): webdriver.promise.Promise; + /** + * Take a screenshot of the visible region encompassed by this element's + * bounding rectangle. + * + * @param {boolean=} opt_scroll Optional argument that indicates whether the + * element should be scrolled into view before taking a screenshot. + * Defaults to false. + * @return {!promise.Promise} A promise that will be + * resolved to the screenshot as a base-64 encoded PNG. + */ + takeScreenshot(opt_scroll?: boolean): webdriver.promise.Promise; + /** * Schedules a command to retrieve the outer HTML of this element. * @return {!webdriver.promise.Promise.} A promise that will be @@ -4907,25 +6277,6 @@ declare namespace webdriver { */ getOuterHtml(): webdriver.promise.Promise; - /** - * @return {!webdriver.promise.Promise.} A promise - * that resolves to this element's JSON representation as defined by the - * WebDriver wire protocol. - * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol - */ - getId(): webdriver.promise.Promise; - - /** - * Returns the raw ID string ID for this element. - * @return {!webdriver.promise.Promise} A promise that resolves to this - * element's raw ID as a string value. - * @package - */ - getRawId(): webdriver.promise.Promise; - - /** @override */ - serialize(): webdriver.promise.Promise; - /** * Schedules a command to retrieve the inner HTML of this element. * @return {!webdriver.promise.Promise} A promise that will be resolved with the @@ -4933,14 +6284,8 @@ declare namespace webdriver { */ getInnerHtml(): webdriver.promise.Promise; - /** - * Compares to WebElements for equality. - * @param {!webdriver.WebElement} a A WebElement. - * @param {!webdriver.WebElement} b A WebElement. - * @return {!webdriver.promise.Promise} A promise that will be resolved to - * whether the two WebElements are equal. - */ - static equals(a: WebElement, b: WebElement): webdriver.promise.Promise; + /** @override */ + serialize(): webdriver.promise.Promise; } /** @@ -4966,6 +6311,14 @@ declare namespace webdriver { * @final */ class WebElementPromise extends WebElement implements webdriver.promise.IThenable { + /** + * @param {!WebDriver} driver The parent WebDriver instance for this + * element. + * @param {!promise.Promise} el A promise + * that will resolve to the promised element. + */ + constructor(driver: webdriver.WebDriver, el: webdriver.promise.Promise); + /** * Cancels the computation of this promise's value, rejecting the promise in the * process. This method is a no-op if the promise has alreayd been resolved. @@ -5075,191 +6428,31 @@ declare namespace webdriver { * @template R */ thenFinally(callback: () => any): webdriver.promise.Promise; - } - namespace By { /** - * Locates elements that have a specific class name. The returned locator - * is equivalent to searching for elements with the CSS selector ".clazz". + * Registers a listener for when this promise is rejected. This is synonymous + * with the {@code catch} clause in a synchronous API: * - * @param {string} className The class name to search for. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes - * @see http://www.w3.org/TR/CSS2/selector.html#class-html - */ - function className(value: string): Locator; - - /** - * Locates elements using a CSS selector. For browsers that do not support - * CSS selectors, WebDriver implementations may return an - * {@linkplain bot.Error.State.INVALID_SELECTOR invalid selector} error. An - * implementation may, however, emulate the CSS selector API. + * // Synchronous API: + * try { + * doSynchronousWork(); + * } catch (ex) { + * console.error(ex); + * } * - * @param {string} selector The CSS selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/CSS2/selector.html - */ - function css(value: string): Locator; - - /** - * Locates an element by its ID. + * // Asynchronous promise API: + * doAsynchronousWork().catch(function(ex) { + * console.error(ex); + * }); * - * @param {string} id The ID to search for. - * @return {!webdriver.Locator} The new locator. + * @param {function(*): (R|IThenable)} errback The + * function to call if this promise is rejected. The function should + * expect a single argument: the rejection reason. + * @return {!ManagedPromise} A new promise which will be + * resolved with the result of the invoked callback. + * @template R */ - function id(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} matches the given string. - * - * @param {string} text The link text to search for. - * @return {!webdriver.Locator} The new locator. - */ - function linkText(value: string): Locator; - - /** - * Locates an elements by evaluating a - * {@linkplain webdriver.WebDriver#executeScript JavaScript expression}. - * The result of this expression must be an element or list of elements. - * - * @param {!(string|Function)} script The script to execute. - * @param {...*} var_args The arguments to pass to the script. - * @return {function(!webdriver.WebDriver): !webdriver.promise.Promise} A new, - * JavaScript-based locator function. - */ - function js(script: any, ...var_args: any[]): (WebDriver: webdriver.WebDriver) => webdriver.promise.Promise; - - /** - * Locates elements whose {@code name} attribute has the given value. - * - * @param {string} name The name attribute to search for. - * @return {!webdriver.Locator} The new locator. - */ - function name(value: string): Locator; - - /** - * Locates link elements whose {@linkplain webdriver.WebElement#getText visible - * text} contains the given substring. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - */ - function partialLinkText(value: string): Locator; - - /** - * Locates elements with a given tag name. The returned locator is - * equivalent to using the - * [getElementsByTagName](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName) - * DOM function. - * - * @param {string} text The substring to check for in a link's visible text. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html - */ - function tagName(value: string): Locator; - - /** - * Locates elements matching a XPath selector. Care should be taken when - * using an XPath selector with a {@link webdriver.WebElement} as WebDriver - * will respect the context in the specified in the selector. For example, - * given the selector {@code "//div"}, WebDriver will search from the - * document root regardless of whether the locator was used with a - * WebElement. - * - * @param {string} xpath The XPath selector to use. - * @return {!webdriver.Locator} The new locator. - * @see http://www.w3.org/TR/xpath/ - */ - function xpath(value: string): Locator; - - /** - * Short-hand expressions for the primary element locator strategies. - * For example the following two statements are equivalent: - * - * var e1 = driver.findElement(webdriver.By.id('foo')); - * var e2 = driver.findElement({id: 'foo'}); - * - * Care should be taken when using JavaScript minifiers (such as the - * Closure compiler), as locator hashes will always be parsed using - * the un-obfuscated properties listed. - * - * @typedef {( - * {className: string}| - * {css: string}| - * {id: string}| - * {js: string}| - * {linkText: string}| - * {name: string}| - * {partialLinkText: string}| - * {tagName: string}| - * {xpath: string})} - */ - type Hash = {className: string}| - {css: string}| - {id: string}| - {js: string}| - {linkText: string}| - {name: string}| - {partialLinkText: string}| - {tagName: string}| - {xpath: string}; - } - - /** - * An element locator. - */ - class Locator { - /** - * An element locator. - * @param {string} using The type of strategy to use for this locator. - * @param {string} value The search target of this locator. - * @constructor - */ - constructor(using: string, value: string); - - - /** - * Maps {@link webdriver.By.Hash} keys to the appropriate factory function. - * @type {!Object.} - * @const - */ - static Strategy: { - className: typeof webdriver.By.className; - css: typeof webdriver.By.css; - id: typeof webdriver.By.id; - js: typeof webdriver.By.js; - linkText: typeof webdriver.By.linkText; - name: typeof webdriver.By.name; - partialLinkText: typeof webdriver.By.partialLinkText; - tagName: typeof webdriver.By.tagName; - xpath: typeof webdriver.By.xpath; - }; - - /** - * Verifies that a {@code value} is a valid locator to use for searching for - * elements on the page. - * - * @param {*} value The value to check is a valid locator. - * @return {!(webdriver.Locator|Function)} A valid locator object or function. - * @throws {TypeError} If the given value is an invalid locator. - */ - static checkLocator(value: any): Locator | Function; - - /** - * The search strategy to use when searching for an element. - * @type {string} - */ - using: string; - - /** - * The search target for this locator. - * @type {string} - */ - value: string; - - /** @return {string} String representation of this locator. */ - toString(): string; + catch(errback: Function): webdriver.promise.Promise; } /** @@ -5275,8 +6468,7 @@ declare namespace webdriver { * capabilities. * @constructor */ - constructor(id: string, capabilities: Capabilities); - constructor(id: string, capabilities: any); + constructor(id: string, capabilities: Capabilities|Object); //endregion @@ -5290,7 +6482,7 @@ declare namespace webdriver { /** * @return {!webdriver.Capabilities} This session's capabilities. */ - getCapabilities(): Capabilities; + getCapabilities(): webdriver.Capabilities; /** * Retrieves the value of a specific capability. @@ -5376,10 +6568,6 @@ declare module 'selenium-webdriver/chrome' { export = chrome; } -declare module 'selenium-webdriver/firefox' { - export = firefox; -} - declare module 'selenium-webdriver/executors' { export = executors; } diff --git a/selenium-webdriver/selenium-webdriver-tests.ts b/selenium-webdriver/selenium-webdriver-tests.ts index da141b8eb3..8833933ad1 100644 --- a/selenium-webdriver/selenium-webdriver-tests.ts +++ b/selenium-webdriver/selenium-webdriver-tests.ts @@ -3,7 +3,7 @@ function TestChromeDriver() { var driver: chrome.Driver = new chrome.Driver(); driver = new chrome.Driver(webdriver.Capabilities.chrome()); - driver = new chrome.Driver(webdriver.Capabilities.chrome(), new webdriver.promise.ControlFlow()); + driver = new chrome.Driver(webdriver.Capabilities.chrome(), new remote.DriverService('executable', new chrome.Options()), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -31,7 +31,6 @@ function TestChromeOptions() { options = options.setUserPreferences("preferences"); var capabilities: webdriver.Capabilities = options.toCapabilities(); capabilities = options.toCapabilities(webdriver.Capabilities.chrome()); - var values: chrome.IOptionsValues = options.toJSON(); } function TestServiceBuilder() { @@ -52,7 +51,7 @@ function TestServiceBuilder() { function TestChromeModule() { var service: any = chrome.getDefaultService(); - chrome.setDefaultService({}); + chrome.setDefaultService(new remote.DriverService('executable', new chrome.Options())); } function TestBinary() { @@ -66,8 +65,8 @@ function TestBinary() { function TestFirefoxDriver() { var driver: firefox.Driver = new firefox.Driver(); - driver = new chrome.Driver(webdriver.Capabilities.firefox()); - driver = new chrome.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); + driver = new firefox.Driver(webdriver.Capabilities.firefox()); + driver = new firefox.Driver(webdriver.Capabilities.firefox(), new webdriver.promise.ControlFlow()); var baseDriver: webdriver.WebDriver = driver; } @@ -82,7 +81,6 @@ function TestFirefoxOptions() { options = options.setProfile(new firefox.Profile()); options = options.setProxy({ proxyType: "proxy" }); var capabilities: webdriver.Capabilities = options.toCapabilities(); - var capabilities: webdriver.Capabilities = options.toCapabilities({}); } function TestFirefoxProfile() { @@ -108,7 +106,7 @@ function TestFirefoxProfile() { } function TestExecutors() { - var exec: webdriver.CommandExecutor = executors.createExecutor("url"); + var exec: webdriver.Executor = executors.createExecutor("url"); var promise: webdriver.promise.Promise; exec = executors.createExecutor(promise); } @@ -144,7 +142,9 @@ function TestActionSequence() { build(); var sequence: webdriver.ActionSequence = new webdriver.ActionSequence(driver); - var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); + var promise: webdriver.promise.Promise; + element = new webdriver.WebElement(driver, promise); // Click sequence = sequence.click(); @@ -187,7 +187,6 @@ function TestActionSequence() { // SendKeys sequence = sequence.sendKeys("A", "B", "C"); - sequence = sequence.sendKeys(["A", "B", "C"]); sequence.perform().then(function () { }); } @@ -196,7 +195,7 @@ function TestTouchSequence() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var element: webdriver.WebElement = new webdriver.WebElement(driver, { ELEMENT: 'id' }); + var element: webdriver.WebElement = new webdriver.WebElement(driver, 'elementId'); var sequence: webdriver.TouchSequence = new webdriver.TouchSequence(driver); @@ -319,9 +318,9 @@ function TestCommand() { command = command.setParameters({ param: 123 }); } -function TestCommandExecutor() { - var c: webdriver.CommandExecutor = { execute: function (command: webdriver.Command, callback: (error: Error, obj: any) => any) { } }; - c.execute(new webdriver.Command('name'), function (error: Error, response: any) { }); +function TestDeferredExecutor() { + var promise: webdriver.promise.Promise; + var executor: webdriver.DeferredExecutor = new webdriver.DeferredExecutor(promise); } function TestCommandName() { @@ -458,7 +457,7 @@ function TestEventEmitter() { } function TestKey() { - var key: string; + var key: webdriver.Key; key = webdriver.Key.ADD; key = webdriver.Key.ALT; @@ -520,35 +519,15 @@ function TestKey() { key = webdriver.Key.SUBTRACT; key = webdriver.Key.TAB; key = webdriver.Key.UP; - - key = webdriver.Key.chord(webdriver.Key.NUMPAD0, webdriver.Key.NUMPAD1); } -function TestLocator() { +function TestBy() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.Locator = new webdriver.Locator('class name', 'class'); + var locator: webdriver.By = new webdriver.By('class name', 'class'); - var locatorOrFn: webdriver.Locator|Function; - - locatorOrFn = webdriver.Locator.Strategy.className; - locatorOrFn = webdriver.Locator.Strategy.css; - locatorOrFn = webdriver.Locator.Strategy.id; - locatorOrFn = webdriver.Locator.Strategy.js; - locatorOrFn = webdriver.Locator.Strategy.linkText; - locatorOrFn = webdriver.Locator.Strategy.name; - locatorOrFn = webdriver.Locator.Strategy.partialLinkText; - locatorOrFn = webdriver.Locator.Strategy.tagName; - locatorOrFn = webdriver.Locator.Strategy.xpath; - - locatorOrFn = webdriver.Locator.checkLocator(locator); - locatorOrFn = webdriver.Locator.checkLocator({ className: 'class' }); - locatorOrFn = webdriver.Locator.checkLocator(Error); - - var using: string = locator.using; - var value: string = locator.value; var str: string = locator.toString(); locator = webdriver.By.className('class'); @@ -563,7 +542,7 @@ function TestLocator() { // Can import "By" without import declarations var By = webdriver.By; - var locatorHash: webdriver.By.Hash; + var locatorHash: webdriver.ByHash; locatorHash = { className: 'class' }; locatorHash = { css: 'css' }; locatorHash = { id: 'id' }; @@ -591,9 +570,7 @@ function TestSession() { function TestUnhandledAlertError() { var someFunc = function (error: webdriver.UnhandledAlertError) { - var baseError: webdriver.error.Error = error; - - var alert: webdriver.Alert = error.getAlert(); + var baseError: Error = error; var str: string = error.getAlertText(); str = error.toString(); } @@ -614,7 +591,7 @@ function TestWebDriverLogs() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var logs: webdriver.WebDriverLogs = new webdriver.WebDriver.Logs(driver); + var logs: webdriver.Logs = new webdriver.Logs(driver); logs.get(webdriver.logging.Type.BROWSER).then(function (entries: webdriver.logging.Entry[]) { });; logs.getAvailableLogTypes().then(function (types: string[]) { }); @@ -625,7 +602,7 @@ function TestWebDriverNavigation() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var navigation: webdriver.WebDriverNavigation = new webdriver.WebDriver.Navigation(driver); + var navigation: webdriver.Navigation = new webdriver.Navigation(driver); navigation.back().then(function () { }); navigation.forward().then(function () { }); @@ -638,7 +615,7 @@ function TestWebDriverOptions() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var options: webdriver.WebDriverOptions = new webdriver.WebDriver.Options(driver); + var options: webdriver.Options = new webdriver.Options(driver); var promise: webdriver.promise.Promise; // Add Cookie @@ -654,9 +631,9 @@ function TestWebDriverOptions() { options.getCookie('name').then(function (cookies: webdriver.IWebDriverOptionsCookie) { }); options.getCookies().then(function (cookies: webdriver.IWebDriverOptionsCookie[]) { }); - var logs: webdriver.WebDriverLogs = options.logs(); - var timeouts: webdriver.WebDriverTimeouts = options.timeouts(); - var window: webdriver.WebDriverWindow = options.window(); + var logs: webdriver.Logs = options.logs(); + var timeouts: webdriver.Timeouts = options.timeouts(); + var window: webdriver.Window = options.window(); } function TestWebDriverTargetLocator() { @@ -664,13 +641,12 @@ function TestWebDriverTargetLocator() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var locator: webdriver.WebDriverTargetLocator = new webdriver.WebDriver.TargetLocator(driver); + var locator: webdriver.TargetLocator = new webdriver.TargetLocator(driver); var promise: webdriver.promise.Promise; var element: webdriver.WebElement = locator.activeElement(); var alert: webdriver.Alert = locator.alert(); promise = locator.defaultContent(); - promise = locator.frame('name'); promise = locator.frame(1); promise = locator.window('nameOrHandle'); } @@ -680,7 +656,7 @@ function TestWebDriverTimeouts() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var timeouts: webdriver.WebDriverTimeouts = new webdriver.WebDriver.Timeouts(driver); + var timeouts: webdriver.Timeouts = new webdriver.Timeouts(driver); var promise: webdriver.promise.Promise; promise = timeouts.implicitlyWait(123); @@ -693,7 +669,7 @@ function TestWebDriverWindow() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var window: webdriver.WebDriverWindow = new webdriver.WebDriver.Window(driver); + var window: webdriver.Window = new webdriver.Window(driver); var locationPromise: webdriver.promise.Promise; var sizePromise: webdriver.promise.Promise; var voidPromise: webdriver.promise.Promise; @@ -708,7 +684,7 @@ function TestWebDriverWindow() { function TestWebDriver() { var session: webdriver.Session = new webdriver.Session('ABC', webdriver.Capabilities.android()); var sessionPromise: webdriver.promise.Promise; - var executor: webdriver.CommandExecutor = executors.createExecutor("http://someserver"); + var executor: webdriver.Executor = executors.createExecutor("http://someserver"); var flow: webdriver.promise.ControlFlow = new webdriver.promise.ControlFlow(); var driver: webdriver.WebDriver = new webdriver.WebDriver(session, executor); driver = new webdriver.WebDriver(session, executor, flow); @@ -746,15 +722,11 @@ function TestWebDriver() { // findElement var element: webdriver.WebElement; element = driver.findElement(webdriver.By.id('ABC')); - element = driver.findElement({id: 'ABC'}); element = driver.findElement(webdriver.By.js('function(){}')); - element = driver.findElement({js: 'function(){}'}); // findElements driver.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); driver.findElements(webdriver.By.js('function(){}')).then(function (elements: webdriver.WebElement[]) { }); - driver.findElements({ js: 'function(){}' }).then(function (elements: webdriver.WebElement[]) { }); voidPromise = driver.get('http://www.google.com'); driver.getAllWindowHandles().then(function (handles: string[]) { }); @@ -766,13 +738,11 @@ function TestWebDriver() { stringPromise = driver.getWindowHandle(); booleanPromise = driver.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = driver.isElementPresent({className: 'ABC'}); booleanPromise = driver.isElementPresent(webdriver.By.js('function(){}')); - booleanPromise = driver.isElementPresent({js: 'function(){}'}); - var options: webdriver.WebDriverOptions = driver.manage(); - var navigation: webdriver.WebDriverNavigation = driver.navigate(); - var locator: webdriver.WebDriverTargetLocator = driver.switchTo(); + var options: webdriver.Options = driver.manage(); + var navigation: webdriver.Navigation = driver.navigate(); + var locator: webdriver.TargetLocator = driver.switchTo(); var fileDetector: webdriver.FileDetector = new webdriver.FileDetector(); driver.setFileDetector(fileDetector); @@ -795,7 +765,7 @@ function TestWebDriver() { function TestSerializable() { var serializable: webdriver.Serializable; - var serial: string|webdriver.promise.Promise = serializable.serialize(); + var serial: string|webdriver.promise.IThenable = serializable.serialize(); } function TestWebElement() { @@ -803,10 +773,10 @@ function TestWebElement() { withCapabilities(webdriver.Capabilities.chrome()). build(); - var promise: webdriver.promise.Promise; + var promise: webdriver.promise.Promise; var element: webdriver.WebElement; - element = new webdriver.WebElement(driver, { ELEMENT: 'ID' }); + element = new webdriver.WebElement(driver, 'elementId'); element = new webdriver.WebElement(driver, promise); var voidPromise: webdriver.promise.Promise; @@ -817,13 +787,8 @@ function TestWebElement() { voidPromise = element.click(); element = element.findElement(webdriver.By.id('ABC')); - element = element.findElement({id: 'ABC'}); - element.findElements(webdriver.By.className('ABC')).then(function (elements: webdriver.WebElement[]) { }); - element.findElements({ className: 'ABC' }).then(function (elements: webdriver.WebElement[]) { }); - booleanPromise = element.isElementPresent(webdriver.By.className('ABC')); - booleanPromise = element.isElementPresent({className: 'ABC'}); stringPromise = element.getAttribute('class'); stringPromise = element.getCssValue('display'); @@ -840,14 +805,11 @@ function TestWebElement() { voidPromise = element.sendKeys('A', 'B', 'C'); voidPromise = element.sendKeys(stringPromise, stringPromise, stringPromise); voidPromise = element.submit(); - element.getId().then(function (id: typeof webdriver.WebElement.Id) { }); + element.getId().then(function (id: string) { }); element.getRawId().then(function (id: string) { }); - element.serialize().then(function (id: typeof webdriver.WebElement.Id) { }); + element.serialize().then(function (id: webdriver.IWebElementId) { }); - booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, { ELEMENT: 'ID2' })); - - var id: typeof webdriver.WebElement.Id = webdriver.WebElement.Id; - var key: string = webdriver.WebElement.ELEMENT_KEY; + booleanPromise = webdriver.WebElement.equals(element, new webdriver.WebElement(driver, 'elementId')); } function TestWebElementPromise() { @@ -877,7 +839,7 @@ function TestLogging() { preferences.setLevel(webdriver.logging.Type.BROWSER, webdriver.logging.Level.ALL); var prefs: any = preferences.toJSON(); - var level: webdriver.logging.ILevel = webdriver.logging.getLevel('OFF'); + var level: webdriver.logging.Level = webdriver.logging.getLevel('OFF'); level = webdriver.logging.getLevel(1); level = webdriver.logging.Level.ALL; @@ -887,10 +849,10 @@ function TestLogging() { level = webdriver.logging.Level.SEVERE; level = webdriver.logging.Level.WARNING; - var name: string = level.name; - var value: number = level.value; + var name: string = level.name(); + var value: number = level.value(); - var type: string; + var type: webdriver.logging.Type; type = webdriver.logging.Type.BROWSER; type = webdriver.logging.Type.CLIENT; type = webdriver.logging.Type.DRIVER; @@ -913,9 +875,6 @@ function TestLoggingEntry() { var message: string = entry.message; var timestamp: number = entry.timestamp; var type: string = entry.type; - - entry = webdriver.logging.Entry.fromClosureLogRecord({}); - entry = webdriver.logging.Entry.fromClosureLogRecord({}, webdriver.logging.Type.DRIVER); } function TestPromiseModule() { @@ -946,29 +905,29 @@ function TestPromiseModule() { return 5; }, this, 1, 2, 3).then(function (value: number) { }); - var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { + var numbersPromise: webdriver.promise.Promise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter([1, 2, 3], function (element: number, type: any, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.filter(numbersPromise, function (element: number, type: any, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map([1, 2, 3], function (el: number, type: any, index: number, arr: number[]) { return true; }, this); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { return true; }); - numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + numbersPromise = webdriver.promise.map(numbersPromise, function (el: number, type: any, index: number, arr: number[]) { return true; }, this); @@ -995,26 +954,13 @@ function TestPromiseModule() { var bool: boolean = webdriver.promise.isGenerator(function () { }); var isPromise: boolean = webdriver.promise.isPromise('ABC'); - voidPromise = webdriver.promise.rejected({a: 123}); + stringPromise = webdriver.promise.rejected('{a: 123}'); webdriver.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); numberPromise = webdriver.promise.when('abc', function(value: any) { return 123; }, function(err: Error) { return 123; }); } -function TestStacktraceModule() { - var bool: boolean = webdriver.stacktrace.BROWSER_SUPPORTED; - - var frame: webdriver.stacktrace.Frame = new webdriver.stacktrace.Frame(); - var baseFrame: webdriver.stacktrace.Frame = frame; - - var snapshot: webdriver.stacktrace.Snapshot = new webdriver.stacktrace.Snapshot(); - var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; - - var err: Error = webdriver.stacktrace.format(new Error("Error")); - var frames: webdriver.stacktrace.Frame[] = webdriver.stacktrace.get(); -} - function TestUntilModule() { var driver: webdriver.WebDriver = new webdriver.Builder(). withCapabilities(webdriver.Capabilities.chrome()). @@ -1125,13 +1071,12 @@ function TestPromiseClass() { } function TestThenableClass() { - var thenable: webdriver.promise.Thenable = new webdriver.promise.Thenable(); + var thenable: webdriver.promise.Promise = new webdriver.promise.Promise(); thenable.cancel('Abort'); var isPending: boolean = thenable.isPending(); - thenable = thenable.then(); thenable = thenable.then(function (a: string) { return 'cde'; }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { }); thenable = thenable.then(function (a: string) { return 'cde'; }, function (e: any) { return 123; }); @@ -1144,76 +1089,30 @@ function TestThenableClass() { function TestErrorCode() { var errorCode: number; - errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE; - errorCode = webdriver.error.ErrorCode.ELEMENT_NOT_VISIBLE; - errorCode = webdriver.error.ErrorCode.IME_ENGINE_ACTIVATION_FAILED; - errorCode = webdriver.error.ErrorCode.IME_NOT_AVAILABLE; - errorCode = webdriver.error.ErrorCode.INVALID_COOKIE_DOMAIN; - errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_COORDINATES; - errorCode = webdriver.error.ErrorCode.INVALID_ELEMENT_STATE; - errorCode = webdriver.error.ErrorCode.INVALID_SELECTOR_ERROR; - errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR; - errorCode = webdriver.error.ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPE; - errorCode = webdriver.error.ErrorCode.JAVASCRIPT_ERROR; - errorCode = webdriver.error.ErrorCode.METHOD_NOT_ALLOWED; - errorCode = webdriver.error.ErrorCode.MODAL_DIALOG_OPENED; - errorCode = webdriver.error.ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS; - errorCode = webdriver.error.ErrorCode.NO_MODAL_DIALOG_OPEN; - errorCode = webdriver.error.ErrorCode.NO_SUCH_ELEMENT; - errorCode = webdriver.error.ErrorCode.NO_SUCH_FRAME; - errorCode = webdriver.error.ErrorCode.NO_SUCH_WINDOW; - errorCode = webdriver.error.ErrorCode.SCRIPT_TIMEOUT; - errorCode = webdriver.error.ErrorCode.SESSION_NOT_CREATED; - errorCode = webdriver.error.ErrorCode.SQL_DATABASE_ERROR; - errorCode = webdriver.error.ErrorCode.STALE_ELEMENT_REFERENCE; - errorCode = webdriver.error.ErrorCode.SUCCESS; - errorCode = webdriver.error.ErrorCode.TIMEOUT; - errorCode = webdriver.error.ErrorCode.UNABLE_TO_SET_COOKIE; - errorCode = webdriver.error.ErrorCode.UNKNOWN_COMMAND; - errorCode = webdriver.error.ErrorCode.UNKNOWN_ERROR; - errorCode = webdriver.error.ErrorCode.UNSUPPORTED_OPERATION; - errorCode = webdriver.error.ErrorCode.XPATH_LOOKUP_ERROR; -} - -function TestError() { - var error: webdriver.error.Error; - - error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE); - error = new webdriver.error.Error(webdriver.error.ErrorCode.ELEMENT_NOT_SELECTABLE, 'Message'); - - var code: number = error.code; - var state: string = error.state; - var message: string = error.message; - var name: string = error.name; - var stack: string = error.stack; - var isAutomationError: boolean = error.isAutomationError; - var errorStr: string = error.toString(); - - state = webdriver.error.Error.State.ELEMENT_NOT_SELECTABLE - state = webdriver.error.Error.State.ELEMENT_NOT_VISIBLE; - state = webdriver.error.Error.State.IME_ENGINE_ACTIVATION_FAILED; - state = webdriver.error.Error.State.IME_NOT_AVAILABLE; - state = webdriver.error.Error.State.INVALID_COOKIE_DOMAIN; - state = webdriver.error.Error.State.INVALID_ELEMENT_COORDINATES; - state = webdriver.error.Error.State.INVALID_ELEMENT_STATE; - state = webdriver.error.Error.State.INVALID_SELECTOR; - state = webdriver.error.Error.State.JAVASCRIPT_ERROR; - state = webdriver.error.Error.State.MOVE_TARGET_OUT_OF_BOUNDS; - state = webdriver.error.Error.State.NO_SUCH_ALERT; - state = webdriver.error.Error.State.NO_SUCH_DOM - state = webdriver.error.Error.State.NO_SUCH_ELEMENT; - state = webdriver.error.Error.State.NO_SUCH_FRAME; - state = webdriver.error.Error.State.NO_SUCH_WINDOW; - state = webdriver.error.Error.State.SCRIPT_TIMEOUT; - state = webdriver.error.Error.State.SESSION_NOT_CREATED; - state = webdriver.error.Error.State.STALE_ELEMENT_REFERENCE; - state = webdriver.error.Error.State.SUCCESS; - state = webdriver.error.Error.State.TIMEOUT; - state = webdriver.error.Error.State.UNABLE_TO_SET_COOKIE; - state = webdriver.error.Error.State.UNEXPECTED_ALERT_OPEN - state = webdriver.error.Error.State.UNKNOWN_COMMAND; - state = webdriver.error.Error.State.UNKNOWN_ERROR; - state = webdriver.error.Error.State.UNSUPPORTED_OPERATION; + errorCode = new webdriver.error.ElementNotSelectableError().code(); + errorCode = new webdriver.error.ElementNotVisibleError().code(); + errorCode = new webdriver.error.InvalidArgumentError().code(); + errorCode = new webdriver.error.InvalidCookieDomainError().code(); + errorCode = new webdriver.error.InvalidElementCoordinatesError().code(); + errorCode = new webdriver.error.InvalidElementStateError().code(); + errorCode = new webdriver.error.InvalidSelectorError().code(); + errorCode = new webdriver.error.NoSuchSessionError().code(); + errorCode = new webdriver.error.JavascriptError().code(); + errorCode = new webdriver.error.MoveTargetOutOfBoundsError().code(); + errorCode = new webdriver.error.NoSuchAlertError().code(); + errorCode = new webdriver.error.NoSuchElementError().code(); + errorCode = new webdriver.error.NoSuchFrameError().code(); + errorCode = new webdriver.error.NoSuchWindowError().code(); + errorCode = new webdriver.error.ScriptTimeoutError().code(); + errorCode = new webdriver.error.SessionNotCreatedError().code(); + errorCode = new webdriver.error.StaleElementReferenceError().code(); + errorCode = new webdriver.error.TimeoutError().code(); + errorCode = new webdriver.error.UnableToSetCookieError().code(); + errorCode = new webdriver.error.UnableToCaptureScreenError().code(); + errorCode = new webdriver.error.UnexpectedAlertOpenError().code(); + errorCode = new webdriver.error.UnknownCommandError().code(); + errorCode = new webdriver.error.UnknownMethodError().code(); + errorCode = new webdriver.error.UnsupportedOperationError().code(); } function TestTestingModule() { From 895592ef94f5d192e3f861646d258d5362c1b8ce Mon Sep 17 00:00:00 2001 From: Simon Date: Mon, 19 Sep 2016 20:11:18 -0400 Subject: [PATCH 160/212] fixes model.discriminator() signature fixes #11323 fixes #10878 --- mongoose/mongoose-tests.ts | 15 +++++++++++++-- mongoose/mongoose.d.ts | 2 +- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 5feb08b446..03dde5759b 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -1124,7 +1124,6 @@ MongoModel.create([{ type: 'jelly bean' }, { 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); @@ -1386,4 +1385,16 @@ Final2.staticMethod(); Final2.staticProp; var final2 = new Final2(); final2.prop; -final2.method; \ No newline at end of file +final2.method; +interface ibase extends mongoose.Document { + username: string; +} +interface extended extends ibase { + email: string; +} +const base: mongoose.Model = mongoose.model('testfour', null) +const extended: mongoose.Model = base.discriminator('extendedS', null); +const x = new extended({ + username: 'hi', // required in baseSchema + email: 'beddiw', // required in extededSchema +}) \ No newline at end of file diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 2d0046ea8c..6456fdc003 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2119,7 +2119,7 @@ declare module "mongoose" { * @param name discriminator model name * @param schema discriminator model schema */ - discriminator(name: string, schema: Schema): T; + 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; From 7b7c3a630ca727ad96463ed8e7d51872f0969408 Mon Sep 17 00:00:00 2001 From: Craig Nishina Date: Mon, 19 Sep 2016 11:10:30 -0700 Subject: [PATCH 161/212] attempt to fix angular-protractor tests --- protractor-helpers/index.d.ts | 111 + protractor-helpers/package.json | 11 + .../protractor-helpers-tests.ts | 116 ++ protractor-helpers/tsconfig.json | 16 + protractor-http-mock/index.d.ts | 284 +++ protractor-http-mock/package.json | 10 + .../protractor-http-mock-tests.ts | 302 +++ protractor-http-mock/tsconfig.json | 16 + protractor/angular-protractor-tests.ts | 483 +++++ protractor/index.d.ts | 1849 +++++++++++++++++ protractor/package.json | 10 + protractor/tsconfig.json | 16 + 12 files changed, 3224 insertions(+) create mode 100644 protractor-helpers/index.d.ts create mode 100644 protractor-helpers/package.json create mode 100644 protractor-helpers/protractor-helpers-tests.ts create mode 100644 protractor-helpers/tsconfig.json create mode 100644 protractor-http-mock/index.d.ts create mode 100644 protractor-http-mock/package.json create mode 100644 protractor-http-mock/protractor-http-mock-tests.ts create mode 100644 protractor-http-mock/tsconfig.json create mode 100644 protractor/angular-protractor-tests.ts create mode 100644 protractor/index.d.ts create mode 100644 protractor/package.json create mode 100644 protractor/tsconfig.json diff --git a/protractor-helpers/index.d.ts b/protractor-helpers/index.d.ts new file mode 100644 index 0000000000..00df7cff98 --- /dev/null +++ b/protractor-helpers/index.d.ts @@ -0,0 +1,111 @@ +// Type definitions for protractor-helpers v1.0.0 +// Project: https://github.com/wix/protractor-helpers +// Definitions by: John Cant +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + + +/// +/// + +// ElementArrayFinder + +declare namespace protractor { + interface ElementArrayFinder { + getByText(text: string) : protractor.ElementFinder; + $$data(hook: string) : protractor.ElementArrayFinder; + } + + interface ElementFinder { + $data(hook: string) : protractor.ElementFinder; + } +} + +// Globals + +declare function $data(hook: string) : protractor.ElementFinder; +declare function $$data(hook: string) : protractor.ElementArrayFinder; + + +// Locators + +// TODO - find out about result of querySelector and querySelector all. +// Are they Locator s? +declare namespace protractor { + interface IProtractorLocatorStrategy { + dataHook(hook: string, optParentElement?: protractor.ElementFinder, optRootSelector?: string) : webdriver.Locator; + dataHookAll(hook: string, optParentElement?: protractor.ElementFinder, optRootSelector?: string) : webdriver.Locator; + } +} + +// Matchers +// TODO - Typescript doesn't really help much here +// we don't know what type is being tested. +// Fixing this would require modifying the +// jasmine d.ts. + +declare namespace jasmine { + interface Matchers { + toBePresent() : boolean; + toBeDisplayed() : boolean; + toHaveCountOf(expectedCount : number) : boolean; + toHaveText(expectedText : string) : boolean; + toMatchRegex(regex : RegExp) : boolean; + toMatchMoney(expectedValue : number, currencySymbol? : string) : boolean; + toMatchMoneyWithFraction(expectedValue : number, currencySymbol?: string) : boolean; + toHaveValue(actual: string | number) : boolean; + toHaveClass(className : string) : boolean; + toHaveUrl(url : string) : boolean; + toBeDisabled() : boolean; + toBeChecked() : boolean; + toBeValid() : boolean; + toBeInvalid() : boolean; + toBeInvalidRequired() : boolean; + // Copied definitions from angular-translate. + toMatchTranslated(translationId : string, interpolateParams? : any) : boolean; + toMatchTranslated(translationId : string[], interpolateParams? : any) : boolean; + } +} + + +declare module "protractor-helpers" { + + function not(arg: webdriver.promise.IThenable) : webdriver.promise.IThenable; + + // Copied definitions from angular-translate. + function translate(translationId: string, interpolateParams?: any): webdriver.promise.IThenable; + function translate(translationId: string[], interpolateParams?: any): webdriver.promise.IThenable<{ [key: string]: string }>; + + function safeGet(url: string) : void; + + function maximizeWindow(width?: number, height?: number) : void; // TODO + function resetPosition() : void; + function moveToElement(hook: string) : void; + function displayHover(element: protractor.ElementFinder) : void; + + function waitForElement(element: protractor.ElementFinder, timeout?: number) : void; + function waitForElementToDisappear(element: protractor.ElementFinder, timeout?: number) : void; + + function selectOptionByText(select: protractor.ElementFinder, text: string) : void; + function selectOptionByIndex(select: protractor.ElementFinder, index: number) : void; + + function selectOption(option: protractor.ElementFinder) : void + + function isFirefox() : boolean; + function isIE() : boolean; + + function createMessage(actual : string, message : string, isNot : any) : string; // isNot : boolean too inflexible + function createMessage(actual : protractor.ElementFinder, message : string, isNot : any) : string; // isNot : boolean too inflexible + function createMessage(actual : protractor.ElementArrayFinder, message : string, isNot : any) : string; // isNot : boolean too inflexible + + function clearAndSetValue(input : protractor.ElementFinder, value : string) : void; // TODO - sendKeys(value) + + function hasClass(element: protractor.ElementFinder, className: string) : webdriver.promise.IThenable; + function hasValue(element: protractor.ElementFinder, expectedValue: string) : webdriver.promise.IThenable; + function hasValue(element: protractor.ElementFinder, expectedValue: number) : webdriver.promise.IThenable; + function hasLink(element: protractor.ElementFinder, url: string) : webdriver.promise.IThenable; + function isDisabled(element: protractor.ElementFinder) : webdriver.promise.IThenable; + function isChecked(element: protractor.ElementFinder) : webdriver.promise.IThenable; + function getFilteredConsoleErrors() : webdriver.promise.IThenable; // TODO - discuss handling in IE + +} + diff --git a/protractor-helpers/package.json b/protractor-helpers/package.json new file mode 100644 index 0000000000..ae3b947610 --- /dev/null +++ b/protractor-helpers/package.json @@ -0,0 +1,11 @@ +{ + "name": "protractor-helpers", + "version": "1.0.0", + "description": "protractor helpers", + "author": "", + "license": "MIT", + "dependencies": { + "@types/jasmine": "^2.2.34", + "@types/selenium-webdriver": "~2.44.28" + } +} diff --git a/protractor-helpers/protractor-helpers-tests.ts b/protractor-helpers/protractor-helpers-tests.ts new file mode 100644 index 0000000000..269390080e --- /dev/null +++ b/protractor-helpers/protractor-helpers-tests.ts @@ -0,0 +1,116 @@ + + +import helpers = require('protractor-helpers'); + +declare var $$: any, $: any, by: any, element: any; // ?? + +function testElementArrayFinder() { + + var single1 : protractor.ElementFinder = $$('.foo').getByText('Hello'); + var multiple : protractor.ElementArrayFinder = $$('.foo').$$data('Hello'); + +} + +function testElementFinder () { + var single2 : protractor.ElementFinder = $('.foo').$data('Hello'); +} + +function testGlobals() { + + var single : protractor.ElementFinder = $data('Hello'); + var multiple : protractor.ElementArrayFinder = $$data('Hello'); + +} + +function testHelpers() { + + var q0 : webdriver.promise.IThenable = helpers.not($('.foo').isDisplayed()); + // TODO - Check impl + var q1 : webdriver.promise.IThenable<{[key: string]:string}> = helpers.translate(["foo", "bar"]); + var q2 : webdriver.promise.IThenable<{[key: string]:string}> = helpers.translate(["foo", "bar"], {name: 'foo'}); + var q3 : webdriver.promise.IThenable = helpers.translate("foo"); + var q4 : webdriver.promise.IThenable = helpers.translate("foo", {name: 'foo'}); + + helpers.safeGet('https://foo/'); + + helpers.maximizeWindow(500, 500); + helpers.maximizeWindow(500); + helpers.maximizeWindow(undefined, 500); + helpers.maximizeWindow(); + + helpers.resetPosition(); + helpers.moveToElement(".foo"); // TODO - ? + + helpers.displayHover($('.foo')); + + helpers.waitForElement($('.foo')); + helpers.waitForElement($('.foo'), 1000); + helpers.waitForElementToDisappear($('.foo'));; + helpers.waitForElementToDisappear($('.foo'), 1000); + + helpers.selectOptionByText($('select'), "GB"); + helpers.selectOptionByIndex($('select'), 1); + + helpers.selectOption($$('select option').first()); + + var ff : boolean = helpers.isFirefox(); + var ie : boolean = helpers.isIE(); + + var msg : string = helpers.createMessage("actual", "message", true); + var msg : string = helpers.createMessage($('.foo'), "message", true); + var msg : string = helpers.createMessage($$('.foo'), "message", true); + + helpers.clearAndSetValue($('input'), 'Foo'); + + var hc : webdriver.promise.IThenable = helpers.hasClass($('.foo'), 'foo'); + + var hv : webdriver.promise.IThenable = helpers.hasValue($('input[type=text]'), 'foo'); + var hv1 : webdriver.promise.IThenable = helpers.hasValue($('input[type=numeric]'), 12); + var hl : webdriver.promise.IThenable = helpers.hasLink($('div'), 'http://foo.com'); + var disabled : webdriver.promise.IThenable = helpers.isDisabled($('foo')); + var checked : webdriver.promise.IThenable = helpers.isChecked($('foo')); + + var q5 : webdriver.promise.IThenable = helpers.getFilteredConsoleErrors(); + +} + +function testLocators() { + + element(by.dataHook("foo")); + element(by.dataHook("foo", $('.parentfoo'))); + element(by.dataHook("foo", undefined , ".foo")); + element(by.dataHook("foo", $('.parentfoo'), ".foo")); // TODO - This might not make much sense, but can technically be used in working code. Opinions welcome + + element.all(by.dataHook("foo")); + element.all(by.dataHook("foo", $('parentfoo'))); + element.all(by.dataHook("foo", undefined , ".foo")); + element.all(by.dataHook("foo", $('parentfoo'), ".foo")); // TODO - This might not make much sense, but can technically be used in working code. Opinions welcome + +} + +function testMatchers() { + + var expectResult : boolean; + expectResult = expect($('.foo')).toBePresent(); + expectResult = expect($('.foo')).toBeDisplayed(); + expectResult = expect($$('.foo').count()).toHaveCountOf(1); + expectResult = expect($('.foo')).toHaveText("bla"); + expectResult = expect($('.foo')).toMatchRegex(/bla/); + expectResult = expect($('.foo').getText()).toMatchMoney(123, "£"); + expectResult = expect($('.foo').getText()).toMatchMoneyWithFraction(123.45, "£"); + expectResult = expect($('input')).toHaveValue(12); + expectResult = expect($('input')).toHaveValue("bla"); + expectResult = expect($('.foo')).toHaveClass("foo"); + expectResult = expect($('.foo')).toHaveUrl('https://foo.com'); + expectResult = expect($('.foo')).toBeDisabled(); + expectResult = expect($('.foo')).toBeChecked(); + expectResult = expect($('.foo')).toBeValid(); + expectResult = expect($('.foo')).toBeInvalid(); + expectResult = expect($('.foo')).toBeInvalidRequired(); + expectResult = expect($('.foo')).toMatchTranslated("foo"); + expectResult = expect($('.foo')).toMatchTranslated("foo", {foo: "bar"}); + expectResult = expect($('.foo')).toMatchTranslated(["foo"]); + expectResult = expect($('.foo')).toMatchTranslated(["foo", "bla"], {foo: "bar"}); + +} + diff --git a/protractor-helpers/tsconfig.json b/protractor-helpers/tsconfig.json new file mode 100644 index 0000000000..897492ad71 --- /dev/null +++ b/protractor-helpers/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "types": ["jasmine", "selenium-webdriver"], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "protractor-helpers-tests.ts" + ] +} diff --git a/protractor-http-mock/index.d.ts b/protractor-http-mock/index.d.ts new file mode 100644 index 0000000000..5f9dbcd79a --- /dev/null +++ b/protractor-http-mock/index.d.ts @@ -0,0 +1,284 @@ +// Type definitions for protractor-http-mock +// Project: https://github.com/atecarlos/protractor-http-mock +// Definitions by: Crevil +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace mock { + interface ProtractorHttpMock { + /** + * Instantiate mock module. This must be done before the browser connects. + * + * @param mocks An array of mock modules to load into the application. + * @param plugins An array of Plugin objects. + * @param skipDefaults Set true to skip loading of default mocks. + */ + (mocks?: Array>, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; + + /** + * Instantiate mock module. This must be done before the browser connects. + * + * @param mocks An array of mock modules to load into the application. + * @param plugins An array of NPM modules as strings. + * @param skipDefaults Set true to skip loading of default mocks. + */ + (mocks?: Array>, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; + + /** + * Instantiate mock modules from files. This must be done before the browser connects. + * + * @param mocks An array of mock module names relative to the rootDirectory configuration. + * @param plugins An array of Plugin objects. + * @param skipDefaults Set true to skip loading of default mocks. + */ + (mocks: Array, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; + + /** + * Instantiate mock modules from files. This must be done before the browser connects. + * + * @param mocks An array of mock module names relative to the rootDirectory configuration. + * @param plugins An array of NPM modules as strings. + * @param skipDefaults Set true to skip loading of default mocks. + */ + (mocks: Array, plugins?: Array, skipDefaults?: boolean): ProtractorHttpMock; + + /** + * Clean up. + * Typically done in the afterEach call to ensure the teardown + * is executed regardless of what happens in the test execution. + */ + teardown(): void; + + /** + * Returns a promise that will be resolved with an array of + * all matched HTTP requests. + */ + requestsMade(): webdriver.promise.Promise>; + + /** + * Returns a promise that will be resolved with a true boolean + * when all matched HTTP requests are cleared. + */ + clearRequests(): webdriver.promise.Promise; + + /** + * Module configuration to setup + */ + config: { + /** + * Mocks directory where mock files are located. + * Default: process.cwd() + */ + rootDirectory?: string; + + /** + * Path to protractor configuration file. + * Default: protractor.conf + */ + protractorConfig?: string; + }; + + /** + * Add mocks during test execution. + * Returns a promise that will be resolved with a true boolean + * when mocks are added. + * + * @param mocks An array of mock modules to load into the application. + */ + add(mocks: Array>): webdriver.promise.Promise; + + /** + * Remove mocks during test execution. + * Returns a promise that will be resolved with a true boolean + * when the supplied mocks are removed. + * + * @param mocks An array of mock modules to remove from the application. + */ + remove(mocks: Array>): webdriver.promise.Promise; + } + + /** + * Matched request. + */ + interface ReceivedRequest { + url: string; + method: requests.Method; + } + + /** + * Plugin for custom matching logic. + */ + interface Plugin { + /** + * Match function. + * Return a truthy value to indicate successfull match. + * + * @param mockRequest The mock to compare request with. + * @param requestConfig The request object to compare mock with. + */ + match(mockRequest: requests.AllRequests, requestConfig: requests.AllRequests): boolean; + } + + /** + * Plugin for custom matching logic. + */ + interface Plugin { + /** + * Match function. + * Return a truthy value to indicate successfull match. + * + * @param mockRequest The mock to compare request with. + * @param requestConfig The request object to compare mock with. + */ + match(mockRequest: requests.AllRequests, requestConfig: requests.AllRequests): boolean; + } + + namespace requests { + /** + * Request methods type + */ + type Method = "GET" | "POST" | "DELETE" | "PUT" | "HEAD" | "PATCH" | "JSONP"; + + /** + * All available request types. + */ + type AllRequests = Get | + PostData | + Post | + Head | + Delete | + Put | + Patch | + Jsonp; + + /** + * GET request mock. + */ + interface Get { + request: { + method: Method; + path: string; + regex?: boolean; + params?: Object; + queryString?: Object; + headers?: Object; + interceptedRequest?: boolean; + interceptedAnonymousRequest?: boolean; + }; + response: { + status?: number; + data: TResponse; + }; + } + + /** + * POST request mock with payload. + */ + interface PostData { + request: { + method: Method; + path: string; + regex?: boolean; + data: TPayload; + }; + response: { + status?: number; + data: TResponse; + }; + } + + /** + * POST request mock. + */ + interface Post { + request: { + method: Method; + path: string; + regex?: boolean; + }; + response: { + status?: number; + data: TResponse; + }; + } + + /** + * HEAD request mock. + */ + interface Head { + request: { + method: Method; + path: string; + regex?: boolean; + }; + response: { + status?: number; + data: TResponse; + }; + } + + /** + * HTTP Delete request mock. + */ + interface Delete { + request: { + method: Method; + path: string; + regex?: boolean; + }; + response: { + status?: number; + data: TResponse; + }; + } + + /** + * PUT request mock. + */ + interface Put { + request: { + method: Method; + path: string; + regex?: boolean; + }; + response: { + status?: number; + data: TResponse; + }; + } + + /** + * PATCH request mock. + */ + interface Patch { + request: { + method: Method; + path: string; + regex?: boolean; + }; + response: { + status?: number; + data: TResponse; + }; + } + + /** + * JSONP request mock. + */ + interface Jsonp { + request: { + method: Method; + path: string; + regex?: boolean; + }; + response: { + status?: number; + data: TResponse; + }; + } + } +} + +declare var mock: mock.ProtractorHttpMock; +export = mock; diff --git a/protractor-http-mock/package.json b/protractor-http-mock/package.json new file mode 100644 index 0000000000..4d21335bac --- /dev/null +++ b/protractor-http-mock/package.json @@ -0,0 +1,10 @@ +{ + "name": "protractor-http-mock", + "version": "1.0.0", + "description": "protractor http mock", + "author": "", + "license": "MIT", + "dependencies": { + "@types/selenium-webdriver": "~2.44.28" + } +} diff --git a/protractor-http-mock/protractor-http-mock-tests.ts b/protractor-http-mock/protractor-http-mock-tests.ts new file mode 100644 index 0000000000..08b97fd09f --- /dev/null +++ b/protractor-http-mock/protractor-http-mock-tests.ts @@ -0,0 +1,302 @@ +import mock = require("protractor-http-mock"); + +function TestConfig() { + mock.config = { + rootDirectory: "root", + protractorConfig: "protractor.conf.js" + }; +} + +function TestCtorOverloads() { + let del: mock.requests.Delete = { + request: { + path: 'path', + method: 'DELETE' + }, + response: { + status: 400, + data: 1 + } + }; + let put: mock.requests.Put = { + request: { + path: 'path', + method: 'PUT' + }, + response: { + status: 400, + data: 1 + } + }; + let plugin: mock.Plugin = { + match: (mockRequest: mock.requests.Delete, requestConfig: mock.requests.AllRequests) => { + if (requestConfig.request.method && mockRequest.request.method) { + return true; + } + + return false; + } + }; + + let noParam: mock.ProtractorHttpMock = mock(); + let emptyArray: mock.ProtractorHttpMock = mock([]); + let mockFiles: mock.ProtractorHttpMock = mock(['mock1', 'mock2']); + let mocks: mock.ProtractorHttpMock = mock([del, put]); + + let mockFilesNpmPlugins: mock.ProtractorHttpMock = mock(['mock1'], ['plugin']); + let mocksWithNpmPlugins: mock.ProtractorHttpMock = mock([del, put], ['plugin']); + + let pluginMocks: mock.ProtractorHttpMock = mock([del, put], [plugin]); + + let mockFilesNpmPluginsSkipDefaults: mock.ProtractorHttpMock = mock(['mock1'], ['plugin'], true); + let skipDefaults: mock.ProtractorHttpMock = mock([del, put], [plugin], true); +} + +function TestTeardown() { + mock.teardown(); +} + +function TestRequestsMade() { + let values: Array; + mock.requestsMade().then(v => values = v); +} + +function TestClearRequests() { + let promiseValue: boolean; + mock.clearRequests().then(value => { + promiseValue = value; + }); +} + +function TestDynamicAdd() { + let put: mock.requests.Put = { + request: { + path: "path", + method: "PUT" + }, + response: { + status: 400, + data: 1 + } + }; + let resolved: boolean; + mock.add([put]).then(r => resolved = r); +} + +function TestDyanmicRemove() { + let put: mock.requests.Put = { + request: { + path: "path", + method: "PUT" + }, + response: { + status: 400, + data: 1 + } + }; + let resolved: boolean; + mock.remove([put]).then(r => resolved = r); +} + +function TestGetRequestDefinitions() { + let getMinium: mock.requests.Get = { + request: { + path: 'path', + method: 'GET', + regex: true + }, + response: { + data: 1, + status: 500 + } + }; + + let getParams: mock.requests.Get = { + request: { + path: 'path', + method: 'GET', + regex: true, + params: { + param1: 'param1', + param2: 2 + } + }, + response: { + data: 1, + status: 500 + } + }; + + let post: mock.requests.Post = { + request: { + path: 'path', + method: 'POST', + regex: true + }, + response: { + data: 1, + status: 500 + } + }; + + let getQueryString: mock.requests.Get = { + request: { + path: 'path', + method: 'GET', + regex: true, + queryString: { + query1: 'query1', + query2: 2 + } + }, + response: { + data: 1, + status: 500 + } + }; + + let getHeaders: mock.requests.Get = { + request: { + path: 'path', + method: 'GET', + regex: true, + headers: { + head1: 'head1', + head2: 'head2' + } + }, + response: { + data: 1, + status: 500 + } + }; +} + +function TestPostRequestDefinitions() { + let post: mock.requests.Post = { + request: { + path: 'path', + method: 'POST', + regex: true + }, + response: { + data: 1, + status: 500 + } + }; + + let postData: mock.requests.PostData = { + request: { + path: 'path', + method: 'POST', + data: 'data', + regex: true + }, + response: { + data: 1, + status: 500 + } + }; +} + +function TestHeadRequestDefinitions() { + let head: mock.requests.Head = { + request: { + path: 'path', + method: 'HEAD', + regex: true + }, + response: { + status: 500, + data: 1 + } + }; +} + +function TestDeleteRequestDefinitions() { + let del: mock.requests.Delete = { + request: { + path: 'path', + method: 'DELETE', + regex: true + }, + response: { + status: 500, + data: 1 + } + }; +} + +function TestPutRequestDefinitions() { + let put: mock.requests.Put = { + request: { + path: 'path', + method: 'PUT', + regex: true + }, + response: { + status: 500, + data: 1 + } + }; +} + +function TestPatchRequestDefinitions() { + let patch: mock.requests.Patch = { + request: { + path: 'path', + method: 'PATCH', + regex: true + }, + response: { + status: 500, + data: 1 + } + }; +} + +function TestJsonpRequestDefinitions() { + let jsonp: mock.requests.Jsonp = { + request: { + path: 'path', + method: 'JSONP', + regex: true + }, + response: { + status: 500, + data: 1 + } + }; +} + +function TestRuntimeMocks() { + mock.add([{ + request: { + path: '/users', + method: 'GET', + params: { + name: 'Charlie' + } + }, + response: { + data: { + name: 'Override' + } + } + }]); + + mock.remove([{ + request: { + path: '/users', + method: 'GET', + params: { + name: 'Charlie' + } + }, + response: { + data: { + name: 'Override' + } + } + }]); +} diff --git a/protractor-http-mock/tsconfig.json b/protractor-http-mock/tsconfig.json new file mode 100644 index 0000000000..bad3dc76e2 --- /dev/null +++ b/protractor-http-mock/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "types": ["selenium-webdriver"], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "protractor-http-mock-tests.ts" + ] +} diff --git a/protractor/angular-protractor-tests.ts b/protractor/angular-protractor-tests.ts new file mode 100644 index 0000000000..0a7ae85357 --- /dev/null +++ b/protractor/angular-protractor-tests.ts @@ -0,0 +1,483 @@ + + +function TestWebDriverExports() { + var button: number = protractor.Button.LEFT; + + var key: string = protractor.Key.ADD; + var chord: string = protractor.Key.chord(protractor.Key.NUMPAD0, protractor.Key.NUMPAD1); + + var driver: protractor.WebDriver = new protractor.Builder(). + withCapabilities(protractor.Capabilities.chrome()). + build(); + var baseDriver: webdriver.WebDriver = driver; + + var action: protractor.ActionSequence = new protractor.ActionSequence(driver); + var baseAction: webdriver.ActionSequence = action; + + var browser: string = protractor.Browser.ANDROID; + + var builder: protractor.Builder = new protractor.Builder(); + var baseBuilder: webdriver.Builder = builder; + + var capability: string = protractor.Capability.BROWSER_NAME; + + var capabilities: protractor.Capabilities = protractor.Capabilities.chrome(); + var baseCapabilities: webdriver.Capabilities = capabilities; + + var commandName: string = protractor.CommandName.CLICK_ELEMENT; + + var command: protractor.Command = new protractor.Command(protractor.CommandName.CLICK); + var baseCommand: webdriver.Command = command; + + var eventEmitter: protractor.EventEmitter = new protractor.EventEmitter(); + var baseEventEmitter: webdriver.EventEmitter = eventEmitter; + + var webElement: protractor.WebElement = new protractor.WebElement(driver, new protractor.promise.Promise()); + var baseWebElement: webdriver.WebElement = webElement; + + var locator: webdriver.Locator = by.id('abc'); + + var session: protractor.Session = new protractor.Session('ABC', webdriver.Capabilities.android()); + var baseSession: webdriver.Session = session; + + locator = protractor.By.name('name'); + + var driver: protractor.WebDriver = new protractor.WebDriver(session, {}); + driver = new protractor.WebDriver(session, {}, new webdriver.promise.ControlFlow()); + var baseDriver: webdriver.WebDriver = driver; + + var webElement: protractor.WebElement = new protractor.WebElement(driver, { ELEMENT: 'abc' }); + var baseWebElement: webdriver.WebElement = webElement; + + var webElementPromise: protractor.WebElementPromise = new protractor.WebElementPromise(driver, { ELEMENT: 'abc' }); + var baseWebElementPromise: webdriver.WebElementPromise = webElementPromise; +} + +function TestWebDriverErrorModule() { + var errorCode: number = protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE; + var error: protractor.error.Error = new protractor.error.Error(protractor.error.ErrorCode.ELEMENT_NOT_VISIBLE); + var baseError: webdriver.error.Error = error; +} + +function TestWebDriverLoggingModule() { + var levelName: string = protractor.logging.Level.ALL.name; + var loggingType: string = protractor.logging.Type.CLIENT; + + var level: webdriver.logging.ILevel = protractor.logging.Level.ALL; + + var entry: protractor.logging.Entry = new protractor.logging.Entry(protractor.logging.Level.ALL, 'Message'); + var baseEntry: webdriver.logging.Entry = entry; + + level = protractor.logging.getLevel('DEBUG'); + + var prefs: protractor.logging.Preferences = new protractor.logging.Preferences(); +} + +function TestWebDriverPromiseModule() { + var cancelError: protractor.promise.CancellationError = new protractor.promise.CancellationError(); + cancelError = new protractor.promise.CancellationError('message'); + var baseCancelError: webdriver.promise.CancellationError = cancelError; + + var thenable: protractor.promise.Thenable = new protractor.promise.Thenable(); + var baseThenable: webdriver.promise.Thenable = thenable; + + var promise: protractor.promise.Promise = new protractor.promise.Promise(); + var basePromise: webdriver.promise.Promise = promise; + + var deferred: protractor.promise.Deferred = new protractor.promise.Deferred(); + var baseDeferred: webdriver.promise.Deferred = deferred; + + var flow: protractor.promise.ControlFlow = new protractor.promise.ControlFlow(); + var baseFlow: webdriver.promise.ControlFlow = flow; + + var arrayPromise: protractor.promise.Promise = protractor.promise.all([new protractor.promise.Promise(), new protractor.promise.Promise()]); + + protractor.promise.asap(promise, function (value: any) { return true; }); + protractor.promise.asap(promise, function (value: any) { }, function (err: any) { return 'ABC'; }); + + promise = protractor.promise.checkedNodeCall(function (err: any, value: any) { return 123; }); + + promise = protractor.promise.consume(function () { + return 5; + }); + promise = protractor.promise.consume(function () { + return 5; + }, this); + promise = protractor.promise.consume(function () { + return 5; + }, this, 1, 2, 3); + + flow = protractor.promise.controlFlow(); + + promise = protractor.promise.createFlow(function (newFlow: webdriver.promise.ControlFlow) { }); + + deferred = protractor.promise.defer(); + + promise = protractor.promise.delayed(123); + + var numbersPromise: protractor.promise.Promise = protractor.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { + return true; + }); + numbersPromise = protractor.promise.filter([1, 2, 3], function (el: number, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = protractor.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + return true; + }); + numbersPromise = protractor.promise.filter(numbersPromise, function (el: number, index: number, arr: number[]) { + return true; + }, this); + + numbersPromise = protractor.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + return true; + }); + numbersPromise = protractor.promise.map([1, 2, 3], function (el: number, index: number, arr: number[]) { + return true; + }, this); + numbersPromise = protractor.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + return true; + }); + numbersPromise = protractor.promise.map(numbersPromise, function (el: number, index: number, arr: number[]) { + return true; + }, this); + + promise = protractor.promise.fulfilled(); + promise = protractor.promise.fulfilled({ a: 123 }); + + promise = protractor.promise.fullyResolved({ a: 123 }); + + var bool: boolean = protractor.promise.isGenerator(function () { }); + var bool: boolean = protractor.promise.isPromise('ABC'); + + promise = protractor.promise.rejected({ a: 123 }); + + protractor.promise.setDefaultFlow(new webdriver.promise.ControlFlow()); + + promise = protractor.promise.when(promise, function (value: any) { return 123; }, function (err: Error) { return 123; }); +} + +function TestWebDriverStacktraceModule() { + var bool: boolean = protractor.stacktrace.BROWSER_SUPPORTED; + + var frame: protractor.stacktrace.Frame = new protractor.stacktrace.Frame(); + var baseFrame: webdriver.stacktrace.Frame = frame; + + var snapshot: protractor.stacktrace.Snapshot = new protractor.stacktrace.Snapshot(); + var baseSnapshot: webdriver.stacktrace.Snapshot = snapshot; + + var err: Error = protractor.stacktrace.format(new Error("Error")); + var frames: protractor.stacktrace.Frame[] = protractor.stacktrace.get(); +} + +function TestWebDriverUntilModule() { + var conditionB: protractor.until.Condition = new protractor.until.Condition('message', function (driver: webdriver.WebDriver) { return true; }); + var conditionBBase: webdriver.until.Condition = conditionB; + var conditionWebElement: protractor.until.Condition; + var conditionWebElements: protractor.until.Condition; + + conditionB = protractor.until.ableToSwitchToFrame(5); + var conditionAlert: protractor.until.Condition = protractor.until.alertIsPresent(); + var el: protractor.ElementFinder = element(by.id('id')); + conditionB = protractor.until.elementIsDisabled(el); + conditionB = protractor.until.elementIsEnabled(el); + conditionB = protractor.until.elementIsNotSelected(el); + conditionB = protractor.until.elementIsNotVisible(el); + conditionB = protractor.until.elementIsSelected(el); + conditionB = protractor.until.elementIsVisible(el); + conditionB = protractor.until.elementTextContains(el, 'text'); + conditionB = protractor.until.elementTextIs(el, 'text'); + conditionB = protractor.until.elementTextMatches(el, /text/); + conditionB = protractor.until.stalenessOf(el); + conditionB = protractor.until.titleContains('text'); + conditionB = protractor.until.titleIs('text'); + conditionB = protractor.until.titleMatches(/text/); + + conditionWebElement = protractor.until.elementLocated(by.id('id')); + conditionWebElements = protractor.until.elementsLocated(by.className('class')); +} + +function TestWebDriverExpectedConditionsModule() { + var conditionB: protractor.until.Condition; + var el: protractor.ElementFinder = element(by.id('id')); + + conditionB = protractor.ExpectedConditions.alertIsPresent(); + conditionB = protractor.ExpectedConditions.elementToBeClickable(el); + conditionB = protractor.ExpectedConditions.textToBePresentInElement(el, 'text'); + conditionB = protractor.ExpectedConditions.textToBePresentInElementValue(el, 'text'); + conditionB = protractor.ExpectedConditions.titleContains('text'); + conditionB = protractor.ExpectedConditions.titleIs('text'); + conditionB = protractor.ExpectedConditions.presenceOf(el); + conditionB = protractor.ExpectedConditions.stalenessOf(el); + conditionB = protractor.ExpectedConditions.visibilityOf(el); + conditionB = protractor.ExpectedConditions.invisibilityOf(el); + conditionB = protractor.ExpectedConditions.elementToBeSelected(el); + + conditionB = protractor.ExpectedConditions.not(protractor.ExpectedConditions.alertIsPresent()); + conditionB = protractor.ExpectedConditions.and(protractor.ExpectedConditions.alertIsPresent(), protractor.ExpectedConditions.elementToBeClickable(el)); + conditionB = protractor.ExpectedConditions.or(protractor.ExpectedConditions.alertIsPresent(), protractor.ExpectedConditions.elementToBeClickable(el)); +} + +function TestProtractor() { + var ptor: protractor.Protractor; + var driver: webdriver.WebDriver = new webdriver.Builder(). + withCapabilities(webdriver.Capabilities.chrome()). + build(); + + ptor = protractor.wrapDriver(driver); + ptor = protractor.wrapDriver(driver, 'baseUrl'); + ptor = protractor.wrapDriver(driver, 'baseUrl', 'rootElement'); + + ptor = browser; + + var actions: protractor.ActionSequence = ptor.actions(); + + var promise: protractor.promise.Promise = ptor.call(function () { }); + var promise: protractor.promise.Promise = ptor.call(function () { }, this); + var promise: protractor.promise.Promise = ptor.call(function (a: number, b: number, c:number) { }, this, 1, 2,3); + + promise = ptor.executeAsyncScript('SomeScript'); + promise = ptor.executeAsyncScript('SomeScript', 1, 2, 3); + promise = ptor.executeAsyncScript(function () { }); + promise = ptor.executeAsyncScript(function (a: number, b: number, c: number) { }, 1, 2, 3); + + promise = ptor.executeScript('SomeScript'); + promise = ptor.executeScript('SomeScript', 1, 2, 3); + promise = ptor.executeScript(function () { }); + promise = ptor.executeScript(function (a: number, b: number, c: number) { }, 1, 2, 3); + + ptor = browser.forkNewDriverInstance(); + ptor = browser.forkNewDriverInstance(true); + ptor = browser.forkNewDriverInstance(true, false); + + driver = ptor.driver; + var baseUrl: string = ptor.baseUrl; + var rootEl: string = ptor.rootEl; + var ignoreSynchronization: boolean = ptor.ignoreSynchronization; + var params: any = ptor.params; + ptor.resetUrl = "url"; + + ptor.debugger(); + ptor.close(); + var controlFlow: protractor.promise.ControlFlow = ptor.controlFlow(); + + var webElement: protractor.WebElement = ptor.findElement(by.css('.class')); + ptor.findElements(by.css('.class')).then(function (elements: webdriver.WebElement[]) { }); + ptor.isElementPresent(by.css('.class')).then(function (present: boolean) { }); + ptor.isElementPresent(webElement).then(function (present: boolean) { }); + + ptor.clearMockModules(); + ptor.addMockModule('name', 'script'); + ptor.addMockModule('name', function() {}); + ptor.removeMockModule('name'); + ptor.waitForAngular(); + + var elementFinder: protractor.ElementFinder; + var elementArrayFinder: protractor.ElementArrayFinder; + + elementFinder = ptor.element(by.id('ABC')); + elementFinder = ptor.$('.class'); + + elementArrayFinder = ptor.$$('.class'); + + var locationAbsUrl: webdriver.promise.Promise = ptor.getLocationAbsUrl(); + ptor.setLocation('webaddress.com'); + + var voidPromise: webdriver.promise.Promise = ptor.get('webaddress.com'); + voidPromise = ptor.get('webdaddress.com', 45); + voidPromise = ptor.quit(); + voidPromise = ptor.sleep(5000); + + ptor.refresh(); + ptor.refresh(45); + var navigation: webdriver.WebDriverNavigation = ptor.navigate(); + ptor.pause(); + ptor.pause(8080); + + ptor.getAllWindowHandles().then(function (handles: string[]) { }); + + var capabilities: protractor.promise.Promise = ptor.getCapabilities(); + + var stringPromise: webdriver.promise.Promise; + stringPromise = ptor.getCurrentUrl(); + stringPromise = ptor.getPageSource(); + stringPromise = ptor.getTitle(); + stringPromise = ptor.getWindowHandle(); + stringPromise = ptor.takeScreenshot(); + + ptor.getPageTimeout = 5000; + + var session: protractor.promise.Promise = ptor.getSession(); + + var options: webdriver.WebDriverOptions = ptor.manage(); + + promise = ptor.schedule(new protractor.Command(protractor.CommandName.ACCEPT_ALERT), 'asdf'); + + var targetLocator: webdriver.WebDriverTargetLocator = ptor.switchTo(); + + ptor.wait(protractor.until.elementLocated(by.id('id')), 5000).then(function (el: webdriver.IWebElement) { });; + ptor.wait(protractor.until.elementLocated(by.id('id')), 5000, 'message').then(function (el: webdriver.IWebElement) { });; +} + +function TestElement() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.className('class')); +} + +function TestElementFinder() { + var elementFinder: protractor.ElementFinder = element(by.id('id')); + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + elementFinder.getId().then(function (id: webdriver.IWebElementId) { }); + voidPromise = elementFinder.click(); + elementFinder = elementFinder.allowAnimations('string'); + voidPromise = elementFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); + stringPromise = elementFinder.getTagName(); + stringPromise = elementFinder.getCssValue('display'); + stringPromise = elementFinder.getAttribute('atribute'); + stringPromise = elementFinder.getText(); + elementFinder.getSize().then(function (size: webdriver.ISize) { }); + elementFinder.getLocation().then(function (location: webdriver.ILocation) { }); + booleanPromise = elementFinder.isEnabled(); + booleanPromise = elementFinder.isSelected(); + voidPromise = elementFinder.submit(); + voidPromise = elementFinder.clear(); + booleanPromise = elementFinder.isDisplayed(); + stringPromise = elementFinder.getOuterHtml(); + stringPromise = elementFinder.getInnerHtml(); + booleanPromise = elementFinder.isElementPresent(by.id('id')); + elementFinder = elementFinder.$('.class'); + var finders: protractor.ElementArrayFinder = elementFinder.$$('.class'); + elementFinder = elementFinder.evaluate('expression'); + booleanPromise = elementFinder.isPresent(); + + var webElement: webdriver.WebElement = elementFinder.getWebElement(); + finders = elementFinder.all(by.className('class')); + elementFinder = elementFinder.allowAnimations('abc'); + elementFinder = elementFinder.clone(); + elementFinder = elementFinder.element(by.id('id')); + + var b: boolean = elementFinder.isPending(); + var locator: webdriver.Locator = elementFinder.locator(); +} + +function TestElementArrayFinder() { + var elementArrayFinder: protractor.ElementArrayFinder = element.all(by.id('id')); + + var voidPromise: webdriver.promise.Promise; + var stringPromise: webdriver.promise.Promise; + var booleanPromise: webdriver.promise.Promise; + + elementArrayFinder.getId().then(function (id: webdriver.IWebElementId[]) { }); + voidPromise = elementArrayFinder.click(); + elementArrayFinder = elementArrayFinder.allowAnimations(true); + voidPromise = elementArrayFinder.sendKeys(protractor.Key.UP, protractor.Key.DOWN); + stringPromise = elementArrayFinder.getTagName(); + stringPromise = elementArrayFinder.getCssValue('display'); + stringPromise = elementArrayFinder.getAttribute('atribute'); + stringPromise = elementArrayFinder.getText(); + elementArrayFinder.getSize().then(function (size: webdriver.ISize[]) { }); + elementArrayFinder.getLocation().then(function (location: webdriver.ILocation[]) { }); + booleanPromise = elementArrayFinder.isEnabled(); + booleanPromise = elementArrayFinder.isSelected(); + voidPromise = elementArrayFinder.submit(); + voidPromise = elementArrayFinder.clear(); + booleanPromise = elementArrayFinder.isDisplayed(); + stringPromise = elementArrayFinder.getOuterHtml(); + stringPromise = elementArrayFinder.getInnerHtml(); + var finders: protractor.ElementArrayFinder = elementArrayFinder.$$('.class'); + elementArrayFinder = elementArrayFinder.evaluate('expression'); + + finders = elementArrayFinder.all(by.className('class')); + elementArrayFinder = elementArrayFinder.clone(); + + var b: boolean = elementArrayFinder.isPending(); + var locator: webdriver.Locator = elementArrayFinder.locator(); + + var findersArrayPromise: protractor.promise.Promise = elementArrayFinder.asElementFinders_(); + + var driverElementArray: webdriver.WebElement[] = elementArrayFinder.getWebElements(); + var elementFinder: protractor.ElementFinder = elementArrayFinder.get(42); + elementFinder = elementArrayFinder.first(); + elementFinder = elementArrayFinder.last(); + elementFinder = elementArrayFinder.toElementFinder_() + var numberPromise: protractor.promise.Promise = elementArrayFinder.count(); + elementArrayFinder.each(function(element: protractor.ElementFinder){ + // nothing + }); + + stringPromise = elementArrayFinder.map(function(element: protractor.ElementFinder, index: number){ + return 'abc'; + }); + + stringPromise = elementArrayFinder.map(function(element: protractor.ElementFinder, index: number): string { + return 'abc'; + }); + + stringPromise = elementArrayFinder.map>(function(element: protractor.ElementFinder, index: number): webdriver.promise.Promise { + return element.getText(); + }); + + elementArrayFinder = elementArrayFinder.filter(function(element: protractor.ElementFinder, index: number){ + return element.getText().then((text: string) => { + return text === "foo"; + }); + }); + elementArrayFinder.reduce(function (accumulator: string, element: protractor.ElementFinder) { + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, '').then(function (result: string) { }); + elementArrayFinder.reduce(function(accumulator: string, element: protractor.ElementFinder, index: number, array: protractor.ElementFinder[]){ + return element.getText().then((text: string) => { + return accumulator + ',' + text; + }); + }, '').then(function (result: string) { }); + elementArrayFinder.then(function(underlyingElementFinders: protractor.ElementFinder[]){ + //nothing + }); +} + +// This function tests the locator strategies. +function TestLocatorStrategies() { + var ptor: protractor.Protractor = browser; + var webElement: webdriver.WebElement; + + protractor.By.addLocator('customLocator', 'script'); + protractor.By.addLocator('customLocator2', function(){ + // nothing + }); + + // Angular specific locators. + webElement = ptor.findElement(protractor.By.binding('binding')); + webElement = ptor.findElement(protractor.By.exactBinding('exactBinding')); + webElement = ptor.findElement(protractor.By.model('model')); + webElement = ptor.findElement(protractor.By.repeater('repeater')); + webElement = ptor.findElement(protractor.By.repeater('repeater').column(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0)); + webElement = ptor.findElement(protractor.By.repeater('repeater').row(0).column(0)); + webElement = ptor.findElement(protractor.By.buttonText('buttonText')); + webElement = ptor.findElement(protractor.By.partialButtonText('partialButtonText')); + webElement = ptor.findElement(protractor.By.cssContainingText('cssSelector', 'search text')); + webElement = ptor.findElement(protractor.By.options('options')); + // One standard locator for good measure. + webElement = ptor.findElement(protractor.By.id('id')); + + var el: protractor.ElementFinder; + + // Angular specific locators. + el = element(by.binding('binding')); + el = element(by.exactBinding('exactBinding')); + el = element(by.model('model')); + el = element(by.repeater('repeater')); + el = element(by.repeater('repeater').column(0)); + el = element(by.repeater('repeater').row(0)); + el = element(by.repeater('repeater').row(0).column(0)); + el = element(by.buttonText('buttonText')); + el = element(by.partialButtonText('partialButtonText')); + el = element(by.cssContainingText('cssSelector', 'search text')); + el = element(by.options('options')); + // One standard locator for good measure. + el = element(by.id('id')); +} diff --git a/protractor/index.d.ts b/protractor/index.d.ts new file mode 100644 index 0000000000..86f00898a1 --- /dev/null +++ b/protractor/index.d.ts @@ -0,0 +1,1849 @@ +// Type definitions for Angular Protractor 1.5.0 +// Project: https://github.com/angular/protractor +// Definitions by: Bill Armstrong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace protractor { + //region Wrapped webdriver Items + + class ActionSequence extends webdriver.ActionSequence {} + class Builder extends webdriver.Builder {} + class Capabilities extends webdriver.Capabilities {} + class Command extends webdriver.Command {} + class EventEmitter extends webdriver.EventEmitter {} + class Session extends webdriver.Session {} + class WebDriver extends webdriver.WebDriver {} + class WebElement extends webdriver.WebElement {} + class WebElementPromise extends webdriver.WebElementPromise { } + + var Browser: webdriver.IBrowser; + var Button: webdriver.IButton; + var Capability: webdriver.ICapability; + var CommandName: webdriver.ICommandName; + var Key: webdriver.IKey; + + namespace error { + class Error extends webdriver.error.Error {} + var ErrorCode: webdriver.error.IErrorCode; + } + + namespace logging { + class Preferences extends webdriver.logging.Preferences { } + class Entry extends webdriver.logging.Entry { } + + var Type: webdriver.logging.IType; + var Level: webdriver.logging.ILevelValues; + + function getLevel(nameOrValue: string): webdriver.logging.ILevel; + function getLevel(nameOrValue: number): webdriver.logging.ILevel; + } + + namespace promise { + class Thenable extends webdriver.promise.Thenable { } + class Promise extends webdriver.promise.Promise { } + class Deferred extends webdriver.promise.Deferred { } + class ControlFlow extends webdriver.promise.ControlFlow { } + class CancellationError extends webdriver.promise.CancellationError { } + + /** + * Given an array of promises, will return a promise that will be fulfilled + * with the fulfillment values of the input array's values. If any of the + * input array's promises are rejected, the returned promise will be rejected + * with the same reason. + * + * @param {!Array.<(T|!webdriver.promise.Promise.)>} arr An array of + * promises to wait on. + * @return {!webdriver.promise.Promise.>} A promise that is + * fulfilled with an array containing the fulfilled values of the + * input array, or rejected with the same reason as the first + * rejected value. + * @template T + */ + function all(arr: webdriver.promise.Promise[]): webdriver.promise.Promise; + + /** + * Invokes the appropriate callback function as soon as a promised + * {@code value} is resolved. This function is similar to + * {@link webdriver.promise.when}, except it does not return a new promise. + * @param {*} value The value to observe. + * @param {Function} callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + */ + function asap(value: any, callback: Function, opt_errback?: Function): void; + + /** + * @return {!webdriver.promise.ControlFlow} The currently active control flow. + */ + function controlFlow(): webdriver.promise.ControlFlow; + + /** + * Creates a new control flow. The provided callback will be invoked as the + * first task within the new flow, with the flow as its sole argument. Returns + * a promise that resolves to the callback result. + * @param {function(!webdriver.promise.ControlFlow)} callback The entry point + * to the newly created flow. + * @return {!webdriver.promise.Promise} A promise that resolves to the callback + * result. + */ + function createFlow(callback: (flow: webdriver.promise.ControlFlow) => R): webdriver.promise.Promise; + + /** + * Determines whether a {@code value} should be treated as a promise. + * Any object whose "then" property is a function will be considered a promise. + * + * @param {*} value The value to test. + * @return {boolean} Whether the value is a promise. + */ + function isPromise(value: any): boolean; + + /** + * Tests is a function is a generator. + * @param {!Function} fn The function to test. + * @return {boolean} Whether the function is a generator. + */ + function isGenerator(fn: Function): boolean; + + /** + * Creates a promise that will be resolved at a set time in the future. + * @param {number} ms The amount of time, in milliseconds, to wait before + * resolving the promise. + * @return {!webdriver.promise.Promise} The promise. + */ + function delayed(ms: number): webdriver.promise.Promise; + + /** + * Calls a function for each element in an array, and if the function returns + * true adds the element to a new array. + * + *

    If the return value of the filter function is a promise, this function + * will wait for it to be fulfilled before determining whether to insert the + * element into the new array. + * + *

    If the filter function throws or returns a rejected promise, the promise + * returned by this function will be rejected with the same reason. Only the + * first failure will be reported; all subsequent errors will be silently + * ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ( + * boolean|webdriver.promise.Promise.)} fn The function + * to call for each element in the array. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function filter(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise; + function filter(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise + + /** + * Creates a new deferred object. + * @return {!webdriver.promise.Deferred} The new deferred object. + */ + function defer(): webdriver.promise.Deferred; + + /** + * Creates a promise that has been resolved with the given value. + * @param {*=} opt_value The resolved value. + * @return {!webdriver.promise.Promise} The resolved promise. + */ + function fulfilled(opt_value?: T): webdriver.promise.Promise; + + /** + * Calls a function for each element in an array and inserts the result into a + * new array, which is used as the fulfillment value of the promise returned + * by this function. + * + *

    If the return value of the mapping function is a promise, this function + * will wait for it to be fulfilled before inserting it into the new array. + * + *

    If the mapping function throws or returns a rejected promise, the + * promise returned by this function will be rejected with the same reason. + * Only the first failure will be reported; all subsequent errors will be + * silently ignored. + * + * @param {!(Array.|webdriver.promise.Promise.>)} arr The + * array to iterator over, or a promise that will resolve to said array. + * @param {function(this: SELF, TYPE, number, !Array.): ?} fn The + * function to call for each element in the array. This function should + * expect three arguments (the element, the index, and the array itself. + * @param {SELF=} opt_self The object to be used as the value of 'this' within + * {@code fn}. + * @template TYPE, SELF + */ + function map(arr: T[], fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise + function map(arr: webdriver.promise.Promise, fn: (element: T, index: number, array: T[]) => any, opt_self?: any): webdriver.promise.Promise + + /** + * Creates a promise that has been rejected with the given reason. + * @param {*=} opt_reason The rejection reason; may be any value, but is + * usually an Error or a string. + * @return {!webdriver.promise.Promise} The rejected promise. + */ + function rejected(opt_reason?: any): webdriver.promise.Promise; + + /** + * Wraps a function that is assumed to be a node-style callback as its final + * argument. This callback takes two arguments: an error value (which will be + * null if the call succeeded), and the success value as the second argument. + * If the call fails, the returned promise will be rejected, otherwise it will + * be resolved with the result. + * @param {!Function} fn The function to wrap. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * result of the provided function's callback. + */ + function checkedNodeCall(fn: Function, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Consumes a {@code GeneratorFunction}. Each time the generator yields a + * promise, this function will wait for it to be fulfilled before feeding the + * fulfilled value back into {@code next}. Likewise, if a yielded promise is + * rejected, the rejection error will be passed to {@code throw}. + * + *

    Example 1: the Fibonacci Sequence. + *

    
    +         * webdriver.promise.consume(function* fibonacci() {
    +         *   var n1 = 1, n2 = 1;
    +         *   for (var i = 0; i < 4; ++i) {
    +         *     var tmp = yield n1 + n2;
    +         *     n1 = n2;
    +         *     n2 = tmp;
    +         *   }
    +         *   return n1 + n2;
    +         * }).then(function(result) {
    +         *   console.log(result);  // 13
    +         * });
    +         * 
    + * + *

    Example 2: a generator that throws. + *

    
    +         * webdriver.promise.consume(function* () {
    +         *   yield webdriver.promise.delayed(250).then(function() {
    +         *     throw Error('boom');
    +         *   });
    +         * }).thenCatch(function(e) {
    +         *   console.log(e.toString());  // Error: boom
    +         * });
    +         * 
    + * + * @param {!Function} generatorFn The generator function to execute. + * @param {Object=} opt_self The object to use as "this" when invoking the + * initial generator. + * @param {...*} var_args Any arguments to pass to the initial generator. + * @return {!webdriver.promise.Promise.} A promise that will resolve to the + * generator's final result. + * @throws {TypeError} If the given function is not a generator. + */ + function consume(generatorFn: Function, opt_self?: any, ...var_args: any[]): webdriver.promise.Promise; + + /** + * Registers an observer on a promised {@code value}, returning a new promise + * that will be resolved when the value is. If {@code value} is not a promise, + * then the return promise will be immediately resolved. + * @param {*} value The value to observe. + * @param {Function=} opt_callback The function to call when the value is + * resolved successfully. + * @param {Function=} opt_errback The function to call when the value is + * rejected. + * @return {!webdriver.promise.Promise} A new promise. + */ + function when(value: T, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + function when(value: webdriver.promise.Promise, opt_callback?: (value: T) => any, opt_errback?: (error: any) => any): webdriver.promise.Promise; + + /** + * Returns a promise that will be resolved with the input value in a + * fully-resolved state. If the value is an array, each element will be fully + * resolved. Likewise, if the value is an object, all keys will be fully + * resolved. In both cases, all nested arrays and objects will also be + * fully resolved. All fields are resolved in place; the returned promise will + * resolve on {@code value} and not a copy. + * + * Warning: This function makes no checks against objects that contain + * cyclical references: + * + * var value = {}; + * value['self'] = value; + * webdriver.promise.fullyResolved(value); // Stack overflow. + * + * @param {*} value The value to fully resolve. + * @return {!webdriver.promise.Promise} A promise for a fully resolved version + * of the input value. + */ + function fullyResolved(value: any): webdriver.promise.Promise; + + /** + * Changes the default flow to use when no others are active. + * @param {!webdriver.promise.ControlFlow} flow The new default flow. + * @throws {Error} If the default flow is not currently active. + */ + function setDefaultFlow(flow: webdriver.promise.ControlFlow): void; + } + + namespace stacktrace { + class Frame extends webdriver.stacktrace.Frame { } + class Snapshot extends webdriver.stacktrace.Snapshot { } + + /** + * Formats an error's stack trace. + * @param {!(Error|goog.testing.JsUnitException)} error The error to format. + * @return {!(Error|goog.testing.JsUnitException)} The formatted error. + */ + function format(error: any): any; + + /** + * Gets the native stack trace if available otherwise follows the call chain. + * The generated trace will exclude all frames up to and including the call to + * this function. + * @return {!Array.} The frames of the stack trace. + */ + function get(): webdriver.stacktrace.Frame[]; + + /** + * Whether the current browser supports stack traces. + * + * @type {boolean} + * @const + */ + var BROWSER_SUPPORTED: boolean; + } + + namespace until { + class Condition extends webdriver.until.Condition { } + + /** + * Creates a condition that will wait until the input driver is able to switch + * to the designated frame. The target frame may be specified as: + *
      + *
    1. A numeric index into {@code window.frames} for the currently selected + * frame. + *
    2. A {@link webdriver.WebElement}, which must reference a FRAME or IFRAME + * element on the current page. + *
    3. A locator which may be used to first locate a FRAME or IFRAME on the + * current page before attempting to switch to it. + *
    + * + *

    Upon successful resolution of this condition, the driver will be left + * focused on the new frame. + * + * @param {!(number|webdriver.WebElement| + * webdriver.Locator|webdriver.By.Hash| + * function(!webdriver.WebDriver): !webdriver.WebElement)} frame + * The frame identifier. + * @return {!until.Condition.} A new condition. + */ + function ableToSwitchToFrame(frame: number): webdriver.until.Condition; + function ableToSwitchToFrame(frame: webdriver.IWebElement): webdriver.until.Condition; + function ableToSwitchToFrame(frame: webdriver.Locator): webdriver.until.Condition; + function ableToSwitchToFrame(frame: (webdriver: webdriver.WebDriver) => webdriver.IWebElement): webdriver.until.Condition; + function ableToSwitchToFrame(frame: any): webdriver.until.Condition; + + /** + * Creates a condition that waits for an alert to be opened. Upon success, the + * returned promise will be fulfilled with the handle for the opened alert. + * + * @return {!until.Condition.} The new condition. + */ + function alertIsPresent(): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be disabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsDisabled(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be enabled. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isEnabled + */ + function elementIsEnabled(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be deselected. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsNotSelected(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be in the DOM, + * yet not visible to the user. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsNotVisible(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to be selected. + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isSelected + */ + function elementIsSelected(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to become visible. + * + * @param {!webdriver.WebElement} element The element to test. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#isDisplayed + */ + function elementIsVisible(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will loop until an element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.} The new condition. + */ + function elementLocated(locator: webdriver.Locator): webdriver.until.Condition; + function elementLocated(locator: any): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to contain the given + * substring. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} substr The substring to search for. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextContains(element: webdriver.IWebElement, substr: string): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match the given + * {@code text} exactly. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {string} text The expected text. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextIs(element: webdriver.IWebElement, text: string): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element's + * {@link webdriver.WebDriver#getText visible text} to match a regular + * expression. + * + * @param {!webdriver.WebElement} element The element to test. + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + * @see webdriver.WebDriver#getText + */ + function elementTextMatches(element: webdriver.IWebElement, regex: RegExp): webdriver.until.Condition; + + /** + * Creates a condition that will loop until at least one element is + * {@link webdriver.WebDriver#findElement found} with the given locator. + * + * @param {!(webdriver.Locator|webdriver.By.Hash|Function)} locator The locator + * to use. + * @return {!until.Condition.>} The new + * condition. + */ + function elementsLocated(locator: webdriver.Locator): webdriver.until.Condition; + function elementsLocated(locator: any): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the given element to become stale. An + * element is considered stale once it is removed from the DOM, or a new page + * has loaded. + * + * @param {!webdriver.WebElement} element The element that should become stale. + * @return {!until.Condition.} The new condition. + */ + function stalenessOf(element: webdriver.IWebElement): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the current page's title to contain + * the given substring. + * + * @param {string} substr The substring that should be present in the page + * title. + * @return {!until.Condition.} The new condition. + */ + function titleContains(substr: string): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given value. + * + * @param {string} title The expected page title. + * @return {!until.Condition.} The new condition. + */ + function titleIs(title: string): webdriver.until.Condition; + + /** + * Creates a condition that will wait for the current page's title to match the + * given regular expression. + * + * @param {!RegExp} regex The regular expression to test against. + * @return {!until.Condition.} The new condition. + */ + function titleMatches(regex: RegExp): webdriver.until.Condition; + } + + namespace ExpectedConditions { + /** + * Negates the result of a promise. + * + * @param {webdriver.until.Condition} expectedCondition + * @return {!webdriver.until.Condition} An expected condition that returns the negated value. + */ + function not(expectedCondition: webdriver.until.Condition): webdriver.until.Condition; + + /** + * Chain a number of expected conditions using logical_and, short circuiting at the + * first expected condition that evaluates to false. + * + * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'and' together. + * @return {!webdriver.until.Condition} An expected condition that returns a promise which evaluates + * to the result of the logical and. + */ + function and(...fns: webdriver.until.Condition[]): webdriver.until.Condition; + + /** + * Chain a number of expected conditions using logical_or, short circuiting at the + * first expected condition that evaluates to true. + * + * @param {...webdriver.until.Condition[]} fns An array of expected conditions to 'or' together. + * @return {!webdriver.until.Condition} An expected condition that returns a promise which + * evaluates to the result of the logical or. + */ + function or(...fns: webdriver.until.Condition[]): webdriver.until.Condition; + + /** + * Expect an alert to be present. + * + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether an alert is present. + */ + function alertIsPresent(): webdriver.until.Condition; + + /** + * An Expectation for checking an element is visible and enabled such that you can click it. + * + * @param {ElementFinder} element The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is clickable. + */ + function elementToBeClickable(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking if the given text is present in the element. + * Returns false if the elementFinder does not find an element. + * + * @param {ElementFinder} element The element to check + * @param {string} text The text to verify against + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the text is present in the element. + */ + function textToBePresentInElement(element: ElementFinder, text: string): webdriver.until.Condition; + + /** + * An expectation for checking if the given text is present in the element’s value. + * Returns false if the elementFinder does not find an element. + * + * @param {ElementFinder} element The element to check + * @param {string} text The text to verify against + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the text is present in the element's value. + */ + function textToBePresentInElementValue( + element: ElementFinder, text: string + ): webdriver.until.Condition; + + /** + * An expectation for checking that the title contains a case-sensitive substring. + * + * @param {string} title The fragment of title expected + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the title contains the string. + */ + function titleContains(title: string): webdriver.until.Condition; + + /** + * An expectation for checking the title of a page. + * + * @param {string} title The expected title, which must be an exact match. + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the title equals the string. + */ + function titleIs(title: string): webdriver.until.Condition; + + /** + * An expectation for checking that an element is present on the DOM of a page. This does not necessarily + * mean that the element is visible. This is the opposite of 'stalenessOf'. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise + * representing whether the element is present. + */ + function presenceOf(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking that an element is not attached to the DOM of a page. + * This is the opposite of 'presenceOf'. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is stale. + */ + function stalenessOf(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking that an element is present on the DOM of a page and visible. + * Visibility means that the element is not only displayed but also has a height and width that is + * greater than 0. This is the opposite of 'invisibilityOf'. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is visible. + */ + function visibilityOf(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking that an element is present on the DOM of a page. This does not necessarily + * mean that the element is visible. This is the opposite of 'stalenessOf'. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is invisible. + */ + function invisibilityOf(element: ElementFinder): webdriver.until.Condition; + + /** + * An expectation for checking the selection is selected. + * + * @param {ElementFinder} elementFinder The element to check + * @return {!webdriver.until.Condition} An expected condition that returns a promise representing + * whether the element is selected. + */ + function elementToBeSelected(element: ElementFinder): webdriver.until.Condition; + } + + //endregion + + /** + * Use as: element(locator) + * + * The ElementFinder can be treated as a WebElement for most purposes, in + * particular, you may perform actions (i.e. click, getText) on them as you + * would a WebElement. ElementFinders extend Promise, and once an action + * is performed on an ElementFinder, the latest result from the chain can be + * accessed using then. Unlike a WebElement, an ElementFinder will wait for + * angular to settle before performing finds or actions. + * + * ElementFinder can be used to build a chain of locators that is used to find + * an element. An ElementFinder does not actually attempt to find the element + * until an action is called, which means they can be set up in helper files + * before the page is available. + * + * @param {webdriver.Locator} locator An element locator. + * @return {ElementFinder} + */ + interface Element { + (locator: webdriver.Locator): ElementFinder; + + /** + * ElementArrayFinder is used for operations on an array of elements (as opposed + * to a single element). + * + * @param {webdriver.Locator} locator An element locator. + * @return {ElementArrayFinder} + */ + all(locator: webdriver.Locator): ElementArrayFinder; + } + + interface ElementFinder extends webdriver.IWebElement, webdriver.promise.IThenable { + /** + * Calls to element may be chained to find elements within a parent. + * + * @alias element(locator).element(locator) + * @view + *

    + *
    + * Child text + *
    {{person.phone}}
    + *
    + *
    + * + * @example + * // Chain 2 element calls. + * var child = element(by.css('.parent')). + * element(by.css('.child')); + * expect(child.getText()).toBe('Child text\n555-123-4567'); + * + * // Chain 3 element calls. + * var triple = element(by.css('.parent')). + * element(by.css('.child')). + * element(by.binding('person.phone')); + * expect(triple.getText()).toBe('555-123-4567'); + * + * @param {webdriver.Locator} subLocator + * @return {ElementFinder} + */ + element(subLocator: webdriver.Locator): ElementFinder; + + /** + * Calls to element may be chained to find an array of elements within a parent. + * + * @alias element(locator).all(locator) + * @view + *
    + *
      + *
    • First
    • + *
    • Second
    • + *
    • Third
    • + *
    + *
    + * + * @example + * var items = element(by.css('.parent')).all(by.tagName('li')) + * + * @param {webdriver.Locator} subLocator + * @return {ElementArrayFinder} + */ + all(subLocator: webdriver.Locator): ElementArrayFinder; + + /** + * Shortcut for querying the document directly with css. + * + * @alias $(cssSelector) + * @view + *
    + * First + * Second + *
    + * + * @example + * var item = $('.count .two'); + * expect(item.getText()).toBe('Second'); + * + * @param {string} selector A css selector + * @return {ElementFinder} which identifies the located + * {@link webdriver.WebElement} + */ + $(selector: string): ElementFinder; + + /** + * Shortcut for querying the document directly with css. + * + * @alias $$(cssSelector) + * @view + *
    + * First + * Second + *
    + * + * @example + * // The following protractor expressions are equivalent. + * var list = element.all(by.css('.count span')); + * expect(list.count()).toBe(2); + * + * list = $$('.count span'); + * expect(list.count()).toBe(2); + * expect(list.get(0).getText()).toBe('First'); + * expect(list.get(1).getText()).toBe('Second'); + * + * @param {string} selector a css selector + * @return {ElementArrayFinder} which identifies the + * array of the located {@link webdriver.WebElement}s. + */ + $$(selector: string): ElementArrayFinder; + + /** + * Determine whether the element is present on the page. + * + * @view + * {{person.name}} + * + * @example + * // Element exists. + * expect(element(by.binding('person.name')).isPresent()).toBe(true); + * + * // Element not present. + * expect(element(by.binding('notPresent')).isPresent()).toBe(false); + * + * @return {ElementFinder} which resolves to whether + * the element is present on the page. + */ + isPresent(): webdriver.promise.Promise; + + /** + * Override for WebElement.prototype.isElementPresent so that protractor waits + * for Angular to settle before making the check. + * + * @see ElementFinder.isPresent + * + * @param {webdriver.Locator} subLocator Locator for element to look for. + * @return {ElementFinder} which resolves to whether + * the element is present on the page. + */ + isElementPresent(subLocator: webdriver.Locator): webdriver.promise.Promise; + + /** + * @see ElementArrayFinder.prototype.locator + * + * @return {webdriver.Locator} + */ + locator(): webdriver.Locator; + + /** + * Returns the WebElement represented by this ElementFinder. + * Throws the WebDriver error if the element doesn't exist. + * + * @example + * The following three expressions are equivalent. + * element(by.css('.parent')).getWebElement(); + * browser.waitForAngular(); browser.driver.findElement(by.css('.parent')); + * browser.findElement(by.css('.parent')); + * + * @alias element(locator).getWebElement() + * @return {webdriver.WebElement} + */ + getWebElement(): webdriver.WebElement; + + /** + * Evaluates the input as if it were on the scope of the current element. + * @see ElementArrayFinder.evaluate + * + * @param {string} expression + * + * @return {ElementFinder} which resolves to the evaluated expression. + */ + evaluate(expression: string): ElementFinder; + + /** + * @see ElementArrayFinder.prototype.allowAnimations. + * @param {string} value + * + * @return {ElementFinder} which resolves to whether animation is allowed. + */ + allowAnimations(value: string): ElementFinder; + + /** + * Create a shallow copy of ElementFinder. + * + * @return {!ElementFinder} A shallow copy of this. + */ + clone(): ElementFinder; + } + + interface ElementArrayFinder extends webdriver.promise.IThenable { + /** + * Returns the elements as an array of WebElements. + */ + getWebElements(): webdriver.WebElement[]; + + + /** + * Get an element within the ElementArrayFinder by index. The index starts at 0. + * Negative indices are wrapped (i.e. -i means ith element from last) + * This does not actually retrieve the underlying element. + * + * @alias element.all(locator).get(index) + * @view + *
      + *
    • First
    • + *
    • Second
    • + *
    • Third
    • + *
    + * + * @example + * var list = element.all(by.css('.items li')); + * expect(list.get(0).getText()).toBe('First'); + * expect(list.get(1).getText()).toBe('Second'); + * + * @param {number} index Element index. + * @return {ElementFinder} finder representing element at the given index. + */ + get(index: number): ElementFinder; + + /** + * Get the first matching element for the ElementArrayFinder. This does not + * actually retrieve the underlying element. + * + * @alias element.all(locator).first() + * @view + *
      + *
    • First
    • + *
    • Second
    • + *
    • Third
    • + *
    + * + * @example + * var first = element.all(by.css('.items li')).first(); + * expect(first.getText()).toBe('First'); + * + * @return {ElementFinder} finder representing the first matching element + */ + first(): ElementFinder; + + /** + * Get the last matching element for the ElementArrayFinder. This does not + * actually retrieve the underlying element. + * + * @alias element.all(locator).last() + * @view + *
      + *
    • First
    • + *
    • Second
    • + *
    • Third
    • + *
    + * + * @example + * var last = element.all(by.css('.items li')).last(); + * expect(last.getText()).toBe('Third'); + * + * @return {ElementFinder} finder representing the last matching element + */ + last(): ElementFinder; + + /** + * Count the number of elements represented by the ElementArrayFinder. + * + * @alias element.all(locator).count() + * @view + *
      + *
    • First
    • + *
    • Second
    • + *
    • Third
    • + *
    + * + * @example + * var list = element.all(by.css('.items li')); + * expect(list.count()).toBe(3); + * + * @return {!webdriver.promise.Promise} A promise which resolves to the + * number of elements matching the locator. + */ + count(): webdriver.promise.Promise; + + /** + * Calls the input function on each ElementFinder represented by the ElementArrayFinder. + * + * @alias element.all(locator).each(eachFunction) + * @view + *
      + *
    • First
    • + *
    • Second
    • + *
    • Third
    • + *
    + * + * @example + * element.all(by.css('.items li')).each(function(element) { + * // Will print First, Second, Third. + * element.getText().then(console.log); + * }); + * + * @param {function(ElementFinder)} fn Input function + */ + each(fn: (element: ElementFinder, index: number) => void): void; + + /** + * Apply a map function to each element within the ElementArrayFinder. The + * callback receives the ElementFinder as the first argument and the index as + * a second arg. + * + * @alias element.all(locator).map(mapFunction) + * @view + *
      + *
    • First
    • + *
    • Second
    • + *
    • Third
    • + *
    + * + * @example + * var items = element.all(by.css('.items li')).map(function(elm, index) { + * return { + * index: index, + * text: elm.getText(), + * class: elm.getAttribute('class') + * }; + * }); + * expect(items).toEqual([ + * {index: 0, text: 'First', class: 'one'}, + * {index: 1, text: 'Second', class: 'two'}, + * {index: 2, text: 'Third', class: 'three'} + * ]); + * + * @param {function(ElementFinder, number)} mapFn Map function that + * will be applied to each element. + * @return {!webdriver.promise.Promise} A promise that resolves to an array + * of values returned by the map function. + */ + map(mapFn: (element: ElementFinder, index: number) => T): webdriver.promise.Promise; + map(mapFn: (element: ElementFinder, index: number) => T2): webdriver.promise.Promise; + + /** + * Apply a filter function to each element within the ElementArrayFinder. Returns + * a new ElementArrayFinder with all elements that pass the filter function. The + * filter function receives the ElementFinder as the first argument + * and the index as a second arg. + * This does not actually retrieve the underlying list of elements, so it can + * be used in page objects. + * + * @alias element.all(locator).filter(filterFn) + * @view + *
      + *
    • First
    • + *
    • Second
    • + *
    • Third
    • + *
    + * + * @example + * element.all(by.css('.items li')).filter(function(elem, index) { + * return elem.getText().then(function(text) { + * return text === 'Third'; + * }); + * }).then(function(filteredElements) { + * filteredElements[0].click(); + * }); + * + * @param {function(ElementFinder, number): webdriver.WebElement.Promise} filterFn + * Filter function that will test if an element should be returned. + * filterFn can either return a boolean or a promise that resolves to a boolean. + * @return {!ElementArrayFinder} A ElementArrayFinder that represents an array + * of element that satisfy the filter function. + */ + filter(filterFn: (element: ElementFinder, index: number) => any): ElementArrayFinder; + + /** + * Apply a reduce function against an accumulator and every element found + * using the locator (from left-to-right). The reduce function has to reduce + * every element into a single value (the accumulator). Returns promise of + * the accumulator. The reduce function receives the accumulator, current + * ElementFinder, the index, and the entire array of ElementFinders, + * respectively. + * + * @alias element.all(locator).reduce(reduceFn) + * @view + *
      + *
    • First
    • + *
    • Second
    • + *
    • Third
    • + *
    + * + * @example + * var value = element.all(by.css('.items li')).reduce(function(acc, elem) { + * return elem.getText().then(function(text) { + * return acc + text + ' '; + * }); + * }); + * + * expect(value).toEqual('First Second Third '); + * + * @param {function(number, ElementFinder, number, Array.)} + * reduceFn Reduce function that reduces every element into a single value. + * @param {*} initialValue Initial value of the accumulator. + * @return {!webdriver.promise.Promise} A promise that resolves to the final + * value of the accumulator. + */ + reduce(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => webdriver.promise.Promise, initialValue: T): webdriver.promise.Promise; + reduce(reduceFn: (acc: T, element: ElementFinder, index: number, arr: ElementFinder[]) => T, initialValue: T): webdriver.promise.Promise; + + /** + * Represents the ElementArrayFinder as an array of ElementFinders. + * + * @return {Array.} Return a promise, which resolves to a list + * of ElementFinders specified by the locator. + */ + asElementFinders_(): webdriver.promise.Promise; + + /** + * Create a shallow copy of ElementArrayFinder. + * + * @return {!ElementArrayFinder} A shallow copy of this. + */ + clone(): ElementArrayFinder; + + /** + * Calls to ElementArrayFinder may be chained to find an array of elements + * using the current elements in this ElementArrayFinder as the starting point. + * This function returns a new ElementArrayFinder which would contain the + * children elements found (and could also be empty). + * + * @alias element.all(locator).all(locator) + * @view + *
    + *
      + *
    • 1a
    • + *
    • 1b
    • + *
    + *
    + *
    + *
      + *
    • 2a
    • + *
    • 2b
    • + *
    + *
    + * + * @example + * var foo = element.all(by.css('.parent')).all(by.css('.foo')) + * expect(foo.getText()).toEqual(['1a', '2a']) + * var baz = element.all(by.css('.parent')).all(by.css('.baz')) + * expect(baz.getText()).toEqual(['1b']) + * var nonexistent = element.all(by.css('.parent')).all(by.css('.NONEXISTENT')) + * expect(nonexistent.getText()).toEqual(['']) + * + * @param {webdriver.Locator} subLocator + * @return {ElementArrayFinder} + */ + all(locator: webdriver.Locator): ElementArrayFinder; + + /** + * Shorthand function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(selector: string): ElementArrayFinder; + + /** + * Returns an ElementFinder representation of ElementArrayFinder. It ensures + * that the ElementArrayFinder resolves to one and only one underlying element. + * + * @return {ElementFinder} An ElementFinder representation + * @private + */ + toElementFinder_(): ElementFinder; + + /** + * Returns the most relevant locator. + * + * @example + * $('#ID1').locator() // returns by.css('#ID1') + * $('#ID1').$('#ID2').locator() // returns by.css('#ID2') + * $$('#ID1').filter(filterFn).get(0).click().locator() // returns by.css('#ID1') + * + * @return {webdriver.Locator} + */ + locator(): webdriver.Locator; + + /** + * Evaluates the input as if it were on the scope of the current underlying + * elements. + * + * @view + * {{variableInScope}} + * + * @example + * var value = element(by.id('foo')).evaluate('variableInScope'); + * + * @param {string} expression + * + * @return {ElementArrayFinder} which resolves to the + * evaluated expression for each underlying element. + * The result will be resolved as in + * {@link webdriver.WebDriver.executeScript}. In summary - primitives will + * be resolved as is, functions will be converted to string, and elements + * will be returned as a WebElement. + */ + evaluate(expression: string): ElementArrayFinder; + + /** + * Determine if animation is allowed on the current underlying elements. + * @param {string} value + * + * @example + * // Turns off ng-animate animations for all elements in the + * element(by.css('body')).allowAnimations(false); + * + * @return {ElementArrayFinder} which resolves to whether animation is allowed. + */ + allowAnimations(value: boolean): ElementArrayFinder; + + /** + * Schedules a command to click on this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the click command has completed. + */ + click(): webdriver.promise.Promise; + + /** + * Schedules a command to type a sequence on the DOM element represented by this + * instance. + *

    + * Modifier keys (SHIFT, CONTROL, ALT, META) are stateful; once a modifier is + * processed in the keysequence, that key state is toggled until one of the + * following occurs: + *

      + *
    • The modifier key is encountered again in the sequence. At this point the + * state of the key is toggled (along with the appropriate keyup/down events). + *
    • + *
    • The {@code webdriver.Key.NULL} key is encountered in the sequence. When + * this key is encountered, all modifier keys current in the down state are + * released (with accompanying keyup events). The NULL key can be used to + * simulate common keyboard shortcuts: + * + * element.sendKeys("text was", + * webdriver.Key.CONTROL, "a", webdriver.Key.NULL, + * "now text is"); + * // Alternatively: + * element.sendKeys("text was", + * webdriver.Key.chord(webdriver.Key.CONTROL, "a"), + * "now text is"); + *
    • + *
    • The end of the keysequence is encountered. When there are no more keys + * to type, all depressed modifier keys are released (with accompanying keyup + * events). + *
    • + *
    + * Note: On browsers where native keyboard events are not yet + * supported (e.g. Firefox on OS X), key events will be synthesized. Special + * punctionation keys will be synthesized according to a standard QWERTY en-us + * keyboard layout. + * + * @param {...string} var_args The sequence of keys to + * type. All arguments will be joined into a single sequence (var_args is + * permitted for convenience). + * @return {!webdriver.promise.Promise} A promise that will be resolved when all + * keys have been typed. + */ + sendKeys(...var_args: string[]): webdriver.promise.Promise; + + /** + * Schedules a command to query for the tag/node name of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's tag name. + */ + getTagName(): webdriver.promise.Promise; + + /** + * Schedules a command to query for the computed style of the element + * represented by this instance. If the element inherits the named style from + * its parent, the parent will be queried for its value. Where possible, color + * values will be converted to their hex representation (e.g. #00ff00 instead of + * rgb(0, 255, 0)). + *

    + * Warning: the value returned will be as the browser interprets it, so + * it may be tricky to form a proper assertion. + * + * @param {string} cssStyleProperty The name of the CSS style property to look + * up. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * requested CSS value. + */ + getCssValue(cssStyleProperty: string): webdriver.promise.Promise; + + /** + * Schedules a command to query for the value of the given attribute of the + * element. Will return the current value even if it has been modified after the + * page has been loaded. More exactly, this method will return the value of the + * given attribute, unless that attribute is not present, in which case the + * value of the property with the same name is returned. If neither value is + * set, null is returned. The "style" attribute is converted as best can be to a + * text representation with a trailing semi-colon. The following are deemed to + * be "boolean" attributes and will be returned as thus: + * + *

    async, autofocus, autoplay, checked, compact, complete, controls, declare, + * defaultchecked, defaultselected, defer, disabled, draggable, ended, + * formnovalidate, hidden, indeterminate, iscontenteditable, ismap, itemscope, + * loop, multiple, muted, nohref, noresize, noshade, novalidate, nowrap, open, + * paused, pubdate, readonly, required, reversed, scoped, seamless, seeking, + * selected, spellcheck, truespeed, willvalidate + * + *

    Finally, the following commonly mis-capitalized attribute/property names + * are evaluated as expected: + *

      + *
    • "class" + *
    • "readonly" + *
    + * @param {string} attributeName The name of the attribute to query. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * attribute's value. + */ + getAttribute(attributeName: string): webdriver.promise.Promise; + + /** + * Get the visible (i.e. not hidden by CSS) innerText of this element, including + * sub-elements, without any leading or trailing whitespace. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's visible text. + */ + getText(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the size of this element's bounding box, in + * pixels. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's size as a {@code {width:number, height:number}} object. + */ + getSize(): webdriver.promise.Promise; + + /** + * Schedules a command to compute the location of this element in page space. + * @return {!webdriver.promise.Promise} A promise that will be resolved to the + * element's location as a {@code {x:number, y:number}} object. + */ + getLocation(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether the DOM element represented by this + * instance is enabled, as dicted by the {@code disabled} attribute. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently enabled. + */ + isEnabled(): webdriver.promise.Promise; + + /** + * Schedules a command to query whether this element is selected. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently selected. + */ + isSelected(): webdriver.promise.Promise; + + /** + * Schedules a command to submit the form containing this element (or this + * element if it is a FORM element). This command is a no-op if the element is + * not contained in a form. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the form has been submitted. + */ + submit(): webdriver.promise.Promise; + + /** + * Schedules a command to clear the {@code value} of this element. This command + * has no effect if the underlying DOM element is neither a text INPUT element + * nor a TEXTAREA element. + * @return {!webdriver.promise.Promise} A promise that will be resolved when + * the element has been cleared. + */ + clear(): webdriver.promise.Promise; + + /** + * Schedules a command to test whether this element is currently displayed. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * whether this element is currently visible on the page. + */ + isDisplayed(): webdriver.promise.Promise; + + /** + * Schedules a command to retrieve the outer HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with + * the element's outer HTML. + */ + getOuterHtml(): webdriver.promise.Promise; + + /** + * @return {!webdriver.promise.Promise.} A promise + * that resolves to this element's JSON representation as defined by the + * WebDriver wire protocol. + * @see http://code.google.com/p/selenium/wiki/JsonWireProtocol + */ + getId(): webdriver.promise.Promise + + /** + * Schedules a command to retrieve the inner HTML of this element. + * @return {!webdriver.promise.Promise} A promise that will be resolved with the + * element's inner HTML. + */ + getInnerHtml(): webdriver.promise.Promise; + } + + interface LocatorWithColumn extends webdriver.Locator { + column(index: number): webdriver.Locator; + column(name: string): webdriver.Locator; + } + + interface RepeaterLocator extends LocatorWithColumn { + row(index: number): LocatorWithColumn; + } + + interface IProtractorLocatorStrategy { + /** + * webdriver's By is an enum of locator functions, so we must set it to + * a prototype before inheriting from it. + */ + className: typeof webdriver.By.className; + css: typeof webdriver.By.css; + id: typeof webdriver.By.id; + linkText: typeof webdriver.By.linkText; + js: typeof webdriver.By.js; + name: typeof webdriver.By.name; + partialLinkText: typeof webdriver.By.partialLinkText; + tagName: typeof webdriver.By.tagName; + xpath: typeof webdriver.By.xpath; + + /** + * Add a locator to this instance of ProtractorBy. This locator can then be + * used with element(by.locatorName(args)). + * + * @view + * + * + * @example + * // Add the custom locator. + * by.addLocator('buttonTextSimple', + * function(buttonText, opt_parentElement, opt_rootSelector) { + * // This function will be serialized as a string and will execute in the + * // browser. The first argument is the text for the button. The second + * // argument is the parent element, if any. + * var using = opt_parentElement, + * buttons = using.querySelectorAll('button'); + * + * // Return an array of buttons with the text. + * return Array.prototype.filter.call(buttons, function(button) { + * return button.textContent === buttonText; + * }); + * }); + * + * // Use the custom locator. + * element(by.buttonTextSimple('Go!')).click(); + * + * @alias by.addLocator(locatorName, functionOrScript) + * @param {string} name The name of the new locator. + * @param {Function|string} script A script to be run in the context of + * the browser. This script will be passed an array of arguments + * that contains any args passed into the locator followed by the + * element scoping the search and the css selector for the root angular + * element. It should return an array of elements. + */ + addLocator(name: string, script: string): void; + addLocator(name: string, script: Function): void; + + /** + * Find an element by binding. + * + * @view + * {{person.name}} + * + * + * @example + * var span1 = element(by.binding('person.name')); + * expect(span1.getText()).toBe('Foo'); + * + * var span2 = element(by.binding('person.email')); + * expect(span2.getText()).toBe('foo@bar.com'); + * + * @param {string} bindingDescriptor + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + binding(bindingDescriptor: string): webdriver.Locator; + + /** + * Find an element by exact binding. + * + * @view + * {{ person.name }} + * + * {{person_phone|uppercase}} + * + * @example + * expect(element(by.exactBinding('person.name')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person-email')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person')).isPresent()).toBe(false); + * expect(element(by.exactBinding('person_phone')).isPresent()).toBe(true); + * expect(element(by.exactBinding('person_phone|uppercase')).isPresent()).toBe(true); + * expect(element(by.exactBinding('phone')).isPresent()).toBe(false); + * + * @param {string} bindingDescriptor + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + exactBinding(bindingDescriptor: string): webdriver.Locator; + + /** + * Find an element by ng-model expression. + * + * @alias by.model(modelName) + * @view + * + * + * @example + * var input = element(by.model('person.name')); + * input.sendKeys('123'); + * expect(input.getAttribute('value')).toBe('Foo123'); + * + * @param {string} model ng-model expression. + */ + model(model: string): webdriver.Locator; + + /** + * Find a button by text. + * + * @view + * + * + * @example + * element(by.buttonText('Save')); + * + * @param {string} searchText + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + buttonText(searchText: string): webdriver.Locator; + + /** + * Find a button by partial text. + * + * @view + * + * + * @example + * element(by.partialButtonText('Save')); + * + * @param {string} searchText + * @return {{findElementsOverride: findElementsOverride, toString: Function|string}} + */ + partialButtonText(searchText: string): webdriver.Locator; + + + /** + * Find elements inside an ng-repeat. + * + * @view + *
    + * {{cat.name}} + * {{cat.age}} + *
    + * + *
    + * {{$index}} + *
    + *
    + *

    {{book.name}}

    + *

    {{book.blurb}}

    + *
    + * + * @example + * // Returns the DIV for the second cat. + * var secondCat = element(by.repeater('cat in pets').row(1)); + * + * // Returns the SPAN for the first cat's name. + * var firstCatName = element(by.repeater('cat in pets'). + * row(0).column('{{cat.name}}')); + * + * // Returns a promise that resolves to an array of WebElements from a column + * var ages = element.all( + * by.repeater('cat in pets').column('{{cat.age}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 pets rows resolves + * // to an array of 2 elements. + * var rows = element.all(by.repeater('cat in pets')); + * + * // Returns a promise that resolves to an array of WebElements containing all + * // the elements with a binding to the book's name. + * var divs = element.all(by.repeater('book in library').column('book.name')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // the DIVs for the second book. + * var bookInfo = element.all(by.repeater('book in library').row(1)); + * + * // Returns the H4 for the first book's name. + * var firstBookName = element(by.repeater('book in library'). + * row(0).column('{{book.name}}')); + * + * // Returns a promise that resolves to an array of WebElements containing + * // all top level elements repeated by the repeater. For 2 books divs + * // resolves to an array of 4 elements. + * var divs = element.all(by.repeater('book in library')); + */ + repeater(repeatDescriptor: string): RepeaterLocator; + + /** + * Find elements by CSS which contain a certain string. + * + * @view + *
      + *
    • Dog
    • + *
    • Cat
    • + *
    + * + * @example + * // Returns the DIV for the dog, but not cat. + * var dog = element(by.cssContainingText('.pet', 'Dog')); + */ + cssContainingText(cssSelector: string, searchText: string): webdriver.Locator; + + /** + * Find an element by ng-options expression. + * + * @alias by.options(optionsDescriptor) + * @view + * + * + * @example + * var allOptions = element.all(by.options('c for c in colors')); + * expect(allOptions.count()).toEqual(2); + * var firstOption = allOptions.first(); + * expect(firstOption.getText()).toEqual('red'); + * + * @param {string} optionsDescriptor ng-options expression. + */ + options(optionsDescriptor: string): webdriver.Locator; + } + + var By: IProtractorLocatorStrategy; + + interface Protractor extends webdriver.WebDriver { + + /** + * The wrapped webdriver instance. Use this to interact with pages that do + * not contain Angular (such as a log-in screen). + * + * @type {webdriver.WebDriver} + */ + driver: webdriver.WebDriver; + + /** + * Helper function for finding elements. + * + * @type {function(webdriver.Locator): ElementFinder} + */ + element(locator: webdriver.Locator): ElementFinder; + + /** + * Shorthand function for finding elements by css. + * + * @type {function(string): ElementFinder} + */ + $(selector: string): ElementFinder; + + /** + * Shorthand function for finding arrays of elements by css. + * + * @type {function(string): ElementArrayFinder} + */ + $$(selector: string): ElementArrayFinder; + + /** + * All get methods will be resolved against this base URL. Relative URLs are = + * resolved the way anchor tags resolve. + * + * @type {string} + */ + baseUrl: string; + + /** + * The css selector for an element on which to find Angular. This is usually + * 'body' but if your ng-app is on a subsection of the page it may be + * a subelement. + * + * @type {string} + */ + rootEl: string; + + /** + * If true, Protractor will not attempt to synchronize with the page before + * performing actions. This can be harmful because Protractor will not wait + * until $timeouts and $http calls have been processed, which can cause + * tests to become flaky. This should be used only when necessary, such as + * when a page continuously polls an API using $timeout. + * + * @type {boolean} + */ + ignoreSynchronization: boolean; + + /** + * Timeout in milliseconds to wait for pages to load when calling `get`. + * + * @type {number} + */ + getPageTimeout: number; + + /** + * An object that holds custom test parameters. + * + * @type {Object} + */ + params: any; + + /** + * The reset URL to use between page loads. + * + * @type {string} + */ + resetUrl: string; + + /** + * Instruct webdriver to wait until Angular has finished rendering and has + * no outstanding $http calls before continuing. + * + * @return {!webdriver.promise.Promise} A promise that will resolve to the + * scripts return value. + */ + waitForAngular(): webdriver.promise.Promise; + + /** + * Add a module to load before Angular whenever Protractor.get is called. + * Modules will be registered after existing modules already on the page, + * so any module registered here will override preexisting modules with the same + * name. + * + * @example + * browser.addMockModule('modName', function() { + * angular.module('modName', []).value('foo', 'bar'); + * }); + * + * @param {!string} name The name of the module to load or override. + * @param {!string|Function} script The JavaScript to load the module. + * @param {...*} varArgs Any additional arguments will be provided to + * the script and may be referenced using the `arguments` object. + */ + addMockModule(name: string, script: string, ...varArgs: any[]): void; + addMockModule(name: string, script: Function, ...varArgs: any[]): void; + + /** + * Clear the list of registered mock modules. + */ + clearMockModules(): void; + + /** + * Remove a registered mock module. + * + * @example + * browser.removeMockModule('modName'); + * + * @param {!string} name The name of the module to remove. + */ + removeMockModule(name: string): void; + + /** + * @see webdriver.WebDriver.get + * + * Navigate to the given destination and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {string} destination Destination URL. + * @param {number=} opt_timeout Number of milliseconds to wait for Angular to + * start. + */ + get(destination: string, opt_timeout?: number): webdriver.promise.Promise; + + /** + * See webdriver.WebDriver.refresh + * + * Makes a full reload of the current page and loads mock modules before + * Angular. Assumes that the page being loaded uses Angular. + * If you need to access a page which does not have Angular on load, use + * the wrapped webdriver directly. + * + * @param {number=} opt_timeout Number of seconds to wait for Angular to start. + */ + refresh(opt_timeout?: number): webdriver.promise.Promise; + + /** + * Browse to another page using in-page navigation. + * + * @param {string} url In page URL using the same syntax as $location.url() + * @returns {!webdriver.promise.Promise} A promise that will resolve once + * page has been changed. + */ + setLocation(url: string): webdriver.promise.Promise; + + /** + * Returns the current absolute url from AngularJS. + */ + getLocationAbsUrl(): webdriver.promise.Promise; + + /** + * Pauses the test and injects some helper functions into the browser, so that + * debugging may be done in the browser console. + * + * This should be used under node in debug mode, i.e. with + * protractor debug + * + * @example + * While in the debugger, commands can be scheduled through webdriver by + * entering the repl: + * debug> repl + * Press Ctrl + C to leave rdebug repl + * > ptor.findElement(protractor.By.input('user').sendKeys('Laura')); + * > ptor.debugger(); + * debug> c + * + * This will run the sendKeys command as the next task, then re-enter the + * debugger. + */ + debugger(): void; + + /** + * Beta (unstable) pause function for debugging webdriver tests. Use + * browser.pause() in your test to enter the protractor debugger from that + * point in the control flow. + * Does not require changes to the command line (no need to add 'debug'). + * + * @example + * element(by.id('foo')).click(); + * browser.pause(); + * // Execution will stop before the next click action. + * element(by.id('bar')).click(); + * + * @param {number=} opt_debugPort Optional port to use for the debugging process + */ + pause(opt_debugPort?: number): void; + } + + // Interface for the global browser object. + interface IBrowser extends Protractor { + /** + * Fork another instance of protractor for use in interactive tests. + * + * @param {boolean} opt_useSameUrl Whether to navigate to current url on creation + * @param {boolean} opt_copyMockModules Whether to apply same mock modules on creation + * @return {Protractor} a protractor instance. + */ + forkNewDriverInstance(opt_useSameUrl?: boolean, opt_copyMockModules?: boolean): Protractor; + + /** + * Get the processed configuration object that is currently being run. This will contain + * the specs and capabilities properties of the current runner instance. + * + * Set by the runner. + * + * @return {webdriver.promise.Promise} A promise which resolves to the capabilities object. + */ + getProcessedConfig(): webdriver.promise.Promise; + } + + /** + * Create a new instance of Protractor by wrapping a webdriver instance. + * + * @param {webdriver.WebDriver} webdriver The configured webdriver instance. + * @param {string=} opt_baseUrl A URL to prepend to relative gets. + * @return {Protractor} + */ + function wrapDriver(webdriver: webdriver.WebDriver, opt_baseUrl?: string, opt_rootElement?: string): Protractor; +} + +interface cssSelectorHelper { + (cssLocator: string): protractor.ElementFinder; +} + +interface cssArraySelectorHelper { + (cssLocator: string): protractor.ElementArrayFinder; +} + +declare var browser: protractor.IBrowser; +declare var by: protractor.IProtractorLocatorStrategy; +declare var By: protractor.IProtractorLocatorStrategy; +declare var element: protractor.Element; +declare var $: cssSelectorHelper; +declare var $$: cssArraySelectorHelper; + +declare module 'protractor' { + export = protractor; +} diff --git a/protractor/package.json b/protractor/package.json new file mode 100644 index 0000000000..7776c11946 --- /dev/null +++ b/protractor/package.json @@ -0,0 +1,10 @@ +{ + "name": "protractor", + "version": "1.0.0", + "description": "protractor", + "author": "", + "license": "MIT", + "dependencies": { + "@types/selenium-webdriver": "~2.44.28" + } +} diff --git a/protractor/tsconfig.json b/protractor/tsconfig.json new file mode 100644 index 0000000000..46e32cb409 --- /dev/null +++ b/protractor/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "types": ["selenium-webdriver"], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "angular-protractor-tests.ts" + ] +} From 43591e0180996460901680ab92abfa3227744e35 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Mon, 19 Sep 2016 21:36:06 -0500 Subject: [PATCH 162/212] Making requested changes by @andy-ms for s3-upload-stream typing --- s3-upload-stream/index.d.ts | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/s3-upload-stream/index.d.ts b/s3-upload-stream/index.d.ts index 530fff9674..382c3a57f1 100644 --- a/s3-upload-stream/index.d.ts +++ b/s3-upload-stream/index.d.ts @@ -4,23 +4,19 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -/// +/// import * as stream from 'stream'; import * as AWS from 'aws-sdk'; -interface IS3Stream { - (client: AWS.S3): IS3StreamUploader +interface S3StreamUploader { + upload(destinationDetails: AWS.s3.PutObjectRequest, sessionDetails?: any): S3WriteStream; } -interface IS3StreamUploader { - upload(destinationDetails: AWS.s3.PutObjectRequest, sessionDetails?: any): IS3WriteStream; -} - -interface IS3WriteStream extends stream.Writable { +interface S3WriteStream extends stream.Writable { maxPartSize(sizeInBytes: number): void; concurrentParts(numberOfParts: number): void; } -declare var s3Stream: IS3Stream; +declare function s3Stream(client: AWS.S3): S3StreamUploader; export = s3Stream; From b434572f41b4d9e734a2322209f08d1384dca83c Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Mon, 19 Sep 2016 23:04:50 -0400 Subject: [PATCH 163/212] fixup tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Note that these tests aren’t currently passing on master either; the last PR only passed because travis didn’t actually run the tests: https://travis-ci.org/DefinitelyTyped/DefinitelyTyped/builds/160110579 --- twilio/twilio-tests.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/twilio/twilio-tests.ts b/twilio/twilio-tests.ts index 1fb9afa0a4..25c6915068 100644 --- a/twilio/twilio-tests.ts +++ b/twilio/twilio-tests.ts @@ -1,4 +1,5 @@ import * as twilio from './twilio'; +import * as Express from "express"; // Examples taken from https://twilio.github.io/twilio-node/ (v2.1.0) @@ -227,8 +228,12 @@ var token = capability.generate(120); /// Utilities twilio.validateRequest(token, str, 'http://example.herokuapp.com', { query: 'val' }); -twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN'); -twilio.validateExpressRequest({}, 'YOUR_TWILIO_AUTH_TOKEN', {}); +twilio.validateExpressRequest(getMockExpressRequest(), 'YOUR_TWILIO_AUTH_TOKEN'); +twilio.validateExpressRequest(getMockExpressRequest(), 'YOUR_TWILIO_AUTH_TOKEN', {}); twilio.webhook({ validate: false }); twilio.webhook("MYAUTHTOKEN", { validate: false }); + +function getMockExpressRequest(): Express.Request { + return JSON.parse("{}"); +} From 2a7b90340cb7fa0da2784df2c4881374a4d71776 Mon Sep 17 00:00:00 2001 From: Craig Nishina Date: Mon, 19 Sep 2016 21:49:23 -0700 Subject: [PATCH 164/212] fix(react-daterange-picker): fix travis failures closes #11334 --- react-daterange-picker/package.json | 8 ++++---- react-daterange-picker/tsconfig.json | 5 ++--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/react-daterange-picker/package.json b/react-daterange-picker/package.json index 992b24d513..bfdab7b7fe 100644 --- a/react-daterange-picker/package.json +++ b/react-daterange-picker/package.json @@ -1,5 +1,5 @@ { - "dependencies": { - "moment": "2.14.*" - } -} \ No newline at end of file + "scripts": { + "postinstall": "cd ../moment-range && npm install" + } +} diff --git a/react-daterange-picker/tsconfig.json b/react-daterange-picker/tsconfig.json index a4828d6b09..b0493165b7 100644 --- a/react-daterange-picker/tsconfig.json +++ b/react-daterange-picker/tsconfig.json @@ -8,14 +8,13 @@ "typeRoots": [ "../" ], - "types": [], + "types": ["moment-range", "react"], "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react" }, "files": [ "index.d.ts", "react-daterange-picker-tests.tsx" ] -} \ No newline at end of file +} From 4b32d529eba572b91620986d3193e60d77f65c63 Mon Sep 17 00:00:00 2001 From: akankov Date: Tue, 20 Sep 2016 12:48:54 +0700 Subject: [PATCH 165/212] fromData type fix --- dropzone/dropzone.d.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/dropzone/dropzone.d.ts b/dropzone/dropzone.d.ts index 7464151b3b..ff8412b0e8 100644 --- a/dropzone/dropzone.d.ts +++ b/dropzone/dropzone.d.ts @@ -95,8 +95,8 @@ interface DropzoneOptions { uploadprogress?(file:DropzoneFile, progress:number, bytesSent:number):void; totaluploadprogress?(totalProgress:number, totalBytes:number, totalBytesSent:number):void; - sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void; - sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void; + sending?(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; + sendingmultiple?(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; success?(file: DropzoneFile, response: Object|string): void; successmultiple?(files:DropzoneFile[], responseText:string):void; @@ -206,8 +206,8 @@ declare class Dropzone { on(eventName:"uploadprogress", callback:(file:DropzoneFile, progress:number, bytesSent:number) => any):void; on(eventName:"totaluploadprogress", callback:(totalProgress:number, totalBytes:number, totalBytesSent:number) => any):void; - on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:{}) => any):void; - on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}) => any):void; + on(eventName:"sending", callback:(file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData) => any):void; + on(eventName:"sendingmultiple", callback:(files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData) => any):void; on(eventName:"success", callback:(file:DropzoneFile) => any):void; on(eventName:"successmultiple", callback:(files:DropzoneFile[]) => any):void; @@ -246,8 +246,8 @@ declare class Dropzone { emit(eventName:"uploadprogress", file:DropzoneFile, progress:number, bytesSent:number):void; emit(eventName:"totaluploadprogress", totalProgress:number, totalBytes:number, totalBytesSent:number):void; - emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:{}):void; - emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:{}):void; + emit(eventName:"sending", file:DropzoneFile, xhr:XMLHttpRequest, formData:FormData):void; + emit(eventName:"sendingmultiple", files:DropzoneFile[], xhr:XMLHttpRequest, formData:FormData):void; emit(eventName:"success", file:DropzoneFile):void; emit(eventName:"successmultiple", files:DropzoneFile[]):void; From 6eaf28d3038a399f3724d831c86f4d525feace69 Mon Sep 17 00:00:00 2001 From: Stefan Dobrev Date: Fri, 16 Sep 2016 14:32:42 +0300 Subject: [PATCH 166/212] Add justifyContent to CssProperties `justifyContent ` was missing from CssProperties and this PR adds it. More information about it [here](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content). --- react/react.d.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/react/react.d.ts b/react/react.d.ts index 5178ad28a6..30ab2db256 100644 --- a/react/react.d.ts +++ b/react/react.d.ts @@ -1181,6 +1181,12 @@ declare namespace __React { imeMode?: any; + /** + * Defines how the browser distributes space between and around flex items + * along the main-axis of their container. + */ + justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around"; + layoutGrid?: any; layoutGridChar?: any; From 3dacedf0dc0f6c539dfb2751232d25a868752d54 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 11:33:29 +0300 Subject: [PATCH 167/212] Create index.d.ts --- react-redux-toastr/index.d.ts | 105 ++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 react-redux-toastr/index.d.ts diff --git a/react-redux-toastr/index.d.ts b/react-redux-toastr/index.d.ts new file mode 100644 index 0000000000..fb3dabfa61 --- /dev/null +++ b/react-redux-toastr/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for react-redux-toastr 3.7.0 +// Project: https://github.com/diegoddox/react-redux-toastr +// Definitions by: Aleksandar Ivanov https://github.com/Smiche +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare module "react-redux-toastr" { + import R = __React; + import _Redux = Redux; + + interface ToastrOptions { + /** + * Timeout in miliseconds. + */ + timeOut?: number, + /** + * Show newest on top or bottom. + */ + newestOnTop?: boolean, + /** + * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right + */ + position?: string, + confirmText?: ConfirmText + } + + interface ConfirmText { + okText: string, + cancelText: string + } + + /** + * Toastr react component. + */ + export default class ReduxToastr extends R.Component{ } + + interface EmitterOptions { + /** + * Notification popup icon. + * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert + */ + icon?: string, + /** + * Timeout in miliseconds. + */ + timeOut?: number, + removeOnHover?: boolean, + removeOnClick?: boolean, + component?: R.Component, + onShowComplete?: () => void, + onHideComplete?: () => void + } + + interface ToastrConfirmOptions { + onOk: () => void, + onCancel: () => void + } + + interface ToastrEmitter { + /** + * Used to provide a large amount of information. + * It will not close unless a timeOut is provided. + */ + message: (title: string, message: string, options?: EmitterOptions) => void, + info: (title: string, message: string, options?: EmitterOptions) => void, + success: (title: string, message: string, options?: EmitterOptions) => void, + warning: (title: string, message: string, options?: EmitterOptions) => void, + error: (title: string, message: string, options?: EmitterOptions) => void, + /** + * Clear all notifications + */ + clean: () => void, + /** + * Hook confirmation toastr with callback. + */ + confirm: (message: string, options: ToastrConfirmOptions) => any + } + + /** + * Possible actions to dispatch. + */ + interface Actions { + addToastrAction: Redux.Action, + clean: Redux.Action, + remove: Redux.Action, + success: Redux.Action, + info: Redux.Action, + warning: Redux.Action, + error: Redux.Action, + showConfirm: Redux.Action, + hideConfirm: Redux.Action + } + + /** + * Action creator for toastr. + */ + export var actions: Redux.ActionCreator; + /** + * Reducer for the toastr state. + * Combine with your reducers. + */ + export var reducer: Redux.Reducer; + /** + * Used to issue toastr notifications. + */ + export var toastr: ToastrEmitter; +} From 60b8d4769542d602022d0a7c521ac69ae7aff4ea Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 11:34:07 +0300 Subject: [PATCH 168/212] Create library-tests.ts --- react-redux-toastr/library-tests.ts | 51 +++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 react-redux-toastr/library-tests.ts diff --git a/react-redux-toastr/library-tests.ts b/react-redux-toastr/library-tests.ts new file mode 100644 index 0000000000..427823b7c1 --- /dev/null +++ b/react-redux-toastr/library-tests.ts @@ -0,0 +1,51 @@ +/// +/// +/// +/// +import {toastr, reducer as toastrReducer, actions} from 'react-redux-toastr'; +import ReduxToastr from 'react-redux-toastr'; +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import {createStore, combineReducers, bindActionCreators} from 'redux'; +import { Provider, connect } from 'react-redux'; + +function test() { + const store = createStore(combineReducers({ toastr: toastrReducer })); + var toastrFactory = React.createFactory(ReduxToastr); + var element = toastrFactory({ timeOut: 1000, newestOnTop: false }); + var providerFactory = React.createFactory(Provider); + var root = providerFactory({ store: store }, element); + + class Test extends React.Component{ + private toastr; + constructor() { + super() + this.toastr = bindActionCreators(actions, this.props.dispatch); + this.toastr.clean(); + this.toastr.success("hi"); + } + + } + + + var TestComponent = connect(mapStateToProps, mapDispatchToProps)(Test); + function mapDispatchToProps(dispatch) { + return { + actions: bindActionCreators(actions, dispatch) + }; + } + + function mapStateToProps(state) { + return {}; + } + + function callback() { } + + toastr.clean(); + toastr.confirm("Test", { onOk: callback, onCancel: callback }); + toastr.error("Error", "Error message"); + toastr.info("Info", "Info test", { timeOut: 1000, removeOnHover: true, removeOnClick: true, onShowComplete: callback }); + toastr.success("Test", "Test message", { component: new React.Component() }); +} + +test(); From ab8d917787092fdfb16390f2bee6de8ab5c1783c Mon Sep 17 00:00:00 2001 From: Jay Anslow Date: Tue, 20 Sep 2016 09:55:32 +0100 Subject: [PATCH 169/212] Node.JS EventEmitter accepts symbols as event names. --- node/node-tests.ts | 4 ++-- node/node.d.ts | 46 +++++++++++++++++++++++----------------------- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/node/node-tests.ts b/node/node-tests.ts index 1fcf149e99..da3721c3aa 100644 --- a/node/node-tests.ts +++ b/node/node-tests.ts @@ -70,7 +70,7 @@ namespace assert_tests { namespace events_tests { let emitter: events.EventEmitter; - let event: string; + let event: string|symbol; let listener: Function; let any: any; @@ -114,7 +114,7 @@ namespace events_tests { } { - let result: string[]; + let result: (string|symbol)[]; result = emitter.eventNames(); } diff --git a/node/node.d.ts b/node/node.d.ts index 888da5cec4..7f228e1765 100644 --- a/node/node.d.ts +++ b/node/node.d.ts @@ -241,20 +241,20 @@ declare namespace NodeJS { } export class EventEmitter { - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; + addListener(event: string|symbol, listener: Function): this; + on(event: string|symbol, listener: Function): this; + once(event: string|symbol, listener: Function): this; + removeListener(event: string|symbol, listener: Function): this; + removeAllListeners(event?: string|symbol): this; setMaxListeners(n: number): this; getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - listenerCount(type: string): number; + listeners(event: string|symbol): Function[]; + emit(event: string|symbol, ...args: any[]): boolean; + listenerCount(type: string|symbol): number; // Added in Node 6... - prependListener(event: string, listener: Function): this; - prependOnceListener(event: string, listener: Function): this; - eventNames(): string[]; + prependListener(event: string|symbol, listener: Function): this; + prependOnceListener(event: string|symbol, listener: Function): this; + eventNames(): (string|symbol)[]; } export interface ReadableStream extends EventEmitter { @@ -549,22 +549,22 @@ declare module "querystring" { declare module "events" { export class EventEmitter extends NodeJS.EventEmitter { static EventEmitter: EventEmitter; - static listenerCount(emitter: EventEmitter, event: string): number; // deprecated + static listenerCount(emitter: EventEmitter, event: string|symbol): number; // deprecated static defaultMaxListeners: number; - addListener(event: string, listener: Function): this; - on(event: string, listener: Function): this; - once(event: string, listener: Function): this; - prependListener(event: string, listener: Function): this; - prependOnceListener(event: string, listener: Function): this; - removeListener(event: string, listener: Function): this; - removeAllListeners(event?: string): this; + addListener(event: string|symbol, listener: Function): this; + on(event: string|symbol, listener: Function): this; + once(event: string|symbol, listener: Function): this; + prependListener(event: string|symbol, listener: Function): this; + prependOnceListener(event: string|symbol, listener: Function): this; + removeListener(event: string|symbol, listener: Function): this; + removeAllListeners(event?: string|symbol): this; setMaxListeners(n: number): this; getMaxListeners(): number; - listeners(event: string): Function[]; - emit(event: string, ...args: any[]): boolean; - eventNames(): string[]; - listenerCount(type: string): number; + listeners(event: string|symbol): Function[]; + emit(event: string|symbol, ...args: any[]): boolean; + eventNames(): (string|symbol)[]; + listenerCount(type: string|symbol): number; } } From a982c80d5537adbb10e61630436b6f33970c180c Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:45:34 +0300 Subject: [PATCH 170/212] Delete index.d.ts --- react-redux-toastr/index.d.ts | 105 ---------------------------------- 1 file changed, 105 deletions(-) delete mode 100644 react-redux-toastr/index.d.ts diff --git a/react-redux-toastr/index.d.ts b/react-redux-toastr/index.d.ts deleted file mode 100644 index fb3dabfa61..0000000000 --- a/react-redux-toastr/index.d.ts +++ /dev/null @@ -1,105 +0,0 @@ -// Type definitions for react-redux-toastr 3.7.0 -// Project: https://github.com/diegoddox/react-redux-toastr -// Definitions by: Aleksandar Ivanov https://github.com/Smiche -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "react-redux-toastr" { - import R = __React; - import _Redux = Redux; - - interface ToastrOptions { - /** - * Timeout in miliseconds. - */ - timeOut?: number, - /** - * Show newest on top or bottom. - */ - newestOnTop?: boolean, - /** - * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right - */ - position?: string, - confirmText?: ConfirmText - } - - interface ConfirmText { - okText: string, - cancelText: string - } - - /** - * Toastr react component. - */ - export default class ReduxToastr extends R.Component{ } - - interface EmitterOptions { - /** - * Notification popup icon. - * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert - */ - icon?: string, - /** - * Timeout in miliseconds. - */ - timeOut?: number, - removeOnHover?: boolean, - removeOnClick?: boolean, - component?: R.Component, - onShowComplete?: () => void, - onHideComplete?: () => void - } - - interface ToastrConfirmOptions { - onOk: () => void, - onCancel: () => void - } - - interface ToastrEmitter { - /** - * Used to provide a large amount of information. - * It will not close unless a timeOut is provided. - */ - message: (title: string, message: string, options?: EmitterOptions) => void, - info: (title: string, message: string, options?: EmitterOptions) => void, - success: (title: string, message: string, options?: EmitterOptions) => void, - warning: (title: string, message: string, options?: EmitterOptions) => void, - error: (title: string, message: string, options?: EmitterOptions) => void, - /** - * Clear all notifications - */ - clean: () => void, - /** - * Hook confirmation toastr with callback. - */ - confirm: (message: string, options: ToastrConfirmOptions) => any - } - - /** - * Possible actions to dispatch. - */ - interface Actions { - addToastrAction: Redux.Action, - clean: Redux.Action, - remove: Redux.Action, - success: Redux.Action, - info: Redux.Action, - warning: Redux.Action, - error: Redux.Action, - showConfirm: Redux.Action, - hideConfirm: Redux.Action - } - - /** - * Action creator for toastr. - */ - export var actions: Redux.ActionCreator; - /** - * Reducer for the toastr state. - * Combine with your reducers. - */ - export var reducer: Redux.Reducer; - /** - * Used to issue toastr notifications. - */ - export var toastr: ToastrEmitter; -} From 02935de0ccd7821fcbea1e5b091f13b29d7df5f2 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:46:14 +0300 Subject: [PATCH 171/212] Update library-tests.ts --- react-redux-toastr/library-tests.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/react-redux-toastr/library-tests.ts b/react-redux-toastr/library-tests.ts index 427823b7c1..3abfc668d4 100644 --- a/react-redux-toastr/library-tests.ts +++ b/react-redux-toastr/library-tests.ts @@ -1,7 +1,7 @@ -/// -/// -/// -/// +/// +/// +/// +/// import {toastr, reducer as toastrReducer, actions} from 'react-redux-toastr'; import ReduxToastr from 'react-redux-toastr'; import * as React from 'react'; From 2837bdcd4b3e0ed0a326a6c28215709c345498a4 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:46:40 +0300 Subject: [PATCH 172/212] Rename library-tests.ts to react-redux-toastr-tests.ts --- .../{library-tests.ts => react-redux-toastr-tests.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename react-redux-toastr/{library-tests.ts => react-redux-toastr-tests.ts} (100%) diff --git a/react-redux-toastr/library-tests.ts b/react-redux-toastr/react-redux-toastr-tests.ts similarity index 100% rename from react-redux-toastr/library-tests.ts rename to react-redux-toastr/react-redux-toastr-tests.ts From 18780a108d295a2a41ab690bc5747c33d9131931 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:47:05 +0300 Subject: [PATCH 173/212] Create react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 108 +++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 react-redux-toastr/react-redux-toastr.d.ts diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts new file mode 100644 index 0000000000..b10d430065 --- /dev/null +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -0,0 +1,108 @@ +// Type definitions for react-redux-toastr 3.7.0 +// Project: https://github.com/diegoddox/react-redux-toastr +// Definitions by: Aleksandar Ivanov https://github.com/Smiche +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +declare module "react-redux-toastr" { + import R = __React; + import _Redux = Redux; + + interface ToastrOptions { + /** + * Timeout in miliseconds. + */ + timeOut?: number, + /** + * Show newest on top or bottom. + */ + newestOnTop?: boolean, + /** + * Position of the toastr: top-left, top-center, top-right, bottom-left, bottom-center and bottom-right + */ + position?: string, + confirmText?: ConfirmText + } + + interface ConfirmText { + okText: string, + cancelText: string + } + + /** + * Toastr react component. + */ + export default class ReduxToastr extends R.Component{ } + + interface EmitterOptions { + /** + * Notification popup icon. + * icon-close-round, icon-information-circle, icon-check-1, icon-exclamation-triangle, icon-exclamation-alert + */ + icon?: string, + /** + * Timeout in miliseconds. + */ + timeOut?: number, + removeOnHover?: boolean, + removeOnClick?: boolean, + component?: R.Component, + onShowComplete?: () => void, + onHideComplete?: () => void + } + + interface ToastrConfirmOptions { + onOk: () => void, + onCancel: () => void + } + + interface ToastrEmitter { + /** + * Used to provide a large amount of information. + * It will not close unless a timeOut is provided. + */ + message: (title: string, message: string, options?: EmitterOptions) => void, + info: (title: string, message: string, options?: EmitterOptions) => void, + success: (title: string, message: string, options?: EmitterOptions) => void, + warning: (title: string, message: string, options?: EmitterOptions) => void, + error: (title: string, message: string, options?: EmitterOptions) => void, + /** + * Clear all notifications + */ + clean: () => void, + /** + * Hook confirmation toastr with callback. + */ + confirm: (message: string, options: ToastrConfirmOptions) => any + } + + /** + * Possible actions to dispatch. + */ + interface Actions { + addToastrAction: Redux.Action, + clean: Redux.Action, + remove: Redux.Action, + success: Redux.Action, + info: Redux.Action, + warning: Redux.Action, + error: Redux.Action, + showConfirm: Redux.Action, + hideConfirm: Redux.Action + } + + /** + * Action creator for toastr. + */ + export var actions: Redux.ActionCreator; + /** + * Reducer for the toastr state. + * Combine with your reducers. + */ + export var reducer: Redux.Reducer; + /** + * Used to issue toastr notifications. + */ + export var toastr: ToastrEmitter; +} From e6e922c65ae7c97eee8adcb36acd1e9bcaae189d Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:55:37 +0300 Subject: [PATCH 174/212] Update react-redux-toastr-tests.ts --- .../react-redux-toastr-tests.ts | 25 +------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr-tests.ts b/react-redux-toastr/react-redux-toastr-tests.ts index 3abfc668d4..bd0426face 100644 --- a/react-redux-toastr/react-redux-toastr-tests.ts +++ b/react-redux-toastr/react-redux-toastr-tests.ts @@ -1,6 +1,6 @@ /// /// -/// +/// /// import {toastr, reducer as toastrReducer, actions} from 'react-redux-toastr'; import ReduxToastr from 'react-redux-toastr'; @@ -16,29 +16,6 @@ function test() { var providerFactory = React.createFactory(Provider); var root = providerFactory({ store: store }, element); - class Test extends React.Component{ - private toastr; - constructor() { - super() - this.toastr = bindActionCreators(actions, this.props.dispatch); - this.toastr.clean(); - this.toastr.success("hi"); - } - - } - - - var TestComponent = connect(mapStateToProps, mapDispatchToProps)(Test); - function mapDispatchToProps(dispatch) { - return { - actions: bindActionCreators(actions, dispatch) - }; - } - - function mapStateToProps(state) { - return {}; - } - function callback() { } toastr.clean(); From 42e0076772967425975dc40fcec076b7c06e1d9d Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 12:58:24 +0300 Subject: [PATCH 175/212] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index b10d430065..cef006ab20 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-redux-toastr 3.7.0 // Project: https://github.com/diegoddox/react-redux-toastr -// Definitions by: Aleksandar Ivanov https://github.com/Smiche +// Definitions by: Aleksandar Ivanov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// From 7682ff5176695f84efccff19d9afd5215dfbce93 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Tue, 20 Sep 2016 08:06:14 -0500 Subject: [PATCH 176/212] Correcting issues with s3-upload-stream typing --- s3-upload-stream/index.d.ts | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/s3-upload-stream/index.d.ts b/s3-upload-stream/index.d.ts index 382c3a57f1..be8de4148a 100644 --- a/s3-upload-stream/index.d.ts +++ b/s3-upload-stream/index.d.ts @@ -9,14 +9,16 @@ import * as stream from 'stream'; import * as AWS from 'aws-sdk'; -interface S3StreamUploader { - upload(destinationDetails: AWS.s3.PutObjectRequest, sessionDetails?: any): S3WriteStream; +declare namespace s3Stream { + export interface S3StreamUploader { + upload(destinationDetails: AWS.s3.PutObjectRequest, sessionDetails?: any): S3WriteStream; + } + + export interface S3WriteStream extends stream.Writable { + maxPartSize(sizeInBytes: number): void; + concurrentParts(numberOfParts: number): void; + } } -interface S3WriteStream extends stream.Writable { - maxPartSize(sizeInBytes: number): void; - concurrentParts(numberOfParts: number): void; -} - -declare function s3Stream(client: AWS.S3): S3StreamUploader; +declare function s3Stream(client: AWS.S3): s3Stream.S3StreamUploader; export = s3Stream; From 8564feb43c722afc8af0cf1b3e1de908ac7d15c7 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Tue, 20 Sep 2016 08:50:33 -0500 Subject: [PATCH 177/212] Adding typing for co-body --- co-body/co-body-tests.ts | 44 ++++++++++++++++++++++++++++++++++++++++ co-body/index.d.ts | 37 +++++++++++++++++++++++++++++++++ co-body/tsconfig.json | 19 +++++++++++++++++ 3 files changed, 100 insertions(+) create mode 100644 co-body/co-body-tests.ts create mode 100644 co-body/index.d.ts create mode 100644 co-body/tsconfig.json diff --git a/co-body/co-body-tests.ts b/co-body/co-body-tests.ts new file mode 100644 index 0000000000..6011632399 --- /dev/null +++ b/co-body/co-body-tests.ts @@ -0,0 +1,44 @@ +/// +/// + +import * as koa from 'koa'; +import * as parse from 'co-body'; + +var app = new koa(); + +app.use(async function (ctx: koa.Context, next: Function): Promise { + var body: any; + + // application/json + body = await parse.json(ctx.req); + + // explicit limit + body = await parse.json(ctx.req, { limit: '10kb' }); + + // application/x-www-form-urlencoded + body = await parse.form(ctx.req); + + // text/plain + body = await parse.text(ctx.req); + + // either + body = await parse(ctx.req); + + // custom type + body = await parse(ctx.req, { textTypes: ['text', 'html'] }); + + // This lib also supports ctx.req in Koa (or other libraries), so that you may simply use this instead of this.req. + + // application/json + body = await parse.json(ctx); + + // application/x-www-form-urlencoded + body = await parse.form(ctx); + + // text/plain + body = await parse.text(ctx); + + // either + body = await parse(ctx); +}); + diff --git a/co-body/index.d.ts b/co-body/index.d.ts new file mode 100644 index 0000000000..0393db0a94 --- /dev/null +++ b/co-body/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for co-body +// Project: https://github.com/cojs/co-body +// Definitions by: Joshua DeVinney +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// +/// + +import * as http from 'http'; +import * as Koa from 'koa'; +import * as qs from 'qs'; + +declare namespace CoBody { + type Context = http.IncomingMessage | Koa.Context; + + export interface Parse { + (context: Context, options?: Options): Promise; + text: (context: Context, options?: Options) => Promise; + form: (context: Context, options?: Options) => Promise; + json: (context: Context, options?: Options) => Promise; + } + + export interface Options { + limit?: number | string; + strict?: boolean; + queryString?: qs.IParseOptions; + jsonTypes?: string[]; + formTypes?: string[]; + textTypes?: string[]; + encoding?: string; + length?: number; + } +} + +declare var CoBody: CoBody.Parse; +export = CoBody; diff --git a/co-body/tsconfig.json b/co-body/tsconfig.json new file mode 100644 index 0000000000..be5ee22788 --- /dev/null +++ b/co-body/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "co-body-tests.ts" + ] +} \ No newline at end of file From 0502f8480e068fafd516a1189f0ce25a26abb387 Mon Sep 17 00:00:00 2001 From: David Poetzsch-Heffter Date: Tue, 20 Sep 2016 16:44:20 +0200 Subject: [PATCH 178/212] added import statement --- parse-mockdb/parse-mockdb-tests.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/parse-mockdb/parse-mockdb-tests.ts b/parse-mockdb/parse-mockdb-tests.ts index 89f586d9e8..8d60573a8b 100644 --- a/parse-mockdb/parse-mockdb-tests.ts +++ b/parse-mockdb/parse-mockdb-tests.ts @@ -1,5 +1,7 @@ /// +import * as ParseMockDB from "parse-mockdb"; + ParseMockDB.mockDB(); // Mock the Parse RESTController // from parse-mockdb test suite From 962044d3ceb599d00c6ec69053218439b0df87cb Mon Sep 17 00:00:00 2001 From: Ethan Resnick Date: Tue, 20 Sep 2016 10:46:08 -0400 Subject: [PATCH 179/212] Capitalize WebhookOptions --- twilio/twilio.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/twilio/twilio.d.ts b/twilio/twilio.d.ts index c0f16211f5..824b596330 100644 --- a/twilio/twilio.d.ts +++ b/twilio/twilio.d.ts @@ -429,7 +429,7 @@ declare namespace twilio { export class TwimlResponse extends Node {} /// webhook.js - export interface webhookOptions { + export interface WebhookOptions { validate?: boolean; includeHelpers?: boolean; host?: string; @@ -450,8 +450,8 @@ declare namespace twilio { // For interop with node middleware chains export interface MiddlewareFunction { (request: Http.ServerRequest, response: Http.ServerResponse, next: Express.NextFunction): void; } - export function webhook(authToken: string, options?: webhookOptions): MiddlewareFunction; - export function webhook(options?: webhookOptions): MiddlewareFunction; + export function webhook(authToken: string, options?: WebhookOptions): MiddlewareFunction; + export function webhook(options?: WebhookOptions): MiddlewareFunction; export function validateRequest(authToken: string, twilioHeader: string, url: string, params?: any): boolean; export function validateExpressRequest(request: Express.Request, authToken: string, options?: WebhookExpressOptions): boolean; From be207d84a7df0bd0e3047fd60e447996ab707b04 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 18:03:49 +0300 Subject: [PATCH 180/212] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index cef006ab20..380dd3ad61 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -48,13 +48,13 @@ declare module "react-redux-toastr" { removeOnHover?: boolean, removeOnClick?: boolean, component?: R.Component, - onShowComplete?: () => void, - onHideComplete?: () => void + onShowComplete?: (): void; + onHideComplete?: (): void; } interface ToastrConfirmOptions { - onOk: () => void, - onCancel: () => void + onOk: (): void; + onCancel: (): void; } interface ToastrEmitter { @@ -62,19 +62,19 @@ declare module "react-redux-toastr" { * Used to provide a large amount of information. * It will not close unless a timeOut is provided. */ - message: (title: string, message: string, options?: EmitterOptions) => void, - info: (title: string, message: string, options?: EmitterOptions) => void, - success: (title: string, message: string, options?: EmitterOptions) => void, - warning: (title: string, message: string, options?: EmitterOptions) => void, - error: (title: string, message: string, options?: EmitterOptions) => void, + message: (title: string, message: string, options?: EmitterOptions): void; + info: (title: string, message: string, options?: EmitterOptions): void; + success: (title: string, message: string, options?: EmitterOptions): void; + warning: (title: string, message: string, options?: EmitterOptions): void; + error: (title: string, message: string, options?: EmitterOptions): void; /** * Clear all notifications */ - clean: () => void, + clean: (): void; /** * Hook confirmation toastr with callback. */ - confirm: (message: string, options: ToastrConfirmOptions) => any + confirm: (message: string, options: ToastrConfirmOptions): void; } /** From 913827f4c26e487db4454299e65f685f19ac6ced Mon Sep 17 00:00:00 2001 From: Aleksey Blokhin Date: Tue, 20 Sep 2016 18:14:10 +0300 Subject: [PATCH 181/212] `finally` returns original promise. --- js-data/js-data.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/js-data/js-data.d.ts b/js-data/js-data.d.ts index 58bef671b1..284e66486b 100644 --- a/js-data/js-data.d.ts +++ b/js-data/js-data.d.ts @@ -15,7 +15,7 @@ declare namespace JSData { catch(onRejected?:(error:any) => U | JSDataPromise): JSDataPromise; // enhanced with finally - finally(finallyCb?:() => U):JSDataPromise; + finally(finallyCb?:() => any): JSDataPromise; } interface DSConfiguration extends IDSResourceLifecycleEventHandlers { From f11138f44326f40a9c676758ef2bf0164fa94a41 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 18:15:54 +0300 Subject: [PATCH 182/212] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index 380dd3ad61..21c72e093a 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -48,8 +48,8 @@ declare module "react-redux-toastr" { removeOnHover?: boolean, removeOnClick?: boolean, component?: R.Component, - onShowComplete?: (): void; - onHideComplete?: (): void; + onShowComplete?(): void; + onHideComplete?(): void; } interface ToastrConfirmOptions { @@ -62,19 +62,19 @@ declare module "react-redux-toastr" { * Used to provide a large amount of information. * It will not close unless a timeOut is provided. */ - message: (title: string, message: string, options?: EmitterOptions): void; - info: (title: string, message: string, options?: EmitterOptions): void; - success: (title: string, message: string, options?: EmitterOptions): void; - warning: (title: string, message: string, options?: EmitterOptions): void; - error: (title: string, message: string, options?: EmitterOptions): void; + message(title: string, message: string, options?: EmitterOptions): void; + info(title: string, message: string, options?: EmitterOptions): void; + success(title: string, message: string, options?: EmitterOptions): void; + warning(title: string, message: string, options?: EmitterOptions): void; + error(title: string, message: string, options?: EmitterOptions): void; /** * Clear all notifications */ - clean: (): void; + clean(): void; /** * Hook confirmation toastr with callback. */ - confirm: (message: string, options: ToastrConfirmOptions): void; + confirm(message: string, options: ToastrConfirmOptions): void; } /** From 41e5e3d1782f6ded0a0bfdc22f2032550c966ca3 Mon Sep 17 00:00:00 2001 From: Aleksandar Ivanov Date: Tue, 20 Sep 2016 18:16:27 +0300 Subject: [PATCH 183/212] Update react-redux-toastr.d.ts --- react-redux-toastr/react-redux-toastr.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/react-redux-toastr/react-redux-toastr.d.ts b/react-redux-toastr/react-redux-toastr.d.ts index 21c72e093a..1b628455aa 100644 --- a/react-redux-toastr/react-redux-toastr.d.ts +++ b/react-redux-toastr/react-redux-toastr.d.ts @@ -53,8 +53,8 @@ declare module "react-redux-toastr" { } interface ToastrConfirmOptions { - onOk: (): void; - onCancel: (): void; + onOk(): void; + onCancel(): void; } interface ToastrEmitter { From 0a7b57e864008813376180cc043cf242f4c19c50 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Sun, 4 Sep 2016 17:41:31 -0500 Subject: [PATCH 184/212] Adding typings for fs-extra-promise-es6 (sourced from fs-extra-promise) --- .../fs-extra-promise-es6-tests.ts | 228 +++++++++++++++ fs-extra-promise-es6/index.d.ts | 260 ++++++++++++++++++ fs-extra-promise-es6/tsconfig.json | 19 ++ 3 files changed, 507 insertions(+) create mode 100644 fs-extra-promise-es6/fs-extra-promise-es6-tests.ts create mode 100644 fs-extra-promise-es6/index.d.ts create mode 100644 fs-extra-promise-es6/tsconfig.json diff --git a/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts b/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts new file mode 100644 index 0000000000..f32065d0e6 --- /dev/null +++ b/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts @@ -0,0 +1,228 @@ +/// + +import fs = require('fs-extra-promise-es6'); +import stream = require('stream'); + +var stats: fs.Stats; +var str: string; +var strArr: string[]; +var bool: boolean; +var num: number; +var src: string; +var dest: string; +var file: string; +var filename: string; +var dir: string; +var path: string; +var data: any; +var object: Object; +var buffer: NodeBuffer; +var modeNum: number; +var modeStr: string; +var encoding: string; +var type: string; +var flags: string; +var srcpath: string; +var dstpath: string; +var oldPath: string; +var newPath: string; +var cache: string; +var offset: number; +var length: number; +var position: number; +var cacheBool: boolean; +var cacheStr: string; +var fd: number; +var len: number; +var uid: number; +var gid: number; +var atime: number; +var mtime: number; +var statsCallback: (err: Error, stats: fs.Stats) => void; +var errorCallback: (err: Error) => void; +var openOpts: fs.OpenOptions; +var watcher: fs.FSWatcher; +var readStreeam: stream.Readable; +var writeStream: stream.Writable; + +fs.copy(src, dest, errorCallback); +fs.copy(src, dest, (src: string) => { + return false; +}, errorCallback); +fs.copySync(src, dest); +fs.copySync(src, dest, (src: string) => { + return false; +}); +fs.createFile(file, errorCallback); +fs.createFileSync(file); + +fs.mkdirs(dir, errorCallback); +fs.mkdirsSync(dir); +fs.mkdirp(dir, errorCallback); +fs.mkdirpSync(dir); + +fs.outputFile(file, data, errorCallback); +fs.outputFileSync(file, data); +fs.outputJson(file, data, errorCallback); +fs.outputJSON(file, data, errorCallback); + +fs.outputJsonSync(file, data); +fs.outputJSONSync(file, data); + +fs.readJson(file, errorCallback); +fs.readJson(file, openOpts, errorCallback); +fs.readJSON(file, errorCallback); +fs.readJSON(file, openOpts, errorCallback); + +fs.readJsonSync(file, openOpts); +fs.readJSONSync(file, openOpts); + +fs.remove(dir, errorCallback); +fs.removeSync(dir); + +fs.writeJson(file, object, errorCallback); +fs.writeJson(file, object, openOpts, errorCallback); +fs.writeJSON(file, object, errorCallback); +fs.writeJSON(file, object, openOpts, errorCallback); + +fs.writeJsonSync(file, object, openOpts); +fs.writeJSONSync(file, object, openOpts); + +fs.rename(oldPath, newPath, errorCallback); +fs.renameSync(oldPath, newPath); +fs.truncate(fd, len, errorCallback); +fs.truncateSync(fd, len); +fs.chown(path, uid, gid, errorCallback); +fs.chownSync(path, uid, gid); +fs.fchown(fd, uid, gid, errorCallback); +fs.fchownSync(fd, uid, gid); +fs.lchown(path, uid, gid, errorCallback); +fs.lchownSync(path, uid, gid); +fs.chmod(path, modeNum, errorCallback); +fs.chmod(path, modeStr, errorCallback); +fs.chmodSync(path, modeNum); +fs.chmodSync(path, modeStr); +fs.fchmod(fd, modeNum, errorCallback); +fs.fchmod(fd, modeStr, errorCallback); +fs.fchmodSync(fd, modeNum); +fs.fchmodSync(fd, modeStr); +fs.lchmod(path, modeStr, errorCallback); +fs.lchmod(path, modeNum, errorCallback); +fs.lchmodSync(path, modeNum); +fs.lchmodSync(path, modeStr); +fs.stat(path, statsCallback); +fs.lstat(path, statsCallback); +fs.fstat(fd, statsCallback); +stats = fs.statSync(path); +stats = fs.lstatSync(path); +stats = fs.fstatSync(fd); +fs.link(srcpath, dstpath, errorCallback); +fs.linkSync(srcpath, dstpath); +fs.symlink(srcpath, dstpath, type, errorCallback); +fs.symlinkSync(srcpath, dstpath, type); +fs.readlink(path, (err: Error, linkString: string) => { + +}); +fs.realpath(path, (err: Error, resolvedPath: string) => { + +}); +fs.realpath(path, cache, (err: Error, resolvedPath: string) => { + +}); +str = fs.realpathSync(path, cacheBool); +fs.unlink(path, errorCallback); +fs.unlinkSync(path); +fs.rmdir(path, errorCallback); +fs.rmdirSync(path); +fs.mkdir(path, modeNum, errorCallback); +fs.mkdir(path, modeStr, errorCallback); +fs.mkdirSync(path, modeNum); +fs.mkdirSync(path, modeStr); +fs.readdir(path, (err: Error, files: string[]) => { + +}); +strArr = fs.readdirSync(path); +fs.close(fd, errorCallback); +fs.closeSync(fd); +fs.open(path, flags, modeStr, (err: Error, fd: number) => { + +}); +num = fs.openSync(path, flags, modeStr); +fs.utimes(path, atime, mtime, errorCallback); +fs.utimesSync(path, atime, mtime); +fs.futimes(fd, atime, mtime, errorCallback); +fs.futimesSync(fd, atime, mtime); +fs.fsync(fd, errorCallback); +fs.fsyncSync(fd); +fs.write(fd, buffer, offset, length, position, (err: Error, written: number, buffer: NodeBuffer) => { + +}); +num = fs.writeSync(fd, buffer, offset, length, position); +fs.read(fd, buffer, offset, length, position, (err: Error, bytesRead: number, buffer: NodeBuffer) => { + +}); +num = fs.readSync(fd, buffer, offset, length, position); +fs.readFile(filename, (err: Error, data: NodeBuffer) => { + +}); +fs.readFile(filename, encoding, (err: Error, data: string) => { + +}); +fs.readFile(filename, openOpts, (err: Error, data: string) => { + +}); +fs.readFile(filename, (err: Error, data: NodeBuffer) => { + +}); +buffer = fs.readFileSync(filename); +str = fs.readFileSync(filename, encoding); +str = fs.readFileSync(filename, openOpts); + +fs.writeFile(filename, data, errorCallback); +fs.writeFile(filename, data, encoding, errorCallback); +fs.writeFile(filename, data, openOpts, errorCallback); +fs.writeFileSync(filename, data); +fs.writeFileSync(filename, data, encoding); +fs.writeFileSync(filename, data, openOpts); + +fs.appendFile(filename, data, errorCallback); +fs.appendFile(filename, data, encoding, errorCallback); +fs.appendFile(filename, data, openOpts, errorCallback); +fs.appendFileSync(filename, data); +fs.appendFileSync(filename, data, encoding); +fs.appendFileSync(filename, data, openOpts); + +fs.watchFile(filename, { + curr: stats, + prev: stats +}); +fs.watchFile(filename, { + persistent: bool, + interval: num +}, { + curr: stats, + prev: stats +}); +fs.unwatchFile(filename); +watcher = fs.watch(filename, { persistent: bool }, (event: string, filename: string) => { + +}); +fs.exists(path, (exists: boolean) => { + +}); +bool = fs.existsSync(path); + +readStreeam = fs.createReadStream(path); +readStreeam = fs.createReadStream(path, { + flags: str, + encoding: str, + fd: num, + mode: num, + bufferSize: num +}); +writeStream = fs.createWriteStream(path); +writeStream = fs.createWriteStream(path, { + flags: str, + encoding: str, + string: str +}); diff --git a/fs-extra-promise-es6/index.d.ts b/fs-extra-promise-es6/index.d.ts new file mode 100644 index 0000000000..15027a70e3 --- /dev/null +++ b/fs-extra-promise-es6/index.d.ts @@ -0,0 +1,260 @@ +// Type definitions for fs-extra-promise-es6 +// Project: https://github.com/vinsonchuong/fs-extra-promise-es6 +// Definitions by: midknight41 , Jason Swearingen , Joshua DeVinney +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Imported from: fs-extra-promise typings (minus Bluebird) + +/// + + +import stream = require("stream"); + +export interface Stats { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: number; + ino: number; + mode: number; + nlink: number; + uid: number; + gid: number; + rdev: number; + size: number; + blksize: number; + blocks: number; + atime: Date; + mtime: Date; + ctime: Date; +} + +export interface FSWatcher { + close(): void; +} + +export declare class ReadStream extends stream.Readable { } +export declare class WriteStream extends stream.Writable { } + +//extended methods +export declare function copy(src: string, dest: string, callback?: (err: Error) => void): void; +export declare function copy(src: string, dest: string, filter: (src: string) => boolean, callback?: (err: Error) => void): void; + +export declare function copySync(src: string, dest: string): void; +export declare function copySync(src: string, dest: string, filter: (src: string) => boolean): void; + +export declare function createFile(file: string, callback?: (err: Error) => void): void; +export declare function createFileSync(file: string): void; + +export declare function mkdirs(dir: string, callback?: (err: Error) => void): void; +export declare function mkdirp(dir: string, callback?: (err: Error) => void): void; +export declare function mkdirsSync(dir: string): void; +export declare function mkdirpSync(dir: string): void; + +export declare function outputFile(file: string, data: any, callback?: (err: Error) => void): void; +export declare function outputFileSync(file: string, data: any): void; + +export declare function outputJson(file: string, data: any, callback?: (err: Error) => void): void; +export declare function outputJSON(file: string, data: any, callback?: (err: Error) => void): void; +export declare function outputJsonSync(file: string, data: any): void; +export declare function outputJSONSync(file: string, data: any): void; + +export declare function readJson(file: string, callback?: (err: Error) => void): void; +export declare function readJson(file: string, options?: OpenOptions, callback?: (err: Error) => void): void; +export declare function readJSON(file: string, callback?: (err: Error) => void): void; +export declare function readJSON(file: string, options?: OpenOptions, callback?: (err: Error) => void): void; + +export declare function readJsonSync(file: string, options?: OpenOptions): void; +export declare function readJSONSync(file: string, options?: OpenOptions): void; + +export declare function remove(dir: string, callback?: (err: Error) => void): void; +export declare function removeSync(dir: string): void; +// export function delete(dir: string, callback?: (err: Error) => void): void; +// export function deleteSync(dir: string): void; + +export declare function writeJson(file: string, object: any, callback?: (err: Error) => void): void; +export declare function writeJson(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void; +export declare function writeJSON(file: string, object: any, callback?: (err: Error) => void): void; +export declare function writeJSON(file: string, object: any, options?: OpenOptions, callback?: (err: Error) => void): void; + +export declare function writeJsonSync(file: string, object: any, options?: OpenOptions): void; +export declare function writeJSONSync(file: string, object: any, options?: OpenOptions): void; + +export declare function rename(oldPath: string, newPath: string, callback?: (err: Error) => void): void; +export declare function renameSync(oldPath: string, newPath: string): void; +export declare function truncate(fd: number, len: number, callback?: (err: Error) => void): void; +export declare function truncateSync(fd: number, len: number): void; +export declare function chown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; +export declare function chownSync(path: string, uid: number, gid: number): void; +export declare function fchown(fd: number, uid: number, gid: number, callback?: (err: Error) => void): void; +export declare function fchownSync(fd: number, uid: number, gid: number): void; +export declare function lchown(path: string, uid: number, gid: number, callback?: (err: Error) => void): void; +export declare function lchownSync(path: string, uid: number, gid: number): void; +export declare function chmod(path: string, mode: number, callback?: (err: Error) => void): void; +export declare function chmod(path: string, mode: string, callback?: (err: Error) => void): void; +export declare function chmodSync(path: string, mode: number): void; +export declare function chmodSync(path: string, mode: string): void; +export declare function fchmod(fd: number, mode: number, callback?: (err: Error) => void): void; +export declare function fchmod(fd: number, mode: string, callback?: (err: Error) => void): void; +export declare function fchmodSync(fd: number, mode: number): void; +export declare function fchmodSync(fd: number, mode: string): void; +export declare function lchmod(path: string, mode: string, callback?: (err: Error) => void): void; +export declare function lchmod(path: string, mode: number, callback?: (err: Error) => void): void; +export declare function lchmodSync(path: string, mode: number): void; +export declare function lchmodSync(path: string, mode: string): void; +export declare function stat(path: string, callback?: (err: Error, stats: Stats) => void): void; +export declare function lstat(path: string, callback?: (err: Error, stats: Stats) => void): void; +export declare function fstat(fd: number, callback?: (err: Error, stats: Stats) => void): void; +export declare function statSync(path: string): Stats; +export declare function lstatSync(path: string): Stats; +export declare function fstatSync(fd: number): Stats; +export declare function link(srcpath: string, dstpath: string, callback?: (err: Error) => void): void; +export declare function linkSync(srcpath: string, dstpath: string): void; +export declare function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err: Error) => void): void; +export declare function symlinkSync(srcpath: string, dstpath: string, type?: string): void; +export declare function readlink(path: string, callback?: (err: Error, linkString: string) => void): void; +export declare function realpath(path: string, callback?: (err: Error, resolvedPath: string) => void): void; +export declare function realpath(path: string, cache: string, callback: (err: Error, resolvedPath: string) => void): void; +export declare function realpathSync(path: string, cache?: boolean): string; +export declare function unlink(path: string, callback?: (err: Error) => void): void; +export declare function unlinkSync(path: string): void; +export declare function rmdir(path: string, callback?: (err: Error) => void): void; +export declare function rmdirSync(path: string): void; +export declare function mkdir(path: string, mode?: number, callback?: (err: Error) => void): void; +export declare function mkdir(path: string, mode?: string, callback?: (err: Error) => void): void; +export declare function mkdirSync(path: string, mode?: number): void; +export declare function mkdirSync(path: string, mode?: string): void; +export declare function readdir(path: string, callback?: (err: Error, files: string[]) => void): void; +export declare function readdirSync(path: string): string[]; +export declare function close(fd: number, callback?: (err: Error) => void): void; +export declare function closeSync(fd: number): void; +export declare function open(path: string, flags: string, mode?: string, callback?: (err: Error, fs: number) => void): void; +export declare function openSync(path: string, flags: string, mode?: string): number; +export declare function utimes(path: string, atime: number, mtime: number, callback?: (err: Error) => void): void; +export declare function utimesSync(path: string, atime: number, mtime: number): void; +export declare function futimes(fd: number, atime: number, mtime: number, callback?: (err: Error) => void): void; +export declare function futimesSync(fd: number, atime: number, mtime: number): void; +export declare function fsync(fd: number, callback?: (err: Error) => void): void; +export declare function fsyncSync(fd: number): void; +export declare function write(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, written: number, buffer: NodeBuffer) => void): void; +export declare function writeSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; +export declare function read(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number, callback?: (err: Error, bytesRead: number, buffer: NodeBuffer) => void): void; +export declare function readSync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): number; +export declare function readFile(filename: string, encoding: string, callback: (err: Error, data: string) => void): void; +export declare function readFile(filename: string, options: OpenOptions, callback: (err: Error, data: string) => void): void; +export declare function readFile(filename: string, callback: (err: Error, data: NodeBuffer) => void): void; +export declare function readFileSync(filename: string): NodeBuffer; +export declare function readFileSync(filename: string, encoding: string): string; +export declare function readFileSync(filename: string, options: OpenOptions): string; +export declare function writeFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void; +export declare function writeFile(filename: string, data: any, options?: OpenOptions, callback?: (err: Error) => void): void; +export declare function writeFileSync(filename: string, data: any, encoding?: string): void; +export declare function writeFileSync(filename: string, data: any, option?: OpenOptions): void; +export declare function appendFile(filename: string, data: any, encoding?: string, callback?: (err: Error) => void): void; +export declare function appendFile(filename: string, data: any, option?: OpenOptions, callback?: (err: Error) => void): void; +export declare function appendFileSync(filename: string, data: any, encoding?: string): void; +export declare function appendFileSync(filename: string, data: any, option?: OpenOptions): void; +export declare function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void; +export declare function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void; +export declare function unwatchFile(filename: string, listener?: Stats): void; +export declare function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; +export declare function exists(path: string, callback?: (exists: boolean) => void): void; +export declare function existsSync(path: string): boolean; +export declare function ensureDir(path: string, cb: (err: Error) => void): void; +export declare function ensureDirSync(path: string): void; + +export interface OpenOptions { + encoding?: string; + flag?: string; +} + +export interface ReadStreamOptions { + flags?: string; + encoding?: string; + fd?: number; + mode?: number; + bufferSize?: number; +} +export interface WriteStreamOptions { + flags?: string; + encoding?: string; + string?: string; +} +export declare function createReadStream(path: string, options?: ReadStreamOptions): ReadStream; +export declare function createWriteStream(path: string, options?: WriteStreamOptions): WriteStream; + + + +//promisified versions +export declare function copyAsync(src: string, dest: string): Promise; +export declare function copyAsync(src: string, dest: string, filter: (src: string) => boolean): Promise; + +export declare function createFileAsync(file: string): Promise; + +export declare function mkdirsAsync(dir: string): Promise; +export declare function mkdirpAsync(dir: string): Promise; + +export declare function outputFileAsync(file: string, data: any): Promise; + +export declare function outputJsonAsync(file: string, data: any): Promise; +export declare function outputJSONAsync(file: string, data: any): Promise; + +export declare function readJsonAsync(file: string): Promise; +export declare function readJsonAsync(file: string, options?: OpenOptions): Promise; +export declare function readJSONAsync(file: string): Promise; +export declare function readJSONAsync(file: string, options?: OpenOptions): Promise; + + +export declare function removeAsync(dir: string): Promise; +// export function deleteAsync(dir: string):Promise; + +export declare function writeJsonAsync(file: string, object: any): Promise; +export declare function writeJsonAsync(file: string, object: any, options?: OpenOptions): Promise; +export declare function writeJSONAsync(file: string, object: any): Promise; +export declare function writeJSONAsync(file: string, object: any, options?: OpenOptions): Promise; + +export declare function renameAsync(oldPath: string, newPath: string): Promise; +export declare function truncateAsync(fd: number, len: number): Promise; +export declare function chownAsync(path: string, uid: number, gid: number): Promise; +export declare function fchownAsync(fd: number, uid: number, gid: number): Promise; +export declare function lchownAsync(path: string, uid: number, gid: number): Promise; +export declare function chmodAsync(path: string, mode: number): Promise; +export declare function chmodAsync(path: string, mode: string): Promise; +export declare function fchmodAsync(fd: number, mode: number): Promise; +export declare function fchmodAsync(fd: number, mode: string): Promise; +export declare function lchmodAsync(path: string, mode: string): Promise; +export declare function lchmodAsync(path: string, mode: number): Promise; +export declare function statAsync(path: string): Promise; +export declare function lstatAsync(path: string): Promise; +export declare function fstatAsync(fd: number): Promise; +export declare function linkAsync(srcpath: string, dstpath: string): Promise; +export declare function symlinkAsync(srcpath: string, dstpath: string, type?: string): Promise; +export declare function readlinkAsync(path: string): Promise; +export declare function realpathAsync(path: string): Promise; +export declare function realpathAsync(path: string, cache: string): Promise; +export declare function unlinkAsync(path: string): Promise; +export declare function rmdirAsync(path: string): Promise; +export declare function mkdirAsync(path: string, mode?: number): Promise; +export declare function mkdirAsync(path: string, mode?: string): Promise; +export declare function readdirAsync(path: string): Promise; +export declare function closeAsync(fd: number): Promise; +export declare function openAsync(path: string, flags: string, mode?: string): Promise; +export declare function utimesAsync(path: string, atime: number, mtime: number): Promise; +export declare function futimesAsync(fd: number, atime: number, mtime: number): Promise; +export declare function fsyncAsync(fd: number): Promise; +export declare function writeAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +export declare function readAsync(fd: number, buffer: NodeBuffer, offset: number, length: number, position: number): Promise<[number, NodeBuffer]>; +export declare function readFileAsync(filename: string, encoding: string): Promise; +export declare function readFileAsync(filename: string, options: OpenOptions): Promise; +export declare function readFileAsync(filename: string): Promise; +export declare function writeFileAsync(filename: string, data: any, encoding?: string): Promise; +export declare function writeFileAsync(filename: string, data: any, options?: OpenOptions): Promise; +export declare function appendFileAsync(filename: string, data: any, encoding?: string): Promise; +export declare function appendFileAsync(filename: string, data: any, option?: OpenOptions): Promise; + +export declare function existsAsync(path: string): Promise; +export declare function ensureDirAsync(path: string): Promise; diff --git a/fs-extra-promise-es6/tsconfig.json b/fs-extra-promise-es6/tsconfig.json new file mode 100644 index 0000000000..a0bda21ebe --- /dev/null +++ b/fs-extra-promise-es6/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fs-extra-promise-es6-tests.ts" + ] +} \ No newline at end of file From a21f098c7c52d84e17b4e52832d17a0ed84ae4bd Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Mon, 19 Sep 2016 21:46:48 -0500 Subject: [PATCH 185/212] Making changes to fs-extra-promise-es6 to update the node definitions and reuse some definitions per @andy-ms --- fs-extra-promise-es6/index.d.ts | 65 +++++++++++---------------------- 1 file changed, 22 insertions(+), 43 deletions(-) diff --git a/fs-extra-promise-es6/index.d.ts b/fs-extra-promise-es6/index.d.ts index 15027a70e3..e67503e559 100644 --- a/fs-extra-promise-es6/index.d.ts +++ b/fs-extra-promise-es6/index.d.ts @@ -9,29 +9,7 @@ import stream = require("stream"); - -export interface Stats { - isFile(): boolean; - isDirectory(): boolean; - isBlockDevice(): boolean; - isCharacterDevice(): boolean; - isSymbolicLink(): boolean; - isFIFO(): boolean; - isSocket(): boolean; - dev: number; - ino: number; - mode: number; - nlink: number; - uid: number; - gid: number; - rdev: number; - size: number; - blksize: number; - blocks: number; - atime: Date; - mtime: Date; - ctime: Date; -} +import fs = require("fs"); export interface FSWatcher { close(): void; @@ -106,12 +84,12 @@ export declare function lchmod(path: string, mode: string, callback?: (err: Erro export declare function lchmod(path: string, mode: number, callback?: (err: Error) => void): void; export declare function lchmodSync(path: string, mode: number): void; export declare function lchmodSync(path: string, mode: string): void; -export declare function stat(path: string, callback?: (err: Error, stats: Stats) => void): void; -export declare function lstat(path: string, callback?: (err: Error, stats: Stats) => void): void; -export declare function fstat(fd: number, callback?: (err: Error, stats: Stats) => void): void; -export declare function statSync(path: string): Stats; -export declare function lstatSync(path: string): Stats; -export declare function fstatSync(fd: number): Stats; +export declare function stat(path: string, callback?: (err: Error, stats: fs.Stats) => void): void; +export declare function lstat(path: string, callback?: (err: Error, stats: fs.Stats) => void): void; +export declare function fstat(fd: number, callback?: (err: Error, stats: fs.Stats) => void): void; +export declare function statSync(path: string): fs.Stats; +export declare function lstatSync(path: string): fs.Stats; +export declare function fstatSync(fd: number): fs.Stats; export declare function link(srcpath: string, dstpath: string, callback?: (err: Error) => void): void; export declare function linkSync(srcpath: string, dstpath: string): void; export declare function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err: Error) => void): void; @@ -158,9 +136,9 @@ export declare function appendFile(filename: string, data: any, encoding?: strin export declare function appendFile(filename: string, data: any, option?: OpenOptions, callback?: (err: Error) => void): void; export declare function appendFileSync(filename: string, data: any, encoding?: string): void; export declare function appendFileSync(filename: string, data: any, option?: OpenOptions): void; -export declare function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void; -export declare function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void; -export declare function unwatchFile(filename: string, listener?: Stats): void; +export declare function watchFile(filename: string, listener: { curr: fs.Stats; prev: fs.Stats; }): void; +export declare function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: fs.Stats; prev: fs.Stats; }): void; +export declare function unwatchFile(filename: string, listener?: fs.Stats): void; export declare function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; export declare function exists(path: string, callback?: (exists: boolean) => void): void; export declare function existsSync(path: string): boolean; @@ -172,20 +150,21 @@ export interface OpenOptions { flag?: string; } -export interface ReadStreamOptions { +export declare function createReadStream(path: string | Buffer, options?: { flags?: string; encoding?: string; fd?: number; mode?: number; - bufferSize?: number; -} -export interface WriteStreamOptions { + autoClose?: boolean; + start?: number; + end?: number; +}): ReadStream; +export declare function createWriteStream(path: string | Buffer, options?: { flags?: string; encoding?: string; - string?: string; -} -export declare function createReadStream(path: string, options?: ReadStreamOptions): ReadStream; -export declare function createWriteStream(path: string, options?: WriteStreamOptions): WriteStream; + fd?: number; + mode?: number; +}): WriteStream; @@ -228,9 +207,9 @@ export declare function fchmodAsync(fd: number, mode: number): Promise; export declare function fchmodAsync(fd: number, mode: string): Promise; export declare function lchmodAsync(path: string, mode: string): Promise; export declare function lchmodAsync(path: string, mode: number): Promise; -export declare function statAsync(path: string): Promise; -export declare function lstatAsync(path: string): Promise; -export declare function fstatAsync(fd: number): Promise; +export declare function statAsync(path: string): Promise; +export declare function lstatAsync(path: string): Promise; +export declare function fstatAsync(fd: number): Promise; export declare function linkAsync(srcpath: string, dstpath: string): Promise; export declare function symlinkAsync(srcpath: string, dstpath: string, type?: string): Promise; export declare function readlinkAsync(path: string): Promise; From a0ffa74fd9f2400b1faf4829a1be67080ea0a1cf Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Tue, 20 Sep 2016 07:55:39 -0500 Subject: [PATCH 186/212] Adding back the Stats interface, just extending it from fs.Stats instead --- fs-extra-promise-es6/index.d.ts | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/fs-extra-promise-es6/index.d.ts b/fs-extra-promise-es6/index.d.ts index e67503e559..3c9e227fbb 100644 --- a/fs-extra-promise-es6/index.d.ts +++ b/fs-extra-promise-es6/index.d.ts @@ -11,6 +11,9 @@ import stream = require("stream"); import fs = require("fs"); +export interface Stats extends fs.Stats { +} + export interface FSWatcher { close(): void; } @@ -84,12 +87,12 @@ export declare function lchmod(path: string, mode: string, callback?: (err: Erro export declare function lchmod(path: string, mode: number, callback?: (err: Error) => void): void; export declare function lchmodSync(path: string, mode: number): void; export declare function lchmodSync(path: string, mode: string): void; -export declare function stat(path: string, callback?: (err: Error, stats: fs.Stats) => void): void; -export declare function lstat(path: string, callback?: (err: Error, stats: fs.Stats) => void): void; -export declare function fstat(fd: number, callback?: (err: Error, stats: fs.Stats) => void): void; -export declare function statSync(path: string): fs.Stats; -export declare function lstatSync(path: string): fs.Stats; -export declare function fstatSync(fd: number): fs.Stats; +export declare function stat(path: string, callback?: (err: Error, stats: Stats) => void): void; +export declare function lstat(path: string, callback?: (err: Error, stats: Stats) => void): void; +export declare function fstat(fd: number, callback?: (err: Error, stats: Stats) => void): void; +export declare function statSync(path: string): Stats; +export declare function lstatSync(path: string): Stats; +export declare function fstatSync(fd: number): Stats; export declare function link(srcpath: string, dstpath: string, callback?: (err: Error) => void): void; export declare function linkSync(srcpath: string, dstpath: string): void; export declare function symlink(srcpath: string, dstpath: string, type?: string, callback?: (err: Error) => void): void; @@ -136,9 +139,9 @@ export declare function appendFile(filename: string, data: any, encoding?: strin export declare function appendFile(filename: string, data: any, option?: OpenOptions, callback?: (err: Error) => void): void; export declare function appendFileSync(filename: string, data: any, encoding?: string): void; export declare function appendFileSync(filename: string, data: any, option?: OpenOptions): void; -export declare function watchFile(filename: string, listener: { curr: fs.Stats; prev: fs.Stats; }): void; -export declare function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: fs.Stats; prev: fs.Stats; }): void; -export declare function unwatchFile(filename: string, listener?: fs.Stats): void; +export declare function watchFile(filename: string, listener: { curr: Stats; prev: Stats; }): void; +export declare function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: { curr: Stats; prev: Stats; }): void; +export declare function unwatchFile(filename: string, listener?: Stats): void; export declare function watch(filename: string, options?: { persistent?: boolean; }, listener?: (event: string, filename: string) => any): FSWatcher; export declare function exists(path: string, callback?: (exists: boolean) => void): void; export declare function existsSync(path: string): boolean; @@ -207,9 +210,9 @@ export declare function fchmodAsync(fd: number, mode: number): Promise; export declare function fchmodAsync(fd: number, mode: string): Promise; export declare function lchmodAsync(path: string, mode: string): Promise; export declare function lchmodAsync(path: string, mode: number): Promise; -export declare function statAsync(path: string): Promise; -export declare function lstatAsync(path: string): Promise; -export declare function fstatAsync(fd: number): Promise; +export declare function statAsync(path: string): Promise; +export declare function lstatAsync(path: string): Promise; +export declare function fstatAsync(fd: number): Promise; export declare function linkAsync(srcpath: string, dstpath: string): Promise; export declare function symlinkAsync(srcpath: string, dstpath: string, type?: string): Promise; export declare function readlinkAsync(path: string): Promise; From f422dcfbef926353bd56a58849f296ee36d21928 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Tue, 20 Sep 2016 08:09:14 -0500 Subject: [PATCH 187/212] Switching Stats from interface to type --- fs-extra-promise-es6/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fs-extra-promise-es6/index.d.ts b/fs-extra-promise-es6/index.d.ts index 3c9e227fbb..85055636dc 100644 --- a/fs-extra-promise-es6/index.d.ts +++ b/fs-extra-promise-es6/index.d.ts @@ -11,8 +11,7 @@ import stream = require("stream"); import fs = require("fs"); -export interface Stats extends fs.Stats { -} +export type Stats = fs.Stats export interface FSWatcher { close(): void; From 19d322598681132893676203af46d8d2d81d5992 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Tue, 20 Sep 2016 10:34:41 -0500 Subject: [PATCH 188/212] Typing for uid-safe --- uid-safe/index.d.ts | 19 +++++++++++++++++++ uid-safe/tsconfig.json | 19 +++++++++++++++++++ uid-safe/uid-safe-test.ts | 12 ++++++++++++ 3 files changed, 50 insertions(+) create mode 100644 uid-safe/index.d.ts create mode 100644 uid-safe/tsconfig.json create mode 100644 uid-safe/uid-safe-test.ts diff --git a/uid-safe/index.d.ts b/uid-safe/index.d.ts new file mode 100644 index 0000000000..9892734e1c --- /dev/null +++ b/uid-safe/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for co-body +// Project: https://github.com/crypto-utils/uid-safe +// Definitions by: Joshua DeVinney +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace UID { + + export interface Generate { + + (byteLenth: number, callback: (err: any, str: string) => any): void; + (byteLenth: number): Promise; + (byteLenth: number, callback?: (err: any, str: string) => any): Promise | void; + + sync(byteLength: number): string; + } +} + +declare var UID: UID.Generate; +export = UID; diff --git a/uid-safe/tsconfig.json b/uid-safe/tsconfig.json new file mode 100644 index 0000000000..a0bda21ebe --- /dev/null +++ b/uid-safe/tsconfig.json @@ -0,0 +1,19 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fs-extra-promise-es6-tests.ts" + ] +} \ No newline at end of file diff --git a/uid-safe/uid-safe-test.ts b/uid-safe/uid-safe-test.ts new file mode 100644 index 0000000000..6af969ce60 --- /dev/null +++ b/uid-safe/uid-safe-test.ts @@ -0,0 +1,12 @@ +import * as uid from 'uid-safe'; + +uid(18, function (err, string) { + if (err) throw err + // do something with the string +}); + +uid(18).then(function (string) { + // do something with the string +}) + +var string = uid.sync(18); From 07fe82cac5529e424c62fc5da8c1502a43ae8a90 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Tue, 20 Sep 2016 10:49:21 -0500 Subject: [PATCH 189/212] Fixing typos and mistakes in uid-safe typing --- uid-safe/index.d.ts | 7 +++---- uid-safe/tsconfig.json | 2 +- uid-safe/{uid-safe-test.ts => uid-safe-tests.ts} | 0 3 files changed, 4 insertions(+), 5 deletions(-) rename uid-safe/{uid-safe-test.ts => uid-safe-tests.ts} (100%) diff --git a/uid-safe/index.d.ts b/uid-safe/index.d.ts index 9892734e1c..d64c14ad4f 100644 --- a/uid-safe/index.d.ts +++ b/uid-safe/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for co-body +// Type definitions for uid-safe // Project: https://github.com/crypto-utils/uid-safe // Definitions by: Joshua DeVinney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,9 +7,8 @@ declare namespace UID { export interface Generate { - (byteLenth: number, callback: (err: any, str: string) => any): void; - (byteLenth: number): Promise; - (byteLenth: number, callback?: (err: any, str: string) => any): Promise | void; + (byteLength: number, callback: (err: any, str: string) => any): void; + (byteLength: number): Promise; sync(byteLength: number): string; } diff --git a/uid-safe/tsconfig.json b/uid-safe/tsconfig.json index a0bda21ebe..5c29fae11c 100644 --- a/uid-safe/tsconfig.json +++ b/uid-safe/tsconfig.json @@ -14,6 +14,6 @@ }, "files": [ "index.d.ts", - "fs-extra-promise-es6-tests.ts" + "uid-safe-tests.ts" ] } \ No newline at end of file diff --git a/uid-safe/uid-safe-test.ts b/uid-safe/uid-safe-tests.ts similarity index 100% rename from uid-safe/uid-safe-test.ts rename to uid-safe/uid-safe-tests.ts From 38c248d5bc105b8c1f789c23131810fd8702bf6b Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Tue, 20 Sep 2016 11:18:23 -0500 Subject: [PATCH 190/212] Adding uid-safe version number --- uid-safe/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/uid-safe/index.d.ts b/uid-safe/index.d.ts index d64c14ad4f..ee7b13491f 100644 --- a/uid-safe/index.d.ts +++ b/uid-safe/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for uid-safe +// Type definitions for uid-safe v2.1 // Project: https://github.com/crypto-utils/uid-safe // Definitions by: Joshua DeVinney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 785a0a61a9a2d361c93f45ccac1961809aa37585 Mon Sep 17 00:00:00 2001 From: Joshua DeVinney Date: Tue, 20 Sep 2016 11:51:51 -0500 Subject: [PATCH 191/212] Fix failing tests --- fs-extra-promise-es6/fs-extra-promise-es6-tests.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts b/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts index f32065d0e6..12623c54b1 100644 --- a/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts +++ b/fs-extra-promise-es6/fs-extra-promise-es6-tests.ts @@ -217,12 +217,10 @@ readStreeam = fs.createReadStream(path, { flags: str, encoding: str, fd: num, - mode: num, - bufferSize: num + mode: num }); writeStream = fs.createWriteStream(path); writeStream = fs.createWriteStream(path, { flags: str, - encoding: str, - string: str + encoding: str }); From 19425cf32716e63bbbce6a091ec83eaf81a1a3ca Mon Sep 17 00:00:00 2001 From: "Boland, Craig" Date: Tue, 20 Sep 2016 12:22:11 -0500 Subject: [PATCH 192/212] Updated jquery.dataTables.d.ts for 1.10.6. Version release notes: https://cdn.datatables.net/1.10.6/ * Added rows().every() * Added columns().every() * Added cells().every() * Added init() * Expanded method signature when ajax.data is used as a function. --- jquery.dataTables/jquery.dataTables-tests.ts | 196 ++++++++++--------- jquery.dataTables/jquery.dataTables.d.ts | 58 ++++-- 2 files changed, 147 insertions(+), 107 deletions(-) diff --git a/jquery.dataTables/jquery.dataTables-tests.ts b/jquery.dataTables/jquery.dataTables-tests.ts index 4d1d114cb4..6329861604 100644 --- a/jquery.dataTables/jquery.dataTables-tests.ts +++ b/jquery.dataTables/jquery.dataTables-tests.ts @@ -82,21 +82,21 @@ $(document).ready(function () { width: "200px" } col = - { - data: "", - orderData: [10, 11, 20], - render: "", - } + { + data: "", + orderData: [10, 11, 20], + render: "", + } col = - { - data: colDataObject, - render: colRenderObject, - } + { + data: colDataObject, + render: colRenderObject, + } col = - { - data: colDataFunc, - render: colRenderFunc, - } + { + data: colDataFunc, + render: colRenderFunc, + } //#endregion "Column" @@ -124,16 +124,16 @@ $(document).ready(function () { }; colDef = - { - targets: "2", - cellType: "th", - }; + { + targets: "2", + cellType: "th", + }; colDef = - { - targets: ["2", 5], - cellType: "th", - }; + { + targets: ["2", 5], + cellType: "th", + }; //#endregion "ColumnDef" @@ -159,7 +159,7 @@ $(document).ready(function () { var ajaxFunc: DataTables.FunctionAjax = function (data, callback, settings) { }; - var ajaxDataFunc: DataTables.FunctionAjaxData = function (data) { + var ajaxDataFunc: DataTables.FunctionAjaxData = function (data, settings) { return data; }; @@ -229,41 +229,41 @@ $(document).ready(function () { config = - { - ajax: ajaxFunc, - deferLoading: [10, 100], - lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], - order: [0, 'asc'], - orderFixed: [[0, 'asc'], [1, 'asc']], - renderer: { - header: "bootstrap", - pageButton: "jqueryui" - }, - search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, - searchCols: [ - null, - { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, - { "search": "" }, - { "search": "", "smart": true }, - null - ], - }; + { + ajax: ajaxFunc, + deferLoading: [10, 100], + lengthMenu: [[10, 25, 50, -1], [10, 25, 50, "All"]], + order: [0, 'asc'], + orderFixed: [[0, 'asc'], [1, 'asc']], + renderer: { + header: "bootstrap", + pageButton: "jqueryui" + }, + search: { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + searchCols: [ + null, + { "search": "", "smart": true, "regex": false, "caseInsensitive": true }, + { "search": "" }, + { "search": "", "smart": true }, + null + ], + }; config = - { - ajax: { - data: {}, - dataSrc: "", - }, - }; + { + ajax: { + data: {}, + dataSrc: "", + }, + }; config = - { - ajax: { - data: ajaxDataFunc, - dataSrc: function (data) { }, - }, - }; + { + ajax: { + data: ajaxDataFunc, + dataSrc: function (data) { }, + }, + }; //#endregion "Settings" @@ -309,6 +309,8 @@ $(document).ready(function () { draw = dt.draw(true); draw.$(""); + var initSettings = dt.init(); + var off = dt.off("event"); off = dt.off("event", function () { }); off.$(""); @@ -385,11 +387,11 @@ $(document).ready(function () { var select = $('

    @@ -4917,9 +4998,9 @@ declare namespace samchon.protocol.external { * style="max-width: 100%" /> *