From 759b400afea18079474947443a22e40d9b82a6cc Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Tue, 25 Apr 2017 17:44:01 +0200 Subject: [PATCH 0001/1139] Updated i18next extists function definition and allow for additional interpolation options to be passed as TranslationOptions --- types/i18next/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index 958bff12a6..0eb8d64859 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -49,6 +49,8 @@ declare namespace i18n { joinArrays?: string; postProcess?: string | any[]; interpolation?: InterpolationOptions; + //add an indexer to assure that interpolation arguments can be passed + [x: string]: any; } interface Options { @@ -106,7 +108,7 @@ declare namespace i18n { t(key: string, options?: TranslationOptions): string | any | Array; - exists(): boolean; + exists(key, options?: TranslationOptions): boolean; setDefaultNamespace(ns: string): void; From 58b46e0cf1a73f23f47f57028f0779894867be84 Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Tue, 25 Apr 2017 17:47:16 +0200 Subject: [PATCH 0002/1139] Updated 18next test --- types/i18next/i18next-tests.ts | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/types/i18next/i18next-tests.ts b/types/i18next/i18next-tests.ts index 23c67cc742..9230534618 100644 --- a/types/i18next/i18next-tests.ts +++ b/types/i18next/i18next-tests.ts @@ -10,12 +10,14 @@ i18n.init({ resources: { en: { translation: { - helloWorld: 'Hello, world!' + helloWorld: 'Hello, world!', + helloWorldInterpolated: 'Hello, {{name}}!' } }, ru: { translation: { - helloWorld: 'Привет, мир!' + helloWorld: 'Привет, мир!', + helloWorldInterpolated: 'Привет, {{name}}!' } } }, @@ -61,6 +63,14 @@ i18n.t('helloWorld', { count: 10 }); +i18n.t('helloWorldInterpolated', { + defaultValue: 'default', + count: 10, + name: "world" +}); + +I18n.exists("helloWorld"); + const options:i18n.Options = i18n.options; const currentLanguage:string = i18n.language; const userLanguageCodes:string[] = i18n.languages; From 0840c661ed3d0ebca9b3feaabcc569bfd6798f19 Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Tue, 25 Apr 2017 18:04:04 +0200 Subject: [PATCH 0003/1139] i18next fixed typing of exists key parameter --- types/i18next/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index 0eb8d64859..ee06d8d18c 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -108,7 +108,7 @@ declare namespace i18n { t(key: string, options?: TranslationOptions): string | any | Array; - exists(key, options?: TranslationOptions): boolean; + exists(key: string, options?: TranslationOptions): boolean; setDefaultNamespace(ns: string): void; From d91888b1a91c386335f99e6a19c02d00b3b72e2d Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Tue, 25 Apr 2017 18:10:38 +0200 Subject: [PATCH 0004/1139] i18next Fixed test typo --- types/i18next/i18next-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/i18next/i18next-tests.ts b/types/i18next/i18next-tests.ts index 9230534618..e51f2f495c 100644 --- a/types/i18next/i18next-tests.ts +++ b/types/i18next/i18next-tests.ts @@ -69,7 +69,7 @@ i18n.t('helloWorldInterpolated', { name: "world" }); -I18n.exists("helloWorld"); +i18n.exists("helloWorld"); const options:i18n.Options = i18n.options; const currentLanguage:string = i18n.language; From 60fc1660d63c41545115dc38d2b6985f1d58a9e5 Mon Sep 17 00:00:00 2001 From: Matthias Lochbrunner Date: Mon, 8 May 2017 10:01:54 +0200 Subject: [PATCH 0005/1139] Add openStdin() --- types/node/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 67f275c7b6..a410e0e77f 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -370,6 +370,7 @@ declare namespace NodeJS { stdout: Socket; stderr: Socket; stdin: Socket; + openStdin(): Socket; argv: string[]; argv0: string; execArgv: string[]; From a23357923b791eede4eb384bfb985ff09ba61bfc Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Mon, 15 May 2017 18:32:01 +0200 Subject: [PATCH 0006/1139] Added missing definition for sequelize unmanaged transaction with options --- types/sequelize/v3/index.d.ts | 2 +- types/sequelize/v3/sequelize-tests.ts | 1850 +++++++++++++------------ 2 files changed, 932 insertions(+), 920 deletions(-) diff --git a/types/sequelize/v3/index.d.ts b/types/sequelize/v3/index.d.ts index e823a926e2..cd5b43499d 100644 --- a/types/sequelize/v3/index.d.ts +++ b/types/sequelize/v3/index.d.ts @@ -5694,7 +5694,7 @@ declare namespace sequelize { transaction(options: TransactionOptions, autoCallback: (t: Transaction) => Promise): Promise; transaction(autoCallback: (t: Transaction) => Promise): Promise; - transaction(): Promise; + transaction(options?: TransactionOptions): Promise; /** * Close all connections used by this sequelize instance, and free all references so the instance can be diff --git a/types/sequelize/v3/sequelize-tests.ts b/types/sequelize/v3/sequelize-tests.ts index 83c4536a71..4fde0d82b3 100644 --- a/types/sequelize/v3/sequelize-tests.ts +++ b/types/sequelize/v3/sequelize-tests.ts @@ -8,17 +8,17 @@ import Sequelize = require("sequelize"); interface AnyAttributes { }; interface AnyInstance extends Sequelize.Instance { }; -var s = new Sequelize( '' ); +var s = new Sequelize(''); var sequelize = s; var DataTypes = Sequelize; -var User = s.define( 'user', {} ); -var user = User.build(); -var Task = s.define( 'task', {} ); -var Group = s.define( 'group', {} ); -var Comment = s.define( 'comment', {} ); -var Post = s.define( 'post', {} ); -var t : Sequelize.Transaction = null; -s.transaction().then( ( a ) => t = a ); +var User = s.define('user', {}); +var user = User.build(); +var Task = s.define('task', {}); +var Group = s.define('group', {}); +var Comment = s.define('comment', {}); +var Post = s.define('post', {}); +var t: Sequelize.Transaction = null; +s.transaction().then((a) => t = a); // // Generics @@ -26,33 +26,33 @@ s.transaction().then( ( a ) => t = a ); // interface GUserAttributes { - id? : number; - username? : string; + id?: number; + username?: string; } -interface GUserInstance extends Sequelize.Instance {} -var GUser = s.define( 'user', { id: Sequelize.INTEGER, username : Sequelize.STRING }); -GUser.create({ id : 1, username : 'one' }).then( ( guser ) => guser.save() ); +interface GUserInstance extends Sequelize.Instance { } +var GUser = s.define('user', { id: Sequelize.INTEGER, username: Sequelize.STRING }); +GUser.create({ id: 1, username: 'one' }).then((guser) => guser.save()); -var schema : Sequelize.DefineAttributes = { - key : { type : Sequelize.STRING, primaryKey : true }, - value : Sequelize.STRING +var schema: Sequelize.DefineAttributes = { + key: { type: Sequelize.STRING, primaryKey: true }, + value: Sequelize.STRING }; s.define('user', schema); interface GTaskAttributes { - revision? : number; - name? : string; + revision?: number; + name?: string; } interface GTaskInstance extends Sequelize.Instance { - upRevision(): void; + upRevision(): void; } -var GTask = s.define( 'task', { revision : Sequelize.INTEGER, name : Sequelize.STRING }); +var GTask = s.define('task', { revision: Sequelize.INTEGER, name: Sequelize.STRING }); GUser.hasMany(GTask); -GTask.create({ revision: 1, name: 'test' }).then( (gtask) => gtask.upRevision() ); +GTask.create({ revision: 1, name: 'test' }).then((gtask) => gtask.upRevision()); // @@ -62,92 +62,92 @@ GTask.create({ revision: 1, name: 'test' }).then( (gtask) => gtask.upRevision() // https://github.com/sequelize/sequelize/tree/v3.4.1/test/integration/associations // -User.hasOne( Task ); -User.hasOne( Task, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); -User.hasOne( Task, { foreignKey : 'userCoolIdTag' } ); -User.hasOne( Task, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); -Task.hasOne( User, { foreignKey : { name : 'taskId', field : 'task_id' } } ); -User.hasOne( Task, { foreignKey : { name : 'uid', allowNull : false } } ); -User.hasOne( Task, { onDelete : 'cascade' } ); -User.hasOne( Task, { onUpdate : 'cascade' } ); -User.hasOne( Task, { onDelete : 'cascade', hooks : true } ); -User.hasOne( Task, { foreignKey : { allowNull : false } } ); -User.hasOne( Task, { foreignKeyConstraint : true } ); +User.hasOne(Task); +User.hasOne(Task, { foreignKey: 'primaryGroupId', as: 'primaryUsers' }); +User.hasOne(Task, { foreignKey: 'userCoolIdTag' }); +User.hasOne(Task, { foreignKey: 'userId', keyType: Sequelize.STRING, constraints: false }); +Task.hasOne(User, { foreignKey: { name: 'taskId', field: 'task_id' } }); +User.hasOne(Task, { foreignKey: { name: 'uid', allowNull: false } }); +User.hasOne(Task, { onDelete: 'cascade' }); +User.hasOne(Task, { onUpdate: 'cascade' }); +User.hasOne(Task, { onDelete: 'cascade', hooks: true }); +User.hasOne(Task, { foreignKey: { allowNull: false } }); +User.hasOne(Task, { foreignKeyConstraint: true }); -User.belongsTo( Task ); -User.belongsTo( Task, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); -Task.belongsTo( User, { foreignKey : 'user_id' } ); -Task.belongsTo( User, { foreignKey : 'user_name', targetKey : 'username' } ); -User.belongsTo( User, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); -User.belongsTo( Post, { foreignKey : { name : 'AccountId', field : 'account_id' } } ); -Task.belongsTo( User, { foreignKey : { allowNull : false, name : 'uid' } } ); -Task.belongsTo( User, { constraints : false } ); -Task.belongsTo( User, { onDelete : 'cascade' } ); -Task.belongsTo( User, { onUpdate : 'restrict' } ); -User.belongsTo( User, { - as : 'parentBlocks', - foreignKey : 'child', - foreignKeyConstraint : true -} ); +User.belongsTo(Task); +User.belongsTo(Task, { foreignKey: 'primaryGroupId', as: 'primaryUsers' }); +Task.belongsTo(User, { foreignKey: 'user_id' }); +Task.belongsTo(User, { foreignKey: 'user_name', targetKey: 'username' }); +User.belongsTo(User, { foreignKey: 'userId', keyType: Sequelize.STRING, constraints: false }); +User.belongsTo(Post, { foreignKey: { name: 'AccountId', field: 'account_id' } }); +Task.belongsTo(User, { foreignKey: { allowNull: false, name: 'uid' } }); +Task.belongsTo(User, { constraints: false }); +Task.belongsTo(User, { onDelete: 'cascade' }); +Task.belongsTo(User, { onUpdate: 'restrict' }); +User.belongsTo(User, { + as: 'parentBlocks', + foreignKey: 'child', + foreignKeyConstraint: true +}); -User.hasMany( User ); -User.hasMany( User, { foreignKey : 'primaryGroupId', as : 'primaryUsers' } ); -User.hasMany( Task, { foreignKey : 'userId' } ); -User.hasMany( Task, { foreignKey : 'userId', as : 'activeTasks', scope : { active : true } } ); -User.hasMany( Task, { foreignKey : 'userId', keyType : Sequelize.STRING, constraints : false } ); -User.hasMany( Task, { foreignKey : { name : 'uid', allowNull : false } } ); -User.hasMany( Task, { foreignKey : { allowNull : true } } ); -User.hasMany( Task, { as : 'Children' } ); -User.hasMany( Task, { as : { singular : 'task', plural : 'taskz' } } ); -User.hasMany( Task, { constraints : false } ); -User.hasMany( Task, { onDelete : 'cascade' } ); -User.hasMany( Task, { onUpdate : 'cascade' } ); -Post.hasMany( Task, { foreignKey : 'commentable_id', scope : { commentable : 'post' } } ); -User.hasMany( User, { - as : 'childBlocks', - foreignKey : 'parent', - foreignKeyConstraint : true -} ); +User.hasMany(User); +User.hasMany(User, { foreignKey: 'primaryGroupId', as: 'primaryUsers' }); +User.hasMany(Task, { foreignKey: 'userId' }); +User.hasMany(Task, { foreignKey: 'userId', as: 'activeTasks', scope: { active: true } }); +User.hasMany(Task, { foreignKey: 'userId', keyType: Sequelize.STRING, constraints: false }); +User.hasMany(Task, { foreignKey: { name: 'uid', allowNull: false } }); +User.hasMany(Task, { foreignKey: { allowNull: true } }); +User.hasMany(Task, { as: 'Children' }); +User.hasMany(Task, { as: { singular: 'task', plural: 'taskz' } }); +User.hasMany(Task, { constraints: false }); +User.hasMany(Task, { onDelete: 'cascade' }); +User.hasMany(Task, { onUpdate: 'cascade' }); +Post.hasMany(Task, { foreignKey: 'commentable_id', scope: { commentable: 'post' } }); +User.hasMany(User, { + as: 'childBlocks', + foreignKey: 'parent', + foreignKeyConstraint: true +}); -User.belongsToMany( Task, { through : 'UserTasks' } ); -User.belongsToMany( User, { through : Task } ); -User.belongsToMany( Group, { as : 'groups', through : Task, foreignKey : 'id_user' } ); -User.belongsToMany( Task, { as : 'activeTasks', through : Task, scope : { active : true } } ); -User.belongsToMany( Task, { as : 'startedTasks', through : { model : Task, scope : { started : true } } } ); -User.belongsToMany( Group, { through : 'group_members', foreignKey : 'group_id', otherKey : 'member_id' } ); -User.belongsToMany( User, { as : 'Participants', through : User } ); -User.belongsToMany( Group, { through : 'user_places', foreignKey : 'user_id' } ); -User.belongsToMany( Group, { - through : 'user_projects', - as : 'Projects', - foreignKey : { - field : 'user_id', - name : 'userId' +User.belongsToMany(Task, { through: 'UserTasks' }); +User.belongsToMany(User, { through: Task }); +User.belongsToMany(Group, { as: 'groups', through: Task, foreignKey: 'id_user' }); +User.belongsToMany(Task, { as: 'activeTasks', through: Task, scope: { active: true } }); +User.belongsToMany(Task, { as: 'startedTasks', through: { model: Task, scope: { started: true } } }); +User.belongsToMany(Group, { through: 'group_members', foreignKey: 'group_id', otherKey: 'member_id' }); +User.belongsToMany(User, { as: 'Participants', through: User }); +User.belongsToMany(Group, { through: 'user_places', foreignKey: 'user_id' }); +User.belongsToMany(Group, { + through: 'user_projects', + as: 'Projects', + foreignKey: { + field: 'user_id', + name: 'userId' }, - otherKey : { - field : 'project_id', - name : 'projectId' + otherKey: { + field: 'project_id', + name: 'projectId' } -} ); -User.belongsToMany( Task, { onDelete : 'RESTRICT', through : 'tasksusers' } ); -User.belongsToMany( Task, { constraints : false, through : 'tasksusers' } ); -User.belongsToMany( Task, { foreignKey : { name : 'user_id', defaultValue : 42 }, through : 'UserProjects' } ); -User.belongsToMany( Post, { through : User } ); -Post.belongsToMany( User, { as : 'categories', through : User, scope : { type : 'category' } } ); -Post.belongsToMany( User, { as : 'tags', through : User, scope : { type : 'tag' } } ); -Post.belongsToMany( User, { - through : { - model : User, - unique : false, - scope : { - taggable : 'post' +}); +User.belongsToMany(Task, { onDelete: 'RESTRICT', through: 'tasksusers' }); +User.belongsToMany(Task, { constraints: false, through: 'tasksusers' }); +User.belongsToMany(Task, { foreignKey: { name: 'user_id', defaultValue: 42 }, through: 'UserProjects' }); +User.belongsToMany(Post, { through: User }); +Post.belongsToMany(User, { as: 'categories', through: User, scope: { type: 'category' } }); +Post.belongsToMany(User, { as: 'tags', through: User, scope: { type: 'tag' } }); +Post.belongsToMany(User, { + through: { + model: User, + unique: false, + scope: { + taggable: 'post' } }, - foreignKey : 'taggable_id', - constraints : false -} ); -Post.belongsToMany( Post, { through : { model : Post, unique : false }, foreignKey : 'tag_id' } ); -Post.belongsToMany( Post, { as : 'Parents', through : 'Family', foreignKey : 'ChildId', otherKey : 'PersonId' } ); + foreignKey: 'taggable_id', + constraints: false +}); +Post.belongsToMany(Post, { through: { model: Post, unique: false }, foreignKey: 'tag_id' }); +Post.belongsToMany(Post, { as: 'Parents', through: 'Family', foreignKey: 'ChildId', otherKey: 'PersonId' }); // // Mixins @@ -468,19 +468,19 @@ interface CustomerInstance extends Sequelize.Instance, Custo // Sequelize.STRING; -Sequelize.STRING( 1234 ); -Sequelize.STRING( { length : 1234 } ); -Sequelize.STRING( 1234 ).BINARY; +Sequelize.STRING(1234); +Sequelize.STRING({ length: 1234 }); +Sequelize.STRING(1234).BINARY; Sequelize.STRING.BINARY; Sequelize.TEXT; -Sequelize.TEXT( 'tiny' ); -Sequelize.TEXT( { length : 'tiny' } ); -Sequelize.TEXT( 'medium' ); -Sequelize.TEXT( 'long' ); +Sequelize.TEXT('tiny'); +Sequelize.TEXT({ length: 'tiny' }); +Sequelize.TEXT('medium'); +Sequelize.TEXT('long'); Sequelize.CHAR; -Sequelize.CHAR( 12 ); -Sequelize.CHAR( { length : 12 } ); -Sequelize.CHAR( 12 ).BINARY; +Sequelize.CHAR(12); +Sequelize.CHAR({ length: 12 }); +Sequelize.CHAR(12).BINARY; Sequelize.CHAR.BINARY; Sequelize.BOOLEAN; Sequelize.DATE; @@ -492,97 +492,97 @@ Sequelize.NOW; Sequelize.INTEGER; Sequelize.INTEGER.UNSIGNED; Sequelize.INTEGER.UNSIGNED.ZEROFILL; -Sequelize.INTEGER( 11 ); -Sequelize.INTEGER( { length : 11 } ); -Sequelize.INTEGER( 11 ).UNSIGNED; -Sequelize.INTEGER( 11 ).UNSIGNED.ZEROFILL; -Sequelize.INTEGER( 11 ).ZEROFILL; -Sequelize.INTEGER( 11 ).ZEROFILL.UNSIGNED; +Sequelize.INTEGER(11); +Sequelize.INTEGER({ length: 11 }); +Sequelize.INTEGER(11).UNSIGNED; +Sequelize.INTEGER(11).UNSIGNED.ZEROFILL; +Sequelize.INTEGER(11).ZEROFILL; +Sequelize.INTEGER(11).ZEROFILL.UNSIGNED; Sequelize.BIGINT; Sequelize.BIGINT.UNSIGNED; Sequelize.BIGINT.UNSIGNED.ZEROFILL; -Sequelize.BIGINT( 11 ); -Sequelize.BIGINT( { length : 11 } ); -Sequelize.BIGINT( 11 ).UNSIGNED; -Sequelize.BIGINT( 11 ).UNSIGNED.ZEROFILL; -Sequelize.BIGINT( 11 ).ZEROFILL; -Sequelize.BIGINT( 11 ).ZEROFILL.UNSIGNED; +Sequelize.BIGINT(11); +Sequelize.BIGINT({ length: 11 }); +Sequelize.BIGINT(11).UNSIGNED; +Sequelize.BIGINT(11).UNSIGNED.ZEROFILL; +Sequelize.BIGINT(11).ZEROFILL; +Sequelize.BIGINT(11).ZEROFILL.UNSIGNED; Sequelize.REAL.UNSIGNED; -Sequelize.REAL( 11 ); -Sequelize.REAL( { length : 11 } ); -Sequelize.REAL( 11 ).UNSIGNED; -Sequelize.REAL( 11 ).UNSIGNED.ZEROFILL; -Sequelize.REAL( 11 ).ZEROFILL; -Sequelize.REAL( 11 ).ZEROFILL.UNSIGNED; -Sequelize.REAL( 11, 12 ); -Sequelize.REAL( 11, 12 ).UNSIGNED; -Sequelize.REAL( { length : 11, decimals : 12 } ).UNSIGNED; -Sequelize.REAL( 11, 12 ).UNSIGNED.ZEROFILL; -Sequelize.REAL( 11, 12 ).ZEROFILL; -Sequelize.REAL( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.REAL(11); +Sequelize.REAL({ length: 11 }); +Sequelize.REAL(11).UNSIGNED; +Sequelize.REAL(11).UNSIGNED.ZEROFILL; +Sequelize.REAL(11).ZEROFILL; +Sequelize.REAL(11).ZEROFILL.UNSIGNED; +Sequelize.REAL(11, 12); +Sequelize.REAL(11, 12).UNSIGNED; +Sequelize.REAL({ length: 11, decimals: 12 }).UNSIGNED; +Sequelize.REAL(11, 12).UNSIGNED.ZEROFILL; +Sequelize.REAL(11, 12).ZEROFILL; +Sequelize.REAL(11, 12).ZEROFILL.UNSIGNED; Sequelize.DOUBLE; Sequelize.DOUBLE.UNSIGNED; -Sequelize.DOUBLE( 11 ); -Sequelize.DOUBLE( 11 ).UNSIGNED; -Sequelize.DOUBLE( { length : 11 } ).UNSIGNED; -Sequelize.DOUBLE( 11 ).UNSIGNED.ZEROFILL; -Sequelize.DOUBLE( 11 ).ZEROFILL; -Sequelize.DOUBLE( 11 ).ZEROFILL.UNSIGNED; -Sequelize.DOUBLE( 11, 12 ); -Sequelize.DOUBLE( 11, 12 ).UNSIGNED; -Sequelize.DOUBLE( 11, 12 ).UNSIGNED.ZEROFILL; -Sequelize.DOUBLE( 11, 12 ).ZEROFILL; -Sequelize.DOUBLE( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.DOUBLE(11); +Sequelize.DOUBLE(11).UNSIGNED; +Sequelize.DOUBLE({ length: 11 }).UNSIGNED; +Sequelize.DOUBLE(11).UNSIGNED.ZEROFILL; +Sequelize.DOUBLE(11).ZEROFILL; +Sequelize.DOUBLE(11).ZEROFILL.UNSIGNED; +Sequelize.DOUBLE(11, 12); +Sequelize.DOUBLE(11, 12).UNSIGNED; +Sequelize.DOUBLE(11, 12).UNSIGNED.ZEROFILL; +Sequelize.DOUBLE(11, 12).ZEROFILL; +Sequelize.DOUBLE(11, 12).ZEROFILL.UNSIGNED; Sequelize.FLOAT; Sequelize.FLOAT.UNSIGNED; -Sequelize.FLOAT( 11 ); -Sequelize.FLOAT( 11 ).UNSIGNED; -Sequelize.FLOAT( 11 ).UNSIGNED.ZEROFILL; -Sequelize.FLOAT( 11 ).ZEROFILL; -Sequelize.FLOAT( { length : 11 } ).ZEROFILL; -Sequelize.FLOAT( 11 ).ZEROFILL.UNSIGNED; -Sequelize.FLOAT( 11, 12 ); -Sequelize.FLOAT( 11, 12 ).UNSIGNED; -Sequelize.FLOAT( { length : 11, decimals : 12 } ).UNSIGNED; -Sequelize.FLOAT( 11, 12 ).UNSIGNED.ZEROFILL; -Sequelize.FLOAT( 11, 12 ).ZEROFILL; -Sequelize.FLOAT( 11, 12 ).ZEROFILL.UNSIGNED; +Sequelize.FLOAT(11); +Sequelize.FLOAT(11).UNSIGNED; +Sequelize.FLOAT(11).UNSIGNED.ZEROFILL; +Sequelize.FLOAT(11).ZEROFILL; +Sequelize.FLOAT({ length: 11 }).ZEROFILL; +Sequelize.FLOAT(11).ZEROFILL.UNSIGNED; +Sequelize.FLOAT(11, 12); +Sequelize.FLOAT(11, 12).UNSIGNED; +Sequelize.FLOAT({ length: 11, decimals: 12 }).UNSIGNED; +Sequelize.FLOAT(11, 12).UNSIGNED.ZEROFILL; +Sequelize.FLOAT(11, 12).ZEROFILL; +Sequelize.FLOAT(11, 12).ZEROFILL.UNSIGNED; Sequelize.NUMERIC; -Sequelize.NUMERIC( 15, 5 ); +Sequelize.NUMERIC(15, 5); Sequelize.DECIMAL; -Sequelize.DECIMAL( 10, 2 ); -Sequelize.DECIMAL( { precision : 10, scale : 2 } ); -Sequelize.DECIMAL( 10 ); -Sequelize.DECIMAL( { precision : 10 } ); -Sequelize.ENUM( 'value 1', 'value 2' ); +Sequelize.DECIMAL(10, 2); +Sequelize.DECIMAL({ precision: 10, scale: 2 }); +Sequelize.DECIMAL(10); +Sequelize.DECIMAL({ precision: 10 }); +Sequelize.ENUM('value 1', 'value 2'); Sequelize.BLOB; -Sequelize.BLOB( 'tiny' ); -Sequelize.BLOB( 'medium' ); -Sequelize.BLOB( { length : 'medium' } ); -Sequelize.BLOB( 'long' ); -Sequelize.ARRAY( Sequelize.STRING ); -Sequelize.ARRAY( Sequelize.STRING( 100 ) ); -Sequelize.ARRAY( Sequelize.INTEGER ); -Sequelize.ARRAY( Sequelize.HSTORE ); -Sequelize.ARRAY( Sequelize.ARRAY( Sequelize.STRING ) ); -Sequelize.ARRAY( Sequelize.TEXT ); -Sequelize.ARRAY( Sequelize.DATE ); -Sequelize.ARRAY( Sequelize.BOOLEAN ); -Sequelize.ARRAY( Sequelize.DECIMAL ); -Sequelize.ARRAY( Sequelize.DECIMAL( 6 ) ); -Sequelize.ARRAY( Sequelize.DECIMAL( 6, 4 ) ); -Sequelize.ARRAY( Sequelize.DOUBLE ); -Sequelize.ARRAY( Sequelize.REAL ); -Sequelize.ARRAY( Sequelize.JSON ); -Sequelize.ARRAY( Sequelize.JSONB ); +Sequelize.BLOB('tiny'); +Sequelize.BLOB('medium'); +Sequelize.BLOB({ length: 'medium' }); +Sequelize.BLOB('long'); +Sequelize.ARRAY(Sequelize.STRING); +Sequelize.ARRAY(Sequelize.STRING(100)); +Sequelize.ARRAY(Sequelize.INTEGER); +Sequelize.ARRAY(Sequelize.HSTORE); +Sequelize.ARRAY(Sequelize.ARRAY(Sequelize.STRING)); +Sequelize.ARRAY(Sequelize.TEXT); +Sequelize.ARRAY(Sequelize.DATE); +Sequelize.ARRAY(Sequelize.BOOLEAN); +Sequelize.ARRAY(Sequelize.DECIMAL); +Sequelize.ARRAY(Sequelize.DECIMAL(6)); +Sequelize.ARRAY(Sequelize.DECIMAL(6, 4)); +Sequelize.ARRAY(Sequelize.DOUBLE); +Sequelize.ARRAY(Sequelize.REAL); +Sequelize.ARRAY(Sequelize.JSON); +Sequelize.ARRAY(Sequelize.JSONB); Sequelize.GEOMETRY; -Sequelize.GEOMETRY( 'POINT' ); -Sequelize.GEOMETRY( 'LINESTRING' ); -Sequelize.GEOMETRY( 'POLYGON' ); -Sequelize.GEOMETRY( 'POINT', 4326 ); +Sequelize.GEOMETRY('POINT'); +Sequelize.GEOMETRY('LINESTRING'); +Sequelize.GEOMETRY('POLYGON'); +Sequelize.GEOMETRY('POINT', 4326); Sequelize.VIRTUAL; -new Sequelize.VIRTUAL( Sequelize.STRING ); -new Sequelize.VIRTUAL( Sequelize.DATE , ['property1', 'property2']); +new Sequelize.VIRTUAL(Sequelize.STRING); +new Sequelize.VIRTUAL(Sequelize.DATE, ['property1', 'property2']); // // Deferrable @@ -595,9 +595,9 @@ Sequelize.Deferrable.NOT; Sequelize.Deferrable.INITIALLY_IMMEDIATE; Sequelize.Deferrable.INITIALLY_DEFERRED; Sequelize.Deferrable.SET_DEFERRED; -Sequelize.Deferrable.SET_DEFERRED( ['taskTableName_user_id_fkey'] ); +Sequelize.Deferrable.SET_DEFERRED(['taskTableName_user_id_fkey']); Sequelize.Deferrable.SET_IMMEDIATE; -Sequelize.Deferrable.SET_IMMEDIATE( ['taskTableName_user_id_fkey'] ); +Sequelize.Deferrable.SET_IMMEDIATE(['taskTableName_user_id_fkey']); // // Errors @@ -610,23 +610,23 @@ Sequelize.Error; Sequelize.ValidationError; s.Error; s.ValidationError; -new s.ValidationError( 'Validation Error', [ - new s.ValidationErrorItem( ' cannot be null', 'notNull Violation', '', null ) - , new s.ValidationErrorItem( ' cannot be an array or an object', 'string violation', - '', null ) -] ); +new s.ValidationError('Validation Error', [ + new s.ValidationErrorItem(' cannot be null', 'notNull Violation', '', null) + , new s.ValidationErrorItem(' cannot be an array or an object', 'string violation', + '', null) +]); new s.Error(); new s.ValidationError(); -new s.ValidationErrorItem( 'invalid', 'type', 'first_name', null ); -new s.ValidationErrorItem( 'invalid', 'type', 'last_name', null ); -new s.DatabaseError( new Error( 'original database error message' ) ); -new s.ConnectionError( new Error( 'original connection error message' ) ); -new s.ConnectionRefusedError( new Error( 'original connection error message' ) ); -new s.AccessDeniedError( new Error( 'original connection error message' ) ); -new s.HostNotFoundError( new Error( 'original connection error message' ) ); -new s.HostNotReachableError( new Error( 'original connection error message' ) ); -new s.InvalidConnectionError( new Error( 'original connection error message' ) ); -new s.ConnectionTimedOutError( new Error( 'original connection error message' ) ); +new s.ValidationErrorItem('invalid', 'type', 'first_name', null); +new s.ValidationErrorItem('invalid', 'type', 'last_name', null); +new s.DatabaseError(new Error('original database error message')); +new s.ConnectionError(new Error('original connection error message')); +new s.ConnectionRefusedError(new Error('original connection error message')); +new s.AccessDeniedError(new Error('original connection error message')); +new s.HostNotFoundError(new Error('original connection error message')); +new s.HostNotReachableError(new Error('original connection error message')); +new s.InvalidConnectionError(new Error('original connection error message')); +new s.ConnectionTimedOutError(new Error('original connection error message')); // // Hooks @@ -635,111 +635,111 @@ new s.ConnectionTimedOutError( new Error( 'original connection error message' ) // https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/hooks.test.js // -User.addHook( 'afterCreate', function( instance : Sequelize.Instance, options : Object, next : Function ) { next(); } ); -User.addHook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function) { next(); } ); -s.addHook( 'beforeInit', function( config : Object, options : Object ) { } ); -User.hook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function) { next(); } ); -User.hook( 'afterCreate', 'myHook', function( instance : Sequelize.Instance, options : Object, next : Function ) { next(); } ); +User.addHook('afterCreate', function (instance: Sequelize.Instance, options: Object, next: Function) { next(); }); +User.addHook('afterCreate', 'myHook', function (instance: Sequelize.Instance, options: Object, next: Function) { next(); }); +s.addHook('beforeInit', function (config: Object, options: Object) { }); +User.hook('afterCreate', 'myHook', function (instance: Sequelize.Instance, options: Object, next: Function) { next(); }); +User.hook('afterCreate', 'myHook', function (instance: Sequelize.Instance, options: Object, next: Function) { next(); }); -User.removeHook( 'afterCreate', 'myHook' ); +User.removeHook('afterCreate', 'myHook'); -User.hasHook( 'afterCreate' ); -User.hasHooks( 'afterCreate' ); +User.hasHook('afterCreate'); +User.hasHooks('afterCreate'); -User.beforeValidate( function( user, options ) { user.isNewRecord; } ); -User.beforeValidate( 'myHook', function( user, options ) { user.isNewRecord; } ); +User.beforeValidate(function (user, options) { user.isNewRecord; }); +User.beforeValidate('myHook', function (user, options) { user.isNewRecord; }); -User.afterValidate( function( user, options ) { user.isNewRecord; } ); -User.afterValidate( 'myHook', function( user, options ) { user.isNewRecord; } ); +User.afterValidate(function (user, options) { user.isNewRecord; }); +User.afterValidate('myHook', function (user, options) { user.isNewRecord; }); -User.beforeCreate( function( user, options ) { user.isNewRecord; } ); -User.beforeCreate( function( user, options, fn ) {fn();} ); -User.beforeCreate( 'myHook', function( user, options ) { user.isNewRecord; } ); +User.beforeCreate(function (user, options) { user.isNewRecord; }); +User.beforeCreate(function (user, options, fn) { fn(); }); +User.beforeCreate('myHook', function (user, options) { user.isNewRecord; }); -User.afterCreate( function( user, options ) { user.isNewRecord; } ); -User.afterCreate( function( user, options, fn ) {fn();} ); -User.afterCreate( 'myHook', function( user, options ) { user.isNewRecord; } ); +User.afterCreate(function (user, options) { user.isNewRecord; }); +User.afterCreate(function (user, options, fn) { fn(); }); +User.afterCreate('myHook', function (user, options) { user.isNewRecord; }); -User.beforeDestroy( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.beforeDestroy( function( user, options, fn ) {fn();} ); -User.beforeDestroy( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); -User.beforeDelete( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.beforeDelete( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.beforeDestroy(function (user, options) { throw new Error('Whoops!'); }); +User.beforeDestroy(function (user, options, fn) { fn(); }); +User.beforeDestroy('myHook', function (user, options) { throw new Error('Whoops!'); }); +User.beforeDelete(function (user, options) { throw new Error('Whoops!'); }); +User.beforeDelete('myHook', function (user, options) { throw new Error('Whoops!'); }); -User.afterDestroy( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.afterDestroy( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); -User.afterDestroy( function( user, options, fn ) {fn();} ); -User.afterDelete( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.afterDelete( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterDestroy(function (user, options) { throw new Error('Whoops!'); }); +User.afterDestroy('myHook', function (user, options) { throw new Error('Whoops!'); }); +User.afterDestroy(function (user, options, fn) { fn(); }); +User.afterDelete(function (user, options) { throw new Error('Whoops!'); }); +User.afterDelete('myHook', function (user, options) { throw new Error('Whoops!'); }); -User.beforeUpdate( function( user, options ) {throw new Error( 'Whoops!' ); } ); -User.beforeUpdate( 'myHook', function( user, options ) {throw new Error( 'Whoops!' ); } ); +User.beforeUpdate(function (user, options) { throw new Error('Whoops!'); }); +User.beforeUpdate('myHook', function (user, options) { throw new Error('Whoops!'); }); -User.afterUpdate( function( user, options ) {throw new Error( 'Whoops!' );} ); -User.afterUpdate( 'myHook', function( user, options ) {throw new Error( 'Whoops!' );} ); +User.afterUpdate(function (user, options) { throw new Error('Whoops!'); }); +User.afterUpdate('myHook', function (user, options) { throw new Error('Whoops!'); }); -User.beforeBulkCreate( function( daos, options ) { throw new Error( 'Whoops!' );} ); -User.beforeBulkCreate( 'myHook', function( daos, options ) { throw new Error( 'Whoops!' );} ); -User.beforeBulkCreate( function( daos, options, fn ) {fn();} ); +User.beforeBulkCreate(function (daos, options) { throw new Error('Whoops!'); }); +User.beforeBulkCreate('myHook', function (daos, options) { throw new Error('Whoops!'); }); +User.beforeBulkCreate(function (daos, options, fn) { fn(); }); -User.afterBulkCreate( function( daos, options ) {throw new Error( 'Whoops!' ); } ); -User.afterBulkCreate( 'myHook', function( daos, options ) {throw new Error( 'Whoops!' ); } ); -User.afterBulkCreate( function( daos, options, fn ) {fn();} ); +User.afterBulkCreate(function (daos, options) { throw new Error('Whoops!'); }); +User.afterBulkCreate('myHook', function (daos, options) { throw new Error('Whoops!'); }); +User.afterBulkCreate(function (daos, options, fn) { fn(); }); -User.beforeBulkDestroy( function( options ) {throw new Error( 'Whoops!' );} ); -User.beforeBulkDestroy( function( options, fn ) {fn();} ); -User.beforeBulkDestroy( 'myHook', function( options, fn ) {fn();} ); -User.beforeBulkDelete( 'myHook', function( options, fn ) {fn();} ); +User.beforeBulkDestroy(function (options) { throw new Error('Whoops!'); }); +User.beforeBulkDestroy(function (options, fn) { fn(); }); +User.beforeBulkDestroy('myHook', function (options, fn) { fn(); }); +User.beforeBulkDelete('myHook', function (options, fn) { fn(); }); -User.afterBulkDestroy( function( options ) {throw new Error( 'Whoops!' );} ); -User.afterBulkDestroy( function( options, fn ) {fn();} ); -User.afterBulkDestroy( 'myHook', function( options, fn ) {fn();} ); -User.afterBulkDelete( 'myHook', function( options, fn ) {fn();} ); +User.afterBulkDestroy(function (options) { throw new Error('Whoops!'); }); +User.afterBulkDestroy(function (options, fn) { fn(); }); +User.afterBulkDestroy('myHook', function (options, fn) { fn(); }); +User.afterBulkDelete('myHook', function (options, fn) { fn(); }); -User.beforeBulkUpdate( function( options ) {throw new Error( 'Whoops!' );} ); -User.beforeBulkUpdate( 'myHook', function( options ) {throw new Error( 'Whoops!' );} ); +User.beforeBulkUpdate(function (options) { throw new Error('Whoops!'); }); +User.beforeBulkUpdate('myHook', function (options) { throw new Error('Whoops!'); }); -User.afterBulkUpdate( function( options ) {throw new Error( 'Whoops!' );} ); -User.afterBulkUpdate( 'myHook', function( options ) {throw new Error( 'Whoops!' );} ); +User.afterBulkUpdate(function (options) { throw new Error('Whoops!'); }); +User.afterBulkUpdate('myHook', function (options) { throw new Error('Whoops!'); }); -User.beforeFind( function( options ) {} ); -User.beforeFind( 'myHook', function( options ) {} ); +User.beforeFind(function (options) { }); +User.beforeFind('myHook', function (options) { }); -User.beforeFindAfterExpandIncludeAll( function( options ) {} ); -User.beforeFindAfterExpandIncludeAll( 'myHook', function( options ) {} ); +User.beforeFindAfterExpandIncludeAll(function (options) { }); +User.beforeFindAfterExpandIncludeAll('myHook', function (options) { }); -User.beforeFindAfterOptions( function( options ) {} ); -User.beforeFindAfterOptions( 'myHook', function( options ) {} ); +User.beforeFindAfterOptions(function (options) { }); +User.beforeFindAfterOptions('myHook', function (options) { }); -User.afterFind( function( user ) {} ); -User.afterFind( 'myHook', function( user ) {} ); +User.afterFind(function (user) { }); +User.afterFind('myHook', function (user) { }); -s.beforeDefine( function( attributes, options ) {} ); -s.beforeDefine( 'myHook', function( attributes, options ) {} ); +s.beforeDefine(function (attributes, options) { }); +s.beforeDefine('myHook', function (attributes, options) { }); -s.afterDefine( function( model ) {} ); -s.afterDefine( 'myHook', function( model ) {} ); +s.afterDefine(function (model) { }); +s.afterDefine('myHook', function (model) { }); -s.beforeInit( function( config, options ) {} ); -s.beforeInit( 'myHook', function( attributes, options ) {} ); +s.beforeInit(function (config, options) { }); +s.beforeInit('myHook', function (attributes, options) { }); -s.afterInit( function( model ) {} ); -s.afterInit( 'myHook', function( model ) {} ); +s.afterInit(function (model) { }); +s.afterInit('myHook', function (model) { }); -s.define( 'User', {}, { - hooks : { - beforeValidate : function( user, options, fn ) {fn();}, - afterValidate : function( user, options, fn ) {fn();}, - beforeCreate : function( user, options, fn ) {fn();}, - afterCreate : function( user, options, fn ) {fn();}, - beforeDestroy : function( user, options, fn ) {fn();}, - afterDestroy : function( user, options, fn ) {fn();}, - beforeDelete : function( user, options, fn ) {fn();}, - afterDelete : function( user, options, fn ) {fn();}, - beforeUpdate : function( user, options, fn ) {fn();}, - afterUpdate : function( user, options, fn ) {fn();} +s.define('User', {}, { + hooks: { + beforeValidate: function (user, options, fn) { fn(); }, + afterValidate: function (user, options, fn) { fn(); }, + beforeCreate: function (user, options, fn) { fn(); }, + afterCreate: function (user, options, fn) { fn(); }, + beforeDestroy: function (user, options, fn) { fn(); }, + afterDestroy: function (user, options, fn) { fn(); }, + beforeDelete: function (user, options, fn) { fn(); }, + afterDelete: function (user, options, fn) { fn(); }, + beforeUpdate: function (user, options, fn) { fn(); }, + afterUpdate: function (user, options, fn) { fn(); } } -} ); +}); // // Instance @@ -752,71 +752,71 @@ s.define( 'User', {}, { user.isNewRecord = true; -user.Model.build( { a : 'b' } ); +user.Model.build({ a: 'b' }); user.sequelize.close(); user.where(); -user.getDataValue( '' ); +user.getDataValue(''); -user.setDataValue( '', '' ); -user.setDataValue( '', {} ); +user.setDataValue('', ''); +user.setDataValue('', {}); -user.get( 'aNumber', { plain : true, clone : true } ); +user.get('aNumber', { plain: true, clone: true }); user.get(); -user.set( 'email', 'B' ); -user.set( { name : 'B', bio : 'B' } ).save().then( ( p ) => p ); -user.set( 'birthdate', new Date() ); -user.set( { id : 1, t : 'c', q : [{ id : 1, n : 'a' }, { id : 2, n : 'Beta' }], u : { id : 1, f : 'b', l : 'd' } } ); -user.setAttributes( { a : 3 } ); -user.setAttributes( { id : 1, a : 'n', c : [{ id : 1 }, { id : 2, f : 'e' }], x : { id : 1, f : 'h', l : 'd' } } ); +user.set('email', 'B'); +user.set({ name: 'B', bio: 'B' }).save().then((p) => p); +user.set('birthdate', new Date()); +user.set({ id: 1, t: 'c', q: [{ id: 1, n: 'a' }, { id: 2, n: 'Beta' }], u: { id: 1, f: 'b', l: 'd' } }); +user.setAttributes({ a: 3 }); +user.setAttributes({ id: 1, a: 'n', c: [{ id: 1 }, { id: 2, f: 'e' }], x: { id: 1, f: 'h', l: 'd' } }); -user.changed( 'name' ); +user.changed('name'); user.changed(); -user.previous( 'name' ); +user.previous('name'); -user.save().then( ( p ) => p ); -user.save( { fields : ['a'] } ).then( ( p ) => p ); -user.save( { transaction : t } ); +user.save().then((p) => p); +user.save({ fields: ['a'] }).then((p) => p); +user.save({ transaction: t }); user.reload(); -user.reload( { attributes : ['bNumber'] } ); -user.reload( { transaction : t } ); +user.reload({ attributes: ['bNumber'] }); +user.reload({ transaction: t }); user.validate(); -user.update( { bNumber : 2 }, { where : { id : 1 } } ); -user.update( { username : 'userman' }, { silent : true } ); -user.update( { username : 'yolo' }, { logging : function() { } } ); -user.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); -user.updateAttributes( { a : 3 } ).then( ( p ) => p ); -user.updateAttributes( { a : 3 }, { fields : ['secretValue'], logging : function( ) {} } ); +user.update({ bNumber: 2 }, { where: { id: 1 } }); +user.update({ username: 'userman' }, { silent: true }); +user.update({ username: 'yolo' }, { logging: function () { } }); +user.update({ username: 'bar' }, { where: { username: 'foo' }, transaction: t }).then((p) => p); +user.updateAttributes({ a: 3 }).then((p) => p); +user.updateAttributes({ a: 3 }, { fields: ['secretValue'], logging: function () { } }); -user.destroy().then( ( p ) => p ); -user.destroy( { logging : function( ) {} } ); -user.destroy( { transaction : t } ).then( ( p ) => p ); +user.destroy().then((p) => p); +user.destroy({ logging: function () { } }); +user.destroy({ transaction: t }).then((p) => p); user.restore(); -user.increment( 'number', { by : 2 } ).then( ( p ) => p ); -user.increment( ['aNumber'], { by : 2, where : { bNumber : 1 } } ).then( ( p ) => p ); -user.increment( ['aNumber'], { by : 2 } ).then( ( p ) => p ); -user.increment( 'aNumber' ).then( ( p ) => p ); -user.increment( { 'aNumber' : 1, 'bNumber' : 2 } ).then( ( p ) => p ); -user.increment( 'number', { by : 2, transaction : t } ).then( ( p ) => p ); +user.increment('number', { by: 2 }).then((p) => p); +user.increment(['aNumber'], { by: 2, where: { bNumber: 1 } }).then((p) => p); +user.increment(['aNumber'], { by: 2 }).then((p) => p); +user.increment('aNumber').then((p) => p); +user.increment({ 'aNumber': 1, 'bNumber': 2 }).then((p) => p); +user.increment('number', { by: 2, transaction: t }).then((p) => p); -user.decrement( 'aNumber', { by : 2 } ).then( ( p ) => p ); -user.decrement( ['aNumber'], { by : 2 } ).then( ( p ) => p ); -user.decrement( 'aNumber' ).then( ( p ) => p ); -user.decrement( { 'aNumber' : 1, 'bNumber' : 2 } ).then( ( p ) => p ); -user.decrement( 'number', { by : 2, transaction : t } ).then( ( p ) => p ); +user.decrement('aNumber', { by: 2 }).then((p) => p); +user.decrement(['aNumber'], { by: 2 }).then((p) => p); +user.decrement('aNumber').then((p) => p); +user.decrement({ 'aNumber': 1, 'bNumber': 2 }).then((p) => p); +user.decrement('number', { by: 2, transaction: t }).then((p) => p); -user.equals( user ); +user.equals(user); -user.equalsOneOf( [user, user] ); +user.equalsOneOf([user, user]); user.toJSON(); @@ -827,215 +827,215 @@ user.toJSON(); // https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/model.test.js // -User.removeAttribute( 'id' ); +User.removeAttribute('id'); -User.sync( { force : true } ).then( function() { } ); -User.sync( { force : true, logging : function() { } } ); +User.sync({ force: true }).then(function () { }); +User.sync({ force: true, logging: function () { } }); User.drop(); -User.schema( 'special' ); -User.schema( 'special' ).create( { age : 3 }, { logging : function( ) {} } ); +User.schema('special'); +User.schema('special').create({ age: 3 }, { logging: function () { } }); User.getTableName(); -User.addScope('lowAccess', { where : { parent_id : 2 } }); -User.addScope('lowAccess', { where : { parent_id : 2 } }, { override: true }); -User.addScope('lowAccessWithParam', function(id: number) { - return { where : { parent_id : id } } -} ); +User.addScope('lowAccess', { where: { parent_id: 2 } }); +User.addScope('lowAccess', { where: { parent_id: 2 } }, { override: true }); +User.addScope('lowAccessWithParam', function (id: number) { + return { where: { parent_id: id } } +}); -User.scope( 'lowAccess' ).count(); -User.scope( { where : { parent_id : 2 } } ); -User.scope( [ 'lowAccess', { method: ['lowAccessWithParam', 2] }, { where : { parent_id : 2 } } ] ) +User.scope('lowAccess').count(); +User.scope({ where: { parent_id: 2 } }); +User.scope(['lowAccess', { method: ['lowAccessWithParam', 2] }, { where: { parent_id: 2 } }]) User.findAll(); -User.findAll( { where : { data : { employment : null } } } ); -User.findAll( { where : { aNumber : { gte : 10 } } } ).then( ( u ) => u[0].isNewRecord ); -User.findAll( { where : [s.or( { u : 'b' }, { u : ';' } ), s.and( { id : [1, 2] } )], include : [{ model : User }] } ); -User.findAll( { - where : [s.or( { a : 'b' }, { c : 'd' } ), s.and( { id : [1, 2, 3] }, - s.or( { deletedAt : null }, { deletedAt : { gt : new Date( 0 ) } } ) )] -} ); -User.findAll( { paranoid : false, where : [' IS NOT NULL '], include : [{ model : User }] } ); -User.findAll( { transaction : t } ); -User.findAll( { where : { data : { name : { last : 's' }, employment : { $ne : 'a' } } }, order : [['id', 'ASC']] } ); -User.findAll( { where : { username : ['boo', 'boo2'] } } ); -User.findAll( { where : { username : { like : '%2' } } } ); -User.findAll( { where : { theDate : { '..' : ['2013-01-02', '2013-01-11'] } } } ); -User.findAll( { where : { intVal : { '!..' : [8, 10] } } } ); -User.findAll( { where : { theDate : { between : ['2013-01-02', '2013-01-11'] } } } ); -User.findAll( { where : { theDate : { between : ['2013-01-02', '2013-01-11'] }, intVal : 10 } } ); -User.findAll( { where : { theDate : { between : ['2012-12-10', '2013-01-02'] } } } ); -User.findAll( { where : { theDate : { nbetween : ['2013-01-04', '2013-01-20'] } } } ); -User.findAll( { order : [s.col( 'name' )] } ); -User.findAll( { order : [['theDate', 'DESC']] } ); -User.findAll( { include : [User], order : [[User, User, 'numYears', 'c']] } ); -User.findAll( { include : [{ model : User, include : [User, { model : User, as : 'residents' }] }] } ); -User.findAll( { order : [[User, { model : User, as : 'residents' }, 'lastName', 'c']] } ); -User.findAll( { include : [User], order : [[User, 'name', 'c']] } ); -User.findAll( { include : [{ all : 'HasMany', attributes : ['name'] }] } ); -User.findAll( { include : [{ all : true }, { model : User, attributes : ['id'] }] } ); -User.findAll( { include : [{ all : 'BelongsTo' }] } ); -User.findAll( { include : [{ all : true }] } ); -User.findAll( { where : { username : 'barfooz' }, raw : true } ); -User.findAll( { where : { name : 'worker' }, include : [{ model : User, as : 'ToDos' }] } ); -User.findAll( { where : { user_id : 1 }, attributes : ['a', 'b'], include : [{ model : User, attributes : ['c'] }] } ); -User.findAll( { order : s.literal( 'email =' ) } ); -User.findAll( { order : [s.literal( 'email = ' + s.escape( 'test@sequelizejs.com' ) )] } ); -User.findAll( { order : [['id', ';DELETE YOLO INJECTIONS']] } ); -User.findAll( { include : [User], order : [[User, 'id', ';DELETE YOLO INJECTIONS']] } ); -User.findAll( { include : [User], order : [['id', 'ASC NULLS LAST'], [User, 'id', 'DESC NULLS FIRST']] } ); -User.findAll( { include : [{ model : User, where : { title : 'DoDat' }, include : [{ model : User }] }] } ); -User.findAll( { attributes: ['username', 'data']}); -User.findAll( { attributes: {include: ['username', 'data']} }); -User.findAll( { attributes: [['username', 'user_name'], ['email', 'user_email']] }); -User.findAll( { attributes: [s.fn('count', Sequelize.col('*'))] }); -User.findAll( { attributes: [[s.fn('count', Sequelize.col('*')), 'count']] }); -User.findAll( { attributes: [[s.fn('count', Sequelize.col('*')), 'count']], group: ['sex'] }); -User.findAll( { attributes: [s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER')] }); -User.findAll( { attributes: [[s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER'), 'count']] }); +User.findAll({ where: { data: { employment: null } } }); +User.findAll({ where: { aNumber: { gte: 10 } } }).then((u) => u[0].isNewRecord); +User.findAll({ where: [s.or({ u: 'b' }, { u: ';' }), s.and({ id: [1, 2] })], include: [{ model: User }] }); +User.findAll({ + where: [s.or({ a: 'b' }, { c: 'd' }), s.and({ id: [1, 2, 3] }, + s.or({ deletedAt: null }, { deletedAt: { gt: new Date(0) } }))] +}); +User.findAll({ paranoid: false, where: [' IS NOT NULL '], include: [{ model: User }] }); +User.findAll({ transaction: t }); +User.findAll({ where: { data: { name: { last: 's' }, employment: { $ne: 'a' } } }, order: [['id', 'ASC']] }); +User.findAll({ where: { username: ['boo', 'boo2'] } }); +User.findAll({ where: { username: { like: '%2' } } }); +User.findAll({ where: { theDate: { '..': ['2013-01-02', '2013-01-11'] } } }); +User.findAll({ where: { intVal: { '!..': [8, 10] } } }); +User.findAll({ where: { theDate: { between: ['2013-01-02', '2013-01-11'] } } }); +User.findAll({ where: { theDate: { between: ['2013-01-02', '2013-01-11'] }, intVal: 10 } }); +User.findAll({ where: { theDate: { between: ['2012-12-10', '2013-01-02'] } } }); +User.findAll({ where: { theDate: { nbetween: ['2013-01-04', '2013-01-20'] } } }); +User.findAll({ order: [s.col('name')] }); +User.findAll({ order: [['theDate', 'DESC']] }); +User.findAll({ include: [User], order: [[User, User, 'numYears', 'c']] }); +User.findAll({ include: [{ model: User, include: [User, { model: User, as: 'residents' }] }] }); +User.findAll({ order: [[User, { model: User, as: 'residents' }, 'lastName', 'c']] }); +User.findAll({ include: [User], order: [[User, 'name', 'c']] }); +User.findAll({ include: [{ all: 'HasMany', attributes: ['name'] }] }); +User.findAll({ include: [{ all: true }, { model: User, attributes: ['id'] }] }); +User.findAll({ include: [{ all: 'BelongsTo' }] }); +User.findAll({ include: [{ all: true }] }); +User.findAll({ where: { username: 'barfooz' }, raw: true }); +User.findAll({ where: { name: 'worker' }, include: [{ model: User, as: 'ToDos' }] }); +User.findAll({ where: { user_id: 1 }, attributes: ['a', 'b'], include: [{ model: User, attributes: ['c'] }] }); +User.findAll({ order: s.literal('email =') }); +User.findAll({ order: [s.literal('email = ' + s.escape('test@sequelizejs.com'))] }); +User.findAll({ order: [['id', ';DELETE YOLO INJECTIONS']] }); +User.findAll({ include: [User], order: [[User, 'id', ';DELETE YOLO INJECTIONS']] }); +User.findAll({ include: [User], order: [['id', 'ASC NULLS LAST'], [User, 'id', 'DESC NULLS FIRST']] }); +User.findAll({ include: [{ model: User, where: { title: 'DoDat' }, include: [{ model: User }] }] }); +User.findAll({ attributes: ['username', 'data'] }); +User.findAll({ attributes: { include: ['username', 'data'] } }); +User.findAll({ attributes: [['username', 'user_name'], ['email', 'user_email']] }); +User.findAll({ attributes: [s.fn('count', Sequelize.col('*'))] }); +User.findAll({ attributes: [[s.fn('count', Sequelize.col('*')), 'count']] }); +User.findAll({ attributes: [[s.fn('count', Sequelize.col('*')), 'count']], group: ['sex'] }); +User.findAll({ attributes: [s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER')] }); +User.findAll({ attributes: [[s.cast(s.fn('count', Sequelize.col('*')), 'INTEGER'), 'count']] }); -User.findById( 'a string' ); +User.findById('a string'); -User.findOne( { where : { username : 'foo' } } ); -User.findOne( { where : { id : 1 }, attributes : ['id', ['username', 'name']] } ); -User.findOne( { where : { id : 1 }, attributes : ['id'] } ); -User.findOne( { where : { username : 'foo' }, logging : function( ) { } } ); -User.findOne( { limit : 10 } ); -User.findOne( { include : [1] } ); -User.findOne( { where : { title : 'homework' }, include : [User] } ); -User.findOne( { where : { name : 'environment' }, include : [{ model : User, as : 'PrivateDomain' }] } ); -User.findOne( { where : { username : 'foo' }, transaction : t } ).then( ( p ) => p ); -User.findOne( { include : [User] } ); -User.findOne( { include : [{ model : User, as : 'Work' }] } ); -User.findOne( { where : { name : 'worker' }, include : [{ model : User, as : 'ToDo' }] } ); -User.findOne( { include : [{ model : User, as : 'ToDo' }, { model : User, as : 'DoTo' }] } ); -User.findOne( { where : { name : 'worker' }, include : [User] } ); -User.findOne( { where : { name : 'Boris' }, include : [User, { model : User, as : 'Photos' }] } ); -User.findOne( { where : { username : 'someone' }, include : [User] } ); -User.findOne( { where : { username : 'barfooz' }, raw : true } ); +User.findOne({ where: { username: 'foo' } }); +User.findOne({ where: { id: 1 }, attributes: ['id', ['username', 'name']] }); +User.findOne({ where: { id: 1 }, attributes: ['id'] }); +User.findOne({ where: { username: 'foo' }, logging: function () { } }); +User.findOne({ limit: 10 }); +User.findOne({ include: [1] }); +User.findOne({ where: { title: 'homework' }, include: [User] }); +User.findOne({ where: { name: 'environment' }, include: [{ model: User, as: 'PrivateDomain' }] }); +User.findOne({ where: { username: 'foo' }, transaction: t }).then((p) => p); +User.findOne({ include: [User] }); +User.findOne({ include: [{ model: User, as: 'Work' }] }); +User.findOne({ where: { name: 'worker' }, include: [{ model: User, as: 'ToDo' }] }); +User.findOne({ include: [{ model: User, as: 'ToDo' }, { model: User, as: 'DoTo' }] }); +User.findOne({ where: { name: 'worker' }, include: [User] }); +User.findOne({ where: { name: 'Boris' }, include: [User, { model: User, as: 'Photos' }] }); +User.findOne({ where: { username: 'someone' }, include: [User] }); +User.findOne({ where: { username: 'barfooz' }, raw: true }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 User.findOne( { updatedAt : { ne : null } } ); */ -User.find( { where : { intVal : { gt : 5 } } } ); -User.find( { where : { intVal : { lte : 5 } } } ); +User.find({ where: { intVal: { gt: 5 } } }); +User.find({ where: { intVal: { lte: 5 } } }); User.count(); -User.count( { transaction : t } ); -User.count().then( function( c ) { c.toFixed(); } ); -User.count( { where : ["username LIKE '%us%'"] } ); -User.count( { include : [{ model : User, required : false }] } ); -User.count( { distinct : true, include : [{ model : User, required : false }] } ); -User.count( { attributes : ['data'], group : ['data'] } ); -User.count( { where : { access_level : { gt : 5 } } } ); +User.count({ transaction: t }); +User.count().then(function (c) { c.toFixed(); }); +User.count({ where: ["username LIKE '%us%'"] }); +User.count({ include: [{ model: User, required: false }] }); +User.count({ distinct: true, include: [{ model: User, required: false }] }); +User.count({ attributes: ['data'], group: ['data'] }); +User.count({ where: { access_level: { gt: 5 } } }); -User.findAndCountAll( { offset : 5, limit : 1, include : [User, { model : User, as : 'a' }] } ); +User.findAndCountAll({ offset: 5, limit: 1, include: [User, { model: User, as: 'a' }] }); -User.max( 'age', { transaction : t } ); -User.max( 'age' ); -User.max( 'age', { logging : function( ) { } } ); +User.max('age', { transaction: t }); +User.max('age'); +User.max('age', { logging: function () { } }); -User.min( 'age', { transaction : t } ); -User.min( 'age' ); -User.min( 'age', { logging : function( ) { } } ); +User.min('age', { transaction: t }); +User.min('age'); +User.min('age', { logging: function () { } }); -User.sum( 'order' ); -User.sum( 'age', { where : { 'gender' : 'male' } } ); -User.sum( 'age', { logging : function( ) { } } ); +User.sum('order'); +User.sum('age', { where: { 'gender': 'male' } }); +User.sum('age', { logging: function () { } }); -User.build( { username : 'John Wayne' } ).save(); +User.build({ username: 'John Wayne' }).save(); User.build(); -User.build( { id : 1, T : [{ n : 'a' }, { id : 2 }], A : { id : 1, n : 'a', c : 'a' } }, { include : [User, Task] } ); -User.build( { id : 1, }, { include : [{ model : User, as : 'followers' }, { model : Task, as : 'categories' }] } ); +User.build({ id: 1, T: [{ n: 'a' }, { id: 2 }], A: { id: 1, n: 'a', c: 'a' } }, { include: [User, Task] }); +User.build({ id: 1, }, { include: [{ model: User, as: 'followers' }, { model: Task, as: 'categories' }] }); User.create(); -User.create( { createdAt : 1, updatedAt : 2 }, { silent : true } ); -User.create( {}, { returning : true } ); -User.create( { intVal : s.literal( 'CAST(1-2 AS' ) } ); -User.create( { secretValue : s.fn( 'upper', 'sequelize' ) } ); -User.create( { myvals : [1, 2, 3, 4], mystr : ['One', 'Two', 'Three', 'Four'] } ); -User.create( { name : 'Fluffy Bunny', smth : 'else' }, { logging : function( ) {} } ); -User.create( {}, { fields : [] } ); -User.create( { name : 'Yolo Bear', email : 'yolo@bear.com' }, { fields : ['name'] } ); -User.create( { title : 'Chair', User : { first_name : 'Mick', last_name : 'Broadstone' } }, { include : [User] } ); -User.create( { title : 'Chair', creator : { first_name : 'Matt', last_name : 'Hansen' } }, { include : [User] } ); -User.create( { id : 1, title : 'e', Tags : [{ id : 1, name : 'c' }, { id : 2, name : 'd' }] }, { include : [User] } ); -User.create( { id : 'My own ID!' } ).then( ( i ) => i.isNewRecord ); +User.create({ createdAt: 1, updatedAt: 2 }, { silent: true }); +User.create({}, { returning: true }); +User.create({ intVal: s.literal('CAST(1-2 AS') }); +User.create({ secretValue: s.fn('upper', 'sequelize') }); +User.create({ myvals: [1, 2, 3, 4], mystr: ['One', 'Two', 'Three', 'Four'] }); +User.create({ name: 'Fluffy Bunny', smth: 'else' }, { logging: function () { } }); +User.create({}, { fields: [] }); +User.create({ name: 'Yolo Bear', email: 'yolo@bear.com' }, { fields: ['name'] }); +User.create({ title: 'Chair', User: { first_name: 'Mick', last_name: 'Broadstone' } }, { include: [User] }); +User.create({ title: 'Chair', creator: { first_name: 'Matt', last_name: 'Hansen' } }, { include: [User] }); +User.create({ id: 1, title: 'e', Tags: [{ id: 1, name: 'c' }, { id: 2, name: 'd' }] }, { include: [User] }); +User.create({ id: 'My own ID!' }).then((i) => i.isNewRecord); -User.findOrInitialize( { where : { username : 'foo' } } ).then( ( p ) => p ); -User.findOrInitialize( { where : { username : 'foo' }, transaction : t } ); -User.findOrInitialize( { where : { username : 'foo' }, defaults : { foo : 'asd' }, transaction : t } ); +User.findOrInitialize({ where: { username: 'foo' } }).then((p) => p); +User.findOrInitialize({ where: { username: 'foo' }, transaction: t }); +User.findOrInitialize({ where: { username: 'foo' }, defaults: { foo: 'asd' }, transaction: t }); -User.findOrCreate( { where : { a : 'b' }, defaults : { json : { a : { b : 'c' }, d : [1, 2, 3] } } } ); -User.findOrCreate( { where : { a : 'b' }, defaults : { json : 'a', data : 'b' } } ); +User.findOrCreate({ where: { a: 'b' }, defaults: { json: { a: { b: 'c' }, d: [1, 2, 3] } } }); +User.findOrCreate({ where: { a: 'b' }, defaults: { json: 'a', data: 'b' } }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 User.findOrCreate( { where : { a : 'b' }, transaction : t, lock : t.LOCK.UPDATE } ); */ -User.findOrCreate( { where : { a : 'b' }, logging : function( ) { } } ); -User.findOrCreate( { where : { username : 'Username' }, defaults : { data : 'some data' }, transaction : t } ); -User.findOrCreate( { where : { objectId : 'asdasdasd' }, defaults : { username : 'gottlieb' } } ); -User.findOrCreate( { where : { id : undefined }, defaults : { name : Math.random().toString() } } ); -User.findOrCreate( { where : { email : 'unique.email.@d.com', companyId : Math.floor( Math.random() * 5 ) } } ); -User.findOrCreate( { where : { objectId : 1 }, defaults : { bool : false } } ); -User.findOrCreate( { where : 'c', defaults : {} } ); +User.findOrCreate({ where: { a: 'b' }, logging: function () { } }); +User.findOrCreate({ where: { username: 'Username' }, defaults: { data: 'some data' }, transaction: t }); +User.findOrCreate({ where: { objectId: 'asdasdasd' }, defaults: { username: 'gottlieb' } }); +User.findOrCreate({ where: { id: undefined }, defaults: { name: Math.random().toString() } }); +User.findOrCreate({ where: { email: 'unique.email.@d.com', companyId: Math.floor(Math.random() * 5) } }); +User.findOrCreate({ where: { objectId: 1 }, defaults: { bool: false } }); +User.findOrCreate({ where: 'c', defaults: {} }); -User.upsert( { id : 42, username : 'doe', foo : s.fn( 'upper', 'mixedCase2' ) } ); +User.upsert({ id: 42, username: 'doe', foo: s.fn('upper', 'mixedCase2') }); -User.bulkCreate( [{ aNumber : 10 }, { aNumber : 12 }] ).then( ( i ) => i[0].isNewRecord ); -User.bulkCreate( [{ username : 'bar' }, { username : 'bar' }, { username : 'bar' }] ); -User.bulkCreate( [{}, {}], { validate : true, individualHooks : true } ); -User.bulkCreate( [{ style : 'ipa' }], { logging : function() { } } ); -User.bulkCreate( [{ a : 'b', c : 'd', e : 'f' }, { a : 'b', c : 'd', e : 'f' }], { fields : ['a', 'b'] } ); -User.bulkCreate( [{ name : 'foo', code : '123' }, { code : 'c' }, { name : 'bar', code : '1' }], { validate : true } ); -User.bulkCreate( [{ name : 'foo', code : '123' }, { code : '1234' }], { fields : ['code'], validate : true } ); -User.bulkCreate( [{ name : 'a', c : 'b' }, { name : 'e', c : 'f' }], { fields : ['e', 'f'], ignoreDuplicates : true } ); +User.bulkCreate([{ aNumber: 10 }, { aNumber: 12 }]).then((i) => i[0].isNewRecord); +User.bulkCreate([{ username: 'bar' }, { username: 'bar' }, { username: 'bar' }]); +User.bulkCreate([{}, {}], { validate: true, individualHooks: true }); +User.bulkCreate([{ style: 'ipa' }], { logging: function () { } }); +User.bulkCreate([{ a: 'b', c: 'd', e: 'f' }, { a: 'b', c: 'd', e: 'f' }], { fields: ['a', 'b'] }); +User.bulkCreate([{ name: 'foo', code: '123' }, { code: 'c' }, { name: 'bar', code: '1' }], { validate: true }); +User.bulkCreate([{ name: 'foo', code: '123' }, { code: '1234' }], { fields: ['code'], validate: true }); +User.bulkCreate([{ name: 'a', c: 'b' }, { name: 'e', c: 'f' }], { fields: ['e', 'f'], ignoreDuplicates: true }); User.truncate(); -User.destroy( { where : { client_id : 13 } } ).then( ( a ) => a.toFixed() ); -User.destroy( { force : true } ); -User.destroy( { where : {}, transaction : t } ); -User.destroy( { where : { access_level : { lt : 5 } } } ); -User.destroy( { truncate : true } ); -User.destroy( { where : {} } ); +User.destroy({ where: { client_id: 13 } }).then((a) => a.toFixed()); +User.destroy({ force: true }); +User.destroy({ where: {}, transaction: t }); +User.destroy({ where: { access_level: { lt: 5 } } }); +User.destroy({ truncate: true }); +User.destroy({ where: {} }); -User.restore( { where : { secretValue : '42' } } ); +User.restore({ where: { secretValue: '42' } }); -User.update( { username : 'ruben' }, { where : {} } ); -User.update( { username : 'ruben' }, { where : { access_level : { lt : 5 } } } ); -User.update( { username : 'ruben' }, { where : { username : 'dan' } } ); -User.update( { username : 'bar' }, { where : { username : 'foo' }, transaction : t } ); -User.update( { username : 'Bill', secretValue : '43' }, { where : { secretValue : '42' }, fields : ['username'] } ); -User.update( { username : s.cast( '1', 'char' ) }, { where : { username : 'John' } } ); -User.update( { username : s.fn( 'upper', s.col( 'username' ) ) }, { where : { username : 'John' } } ); -User.update( { username : 'Bill' }, { where : { secretValue : '42' }, returning : true } ); -User.update( { secretValue : '43' }, { where : { username : 'Peter' }, limit : 1 } ); -User.update( { name : Math.random().toString() }, { where : { id : '1' } } ); -User.update( { a : { b : 10, c : 'd' } }, { where : { username : 'Jan' }, sideEffects : false } ); -User.update( { geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } }, { - where : { - u : { - u : 'u', - geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } +User.update({ username: 'ruben' }, { where: {} }); +User.update({ username: 'ruben' }, { where: { access_level: { lt: 5 } } }); +User.update({ username: 'ruben' }, { where: { username: 'dan' } }); +User.update({ username: 'bar' }, { where: { username: 'foo' }, transaction: t }); +User.update({ username: 'Bill', secretValue: '43' }, { where: { secretValue: '42' }, fields: ['username'] }); +User.update({ username: s.cast('1', 'char') }, { where: { username: 'John' } }); +User.update({ username: s.fn('upper', s.col('username')) }, { where: { username: 'John' } }); +User.update({ username: 'Bill' }, { where: { secretValue: '42' }, returning: true }); +User.update({ secretValue: '43' }, { where: { username: 'Peter' }, limit: 1 }); +User.update({ name: Math.random().toString() }, { where: { id: '1' } }); +User.update({ a: { b: 10, c: 'd' } }, { where: { username: 'Jan' }, sideEffects: false }); +User.update({ geometry: { type: 'Point', coordinates: [49.807222, -86.984722] } }, { + where: { + u: { + u: 'u', + geometry: { type: 'Point', coordinates: [49.807222, -86.984722] } } } -} ); -User.update( { - geometry : { - type : 'Polygon', - coordinates : [[[100.0, 0.0], [102.0, 0.0], [102.0, 1.0], [100.0, 1.0], [100.0, 0.0]]] +}); +User.update({ + geometry: { + type: 'Polygon', + coordinates: [[[100.0, 0.0], [102.0, 0.0], [102.0, 1.0], [100.0, 1.0], [100.0, 0.0]]] } }, { - where : { - username : { - username : 'username', - geometry : { type : 'Point', coordinates : [49.807222, -86.984722] } + where: { + username: { + username: 'username', + geometry: { type: 'Point', coordinates: [49.807222, -86.984722] } + } } - } -} ); + }); -User.unscoped().find( { where : { username : 'bob' } } ); +User.unscoped().find({ where: { username: 'bob' } }); User.unscoped().count(); // @@ -1048,77 +1048,77 @@ User.unscoped().count(); var queryInterface = s.getQueryInterface(); queryInterface.dropAllTables(); -queryInterface.showAllTables( { logging : function() { } } ); -queryInterface.createTable( 'table', { name : Sequelize.STRING }, { logging : function() { } } ); -queryInterface.createTable( 'skipme', { name : Sequelize.STRING } ); +queryInterface.showAllTables({ logging: function () { } }); +queryInterface.createTable('table', { name: Sequelize.STRING }, { logging: function () { } }); +queryInterface.createTable('skipme', { name: Sequelize.STRING }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 queryInterface.dropAllTables( { skip : ['skipme'] } ); */ -queryInterface.dropTable( 'Group', { logging : function() { } } ); -queryInterface.addIndex( 'Group', ['username', 'isAdmin'], { logging : function() { } } ); -queryInterface.showIndex( 'Group', { logging : function() { } } ); -queryInterface.removeIndex( 'Group', ['username', 'isAdmin'], { logging : function() { } } ); -queryInterface.showIndex( 'Group' ); +queryInterface.dropTable('Group', { logging: function () { } }); +queryInterface.addIndex('Group', ['username', 'isAdmin'], { logging: function () { } }); +queryInterface.showIndex('Group', { logging: function () { } }); +queryInterface.removeIndex('Group', ['username', 'isAdmin'], { logging: function () { } }); +queryInterface.showIndex('Group'); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 queryInterface.createTable( 'table', { name : { type : Sequelize.STRING } }, { schema : 'schema' } ); */ -queryInterface.addIndex( { schema : 'a', tableName : 'c' }, ['d', 'e'], { logging : function() {} }, 'schema_table' ); -queryInterface.showIndex( { schema : 'schema', tableName : 'table' }, { logging : function() {} } ); -queryInterface.addIndex( 'Group', ['from'] ); -queryInterface.describeTable( '_Users', { logging : function() {} } ); -queryInterface.createTable( 's', { table_id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); +queryInterface.addIndex({ schema: 'a', tableName: 'c' }, ['d', 'e'], { logging: function () { } }, 'schema_table'); +queryInterface.showIndex({ schema: 'schema', tableName: 'table' }, { logging: function () { } }); +queryInterface.addIndex('Group', ['from']); +queryInterface.describeTable('_Users', { logging: function () { } }); +queryInterface.createTable('s', { table_id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 queryInterface.insert( null, 'TableWithPK', {}, { raw : true, returning : true, plain : true } ); */ -queryInterface.createTable( 'SomeTable', { someEnum : Sequelize.ENUM( 'value1', 'value2', 'value3' ) } ); -queryInterface.createTable( 'SomeTable', { someEnum : { type : Sequelize.ENUM, values : ['b1', 'b2', 'b3'] } } ); -queryInterface.createTable( 't', { someEnum : { type : Sequelize.ENUM, values : ['c1', 'c2', 'c3'], field : 'd' } } ); +queryInterface.createTable('SomeTable', { someEnum: Sequelize.ENUM('value1', 'value2', 'value3') }); +queryInterface.createTable('SomeTable', { someEnum: { type: Sequelize.ENUM, values: ['b1', 'b2', 'b3'] } }); +queryInterface.createTable('t', { someEnum: { type: Sequelize.ENUM, values: ['c1', 'c2', 'c3'], field: 'd' } }); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 queryInterface.createTable( 'User', { name : { type : Sequelize.STRING } }, { schema : 'hero' } ); queryInterface.rawSelect( 'User', { schema : 'hero', logging : function() {} }, 'name' ); */ -queryInterface.renameColumn( '_Users', 'username', 'pseudo', { logging : function() {} } ); -queryInterface.renameColumn( { schema : 'archive', tableName : 'Users' }, 'username', 'pseudo' ); -queryInterface.renameColumn( '_Users', 'username', 'pseudo' ); -queryInterface.createTable( { tableName : 'y', schema : 'a' }, - { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true }, currency : Sequelize.INTEGER } ); -queryInterface.changeColumn( { tableName : 'a', schema : 'b' }, 'c', { type : Sequelize.FLOAT }, - { logging : () => s } ); -queryInterface.createTable( 'users', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); -queryInterface.createTable( 'level', { id : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } } ); -queryInterface.addColumn( 'users', 'someEnum', Sequelize.ENUM( 'value1', 'value2', 'value3' ) ); -queryInterface.addColumn( 'users', 'so', { type : Sequelize.ENUM, values : ['value1', 'value2', 'value3'] } ); -queryInterface.createTable( 'hosts', { - id : { - type : Sequelize.INTEGER, - primaryKey : true, - autoIncrement : true +queryInterface.renameColumn('_Users', 'username', 'pseudo', { logging: function () { } }); +queryInterface.renameColumn({ schema: 'archive', tableName: 'Users' }, 'username', 'pseudo'); +queryInterface.renameColumn('_Users', 'username', 'pseudo'); +queryInterface.createTable({ tableName: 'y', schema: 'a' }, + { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, currency: Sequelize.INTEGER }); +queryInterface.changeColumn({ tableName: 'a', schema: 'b' }, 'c', { type: Sequelize.FLOAT }, + { logging: () => s }); +queryInterface.createTable('users', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } }); +queryInterface.createTable('level', { id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } }); +queryInterface.addColumn('users', 'someEnum', Sequelize.ENUM('value1', 'value2', 'value3')); +queryInterface.addColumn('users', 'so', { type: Sequelize.ENUM, values: ['value1', 'value2', 'value3'] }); +queryInterface.createTable('hosts', { + id: { + type: Sequelize.INTEGER, + primaryKey: true, + autoIncrement: true }, - admin : { - type : Sequelize.INTEGER, - references : { - model : User, - key : 'id' + admin: { + type: Sequelize.INTEGER, + references: { + model: User, + key: 'id' } }, - operator : { - type : Sequelize.INTEGER, - references : { - model : User, - key : 'id' + operator: { + type: Sequelize.INTEGER, + references: { + model: User, + key: 'id' }, - onUpdate : 'cascade' + onUpdate: 'cascade' }, - owner : { - type : Sequelize.INTEGER, - references : { - model : User, - key : 'id' + owner: { + type: Sequelize.INTEGER, + references: { + model: User, + key: 'id' }, - onUpdate : 'cascade', - onDelete : 'set null' + onUpdate: 'cascade', + onDelete: 'set null' } -} ); +}); // // Query Types @@ -1128,136 +1128,136 @@ queryInterface.createTable( 'hosts', { s.getDialect(); s.validate(); s.authenticate(); -s.isDefined( '' ); -s.model( 'pp' ); -s.query( '', { raw : true } ); -s.query( '' ); -s.query( '' ).then( function( res ) {} ); -s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { raw : true, replacements : [1, 2] } ); -s.query( '', { raw : true, nest : false } ); -s.query( 'select ? as foo, ? as bar', { type : this.sequelize.QueryTypes.SELECT, replacements : [1, 2] } ); -s.query( { query : 'select ? as foo, ? as bar', values : [1, 2] }, { type : s.QueryTypes.SELECT } ); -s.query( 'select :one as foo, :two as bar', { raw : true, replacements : { one : 1, two : 2 } } ); -s.transaction().then( function( t ) { s.set( { foo : 'bar' }, { transaction : t } ); } ); -s.define( 'foo', { bar : Sequelize.STRING }, { collate : 'utf8_bin' } ); -s.define( 'Foto', { name : Sequelize.STRING }, { tableName : 'photos' } ); -s.databaseVersion().then( function( version ) { } ); +s.isDefined(''); +s.model('pp'); +s.query('', { raw: true }); +s.query(''); +s.query('').then(function (res) { }); +s.query({ query: 'select ? as foo, ? as bar', values: [1, 2] }, { raw: true, replacements: [1, 2] }); +s.query('', { raw: true, nest: false }); +s.query('select ? as foo, ? as bar', { type: this.sequelize.QueryTypes.SELECT, replacements: [1, 2] }); +s.query({ query: 'select ? as foo, ? as bar', values: [1, 2] }, { type: s.QueryTypes.SELECT }); +s.query('select :one as foo, :two as bar', { raw: true, replacements: { one: 1, two: 2 } }); +s.transaction().then(function (t) { s.set({ foo: 'bar' }, { transaction: t }); }); +s.define('foo', { bar: Sequelize.STRING }, { collate: 'utf8_bin' }); +s.define('Foto', { name: Sequelize.STRING }, { tableName: 'photos' }); +s.databaseVersion().then(function (version) { }); // // Sequelize // ~~~~~~~~~~~ // -new Sequelize( 'db', 'user', 'pw', { logging : false } ); -new Sequelize( 'db', 'user', 'pass', { - dialect : '', - port : 99999, - pool : {} -} ); -new Sequelize( '' ).query( '', { type : s.QueryTypes.FOREIGNKEYS, logging : function() {} } ); -new Sequelize( 'sqlite://test.sqlite' ); -new Sequelize( 'wat', 'trololo', 'wow', { port : 99999 } ); -new Sequelize( 'localhost', 'wtf', 'lol', { port : 99999 } ); -new Sequelize( 'sequelize', null, null, { - replication : { - read : { - host : 'localhost', - username : 'omg', - password : 'lol' +new Sequelize('db', 'user', 'pw', { logging: false }); +new Sequelize('db', 'user', 'pass', { + dialect: '', + port: 99999, + pool: {} +}); +new Sequelize('').query('', { type: s.QueryTypes.FOREIGNKEYS, logging: function () { } }); +new Sequelize('sqlite://test.sqlite'); +new Sequelize('wat', 'trololo', 'wow', { port: 99999 }); +new Sequelize('localhost', 'wtf', 'lol', { port: 99999 }); +new Sequelize('sequelize', null, null, { + replication: { + read: { + host: 'localhost', + username: 'omg', + password: 'lol' } } -} ); +}); -s.model( 'Project' ); +s.model('Project'); s.models['Project']; -s.define( 'Project', { - name : Sequelize.STRING -} ); +s.define('Project', { + name: Sequelize.STRING +}); -var s = new Sequelize( '' ); -var testModel = s.define( 'User', { - username : Sequelize.STRING, - secretValue : Sequelize.STRING, - data : Sequelize.STRING, - intVal : Sequelize.INTEGER, - theDate : Sequelize.DATE, - aBool : Sequelize.BOOLEAN -} ); -var testModel = s.define( 'FrozenUser', {}, { freezeTableName : true } ); -s.define( 'UserWithClassAndInstanceMethods', {}, { - classMethods : { doSmth : function() { return 1; } }, - instanceMethods : { makeItSo : function() { return 2; } } -} ); -s.define( 'UserCol', { - id : { - type : Sequelize.STRING, - defaultValue : 'User', - primaryKey : true +var s = new Sequelize(''); +var testModel = s.define('User', { + username: Sequelize.STRING, + secretValue: Sequelize.STRING, + data: Sequelize.STRING, + intVal: Sequelize.INTEGER, + theDate: Sequelize.DATE, + aBool: Sequelize.BOOLEAN +}); +var testModel = s.define('FrozenUser', {}, { freezeTableName: true }); +s.define('UserWithClassAndInstanceMethods', {}, { + classMethods: { doSmth: function () { return 1; } }, + instanceMethods: { makeItSo: function () { return 2; } } +}); +s.define('UserCol', { + id: { + type: Sequelize.STRING, + defaultValue: 'User', + primaryKey: true } -} ); -s.define( 'UserWithTwoAutoIncrements', { - userid : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true }, - userscore : { type : Sequelize.INTEGER, primaryKey : true, autoIncrement : true } -} ); -s.define( 'Foo', { - field : Sequelize.INTEGER +}); +s.define('UserWithTwoAutoIncrements', { + userid: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true }, + userscore: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true } +}); +s.define('Foo', { + field: Sequelize.INTEGER }, { - validate : { - field : function() {} - } -} ); -var UserTable = s.define( 'UserCol', { - aNumber : Sequelize.INTEGER, - createdAt : { - type : Sequelize.DATE, - defaultValue : new Date() + validate: { + field: function () { } + } + }); +var UserTable = s.define('UserCol', { + aNumber: Sequelize.INTEGER, + createdAt: { + type: Sequelize.DATE, + defaultValue: new Date() }, - updatedAt : { - type : Sequelize.DATE, - defaultValue : new Date() + updatedAt: { + type: Sequelize.DATE, + defaultValue: new Date() } -}, { timestamps : true } ); +}, { timestamps: true }); -s.define( 'UserCol', { - aNumber : Sequelize.INTEGER +s.define('UserCol', { + aNumber: Sequelize.INTEGER }, { - timestamps : true, - updatedAt : 'updatedOn', - createdAt : 'dateCreated', - deletedAt : 'deletedAtThisTime', - paranoid : true -} ); -s.define( 'UpdatingUser', { - name : Sequelize.STRING + timestamps: true, + updatedAt: 'updatedOn', + createdAt: 'dateCreated', + deletedAt: 'deletedAtThisTime', + paranoid: true + }); +s.define('UpdatingUser', { + name: Sequelize.STRING }, { - timestamps : true, - updatedAt : false, - createdAt : false, - deletedAt : 'deletedAtThisTime', - paranoid : true -} ); -s.define( 'TaskBuild', { - title : { - type : Sequelize.STRING( 50 ), - allowNull : false, - defaultValue : '' + timestamps: true, + updatedAt: false, + createdAt: false, + deletedAt: 'deletedAtThisTime', + paranoid: true + }); +s.define('TaskBuild', { + title: { + type: Sequelize.STRING(50), + allowNull: false, + defaultValue: '' } }, { - setterMethods : { - title : function() { } - } -} ); -s.define( 'UserCol', { - aNumber : Sequelize.INTEGER + setterMethods: { + title: function () { } + } + }); +s.define('UserCol', { + aNumber: Sequelize.INTEGER }, { - paranoid : true, - underscored : true -} ); + paranoid: true, + underscored: true + }); -s.define( 'UserWithUniqueUsername', { - username : { type : Sequelize.STRING, unique : { name : 'user_and_email', msg : 'User and email must be unique' } }, - email : { type : Sequelize.STRING, unique : 'user_and_email' } -} ); +s.define('UserWithUniqueUsername', { + username: { type: Sequelize.STRING, unique: { name: 'user_and_email', msg: 'User and email must be unique' } }, + email: { type: Sequelize.STRING, unique: 'user_and_email' } +}); /* NOTE https://github.com/DefinitelyTyped/DefinitelyTyped/pull/5590 s.define( 'UserWithUniqueUsername', { user_id : { type : Sequelize.INTEGER }, @@ -1273,271 +1273,271 @@ s.define( 'UserWithUniqueUsername', { }] } ); */ -s.define( 'TaskBuild', { - title : { type : Sequelize.STRING, defaultValue : 'a task!' }, - foo : { type : Sequelize.INTEGER, defaultValue : 2 }, - bar : { type : Sequelize.DATE }, - foobar : { type : Sequelize.TEXT, defaultValue : 'asd' }, - flag : { type : Sequelize.BOOLEAN, defaultValue : false } -} ); -s.define( 'ProductWithSettersAndGetters1', { - price : { - type : Sequelize.INTEGER, - get : function() { - return 'answer = ' + this.getDataValue( 'price' ); +s.define('TaskBuild', { + title: { type: Sequelize.STRING, defaultValue: 'a task!' }, + foo: { type: Sequelize.INTEGER, defaultValue: 2 }, + bar: { type: Sequelize.DATE }, + foobar: { type: Sequelize.TEXT, defaultValue: 'asd' }, + flag: { type: Sequelize.BOOLEAN, defaultValue: false } +}); +s.define('ProductWithSettersAndGetters1', { + price: { + type: Sequelize.INTEGER, + get: function () { + return 'answer = ' + this.getDataValue('price'); }, - set : function( v ) { - return this.setDataValue( 'price', v + 42 ); + set: function (v) { + return this.setDataValue('price', v + 42); } } -} ); -s.define( 'ProductWithSettersAndGetters2', { - priceInCents : Sequelize.INTEGER +}); +s.define('ProductWithSettersAndGetters2', { + priceInCents: Sequelize.INTEGER }, { - setterMethods : { - price : function( value ) { - this.dataValues.priceInCents = value * 100; - } - }, - getterMethods : { - price : function() { - return '$' + (this.getDataValue( 'priceInCents' ) / 100); + setterMethods: { + price: function (value) { + this.dataValues.priceInCents = value * 100; + } }, + getterMethods: { + price: function () { + return '$' + (this.getDataValue('priceInCents') / 100); + }, - priceInCents : function() { - return this.dataValues.priceInCents; + priceInCents: function () { + return this.dataValues.priceInCents; + } } - } -} ); + }); -s.define( 'post', { - title : Sequelize.STRING, - authorId : { type : Sequelize.INTEGER, references : testModel, referencesKey : 'id' } +s.define('post', { + title: Sequelize.STRING, + authorId: { type: Sequelize.INTEGER, references: testModel, referencesKey: 'id' } } as any /* TODO please remove `as any` */); -s.define( 'post', { - title : Sequelize.STRING, - authorId : { type : Sequelize.INTEGER, references : { model : testModel, key : 'id' } } -} ); +s.define('post', { + title: Sequelize.STRING, + authorId: { type: Sequelize.INTEGER, references: { model: testModel, key: 'id' } } +}); -s.define( 'User', { - username : Sequelize.STRING, - geometry : Sequelize.GEOMETRY( 'POINT' ) -} ); +s.define('User', { + username: Sequelize.STRING, + geometry: Sequelize.GEOMETRY('POINT') +}); -s.define( 'ScopeMe', { - username : Sequelize.STRING, - email : Sequelize.STRING, - access_level : Sequelize.INTEGER, - other_value : Sequelize.INTEGER, - parent_id : Sequelize.INTEGER +s.define('ScopeMe', { + username: Sequelize.STRING, + email: Sequelize.STRING, + access_level: Sequelize.INTEGER, + other_value: Sequelize.INTEGER, + parent_id: Sequelize.INTEGER }, { - defaultScope : { - where : { - access_level : { - gte : 5 - } - } - }, - scopes : { - isTony : { - where : { - username : 'tony' - } - }, - } -} ); -s.define( 'company', { - active : Sequelize.BOOLEAN -}, { - defaultScope : { - where : { active : true } - }, - scopes : { - notActive : { - where : { - active : false - } - }, - reversed : { - order : [['id', 'DESC']] - } - } -} ); -s.define( 'profile', { - active : Sequelize.BOOLEAN -}, { - defaultScope : { - where : { active : true } - }, - scopes : { - notActive : { - where : { - active : false - } - }, - } -} ); - -s.define( 'ScopeMe', { - username : Sequelize.STRING, - email : Sequelize.STRING, - access_level : Sequelize.INTEGER, - other_value : Sequelize.INTEGER -}, { - defaultScope : { - where : { - access_level : { - gte : 5 - } - } - }, - scopes : { - lowAccess : { - where : { - access_level : { - lte : 5 + defaultScope: { + where: { + access_level: { + gte: 5 } } }, - withOrder : { - order : 'username' + scopes: { + isTony: { + where: { + username: 'tony' + } + }, } - } -} ); - -s.define( 'ScopeMe', { - username : Sequelize.STRING, - email : Sequelize.STRING, - access_level : Sequelize.INTEGER, - other_value : Sequelize.INTEGER + }); +s.define('company', { + active: Sequelize.BOOLEAN }, { - defaultScope : { - where : { - access_level : { - gte : 5 + defaultScope: { + where: { active: true } + }, + scopes: { + notActive: { + where: { + active: false + } + }, + reversed: { + order: [['id', 'DESC']] } } - }, - scopes : { - lowAccess : { - where : { - access_level : { - lte : 5 + }); +s.define('profile', { + active: Sequelize.BOOLEAN +}, { + defaultScope: { + where: { active: true } + }, + scopes: { + notActive: { + where: { + active: false + } + }, + } + }); + +s.define('ScopeMe', { + username: Sequelize.STRING, + email: Sequelize.STRING, + access_level: Sequelize.INTEGER, + other_value: Sequelize.INTEGER +}, { + defaultScope: { + where: { + access_level: { + gte: 5 + } + } + }, + scopes: { + lowAccess: { + where: { + access_level: { + lte: 5 + } + } + }, + withOrder: { + order: 'username' + } + } + }); + +s.define('ScopeMe', { + username: Sequelize.STRING, + email: Sequelize.STRING, + access_level: Sequelize.INTEGER, + other_value: Sequelize.INTEGER +}, { + defaultScope: { + where: { + access_level: { + gte: 5 + } + } + }, + scopes: { + lowAccess: { + where: { + access_level: { + lte: 5 + } } } } - } -} ); + }); -s.define( 'user', { - id : { - type : Sequelize.INTEGER, - allowNull : false, - primaryKey : true, - autoIncrement : true, - field : 'userId' +s.define('user', { + id: { + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true, + autoIncrement: true, + field: 'userId' }, - name : { - type : Sequelize.STRING, - field : 'full_name' + name: { + type: Sequelize.STRING, + field: 'full_name' }, - taskCount : { - type : Sequelize.INTEGER, - field : 'task_count', - defaultValue : 0, - allowNull : false + taskCount: { + type: Sequelize.INTEGER, + field: 'task_count', + defaultValue: 0, + allowNull: false } }, { - tableName : 'users', - timestamps : false -} ); -s.define( 'task', { - id : { - type : Sequelize.INTEGER, - allowNull : false, - primaryKey : true, - autoIncrement : true, - field : 'taskId' + tableName: 'users', + timestamps: false + }); +s.define('task', { + id: { + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true, + autoIncrement: true, + field: 'taskId' }, - title : { - type : Sequelize.STRING, - field : 'name' + title: { + type: Sequelize.STRING, + field: 'name' } }, { - tableName : 'tasks', - timestamps : false -} ); -s.define( 'comment', { - id : { - type : Sequelize.INTEGER, - allowNull : false, - primaryKey : true, - autoIncrement : true, - field : 'commentId' + tableName: 'tasks', + timestamps: false + }); +s.define('comment', { + id: { + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true, + autoIncrement: true, + field: 'commentId' }, - text : { - type : Sequelize.STRING, - field : 'comment_text' + text: { + type: Sequelize.STRING, + field: 'comment_text' }, - notes : { - type : Sequelize.STRING, - field : 'notes' + notes: { + type: Sequelize.STRING, + field: 'notes' } }, { - tableName : 'comments', - timestamps : false -} ); -s.define( 'test', { - id : { - type : Sequelize.INTEGER, - field : 'test_id', - autoIncrement : true, - primaryKey : true, - validate : { - min : 1 + tableName: 'comments', + timestamps: false + }); +s.define('test', { + id: { + type: Sequelize.INTEGER, + field: 'test_id', + autoIncrement: true, + primaryKey: true, + validate: { + min: 1 } }, - title : { - allowNull : false, - type : Sequelize.STRING( 255 ), - field : 'test_title' + title: { + allowNull: false, + type: Sequelize.STRING(255), + field: 'test_title' } }, { - timestamps : true, - underscored : true, - freezeTableName : true -} ); + timestamps: true, + underscored: true, + freezeTableName: true + }); -s.define( 'User', { - deletedAt : { - type : Sequelize.DATE, - field : 'deleted_at' +s.define('User', { + deletedAt: { + type: Sequelize.DATE, + field: 'deleted_at' } }, { - timestamps : true, - paranoid : true -} ); + timestamps: true, + paranoid: true + }); -s.define( 'TriggerTest', { - id : { - type : Sequelize.INTEGER, - field : 'test_id', - autoIncrement : true, - primaryKey : true, - validate : { - min : 1 +s.define('TriggerTest', { + id: { + type: Sequelize.INTEGER, + field: 'test_id', + autoIncrement: true, + primaryKey: true, + validate: { + min: 1 } }, - title : { - allowNull : false, - type : Sequelize.STRING( 255 ), - field : 'test_title' + title: { + allowNull: false, + type: Sequelize.STRING(255), + field: 'test_title' } }, { - timestamps : false, - underscored : true, - hasTrigger : true -} ); + timestamps: false, + underscored: true, + hasTrigger: true + }); // // Transaction @@ -1546,68 +1546,80 @@ s.define( 'TriggerTest', { // https://github.com/sequelize/sequelize/blob/v3.4.1/test/integration/transaction.test.js // -s.transaction().then( function( t ) { +s.transaction().then(function (t) { t.commit(); t.rollback(); - User.find( { - where : { - username : 'John' + User.find({ + where: { + username: 'John' }, - include : [User], - lock : t.LOCK.UPDATE, - transaction : t - } ); - User.find( { - where : { - username : 'John' + include: [User], + lock: t.LOCK.UPDATE, + transaction: t + }); + User.find({ + where: { + username: 'John' }, - include : [User], - lock : { - level : t.LOCK.UPDATE, - of : User + include: [User], + lock: { + level: t.LOCK.UPDATE, + of: User }, - transaction : t - } ); - User.update( { - active : true + transaction: t + }); + User.update({ + active: true }, { - where : { - active : false + where: { + active: false + }, + transaction: t + }); + User.find({ + where: { + username: 'jan' }, - transaction : t - } ); - User.find( { - where : { - username : 'jan' + lock: t.LOCK.NO_KEY_UPDATE, + transaction: t + }); + User.find({ + where: { + username: 'jan' }, - lock : t.LOCK.NO_KEY_UPDATE, - transaction : t - } ); - User.find( { - where : { - username : 'jan' - }, - lock : t.LOCK.KEY_SHARE, - transaction : t - } ); + lock: t.LOCK.KEY_SHARE, + transaction: t + }); -} ); +}); -s.transaction( function() { +s.transaction({ + isolationLevel: s.Transaction.ISOLATION_LEVELS.READ_COMMITTED +}).then(function (t2) { + return User.find({ + where: { + username: 'jan' + }, + lock: t2.LOCK.UPDATE, + transaction: t2 + }); +}); + +s.transaction(function () { return Promise.resolve(); -} ); -s.transaction( { isolationLevel : 'SERIALIZABLE' }, function( t ) { return Promise.resolve(); } ); -s.transaction( { isolationLevel : s.Transaction.ISOLATION_LEVELS.SERIALIZABLE }, (t) => Promise.resolve() ); -s.transaction( { isolationLevel : s.Transaction.ISOLATION_LEVELS.READ_COMMITTED }, (t) => Promise.resolve() ); +}); +s.transaction({ isolationLevel: 'SERIALIZABLE' }, function (t) { return Promise.resolve(); }); +s.transaction({ isolationLevel: s.Transaction.ISOLATION_LEVELS.SERIALIZABLE }, (t) => Promise.resolve()); +s.transaction({ isolationLevel: s.Transaction.ISOLATION_LEVELS.READ_COMMITTED }, (t) => Promise.resolve()); // transaction types -new Sequelize( '', { transactionType: 'DEFERRED' } ); -new Sequelize( '', { transactionType: Sequelize.Transaction.TYPES.DEFERRED} ); -new Sequelize( '', { transactionType: Sequelize.Transaction.TYPES.IMMEDIATE} ); -new Sequelize( '', { transactionType: Sequelize.Transaction.TYPES.EXCLUSIVE} ); -s.transaction( { type : 'DEFERRED' }, (t) => Promise.resolve() ); -s.transaction( { type : s.Transaction.TYPES.DEFERRED }, (t) => Promise.resolve() ); -s.transaction( { type : s.Transaction.TYPES.IMMEDIATE }, (t) => Promise.resolve() ); -s.transaction( { type : s.Transaction.TYPES.EXCLUSIVE }, (t) => Promise.resolve() ); +new Sequelize('', { transactionType: 'DEFERRED' }); +new Sequelize('', { transactionType: Sequelize.Transaction.TYPES.DEFERRED }); +new Sequelize('', { transactionType: Sequelize.Transaction.TYPES.IMMEDIATE }); +new Sequelize('', { transactionType: Sequelize.Transaction.TYPES.EXCLUSIVE }); +s.transaction({ type: 'DEFERRED' }, (t) => Promise.resolve()); +s.transaction({ type: s.Transaction.TYPES.DEFERRED }, (t) => Promise.resolve()); +s.transaction({ type: s.Transaction.TYPES.IMMEDIATE }, (t) => Promise.resolve()); +s.transaction({ type: s.Transaction.TYPES.EXCLUSIVE }, (t) => Promise.resolve()); From a84ff5234e5e3d83c36aea98fdc5c25d0bfa50ea Mon Sep 17 00:00:00 2001 From: Konrad Mattheis Date: Sat, 20 May 2017 00:40:18 +0200 Subject: [PATCH 0007/1139] * move qlik-engineapi types from / to new /types --- {qlik-engineapi => types/qlik-engineapi}/index.d.ts | 0 {qlik-engineapi => types/qlik-engineapi}/qlik-engineapi-tests.ts | 0 {qlik-engineapi => types/qlik-engineapi}/tsconfig.json | 0 {qlik-engineapi => types/qlik-engineapi}/tslint.json | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename {qlik-engineapi => types/qlik-engineapi}/index.d.ts (100%) rename {qlik-engineapi => types/qlik-engineapi}/qlik-engineapi-tests.ts (100%) rename {qlik-engineapi => types/qlik-engineapi}/tsconfig.json (100%) rename {qlik-engineapi => types/qlik-engineapi}/tslint.json (100%) diff --git a/qlik-engineapi/index.d.ts b/types/qlik-engineapi/index.d.ts similarity index 100% rename from qlik-engineapi/index.d.ts rename to types/qlik-engineapi/index.d.ts diff --git a/qlik-engineapi/qlik-engineapi-tests.ts b/types/qlik-engineapi/qlik-engineapi-tests.ts similarity index 100% rename from qlik-engineapi/qlik-engineapi-tests.ts rename to types/qlik-engineapi/qlik-engineapi-tests.ts diff --git a/qlik-engineapi/tsconfig.json b/types/qlik-engineapi/tsconfig.json similarity index 100% rename from qlik-engineapi/tsconfig.json rename to types/qlik-engineapi/tsconfig.json diff --git a/qlik-engineapi/tslint.json b/types/qlik-engineapi/tslint.json similarity index 100% rename from qlik-engineapi/tslint.json rename to types/qlik-engineapi/tslint.json From 7fbcd08359659b6f9db5cec24bdc6f155622ad7f Mon Sep 17 00:00:00 2001 From: Konrad Mattheis Date: Sat, 20 May 2017 01:24:13 +0200 Subject: [PATCH 0008/1139] fix TSLint errors Signed-off-by: Konrad Mattheis --- types/qlik-engineapi/index.d.ts | 70 ++++++++------------ types/qlik-engineapi/qlik-engineapi-tests.ts | 1 + types/qlik-engineapi/tslint.json | 8 +-- 3 files changed, 33 insertions(+), 46 deletions(-) diff --git a/types/qlik-engineapi/index.d.ts b/types/qlik-engineapi/index.d.ts index 4baf80e8fe..6b6adc25d8 100644 --- a/types/qlik-engineapi/index.d.ts +++ b/types/qlik-engineapi/index.d.ts @@ -101,7 +101,7 @@ declare namespace EngineAPI { interface IGenericProperties { qInfo: INxInfo; - //?Dynamic properties? + // ?Dynamic properties? [qMetaDef: string]: any; } @@ -1021,10 +1021,10 @@ declare namespace EngineAPI { } interface IImplementOn { - //? nicht in der docu - on(event: "changed" | "closed", func: () => void); + // ? not in Docu + on(event: "changed" | "closed", func: () => void): void; - //? not in Docu + // ? not in Docu id: string; } @@ -1053,7 +1053,13 @@ declare namespace EngineAPI { getChild(qId: string): Promise; getEffectiveProperties(): Promise; getFullPropertyTree(): Promise; - getHyperCubeBinnedData(qPath: string, qPages: INxPage[], qViewport: INxViewPort, qDataRanges: INxDataAreaPage, qMaxNbrCells: number, qQueryLevel: number, qBinningMethod: number): Promise; + getHyperCubeBinnedData(qPath: string, + qPages: INxPage[], + qViewport: INxViewPort, + qDataRanges: INxDataAreaPage, + qMaxNbrCells: number, + qQueryLevel: number, + qBinningMethod: number): Promise; getHyperCubeContinuousData(qPath: string, qOptions: IContinuousDataOptions[]): Promise | Promise | Promise; getHyperCubeData(qPath: string, qPages: INxPage[]): Promise; getHyperCubePivotData(qPath: string, qPages: INxPage[]): Promise; @@ -1287,13 +1293,13 @@ declare namespace EngineAPI { cancelRequest(qRequestId: number): Promise; configureReload(qCancelOnScriptError: boolean, qUseErrorData: boolean, qInteractOnError: boolean): Promise; copyApp(qTargetAppId: string, qSrcAppId: string, qIds: string[]): Promise; - createApp(qAppName: string, qLocalizedScriptMainSection: string): Promise; //?Result + createApp(qAppName: string, qLocalizedScriptMainSection: string): Promise; // ?Result createDocEx(qDocName: string, qUserName?: string, qPassword?: string, qSerial?: string, qLocalizedScriptMainSection?: string): Promise; createSessionApp(): Promise; createSessionAppFromApp(qSrcAppId: string): Promise; deleteApp(qAppId: string): Promise; exportApp(qTargetPath: string, qSrcAppId: string, qIds: string[]): Promise; - getActiveDoc(): Promise; //?Result + getActiveDoc(): Promise; // ?Result getAppEntry(qAppID: string): Promise; getAuthenticatedUser(): Promise; getBNF(qBnfType: BnfType): Promise; @@ -1595,7 +1601,7 @@ declare namespace EngineAPI { * Validation error. * REF(NxValidationError) */ - //?Type = REF(NxValidationError)? + // ?Type = REF(NxValidationError)? qError: INxValidationError; } @@ -1743,8 +1749,8 @@ declare namespace EngineAPI { qAttributeExpressions?: INxAttrExprDef[]; qAttributeDimensions?: INxAttrDimDef[]; - qIncludeElemValue?: boolean; //?Nicht in Doku - qShowTotal?: boolean; //?Nicht in Doku + qIncludeElemValue?: boolean; // ?Nicht in Doku + qShowTotal?: boolean; // ?Nicht in Doku } interface INxCellPosition { @@ -1765,7 +1771,7 @@ declare namespace EngineAPI { qSortByExpression?: TypeSortDirection; qExpression?: IValueExpr; - qSortByGreyness?: TypeSortDirection; //?Nicht in Doku + qSortByGreyness?: TypeSortDirection; // ?Nicht in Doku } interface IStringExpressionContainer { @@ -1825,20 +1831,20 @@ declare namespace EngineAPI { qData: T; } - //public enum NxHypercubeMode { + // public enum NxHypercubeMode { // [QixName("P: // DATA_MODE_PIVOT = 1, // [QixName("K: // DATA_MODE_PIVOT_STACK = 2, // [QixName("S: // DATA_MODE_STRAIGHT = 0 - //} + // } - //public enum SortDirection { + // public enum SortDirection { // Ascending = 1, // Descending = -1, // None = 0 - //} + // } } //#region Prototype Interfaces for Class definitions @@ -1957,8 +1963,8 @@ declare namespace EngineAPI { qCalcCond: IValueExpr; qSortbyYValue: string; - qPseudoDimPos: number; //?Dokufehler - qReductionMode: ReductionModeType; //?Dokufehler + qPseudoDimPos: number; // ?Dokufehler + qReductionMode: ReductionModeType; // ?Dokufehler } interface IVisualizationHyperCubeDef extends IHyperCubeDef { @@ -2059,7 +2065,7 @@ declare namespace EngineAPI { interface IBookmarkListDef { qType: "bookmark"; - // qData: //?nicht dokumentiert + // qData: nicht dokumentiert // example from websocket // qData: { title: "/qMetaDef/title", description: "/qMetaDef/description", sheetId: "/sheetId", title: "/qMetaDef/title" } } @@ -2101,7 +2107,7 @@ declare namespace EngineAPI { interface IMeasureListDef { qType: "measure"; - // qData: INxMeasure[]; //?nicht dokumentiert + // qData: INxMeasure[]; nicht dokumentiert // example from websocket // qData : { title: "/qMetaDef/title", tags: "/qMetaDef/tags" } } @@ -2143,7 +2149,7 @@ declare namespace EngineAPI { interface IDimensionListDef { qType: "dimension"; - //qData: INxDimension[]; //?nicht dokumentiert + // qData: INxDimension[]; nicht dokumentiert } interface IDimensionListObject extends IGenericObject { @@ -2167,7 +2173,7 @@ declare namespace EngineAPI { qIsReserved?: boolean; qMeta?: INxMeta; qInfo: INxInfo; - qData: any; //?nicht dokumentiert + qData: any; // ? nicht dokumentiert qIsScriptCreated: boolean; } @@ -2187,7 +2193,7 @@ declare namespace EngineAPI { qType: string; qShowReserved: boolean; qShowConfig: boolean; - qData: any; //?nicht dokumentiert + qData: any; // ?nicht dokumentiert } interface IVariableListObject extends IGenericObject { @@ -2271,23 +2277,3 @@ declare namespace EngineAPI { } } //#endregion - -// extens the AppAPI Namespace with the access of the EnigmaModel - -declare namespace AppAPI { - interface IApp { - model: IModel; - } - - interface IModel { - enigmaModel: Enigma.IApp; - } -} - -declare namespace ExtensionAPI { - - interface IExtensionModel { - enigmaModel: Enigma.IGenericObject; - } - -} \ No newline at end of file diff --git a/types/qlik-engineapi/qlik-engineapi-tests.ts b/types/qlik-engineapi/qlik-engineapi-tests.ts index e69de29bb2..3484d95073 100644 --- a/types/qlik-engineapi/qlik-engineapi-tests.ts +++ b/types/qlik-engineapi/qlik-engineapi-tests.ts @@ -0,0 +1 @@ +let app: EngineAPI.IApp; diff --git a/types/qlik-engineapi/tslint.json b/types/qlik-engineapi/tslint.json index cae1bdf2ad..9a48ae7955 100644 --- a/types/qlik-engineapi/tslint.json +++ b/types/qlik-engineapi/tslint.json @@ -1,8 +1,8 @@ -{ - "extends": "../tslint.json", +{ + "extends": "dtslint/dt.json", "rules": { - "forbidden-types": false, + "ban-types": false, "no-empty-interface": false, "interface-name": false } -} \ No newline at end of file +} From 686775b8d68234997d45ea5b1b48d01af422f2b1 Mon Sep 17 00:00:00 2001 From: Zebulon McCorkle Date: Tue, 27 Jun 2017 19:07:05 -0400 Subject: [PATCH 0009/1139] Add extremely alpha typings for http-proxy-middleware --- .../http-proxy-middleware-tests.ts | 23 +++++++ types/http-proxy-middleware/index.d.ts | 67 +++++++++++++++++++ types/http-proxy-middleware/tsconfig.json | 22 ++++++ 3 files changed, 112 insertions(+) create mode 100644 types/http-proxy-middleware/http-proxy-middleware-tests.ts create mode 100644 types/http-proxy-middleware/index.d.ts create mode 100644 types/http-proxy-middleware/tsconfig.json diff --git a/types/http-proxy-middleware/http-proxy-middleware-tests.ts b/types/http-proxy-middleware/http-proxy-middleware-tests.ts new file mode 100644 index 0000000000..db331eec3d --- /dev/null +++ b/types/http-proxy-middleware/http-proxy-middleware-tests.ts @@ -0,0 +1,23 @@ +// Derived from https://github.com/chimurai/http-proxy-middleware#example + +import * as express from 'express'; +import * as proxy from 'http-proxy-middleware'; + +const options = { + target: 'http://www.example.org', + changeOrigin: true, + ws: true, + pathRewrite: { + '^/api/old-path': '/api/new-path', + '^/api/remove/path': '/path' + }, + router: { + 'dev.localhost:3000': 'http://localhost:8000' + } +}; + +const myProxy = proxy(options); + +const app = express(); +app.use('/api', myProxy); +app.listen(3000); diff --git a/types/http-proxy-middleware/index.d.ts b/types/http-proxy-middleware/index.d.ts new file mode 100644 index 0000000000..516ba72709 --- /dev/null +++ b/types/http-proxy-middleware/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for http-proxy-middleware +// Project: https://github.com/chimurai/http-proxy-middleware +// Definitions by: Zebulon McCorkle +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +/// + +import * as http from 'http'; +import * as net from 'net'; +import * as tls from 'tls'; +import * as connect from 'connect'; + +declare function proxy(config: proxy.Config): proxy.Proxy; +declare function proxy(contextOrUri: string, config: proxy.Config): proxy.Proxy; + +declare namespace proxy { + type Logger = (...objs: any[]) => void; + export interface LogProvider { + log: Logger, + debug?: Logger, + info?: Logger, + warn?: Logger, + error?: Logger, + } + + export interface Config { + pathRewrite?: { [regexp: string]: string } | ((path: string, req: http.IncomingMessage) => string), + router?: { [hostOrPath: string]: string } | ((req: http.IncomingMessage) => string), + logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent', + logProvider?: (provider: LogProvider) => LogProvider, + + onError?: connect.HandleFunction, + onProxyRes?: (proxyRes: http.ServerResponse, req: http.IncomingMessage, res: http.ServerResponse) => void, + onProxyReq?: (proxyReq: http.ClientRequest, req: http.IncomingMessage, res: http.ServerResponse) => void, + onProxyReqWs?: (proxyReq: http.ClientRequest, req: http.IncomingMessage, socket: any, options: any, head: any) => void, // TODO: Figure out the types of the last 3 + onOpen?: (proxySocket: net.Socket) => void, + onClose?: (res: http.ServerResponse, socket: net.Socket) => void, + + target?: string, + forward?: string, + agent?: http.Agent, + ssl?: tls.TlsOptions, + ws?: boolean, + xfwd?: boolean, + secure?: boolean, + toProxy?: boolean, + prependPath?: boolean, + ignorePath?: boolean, + localAddress?: string, + changeOrigin?: boolean, + auth?: string, + hostRewrite?: any, // TODO + autoRewrite?: any, // TODO + protocolRewrite?: any, // TODO + cookieDomainRewrite?: false | string | { [domain: string]: string }, + headers?: { [header: string]: string }, + proxyTimeout?: number, + } + + export interface Proxy extends connect.NextHandleFunction { + + } +} + +export = proxy; diff --git a/types/http-proxy-middleware/tsconfig.json b/types/http-proxy-middleware/tsconfig.json new file mode 100644 index 0000000000..1fa2b32d6d --- /dev/null +++ b/types/http-proxy-middleware/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "http-proxy-middleware-tests.ts" + ] +} From 8869554ffe7a46177a1856c202cd9c7898492439 Mon Sep 17 00:00:00 2001 From: Ifiok Jr Date: Sun, 9 Jul 2017 15:48:19 +0100 Subject: [PATCH 0010/1139] initial additions for react-native-fbsdk --- types/react-native-fbsdk/index.d.ts | 1039 +++++++++++++++++ .../react-native-fbsdk-tests.tsx | 36 + types/react-native-fbsdk/tsconfig.json | 24 + types/react-native-fbsdk/tslint.json | 1 + 4 files changed, 1100 insertions(+) create mode 100644 types/react-native-fbsdk/index.d.ts create mode 100644 types/react-native-fbsdk/react-native-fbsdk-tests.tsx create mode 100644 types/react-native-fbsdk/tsconfig.json create mode 100644 types/react-native-fbsdk/tslint.json diff --git a/types/react-native-fbsdk/index.d.ts b/types/react-native-fbsdk/index.d.ts new file mode 100644 index 0000000000..c27fdb7671 --- /dev/null +++ b/types/react-native-fbsdk/index.d.ts @@ -0,0 +1,1039 @@ +// Type definitions for react-native-fbsdk 0.6 +// Project: https://github.com/facebook/react-native-fbsdk +// Definitions by: Ifiok Jr. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { ComponentClass, Component } from 'react'; +import { StyleSheet } from 'react-native'; +import { LoginManager } from 'react-native-fbsdk'; +declare namespace FBSDK { + /** + * Specifies the privacy of a group. + */ + type AppGroupPrivacy = + // Anyone can see the group, who's in in and what members post. + 'Open' | + // Anyone can see the group and who's in it, but only members can see posts. + 'Closed'; + + /** + * A model for app invites. + */ + interface AppGroupCreationContent { + /** + * The description of the group. + */ + description: string; + + /** + * The name of the group. + */ + name: string; + + /** + * The privacy for the group. + */ + privacy: AppGroupPrivacy; + } + + /** + * A model for app invites. + */ + interface AppInviteContent { + /** + * A URL to a preview image that will be displayed with the app invite. + * This is optional. If you don't include it, a fallback image will be used. + */ + previewImageUrl?: string; + + /** + * An app link target that will be used as a target when the user accepts the invite. + */ + applinkUrl: string; + + /** + * Promotional code to be displayed while sending and receiving the invite. + * This is optional. This can be between 0 and 10 characters long and can contain + * alphanumeric characters only. To set a promo code, you need to set promo text. + */ + promotionCode?: string; + + /** + * Promotional text to be displayed while sending and receiving the invite. + * This is optional. This can be between 0 and 80 characters long and can contain + * alphanumeric and spaces only. + */ + promotionText?: string; + } + + type GameRequestActionType = + // The user is sending an object to their friends. + 'send' | + // The user is asking for an object from friends. + 'askfor' | + // It is the turn of the friends to play against the user in a match. + 'turn'; + + type GameRequestFilters = + // Friends using the app can be displayed. + 'app_users' | + // Friends not using the app can be displayed. + 'app_non_users'; + + /** + * A model for a game request. + */ + interface GameRequestContent { + /** + * A plain-text message to be sent as part of the request. Required. + */ + message: string; + + /** + * Used when defining additional context about the nature of the request. + * The parameter 'objectID' is required if the action type is either 'send' or 'ask-for'. + */ + actionType?: GameRequestActionType; + + /** + * Additional freeform data you may pass for tracking. The maximum length is 255 characters. + */ + data?: string; + + /** + * Controls the set of friends someone sees if a multi-friend selector is shown. + */ + filters?: GameRequestFilters; + + /** + * The Open Graph object ID of the object being sent/asked for. This cannot be null for ActionType SEND and + * ASKFOR. + */ + objectId?: string; + + /** + * An array of user IDs, usernames or invite tokens of people to send requests to. + */ + recipients?: string[]; + + /** + * An array of user IDs that will be included in the dialog as the first suggested friends. + * Can't be used together with filters. + */ + suggestions?: string[]; + + /** + * The title for the dialog. + */ + title?: string; + } + + type ObjectIdActionType = 'unknown' | 'open_graph' | 'page'; + + /** + * A base interface for content to be shared. + */ + interface ObjectIdAndType { + /** + * The object ID, this can be a URL or a Facebook ID. + */ + objectId: string; + + /** + * Encapsulates the valid values for the facebook:object_type + * attribute for a LikeView + */ + objectType: ObjectIdActionType; + } + + type ShareContent = ShareLinkContent | SharePhotoContent | ShareVideoContent | ShareOpenGraphContent; + /** + * A base interface for content to be shared. + */ + interface ShareContentCommonParameters { + /** + * List of IDs for taggable people to tag with this content. + */ + peopleIds?: string[]; + + /** + * The ID for a place to tag with this content. + */ + placeId?: string; + + /** + * A value to be added to the referrer URL when a person follows a link from + * this shared content on feed. + */ + ref?: string; + + /** + * A hashtag to be added to the share interface. The hashtag must be 32 characters or less. + */ + hashtag?: string; + } + + /** + * A model for status and link content to be shared. + */ + interface ShareLinkContent { + /** + * The type of content to be shared is link. + */ + contentType: 'link'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl: string; + + /** + * The Description of the link. + * If not specified, this field is automatically populated by information scraped + * from the contentURL, typically the title of the page. + * @deprecated `contentDescription` is deprecated from Graph API 2.9. + * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. + */ + contentDescription?: string; + + /** + * The title to display for this link. + * @deprecated `contentTitle` is deprecated from Graph API 2.9. + * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. + */ + contentTitle?: string; + + /** + * The URL of a picture to attach to this comment. + * @deprecated `imageUrl` is deprecated from Graph API 2.9. + * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. + */ + imageUrl?: string; + + /** + * The predefined quote to attach to this comment. + * If specified, the quote text will render with custom styling on top of the link. + */ + quote?: string; + } + + interface OpenGraphProperties { + [key: string]: OpenGraphValue; + } + + interface OpenGraphValue { + type: OpenGraphValueType; + + value: any; + } + + type OpenGraphValueType = + 'number' | + 'open-graph-object' | + 'photo' | + 'string'; + + interface ShareOpenGraphValueContainer { + /** + * Sets a number for the specified key. + */ + // tslint:disable-next-line:variable-name + putNumber(key: string, number: number): void; + + /** + * Sets an open graph object for the specified key. + */ + putObject(key: string, object: ShareOpenGraphValueContainer): void; + + /** + * Sets a photo for the specified key. + */ + putPhoto(key: string, photo: SharePhoto): void; + + /** + * Sets a string for the specified key. + */ + // tslint:disable-next-line:variable-name + putString(key: string, string: string): void; + + /** + * Gets an entry for the given key. + */ + getEntry(key: string): OpenGraphValue; + } + + /** + * Represents an interface for adding and retrieving values to open graph objects and actions. + */ + class ShareOpenGraphValueContainer { + private _properties: OpenGraphProperties; + + constructor(properties: OpenGraphProperties); + } + + /** + * Represents an open graph action. + */ + class ShareOpenGraphAction extends ShareOpenGraphValueContainer { + /** + * The action type. + */ + actionType: string; + + constructor(actionType: string); + } + + /** + * Represents a content object containing information about an Open Graph Action. + */ + interface ShareOpenGraphContent { + /** + * The type of content to be shared is open graph content. + */ + contentType: 'open-graph'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl?: string; + + /** + * Open Graph Action to be shared. + */ + action: ShareOpenGraphAction; + + /** + * Property name that points to the primary Open Graph Object in the action. + */ + previewPropertyName: string; + } + + /** + * Represents an open graph object. + */ + class ShareOpenGraphObject extends ShareOpenGraphValueContainer {} + + /** + * A photo for sharing. + */ + interface SharePhoto { + /** + * The URL to the photo. + * Note that when sharing SharePhotoContent with Share Button, the imageUrl + * of a SharePhoto cannot be the Uri of an image on the web. + */ + imageUrl: string; + + /** + * Specifies whether the photo was generated by the user or the application. + */ + userGenerated?: boolean; + + /** + * The user generated caption for the photo. Note that the 'caption' must + * come from the user, as pre-filled content is forbidden by the platform + * Policies (2.3). + */ + caption?: string; + } + + /** + * A model for photo content to be shared. + */ + interface SharePhotoContent { + /** + * The type of content to be shared is photo. + */ + contentType: 'photo'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl?: string; + + /** + * Photos to be shared. + */ + photos: SharePhoto[]; + } + + /** + * A video for sharing. + */ + interface ShareVideo { + /** + * The URL to the video. Must point to the location of the video on disk. + */ + localUrl: string; + } + + /** + * A model for video content to be shared. + */ + interface ShareVideoContent { + /** + * The type of content to be shared is photo. + */ + contentType: 'video'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl?: string; + + /** + * Video to be shared. + */ + video: ShareVideo; + + /** + * Description of the video. + */ + contentDescription?: string; + + /** + * Title of the video. + */ + contentTitle?: string; + + /** + * The photo that represents the video. + */ + previewPhoto?: SharePhoto; + } + + interface AccessTokenMap { + accessToken: string; + applicationID: string; + userID: string; + permissions: string[]; + declinedPermissions: string[]; + accessTokenSource?: string; + expirationTime: number; + lastRefreshTime: number; + } + + /** + * Represents an immutable access token for using Facebook services. + */ + class AccessToken { + /** + * The access token string. + */ + accessToken: string; + + /** + * The app ID. + */ + applicationID: string; + + /** + * The user ID. + */ + userID: string; + + /** + * The known granted permissions. + */ + permissions: string[]; + + /** + * The known declined permissions. + */ + declinedPermissions: string[]; + + /** + * The source of access token. + * @platform android + */ + accessTokenSource?: string; + + /** + * The expiration time of the access token. + * The value is the number of milliseconds since Jan. 1, 1970, midnight GMT. + */ + expirationTime: number; + + /** + * The last refresh time of the access token. + * The value is the number of milliseconds since Jan. 1, 1970, midnight GMT. + */ + lastRefreshTime: number; + /** + * Getter for the access token that is current for the application. + */ + static getCurrentAccessToken(): Promise; + + /** + * Setter for the access token that is current for the application. + */ + static setCurrentAccessToken(accessToken: AccessTokenMap): void; + + /** + * Updates the current access token with up to date permissions, + * and extends the expiration date, if extension is possible. + */ + + static refreshCurrentAccessTokenAsync(): Promise; + + constructor(tokenMap: AccessTokenMap); + + /** + * Gets the date at which the access token expires. The value is the number of + * milliseconds since Jan. 1, 1970, midnight GMT. + */ + getExpires(): number; + + /** + * Get the list of permissions associated with this access token. Note that the most up-to-date + * list of permissions is maintained by Facebook, so this list may be outdated if permissions + * have been added or removed since the time the AccessToken object was created. See + * https://developers.facebook.com/docs/reference/login/#permissions for details. + */ + getPermissions(): string[]; + + /** + * Gets the list of permissions declined by the user with this access token. It represents the + * entire set of permissions that have been requested and declined. Note that the most + * up-to-date list of permissions is maintained by Facebook, so this list may be outdated if + * permissions have been granted or declined since the last time an AccessToken object was + * created. See https://developers.facebook.com/docs/reference/login/#permissions for details. + */ + getDeclinedPermissions(): string[]; + + /** + * Gets the date at which the token was last refreshed. Since tokens expire, the Facebook SDK + * will attempt to renew them periodically. The value is the number of milliseconds since + * Jan. 1, 1970, midnight GMT. + */ + getLastRefresh(): number; + + /** + * Gets the ID of the Facebook Application associated with this access token. + */ + getApplicationId(): string; + + /** + * Gets user ID associated with this access token. + */ + getUserId(): string; + } + + /** + * Controls when an AppEventsLogger sends log events to the server + */ + type AppEventsFlushBehavior = + /** + * Flush automatically: periodically (every 15 seconds or after every 100 events), and + * always at app reactivation. This is the default value. + */ + 'auto' | + /** + * Only flush when AppEventsLogger.flush() is explicitly invoked. + */ + 'explicity-only'; + + interface Params { + [key: string]: string | number; + } + + interface AppEventsLogger { + /** + * Sets the current event flushing behavior specifying when events + * are sent back to Facebook servers. + */ + setFlushBehavior(flushBehavior: AppEventsFlushBehavior): void; + + /** + * Logs an event with eventName and optional arguments. + * This function supports the following usage: + * logEvent(eventName: string); + * logEvent(eventName: string, valueToSum: number); + * logEvent(eventName: string, parameters: {[key:string]:string|number}); + * logEvent(eventName: string, valueToSum: number, parameters: {[key:string]:string|number}); + * See https://developers.facebook.com/docs/app-events/android for detail. + */ + logEvent(eventName: string, ...args: Array): void; + + /** + * Logs a purchase. See http://en.wikipedia.org/wiki/ISO_4217 for currencyCode. + */ + logPurchase(purchaseAmount: number, currencyCode: string, parameters?: object): void; + + /** + * Logs an app event that tracks that the application was open via Push Notification. + */ + logPushNotificationOpen(payload?: object): void; + + /** + * Explicitly kicks off flushing of events to Facebook. + */ + flush(): void; + + /** + * For iOS only, sets and sends device token to register the current application for push notifications. + * @platform ios + */ + setPushNotificationsDeviceToken(deviceToken: string): void; + + /** + * For Android only, sets and sends registration id to register the current app for push notifications. + * @platform Android + */ + setPushNotificationsRegistrationId(registrationId: string): void; + } + + const AppEventsLogger: AppEventsLogger; + + interface AppInviteDialog { + /** + * Check if the dialog can be shown. + */ + canShow(): Promise; + + /** + * Shows the dialog using the specified content. + */ + show(appInviteContent: AppInviteContent): Promise; + } + + const AppInviteDialog: AppInviteDialog; + + interface GameRequestDialog { + /** + * Check if the dialog can be shown. + */ + canShow(): Promise; + + /** + * Shows the dialog using the specified content. + */ + show(gameRequestContent: GameRequestContent): Promise; + } + + const GameRequestDialog: GameRequestDialog; + + type GraphRequestCallback = (error?: object, result?: object) => void; + interface GraphRequestConfig { + /** + * The httpMethod to use for the request, for example "GET" or "POST". + */ + httpMethod?: string; + /** + * The Graph API version to use (e.g., "v2.0") + */ + version?: string; + /** + * The request parameters. + */ + parameters?: GraphRequestParameters; + /** + * The access token used by the request. + */ + accessToken?: string; + } + + interface GraphRequestParameters { + [key: string]: object; + } + + /** + * Represents a Graph API request and provides batch request supports. + */ + class GraphRequest { + /** + * The Graph API endpoint to use for the request, for example "me". + */ + graphPath: string; + + /** + * The optional config for the request. + */ + config?: GraphRequestConfig; + + /** + * Called upon completion or failure of the request. + */ + callback?: GraphRequestCallback; + + /** + * Constructs a new Graph API request. + */ + constructor(graphPath: string, config?: GraphRequestConfig | null, callback?: GraphRequestCallback); + + /** + * Adds a string parameter to the request. + */ + addStringParameter(paramString: string, key: string): void; + } + + class GraphRequestManager { + requestBatch: GraphRequest[]; + requestCallbacks: Array; + batchCallback: GraphRequestCallback; + constructor(); + + /** + * Add a graph request. + */ + addRequest(request: GraphRequest): GraphRequestManager; + + /** + * Add call back to the GraphRequestManager. Only one callback can be added. + * Note that invocation of the batch callback does not indicate success of every + * graph request made, only that the entire batch has finished executing. + */ + addBatchCallback(callback: GraphRequestCallback): GraphRequestManager; + + /** + * Executes requests in a batch. + * Note that when there's an issue with network connection the batch callback + * behavior differs in Android and iOS. + * On iOS, the batch callback returns an error if the batch fails with a network error. + * On Android, the batch callback always returns {"result": "batch finished executing"} + * after the batch time out. This is because detecting network status requires + * extra permission and it's unncessary for the sdk. Instead, you can use the NetInfo module + * in react-native to get the network status. + */ + start(timeout?: number): void; + } + + type AuxiliaryViewPosition = 'top' | 'bottom' | 'inline'; + type HorizontalAlignment = 'center' | 'left' | 'right'; + type LikeViewStyle = 'button'| // Note 'button' is only available on Android. + 'standard' | + 'box_count'; + + interface LikeViewProps { + /** + * The objectId and type for the object to like. + */ + objectIdAndType: ObjectIdAndType; + + /** + * The style to use for the receiver. Distinct from React styling. + */ + likeViewStyle?: LikeViewStyle; + + /** + * The position for the auxiliary view for the receiver. + */ + auxiliaryViewPosition?: AuxiliaryViewPosition; + + /** + * The text alignment of the social sentence. + */ + horizontalAlignment?: HorizontalAlignment; + + /** + * The foreground color to use for the content of the receiver. + */ + foregroundColor?: number; + + /** + * If true, a sound is played when the receiver is toggled. + */ + soundEnabled?: boolean; + + /** + * View style, if any. + */ + style?: StyleSheet.Style; + } + + class LikeView extends Component {} + + type TooltipBehaviorIOS = 'auto' | 'force_display' | 'disable'; + + interface LoginButtonProps { + /** + * Represents the read permissions to request when the login button + * is pressed. + */ + readPermissions?: string[]; + + /** + * Represents the publish permissions to request when the login + * button is pressed. + */ + publishPermissions?: string[]; + + /** + * The callback invoked upon error/completion of a login request. + */ + onLoginFinished?(error: object, result: LoginResult): void; + + /** + * The callback invoked upon completion of a logout request. + */ + onLogoutFinished?(): void; + + /** + * The behavior to use when attempting a login. + * @platform android + */ + loginBehaviorAndroid?: LoginBehaviorAndroid; + + /** + * The behavior to use when attempting a login. + * @platform ios + */ + loginBehaviorIOS?: LoginBehaviorIOS; + + /** + * The default audience to target when attempting a login. + */ + defaultAudience?: DefaultAudience; + + /** + * For iOS only, the desired tooltip behavior. + * @platform ios + */ + tooltipBehaviorIOS?: TooltipBehaviorIOS; + + /** + * View style, if any. + */ + style?: StyleSheet.Style; + } + + class LoginButton extends Component { + private _eventHandler(event: object): void; + } + + /** + * Indicates which default audience to use for sessions that post data to Facebook. + */ + type DefaultAudience = + // Indicates that the user's friends are able to see posts made by the application. + 'friends' | + // Indicates that all Facebook users are able to see posts made by the application. + 'everyone' | + // Indicates that only the user is able to see posts made by the application. + 'only_me'; + + type LoginBehavior = LoginBehaviorIOS | LoginBehaviorAndroid; + + /** + * Indicate how Facebook Login should be attempted on Android. + */ + type LoginBehaviorAndroid = + // Attempt login in using the Facebook App, and if that does not work fall back to web dialog auth. + 'native_with_fallback'| + // Only attempt to login using the Facebook App. + 'native_only'| + // Only the web dialog auth should be used. + 'web_only'; + + /** + * Indicate how Facebook Login should be attempted on iOS. + */ + type LoginBehaviorIOS = + // Attempts log in through the native Facebook app. + // The SDK may still use Safari instead. + // See details in https://developers.facebook.com/blog/post/2015/10/29/Facebook-Login-iOS9/ + 'native' | + // Attempts log in through the Safari browser. + 'browser' | + // Attempts log in through the Facebook account currently signed in through Settings. + 'system_account' | + // Attempts log in through a modal UIWebView pop-up. + 'web'; + + /** + * Shows the results of a login operation. + */ + interface LoginResult { + isCancelled: boolean; + grantedPermissions?: string[]; + declinedPermissions?: string[]; + } + + interface LoginManager { + /** + * Logs the user in with the requested read permissions. + */ + logInWithReadPermissions(permissions: string[]): Promise; + + /** + * Logs the user in with the requested publish permissions. + */ + logInWithPublishPermissions(permissions: string[]): Promise; + + /** + * Getter for the login behavior. + */ + getLoginBehavior(): Promise; + + /** + * Setter for the login behavior. + */ + setLoginBehavior(loginBehavior: LoginBehavior): void; + + /** + * Getter for the default audience. + */ + getDefaultAudience(): Promise; + + /** + * Setter for the default audience. + */ + setDefaultAudience(defaultAudience: DefaultAudience): void; + + /** + * Logs out the user. + */ + logOut(): void; + } + + const LoginManager: LoginManager; + + interface MessageDialog { + /** + * Check if the dialog can be shown. + */ + canShow(shareContent: ShareContent): Promise; + + /** + * Shows the dialog using the specified content. + */ + show(shareContent: ShareContent): Promise; + + /** + * Sets whether or not the native message dialog should fail when it encounters a data error. + */ + setShouldFailOnDataError(shouldFailOnDataError: boolean): void; + } + + const MessageDialog: MessageDialog; + + interface SendButtonProps { + /** + * Content to be shared. + */ + shareContent: ShareContent; + + /** + * View style, if any. + */ + style?: StyleSheet.Style; + } + + class SendButton extends Component {} + + interface ShareApi { + /** + * Check if the content can be shared via share api. + */ + canShare(shareContent: ShareContent): Promise; + + /** + * For iOS only, creates a User Owned Open Graph object without an action. + * NOTE: Only one share action can be performed at a time. + * @platform ios + */ + createOpenGraphObject(openGraphObject: ShareOpenGraphObject): Promise; + + /** + * Shares the specified content with a message. + * NOTE: Only one share action can be performed at a time. + */ + share(shareContent: ShareContent, graphNode: string, message: string): Promise; + } + + const ShareApi: ShareApi; + + interface ShareButtonProps { + /** + * Content to be shared. + */ + shareContent: ShareContent; + + /** + * View style, if any. + */ + style?: StyleSheet.Style; + } + + class ShareButton extends Component {} + + type ShareDialogMode = ShareDialogModeIOS | ShareDialogModeAndroid; + type ShareDialogModeAndroid = + /** + * The mode is determined automatically. + */ + 'automatic'| + /** + * The native dialog is used. + */ + 'native'| + /** + * The web dialog is used. + */ + 'web'| + /** + * The feed dialog is used. + */ + 'feed'; + type ShareDialogModeIOS = + /* + * Acts with the most appropriate mode that is available. + */ + 'automatic'| + /* + * Displays the dialog in Safari. + */ + 'browser'| + /* + * Displays the dialog in a UIWebView within the app. + */ + 'webview'; + + interface ShareDialog { + /** + * Check if the dialog can be shown. + */ + canShow(shareContent: ShareContent): Promise; + + /** + * Shows the dialog using the specified content. + */ + show(shareContent: ShareContent): Promise; + + /** + * Sets the mode for the share dialog. + */ + setMode(mode: ShareDialogMode): void; + + /** + * Sets whether or not the native share dialog should fail when it encounters a data error. + */ + setShouldFailOnDataError(shouldFailOnDataError: boolean): void; + } + + const ShareDialog: ShareDialog; +} +export as namespace FBSDK; +// tslint:disable-next-line:export-just-namespace +export = FBSDK; diff --git a/types/react-native-fbsdk/react-native-fbsdk-tests.tsx b/types/react-native-fbsdk/react-native-fbsdk-tests.tsx new file mode 100644 index 0000000000..a6334f2cfc --- /dev/null +++ b/types/react-native-fbsdk/react-native-fbsdk-tests.tsx @@ -0,0 +1,36 @@ +import * as React from 'react'; +import * as FBSDK from 'react-native-fbsdk'; +import { View } from 'react-native'; +import render from '../react-dom/index'; + +const { + LoginButton, + AccessToken +} = FBSDK; + +class Login extends React.Component { + render() { + return ( + + { + if (error) { + alert("login has error: " + result.error); + } else if (result.isCancelled) { + alert("login is cancelled."); + } else { + AccessToken.getCurrentAccessToken().then( + (data) => { + alert(data.accessToken.toString()) + } + ); + } + } + } + onLogoutFinished={() => alert("logout.")}/> + + ); + } +} diff --git a/types/react-native-fbsdk/tsconfig.json b/types/react-native-fbsdk/tsconfig.json new file mode 100644 index 0000000000..52ea75b5cb --- /dev/null +++ b/types/react-native-fbsdk/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-native-elements-tests.tsx" + ] +} diff --git a/types/react-native-fbsdk/tslint.json b/types/react-native-fbsdk/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-fbsdk/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 9ef6dc6a7b40bc8fd86ec6e580deda94652668c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciar=C3=A1n=20Curley?= Date: Mon, 10 Jul 2017 13:04:34 +0100 Subject: [PATCH 0011/1139] Flesh out Subscriable type to better match ES Observable spec --- types/recompose/index.d.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 3e3d6b85ae..ee99adca68 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -16,8 +16,18 @@ declare module 'recompose' { type mapper = (input: TInner) => TOutter; type predicate = mapper; type predicateDiff = (current: T, next: T) => boolean + interface Observer { + next(value: T): void; + error(err: any): void; + complete(): void; + } + + interface Subscription { + unsubscribe(): void; + closed: boolean; + } interface Subscribable { - subscribe: Function; + subscribe(observer: Observer):Subscription; } interface ComponentEnhancer { From 7db3bd0d08ef03c278ac6311fb5a3d062e9d5473 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciar=C3=A1n=20Curley?= Date: Mon, 10 Jul 2017 16:29:21 +0100 Subject: [PATCH 0012/1139] Was able to simplfy things --- types/recompose/index.d.ts | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index ee99adca68..6b84b33034 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -15,19 +15,10 @@ declare module 'recompose' { type Component

= ComponentClass

| StatelessComponent

; type mapper = (input: TInner) => TOutter; type predicate = mapper; - type predicateDiff = (current: T, next: T) => boolean - interface Observer { - next(value: T): void; - error(err: any): void; - complete(): void; - } + type predicateDiff = (current: T, next: T) => boolean} - interface Subscription { - unsubscribe(): void; - closed: boolean; - } interface Subscribable { - subscribe(observer: Observer):Subscription; + subscribe(observer: any):any; } interface ComponentEnhancer { From d58e9e015a85b38180c0c15a15dc2d15076d6175 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciar=C3=A1n=20Curley?= Date: Mon, 10 Jul 2017 16:45:11 +0100 Subject: [PATCH 0013/1139] Fix CI Fail; forgot Ctrl-S on my end --- types/recompose/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index 6b84b33034..dedc360f4d 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -15,7 +15,7 @@ declare module 'recompose' { type Component

= ComponentClass

| StatelessComponent

; type mapper = (input: TInner) => TOutter; type predicate = mapper; - type predicateDiff = (current: T, next: T) => boolean} + type predicateDiff = (current: T, next: T) => boolean interface Subscribable { subscribe(observer: any):any; From e525932a5b6916f01c784763c0e4ee346d5213a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ciar=C3=A1n=20Curley?= Date: Mon, 10 Jul 2017 17:35:23 +0100 Subject: [PATCH 0014/1139] Rewrote again to match observable found in componentFromStream --- types/recompose/index.d.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index dedc360f4d..09c8d6a59d 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -17,8 +17,17 @@ declare module 'recompose' { type predicate = mapper; type predicateDiff = (current: T, next: T) => boolean + interface Observer{ + next(props: T): void; + complete(): void; + } + + interface Subscription{ + unsubscribe(): void + } + interface Subscribable { - subscribe(observer: any):any; + subscribe(observer: Observer): Subscription; } interface ComponentEnhancer { From 4eb2295312495f57b8405eea37f57165c8ddae17 Mon Sep 17 00:00:00 2001 From: Neek Sandhu Date: Tue, 11 Jul 2017 22:17:11 -0700 Subject: [PATCH 0015/1139] Add types for css-modules Enables users to `import styles from '../main.css'` in your TypeScript files. From there on, assuming user is using `webpack` with `css-loader`, they can also do `styles.toString()` or `classNames(styles.productLabel...` without any squiggly lines, instead works with intellisense beautifully (both of ops have `string` as return type) --- types/css-modules/css-modules-tests.ts | 21 +++++++++++++++++++++ types/css-modules/index.d.ts | 16 ++++++++++++++++ types/css-modules/tsconfig.json | 22 ++++++++++++++++++++++ 3 files changed, 59 insertions(+) create mode 100644 types/css-modules/css-modules-tests.ts create mode 100644 types/css-modules/index.d.ts create mode 100644 types/css-modules/tsconfig.json diff --git a/types/css-modules/css-modules-tests.ts b/types/css-modules/css-modules-tests.ts new file mode 100644 index 0000000000..9456029319 --- /dev/null +++ b/types/css-modules/css-modules-tests.ts @@ -0,0 +1,21 @@ +import styles from './main.css' +import * as classNames from 'classnames' + +class App { + private theme: string + constructor(theme: string) { + this.theme = theme + } + + render() { + // as a style tag (using webpack's css-loader) + const tpl = `

` + // or as scoped unique classes, also latest typescript versions allow prop access using dot like styles.darkUI instead of styles['darkUI'] + return ` +
+
+ ` + } +} diff --git a/types/css-modules/index.d.ts b/types/css-modules/index.d.ts new file mode 100644 index 0000000000..1e9a21823b --- /dev/null +++ b/types/css-modules/index.d.ts @@ -0,0 +1,16 @@ +declare module '*.css' { + type Stringifyable = { + /** + * Stringifies the imported stylesheet for use with inline style tags + */ + toString: () => string + } + type SelectorNode = { + /** + * Returns the specific selector from imported stylesheet as string + */ + [key: string]: string + } + const styles: SelectorNode & Stringifyable + export default styles +} \ No newline at end of file diff --git a/types/css-modules/tsconfig.json b/types/css-modules/tsconfig.json new file mode 100644 index 0000000000..aff10df5a6 --- /dev/null +++ b/types/css-modules/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "css-modules-tests.ts" + ] +} \ No newline at end of file From b69cd5df972b2f5b3664ff28e5ffce7a170afc65 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Thu, 13 Jul 2017 13:55:52 -0700 Subject: [PATCH 0016/1139] - Made the TreeItem.children prop optional since the library allows this and prevents verboseness/unneeded empty arrays - Added 'dom' lib in tsconfig to fix dom errors from definition dependencies when running `tsc` --- types/react-sortable-tree/index.d.ts | 2 +- types/react-sortable-tree/react-sortable-tree-tests.tsx | 2 +- types/react-sortable-tree/tsconfig.json | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/types/react-sortable-tree/index.d.ts b/types/react-sortable-tree/index.d.ts index a7805cd90e..a6a04f4968 100644 --- a/types/react-sortable-tree/index.d.ts +++ b/types/react-sortable-tree/index.d.ts @@ -15,7 +15,7 @@ export interface TreeItem { title?: string; subtitle?: string; expanded?: boolean; - children: TreeItem[]; + children?: TreeItem[]; [x: string]: any; } diff --git a/types/react-sortable-tree/react-sortable-tree-tests.tsx b/types/react-sortable-tree/react-sortable-tree-tests.tsx index 8b89db5196..1a5e2dfcd0 100644 --- a/types/react-sortable-tree/react-sortable-tree-tests.tsx +++ b/types/react-sortable-tree/react-sortable-tree-tests.tsx @@ -21,7 +21,7 @@ class Test extends React.Component { { title: "Title", subtitle: "Subtitle", children: [ {title: "Child 1", subtitle: "Subtitle", children: []}, - {title: "Child 2", subtitle: "Subtitle", children: []} + {title: "Child 2", subtitle: "Subtitle"} ] } ]; diff --git a/types/react-sortable-tree/tsconfig.json b/types/react-sortable-tree/tsconfig.json index f82f976d38..df74da5295 100644 --- a/types/react-sortable-tree/tsconfig.json +++ b/types/react-sortable-tree/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, From 35ed47ed7c2444450bfdcdb926b33dd3f147745e Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Fri, 14 Jul 2017 15:13:25 +0200 Subject: [PATCH 0017/1139] added literal as allowed type for attributes --- types/sequelize/index.d.ts | 2 +- types/sequelize/v3/index.d.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 9ffda92873..de85bd7f54 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -3198,7 +3198,7 @@ declare namespace sequelize { /** * Shortcut for types used in FindOptions.attributes */ - type FindOptionsAttributesArray = Array; + type FindOptionsAttributesArray = Array; /** * Options that are passed to any model creating a SELECT query diff --git a/types/sequelize/v3/index.d.ts b/types/sequelize/v3/index.d.ts index a43a72b770..b86c82ca73 100644 --- a/types/sequelize/v3/index.d.ts +++ b/types/sequelize/v3/index.d.ts @@ -3138,9 +3138,9 @@ declare namespace sequelize { } /** - * Shortcut for types used in FindOptions.attributes - */ - type FindOptionsAttributesArray = Array; + * Shortcut for types used in FindOptions.attributes + */ + type FindOptionsAttributesArray = Array; /** * Options that are passed to any model creating a SELECT query From 05c5f20a7cc66ec2ad510967db41c5a5f3dda035 Mon Sep 17 00:00:00 2001 From: Jan Sziegaud Date: Fri, 14 Jul 2017 16:12:48 +0200 Subject: [PATCH 0018/1139] added missing Option parameter --- types/csv-parse/index.d.ts | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/types/csv-parse/index.d.ts b/types/csv-parse/index.d.ts index cbf79729e5..e85742c1c9 100644 --- a/types/csv-parse/index.d.ts +++ b/types/csv-parse/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for csv-parse 1.1 // Project: https://github.com/wdavidw/node-csv-parse // Definitions by: David Muller +// Jan Sziegaud // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -111,6 +112,16 @@ declare namespace parse { * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. */ auto_parse_date?: boolean; + + /** + * Start returning records from a particular line. + */ + from?: number; + + /** + * Stop returning records after a particular line. + */ + to?: number; } // TODO: what is this for? From cd3aa0e9a7aea9fe4908d90f05c867fb91a96e75 Mon Sep 17 00:00:00 2001 From: Dale Lane Date: Fri, 14 Jul 2017 16:02:24 +0100 Subject: [PATCH 0019/1139] fix: Remove duplicate time property A time property was added in two separate commits: https://github.com/DefinitelyTyped/DefinitelyTyped/commit/d3864ce1 https://github.com/DefinitelyTyped/DefinitelyTyped/commit/814578c0 It looks like these both got merged in at similar times, and both additions ended up making it in. It's breaking some builds for us, so it'd be good to remove one of them. --- types/request/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index 7ae56c10d4..dac5b36e42 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -154,7 +154,6 @@ declare namespace request { ca?: string | Buffer | string[] | Buffer[]; har?: HttpArchiveRequest; useQuerystring?: boolean; - time?: boolean; } interface UriOptions { From 0961f7aec7da4aafa2c90391e115aa9e49ac526e Mon Sep 17 00:00:00 2001 From: Jan Klimke Date: Fri, 14 Jul 2017 18:29:25 +0200 Subject: [PATCH 0020/1139] removed merge markers --- types/sequelize/v3/index.d.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/types/sequelize/v3/index.d.ts b/types/sequelize/v3/index.d.ts index b86c82ca73..0e3a27a4e4 100644 --- a/types/sequelize/v3/index.d.ts +++ b/types/sequelize/v3/index.d.ts @@ -5712,10 +5712,7 @@ declare namespace sequelize { autoCallback: (t: Transaction) => PromiseLike): Promise; transaction(autoCallback: (t: Transaction) => PromiseLike): Promise; transaction(options?: TransactionOptions): Promise; -<<<<<<< HEAD -======= ->>>>>>> 8aff840533088365ab17b7be1bb1b8df3cb35e8a /** * Close all connections used by this sequelize instance, and free all references so the instance can be From cb8a120a17f6b7a1ee5d3552ac0babd11756b293 Mon Sep 17 00:00:00 2001 From: Chris Smith Date: Fri, 14 Jul 2017 09:59:10 -0700 Subject: [PATCH 0021/1139] Adjusted MeasureChildren have more flexible typing - Added React.ReactNode as an accepted children type - Added higher order component test which was the problem case --- types/react-measure/index.d.ts | 7 +++---- types/react-measure/react-measure-tests.tsx | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/types/react-measure/index.d.ts b/types/react-measure/index.d.ts index cbbc928215..c487cd7264 100644 --- a/types/react-measure/index.d.ts +++ b/types/react-measure/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-measure 0.4.0 +// Type definitions for react-measure 0.4 // Project: https://github.com/souporserious/react-measure // Definitions by: Alexey Svetliakov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -19,7 +19,7 @@ declare module "react-measure" { left?: number; } - type MeasureChildren = React.ReactElement | { (dimension: Dimensions): React.ReactElement }; + type MeasureChildren = React.ReactNode | React.ReactElement | ((dimension: Dimensions) => React.ReactElement); interface MeasureProps { /** @@ -43,7 +43,7 @@ declare module "react-measure" { /** * Callback when the component has been mutated. Receives dimensions, mutations, and anything passed to shouldMeasure. */ - onMeasure?: (dimensions: Dimensions) => void; + onMeasure?(dimensions: Dimensions): void; /** * Children, ordinary JSX element or function. Leaving it for reference here */ @@ -51,5 +51,4 @@ declare module "react-measure" { } } export = Measure; - } diff --git a/types/react-measure/react-measure-tests.tsx b/types/react-measure/react-measure-tests.tsx index a12266339f..4c02ba8f07 100644 --- a/types/react-measure/react-measure-tests.tsx +++ b/types/react-measure/react-measure-tests.tsx @@ -34,3 +34,20 @@ class Test2 extends React.Component { ); } } + +function testHocComponent(Component: React.ComponentClass): React.ComponentClass { + return class extends React.Component { + render(): JSX.Element { + return ( + + ; + + ); + } + + private handleDimensionChange = (dimensions: Measure.Dimensions) => { + dimensions.width; + dimensions.height; + } + }; +} From 8f42dfbc91da5f16f4421f27c32f5e108131d6bf Mon Sep 17 00:00:00 2001 From: Nathan Brown Date: Fri, 14 Jul 2017 13:24:38 -0700 Subject: [PATCH 0022/1139] [react-test-renderer] Include update() and getInstance() Added missing functions to definition of `react-test-renderer`. Also renamed `create()` return type to match Flow type name in React repository. --- types/react-test-renderer/index.d.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/types/react-test-renderer/index.d.ts b/types/react-test-renderer/index.d.ts index 6e1d9037cc..a7eb0bf739 100644 --- a/types/react-test-renderer/index.d.ts +++ b/types/react-test-renderer/index.d.ts @@ -6,9 +6,11 @@ import { ReactElement } from "react"; -export interface Renderer { +export interface ReactTestInstance { toJSON(): ReactTestRendererJSON; unmount(nextElement?: ReactElement): void; + update(nextElement: ReactElement): void; + getInstance(): any; } export interface ReactTestRendererJSON { type: string; @@ -20,4 +22,4 @@ export interface TestRendererOptions { createNodeMock(element: ReactElement): any; } // https://github.com/facebook/react/blob/master/src/renderers/testing/ReactTestMount.js#L155 -export function create(nextElement: ReactElement, options?: TestRendererOptions): Renderer; +export function create(nextElement: ReactElement, options?: TestRendererOptions): ReactTestInstance; From 2b46b16e14cbfc52f02806f319529071822669e4 Mon Sep 17 00:00:00 2001 From: Pan Date: Fri, 14 Jul 2017 17:33:36 -0400 Subject: [PATCH 0023/1139] Add rowSpan to table columns Like colSpan, passing rowSpan to table header and row column as they are useful for td/th as well. --- types/material-ui/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index ec7ad246b4..154be283de 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1702,6 +1702,7 @@ declare namespace __MaterialUI { // useful attributes passed to colSpan?: number; + rowSpan?: number; } export class TableRowColumn extends React.Component { } @@ -1732,6 +1733,7 @@ declare namespace __MaterialUI { // useful attributes passed to colSpan?: number; + rowSpan?: number; } export class TableHeaderColumn extends React.Component { } From 5f17d5489bf7b184d9c93bc48cc730f3671f3667 Mon Sep 17 00:00:00 2001 From: Ian Shea Date: Fri, 14 Jul 2017 16:31:28 -0700 Subject: [PATCH 0024/1139] added state definition for components --- types/react-transition-group/CSSTransition.d.ts | 4 +++- types/react-transition-group/Transition.d.ts | 4 +++- types/react-transition-group/TransitionGroup.d.ts | 6 ++++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/types/react-transition-group/CSSTransition.d.ts b/types/react-transition-group/CSSTransition.d.ts index 67b869edf6..0fde6942cb 100644 --- a/types/react-transition-group/CSSTransition.d.ts +++ b/types/react-transition-group/CSSTransition.d.ts @@ -33,6 +33,8 @@ export interface CSSTransitionProps extends TransitionProps { classNames: string | CSSTransitionClassNames; } -declare class CSSTransition extends Component {} +export interface CSSTransitionState {} + +declare class CSSTransition extends Component {} export default CSSTransition; diff --git a/types/react-transition-group/Transition.d.ts b/types/react-transition-group/Transition.d.ts index 24f0265ee2..e1ffb32af3 100644 --- a/types/react-transition-group/Transition.d.ts +++ b/types/react-transition-group/Transition.d.ts @@ -25,6 +25,8 @@ export interface TransitionProps extends TransitionActions { [prop: string]: any; } +export interface TransitionState {} + /** * The Transition component lets you describe a transition from one component * state to another _over time_ with a simple declarative API. Most commonly @@ -66,6 +68,6 @@ export interface TransitionProps extends TransitionActions { * ``` * */ -declare class Transition extends Component {} +declare class Transition extends Component {} export default Transition; diff --git a/types/react-transition-group/TransitionGroup.d.ts b/types/react-transition-group/TransitionGroup.d.ts index 3f04332bc8..3ddc42a16e 100644 --- a/types/react-transition-group/TransitionGroup.d.ts +++ b/types/react-transition-group/TransitionGroup.d.ts @@ -1,4 +1,4 @@ -import { Component, ReactType, HTMLProps, ReactElement } from "react"; +import { Component, HTMLProps, ReactElement, ReactType } from "react"; import { TransitionActions, TransitionProps } from "react-transition-group/Transition"; export interface IntrinsicTransitionGroupProps extends TransitionActions { @@ -14,6 +14,8 @@ export type TransitionGroupProps | Array>; }; +export interface TransitionGroupState {} + /** * The `` component manages a set of `` components * in a list. Like with the `` component, ``, is a @@ -71,6 +73,6 @@ export type TransitionGroupProps {} +declare class TransitionGroup extends Component {} export default TransitionGroup; From e114c62e2f557aac1e8530962fa38ceebce583c7 Mon Sep 17 00:00:00 2001 From: Ian Shea Date: Fri, 14 Jul 2017 16:36:44 -0700 Subject: [PATCH 0025/1139] fixing lint error, passing {} instead of empty interface --- types/react-transition-group/CSSTransition.d.ts | 4 +--- types/react-transition-group/Transition.d.ts | 4 +--- types/react-transition-group/TransitionGroup.d.ts | 4 +--- 3 files changed, 3 insertions(+), 9 deletions(-) diff --git a/types/react-transition-group/CSSTransition.d.ts b/types/react-transition-group/CSSTransition.d.ts index 0fde6942cb..7f0e398756 100644 --- a/types/react-transition-group/CSSTransition.d.ts +++ b/types/react-transition-group/CSSTransition.d.ts @@ -33,8 +33,6 @@ export interface CSSTransitionProps extends TransitionProps { classNames: string | CSSTransitionClassNames; } -export interface CSSTransitionState {} - -declare class CSSTransition extends Component {} +declare class CSSTransition extends Component {} export default CSSTransition; diff --git a/types/react-transition-group/Transition.d.ts b/types/react-transition-group/Transition.d.ts index e1ffb32af3..29bc3e2bde 100644 --- a/types/react-transition-group/Transition.d.ts +++ b/types/react-transition-group/Transition.d.ts @@ -25,8 +25,6 @@ export interface TransitionProps extends TransitionActions { [prop: string]: any; } -export interface TransitionState {} - /** * The Transition component lets you describe a transition from one component * state to another _over time_ with a simple declarative API. Most commonly @@ -68,6 +66,6 @@ export interface TransitionState {} * ``` * */ -declare class Transition extends Component {} +declare class Transition extends Component {} export default Transition; diff --git a/types/react-transition-group/TransitionGroup.d.ts b/types/react-transition-group/TransitionGroup.d.ts index 3ddc42a16e..6aa8cd5bb1 100644 --- a/types/react-transition-group/TransitionGroup.d.ts +++ b/types/react-transition-group/TransitionGroup.d.ts @@ -14,8 +14,6 @@ export type TransitionGroupProps | Array>; }; -export interface TransitionGroupState {} - /** * The `` component manages a set of `` components * in a list. Like with the `` component, ``, is a @@ -73,6 +71,6 @@ export interface TransitionGroupState {} * components. This means you can mix and match animations across different * list items. */ -declare class TransitionGroup extends Component {} +declare class TransitionGroup extends Component {} export default TransitionGroup; From c71499ee1b7e5180d813c079135c97b7b40f2a5d Mon Sep 17 00:00:00 2001 From: Roman Lysogor Date: Fri, 14 Jul 2017 17:09:19 -0700 Subject: [PATCH 0026/1139] Added DraftEditorProps props to improve mobile web behaviors when user typing --- types/draft-js/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index ff52f8932e..1019df8fce 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -102,6 +102,11 @@ declare namespace Draft { tabIndex?: number; + // exposed especially to help improve mobile web behaviors + autoCapitalize?: string; + autoComplete?: string; + autoCorrect?: string; + ariaActiveDescendantID?: string; ariaAutoComplete?: string; ariaDescribedBy?: string; From ead0824c8767750ce7995acc4a93aee1761532bb Mon Sep 17 00:00:00 2001 From: Neek Sandhu Date: Fri, 14 Jul 2017 19:15:34 -0700 Subject: [PATCH 0027/1139] Add DefinitelyTyped headers --- types/css-modules/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/css-modules/index.d.ts b/types/css-modules/index.d.ts index 1e9a21823b..8b65145a52 100644 --- a/types/css-modules/index.d.ts +++ b/types/css-modules/index.d.ts @@ -1,3 +1,8 @@ +// Type definitions for css-modules 1506 +// Project: https://github.com/css-modules/css-modules +// Definitions by: NeekSandhu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + declare module '*.css' { type Stringifyable = { /** @@ -13,4 +18,4 @@ declare module '*.css' { } const styles: SelectorNode & Stringifyable export default styles -} \ No newline at end of file +} From 7225bdcae60bdf8a6f6bcc48ba2af8a81b0cf6ed Mon Sep 17 00:00:00 2001 From: Izik Lisbon Date: Fri, 14 Jul 2017 20:21:08 -0700 Subject: [PATCH 0028/1139] Sequelize: Add to the Table's options to support Optimistic Locking. --- types/sequelize/index.d.ts | 6 ++++++ types/sequelize/sequelize-tests.ts | 15 ++++++++++++++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 9ffda92873..4d41675ba3 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -5094,6 +5094,12 @@ declare namespace sequelize { */ validate?: DefineValidateOptions; + /** + * Enable optimistic locking. When enabled, sequelize will add a version count attribute + * to the model and throw an OptimisticLockingError error when stale instances are saved. + * Set to true or a string with the attribute name you want to use to enable. + */ + version?: boolean | string; } /** diff --git a/types/sequelize/sequelize-tests.ts b/types/sequelize/sequelize-tests.ts index 9000dd92b0..c2a171109f 100644 --- a/types/sequelize/sequelize-tests.ts +++ b/types/sequelize/sequelize-tests.ts @@ -1572,7 +1572,20 @@ s.define( 'test', { underscored : true, freezeTableName : true } ); - +s.define( 'testBooeanVersionOption', { + version : { + type : Sequelize.INTEGER, + } +}, { + version: true +} ); +s.define( 'testStringVersionOption', { + nameOfOptimisticLockColumn : { + type : Sequelize.INTEGER, + } +}, { + version: "nameOfOptimisticLockColumn" +} ); s.define( 'User', { deletedAt : { type : Sequelize.DATE, From dd001458d31ac80fe8ab2ff61b699369700b2fe6 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sat, 15 Jul 2017 10:41:53 +0200 Subject: [PATCH 0029/1139] [svg4everybody] introduce typings --- types/svg4everybody/index.d.ts | 20 +++++++++++++++++++ types/svg4everybody/svg4everybody-tests.ts | 18 +++++++++++++++++ types/svg4everybody/tsconfig.json | 23 ++++++++++++++++++++++ types/svg4everybody/tslint.json | 1 + 4 files changed, 62 insertions(+) create mode 100644 types/svg4everybody/index.d.ts create mode 100644 types/svg4everybody/svg4everybody-tests.ts create mode 100644 types/svg4everybody/tsconfig.json create mode 100644 types/svg4everybody/tslint.json diff --git a/types/svg4everybody/index.d.ts b/types/svg4everybody/index.d.ts new file mode 100644 index 0000000000..fa189a09f6 --- /dev/null +++ b/types/svg4everybody/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for svg4everybody 2.1 +// Project: https://github.com/jonathantneal/svg4everybody#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Svg4everybodyOpts } from "./"; +export as namespace svg4everybody; + +export = svg4everybody; + +declare function svg4everybody(options?: Svg4everybodyOpts): void; + +declare namespace svg4everybody { + interface Svg4everybodyOpts { + fallback?(src: string, svg: SVGElement, use: SVGUseElement): string; + validate?(src: string, svg: SVGElement, use: SVGUseElement): boolean; + nosvg?: boolean; + polyfill?: boolean; + } +} diff --git a/types/svg4everybody/svg4everybody-tests.ts b/types/svg4everybody/svg4everybody-tests.ts new file mode 100644 index 0000000000..2a62a71a24 --- /dev/null +++ b/types/svg4everybody/svg4everybody-tests.ts @@ -0,0 +1,18 @@ +svg4everybody(); + +svg4everybody({ + fallback(src, svg, use) { + return 'fallback.png'; + } +}); + +svg4everybody({ + validate(src, svg, use) { + return true; + } +}); + +svg4everybody({ + nosvg: true, + polyfill: true +}); diff --git a/types/svg4everybody/tsconfig.json b/types/svg4everybody/tsconfig.json new file mode 100644 index 0000000000..ea4012184a --- /dev/null +++ b/types/svg4everybody/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "svg4everybody-tests.ts" + ] +} diff --git a/types/svg4everybody/tslint.json b/types/svg4everybody/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/svg4everybody/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From ecb5ff23f331bfcf5aef80b5a976446efcb950aa Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sat, 15 Jul 2017 10:46:10 +0200 Subject: [PATCH 0030/1139] [svg4everybody] fix import --- types/svg4everybody/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/svg4everybody/index.d.ts b/types/svg4everybody/index.d.ts index fa189a09f6..3b1ec96cff 100644 --- a/types/svg4everybody/index.d.ts +++ b/types/svg4everybody/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { Svg4everybodyOpts } from "./"; +import { Svg4everybodyOpts } from "svg4everybody"; export as namespace svg4everybody; export = svg4everybody; From 5a0d17c112b187d560c81957a313f7db4ad60eb9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= Date: Sat, 15 Jul 2017 17:48:42 +0900 Subject: [PATCH 0031/1139] Add a new package "mersenne-twister" --- types/mersenne-twister/index.d.ts | 47 +++++++++++++++++++ .../mersenne-twister-tests.ts | 23 +++++++++ types/mersenne-twister/tsconfig.json | 25 ++++++++++ types/mersenne-twister/tslint.json | 1 + 4 files changed, 96 insertions(+) create mode 100644 types/mersenne-twister/index.d.ts create mode 100644 types/mersenne-twister/mersenne-twister-tests.ts create mode 100644 types/mersenne-twister/tsconfig.json create mode 100644 types/mersenne-twister/tslint.json diff --git a/types/mersenne-twister/index.d.ts b/types/mersenne-twister/index.d.ts new file mode 100644 index 0000000000..938c8b6b69 --- /dev/null +++ b/types/mersenne-twister/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for mersenne-twister 1.1 +// Project: https://github.com/boo1ean/mersenne-twister +// Definitions by: KentarouTakeda +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = class MersenneTwister { + /** + * constructs mt with a number + * @params seed + */ + constructor(seed?: number|number[]); + + /** + * initializes mt with a number + */ + init_seed(seed: number): void; + + /** + * generates a random number on [0,0xffffffff]-interval + */ + random_int(): number; + + /** + * generates a random number on [0,0x7fffffff]-interval + */ + random_int31(): number; + + /** + * generates a random number on [0,1]-real-interval + */ + random_incl(): number; + + /** + * generates a random number on [0,1)-real-interval + */ + random(): number; + + /** + * generates a random number on (0,1)-real-interval + */ + random_excl(): number; + + /** + * generates a random number on [0,1) with 53-bit resolution + */ + random_long(): number; +}; diff --git a/types/mersenne-twister/mersenne-twister-tests.ts b/types/mersenne-twister/mersenne-twister-tests.ts new file mode 100644 index 0000000000..663f69c49a --- /dev/null +++ b/types/mersenne-twister/mersenne-twister-tests.ts @@ -0,0 +1,23 @@ +import MersenneTwister = require('mersenne-twister'); + +const msWithTime = new MersenneTwister(); +const msWithNumber = new MersenneTwister(1); +const msWithNumbers = new MersenneTwister([1, 2, 3]); +const msWithInitSeed = new MersenneTwister(); +msWithInitSeed.init_seed(1); + +const ms = msWithTime; +let result: number; + +result = ms.random(); +console.log(result); +result = ms.random_excl(); +console.log(result); +result = ms.random_incl(); +console.log(result); +result = ms.random_int(); +console.log(result); +result = ms.random_int31(); +console.log(result); +result = ms.random_long(); +console.log(result); diff --git a/types/mersenne-twister/tsconfig.json b/types/mersenne-twister/tsconfig.json new file mode 100644 index 0000000000..e4303a44be --- /dev/null +++ b/types/mersenne-twister/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mersenne-twister-tests.ts" + ] +} diff --git a/types/mersenne-twister/tslint.json b/types/mersenne-twister/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mersenne-twister/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 3cf108c7d89c81de04a5c638b4af115f24b2023f Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Sat, 15 Jul 2017 11:38:27 +0200 Subject: [PATCH 0032/1139] feat(lodash decorators): remove typings as of `4.0.0` --- notNeededPackages.json | 6 + types/lodash-decorators/index.d.ts | 234 ------------ .../lodash-decorators-tests.ts | 361 ------------------ types/lodash-decorators/tsconfig.json | 25 -- 4 files changed, 6 insertions(+), 620 deletions(-) delete mode 100644 types/lodash-decorators/index.d.ts delete mode 100644 types/lodash-decorators/lodash-decorators-tests.ts delete mode 100644 types/lodash-decorators/tsconfig.json diff --git a/notNeededPackages.json b/notNeededPackages.json index 50d71d2165..8cf6a8ce83 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -294,6 +294,12 @@ "sourceRepoURL": "https://github.com/localForage/localForage", "asOfVersion": "0.0.34" }, + { + "libraryName": "lodash-decorators", + "typingsPackageName": "lodash-decorators", + "sourceRepoURL": "https://github.com/steelsojka/lodash-decorators", + "asOfVersion": "4.0.0" + }, { "libraryName": "lower-case", "typingsPackageName": "lower-case", diff --git a/types/lodash-decorators/index.d.ts b/types/lodash-decorators/index.d.ts deleted file mode 100644 index 1085db3a3a..0000000000 --- a/types/lodash-decorators/index.d.ts +++ /dev/null @@ -1,234 +0,0 @@ -// Type definitions for lodash-decorators 3.0 -// Project: https://github.com/steelsojka/lodash-decorators -// Definitions by: Alan Agius , Qubo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 - -/// - -declare module "lodash-decorators" { - // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts - - type ClassDecorator = (target: TFunction) => TFunction | void; - - type PropertyDecorator = (target: object, propertyKey: string | symbol) => void; - - type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; - - type ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => void; - - type TypedMethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; - - interface MethodDecoratorWithAccessor extends MethodDecorator, Accessor { } - - interface Accessor { - set: T; - get: T; - proto: T; - } - - type DebounceDecorator = (wait: number, options?: _.DebounceSettings) => MethodDecorator; - - type ThrottleDecorator = (wait: number, options?: _.ThrottleSettings) => MethodDecorator; - - type MemoizeDecorator = (resolver?: Function) => MethodDecorator; - - type AfterDecorator = (n: number) => MethodDecorator; - - type BeforeDecorator = (n: number) => MethodDecorator; - - type AryDecorator = (n: number) => MethodDecorator; - - type CurryDecorator = (arity?: number) => MethodDecorator; - - type CurryRightDecorator = (arity?: number) => MethodDecorator; - - type RestDecorator = (start?: number) => MethodDecorator; - - type OverArgsDecorator = (func: Function, ...transforms: Function[]) => MethodDecorator; - - type PartialDecorator = (func: Function | string, ...args: any[]) => MethodDecorator; - - type WrapDecorator = (wrapper: ((func: Function, ...args: any[]) => any) | string) => MethodDecorator; - - type ComposeDecorator = (...funcs: Array<(Function | string)>) => MethodDecorator; - - type DelayDecorator = (wait: number, ...args: any[]) => MethodDecorator; - - type DeferDecorator = (...args: any[]) => MethodDecorator; - - interface BindDecorator { - (): TypedMethodDecorator<(() => R)>; - (param1?: T1): - TypedMethodDecorator<((param1: T1) => R)>; - (param1?: T1, param2?: T2): - TypedMethodDecorator<((param1: T1, param2: T2) => R)>; - (param1?: T1, param2?: T2, param3?: T3): - TypedMethodDecorator<((param1: T1, param2: T2, param3: T3) => R)>; - (param1?: T1, param2?: T2, param3?: T3, param4?: T4): - TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4) => R)>; - (param1?: T1, param2?: T2, param3?: T3, param4?: T4, param5?: T5): - TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4, param5: T5) => R)>; - (param1?: T1, param2?: T2, param3?: T3, param4?: T4, param5?: T5, param6?: T6): - TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4, param5: T5, param6: T6) => R)>; - } - - type BindAllDecorator = (...methodNames: string[]) => ClassDecorator; - - const debounce: DebounceDecorator & Accessor; - const Debounce: DebounceDecorator & Accessor; - - const throttle: ThrottleDecorator & Accessor; - const Throttle: ThrottleDecorator & Accessor; - - const memoize: MemoizeDecorator & Accessor; - const Memoize: MemoizeDecorator & Accessor; - - const after: AfterDecorator & Accessor; - const After: AfterDecorator & Accessor; - - const before: BeforeDecorator & Accessor; - const Before: BeforeDecorator & Accessor; - - const ary: AryDecorator & Accessor; - const Ary: AryDecorator & Accessor; - - const curry: CurryDecorator & Accessor; - const Curry: CurryDecorator & Accessor; - - const curryRight: CurryRightDecorator & Accessor; - const CurryRight: CurryRightDecorator & Accessor; - - const overArgs: OverArgsDecorator & Accessor; - const OverArgs: OverArgsDecorator & Accessor; - - const rest: RestDecorator & Accessor; - const Rest: RestDecorator & Accessor; - - const partial: PartialDecorator & Accessor; - const Partial: PartialDecorator & Accessor; - - const partialRight: PartialDecorator & Accessor; - const PartialRight: PartialDecorator & Accessor; - - const wrap: WrapDecorator & Accessor; - const Wrap: WrapDecorator & Accessor; - - const flow: ComposeDecorator & Accessor; - const Flow: ComposeDecorator & Accessor; - - const flowRight: ComposeDecorator & Accessor; - const FlowRight: ComposeDecorator & Accessor; - - const delay: DelayDecorator & Accessor; - const Delay: DelayDecorator & Accessor; - - const defer: DeferDecorator & Accessor; - const Defer: DeferDecorator & Accessor; - - const bind: BindDecorator & Accessor; - const Bind: BindDecorator & Accessor; - - const bindAll: BindAllDecorator; - const BindAll: BindAllDecorator; - - const once: MethodDecoratorWithAccessor; - const Once: MethodDecoratorWithAccessor; - - const attempt: MethodDecoratorWithAccessor; - const Attempt: MethodDecoratorWithAccessor; - - const spread: MethodDecoratorWithAccessor; - const Spread: MethodDecoratorWithAccessor; - - const rearg: MethodDecoratorWithAccessor; - const Rearg: MethodDecoratorWithAccessor; - - const negate: MethodDecoratorWithAccessor; - const Negate: MethodDecoratorWithAccessor; - - const tap: MethodDecoratorWithAccessor; - const Tap: MethodDecoratorWithAccessor; - - const flip: MethodDecoratorWithAccessor; - const Flip: MethodDecoratorWithAccessor; -} - -declare module "lodash-decorators/extensions" { - // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts - type ClassDecorator = (target: TFunction) => TFunction | void; - - type PropertyDecorator = (target: object, propertyKey: string | symbol) => void; - - type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; - - type ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => void; - - interface DeprecatedDecorator extends MethodDecorator, ClassDecorator { - methodAction(fn: Function & { name: string }): void; - } - - const deprecated: DeprecatedDecorator; - const Deprecated: DeprecatedDecorator; - - function writable(writable?: boolean): MethodDecorator; - function Writable(writable?: boolean): MethodDecorator; - - function configurable(configurable?: boolean): MethodDecorator; - function Configurable(configurable?: boolean): MethodDecorator; - - function returnsArg(index?: number): MethodDecorator; - function ReturnsArg(index?: number): MethodDecorator; - - function enumerable(enumerable?: boolean): MethodDecorator; - function Enumerable(enumerable?: boolean): MethodDecorator; - - const nonenumerable: MethodDecorator; - const Nonenumerable: MethodDecorator; - - const nonconfigurable: MethodDecorator; - const Nonconfigurable: MethodDecorator; - - const readonly: MethodDecorator; - const Readonly: MethodDecorator; -} - -declare module "lodash-decorators/validate" { - // Originally copied from ../node_modules/typescript/lib/lib.es6.d.ts - type ClassDecorator = (target: TFunction) => TFunction | void; - - type PropertyDecorator = (target: object, propertyKey: string | symbol) => void; - - type MethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; - - type ParameterDecorator = (target: object, propertyKey: string | symbol, parameterIndex: number) => void; - - type TypedMethodDecorator = (target: object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor) => TypedPropertyDescriptor | void; - - type Predicate = (t: T) => boolean; - - type Predicates = Predicate | Array>; - - interface ValidateDecorator { - (p1: Predicates): - TypedMethodDecorator<((param1: T1) => R)>; - (p1: Predicates, p2?: Predicates): - TypedMethodDecorator<((param1: T1, param2: T2) => R)>; - (p1: Predicates, p2?: Predicates, p3?: Predicates): - TypedMethodDecorator<((param1: T1, param2: T2, param3: T3) => R)>; - (p1: Predicates, p2?: Predicates, p3?: Predicates, p4?: Predicates): - TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4) => R)>; - (p1: Predicates, p2?: Predicates, p3?: Predicates, p4?: Predicates, p5?: Predicates): - TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4, param5: T5) => R)>; - (p1: Predicates, p2?: Predicates, p3?: Predicates, p4?: Predicates, p5?: Predicates, p6?: Predicates): - TypedMethodDecorator<((param1: T1, param2: T2, param3: T3, param4: T4, param5: T5, param6: T6) => R)>; - } - - type ValidateReturnDecorator = (p1: Predicates) => TypedMethodDecorator<((...args: any[]) => R)>; - - const validate: ValidateDecorator; - const Validate: ValidateDecorator; - - const validateReturn: ValidateReturnDecorator; - const ValidateReturn: ValidateReturnDecorator; -} diff --git a/types/lodash-decorators/lodash-decorators-tests.ts b/types/lodash-decorators/lodash-decorators-tests.ts deleted file mode 100644 index 61c23f1ddb..0000000000 --- a/types/lodash-decorators/lodash-decorators-tests.ts +++ /dev/null @@ -1,361 +0,0 @@ -// -// With Arguments -// - -import { after, debounce, memoize, curry } from 'lodash-decorators'; - -class Person { - firstName: string; - lastName: string; - constructor(firstName: string, lastName: string) { - this.firstName = firstName; - this.lastName = lastName; - } - - @after(3) - @debounce(100) - getFullName(): string { - return `${this.firstName} ${this.lastName}`; - } - - @curry(2) - @memoize() - doSomeHeavyProcessing(arg1: any, arg2: any) { - } -} - -// -// Without Arguments -// - -import { tap } from 'lodash-decorators'; - -class Person2 { - firstName: string; - lastName: string; - constructor(firstName?: string, lastName?: string) { - this.firstName = firstName; - this.lastName = lastName; - } - - @once - getFullName(): string { - return `${this.firstName} ${this.lastName}`; - } - - @tap - popIt(list: number[]): void { - list.pop(); - } -} - -const person2 = new Person2(); - -person2.popIt([1, 2, 3]); // => [1, 2] - -// -// Partials -// - -import { partial, wrap } from 'lodash-decorators'; - -class Person3 { - firstName: string; - lastName: string; - constructor(firstName?: string, lastName?: string) { - this.firstName = firstName; - this.lastName = lastName; - } - - getName(type: string) { - return type === 'firstName' ? this.firstName : this.lastName; - } - - @partial('getName', 'firstName') - getFirstName(): string { return null; } - - @partial('getName', null) - getLastName(): string { return null; } - - @wrap('getName') - getUpperCaseName(fn: () => string): string { - return fn().toUpperCase(); - } -} - -// by .d.ts author: a workaround to ensure type -interface Person3Ex extends Person3 { - getUpperCaseName(): string; -} - -const person3 = new Person3('Joe', 'Smith') as Person3Ex; - -person3.getFirstName(); // 'Joe' -person3.getLastName(); // 'Smith' -person3.getUpperCaseName(); // JOE SMITH - -// -// Composition -// -import * as _ from 'lodash'; - -class Person4 { - firstName: string; - lastName: string; - constructor(firstName?: string, lastName?: string) { - this.firstName = firstName; - this.lastName = lastName; - } - - getName(): string { - return `${this.firstName} ${this.lastName}`; - } - - @flow(_.kebabCase, 'getName') - logName(name: string): void { - console.log(name); - } -} - -// by .d.ts author: a workaround to ensure type -interface Person4Ex extends Person4 { - logName(): void; -} - -const person4 = new Person4('Joe', 'Smith') as Person4Ex; - -person4.logName(); // joe-smith - -// -// Instance Decorators -// - -class Person5 { - @curry(2) // <= prototype decorator - @debounce(100) // <= instance decorator - getName() { } // => Throws an error. (╯°□°)╯︵ ┻━┻ - - @debounce(100) // <= instance decorator - @curry(2) // <= prototype decorator - getName2() { } // => All is well :) -} - -// -// Getters and Setters -// - -import { once, flow } from 'lodash-decorators'; - -function alwaysArray(value: string | string[]): string[] { - return Array.isArray(value) ? value : _.isUndefined(value) ? [] : [value]; -} - -class Person6 { - constructor() { } - private nameList: string[]; - - // TODO: So far, TypeScript doesn't allow to put multiple decoratoes on set/get accessors. - // see https://github.com/Microsoft/TypeScript/issues/2249#issuecomment-141684146 - // @once.get - get names(): string[] { - // MEMO: Resolve type inconsistency - return [this.nameList.join(' ')]; - // MEMO: Original expression in repo - // return this.nameList.join(' '); - } - - @flow.set(alwaysArray) - set names(names: string[]) { - this.nameList = names; - } -} - -// by .d.ts author: a workaround to ensure type -interface Person6Alt { - names: string[] | string; -} - -const person6 = new Person6(); - -// nameList will always be an array. -person6.names = undefined; // => [] -(person6 as Person6Alt).names = 'Joe'; // => ['Joe'] -person6.names = ['Jim']; // => ['Jim'] - -// -// Bind -// - -import { bind } from 'lodash-decorators'; - -class Person7 { - firstName: string; - lastName: string; - constructor(firstName: string, lastName: string) { - this.firstName = firstName; - this.lastName = lastName; - } - - @bind() - getName(): string { - return `${this.firstName} ${this.lastName}`; - } - - // It can also function as a partial - @bind('Joe') - getUpperCaseName(name: string): string { - return name.toUpperCase(); - } -} - -// by .d.ts author: a workaround to ensure type -interface Person7Ex extends Person7 { - getUpperCaseName(): string; -} - -const person7 = new Person7('Joe', 'Smith') as Person7Ex; - -person7.getName.call(null); // Joe Smith -person7.getUpperCaseName(); // JOE - -import { bindAll } from 'lodash-decorators'; - -@bindAll() -class Person8 { - firstName: string; - lastName: string; - constructor(firstName: string, lastName: string) { - this.firstName = firstName; - this.lastName = lastName; - } - - getName() { - return `${this.firstName} ${this.lastName}`; - } -} - -const person8 = new Person8('Joe', 'Smith'); - -person8.getName.call(null); // Joe Smith - -// -// Forcing Decorator on Prototype -// - -import { throttle } from 'lodash-decorators'; - -class Person9 { - @throttle(1000) - doStuff() { } - - @throttle.proto(1000) - doStuffMore() { } -} - -const person9_1 = new Person9(); -const person9_2 = new Person9(); - -person9_1.doStuff(); // => Both are called -person9_2.doStuff(); - -person9_1.doStuffMore(); -person9_2.doStuffMore(); - -// Only one of these methods is actual invoked because throttle is applied to the prototype method -// and not the instance method. - -// -// Extensions -// - -import { deprecated } from 'lodash-decorators/extensions'; - -// This is applied globally. -deprecated.methodAction = fn => console.log(`Don't use ${fn.name}!`); - -@deprecated -class Person10 { - constructor() { } -} - -class OtherPerson { - @deprecated - fn() { } -} - -const person10 = new Person10(); // => Warning! - -const otherPerson = new OtherPerson(); -otherPerson.fn(); // => Don't use fn! - -// -// https://github.com/steelsojka/lodash-decorators/tree/master/src/extensions -// - -import { Writable, ReturnsArg } from 'lodash-decorators/extensions'; - -class Person11 { - constructor() { } - - @Writable(false) - getName() { } - - @ReturnsArg(1) - doSomething(x: any, y: any, z: any) { - // Do something here - } -} - -// -// https://github.com/steelsojka/lodash-decorators/tree/master/src/validate -// - -import { Validate } from 'lodash-decorators/validate'; - -class Person12 { - name: string; - constructor() { } - - @Validate(_.isString) - setName(name: any) { - this.name = name as string; - } -} - -class Person13 { - name: string; - age: number; - constructor() { } - - @Validate( - _.isString, - [_.isNumber, _.partial(_.lt, 10) as ((_: any) => boolean)] - ) - setData(name: any, age: any) { - this.name = name as string; - this.age = age as number; - } -} - -const person13 = new Person13(); - -person13.setData('test', 5); // => TypeError -person13.setData('test', 12); // => Valid - -// -// Additional typings -// - -import { validateReturn } from 'lodash-decorators/validate'; - -class Calc { - @validateReturn((c: number) => c > 0) - add(a: number, b: number): number { - return a + b; - } - - @validateReturn([c => c > 0]) - mul(a: number, b: number): number { - return a + b; - } -} diff --git a/types/lodash-decorators/tsconfig.json b/types/lodash-decorators/tsconfig.json deleted file mode 100644 index 22d610d56e..0000000000 --- a/types/lodash-decorators/tsconfig.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "target": "es6", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "experimentalDecorators": true, - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "lodash-decorators-tests.ts" - ] -} \ No newline at end of file From 12469ce0d02889a15e91c5f519fbe9a47199fa52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20Ga=C5=82uszka?= Date: Mon, 10 Jul 2017 11:49:10 +0200 Subject: [PATCH 0033/1139] [stripe] fix definitions files and tests --- types/stripe-v2/index.d.ts | 173 +++++++++++++++++++ types/stripe-v2/stripe-v2-tests.ts | 32 ++++ types/{stripe => stripe-v2}/tsconfig.json | 2 +- types/{stripe => stripe-v2}/tslint.json | 0 types/{stripe => stripe-v3}/index.d.ts | 18 +- types/stripe-v3/stripe-v3-tests.ts | 113 ++++++++++++ types/{stripe/v2 => stripe-v3}/tsconfig.json | 9 +- types/{stripe/v2 => stripe-v3}/tslint.json | 0 types/stripe/stripe-tests.ts | 39 ----- types/stripe/v2/index.d.ts | 170 ------------------ types/stripe/v2/stripe-tests.ts | 25 --- 11 files changed, 336 insertions(+), 245 deletions(-) create mode 100644 types/stripe-v2/index.d.ts create mode 100644 types/stripe-v2/stripe-v2-tests.ts rename types/{stripe => stripe-v2}/tsconfig.json (93%) rename types/{stripe => stripe-v2}/tslint.json (100%) rename types/{stripe => stripe-v3}/index.d.ts (93%) create mode 100644 types/stripe-v3/stripe-v3-tests.ts rename types/{stripe/v2 => stripe-v3}/tsconfig.json (73%) rename types/{stripe/v2 => stripe-v3}/tslint.json (100%) delete mode 100644 types/stripe/stripe-tests.ts delete mode 100644 types/stripe/v2/index.d.ts delete mode 100644 types/stripe/v2/stripe-tests.ts diff --git a/types/stripe-v2/index.d.ts b/types/stripe-v2/index.d.ts new file mode 100644 index 0000000000..563fb89780 --- /dev/null +++ b/types/stripe-v2/index.d.ts @@ -0,0 +1,173 @@ +// Type definitions for stripe-v2 2.x +// Project: https://stripe.com/ +// Definitions by: Andy Hawkins +// Eric J. Smith +// Amrit Kahlon +// Adam Cmiel +// Justin Leider +// Kamil Gałuszka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var Stripe: stripe.StripeStatic; + +declare namespace stripe { + interface StripeStatic { + applePay: StripeApplePay; + setPublishableKey(key: string): void; + validateCardNumber(cardNumber: string): boolean; + validateExpiry(month: string, year: string): boolean; + validateCVC(cardCVC: string): boolean; + cardType(cardNumber: string): StripeCardDataBrand; + getToken(token: string, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + card: StripeCard; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + bankAccount: StripeBankAccount; + } + + interface StripeCardTokenData { + number: string; + exp_month?: number; + exp_year?: number; + exp?: string; + cvc?: string; + name?: string; + address_line1?: string; + address_line2?: string; + address_city?: string; + address_state?: string; + address_zip?: string; + address_country?: string; + } + + interface StripeTokenResponse { + id: string; + client_ip: string; + created: number; + livemode: boolean; + object: string; + type: string; + used: boolean; + error?: StripeError; + } + + interface StripeCardTokenResponse extends StripeTokenResponse { + card: StripeCard; + } + + interface StripeError { + type: string; + code: string; + message: string; + param?: string; + } + + type StripeCardDataBrand = 'Visa' | 'American Express' | 'MasterCard' | 'Discover' | 'JCB' | 'Diners Club' | 'Unknown'; + + type StripeCardDataFunding = 'credit' | 'debit' | 'prepaid' | 'unknown'; + + interface StripeCard { + object: string; + last4: string; + exp_month: number; + exp_year: number; + country?: string; + name?: string; + address_line1?: string; + address_line2?: string; + address_city?: string; + address_state?: string; + address_zip?: string; + address_country?: string; + brand?: StripeCardDataBrand; + funding?: StripeCardDataFunding; + createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; + validateCardNumber(cardNumber: string): boolean; + validateExpiry(month: string, year: string): boolean; + validateCVC(cardCVC: string): boolean; + } + + interface StripeBankAccount { + createToken(params: StripeBankTokenParams, stripeResponseHandler: (status: number, response: StripeBankTokenResponse) => void): void; + validateRoutingNumber(routingNumber: number | string, countryCode: string): boolean; + validateAccountNumber(accountNumber: number | string, countryCode: string): boolean; + } + + interface StripeBankTokenParams { + country: string; + currency: string; + account_number: number | string; + routing_number?: number | string; + account_holder_name: string; + account_holder_type: string; + } + + interface StripeBankTokenResponse extends StripeTokenResponse { + bank_account: { + country: string; + bank_name: string; + last4: number; + validated: boolean; + object: string; + }; + } + + interface StripeApplePay { + checkAvailability(resopnseHandler: (result: boolean) => void): void; + buildSession(data: StripeApplePayPaymentRequest, + onSuccessHandler: (result: StripeApplePaySessionResult, completion: ((value: any) => void)) => void, + onErrorHanlder: (error: { message: string }) => void): any; + } + + type StripeApplePayBillingContactField = 'postalAddress' | 'name'; + type StripeApplePayShippingContactField = StripeApplePayBillingContactField | 'phone' | 'email'; + type StripeApplePayShipping = 'shipping' | 'delivery' | 'storePickup' | 'servicePickup'; + + interface StripeApplePayPaymentRequest { + billingContact: StripeApplePayPaymentContact; + countryCode: string; + currencyCode: string; + total: StripeApplePayLineItem; + lineItems?: StripeApplePayLineItem[]; + requiredBillingContactFields?: StripeApplePayBillingContactField[]; + requiredShippingContactFields?: StripeApplePayShippingContactField[]; + shippingContact?: StripeApplePayPaymentContact; + shippingMethods?: StripeApplePayShippingMethod[]; + shippingType?: StripeApplePayShipping[]; + } + + // https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types + interface StripeApplePayLineItem { + type: 'pending' | 'final'; + label: string; + amount: number; + } + + interface StripeApplePaySessionResult { + token: StripeCardTokenResponse; + shippingContact?: StripeApplePayPaymentContact; + shippingMethod?: StripeApplePayShippingMethod; + } + + interface StripeApplePayShippingMethod { + label: string; + detail: string; + amount: number; + identifier: string; + } + + interface StripeApplePayPaymentContact { + emailAddress: string; + phoneNumber: string; + givenName: string; + familyName: string; + addressLines: string[]; + locality: string; + administrativeArea: string; + postalCode: string; + countryCode: string; + } +} + +// The Stripe client side APIs are not made available to package managers for direct installation. +// As explained compliance reasons. Source: https://github.com/stripe/stripe-node/blob/master/README.md#these-are-serverside-bindings-only +// A release date versioning schema is used to version these APIs. diff --git a/types/stripe-v2/stripe-v2-tests.ts b/types/stripe-v2/stripe-v2-tests.ts new file mode 100644 index 0000000000..936d311f53 --- /dev/null +++ b/types/stripe-v2/stripe-v2-tests.ts @@ -0,0 +1,32 @@ +declare function describe(desc: string, fn: () => void): void; +declare function it(desc: string, fn: () => void): void; + +describe("Stripe", () => { + it("should excercise Stripe API", () => { + function success(card: stripe.StripeCard) { + console.log(card.brand && card.brand.toString()); + } + + const cardNumber = '4242424242424242'; + + const isValid = Stripe.validateCardNumber(cardNumber); + if (isValid) { + const tokenData: stripe.StripeCardTokenData = { + number: cardNumber, + exp_month: 1, + exp_year: 2100, + cvc: '111' + }; + Stripe.card.createToken(tokenData, (status, response) => { + if (response.error) { + console.error(response.error.message); + if (response.error.param) { + console.error(response.error.param); + } + } else { + success(response.card); + } + }); + } + }); +}); diff --git a/types/stripe/tsconfig.json b/types/stripe-v2/tsconfig.json similarity index 93% rename from types/stripe/tsconfig.json rename to types/stripe-v2/tsconfig.json index c15aeceae9..a40e816e5a 100644 --- a/types/stripe/tsconfig.json +++ b/types/stripe-v2/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "stripe-tests.ts" + "stripe-v2-tests.ts" ] } diff --git a/types/stripe/tslint.json b/types/stripe-v2/tslint.json similarity index 100% rename from types/stripe/tslint.json rename to types/stripe-v2/tslint.json diff --git a/types/stripe/index.d.ts b/types/stripe-v3/index.d.ts similarity index 93% rename from types/stripe/index.d.ts rename to types/stripe-v3/index.d.ts index f58d5e602f..2337e6adc2 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe-v3/index.d.ts @@ -1,20 +1,30 @@ -// Type definitions for stripe 3.0 +// Type definitions for stripe-v3 3.0 // Project: https://stripe.com/ // Definitions by: Andy Hawkins // Eric J. Smith // Amrit Kahlon // Adam Cmiel // Justin Leider +// Kamil Gałuszka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export function Stripe(stripePublicKey: string): stripe.StripeStatic; +declare var Stripe: stripe.StripeStatic; -export namespace stripe { +declare namespace stripe { interface StripeStatic { + (publicKey: string): Stripe; + version: number; + } + + interface Stripe { elements(options?: elements.ElementsCreateOptions): elements.Elements; createToken(element: elements.Element, options?: TokenOptions): Promise; } + interface StripeOptions { + stripeAccount: string; + } + interface TokenOptions { name?: string; address_line1?: string; @@ -153,7 +163,7 @@ export namespace stripe { empty?: Style; invalid?: Style; }; - value?: string | {[objectKey: string]: string; }; + value?: string | { [objectKey: string]: string; }; } interface Style extends StyleOptions { diff --git a/types/stripe-v3/stripe-v3-tests.ts b/types/stripe-v3/stripe-v3-tests.ts new file mode 100644 index 0000000000..acf878d945 --- /dev/null +++ b/types/stripe-v3/stripe-v3-tests.ts @@ -0,0 +1,113 @@ +/// + +declare function describe(desc: string, fn: () => void): void; +declare function it(desc: string, fn: () => void): void; + +describe("Stripe", () => { + it("should excercise all Stripe API", () => { + const stripe = Stripe('public-key'); + const elements = stripe.elements(); + const style = { + base: { + color: '#32325d', + lineHeight: '24px', + fontFamily: 'Roboto, "Helvetica Neue", sans-serif', + fontSmoothing: 'antialiased', + fontSize: '16px', + '::placeholder': { + color: '#aab7c4' + } + }, + invalid: { + color: '#B71C1C', + iconColor: '#B71C1C' + } + }; + const card = elements.create('card', { hidePostalCode: true, style }); + card.mount(document.createElement('div')); + card.on('ready', () => { + console.log('ready'); + }); + card.on('change', (resp: stripe.elements.ElementChangeResponse) => { + console.log(resp.brand); + }); + stripe.createToken(card, { + name: 'Jimmy', + address_city: 'Toronto', + address_country: 'Canada' + }) + .then((result: stripe.TokenResponse) => { + console.log(result.token); + }, + (error: stripe.Error) => { + console.error(error); + }); + }); +}); + +describe("Stripe v2 & v3", () => { + it("should excercise all Stripe API", () => { + function success(card: stripe.StripeCard) { + console.log(card.brand && card.brand.toString()); + } + + const cardNumber = '4242424242424242'; + + const isValid = Stripe.validateCardNumber(cardNumber); + if (isValid) { + const tokenData: stripe.StripeCardTokenData = { + number: cardNumber, + exp_month: 1, + exp_year: 2100, + cvc: '111' + }; + Stripe.card.createToken(tokenData, (status, response) => { + if (response.error) { + console.error(response.error.message); + if (response.error.param) { + console.error(response.error.param); + } + } else { + success(response.card); + } + }); + } + const stripe = Stripe('public-key'); + const elements = stripe.elements(); + const style = { + base: { + color: '#32325d', + lineHeight: '24px', + fontFamily: 'Roboto, "Helvetica Neue", sans-serif', + fontSmoothing: 'antialiased', + fontSize: '16px', + '::placeholder': { + color: '#aab7c4' + } + }, + invalid: { + color: '#B71C1C', + iconColor: '#B71C1C' + } + }; + const card = elements.create('card', { hidePostalCode: true, style }); + card.mount(document.createElement('div')); + card.on('ready', () => { + console.log('ready'); + }); + card.on('change', (resp: stripe.elements.ElementChangeResponse) => { + console.log(resp.brand); + }); + stripe.createToken(card, { + name: 'Jimmy', + address_city: 'Toronto', + address_country: 'Canada' + }) + .then((result: stripe.TokenResponse) => { + console.log(result.token); + }, + (error: stripe.Error) => { + console.error(error); + }); + }); +}); diff --git a/types/stripe/v2/tsconfig.json b/types/stripe-v3/tsconfig.json similarity index 73% rename from types/stripe/v2/tsconfig.json rename to types/stripe-v3/tsconfig.json index 5917b8206d..4740cec2c1 100644 --- a/types/stripe/v2/tsconfig.json +++ b/types/stripe-v3/tsconfig.json @@ -8,19 +8,16 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "baseUrl": "../../", + "baseUrl": "../", "typeRoots": [ - "../../" + "../" ], "types": [], - "paths": { - "stripe": ["stripe/v2"] - }, "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "stripe-tests.ts" + "stripe-v3-tests.ts" ] } diff --git a/types/stripe/v2/tslint.json b/types/stripe-v3/tslint.json similarity index 100% rename from types/stripe/v2/tslint.json rename to types/stripe-v3/tslint.json diff --git a/types/stripe/stripe-tests.ts b/types/stripe/stripe-tests.ts deleted file mode 100644 index f777c0eb34..0000000000 --- a/types/stripe/stripe-tests.ts +++ /dev/null @@ -1,39 +0,0 @@ -import {stripe, Stripe} from 'stripe'; - -const stripe = Stripe('public-key'); -const elements = stripe.elements(); -const style = { - base: { - color: '#32325d', - lineHeight: '24px', - fontFamily: 'Roboto, "Helvetica Neue", sans-serif', - fontSmoothing: 'antialiased', - fontSize: '16px', - '::placeholder': { - color: '#aab7c4' - } - }, - invalid: { - color: '#B71C1C', - iconColor: '#B71C1C' - } -}; -const card = elements.create('card', {hidePostalCode: true, style}); -card.mount(document.createElement('div')); -card.on('ready', () => { - console.log('ready'); -}); -card.on('change', (resp: stripe.elements.ElementChangeResponse) => { - console.log(resp.brand); -}); -stripe.createToken(card, { - name: 'Jimmy', - address_city: 'Toronto', - address_country: 'Canada' -}) -.then((result: stripe.TokenResponse) => { - console.log(result.token); -}, -(error: stripe.Error) => { - console.error(error); -}); diff --git a/types/stripe/v2/index.d.ts b/types/stripe/v2/index.d.ts deleted file mode 100644 index cc486b5d5b..0000000000 --- a/types/stripe/v2/index.d.ts +++ /dev/null @@ -1,170 +0,0 @@ -// Type definitions for stripe 2.x -// Project: https://stripe.com/ -// Definitions by: Andy Hawkins -// Eric J. Smith -// Amrit Kahlon -// Adam Cmiel -// Justin Leider -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare const Stripe: StripeStatic; - -interface StripeStatic { - applePay: StripeApplePay; - setPublishableKey(key: string): void; - validateCardNumber(cardNumber: string): boolean; - validateExpiry(month: string, year: string): boolean; - validateCVC(cardCVC: string): boolean; - cardType(cardNumber: string): StripeCardDataBrand; - getToken(token: string, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; - card: StripeCard; - createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; - bankAccount: StripeBankAccount; -} - -interface StripeCardTokenData { - number: string; - exp_month?: number; - exp_year?: number; - exp?: string; - cvc?: string; - name?: string; - address_line1?: string; - address_line2?: string; - address_city?: string; - address_state?: string; - address_zip?: string; - address_country?: string; -} - -interface StripeTokenResponse { - id: string; - client_ip: string; - created: number; - livemode: boolean; - object: string; - type: string; - used: boolean; - error?: StripeError; -} - -interface StripeCardTokenResponse extends StripeTokenResponse { - card: StripeCard; -} - -interface StripeError { - type: string; - code: string; - message: string; - param?: string; -} - -type StripeCardDataBrand = 'Visa' | 'American Express' | 'MasterCard' | 'Discover' | 'JCB' | 'Diners Club' | 'Unknown'; - -type StripeCardDataFunding = 'credit' | 'debit' | 'prepaid' | 'unknown'; - -interface StripeCard { - object: string; - last4: string; - exp_month: number; - exp_year: number; - country?: string; - name?: string; - address_line1?: string; - address_line2?: string; - address_city?: string; - address_state?: string; - address_zip?: string; - address_country?: string; - brand?: StripeCardDataBrand; - funding?: StripeCardDataFunding; - createToken(data: StripeCardTokenData, responseHandler: (status: number, response: StripeCardTokenResponse) => void): void; - validateCardNumber(cardNumber: string): boolean; - validateExpiry(month: string, year: string): boolean; - validateCVC(cardCVC: string): boolean; -} - -interface StripeBankAccount { - createToken(params: StripeBankTokenParams, stripeResponseHandler: (status: number, response: StripeBankTokenResponse) => void): void; - validateRoutingNumber(routingNumber: number | string, countryCode: string): boolean; - validateAccountNumber(accountNumber: number | string, countryCode: string): boolean; -} - -interface StripeBankTokenParams { - country: string; - currency: string; - account_number: number | string; - routing_number?: number | string; - account_holder_name: string; - account_holder_type: string; -} - -interface StripeBankTokenResponse extends StripeTokenResponse { - bank_account: { - country: string; - bank_name: string; - last4: number; - validated: boolean; - object: string; - }; -} - -interface StripeApplePay { - checkAvailability(resopnseHandler: (result: boolean) => void): void; - buildSession(data: StripeApplePayPaymentRequest, - onSuccessHandler: (result: StripeApplePaySessionResult, completion: ((value: any) => void)) => void, - onErrorHanlder: (error: { message: string }) => void): any; -} - -type StripeApplePayBillingContactField = 'postalAddress' | 'name'; -type StripeApplePayShippingContactField = StripeApplePayBillingContactField | 'phone' | 'email'; -type StripeApplePayShipping = 'shipping' | 'delivery' | 'storePickup' | 'servicePickup'; - -interface StripeApplePayPaymentRequest { - billingContact: StripeApplePayPaymentContact; - countryCode: string; - currencyCode: string; - total: StripeApplePayLineItem; - lineItems?: StripeApplePayLineItem[]; - requiredBillingContactFields?: StripeApplePayBillingContactField[]; - requiredShippingContactFields?: StripeApplePayShippingContactField[]; - shippingContact?: StripeApplePayPaymentContact; - shippingMethods?: StripeApplePayShippingMethod[]; - shippingType?: StripeApplePayShipping[]; -} - -// https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types -interface StripeApplePayLineItem { - type: 'pending' | 'final'; - label: string; - amount: number; -} - -interface StripeApplePaySessionResult { - token: StripeCardTokenResponse; - shippingContact?: StripeApplePayPaymentContact; - shippingMethod?: StripeApplePayShippingMethod; -} - -interface StripeApplePayShippingMethod { - label: string; - detail: string; - amount: number; - identifier: string; -} - -interface StripeApplePayPaymentContact { - emailAddress: string; - phoneNumber: string; - givenName: string; - familyName: string; - addressLines: string[]; - locality: string; - administrativeArea: string; - postalCode: string; - countryCode: string; -} - -// The Stripe client side APIs are not made available to package managers for direct installation. -// As explained compliance reasons. Source: https://github.com/stripe/stripe-node/blob/master/README.md#these-are-serverside-bindings-only -// A release date versioning schema is used to version these APIs. diff --git a/types/stripe/v2/stripe-tests.ts b/types/stripe/v2/stripe-tests.ts deleted file mode 100644 index 56e6343f5c..0000000000 --- a/types/stripe/v2/stripe-tests.ts +++ /dev/null @@ -1,25 +0,0 @@ -function success(card: StripeCard) { - console.log(card.brand && card.brand.toString()); -} - -const cardNumber = '4242424242424242'; - -const isValid = Stripe.validateCardNumber(cardNumber); -if (isValid) { - const tokenData: StripeCardTokenData = { - number: cardNumber, - exp_month: 1, - exp_year: 2100, - cvc: '111' - }; - Stripe.card.createToken(tokenData, (status, response) => { - if (response.error) { - console.error(response.error.message); - if (response.error.param) { - console.error(response.error.param); - } - } else { - success(response.card); - } - }); -} From 3664cc36abf268be686266b0bd59c6b8b5e3a29a Mon Sep 17 00:00:00 2001 From: lochbrunner Date: Sat, 15 Jul 2017 13:25:01 +0200 Subject: [PATCH 0034/1139] Making XmlDocument as an extension of XmlElement --- types/xmldoc/index.d.ts | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/types/xmldoc/index.d.ts b/types/xmldoc/index.d.ts index a4373606d9..040653d61f 100644 --- a/types/xmldoc/index.d.ts +++ b/types/xmldoc/index.d.ts @@ -3,19 +3,10 @@ // Definitions by: Xavier Stouder , Andrew Sheehan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped): // TypeScript Version: 2.1 -export class XmlDocument { +export class XmlDocument extends XmlElement{ constructor(xmlString: string); doctype: string; - - eachChild(func: (child: XmlElement, index?: number, array?: XmlElement[]) => void): void; - childNamed(name: string): XmlElement; - childrenNamed(name: string): XmlElement[]; - childWithAttribute(name: string, value?: string): XmlElement; - descendantWithPath(path: string): XmlElement; - valueWithPath(path: string): string; - toString(opts?: XmlOptions): string; - toStringWithIndent(indent: string, opts?: XmlOptions): string; } export class XmlElement { From 2be18aea82438a7601896f0b65451037453a17eb Mon Sep 17 00:00:00 2001 From: lochbrunner Date: Sat, 15 Jul 2017 13:33:55 +0200 Subject: [PATCH 0035/1139] Remove unused function --- scripts/generate-tsconfigs.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/scripts/generate-tsconfigs.ts b/scripts/generate-tsconfigs.ts index b72144bf40..0115067e34 100644 --- a/scripts/generate-tsconfigs.ts +++ b/scripts/generate-tsconfigs.ts @@ -5,10 +5,6 @@ import * as fs from 'fs'; import * as path from 'path'; -function repeat(s: string, count: number) { - return Array(count + 1).join(s); -} - const home = path.join(__dirname, '..'); for (const dirName of fs.readdirSync(home)) { From eec6926c4b2115b554b91d800163a0821d0206f1 Mon Sep 17 00:00:00 2001 From: lochbrunner Date: Sat, 15 Jul 2017 13:34:03 +0200 Subject: [PATCH 0036/1139] Add missing whitespace --- types/xmldoc/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/xmldoc/index.d.ts b/types/xmldoc/index.d.ts index 040653d61f..53f21f2027 100644 --- a/types/xmldoc/index.d.ts +++ b/types/xmldoc/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Xavier Stouder , Andrew Sheehan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped): // TypeScript Version: 2.1 -export class XmlDocument extends XmlElement{ +export class XmlDocument extends XmlElement { constructor(xmlString: string); doctype: string; From a6120944b9d923e18fe4ea6474403ca83e80895c Mon Sep 17 00:00:00 2001 From: Roger Ostrander Date: Sat, 15 Jul 2017 15:28:38 -0400 Subject: [PATCH 0037/1139] Added type definitions for rot-js --- types/rot-js/index.d.ts | 722 ++++++++++++++++++++++ types/rot-js/rot-js-tests.ts | 1119 ++++++++++++++++++++++++++++++++++ types/rot-js/tsconfig.json | 23 + types/rot-js/tslint.json | 1 + 4 files changed, 1865 insertions(+) create mode 100644 types/rot-js/index.d.ts create mode 100644 types/rot-js/rot-js-tests.ts create mode 100644 types/rot-js/tsconfig.json create mode 100644 types/rot-js/tslint.json diff --git a/types/rot-js/index.d.ts b/types/rot-js/index.d.ts new file mode 100644 index 0000000000..32a75dbc9f --- /dev/null +++ b/types/rot-js/index.d.ts @@ -0,0 +1,722 @@ +// Type definitions for rot-js 0.6 +// Project: https://github.com/ondras/rot.js +// Definitions by: Roger Ostrander +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Extensions (thanks, https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html ) +declare global { + interface Array { + random(): T; + randomize(): T[]; + } + + interface Number { + mod(n: number): number; + } + + // Added to support `String.format` + interface FormatFunc { + (...args: any[]): string; + map: { [key: string]: string }; + } + + interface StringConstructor { + format: FormatFunc; + } + + interface String { + capitalize(): string; + lpad(character?: string, count?: number): string; + rpad(character?: string, count?: number): string; + + format: FormatFunc; + } +} + +export function isSupported(): boolean; + +// Docs explicitly show examples of overriding these, but TS2 (and ES6) +// say that module-level vars are constant, so here we are: +export const DEFAULT_WIDTH: number; +export const DEFAULT_HEIGHT: number; + +/** Directional constants. Ordering is important! */ +export const DIRS: { + "4": Array<[number, number]>; + "6": Array<[number, number]>; + "8": Array<[number, number]>; +}; + +/** Cancel key. */ +export const VK_CANCEL: number; +/** Help key. */ +export const VK_HELP: number; +/** Backspace key. */ +export const VK_BACK_SPACE: number; +/** Tab key. */ +export const VK_TAB: number; +/** 5 key on Numpad when NumLock is unlocked. Or on Mac, clear key which is positioned at NumLock key. */ +export const VK_CLEAR: number; +/** Return/enter key on the main keyboard. */ +export const VK_RETURN: number; +/** Reserved, but not used. */ +export const VK_ENTER: number; +/** Shift key. */ +export const VK_SHIFT: number; +/** Control key. */ +export const VK_CONTROL: number; +/** Alt (Option on Mac) key. */ +export const VK_ALT: number; +/** Pause key. */ +export const VK_PAUSE: number; +/** Caps lock. */ +export const VK_CAPS_LOCK: number; +/** Escape key. */ +export const VK_ESCAPE: number; +/** Space bar. */ +export const VK_SPACE: number; +/** Page Up key. */ +export const VK_PAGE_UP: number; +/** Page Down key. */ +export const VK_PAGE_DOWN: number; +/** End key. */ +export const VK_END: number; +/** Home key. */ +export const VK_HOME: number; +/** Left arrow. */ +export const VK_LEFT: number; +/** Up arrow. */ +export const VK_UP: number; +/** Right arrow. */ +export const VK_RIGHT: number; +/** Down arrow. */ +export const VK_DOWN: number; +/** Print Screen key. */ +export const VK_PRINTSCREEN: number; +/** Ins(ert) key. */ +export const VK_INSERT: number; +/** Del(ete) key. */ +export const VK_DELETE: number; +/***/ +export const VK_0: number; +/***/ +export const VK_1: number; +/***/ +export const VK_2: number; +/***/ +export const VK_3: number; +/***/ +export const VK_4: number; +/***/ +export const VK_5: number; +/***/ +export const VK_6: number; +/***/ +export const VK_7: number; +/***/ +export const VK_8: number; +/***/ +export const VK_9: number; +/** Colon (:) key. Requires Gecko 15.0 */ +export const VK_COLON: number; +/** Semicolon (;) key. */ +export const VK_SEMICOLON: number; +/** Less-than (<) key. Requires Gecko 15.0 */ +export const VK_LESS_THAN: number; +/** Equals (=) key. */ +export const VK_EQUALS: number; +/** Greater-than (>) key. Requires Gecko 15.0 */ +export const VK_GREATER_THAN: number; +/** Question mark (?) key. Requires Gecko 15.0 */ +export const VK_QUESTION_MARK: number; +/** Atmark (@) key. Requires Gecko 15.0 */ +export const VK_AT: number; +/***/ +export const VK_A: number; +/***/ +export const VK_B: number; +/***/ +export const VK_C: number; +/***/ +export const VK_D: number; +/***/ +export const VK_E: number; +/***/ +export const VK_F: number; +/***/ +export const VK_G: number; +/***/ +export const VK_H: number; +/***/ +export const VK_I: number; +/***/ +export const VK_J: number; +/***/ +export const VK_K: number; +/***/ +export const VK_L: number; +/***/ +export const VK_M: number; +/***/ +export const VK_N: number; +/***/ +export const VK_O: number; +/***/ +export const VK_P: number; +/***/ +export const VK_Q: number; +/***/ +export const VK_R: number; +/***/ +export const VK_S: number; +/***/ +export const VK_T: number; +/***/ +export const VK_U: number; +/***/ +export const VK_V: number; +/***/ +export const VK_W: number; +/***/ +export const VK_X: number; +/***/ +export const VK_Y: number; +/***/ +export const VK_Z: number; +/***/ +export const VK_CONTEXT_MENU: number; +/** 0 on the numeric keypad. */ +export const VK_NUMPAD0: number; +/** 1 on the numeric keypad. */ +export const VK_NUMPAD1: number; +/** 2 on the numeric keypad. */ +export const VK_NUMPAD2: number; +/** 3 on the numeric keypad. */ +export const VK_NUMPAD3: number; +/** 4 on the numeric keypad. */ +export const VK_NUMPAD4: number; +/** 5 on the numeric keypad. */ +export const VK_NUMPAD5: number; +/** 6 on the numeric keypad. */ +export const VK_NUMPAD6: number; +/** 7 on the numeric keypad. */ +export const VK_NUMPAD7: number; +/** 8 on the numeric keypad. */ +export const VK_NUMPAD8: number; +/** 9 on the numeric keypad. */ +export const VK_NUMPAD9: number; +/** * on the numeric keypad. */ +export const VK_MULTIPLY: number; +/** + on the numeric keypad. */ +export const VK_ADD: number; +/***/ +export const VK_SEPARATOR: number; +/** - on the numeric keypad. */ +export const VK_SUBTRACT: number; +/** Decimal point on the numeric keypad. */ +export const VK_DECIMAL: number; +/** / on the numeric keypad. */ +export const VK_DIVIDE: number; +/** F1 key. */ +export const VK_F1: number; +/** F2 key. */ +export const VK_F2: number; +/** F3 key. */ +export const VK_F3: number; +/** F4 key. */ +export const VK_F4: number; +/** F5 key. */ +export const VK_F5: number; +/** F6 key. */ +export const VK_F6: number; +/** F7 key. */ +export const VK_F7: number; +/** F8 key. */ +export const VK_F8: number; +/** F9 key. */ +export const VK_F9: number; +/** F10 key. */ +export const VK_F10: number; +/** F11 key. */ +export const VK_F11: number; +/** F12 key. */ +export const VK_F12: number; +/** F13 key. */ +export const VK_F13: number; +/** F14 key. */ +export const VK_F14: number; +/** F15 key. */ +export const VK_F15: number; +/** F16 key. */ +export const VK_F16: number; +/** F17 key. */ +export const VK_F17: number; +/** F18 key. */ +export const VK_F18: number; +/** F19 key. */ +export const VK_F19: number; +/** F20 key. */ +export const VK_F20: number; +/** F21 key. */ +export const VK_F21: number; +/** F22 key. */ +export const VK_F22: number; +/** F23 key. */ +export const VK_F23: number; +/** F24 key. */ +export const VK_F24: number; +/** Num Lock key. */ +export const VK_NUM_LOCK: number; +/** Scroll Lock key. */ +export const VK_SCROLL_LOCK: number; +/** Circumflex (^) key. Requires Gecko 15.0 */ +export const VK_CIRCUMFLEX: number; +/** Exclamation (!) key. Requires Gecko 15.0 */ +export const VK_EXCLAMATION: number; +/** Double quote () key. Requires Gecko 15.0 */ +export const VK_DOUBLE_QUOTE: number; +/** Hash (#) key. Requires Gecko 15.0 */ +export const VK_HASH: number; +/** Dollar sign ($) key. Requires Gecko 15.0 */ +export const VK_DOLLAR: number; +/** Percent (%) key. Requires Gecko 15.0 */ +export const VK_PERCENT: number; +/** Ampersand (&) key. Requires Gecko 15.0 */ +export const VK_AMPERSAND: number; +/** Underscore (_) key. Requires Gecko 15.0 */ +export const VK_UNDERSCORE: number; +/** Open parenthesis (() key. Requires Gecko 15.0 */ +export const VK_OPEN_PAREN: number; +/** Close parenthesis ()) key. Requires Gecko 15.0 */ +export const VK_CLOSE_PAREN: number; +/* Asterisk (*) key. Requires Gecko 15.0 */ +export const VK_ASTERISK: number; +/** Plus (+) key. Requires Gecko 15.0 */ +export const VK_PLUS: number; +/** Pipe (|) key. Requires Gecko 15.0 */ +export const VK_PIPE: number; +/** Hyphen-US/docs/Minus (-) key. Requires Gecko 15.0 */ +export const VK_HYPHEN_MINUS: number; +/** Open curly bracket ({) key. Requires Gecko 15.0 */ +export const VK_OPEN_CURLY_BRACKET: number; +/** Close curly bracket (}) key. Requires Gecko 15.0 */ +export const VK_CLOSE_CURLY_BRACKET: number; +/** Tilde (~) key. Requires Gecko 15.0 */ +export const VK_TILDE: number; +/** Comma (,) key. */ +export const VK_COMMA: number; +/** Period (.) key. */ +export const VK_PERIOD: number; +/** Slash (/) key. */ +export const VK_SLASH: number; +/** Back tick (`) key. */ +export const VK_BACK_QUOTE: number; +/** Open square bracket ([) key. */ +export const VK_OPEN_BRACKET: number; +/** Back slash (\) key. */ +export const VK_BACK_SLASH: number; +/** Close square bracket (]) key. */ +export const VK_CLOSE_BRACKET: number; +/** Quote (''') key. */ +export const VK_QUOTE: number; +/** Meta key on Linux, Command key on Mac. */ +export const VK_META: number; +/** AltGr key on Linux. Requires Gecko 15.0 */ +export const VK_ALTGR: number; +/** Windows logo key on Windows. Or Super or Hyper key on Linux. Requires Gecko 15.0 */ +export const VK_WIN: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_KANA: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_HANGUL: number; +/** 英数 key on Japanese Mac keyboard. Requires Gecko 15.0 */ +export const VK_EISU: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_JUNJA: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_FINAL: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_HANJA: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_KANJI: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_CONVERT: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_NONCONVERT: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_ACCEPT: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_MODECHANGE: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_SELECT: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_PRINT: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_EXECUTE: number; +/** Linux support for this keycode was added in Gecko 4.0. */ +export const VK_SLEEP: number; + +// Added to support `measure` +export interface Size { + width: number; + height: number; +} + +export namespace Text { + const RE_COLORS: RegExp; + + /* token types */ + const TYPE_BG: number; + const TYPE_FG: number; + const TYPE_NEWLINE: number; + const TYPE_TEXT: number; + + function measure(str: string, maxWidth: number): Size; + + // Added to support `tokenize` + interface Token { + type: number; + value?: string; + } + + function tokenize(str: string, maxWidth: number): Token[]; +} + +// Duplication is so that we can support chaining like ROT does, +// but also use ROT.RNG like a normal namespace +export interface RNGable { + getSeed(): number; + setSeed(seed: number): RNGable; + getUniform(): number; + getUniformInt(lowerBound: number, upperBound: number): number; + getNormal(mean?: number, stddev?: number): number; + getPercentage(): number; + getWeightedValue(data: { T: number }): T; + getState(): [number, number, number, number]; + setState(state: [number, number, number, number]): RNGable; + clone(): RNGable; +} + +export namespace RNG { + function getSeed(): number; + function setSeed(seed: number): RNGable; + function getUniform(): number; + function getUniformInt(lowerBound: number, upperBound: number): number; + function getNormal(mean?: number, stddev?: number): number; + function getPercentage(): number; + // Can't do the following because index has to explicitly be strings + // or numbers, see https://github.com/Microsoft/TypeScript/issues/5683 + // function getWeightedValue(data: {[key: T]: number}): T; + // Provide a type-safe version for strings, at least: + function getWeightedValue(data: { [key: string]: number }): string; + // And everything else: + function getWeightedValue(data: any): any; + function getState(): [number, number, number, number]; + function setState(state: [number, number, number, number]): RNGable; + function clone(): RNGable; +} + +export interface DisplayOptions { + width?: number; + height?: number; + transpose?: boolean; + fontSize?: number; + fontFamily?: string; + fontStyle?: string; + fg?: string; + bg?: string; + spacing?: number; + border?: number; + layout?: string; + forceSquareRatio?: boolean; + tileWidth?: number; + tileHeight?: number; + tileMap?: any; + tileSet?: any; + tileColorize?: boolean; + termColor?: string; +} + +export class Display { + DEBUG: DigCallback; + + constructor(options?: DisplayOptions); + clear(): void; + computeSize(availWidth: number, availHeight: number): [number, number]; + computeFontSize(availWidth: number, availHeight: number): number; + draw(x: number, y: number, character: string | string[], fg?: string, bg?: string): void; + drawText(x: number, y: number, text: string, maxWidth?: number): number; + eventToPosition(e: UIEvent): [number, number] | number; + getContainer(): Node; + getOptions(): DisplayOptions; + setOptions(options: DisplayOptions): Display; +} + +// Map callbacks +export type DigCallback = (x: number, y: number, cellValue: number) => any; +export type DoorCallback = (x: number, y: number) => any; +export type CanBeDugCallback = (x: number, y: number) => boolean; +export type IsWallCallback = (x: number, y: number) => boolean; + +// Map +export class Map { + constructor(width: number, height: number); + create(callback?: DigCallback): Map; +} + +export interface CellularOptions { + born?: number[]; + survive?: number[]; + topology?: number; + // Docs say this exists, even though it's never used: + connected?: boolean; +} + +export interface DiggerOptions { + roomWidth?: [number, number]; + roomHeight?: [number, number]; + corridorLength?: [number, number]; + dugPercentage?: number; + timeLimit?: number; +} + +export interface UniformOptions { + roomWidth?: [number, number]; + roomHeight?: [number, number]; + roomDugPercentage?: number; + timeLimit?: number; +} + +export interface RogueOptions { + cellWidth?: number; + cellHeight?: number; + roomWidth?: [number, number]; + roomHeight?: [number, number]; +} + +export interface RoomOptions { + roomWidth?: [number, number]; + roomHeight?: [number, number]; +} + +export interface CorridorOptions { + corridorLength: [number, number]; +} +export type FeatureOptions = RoomOptions | CorridorOptions; + +export namespace Map { + class Arena extends Map { } + class DividedMaze extends Map { } + class IceyMaze extends Map { + constructor(width?: number, height?: number, regularity?: number); + } + class EllerMaze extends Map { } + class Cellular extends Map { + constructor(width?: number, height?: number, options?: CellularOptions); + randomize(probability: number): this; + setOptions(options: CellularOptions): void; + set(x: number, y: number, value: any): void; + serviceCallback(callback: DigCallback): void; + connect(callback: DigCallback, value?: number, connectionCallback?: DoorCallback): void; + } + class Dungeon extends Map { + getRooms(): Map.Feature.Room[]; + getCorridors(): Map.Feature.Corridor[]; + } + + class Digger extends Dungeon { + constructor(width?: number, height?: number, options?: DiggerOptions); + } + + class Uniform extends Dungeon { + constructor(width?: number, height?: number, options?: UniformOptions); + } + + class Rogue extends Map { + constructor(width?: number, height?: number, options?: RogueOptions); + } + + class Feature { + isValid(canBeDugCallback: CanBeDugCallback): boolean; + create(digCallback: DigCallback): void; + debug(): void; + static createRandomAt(x: number, y: number, dx: number, dy: number, options?: FeatureOptions): Feature; + } + + namespace Feature { + class Room { + constructor(x1: number, y1: number, x2: number, y2: number, doorX?: number, doorY?: number); + + static createRandom(availWidth: number, availHeight: number, options?: RoomOptions): Room; + static createRandomAt(x: number, y: number, dx: number, dy: number, options?: RoomOptions): Room; + static createRandomCenter(cx: number, cy: number, options?: RoomOptions): Room; + + create(digCallback: DigCallback): void; + debug(): void; + + addDoor(x: number, y: number): this; + getDoors(callback: DoorCallback): this; + clearDoors(): this; + addDoors(isWallCallback: IsWallCallback): this; + isValid(isWallCallback: IsWallCallback, canBeDugCallback: CanBeDugCallback): boolean; + getCenter(): [number, number]; + + getLeft(): number; + getRight(): number; + getTop(): number; + getBottom(): number; + } + + class Corridor { + constructor(startX: number, startY: number, endX: number, endY: number); + + static createRandomAt(x: number, y: number, dx: number, dy: number, options?: CorridorOptions): Corridor; + + create(digCallback: DigCallback): boolean; + debug(): void; + + isValid(isWallCallback: IsWallCallback, canBeDugCallback: CanBeDugCallback): boolean; + createPriorityWalls(priorityWallCallback: DoorCallback): void; + } + } +} + +// FOV callbacks +export type LightPassesCallback = (x: number, y: number) => boolean; +export type FOVCallback = (x: number, y: number, R: number, visibility: number) => any; + +export interface FOVOptions { + topology?: number; +} + +export class FOV { + constructor(lightPassesCallback: LightPassesCallback, options?: FOVOptions); + compute(x: number, y: number, R: number, callback: FOVCallback): void; +} +export namespace FOV { + class DiscreteShadowcasting extends FOV { } + class PreciseShadowcasting extends FOV { } + + class RecursiveShadowcasting extends FOV { + compute180(x: number, y: number, R: number, dir: number, callback: FOVCallback): void; + compute90(x: number, y: number, R: number, dir: number, callback: FOVCallback): void; + } + namespace RecursiveShadowcasting { + const OCTANTS: Array<[number, number, number, number]>; + } +} + +export type ColorArray = [number, number, number]; + +export namespace Color { + function fromString(str: string): [number, number, number]; + function add(color1: [number, number, number], ...colors2: Array<[number, number, number]>): [number, number, number]; + function add_(color1: [number, number, number], ...colors2: Array<[number, number, number]>): [number, number, number]; + function multiply(color1: [number, number, number], ...colors2: Array<[number, number, number]>): [number, number, number]; + function multiply_(color1: [number, number, number], ...colors2: Array<[number, number, number]>): [number, number, number]; + function interpolate(color1: [number, number, number], color2: [number, number, number], factor: number): [number, number, number]; + function interpolateHSL(color1: [number, number, number], color2: [number, number, number], factor: number): [number, number, number]; + function randomize(color: [number, number, number], diff: number | [number, number, number]): [number, number, number]; + function rgb2hsl(color: [number, number, number]): [number, number, number]; + function hsl2rgb(color: [number, number, number]): [number, number, number]; + function toRGB(color: [number, number, number]): string; + function toHex(color: [number, number, number]): string; +} + +// Lighting callbacks +export type ReflectivityCallback = (x: number, y: number) => number; +export type LightingCallback = (x: number, y: number, color: [number, number, number]) => any; + +export interface LightingOptions { + passes?: number; + emissionThreshold?: number; + range?: number; +} + +export class Lighting { + constructor(reflectivityCallback: ReflectivityCallback, options?: LightingOptions); + + setOptions(options: LightingOptions): this; + setFOV(fov: FOV): this; + setLight(x: number, y: number, color: string | [number, number, number]): this; + clearLights(): void; + reset(): this; + compute(lightingCallback: LightingCallback): this; +} + +// Path callbacks +export type PassableCallback = (x: number, y: number) => boolean; +export type PathCallback = (x: number, y: number) => any; + +export interface PathOptions { + topology?: number; +} + +export class Path { + constructor(toX: number, toY: number, passableCallback: PassableCallback, options?: PathOptions); + + compute(fromX: number, fromY: number, callback: PathCallback): void; +} + +export namespace Path { + class Dijkstra extends Path { } + class AStar extends Path { } +} + +export interface Noise { + get(x: number, y: number): number; +} +export namespace Noise { + class Simplex implements Noise { + constructor(gradients?: number); + get(xin: number, yin: number): number; + } +} + +export class EventQueue { + getTime(): number; + clear(): void; + add(event: T, time: number): void; + get(): T; + getEventTime(event: T): number; + remove(event: T): boolean; + remove(index: number): boolean; +} + +export class Scheduler { + getTime(): number; + add(item: any, repeat: boolean, time?: number): Scheduler; + getTimeOf(item: any): number; + clear(): Scheduler; + remove(item: any): any; + next(): any; +} + +export namespace Scheduler { + class Simple extends Scheduler { } + class Speed extends Scheduler { } + class Action extends Scheduler { + setDuration(time: number): Action; + } +} + +export class Engine { + constructor(scheduler: Scheduler); + start(): Engine; + lock(): Engine; + unlock(): Engine; +} + +export interface StringGeneratorOptions { + words?: boolean; + order?: number; + prior?: number; +} + +export class StringGenerator { + constructor(options?: StringGeneratorOptions); + clear(): void; + generate(): string; + observe(str: string): void; + getStats(): string; +} diff --git a/types/rot-js/rot-js-tests.ts b/types/rot-js/rot-js-tests.ts new file mode 100644 index 0000000000..bef1de16d3 --- /dev/null +++ b/types/rot-js/rot-js-tests.ts @@ -0,0 +1,1119 @@ +import * as ROT from 'rot-js'; + +// All the documentation uses a function called `SHOW` to do results; stubbing it out here +// so that I can copy/paste directly. +function SHOW(...something: any[]): any { + console.log(something); +} + +let w = 80; +let h = 40; +let display: ROT.Display; + +// Introduction / Browser Support + +SHOW( + ROT.isSupported() +); + +// JS Enhancements / Array + +SHOW( + ["apples", "oranges", "zombies"].random(), + ["apples", "oranges", "zombies"].randomize() +); + +// JS Enhancements / String + +SHOW( + "hello world".capitalize(), + "hello %s, this is %s".format("world", "sparta"), + "7".lpad("0", 3), + "123".rpad(".", 6) +); + +// JS Enhancements / Number + +SHOW( + (15) % 7, + (-15) % 7, + (15).mod(7), + (-15).mod(7) +); + +// JS Enhancements / (Object | Function) not included, as TS does that for us + +// JS Enhancements / String formatting +SHOW( + String.format("%s %s", "hello", "world"), + "%s %s".format("hello", "world") +); +// ---- + +let myObj = { + foo() { return "bar"; } +}; +String.format.map['f'] = "foo"; + +SHOW("%f".format(myObj)); +// ---- + +class Item { + constructor(private name: string) { } + + a() { + let first = self.name.charAt(0); + return (first.match(/[aeiouy]/i) ? "an" : "a") + " " + this.name; + } + + the() { + return `the ${this.name}`; + } +} + +String.format.map['a'] = "a"; +String.format.map['the'] = "the"; + +let apple = new Item("apple"); +let banana = new Item("banana"); +let template = "You eat %a. %The was delicious."; + +SHOW(template.format(apple, apple)); +SHOW(template.format(banana, banana)); +// ---- + +class Animal { + constructor(private name: string) { } + adjective(x: string) { + return `${x} ${this.name}`; + } +} + +String.format.map['adjective'] = "adjective"; + +let cat = new Animal("cat"); +template = "You see a %{adjective,black}."; + +SHOW(template.format(cat)); + +// Keyboard Handling not included, as nothing ROT specific in there + +// RNG / Generating random values + +SHOW( + ROT.RNG.getUniform(), + ROT.RNG.getNormal(0, 10), + ROT.RNG.getPercentage() +); +// ---- + +let canvas = document.createElement("canvas"); +canvas.width = 500; +canvas.height = 200; +SHOW(canvas); + +let ctx = canvas.getContext("2d"); +ctx!.fillStyle = "#fff"; +ctx!.fillRect(0, 0, canvas.width, canvas.height); +ctx!.fillStyle = "#f00"; + +let data = new Array(); +for (let i = 0; i < 40000; i++) { /* generate histogram */ + let num = Math.round(ROT.RNG.getNormal(250, 100)); + data[num] = (data[num] || 0) + 1; +} + +for (let i = 0; i < data.length; i++) { /* plot histogram */ + ctx!.fillRect(i, canvas.height - data[i], 1, data[i]); +} + +// RNG / Working with RNG state +let state = ROT.RNG.getState(); +SHOW(ROT.RNG.getUniform()); + +ROT.RNG.setState(state); +SHOW(ROT.RNG.getUniform()); +// ---- + +let seed = ROT.RNG.getSeed(); + +ROT.RNG.setSeed(12345); +SHOW( + ROT.RNG.getUniform(), + ROT.RNG.getUniform() +); + +ROT.RNG.setSeed(12345); +SHOW( + ROT.RNG.getUniform(), + ROT.RNG.getUniform() +); + +// RNG / Cloning a RNG + +let clone = ROT.RNG.clone(); + +SHOW(ROT.RNG.getUniform()); +SHOW(clone.getUniform()); + +ROT.RNG.setSeed(123); +SHOW(ROT.RNG.getUniform()); +SHOW(clone.getUniform()); + +// RNG / Picking a weighted value +let monsters = { + orc: 3, + ogre: 1, + rat: 5 +}; + +for (let i = 0; i < 20; i++) { + SHOW(ROT.RNG.getWeightedValue(monsters)); +} + +// Console Display / Creating a display + +display = new ROT.Display({ width: 20, height: 5 }); +SHOW(display.getContainer()); /* do not forget to append to page! */ + +// Console Display / Configuring the display +display = new ROT.Display({ width: 20, height: 5 }); +SHOW(display.getContainer()); +display.setOptions({ + width: 30, + fontSize: 8, + fontStyle: "bold", + bg: "#a00" +}); + +// Console Display / Drawing individual characters + +display = new ROT.Display({ width: 40, height: 9 }); +SHOW(display.getContainer()); + +display.draw(5, 4, "@"); +display.draw(15, 4, "%", "#0f0"); /* foreground color */ +display.draw(25, 4, "#", "#f00", "#009"); /* and background color */ + +// Console Display / Drawing strings + +display = new ROT.Display({ width: 40, height: 20 }); +SHOW(display.getContainer()); + +display.drawText(5, 2, "Hello world"); + +/* last argument specifies maximum length */ +display.drawText(20, 5, "This line of text is very long.", 16); + +/* lines are broken at word boundaries; lines are trimmed */ +let words = ["lorem", "ipsum", "dolor", "sit", "amet"]; +let long: string[] = []; +for (let i = 0; i < 30; i++) { long.push(words.random()); } +let longer = long.join(" "); + +display.drawText(1, 10, longer, 38); + +// Console Display / Specifying foreground/background color in strings + +display = new ROT.Display({ width: 40, height: 5 }); +SHOW(display.getContainer()); + +let str = "Goodbye %c{red}cr%b{blue}u%b{}el %c{}world"; +display.drawText(5, 2, str); + +// Console Display / Forced square aspect ratio +let options: ROT.DisplayOptions = { + width: 20, + height: 8, + fontSize: 18, + forceSquareRatio: true +}; +display = new ROT.Display(options); +SHOW(display.getContainer()); + +str = "Using a regular grid\n@....%b{blue}#%b{}##.%b{red}.%b{}.$$$"; +display.drawText(2, 2, str); + +// Console display / graphical tiles + +let tileSet = document.createElement("img"); +tileSet.src = "tiles.png"; + +options = { + layout: "tile", + bg: "transparent", + tileWidth: 64, + tileHeight: 64, + tileSet, + tileMap: { + "@": [0, 0], + "#": [0, 64], + a: [64, 0], + "!": [64, 64] + }, + width: 3, + height: 3 +}; +display = new ROT.Display(options); +SHOW(display.getContainer()); + +tileSet.onload = () => { + display.draw(1, 1, "@"); + display.draw(0, 0, "#"); + display.draw(0, 1, "#"); + display.draw(1, 0, "#"); + display.draw(0, 2, "#"); + display.draw(2, 2, "a"); + display.draw(2, 0, "!"); + display.draw(2, 1, "!"); +}; + +// Console display / graphical tiles / Multiple tiles at one place +tileSet = document.createElement("img"); +tileSet.src = "tiles.png"; + +options = { + layout: "tile", + bg: "transparent", + tileWidth: 64, + tileHeight: 64, + tileSet, + tileMap: { + "@": [0, 0], + "#": [0, 64] + }, + width: 1, + height: 1 +}; +display = new ROT.Display(options); +SHOW(display.getContainer()); + +tileSet.onload = () => { + display.draw(0, 0, ["#", "@"]); +}; + +// Console display / graphical tiles / Colorizing tiles + +tileSet = document.createElement("img"); +tileSet.src = "tiles.png"; + +options = { + layout: "tile", + tileWidth: 64, + tileHeight: 64, + tileSet, + tileMap: { + "@": [0, 0], + "#": [0, 64], + a: [64, 0], + "!": [64, 64] + }, + width: 3, + height: 2, + tileColorize: true +}; +display = new ROT.Display(options); +SHOW(display.getContainer()); + +tileSet.onload = () => { + display.draw(0, 0, "@", "transparent"); + display.draw(1, 0, "@", "green", "red"); + display.draw(2, 0, "@", "rgba(30, 200, 30, 0.5)", "red"); + display.draw(0, 1, "#", "transparent"); + display.draw(1, 1, "#", "white"); + display.draw(2, 1, "#", "transparent", "rgba(250, 250, 0, 0.5)"); +}; + +// Map creation +let map = new ROT.Map.Arena(3, 3); +let userCallback = (x: number, y: number, value: number) => { + SHOW("Value %s generated at [%s,%s]".format(value, x, y)); +}; +map.create(userCallback); +map = new ROT.Map.Arena(10, 5); + +let display1 = new ROT.Display({ width: 10, height: 5, fontSize: 18 }); +SHOW(display1.getContainer()); + +map.create((x, y, wall) => { + display1.draw(x, y, wall ? "#" : "."); +}); + +/* debugging with small font */ +let display2 = new ROT.Display({ width: 10, height: 5, fontSize: 8 }); +SHOW(display2.getContainer()); +map.create(display2.DEBUG); + +// Map creation / Maze / DividedMaze +let dm = new ROT.Map.DividedMaze(w, h); + +for (let i = 0; i < 4; i++) { + display = new ROT.Display({ width: w, height: h, fontSize: 6 }); + SHOW(display.getContainer()); + + dm.create(display.DEBUG); +} + +// Map creation / Maze / Icey's Maze + +for (let i = 0; i < 4; i++) { + display = new ROT.Display({ width: w, height: h, fontSize: 6 }); + SHOW(display.getContainer()); + + let maze = new ROT.Map.IceyMaze(w, h, 4 * i); + maze.create(display.DEBUG); +} + +// Map creation / Maze / Eller's Perfect Maze + +let em = new ROT.Map.EllerMaze(w, h); + +for (let i = 0; i < 4; i++) { + display = new ROT.Display({ width: w, height: h, fontSize: 6 }); + SHOW(display.getContainer()); + + em.create(display.DEBUG); +} + +// Map creation / Cellular +let cellular = new ROT.Map.Cellular(w, h); + +/* cells with 1/2 probability */ +cellular.randomize(0.5); + +/* generate and show four generations */ +for (let i = 0; i < 4; i++) { + display = new ROT.Display({ width: w, height: h, fontSize: 4 }); + SHOW(display.getContainer()); + cellular.create(display.DEBUG); +} +// ---- + +w = 100; h = 60; +display = new ROT.Display({ width: w, height: h, fontSize: 6 }); +SHOW(display.getContainer()); + +/* custom born/survive rules */ +cellular = new ROT.Map.Cellular(w, h, { + born: [4, 5, 6, 7, 8], + survive: [2, 3, 4, 5] +}); + +cellular.randomize(0.9); + +/* generate fifty iterations, show the last one */ +for (let i = 49; i >= 0; i--) { + cellular.create(i ? undefined : display.DEBUG); +} +// ---- + +/* create a connected map where the player can reach all non-wall sections */ +cellular = new ROT.Map.Cellular(w, h, { connected: true }); + +/* cells with 1/2 probability */ +cellular.randomize(0.5); + +/* make a few generations */ +for (let i = 0; i < 4; i++) cellular.create(); + +/* display only the final map */ +display = new ROT.Display({ width: w, height: h, fontSize: 4 }); +SHOW(display.getContainer()); +cellular.create(display.DEBUG); + +/* now connect the maze */ +display = new ROT.Display({ width: w, height: h, fontSize: 4 }); +SHOW(display.getContainer()); +cellular.connect(display.DEBUG); +// ---- + +/* create a connected map where the player can reach all non-wall sections */ +cellular = new ROT.Map.Cellular(w, h, { connected: true }); + +/* cells with 1/2 probability */ +cellular.randomize(0.5); + +/* make a few generations */ +for (let i = 0; i < 4; i++) cellular.create(); + +/* display only the final map */ +display = new ROT.Display({ width: w, height: h, fontSize: 4 }); +SHOW(display.getContainer()); +cellular.create(display.DEBUG); + +/* now connect the maze */ +display = new ROT.Display({ width: w, height: h, fontSize: 4 }); +SHOW(display.getContainer()); +cellular.connect(display.DEBUG, 1); +// ---- + +/* create a connected map where the player can reach all non-wall sections */ +cellular = new ROT.Map.Cellular(w, h, { connected: true }); + +/* cells with 1/2 probability */ +cellular.randomize(0.5); + +/* make a few generations */ +for (let i = 0; i < 4; i++) cellular.create(); + +/* display only the final map */ +display = new ROT.Display({ width: w, height: h, fontSize: 4 }); +SHOW(display.getContainer()); +cellular.create(display.DEBUG); + +/* now connect the maze */ +display = new ROT.Display({ width: w, height: h, fontSize: 4 }); +SHOW(display.getContainer()); +cellular.connect(display.DEBUG, 0, (from, to) => { + SHOW("Connection was made " + from + " to " + to); +}); + +// Map creation / Dungeon + +ROT.RNG.setSeed(1234); +let dungeon = new ROT.Map.Digger(); +display = new ROT.Display({ fontSize: 8 }); +SHOW(display.getContainer()); +dungeon.create(display.DEBUG); + +let drawDoor = (x: number, y: number) => { + display.draw(x, y, "", "", "red"); +}; + +let rooms = dungeon.getRooms(); +for (let i = 0; i < rooms.length; i++) { + let room = rooms[i]; + SHOW("Room #%s: [%s, %s] => [%s, %s]".format( + (i + 1), + room.getLeft(), room.getTop(), + room.getRight(), room.getBottom() + )); + + room.getDoors(drawDoor); +} + +// Map creation / Dungeon / Digger +dungeon = new ROT.Map.Digger(w, h); + +for (let i = 0; i < 4; i++) { + display = new ROT.Display({ width: w, height: h, fontSize: 6 }); + SHOW(display.getContainer()); + dungeon.create(display.DEBUG); +} + +// Map creation / Dungeon / Uniform + +let uniform = new ROT.Map.Uniform(w, h); + +for (let i = 0; i < 4; i++) { + display = new ROT.Display({ width: w, height: h, fontSize: 6 }); + SHOW(display.getContainer()); + uniform.create(display.DEBUG); +} + +// Map creation / Dungeon / Rogue + +let rogue = new ROT.Map.Rogue(w, h); +display = new ROT.Display({ width: w, height: h, fontSize: 6 }); +SHOW(display.getContainer()); +rogue.create(display.DEBUG); + +// FOV computation / Precise shadowcasting + +ROT.RNG.setSeed(12345); +// Not supported in ES6/TS2 +// ROT.DEFAULT_WIDTH = 80; +// ROT.DEFAULT_HEIGHT = 30; + +display = new ROT.Display({ fontSize: 2 }); +SHOW(display.getContainer()); + +/* create a map */ +let data_uniform: any = {}; +new ROT.Map.Uniform().create((x: number, y: number, type: number) => { + data_uniform[x + "," + y] = type; + display.DEBUG(x, y, type); +}); + +/* input callback */ +let lightPasses = (x: number, y: number) => { + let key = x + "," + y; + if (key in data_uniform) { return (data_uniform[key] === 0); } + return false; +}; + +let fov = new ROT.FOV.PreciseShadowcasting(lightPasses); + +/* output callback */ +fov.compute(50, 22, 10, (x, y, r, visibility) => { + let ch = (r ? "" : "@"); + let color = (data_uniform[x + "," + y] ? "#aa0" : "#660"); + display.draw(x, y, ch, "#fff", color); +}); + +// FOV computation / Recursive shadowcasting + +ROT.RNG.setSeed(12345); +const DIR_NORTH = 0; +const DIR_WEST = 6; + +display = new ROT.Display({ fontSize: 12 }); +SHOW(display.getContainer()); + +/* create a map */ +data_uniform = {}; +new ROT.Map.Uniform().create((x: number, y: number, type: number) => { + data_uniform[x + "," + y] = type; + display.DEBUG(x, y, type); +}); + +/* input callback */ +lightPasses = (x: number, y: number) => { + let key = x + "," + y; + if (key in data_uniform) { return (data_uniform[key] === 0); } + return false; +}; + +let fov2 = new ROT.FOV.RecursiveShadowcasting(lightPasses); + +/* output callback for mob with bad vision */ +fov2.compute90(50, 22, 10, DIR_WEST, (x: number, y: number, r: number, visibility: number) => { + let ch = (r ? "1" : "@"); + let color = (data_uniform[x + "," + y] ? "#aa0" : "#660"); + display.draw(x, y, ch, "#fff", color); +}); + +/* output callback for second mob with better vision */ +fov2.compute180(57, 14, 10, DIR_NORTH, (x: number, y: number, r: number, visibility: number) => { + let ch = (r ? "2" : "@"); + let color = (data_uniform[x + "," + y] ? "#aa0" : "#660"); + display.draw(x, y, ch, "#fff", color); +}); + +/* output callback for third mob with supernatural vision */ +fov2.compute(65, 5, 10, (x: number, y: number, r: number, visibility: number) => { + let ch = (r ? "3" : "@"); + let color = (data_uniform[x + "," + y] ? "#aa0" : "#660"); + display.draw(x, y, ch, "#fff", color); +}); + +// Color / Converting string → array +SHOW( + ROT.Color.fromString("rgb(10, 128, 230)"), + ROT.Color.fromString("#faa"), + ROT.Color.fromString("#83fcc4"), + ROT.Color.fromString("goldenrod") +); + +// Color / Converting array → string +SHOW( + ROT.Color.toRGB([10, 128, 230]), + ROT.Color.toHex([10, 128, 230]) +); + +// Color / Converting between RGB and HSL +SHOW( + ROT.Color.rgb2hsl([51, 102, 51]), + ROT.Color.hsl2rgb([0.333, 0.333, 0.3]) +); + +// Color / Adding and mixing colors +SHOW( /* addition = lightening */ + ROT.Color.add([10, 128, 230], [200, 10, 15], [30, 30, 100]), + ROT.Color.add_([10, 128, 230], [200, 10, 15]) +); +SHOW( /* multiplication = darkening */ + ROT.Color.multiply([10, 128, 230], [200, 10, 15]), + ROT.Color.multiply_([10, 128, 230], [200, 10, 15]) +); + +// Color / Interpolating between two colors +SHOW( + /* computed in RGB space */ + ROT.Color.interpolate([10, 128, 230], [30, 255, 255], 0.3), + + /* computed in HSL space */ + ROT.Color.interpolateHSL([10, 128, 230], [30, 255, 255], 0.3) +); + +// Color / Creating random letiants +SHOW( + ROT.Color.randomize([100, 128, 230], [30, 10, 20]), + ROT.Color.randomize([100, 128, 230], [30, 10, 20]), + ROT.Color.randomize([100, 128, 230], [30, 10, 20]) +); + +// Color / Lighting +ROT.RNG.setSeed(12345); + +let mapData: any = {}; +let lightData: { [key: string]: [number, number, number] } = {}; + +/* build a map */ +cellular = new ROT.Map.Cellular().randomize(0.5); +let createCallback = (x: number, y: number, value: number) => { + mapData[x + "," + y] = value; +}; +for (let i = 0; i < 4; i++) { + cellular.create(createCallback); +} + +/* prepare a FOV algorithm */ +lightPasses = (x: number, y: number) => { + return (mapData[x + "," + y] === 1); +}; +fov = new ROT.FOV.PreciseShadowcasting(lightPasses, { topology: 4 }); + +/* prepare a lighting algorithm */ +let reflectivity = (x: number, y: number) => { + return (mapData[x + "," + y] === 1 ? 0.3 : 0); +}; +let lighting = new ROT.Lighting(reflectivity, { range: 12, passes: 2 }); +lighting.setFOV(fov); +lighting.setLight(12, 12, [240, 240, 30]); +lighting.setLight(20, 20, [240, 60, 60]); +lighting.setLight(45, 25, [200, 200, 200]); + +let lightingCallback = (x: number, y: number, color: [number, number, number]) => { + lightData[x + "," + y] = color; +}; +lighting.compute(lightingCallback); + +/* draw the resulting mix of mapData and lightData */ +display = new ROT.Display({ fontSize: 8 }); +SHOW(display.getContainer()); + +/* all cells are lit by ambient light; some are also lit by light sources */ +let ambientLight: ROT.ColorArray = [100, 100, 100]; +for (let id in mapData) { + let parts = id.split(","); + let x = parseInt(parts[0], 10); + let y = parseInt(parts[1], 10); + + let baseColor: ROT.ColorArray = (mapData[id] ? [100, 100, 100] : [50, 50, 50]); + let light = ambientLight; + + if (id in lightData) { /* add light from our computation */ + light = ROT.Color.add(light, lightData[id]); + } + + let finalColor = ROT.Color.multiply(baseColor, light); + display.draw(x, y, "@", "white", ROT.Color.toRGB(finalColor)); +} + +// Pathfinding / Dijkstra's algorithm + +ROT.RNG.setSeed(12345); +display = new ROT.Display({ width: w, height: h, fontSize: 6 }); +SHOW(display.getContainer()); + +/* generate map and store its data */ +let uni_data: any = {}; +let uni_map = new ROT.Map.Uniform(w, h); +uni_map.create((x, y, value) => { + uni_data[x + "," + y] = value; + display.DEBUG(x, y, value); +}); + +/* input callback informs about map structure */ +let passableCallback = (x: number, y: number) => { + return (uni_data[x + "," + y] === 0); +}; + +/* prepare path to given coords */ +let dijkstra = new ROT.Path.Dijkstra(98, 38, passableCallback); + +/* compute from given coords #1 */ +dijkstra.compute(8, 45, (x: number, y: number) => { + display.draw(x, y, "", "", "#800"); +}); + +/* compute from given coords #2 */ +dijkstra.compute(130, 8, (x: number, y: number) => { + display.draw(x, y, "", "", "#800"); +}); + +/* highlight */ +display.draw(8, 45, "", "", "#3f3"); +display.draw(130, 8, "", "", "#3f3"); +display.draw(98, 38, "", "", "#f33"); + +// Pathfinding / A* algorithm + +ROT.RNG.setSeed(12345); +display = new ROT.Display({ width: w, height: h, fontSize: 6 }); +SHOW(display.getContainer()); + +/* generate map and store its data */ +uni_map = new ROT.Map.Uniform(w, h); +uni_map.create((x: number, y: number, value: number) => { + uni_data[x + "," + y] = value; + display.DEBUG(x, y, value); +}); + +/* input callback informs about map structure */ +passableCallback = (x: number, y: number) => { + return (uni_data[x + "," + y] === 0); +}; + +/* prepare path to given coords */ +let astar = new ROT.Path.AStar(98, 38, passableCallback); + +/* compute from given coords #1 */ +astar.compute(8, 45, (x: number, y: number) => { + display.draw(x, y, "", "", "#800"); +}); + +/* compute from given coords #2 */ +astar.compute(130, 8, (x: number, y: number) => { + display.draw(x, y, "", "", "#800"); +}); + +/* highlight */ +display.draw(8, 45, "", "", "#3f3"); +display.draw(130, 8, "", "", "#3f3"); +display.draw(98, 38, "", "", "#f33"); + +// Noise Generation +let noise = new ROT.Noise.Simplex(); + +display = new ROT.Display({ width: w, height: h, fontSize: 3 }); +SHOW(display.getContainer()); + +for (let j = 0; j < h; j++) { + for (let i = 0; i < w; i++) { + let val = noise.get(i / 20, j / 20) * 255; + + let r = ~~(val > 0 ? val : 0); + let g = ~~(val < 0 ? -val : 0); + display.draw(i, j, "", "", "rgb(" + r + "," + g + ",0)"); + } +} +// ---- +noise = new ROT.Noise.Simplex(); + +display = new ROT.Display({ width: w, height: h, fontSize: 12, layout: "hex" }); +SHOW(display.getContainer()); + +for (let j = 0; j < h; j++) { + for (let i = j % 2; i < w; i += 2) { + let val = noise.get(i / 60, j / 60) * 255; + + let r = ~~(val > 0 ? val : 0); + let g = ~~(val < 0 ? -val : 0); + display.draw(i, j, "", "", "rgb(" + r + "," + g + ",0)"); + } +} + +// Timing & scheduling / event queue + +let queue = new ROT.EventQueue(); + +queue.add("event 1", 100); /* queued after 100 time units */ +queue.add("event 2", 10); /* queued after 10 time units */ +queue.add("event 3", 50); /* queued after 50 time units */ + +queue.remove("event 2"); +SHOW( + queue.get(), + queue.get(), + queue.getTime() +); + +// Timing & scheduling / Simple scheduler + +let scheduler = new ROT.Scheduler.Simple(); + +/* generate some actors */ +for (let i = 0; i < 4; i++) { + scheduler.add(i + 1, true); /* true = recurring actor */ +} + +/* simulate several turns */ +let turns: any = []; +for (let i = 0; i < 20; i++) { + let current = scheduler.next(); + turns.push(current); +} + +SHOW("\nGenerated order of actors:"); +SHOW(turns.join(" ") + " ..."); + +// Timing & scheduling / Speed scheduler + +scheduler = new ROT.Scheduler.Speed(); + +class Actor { + constructor(public speed: number, public number: number) { } + + getSpeed() { return this.speed; } +} + +/* generate some actors */ +for (let i = 0; i < 4; i++) { + let actor = new Actor(ROT.RNG.getPercentage(), i + 1); + scheduler.add(actor, true); + SHOW("Object #%s has speed %s.".format(actor.number, actor.speed)); +} + +/* simulate several turns */ +turns = []; +for (let i = 0; i < 40; i++) { + let current = scheduler.next(); + turns.push(current.number); +} + +SHOW("\nGenerated order of turns:"); +SHOW(turns.join(" ") + " ..."); + +// Timing & scheduling / Action-duration scheduler + +let act_scheduler = new ROT.Scheduler.Action(); + +/* generate some actors */ +for (let i = 0; i < 4; i++) { + act_scheduler.add(i + 1, true, i); /* last argument - initial delay */ +} + +/* simulate several turns */ +template = "Actor %s performing action for %s time units (current time: %s)"; +for (let i = 0; i < 20; i++) { + let current = act_scheduler.next(); + + let actionDuration = Math.ceil(ROT.RNG.getUniform() * 20); + act_scheduler.setDuration(actionDuration); + + let padded = actionDuration.toString().lpad("0"); + SHOW(template.format(current, padded, act_scheduler.getTime())); +} + +// Timing & scheduling / Engine / Asynchronous game engine +scheduler = new ROT.Scheduler.Simple(); +let engine = new ROT.Engine(scheduler); +let output: any = []; + +class Actor1 { + constructor(public lives: number) { } + + act() { + output.push("."); + this.lives--; + if (!this.lives) { + scheduler.remove(actor1); + engine.lock(); /* pause execution */ + setTimeout(unlock, 500); /* wait for 500ms */ + } + } +} + +/* sample actor: pauses the execution when dead */ +let actor1 = new Actor1(3); +scheduler.add(actor1, true); + +class Actor2 { + act() { + output.push("@"); + } +} + +let unlock = () => { /* called asynchronously */ + let actor2 = new Actor2(); + + output = []; + scheduler.add(actor2, false); /* add second (non-repeating) actor */ + engine.unlock(); /* continue execution */ + SHOW(output.join("")); +}; + +engine.start(); +SHOW(output.join("")); + +// Timing & scheduling / Engine / Promises + +scheduler = new ROT.Scheduler.Simple(); +engine = new ROT.Engine(scheduler); +output = []; + +/* sample actor: pauses the execution when dead */ +class Actor3 { + constructor(public lives: number) { } + + act() { + let done: any = null; + let promise = { + then(cb: any) { done = cb; } + }; + + output.push("."); + SHOW(output.join("")); + this.lives--; + + /* if alive, wait for 500ms for next turn */ + if (this.lives) { + setTimeout(() => { done(); }, 500); + } + + return promise; + } +} +let actor3 = new Actor3(3); + +scheduler.add(actor3, true); + +engine.start(); + +// String generator + +let sg = new ROT.StringGenerator(); + +let req = new XMLHttpRequest(); +req.open("get", "java.txt", true); +req.send(); + +req.onreadystatechange = () => { + if (req.readyState !== 4) { return; } + + let lines = req.responseText.split("\n"); + while (lines.length) { + let line = lines.pop()!.trim(); + if (!line) { continue; } + sg.observe(line); + } + + for (let i = 0; i < 20; i++) { SHOW(sg.generate()); } +}; + +// Hex support / Displaying hexes +display = new ROT.Display({ width: 8, height: 5 }); +SHOW(display.getContainer()); + +for (let y = 0; y < 5; y++) { + for (let x = y % 2; x < 8; x += 2) { + display.draw(x, y, "•"); + } +} +// ---- + +display = new ROT.Display({ width: 8, height: 5, layout: "hex" }); +SHOW(display.getContainer()); + +for (let y = 0; y < 5; y++) { + for (let x = y % 2; x < 8; x += 2) { + let bg = ["#333", "#666", "#999", "#ccc", "#fff"].random(); + display.draw(x, y, "•", "#000", bg); + } +} +// ---- + +display = new ROT.Display({ + width: 10, height: 4, spacing: 2.5, + layout: "hex", transpose: true +}); +SHOW(display.getContainer()); + +for (let y = 0; y < 4; y++) { + for (let x = y % 2; x < 10; x += 2) { + let bg = ["#333", "#666", "#999", "#ccc", "#fff"].random(); + display.draw(x, y, x + "," + y, "#000", bg); + } +} + +// Hex support / Cellular dungeon generator + +display = new ROT.Display({ width: w, height: h, fontSize: 10, layout: "hex" }); +SHOW(display.getContainer()); + +/* hexagonal map and rules */ +let cell_map = new ROT.Map.Cellular(w, h, { + topology: 6, + born: [4, 5, 6], + survive: [3, 4, 5, 6] +}); + +/* initialize with irregularly random values */ +for (let i = 0; i < w; i++) { + for (let j = 0; j < h; j++) { + let dx = i / w - 0.5; + let dy = j / h - 0.5; + let dist = Math.pow(dx * dx + dy * dy, 0.3); + if (ROT.RNG.getUniform() < dist) { cell_map.set(i, j, 1); } + } +} + +/* generate four iterations, show the last one */ +for (let i = 4; i >= 0; i--) { + cell_map.create(i ? undefined : display.DEBUG); +} + +// Hex support / Pathfinding + +ROT.RNG.setSeed(12345); +display = new ROT.Display({ width: w, height: h, fontSize: 6, layout: "hex" }); +SHOW(display.getContainer()); + +/* generate map and store its data */ +let cell_data: any = {}; +cell_map = new ROT.Map.Cellular(w, h, { + topology: 6, + born: [4, 5, 6], + survive: [3, 4, 5, 6] +}); +cell_map.randomize(0.48); +cell_map.create(); /* two iterations */ +cell_map.create((x: number, y: number, value: number) => { + cell_data[x + "," + y] = value; + display.DEBUG(x, y, value); +}); + +/* input callback informs about map structure */ +passableCallback = (x: number, y: number) => { + return (cell_data[x + "," + y] === 0); +}; + +/* prepare path to given coords */ +dijkstra = new ROT.Path.Dijkstra(120, 64, passableCallback, { topology: 6 }); + +/* compute from given coords */ +dijkstra.compute(30, 16, (x: number, y: number) => { + display.draw(x, y, "", "", "#800"); +}); + +/* highlight */ +display.draw(30, 16, "", "", "#3f3"); +display.draw(120, 64, "", "", "#f33"); + +// Hex support / Field of view + +ROT.RNG.setSeed(12345); + +display = new ROT.Display({ fontSize: 12, layout: "hex" }); +SHOW(display.getContainer()); + +/* generate map and store its data */ +cell_data = {}; +cell_map = new ROT.Map.Cellular(undefined, undefined, { + topology: 6, + born: [4, 5, 6], + survive: [3, 4, 5, 6] +}); +cell_map.randomize(0.4); +cell_map.create((x: number, y: number, value: number) => { + cell_data[x + "," + y] = value; + display.DEBUG(x, y, value); +}); + +/* input callback */ +lightPasses = (x: number, y: number) => { + let key = x + "," + y; + if (key in cell_data) { return (cell_data[key] === 0); } + return false; +}; + +fov = new ROT.FOV.PreciseShadowcasting(lightPasses, { topology: 6 }); + +/* output callback */ +fov.compute(20, 14, 6, (x, y, r, vis) => { + let ch = (r ? "" : "@"); + let color = (cell_data[x + "," + y] ? "#aa0" : "#660"); + display.draw(x, y, ch, "#fff", color); +}); diff --git a/types/rot-js/tsconfig.json b/types/rot-js/tsconfig.json new file mode 100644 index 0000000000..fb42352fb7 --- /dev/null +++ b/types/rot-js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rot-js-tests.ts" + ] +} diff --git a/types/rot-js/tslint.json b/types/rot-js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rot-js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From cc6d29fd143e137aafb9236936cfa3bf04b74887 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 16 Jul 2017 00:58:43 +0200 Subject: [PATCH 0038/1139] [leaflet-providers] introduce typings --- types/leaflet-providers/index.d.ts | 32 +++++++++++++++++++ .../leaflet-providers-tests.ts | 28 ++++++++++++++++ types/leaflet-providers/tsconfig.json | 22 +++++++++++++ types/leaflet-providers/tslint.json | 1 + 4 files changed, 83 insertions(+) create mode 100644 types/leaflet-providers/index.d.ts create mode 100644 types/leaflet-providers/leaflet-providers-tests.ts create mode 100644 types/leaflet-providers/tsconfig.json create mode 100644 types/leaflet-providers/tslint.json diff --git a/types/leaflet-providers/index.d.ts b/types/leaflet-providers/index.d.ts new file mode 100644 index 0000000000..537d9d5574 --- /dev/null +++ b/types/leaflet-providers/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for leaflet-providers 1.1 +// Project: https://github.com/leaflet-extras/leaflet-providers#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace L { + namespace TileLayer { + class Provider extends TileLayer { + constructor(provider: string, options?: TileLayerOptions) + } + + namespace Provider { + const providers: ProvidersMap; + + interface ProvidersMap { + [providerName: string]: ProviderConfig; + } + + interface ProviderConfig { + url: string; + options?: TileLayerOptions; + variants?: { [variantName: string]: string | ProviderConfig }; + } + } + } + + namespace tileLayer { + function provider(provider: string, options?: TileLayerOptions): TileLayer.Provider; + } +} diff --git a/types/leaflet-providers/leaflet-providers-tests.ts b/types/leaflet-providers/leaflet-providers-tests.ts new file mode 100644 index 0000000000..5ab91e5b92 --- /dev/null +++ b/types/leaflet-providers/leaflet-providers-tests.ts @@ -0,0 +1,28 @@ +const map = L.map('map'); +L.tileLayer.provider('Stamen.Watercolor').addTo(map); + +L.tileLayer.provider('HERE.terrainDay', { + app_id: '', + app_code: '' +}).addTo(map); + +new L.TileLayer.Provider('MapBox').addTo(map); +new L.TileLayer.Provider('MapBox', {id: 'ID', accessToken: 'ACCESS_TOKEN'}).addTo(map); + +L.TileLayer.Provider.providers['nlmaps'] = { + url: 'https://geodata.nationaalgeoregister.nl/tiles/service/wmts/{variant}/EPSG:3857/{z}/{x}/{y}.png', + options: { + minZoom: 6, + maxZoom: 19, + bounds: [[50.5, 3.25], [54, 7.6]], + attribution: 'Kaartgegevens © Kadaster' + }, + variants: { + standaard: 'brtachtergrondkaart', + pastel: 'brtachtergrondkaartpastel', + grijs: 'brtachtergrondkaartgrijs', + luchtfoto: { + url: 'https://geodata.nationaalgeoregister.nl/luchtfoto/rgb/wmts/1.0.0/2016_ortho25/EPSG:3857/{z}/{x}/{y}.png', + } + } +}; diff --git a/types/leaflet-providers/tsconfig.json b/types/leaflet-providers/tsconfig.json new file mode 100644 index 0000000000..3cacd8e3db --- /dev/null +++ b/types/leaflet-providers/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "leaflet-providers-tests.ts" + ] +} diff --git a/types/leaflet-providers/tslint.json b/types/leaflet-providers/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/leaflet-providers/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 87972162a799369898730df15582dc634bd149d3 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 16 Jul 2017 11:07:59 +0200 Subject: [PATCH 0039/1139] [socketio-wildcard] introduce typings --- types/socketio-wildcard/index.d.ts | 15 ++++++++++++ .../socketio-wildcard-tests.ts | 24 +++++++++++++++++++ types/socketio-wildcard/tsconfig.json | 22 +++++++++++++++++ types/socketio-wildcard/tslint.json | 1 + 4 files changed, 62 insertions(+) create mode 100644 types/socketio-wildcard/index.d.ts create mode 100644 types/socketio-wildcard/socketio-wildcard-tests.ts create mode 100644 types/socketio-wildcard/tsconfig.json create mode 100644 types/socketio-wildcard/tslint.json diff --git a/types/socketio-wildcard/index.d.ts b/types/socketio-wildcard/index.d.ts new file mode 100644 index 0000000000..3170a27ca5 --- /dev/null +++ b/types/socketio-wildcard/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for socketio-wildcard 2.0 +// Project: https://github.com/hden/socketio-wildcard +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +/// + +import EventEmitter = NodeJS.EventEmitter; +import Socket = SocketIO.Socket; +import ClientSocket = SocketIOClient.Socket; + +export = sioWildcard; + +declare function sioWildcard(emitterCtor?: { prototype: typeof EventEmitter.prototype }): (socket: Socket | ClientSocket, next?: (err?: any) => void) => void; diff --git a/types/socketio-wildcard/socketio-wildcard-tests.ts b/types/socketio-wildcard/socketio-wildcard-tests.ts new file mode 100644 index 0000000000..3d479ef3f9 --- /dev/null +++ b/types/socketio-wildcard/socketio-wildcard-tests.ts @@ -0,0 +1,24 @@ +import ioBuilder = require('socket.io'); +const io = ioBuilder(); +import middlewareBuilder = require('socketio-wildcard'); +const middleware = middlewareBuilder(); + +io.use(middleware); + +io.on('connection', (socket) => { + socket.on('*', (packet) => { + // client.emit('foo', 'bar', 'baz') + packet.data === ['foo', 'bar', 'baz']; + }); +}); + +io.listen(8000); + +import clientIo = require('socket.io-client'); +const socket = clientIo('http://localhost'); +import patchBuilder = require('socketio-wildcard'); +const patch = patchBuilder(clientIo.Manager); +patch(socket); + +socket.on('*', () => { +}); diff --git a/types/socketio-wildcard/tsconfig.json b/types/socketio-wildcard/tsconfig.json new file mode 100644 index 0000000000..ee0d3805f4 --- /dev/null +++ b/types/socketio-wildcard/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "socketio-wildcard-tests.ts" + ] +} diff --git a/types/socketio-wildcard/tslint.json b/types/socketio-wildcard/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/socketio-wildcard/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From de7a88f21c3163747ede22143e4eaa8836aff808 Mon Sep 17 00:00:00 2001 From: Sa-ryong Kang Date: Sun, 16 Jul 2017 18:30:13 +0900 Subject: [PATCH 0040/1139] initial update for react-daum-postcode --- types/react-daum-postcode/index.d.ts | 23 +++++++++++++++ types/react-daum-postcode/package.json | 5 ++++ .../react-daum-postcode-tests.tsx | 29 +++++++++++++++++++ types/react-daum-postcode/tsconfig.json | 25 ++++++++++++++++ types/react-daum-postcode/tslint.json | 1 + 5 files changed, 83 insertions(+) create mode 100644 types/react-daum-postcode/index.d.ts create mode 100644 types/react-daum-postcode/package.json create mode 100644 types/react-daum-postcode/react-daum-postcode-tests.tsx create mode 100644 types/react-daum-postcode/tsconfig.json create mode 100644 types/react-daum-postcode/tslint.json diff --git a/types/react-daum-postcode/index.d.ts b/types/react-daum-postcode/index.d.ts new file mode 100644 index 0000000000..e318a0a8c3 --- /dev/null +++ b/types/react-daum-postcode/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for react-daum-postcode 1.2.1 +// Project: https://github.com/kimminsik-bernard/react-daum-postcode +// Definitions by: Sa-ryong Kang +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Component } from 'react'; + +export interface DaumPostcodeProps { + onComplete?: any; + width?: any; + height?: any; + autoClose?: any; + autoResize?: any; + animation?: any; + style?: any; + defaultQuery?: any; + theme?: any; +} + +export default class DaumPostcode extends Component { + render(): JSX.Element; +} \ No newline at end of file diff --git a/types/react-daum-postcode/package.json b/types/react-daum-postcode/package.json new file mode 100644 index 0000000000..ea72a99f2c --- /dev/null +++ b/types/react-daum-postcode/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "react-daum-postcode": "^1.2.1" + } +} \ No newline at end of file diff --git a/types/react-daum-postcode/react-daum-postcode-tests.tsx b/types/react-daum-postcode/react-daum-postcode-tests.tsx new file mode 100644 index 0000000000..7e58d5f251 --- /dev/null +++ b/types/react-daum-postcode/react-daum-postcode-tests.tsx @@ -0,0 +1,29 @@ +import * as React from 'react'; +import DaumPostcode from 'react-daum-postcode'; + +class Postcode extends React.Component { + handleAddress = (data: any) => { + let fullAddress: string = data.address; + let extraAddress = ''; + + if (data.addressType === 'R') { + if (data.bname !== '') { + extraAddress += data.bname; + } + if (data.buildingName !== '') { + extraAddress += (extraAddress !== '' ? `, ${data.buildingName}` : data.buildingName); + } + fullAddress += (extraAddress !== '' ? ` (${extraAddress})` : ''); + } + + console.log(fullAddress); // e.g. '서울 성동구 왕십리로2길 20 (성수동1가)' + } + + render() { + return ( + + ); + } +} \ No newline at end of file diff --git a/types/react-daum-postcode/tsconfig.json b/types/react-daum-postcode/tsconfig.json new file mode 100644 index 0000000000..190eebaf9d --- /dev/null +++ b/types/react-daum-postcode/tsconfig.json @@ -0,0 +1,25 @@ +{ + "files": [ + "index.d.ts", + "react-daum-postcode-tests.tsx" + ], + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "jsx": "react", + "experimentalDecorators": true, + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/types/react-daum-postcode/tslint.json b/types/react-daum-postcode/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/react-daum-postcode/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file From e930438f4bb08be68e1b8149d3fb4200302ecd3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= Date: Sun, 16 Jul 2017 16:45:38 +0900 Subject: [PATCH 0041/1139] use strictNullChecks mode --- types/chart.js/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/chart.js/tsconfig.json b/types/chart.js/tsconfig.json index a798d69e23..aae63d6394 100644 --- a/types/chart.js/tsconfig.json +++ b/types/chart.js/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" From e144f0643cd2ec6cdd71170e41ec08501a85a574 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= Date: Sun, 16 Jul 2017 16:50:37 +0900 Subject: [PATCH 0042/1139] chart instance has properties "ctx", "canvas", "chartArea" ctx, canvas https://github.com/chartjs/Chart.js/blob/master/src/core/core.controller.js#L78-L79 chartArea https://github.com/chartjs/Chart.js/blob/master/src/core/core.layoutService.js#L417-L423 --- types/chart.js/chart.js-tests.ts | 9 +++++++++ types/chart.js/index.d.ts | 10 ++++++++++ 2 files changed, 19 insertions(+) diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index b9ffd7a8f6..8e5588a232 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -26,3 +26,12 @@ let chart: Chart = new Chart(new CanvasRenderingContext2D(), { } }); chart.update(); + +console.log(chart.ctx && chart.ctx.font); +console.log(chart.canvas && chart.canvas.tagName); +if (chart.chartArea) { + console.log(chart.chartArea.top); + console.log(chart.chartArea.right); + console.log(chart.chartArea.bottom); + console.log(chart.chartArea.left); +} diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 63c30a739b..3620993688 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -26,6 +26,9 @@ declare class Chart { getElementAtEvent: (e: any) => {}; getElementsAtEvent: (e: any) => Array<{}>; getDatasetAtEvent: (e: any) => Array<{}>; + ctx: CanvasRenderingContext2D|null; + canvas: HTMLCanvasElement|null; + chartArea: Chart.ChartArea; static pluginService: PluginServiceStatic; static defaults: { @@ -80,6 +83,13 @@ declare namespace Chart { type PositionType = 'left' | 'right' | 'top' | 'bottom'; + interface ChartArea { + top: number; + right: number; + bottom: number; + left: number; + } + interface ChartLegendItem { text?: string; fillStyle?: string; From 6805914e4c78129b162350d375de465d89ce525f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= Date: Sun, 16 Jul 2017 17:19:49 +0900 Subject: [PATCH 0043/1139] type of transformed data should be not only string but number. Some convenient function for label conversion (e.g. Math.floor) returns number. It is harmless because when displaying, toString() called implicitly. --- types/chart.js/chart.js-tests.ts | 3 +++ types/chart.js/index.d.ts | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index 8e5588a232..853d8e489d 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -20,6 +20,9 @@ let chart: Chart = new Chart(new CanvasRenderingContext2D(), { options: { scales: { xAxes: [{ + ticks: { + callback: Math.floor + }, gridLines: { display: false } }] } diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 3620993688..b4e65ec12f 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -317,7 +317,7 @@ declare namespace Chart { interface TickOptions { autoSkip?: boolean; - callback?(value: any, index: any, values: any): string; + callback?(value: any, index: any, values: any): string|number; display?: boolean; fontColor?: ChartColor; fontFamily?: string; From ff91164e03c91baee3483d0f84ae8f9cb469f83f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= Date: Sun, 16 Jul 2017 18:13:55 +0900 Subject: [PATCH 0044/1139] add properties of ChartTooltipOptions http://www.chartjs.org/docs/latest/configuration/tooltip.html filter, intersect, itemSort, position, caretPadding, displayColors, borderColor, borderWidth --- types/chart.js/chart.js-tests.ts | 10 ++++++++++ types/chart.js/index.d.ts | 8 ++++++++ 2 files changed, 18 insertions(+) diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index 853d8e489d..0d51870168 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -18,6 +18,16 @@ let chart: Chart = new Chart(new CanvasRenderingContext2D(), { ] }, options: { + tooltips: { + filter: data => Number(data.yLabel) > 0, + intersect: true, + itemSort: (a, b) => Math.random() - 0.5, + position: "average", + caretPadding: 2, + displayColors: true, + borderColor: "rgba(0,0,0,0)", + borderWidth: 1, + }, scales: { xAxes: [{ ticks: { diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index b4e65ec12f..bab754a821 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -201,6 +201,7 @@ declare namespace Chart { enabled?: boolean; custom?(a: any): void; mode?: string; + intersect?: boolean; backgroundColor?: ChartColor; titleFontFamily?: string; titleFontSize?: number; @@ -225,6 +226,13 @@ declare namespace Chart { cornerRadius?: number; multiKeyBackground?: string; callbacks?: ChartTooltipCallback; + filter?(item: ChartTooltipItem): boolean; + itemSort?(itemA: ChartTooltipItem, itemB: ChartTooltipItem): number; + position?: "average"|"nearest"; + caretPadding?: number; + displayColors?: boolean; + borderColor?: ChartColor; + borderWidth?: number; } interface ChartHoverOptions { From 56d8e354be30391e3fa140610e3312d8202e23a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= Date: Sun, 16 Jul 2017 18:25:26 +0900 Subject: [PATCH 0045/1139] Add property "intersect" to ChartHoverOptions http://www.chartjs.org/docs/latest/general/interactions/ --- types/chart.js/chart.js-tests.ts | 3 +++ types/chart.js/index.d.ts | 1 + 2 files changed, 4 insertions(+) diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index 0d51870168..5c2dab60f9 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -18,6 +18,9 @@ let chart: Chart = new Chart(new CanvasRenderingContext2D(), { ] }, options: { + hover: { + intersect: true + }, tooltips: { filter: data => Number(data.yLabel) > 0, intersect: true, diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index bab754a821..dab40d797e 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -238,6 +238,7 @@ declare namespace Chart { interface ChartHoverOptions { mode?: string; animationDuration?: number; + intersect?: boolean; onHover?(active: any): void; } From c402b5ed0e2650addac3122c7bfa4db6d80624f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=AD=A6=E7=94=B0=20=E6=86=B2=E5=A4=AA=E9=83=8E?= Date: Sun, 16 Jul 2017 18:40:35 +0900 Subject: [PATCH 0046/1139] Bump version to chart.js 2.6 and add my credit --- types/chart.js/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index dab40d797e..f1a39c84c4 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for Chart.js 2.4 +// Type definitions for Chart.js 2.6 // Project: https://github.com/nnnick/Chart.js // Definitions by: Alberto Nuti // Fabien Lavocat +// KentarouTakeda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From a4ef6371cddbd424cb9e76e144646a555d6940f5 Mon Sep 17 00:00:00 2001 From: Bradley Ayers Date: Sun, 16 Jul 2017 20:07:43 +1000 Subject: [PATCH 0047/1139] Add pg-connection-string. --- types/pg-connection-string/index.d.ts | 17 ++++++++++++++ .../pg-connection-string-tests.ts | 13 +++++++++++ types/pg-connection-string/tsconfig.json | 22 +++++++++++++++++++ types/pg-connection-string/tslint.json | 1 + 4 files changed, 53 insertions(+) create mode 100644 types/pg-connection-string/index.d.ts create mode 100644 types/pg-connection-string/pg-connection-string-tests.ts create mode 100644 types/pg-connection-string/tsconfig.json create mode 100644 types/pg-connection-string/tslint.json diff --git a/types/pg-connection-string/index.d.ts b/types/pg-connection-string/index.d.ts new file mode 100644 index 0000000000..bc2f8bafa5 --- /dev/null +++ b/types/pg-connection-string/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for pg-connection-string 0.1 +// Project: https://github.com/iceddev/pg-connection-string +// Definitions by: Bradley Ayers +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export function parse(connectionString: string): { + host: string; + database: string; + port: string; + application_name?: string; + client_encoding?: string; + fallback_application_name?: string; + user?: string; + password?: string; + ssl?: boolean; +}; diff --git a/types/pg-connection-string/pg-connection-string-tests.ts b/types/pg-connection-string/pg-connection-string-tests.ts new file mode 100644 index 0000000000..bf9698a7b9 --- /dev/null +++ b/types/pg-connection-string/pg-connection-string-tests.ts @@ -0,0 +1,13 @@ +import { parse } from 'pg-connection-string'; + +const parts = parse('postgres://user:password@host:port/dbname'); + +parts.application_name; +parts.client_encoding; +parts.database; +parts.fallback_application_name; +parts.host; +parts.password; +parts.port; +parts.ssl; +parts.user; diff --git a/types/pg-connection-string/tsconfig.json b/types/pg-connection-string/tsconfig.json new file mode 100644 index 0000000000..780089a760 --- /dev/null +++ b/types/pg-connection-string/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pg-connection-string-tests.ts" + ] +} diff --git a/types/pg-connection-string/tslint.json b/types/pg-connection-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pg-connection-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f55a0d804ff9ac2d1dd736c1b8ea1e8adbddd501 Mon Sep 17 00:00:00 2001 From: Sa-ryong Kang Date: Sun, 16 Jul 2017 19:26:44 +0900 Subject: [PATCH 0048/1139] downgrade target TypeScript version to 2.3 from Sa-ryong/react-daum-postcode --- types/react-daum-postcode/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-daum-postcode/index.d.ts b/types/react-daum-postcode/index.d.ts index e318a0a8c3..6f3ea43b9d 100644 --- a/types/react-daum-postcode/index.d.ts +++ b/types/react-daum-postcode/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/kimminsik-bernard/react-daum-postcode // Definitions by: Sa-ryong Kang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.3 import { Component } from 'react'; From 94cee905101111c85c32e7542bd57c396957f1ff Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 16 Jul 2017 15:38:47 +0200 Subject: [PATCH 0049/1139] [proj4leaflet] remove types duplicated from proj4 --- types/proj4leaflet/index.d.ts | 38 +++++++++-------------------------- 1 file changed, 10 insertions(+), 28 deletions(-) diff --git a/types/proj4leaflet/index.d.ts b/types/proj4leaflet/index.d.ts index bed6682dc8..e40ecbfe89 100644 --- a/types/proj4leaflet/index.d.ts +++ b/types/proj4leaflet/index.d.ts @@ -3,11 +3,12 @@ // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +import * as proj4 from "../proj4"; +import * as Leaflet from "leaflet"; -declare namespace L { - namespace Proj { - class CRS implements L.CRS { +declare global { + namespace L.Proj { + class CRS implements Leaflet.CRS { projection: Projection; transformation: Transformation; code?: string; @@ -15,7 +16,7 @@ declare namespace L { wrapLat?: [number, number]; infinite: boolean; - constructor(projection: InterfaceProjection, options?: ProjCRSOptions); + constructor(projection: proj4.InterfaceProjection, options?: ProjCRSOptions); constructor(code: string, proj4def: string, options?: ProjCRSOptions); latLngToPoint(latlng: LatLngExpression, zoom: number): Point; @@ -37,12 +38,12 @@ declare namespace L { wrapLatLng(latlng: LatLng | LatLngLiteral): LatLng; } - class GeoJSON extends L.GeoJSON { + class GeoJSON extends Leaflet.GeoJSON { } const geoJson: (geojson?: GeoJSONGeoJsonObject, options?: GeoJSONOptions) => GeoJSON; - class ImageOverlay extends L.ImageOverlay { + class ImageOverlay extends Leaflet.ImageOverlay { } const imageOverlay: (imageUrl: string, bounds: LatLngBoundsExpression, options?: ImageOverlayOptions) => ImageOverlay; @@ -54,26 +55,7 @@ declare namespace L { resolutions?: number[]; transformation?: Transformation; } - - interface InterfaceProjection { - datum: string; - b: number; - rf: number; - sphere: number; - es: number; - e: number; - ep2: number; - forward(coordinates: TemplateCoordinates): number[]; - inverse(coordinates: TemplateCoordinates): number[]; - } - - type TemplateCoordinates = number[] | InterfaceCoordinates; - - interface InterfaceCoordinates { - x: number; - y: number; - z?: number; - m?: number; - } } } + +export = L; From f9b28cd594c5ff6481451b81072faae382cf5239 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 16 Jul 2017 15:43:29 +0200 Subject: [PATCH 0050/1139] [proj4leaflet] fix import --- types/proj4leaflet/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/proj4leaflet/index.d.ts b/types/proj4leaflet/index.d.ts index e40ecbfe89..bab2b5f953 100644 --- a/types/proj4leaflet/index.d.ts +++ b/types/proj4leaflet/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import * as proj4 from "../proj4"; +import * as proj4 from "proj4"; import * as Leaflet from "leaflet"; declare global { From 4d7e518e6e4a7e09836fbcf3ea419e5effc1c371 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 16 Jul 2017 17:30:59 +0200 Subject: [PATCH 0051/1139] [iframe-resizer] add more specific and missing type definitions --- types/iframe-resizer/iframe-resizer-tests.ts | 49 ++- types/iframe-resizer/index.d.ts | 437 +++++++++++-------- 2 files changed, 286 insertions(+), 200 deletions(-) diff --git a/types/iframe-resizer/iframe-resizer-tests.ts b/types/iframe-resizer/iframe-resizer-tests.ts index d127f8bf36..186dc2ba47 100644 --- a/types/iframe-resizer/iframe-resizer-tests.ts +++ b/types/iframe-resizer/iframe-resizer-tests.ts @@ -1,32 +1,37 @@ -import {IFrameComponent, IFrameOptions, iframeResizer} from "iframe-resizer"; +import { IFrameComponent, IFrameOptions, iframeResizer } from "iframe-resizer"; function testOne(): void { - let iframe: HTMLIFrameElement = document.createElement('iframe'); - let options: IFrameOptions = {log: true}; - let components: IFrameComponent[] = iframeResizer(options, iframe); - if (components) { - components.forEach(component => console.log(component.iFrameResizer)); - } else { - console.log("No components"); - } + let iframe: HTMLIFrameElement = document.createElement('iframe'); + let options: IFrameOptions = {log: true}; + let components: IFrameComponent[] = iframeResizer(options, iframe); + if (components) { + components.forEach(component => console.log(component.iFrameResizer)); + } else { + console.log("No components"); + } } function testTwo(): void { - let iframe: HTMLIFrameElement = document.createElement('iframe'); - let components: IFrameComponent[] = iframeResizer({ - initCallback: () => { - console.log('Init'); - }, - closedCallback: () => { - console.log('Closed'); - } - }, iframe); - if (components) { - components.forEach(component => console.log(component.iFrameResizer)); - } else { - console.log("No components"); + let iframe: HTMLIFrameElement = document.createElement('iframe'); + let components: IFrameComponent[] = iframeResizer({ + initCallback: () => { + console.log('Init'); + }, + closedCallback: () => { + console.log('Closed'); } + }, iframe); + if (components) { + components.forEach(component => console.log(component.iFrameResizer)); + } else { + console.log("No components"); + } +} + +function testThree(): void { + iframeResizer({}, '.my-iframe'); } testOne(); testTwo(); +testThree(); diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 1a05833692..3dd26dd391 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -6,191 +6,272 @@ // tslint:disable:prefer-method-signature // tslint:disable-next-line:no-single-declare-module declare module 'iframe-resizer' { - // tslint:disable-next-line:interface-name - interface IFrameObject { - close(): void; - moveToAnchor(anchor: string): void; - resize(): void; - sendMessage(message: any): void; - } + // tslint:disable-next-line:interface-name + interface IFrameObject { + close(): void; + moveToAnchor(anchor: string): void; + resize(): void; + sendMessage(message: any, targetOrigin?: string): void; + } - // tslint:disable-next-line:interface-name - interface IFrameComponent extends HTMLIFrameElement { - iFrameResizer: IFrameObject; - } + // tslint:disable-next-line:interface-name + interface IFrameComponent extends HTMLIFrameElement { + iFrameResizer: IFrameObject; + } - // tslint:disable-next-line:interface-name - interface IFrameOptions { - /** - * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. - * Disable if using size method with custom dimensions. - */ - autoResize?: boolean; - /** - * Override the body background style in the iFrame. - */ - bodyBackground?: string; - /** - * Override the default body margin style in the iFrame. A string can be any valid value for the - * CSS margin attribute, for example '8px 3em'. A number value is converted into px. - */ - bodyMargin?: number; - /** - * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. - * If your iFrame navigates between different domains, ports or protocols; then you will need to - * provide an array of URLs or disable this option. - */ - checkOrigin?: boolean; - /** - * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. - */ - inPageLinks?: boolean; - /** - * Height calculation method. - */ - heightCalculationMethod?: string; - /** - * Set iFrame Id - */ - id?: string; - /** - * In browsers that don't support mutationObserver, such as IE10, the library falls back to using - * setInterval, to check for changes to the page size. - */ - interval?: number; - /** - * Setting the log option to true will make the scripts in both the host page and the iFrame output - * everything they do to the JavaScript console so you can see the communication between the two scripts. - */ - log?: boolean; - /** - * Set maximum height of iFrame. - */ - maxHeight?: number; - /** - * Set maximum width of iFrame. - */ - maxWidth?: number; - /** - * Set minimum height of iFrame. - */ - minHeight?: number; - /** - * Set minimum width of iFrame. - */ - minWidth?: number; - /** - * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame - * can be resized independently of the browser window. Selecting this value can cause issues with some - * height calculation methods on mobile devices. - */ - resizeFrom?: string; - /** - * Enable scroll bars in iFrame. - */ - scrolling?: boolean; - /** - * Resize iFrame to content height. - */ - sizeHeight?: boolean; - /** - * Resize iFrame to content width. - */ - sizeWidth?: boolean; - /** - * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. - */ - tolerance?: number; - /** - * Width calculation method. - */ - widthCalculationMethod?: string; - /** - * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. - */ - closedCallback?: (iframeId?: string) => void; - /** - * Initial setup callback function. - */ - initCallback?: (iframe?: IFrameComponent) => void; - /** - * Receive message posted from iFrame with the parentIFrame.sendMessage() method. - */ - messageCallback?: (data: IFrameMessageData) => void; - /** - * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width - * and the type of event that triggered the iFrame to resize. - */ - resizedCallback?: (data: IFrameResizedData) => void; - /** - * Called before the page is repositioned after a request from the iFrame, due to either an in page link, - * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). - * If this callback function returns false, it will stop the library from repositioning the page, so that - * you can implement your own animated page scrolling instead. - */ - scrollCallback?: (data: IFrameScrollData) => boolean; - } + // tslint:disable-next-line:interface-name + interface IFrameOptions { + /** + * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. + * Disable if using size method with custom dimensions. + */ + autoResize?: boolean; + /** + * Override the body background style in the iFrame. + */ + bodyBackground?: string; + /** + * Override the default body margin style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyMargin?: number; + /** + * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. + * If your iFrame navigates between different domains, ports or protocols; then you will need to + * provide an array of URLs or disable this option. + */ + checkOrigin?: boolean; + /** + * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. + */ + inPageLinks?: boolean; + /** + * Height calculation method. + */ + heightCalculationMethod?: HeightCalculationMethod; + /** + * Set iFrame Id + */ + id?: string; + /** + * In browsers that don't support mutationObserver, such as IE10, the library falls back to using + * setInterval, to check for changes to the page size. + */ + interval?: number; + /** + * Setting the log option to true will make the scripts in both the host page and the iFrame output + * everything they do to the JavaScript console so you can see the communication between the two scripts. + */ + log?: boolean; + /** + * Set maximum height of iFrame. + */ + maxHeight?: number; + /** + * Set maximum width of iFrame. + */ + maxWidth?: number; + /** + * Set minimum height of iFrame. + */ + minHeight?: number; + /** + * Set minimum width of iFrame. + */ + minWidth?: number; + /** + * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame + * can be resized independently of the browser window. Selecting this value can cause issues with some + * height calculation methods on mobile devices. + */ + resizeFrom?: 'parent' | 'child'; + /** + * Enable scroll bars in iFrame. + */ + scrolling?: boolean | 'auto'; + /** + * Resize iFrame to content height. + */ + sizeHeight?: boolean; + /** + * Resize iFrame to content width. + */ + sizeWidth?: boolean; + /** + * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. + */ + tolerance?: number; + /** + * Width calculation method. + */ + widthCalculationMethod?: WidthCalculationMethod; + /** + * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. + */ + closedCallback?: (iframeId: string) => void; + /** + * Initial setup callback function. + */ + initCallback?: (iframe: IFrameComponent) => void; + /** + * Receive message posted from iFrame with the parentIFrame.sendMessage() method. + */ + messageCallback?: (data: IFrameMessageData) => void; + /** + * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width + * and the type of event that triggered the iFrame to resize. + */ + resizedCallback?: (data: IFrameResizedData) => void; + /** + * Called before the page is repositioned after a request from the iFrame, due to either an in page link, + * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). + * If this callback function returns false, it will stop the library from repositioning the page, so that + * you can implement your own animated page scrolling instead. + */ + scrollCallback?: (data: IFrameScrollData) => boolean; + } - // tslint:disable-next-line:interface-name - interface IFramePageOptions { - /** - * This option allows you to restrict the domain of the parent page, - * to prevent other sites mimicking your parent page. - */ - targetOrigin?: string; - /** - * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. - */ - messageCallback?: (message: any) => void; - /** - * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. - */ - readyCallback?: () => void; - /** - * These option can be used to override the option set in the parent page - */ - heightCalculationMethod?: string; - /** - * These option can be used to override the option set in the parent page - */ - widthCalculationMethod?: string; - } + // tslint:disable-next-line:interface-name + interface IFramePageOptions { + /** + * This option allows you to restrict the domain of the parent page, + * to prevent other sites mimicking your parent page. + */ + targetOrigin?: string; + /** + * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. + */ + messageCallback?: (message: any) => void; + /** + * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. + */ + readyCallback?: () => void; + /** + * These option can be used to override the option set in the parent page + */ + heightCalculationMethod?: HeightCalculationMethod | (() => number); + /** + * These option can be used to override the option set in the parent page + */ + widthCalculationMethod?: WidthCalculationMethod | (() => number); + } - // tslint:disable-next-line:interface-name - interface IFramePage { - autoResize(resize?: boolean): boolean; - close(): void; - getId(): string; - getPageInfo(callback: (data: any) => void | false): void; - scrollTo(x: number, y: number): void; - scrollToOffset(x: number, y: number): void; - sendMessage(message: any, targetOrigin: string): void; - setHeightCalculationMethod(method: string): void; - setWidthCalculationMethod(method: string): void; - setTargetOrigin(targetOrigin: string): void; - size(customHeight: string, customWidth: string): void; - } + type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement'; - // tslint:disable-next-line:interface-name - interface IFrameResizedData { - iframe: IFrameComponent; - height: number; - width: number; - type: string; - } + type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement'; - // tslint:disable-next-line:interface-name - interface IFrameMessageData { - iframe: IFrameComponent; - message: string; - } + // tslint:disable-next-line:interface-name + interface IFramePage { + /** + * Turn autoResizing of the iFrame on and off. Returns bool of current state. + */ + autoResize(resize?: boolean): boolean; + /** + * Remove the iFrame from the parent page. + */ + close(): void; + /** + * Returns the ID of the iFrame that the page is contained in. + */ + getId(): string; + /** + * Ask the containing page for its positioning coordinates. + * + * Your callback function will be recalled when the parent page is scrolled or resized. + * + * Pass false to disable the callback. + */ + getPageInfo(callback: ((data: PageInfo) => void) | false): void; + /** + * Scroll the parent page to the coordinates x and y + */ + scrollTo(x: number, y: number): void; + /** + * Scroll the parent page to the coordinates x and y relative to the position of the iFrame. + */ + scrollToOffset(x: number, y: number): void; + /** + * Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin` + * option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page. + * See the MDN documentation on postMessage for more details. + */ + sendMessage(message: any, targetOrigin?: string): void; + /** + * Change the method use to workout the height of the iFrame. + */ + setHeightCalculationMethod(method: HeightCalculationMethod): void; + /** + * Change the method use to workout the width of the iFrame. + */ + setWidthCalculationMethod(method: WidthCalculationMethod): void; + /** + * Set default target origin. + */ + setTargetOrigin(targetOrigin: string): void; + /** + * Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to + * prevent auto resizing and enable the `sizeWidth` option if you wish to set the width. + */ + size(customHeight?: string, customWidth?: string): void; + } - // tslint:disable-next-line:interface-name - interface IFrameScrollData { - x: number; - y: number; - } + interface PageInfo { + /** + * The height of the iframe in pixels + */ + iframeHeight: number; + /** + * The width of the iframe in pixels + */ + iframeWidth: number; + /** + * The height of the viewport in pixels + */ + clientHeight: number; + /** + * The width of the viewport in pixels + */ + clientWidth: number; + /** + * The number of pixels between the left edge of the containing page and the left edge of the iframe + */ + offsetLeft: number; + /** + * The number of pixels between the top edge of the containing page and the top edge of the iframe + */ + offsetTop: number; + /** + * The number of pixels between the left edge of the iframe and the left edge of the iframe viewport + */ + scrollLeft: number; + /** + * The number of pixels between the top edge of the iframe and the top edge of the iframe viewport + */ + scrollTop: number; + } - function iframeResizer(options: IFrameOptions, target: HTMLElement): IFrameComponent[]; + // tslint:disable-next-line:interface-name + interface IFrameResizedData { + iframe: IFrameComponent; + height: number; + width: number; + type: string; + } + + // tslint:disable-next-line:interface-name + interface IFrameMessageData { + iframe: IFrameComponent; + message: string; + } + + // tslint:disable-next-line:interface-name + interface IFrameScrollData { + x: number; + y: number; + } + + function iframeResizer(options: IFrameOptions, target: string | HTMLElement): IFrameComponent[]; } // tslint:enable:prefer-method-signature From d6ec52740a6708bcb0d3b0c335c973a1feaa2e6c Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sun, 16 Jul 2017 20:44:02 +0200 Subject: [PATCH 0052/1139] [redis-mock] introduce typings --- types/redis-mock/index.d.ts | 6 ++ types/redis-mock/redis-mock-tests.ts | 124 +++++++++++++++++++++++++++ types/redis-mock/tsconfig.json | 22 +++++ types/redis-mock/tslint.json | 1 + 4 files changed, 153 insertions(+) create mode 100644 types/redis-mock/index.d.ts create mode 100644 types/redis-mock/redis-mock-tests.ts create mode 100644 types/redis-mock/tsconfig.json create mode 100644 types/redis-mock/tslint.json diff --git a/types/redis-mock/index.d.ts b/types/redis-mock/index.d.ts new file mode 100644 index 0000000000..20401029d8 --- /dev/null +++ b/types/redis-mock/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for redis-mock 0.17 +// Project: https://github.com/yeahoffline/redis-mock#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export * from "redis"; diff --git a/types/redis-mock/redis-mock-tests.ts b/types/redis-mock/redis-mock-tests.ts new file mode 100644 index 0000000000..437a1fab50 --- /dev/null +++ b/types/redis-mock/redis-mock-tests.ts @@ -0,0 +1,124 @@ +import * as redis from "redis-mock"; + +let value: any; +let valueArr: any[]; +let commandArr: any[][]; +let num: number = 1; +let str: string = "hi"; +let bool: boolean = false; +let err: Error = new Error(); +let args: any[] = []; +let options: redis.ClientOpts = {}; +let client: redis.RedisClient; +let info: redis.ServerInfo; +let resCallback: (err: Error, res: any) => void = () => { +}; +let numCallback: (err: Error, res: number) => void = () => { +}; +let strCallback: (err: Error, res: string) => void = () => { +}; +let messageHandler: (channel: string, message: any) => void = () => { +}; + +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- + +bool = redis.debug_mode; +redis.print(err, value); + +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- + +client = redis.createClient(num, str, options); + +// Test the `retry_strategy` property +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- +function retryStrategyNumber(options: redis.RetryStrategyOptions): number { + // Ensure that the properties of RetryStrategyOptions are resilient to breaking change. + // If the properties of the interface changes, the variables below will also need to be adapted. + let error: Error = options.error; + let total_retry_time: number = options.total_retry_time; + let times_connected: number = options.times_connected; + let attempt: number = options.attempt; + return 5000; +} +function retryStrategyError(options: redis.RetryStrategyOptions): Error { + return new Error('Foo'); +} +client = redis.createClient({ + retry_strategy: retryStrategyNumber +}); +client = redis.createClient({ + retry_strategy: retryStrategyError +}); +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- + +bool = client.connected; +num = client.retry_delay; +num = client.retry_backoff; +valueArr = client.command_queue; +valueArr = client.offline_queue; +info = client.server_info; + +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- + +client.end(true); + +// Connection (http://redis.io/commands#connection) +client.auth(str, resCallback); +client.ping(strCallback); +client.unref(); + +// Strings (http://redis.io/commands#strings) +client.append(str, str, numCallback); +client.bitcount(str, numCallback); +client.bitcount(str, num, num, numCallback); +client.set(str, str, strCallback); +client.get(str, strCallback); +client.exists(str, numCallback); + +// Event handlers +client.on(str, messageHandler); +client.once(str, messageHandler); + +// ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- + +// some of the bulk methods +client.get('test'); +client.get('test', resCallback); +client.set('test', 'test'); +client.set('test', 'test', resCallback); +client.mset(args, resCallback); + +client.incr(str, resCallback); + +// Friendlier hash commands +client.hgetall(str, resCallback); +client.hmset(str, value, resCallback); +client.hmset(str, str, str, str, str, resCallback); + +// Publish / Subscribe +client.publish(str, value); +client.subscribe(str); + +// Multi +client.multi() + .scard(str) + .smembers(str) + .keys('*', resCallback) + .dbsize() + .exec(resCallback); + +client.multi([['get', 'test']]).exec(); + +// Monitor mode +client.monitor(resCallback); + +// Send command +client.send_command(str, args, resCallback); +// Duplicate +client.duplicate(); + +// Pipeline +client.cork(); +client.set("abc", "fff", strCallback); +client.get("abc", resCallback); +client.uncork(); diff --git a/types/redis-mock/tsconfig.json b/types/redis-mock/tsconfig.json new file mode 100644 index 0000000000..84f6e085c4 --- /dev/null +++ b/types/redis-mock/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "redis-mock-tests.ts" + ] +} diff --git a/types/redis-mock/tslint.json b/types/redis-mock/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/redis-mock/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e023c3998e2fc2103cbea173f34d65981c7a9150 Mon Sep 17 00:00:00 2001 From: Maarten Mulders Date: Sun, 16 Jul 2017 21:21:10 +0200 Subject: [PATCH 0053/1139] Type definitions for Recharts --- types/recharts/README.MD | 4 + types/recharts/index.d.ts | 786 +++++++++++++++++++++++++++++ types/recharts/test/index.tsx | 19 + types/recharts/tsconfig.json | 24 + types/recharts/types-metadata.json | 25 + 5 files changed, 858 insertions(+) create mode 100644 types/recharts/README.MD create mode 100644 types/recharts/index.d.ts create mode 100644 types/recharts/test/index.tsx create mode 100644 types/recharts/tsconfig.json create mode 100644 types/recharts/types-metadata.json diff --git a/types/recharts/README.MD b/types/recharts/README.MD new file mode 100644 index 0000000000..063a6dab3c --- /dev/null +++ b/types/recharts/README.MD @@ -0,0 +1,4 @@ +Typings for [Recharts](http://recharts.org/), a composable charting library built on React components + +The [Recharts website](https://github.com/recharts/recharts.org) has comprehensive API documentation which is generated from JavaScript files. +Those files are used as input to generate these typings. diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts new file mode 100644 index 0000000000..ae37eced47 --- /dev/null +++ b/types/recharts/index.d.ts @@ -0,0 +1,786 @@ +// Type definitions for Recharts v0.22.1 +// Project: http://recharts.org/ +// Definitions by: Maarten Mulders +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as React from 'react'; + +type Function = () => any; +type Percentage = string; + +interface AreaProps { + type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | Function, + dataKey?: string | number, + xAxisId?: string | number, + yAxisId?: string | number, + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', + dot?: Boolean | any | React.ReactElement | Function, + activeDot?: Boolean | any | React.ReactElement | Function, + label?: Boolean | any | React.ReactElement | Function, + stroke?: string, + layout?: 'horizontal' | 'vertical', + baseLine?: number | any[], + points?: any[], + stackId?: string | number, + connectNulls?: Boolean, + unit?: string | number, + name?: string | number, + isAnimationActive?: Boolean, + animationBegin?: number, + animationDuration?: number, + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Area extends React.Component { +} + +interface AreaChartProps { + layout?: 'horizontal' | 'vertical', + syncId?: string, + width: number, + height: number, + data: any[], + margin?: any, + stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette', + baseValue?: number | 'dataMin' | 'dataMax' | 'auto', + onClick?: Function, + onMouseEnter?: Function, + onMouseMove?: Function, + onMouseLeave?: Function, +} +export class AreaChart extends React.Component { +} + +interface BarProps { + layout?: 'horizontal' | 'vertical', + dataKey?: string | number, + xAxisId?: string | number, + yAxisId?: string | number, + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', + label?: Boolean | any | React.ReactElement | Function, + data?: any[], + barSize?: number, + maxBarSize?: number, + minPointSize?: number, + shape?: React.ReactElement | Function, + stackId?: string | number, + unit?: string | number, + name?: string | number, + isAnimationActive?: Boolean, + animationBegin?: number, + animationDuration?: number, + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Bar extends React.Component { +} + +interface BarChartProps { + layout?: 'horizontal' | 'vertical', + syncId?: string, + width?: number, + height?: number, + data?: any[], + margin?: any, + barCategoryGap?: Percentage | number, + barGap?: Percentage | number, + barSize?: number, + maxBarSize?: number, + stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette' | 'sign', + onClick?: Function, + onMouseEnter?: Function, + onMouseMove?: Function, + onMouseLeave?: Function, +} +export class BarChart extends React.Component { +} + +interface BrushProps { + dataKey: number | string, + x?: number, + y?: number, + width?: number, + height?: number, + data: any[], + travellerWidth?: number, + startIndex?: number, + endIndex?: number, + tickFormatter?: Function, + onChange?: Function, +} +export class Brush extends React.Component { +} + +interface CartesianAxisProps { + x?: number, + y?: number, + width?: number, + height?: number, + orientation?: 'top' | 'bottom' | 'left' | 'right', + viewBox?: any, + axisLine?: Boolean | any, + tickLine?: Boolean | any, + minTickGap?: number, + tickSize?: number, + interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number, + tick?: Boolean | any | React.ReactElement | Function, + label?: string | number | React.ReactElement | Function, + mirror?: Boolean, +} +export class CartesianAxis extends React.Component { +} + +interface CartesianGridProps { + x?: number, + y?: number, + width?: number, + height?: number, + horizontal?: Boolean, + vertical?: Boolean, + horizontalPoints?: any[], + verticalPoints?: any[], +} +export class CartesianGrid extends React.Component { +} + +interface CellProps { + fill?: string, + stroke?: string, +} +export class Cell extends React.Component { +} + +interface ComposedChartProps { + layout?: 'horizontal' | 'vertical', + syncId?: string, + width?: number, + height?: number, + data?: any[], + margin?: any, + barCategoryGap?: Percentage | number, + barGap?: number, + barSize?: number, + onClick?: Function, + onMouseEnter?: Function, + onMouseMove?: Function, + onMouseLeave?: Function, +} +export class ComposedChart extends React.Component { +} + +interface CrossProps { + x?: number, + y?: number, + top?: number, + left?: number, + width?: number, + height?: number, +} +export class Cross extends React.Component { +} + +interface CurveProps { + type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | Function, + points: any[], + layout?: 'horizontal' | 'vertical', + baseLine?: number | any[], + connectNulls?: Boolean, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Curve extends React.Component { +} + +interface DotProps { + cx: number, + cy: number, + r: number, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseMove?: Function, + onMouseLeave?: Function, +} +export class Dot extends React.Component { +} + +interface ErrorBarProps { + dataKey?: string | number, + width?: number, + strokeWidth?: string, + stroke?: string, + direction?: string, +} +export class ErrorBar extends React.Component { +} + +interface LegendProps { + width?: number, + height?: number, + layout?: 'horizontal' | 'vertical', + align?: 'left' | 'center' | 'right', + verticalAlign?: 'top' | 'middle' | 'bottom', + iconSize?: number, + iconType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye', + payload?: any[], + chartWidth: number, + chartHeight: number, + margin?: any, + content?: React.ReactElement | Function, + wrapperStyle?: any, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Legend extends React.Component { +} + +interface LineProps { + type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | Function, + dataKey: string | number, + xAxisId?: string | number, + yAxisId?: string | number, + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', + dot?: Boolean | any | React.ReactElement | Function, + activeDot?: Boolean | any | React.ReactElement | Function, + label?: Boolean | any | React.ReactElement | Function, + points: any[], + layout?: 'horizontal' | 'vertical', + connectNulls?: Boolean, + unit?: string | number, + name?: string | number, + isAnimationActive?: Boolean, + animationBegin?: number, + animationDuration?: number, + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Line extends React.Component { +} + +interface LineChartProps { + layout?: 'horizontal' | 'vertical', + syncId?: string, + width?: number, + height?: number, + data?: any[], + margin?: any, + onClick?: Function, + onMouseEnter?: Function, + onMouseMove?: Function, + onMouseLeave?: Function, +} +export class LineChart extends React.Component { +} + +interface PieProps { + cx?: Percentage | number, + cy?: Percentage | number, + innerRadius?: Percentage | number, + outerRadius?: Percentage | number, + startAngle?: number, + endAngle?: number, + minAngle?: number, + paddingAngle?: number, + nameKey?: string, + valueKey?: string, + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', + label?: Boolean | any | React.ReactElement | Function, + labelLine?: Boolean | any | React.ReactElement | Function, + data: any[], + activeIndex: any[], + activeShape: any | React.ReactElement | Function, + isAnimationActive?: Boolean, + animationBegin?: number, + animationDuration?: number, + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear' | Function, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Pie extends React.Component { +} + +interface PieChartProps { + width: number, + height: number, + margin?: any, + onClick?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class PieChart extends React.Component { +} + +interface PolarAngleAxisProps { + dataKey: string | number, + cx: number, + cy: number, + radius: Percentage | number, + axisLine?: boolean | any, + axisLineType?: string, + tickLine?: boolean | any, + tick?: boolean | any | React.ReactElement | Function, + ticks: any[], + orient?: string, + tickFormatter: Function, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class PolarAngleAxis extends React.Component { +} + +interface PolarGridProps { + cx: number, + cy: number, + innerRadius: number, + outerRadius: number, + polarAngles: any[], + polarRadius: any[], + gridType?: 'polygon' | 'circle', +} +export class PolarGrid extends React.Component { +} + +interface PolarRadiusAxisProps { + angle?: number, + cx: number, + cy: number, + domain?: any[], + label?: string | number | React.ReactElement | Function, + orientation?: "left" | "right" | "middle", + axisLine?: boolean | any, + tick?: boolean | any | Element | Function, + tickFormatter: Function, + tickCount?: number, + scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | Function, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class PolarRadiusAxis extends React.Component { +} + +interface PolygonProps { + points: any[], + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Polygon extends React.Component { +} + +interface RadarProps { + dataKey: string | number, + points: any[], + shape: Element | Function, + dot?: boolean | any | Element | Function, + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', + label?: boolean | any | Element | Function, + isAnimationActive?: Boolean, + animationBegin?: number, + animationDuration?: number, + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', +} +export class Radar extends React.Component { +} + +interface RadarChartProps { + width: number, + height: number, + cx?: Percentage | number, + cy?: Percentage | number, + startAngle?: number, + innerRadius?: Percentage | number, + outerRadius?: Percentage | number, + margin?: any, + clockWise?: boolean, + onMouseEnter?: Function, + onMouseLeave?: Function, + onClick?: Function, +} +export class RadarChart extends React.Component { +} + +interface RadialBarProps { + cx?: number, + cy?: number, + startAngle?: number, + endAngle?: number, + maxAngle?: number, + minAngle?: number, + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', + label?: Boolean | any | React.ReactElement | Function, + background?: Boolean | any | React.ReactElement | Function, + data: any[], + isAnimationActive?: Boolean, + animationBegin?: number, + animationDuration?: number, + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class RadialBar extends React.Component { +} + +interface RadialBarChartProps { + width?: number, + height?: number, + data?: any[], + margin?: any, + barCategoryGap?: Percentage | number, + barGap?: number, + cx?: Percentage | number, + cy?: Percentage | number, + innerRadius?: Percentage | number, + outerRadius?: Percentage | number, + barSize?: number, + onMouseEnter?: Function, + onMouseLeave?: Function, + onClick?: Function, +} +export class RadialBarChart extends React.Component { +} + +interface RectangleProps { + x?: number, + y?: number, + width?: number, + height?: number, + radius?: number, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Rectangle extends React.Component { +} + +interface ReferenceAreaProps { + xAxisId?: string | number, + yAxisId?: string | number, + x1?: number | string, + x2?: number | string, + y1?: number | string, + y2?: number | string, + alwaysShow?: Boolean, + viewBox: any, + xAxis: any, + yAxis: any, + label?: string | number | React.ReactElement | Function, + isFront?: Boolean, +} +export class ReferenceArea extends React.Component { +} + +interface ReferenceDotProps { + xAxisId?: string | number, + yAxisId?: string | number, + x: number | string, + y: number | string, + alwaysShow?: Boolean, + xAxis: any, + yAxis: any, + label?: string | number | React.ReactElement | Function, + isFront?: Boolean, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseMove?: Function, + onMouseLeave?: Function, +} +export class ReferenceDot extends React.Component { +} + +interface ReferenceLineProps { + xAxisId?: string | number, + yAxisId?: string | number, + x?: number | string, + y?: number | string, + alwaysShow?: Boolean, + viewBox: any, + xAxis: any, + yAxis: any, + label?: string | number | React.ReactElement | Function, + isFront?: Boolean, +} +export class ReferenceLine extends React.Component { +} + +interface ResponsiveContainerProps { + aspect?: number, + width?: Percentage | number, + height?: Percentage | number, + minWidth?: number, + minHeight?: number, + debounce?: number, +} +export class ResponsiveContainer extends React.Component { +} + +interface ScatterProps { + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', + xAxisId?: string | number, + yAxisId?: string | number, + zAxisId?: string | number, + line?: Boolean | any | React.ReactElement | Function, + shape?: 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | React.ReactElement | Function, + lineType?: 'joint' | 'fitting', + points: any[], + isAnimationActive?: Boolean, + animationBegin?: number, + animationDuration?: number, + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Scatter extends React.Component { +} + +interface ScatterChartProps { + width: number, + height: number, + margin?: any, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class ScatterChart extends React.Component { +} + +interface SectorProps { + cx?: number, + cy?: number, + innerRadius?: number, + outerRadius?: number, + startAngle?: number, + endAngle?: number, + cornerRadius?: number, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class Sector extends React.Component { +} + +interface TextProps { + scaleToFit?: Boolean, + angle?: number, + width?: number, + textAnchor?: 'start' | 'middle' | 'end' | 'inherit', + verticalAnchor?: 'start' | 'middle' | 'end', +} +export class Text extends React.Component { +} + +interface TooltipProps { + separator?: string, + offset?: number, + itemStyle?: any, + wrapperStyle?: any, + labelStyle?: any, + cursor?: Boolean | any | React.ReactElement, + viewBox: any, + active?: Boolean, + coordinate?: any, + payload?: any[], + label?: string | number, + content?: React.ReactElement | Function, + formatter?: Function, + labelFormatter?: Function, + itemSorter?: Function, + isAnimationActive?: Boolean, + animationBegin?: number, + animationDuration?: number, + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', +} +export class Tooltip extends React.Component { +} + +interface TreemapProps { + width: number, + height: number, + dataKey?: string, + aspectRatio: number, + isAnimationActive?: Boolean, + animationBegin?: number, + animationDuration?: number, + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', +} +export class Treemap extends React.Component { +} + +interface XAxisProps { + hide?: Boolean, + dataKey?: string | number, + xAxisId?: string | number, + width?: number, + height?: number, + orientation?: 'bottom' | 'top', + type?: 'number' | 'category', + allowDecimals?: Boolean, + allowDataOverflow?: Boolean, + tickCount?: number, + domain?: any[], + interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number, + padding?: any, + minTickGap?: number, + axisLine?: Boolean | any, + tickLine?: Boolean | any, + tickSize?: number, + tickFormatter?: Function, + ticks?: any[], + tick?: Boolean | any | React.ReactElement, + mirror?: Boolean, + reversed?: Boolean, + label?: string | number | React.ReactElement, + scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | Function, + unit?: string | number, + name?: string | number, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class XAxis extends React.Component { +} + +interface YAxisProps { + hide?: Boolean, + dataKey?: string | number, + yAxisId?: string | number, + width?: number, + height?: number, + orientation?: 'left' | 'right', + type?: 'number' | 'category', + domain?: any[], + interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number, + padding?: any, + minTickGap?: number, + allowDecimals?: Boolean, + allowDataOverflow?: Boolean, + axisLine?: Boolean | any, + tickLine?: Boolean | any, + tickSize?: number, + tickFormatter?: Function, + ticks?: any[], + tick?: Boolean | any | React.ReactElement, + mirror?: Boolean, + reversed?: Boolean, + label?: string | number | React.ReactElement, + scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | Function, + unit?: string | number, + name?: string | number, + onClick?: Function, + onMouseDown?: Function, + onMouseUp?: Function, + onMouseMove?: Function, + onMouseOver?: Function, + onMouseOut?: Function, + onMouseEnter?: Function, + onMouseLeave?: Function, +} +export class YAxis extends React.Component { +} + +interface ZAxisProps { + dataKey: string | number, + zAxisId?: string | number, + range?: any[], + unit?: string | number, + name?: string | number, + scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | Function, +} +export class ZAxis extends React.Component { +} + diff --git a/types/recharts/test/index.tsx b/types/recharts/test/index.tsx new file mode 100644 index 0000000000..f7d415a615 --- /dev/null +++ b/types/recharts/test/index.tsx @@ -0,0 +1,19 @@ +import * as React from 'react' +import * as ReactDOM from 'react-dom'; + +import { CartesianGrid, LineChart, Line, Tooltip, XAxis, YAxis } from 'recharts'; + +const Component = (props: {}) => { + return ( + + + + + + + + ); +} + + +ReactDOM.render(, document.getElementById('app')); diff --git a/types/recharts/tsconfig.json b/types/recharts/tsconfig.json new file mode 100644 index 0000000000..41fddb0ef2 --- /dev/null +++ b/types/recharts/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": false, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/index.tsx" + ], + "jsx": "react" +} diff --git a/types/recharts/types-metadata.json b/types/recharts/types-metadata.json new file mode 100644 index 0000000000..795b5eb678 --- /dev/null +++ b/types/recharts/types-metadata.json @@ -0,0 +1,25 @@ +{ + "authors": "Maarten Mulders ", + "libraryDependencies": [ + "react" + ], + "moduleDependencies": [], + "libraryMajorVersion": 0, + "libraryMinorVersion": 12, + "typeScriptVersion": "2.0", + "libraryName": "recharts", + "typingsPackageName": "recharts", + "projectName": "http://recharts.org/", + "sourceRepoURL": "https://www.github.com/DefinitelyTyped/DefinitelyTyped", + "sourceBranch": "master", + "globals": [ + ], + "declaredModules": [ + "recharts" + ], + "files": [ + "index.d.ts" + ], + "hasPackageJson": false, + "contentHash": "be2be503d947ebda48e7af156e1b24198540234a732125ceb62c14ce759d98d5" +} From 8088446401a5f830f83dfb0ee1675f08fdd60b4b Mon Sep 17 00:00:00 2001 From: Fedor Nezhivoi Date: Sun, 16 Jul 2017 22:43:46 +0300 Subject: [PATCH 0054/1139] @types/react-native: fix style related bugs --- types/react-native/index.d.ts | 13 +++++++------ types/react-native/test/index.tsx | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index f3f90b88f9..3317eff673 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1657,7 +1657,9 @@ export interface ViewPropertiesAndroid { } -export type StyleProp = T | Array +type Falsy = undefined | null | false +interface RecursiveArray extends Array> {} +export type StyleProp = T | RecursiveArray | Falsy /** * @see https://facebook.github.io/react-native/docs/view.html#props @@ -4904,11 +4906,8 @@ export namespace NavigatorStatic { // @see https://github.com/facebook/react-native/blob/0.34-stable\Libraries\StyleSheet\StyleSheetTypes.js export namespace StyleSheet { - - type Style = ViewStyle | TextStyle | ImageStyle - type NamedStyles = { - [P in keyof T]: Style; + [P in keyof T]: ViewStyle | TextStyle | ImageStyle; } /** @@ -4955,7 +4954,9 @@ export namespace StyleSheet { * their respective objects, merged as one and then returned. This also explains * the alternative use. */ - export function flatten(style?: Style | Style[]): Style + export function flatten(style?: StyleProp): ViewStyle + export function flatten(style?: StyleProp): TextStyle + export function flatten(style?: StyleProp): ImageStyle /** * This is defined as the width of a thin line on the platform. It can be diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 269162c9f3..446cb176f1 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -141,7 +141,7 @@ class Welcome extends React.Component { render() { return ( - + Welcome to React Native From da6e0916d846a155bf37978d783667c2abe0f733 Mon Sep 17 00:00:00 2001 From: Maarten Mulders Date: Sun, 16 Jul 2017 21:30:07 +0200 Subject: [PATCH 0055/1139] Fix test file --- types/recharts/test/index.tsx | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/types/recharts/test/index.tsx b/types/recharts/test/index.tsx index f7d415a615..62d3b6f830 100644 --- a/types/recharts/test/index.tsx +++ b/types/recharts/test/index.tsx @@ -1,19 +1,20 @@ -import * as React from 'react' +import * as React from 'react'; import * as ReactDOM from 'react-dom'; -import { CartesianGrid, LineChart, Line, Tooltip, XAxis, YAxis } from 'recharts'; +import { Recharts } from 'recharts'; + +const data: any[] = []; const Component = (props: {}) => { return ( - - - - - - - + + + + + + + ); -} - +}; ReactDOM.render(, document.getElementById('app')); From 50a0fed497f0438de57e5b32d11baaf22c91d8b2 Mon Sep 17 00:00:00 2001 From: Maarten Mulders Date: Sun, 16 Jul 2017 21:57:09 +0200 Subject: [PATCH 0056/1139] Fix tslint issues --- types/recharts/index.d.ts | 1517 +++++++++++++++++----------------- types/recharts/tsconfig.json | 8 +- types/recharts/tslint.json | 3 + 3 files changed, 746 insertions(+), 782 deletions(-) create mode 100644 types/recharts/tslint.json diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index ae37eced47..b858309147 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -1,786 +1,747 @@ -// Type definitions for Recharts v0.22.1 +// Type definitions for Recharts 0.22 // Project: http://recharts.org/ // Definitions by: Maarten Mulders // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// import * as React from 'react'; -type Function = () => any; -type Percentage = string; +export namespace Recharts { + type Percentage = string; + type RechartsFunction = () => void; -interface AreaProps { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | Function, - dataKey?: string | number, - xAxisId?: string | number, - yAxisId?: string | number, - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', - dot?: Boolean | any | React.ReactElement | Function, - activeDot?: Boolean | any | React.ReactElement | Function, - label?: Boolean | any | React.ReactElement | Function, - stroke?: string, - layout?: 'horizontal' | 'vertical', - baseLine?: number | any[], - points?: any[], - stackId?: string | number, - connectNulls?: Boolean, - unit?: string | number, - name?: string | number, - isAnimationActive?: Boolean, - animationBegin?: number, - animationDuration?: number, - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, + interface AreaProps { + type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; + dataKey?: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; + dot?: boolean | any | React.ReactElement | RechartsFunction; + activeDot?: boolean | any | React.ReactElement | RechartsFunction; + label?: boolean | any | React.ReactElement | RechartsFunction; + stroke?: string; + layout?: 'horizontal' | 'vertical'; + baseLine?: number | any[]; + points?: any[]; + stackId?: string | number; + connectNulls?: boolean; + unit?: string | number; + name?: string | number; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Area extends React.Component { + } + interface AreaChartProps { + layout?: 'horizontal' | 'vertical'; + syncId?: string; + width: number; + height: number; + data: any[]; + margin?: any; + stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette'; + baseValue?: number | 'dataMin' | 'dataMax' | 'auto'; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class AreaChart extends React.Component { + } + interface BarProps { + layout?: 'horizontal' | 'vertical'; + dataKey?: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; + label?: boolean | any | React.ReactElement | RechartsFunction; + data?: any[]; + barSize?: number; + maxBarSize?: number; + minPointSize?: number; + shape?: React.ReactElement | RechartsFunction; + stackId?: string | number; + unit?: string | number; + name?: string | number; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Bar extends React.Component { + } + interface BarChartProps { + layout?: 'horizontal' | 'vertical'; + syncId?: string; + width?: number; + height?: number; + data?: any[]; + margin?: any; + barCategoryGap?: Percentage | number; + barGap?: Percentage | number; + barSize?: number; + maxBarSize?: number; + stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette' | 'sign'; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class BarChart extends React.Component { + } + interface BrushProps { + dataKey: number | string; + x?: number; + y?: number; + width?: number; + height?: number; + data: any[]; + travellerWidth?: number; + startIndex?: number; + endIndex?: number; + tickFormatter?: RechartsFunction; + onChange?: RechartsFunction; + } + class Brush extends React.Component { + } + interface CartesianAxisProps { + x?: number; + y?: number; + width?: number; + height?: number; + orientation?: 'top' | 'bottom' | 'left' | 'right'; + viewBox?: any; + axisLine?: boolean | any; + tickLine?: boolean | any; + minTickGap?: number; + tickSize?: number; + interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; + tick?: boolean | any | React.ReactElement | RechartsFunction; + label?: string | number | React.ReactElement | RechartsFunction; + mirror?: boolean; + } + class CartesianAxis extends React.Component { + } + interface CartesianGridProps { + x?: number; + y?: number; + width?: number; + height?: number; + horizontal?: boolean; + vertical?: boolean; + horizontalPoints?: any[]; + verticalPoints?: any[]; + } + class CartesianGrid extends React.Component { + } + interface CellProps { + fill?: string; + stroke?: string; + } + class Cell extends React.Component { + } + interface ComposedChartProps { + layout?: 'horizontal' | 'vertical'; + syncId?: string; + width?: number; + height?: number; + data?: any[]; + margin?: any; + barCategoryGap?: Percentage | number; + barGap?: number; + barSize?: number; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class ComposedChart extends React.Component { + } + interface CrossProps { + x?: number; + y?: number; + top?: number; + left?: number; + width?: number; + height?: number; + } + class Cross extends React.Component { + } + interface CurveProps { + type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; + points: any[]; + layout?: 'horizontal' | 'vertical'; + baseLine?: number | any[]; + connectNulls?: boolean; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Curve extends React.Component { + } + interface DotProps { + cx: number; + cy: number; + r: number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Dot extends React.Component { + } + interface ErrorBarProps { + dataKey?: string | number; + width?: number; + strokeWidth?: string; + stroke?: string; + direction?: string; + } + class ErrorBar extends React.Component { + } + interface LegendProps { + width?: number; + height?: number; + layout?: 'horizontal' | 'vertical'; + align?: 'left' | 'center' | 'right'; + verticalAlign?: 'top' | 'middle' | 'bottom'; + iconSize?: number; + iconType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye'; + payload?: any[]; + chartWidth: number; + chartHeight: number; + margin?: any; + content?: React.ReactElement | RechartsFunction; + wrapperStyle?: any; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Legend extends React.Component { + } + interface LineProps { + type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; + dataKey: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; + dot?: boolean | any | React.ReactElement | RechartsFunction; + activeDot?: boolean | any | React.ReactElement | RechartsFunction; + label?: boolean | any | React.ReactElement | RechartsFunction; + points: any[]; + layout?: 'horizontal' | 'vertical'; + connectNulls?: boolean; + unit?: string | number; + name?: string | number; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Line extends React.Component { + } + interface LineChartProps { + layout?: 'horizontal' | 'vertical'; + syncId?: string; + width?: number; + height?: number; + data?: any[]; + margin?: any; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class LineChart extends React.Component { + } + interface PieProps { + cx?: Percentage | number; + cy?: Percentage | number; + innerRadius?: Percentage | number; + outerRadius?: Percentage | number; + startAngle?: number; + endAngle?: number; + minAngle?: number; + paddingAngle?: number; + nameKey?: string; + valueKey?: string; + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; + label?: boolean | any | React.ReactElement | RechartsFunction; + labelLine?: boolean | any | React.ReactElement | RechartsFunction; + data: any[]; + activeIndex: any[]; + activeShape: any | React.ReactElement | RechartsFunction; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear' | RechartsFunction; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Pie extends React.Component { + } + interface PieChartProps { + width: number; + height: number; + margin?: any; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class PieChart extends React.Component { + } + interface PolarAngleAxisProps { + dataKey: string | number; + cx: number; + cy: number; + radius: Percentage | number; + axisLine?: boolean | any; + axisLineType?: string; + tickLine?: boolean | any; + tick?: boolean | any | React.ReactElement | RechartsFunction; + ticks: any[]; + orient?: string; + tickFormatter: RechartsFunction; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class PolarAngleAxis extends React.Component { + } + interface PolarGridProps { + cx: number; + cy: number; + innerRadius: number; + outerRadius: number; + polarAngles: any[]; + polarRadius: any[]; + gridType?: 'polygon' | 'circle'; + } + class PolarGrid extends React.Component { + } + interface PolarRadiusAxisProps { + angle?: number; + cx: number; + cy: number; + domain?: any[]; + label?: string | number | React.ReactElement | RechartsFunction; + orientation?: "left" | "right" | "middle"; + axisLine?: boolean | any; + tick?: boolean | any | Element | RechartsFunction; + tickFormatter: RechartsFunction; + tickCount?: number; + scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | RechartsFunction; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class PolarRadiusAxis extends React.Component { + } + interface PolygonProps { + points: any[]; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Polygon extends React.Component { + } + interface RadarProps { + dataKey: string | number; + points: any[]; + shape: Element | RechartsFunction; + dot?: boolean | any | Element | RechartsFunction; + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; + label?: boolean | any | Element | RechartsFunction; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; + } + class Radar extends React.Component { + } + interface RadarChartProps { + width: number; + height: number; + cx?: Percentage | number; + cy?: Percentage | number; + startAngle?: number; + innerRadius?: Percentage | number; + outerRadius?: Percentage | number; + margin?: any; + clockWise?: boolean; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onClick?: RechartsFunction; + } + class RadarChart extends React.Component { + } + interface RadialBarProps { + cx?: number; + cy?: number; + startAngle?: number; + endAngle?: number; + maxAngle?: number; + minAngle?: number; + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; + label?: boolean | any | React.ReactElement | RechartsFunction; + background?: boolean | any | React.ReactElement | RechartsFunction; + data: any[]; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class RadialBar extends React.Component { + } + interface RadialBarChartProps { + width?: number; + height?: number; + data?: any[]; + margin?: any; + barCategoryGap?: Percentage | number; + barGap?: number; + cx?: Percentage | number; + cy?: Percentage | number; + innerRadius?: Percentage | number; + outerRadius?: Percentage | number; + barSize?: number; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onClick?: RechartsFunction; + } + class RadialBarChart extends React.Component { + } + interface RectangleProps { + x?: number; + y?: number; + width?: number; + height?: number; + radius?: number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Rectangle extends React.Component { + } + interface ReferenceAreaProps { + xAxisId?: string | number; + yAxisId?: string | number; + x1?: number | string; + x2?: number | string; + y1?: number | string; + y2?: number | string; + alwaysShow?: boolean; + viewBox: any; + xAxis: any; + yAxis: any; + label?: string | number | React.ReactElement | RechartsFunction; + isFront?: boolean; + } + class ReferenceArea extends React.Component { + } + interface ReferenceDotProps { + xAxisId?: string | number; + yAxisId?: string | number; + x: number | string; + y: number | string; + alwaysShow?: boolean; + xAxis: any; + yAxis: any; + label?: string | number | React.ReactElement | RechartsFunction; + isFront?: boolean; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class ReferenceDot extends React.Component { + } + interface ReferenceLineProps { + xAxisId?: string | number; + yAxisId?: string | number; + x?: number | string; + y?: number | string; + alwaysShow?: boolean; + viewBox: any; + xAxis: any; + yAxis: any; + label?: string | number | React.ReactElement | RechartsFunction; + isFront?: boolean; + } + class ReferenceLine extends React.Component { + } + interface ResponsiveContainerProps { + aspect?: number; + width?: Percentage | number; + height?: Percentage | number; + minWidth?: number; + minHeight?: number; + debounce?: number; + } + class ResponsiveContainer extends React.Component { + } + interface ScatterProps { + legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; + xAxisId?: string | number; + yAxisId?: string | number; + zAxisId?: string | number; + line?: boolean | any | React.ReactElement | RechartsFunction; + shape?: 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | React.ReactElement | RechartsFunction; + lineType?: 'joint' | 'fitting'; + points: any[]; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Scatter extends React.Component { + } + interface ScatterChartProps { + width: number; + height: number; + margin?: any; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class ScatterChart extends React.Component { + } + interface SectorProps { + cx?: number; + cy?: number; + innerRadius?: number; + outerRadius?: number; + startAngle?: number; + endAngle?: number; + cornerRadius?: number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class Sector extends React.Component { + } + interface TextProps { + scaleToFit?: boolean; + angle?: number; + width?: number; + textAnchor?: 'start' | 'middle' | 'end' | 'inherit'; + verticalAnchor?: 'start' | 'middle' | 'end'; + } + class Text extends React.Component { + } + interface TooltipProps { + separator?: string; + offset?: number; + itemStyle?: any; + wrapperStyle?: any; + labelStyle?: any; + cursor?: boolean | any | React.ReactElement; + viewBox: any; + active?: boolean; + coordinate?: any; + payload?: any[]; + label?: string | number; + content?: React.ReactElement | RechartsFunction; + formatter?: RechartsFunction; + labelFormatter?: RechartsFunction; + itemSorter?: RechartsFunction; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; + } + class Tooltip extends React.Component { + } + interface TreemapProps { + width: number; + height: number; + dataKey?: string; + aspectRatio: number; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; + } + class Treemap extends React.Component { + } + interface XAxisProps { + hide?: boolean; + dataKey?: string | number; + xAxisId?: string | number; + width?: number; + height?: number; + orientation?: 'bottom' | 'top'; + type?: 'number' | 'category'; + allowDecimals?: boolean; + allowDataOverflow?: boolean; + tickCount?: number; + domain?: any[]; + interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; + padding?: any; + minTickGap?: number; + axisLine?: boolean | any; + tickLine?: boolean | any; + tickSize?: number; + tickFormatter?: RechartsFunction; + ticks?: any[]; + tick?: boolean | any | React.ReactElement; + mirror?: boolean; + reversed?: boolean; + label?: string | number | React.ReactElement; + scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | RechartsFunction; + unit?: string | number; + name?: string | number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class XAxis extends React.Component { + } + interface YAxisProps { + hide?: boolean; + dataKey?: string | number; + yAxisId?: string | number; + width?: number; + height?: number; + orientation?: 'left' | 'right'; + type?: 'number' | 'category'; + domain?: any[]; + interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; + padding?: any; + minTickGap?: number; + allowDecimals?: boolean; + allowDataOverflow?: boolean; + axisLine?: boolean | any; + tickLine?: boolean | any; + tickSize?: number; + tickFormatter?: RechartsFunction; + ticks?: any[]; + tick?: boolean | any | React.ReactElement; + mirror?: boolean; + reversed?: boolean; + label?: string | number | React.ReactElement; + scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | RechartsFunction; + unit?: string | number; + name?: string | number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + } + class YAxis extends React.Component { + } + interface ZAxisProps { + dataKey: string | number; + zAxisId?: string | number; + range?: any[]; + unit?: string | number; + name?: string | number; + scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | RechartsFunction; + } + class ZAxis extends React.Component { + } } -export class Area extends React.Component { -} - -interface AreaChartProps { - layout?: 'horizontal' | 'vertical', - syncId?: string, - width: number, - height: number, - data: any[], - margin?: any, - stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette', - baseValue?: number | 'dataMin' | 'dataMax' | 'auto', - onClick?: Function, - onMouseEnter?: Function, - onMouseMove?: Function, - onMouseLeave?: Function, -} -export class AreaChart extends React.Component { -} - -interface BarProps { - layout?: 'horizontal' | 'vertical', - dataKey?: string | number, - xAxisId?: string | number, - yAxisId?: string | number, - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', - label?: Boolean | any | React.ReactElement | Function, - data?: any[], - barSize?: number, - maxBarSize?: number, - minPointSize?: number, - shape?: React.ReactElement | Function, - stackId?: string | number, - unit?: string | number, - name?: string | number, - isAnimationActive?: Boolean, - animationBegin?: number, - animationDuration?: number, - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class Bar extends React.Component { -} - -interface BarChartProps { - layout?: 'horizontal' | 'vertical', - syncId?: string, - width?: number, - height?: number, - data?: any[], - margin?: any, - barCategoryGap?: Percentage | number, - barGap?: Percentage | number, - barSize?: number, - maxBarSize?: number, - stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette' | 'sign', - onClick?: Function, - onMouseEnter?: Function, - onMouseMove?: Function, - onMouseLeave?: Function, -} -export class BarChart extends React.Component { -} - -interface BrushProps { - dataKey: number | string, - x?: number, - y?: number, - width?: number, - height?: number, - data: any[], - travellerWidth?: number, - startIndex?: number, - endIndex?: number, - tickFormatter?: Function, - onChange?: Function, -} -export class Brush extends React.Component { -} - -interface CartesianAxisProps { - x?: number, - y?: number, - width?: number, - height?: number, - orientation?: 'top' | 'bottom' | 'left' | 'right', - viewBox?: any, - axisLine?: Boolean | any, - tickLine?: Boolean | any, - minTickGap?: number, - tickSize?: number, - interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number, - tick?: Boolean | any | React.ReactElement | Function, - label?: string | number | React.ReactElement | Function, - mirror?: Boolean, -} -export class CartesianAxis extends React.Component { -} - -interface CartesianGridProps { - x?: number, - y?: number, - width?: number, - height?: number, - horizontal?: Boolean, - vertical?: Boolean, - horizontalPoints?: any[], - verticalPoints?: any[], -} -export class CartesianGrid extends React.Component { -} - -interface CellProps { - fill?: string, - stroke?: string, -} -export class Cell extends React.Component { -} - -interface ComposedChartProps { - layout?: 'horizontal' | 'vertical', - syncId?: string, - width?: number, - height?: number, - data?: any[], - margin?: any, - barCategoryGap?: Percentage | number, - barGap?: number, - barSize?: number, - onClick?: Function, - onMouseEnter?: Function, - onMouseMove?: Function, - onMouseLeave?: Function, -} -export class ComposedChart extends React.Component { -} - -interface CrossProps { - x?: number, - y?: number, - top?: number, - left?: number, - width?: number, - height?: number, -} -export class Cross extends React.Component { -} - -interface CurveProps { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | Function, - points: any[], - layout?: 'horizontal' | 'vertical', - baseLine?: number | any[], - connectNulls?: Boolean, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class Curve extends React.Component { -} - -interface DotProps { - cx: number, - cy: number, - r: number, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseMove?: Function, - onMouseLeave?: Function, -} -export class Dot extends React.Component { -} - -interface ErrorBarProps { - dataKey?: string | number, - width?: number, - strokeWidth?: string, - stroke?: string, - direction?: string, -} -export class ErrorBar extends React.Component { -} - -interface LegendProps { - width?: number, - height?: number, - layout?: 'horizontal' | 'vertical', - align?: 'left' | 'center' | 'right', - verticalAlign?: 'top' | 'middle' | 'bottom', - iconSize?: number, - iconType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye', - payload?: any[], - chartWidth: number, - chartHeight: number, - margin?: any, - content?: React.ReactElement | Function, - wrapperStyle?: any, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class Legend extends React.Component { -} - -interface LineProps { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | Function, - dataKey: string | number, - xAxisId?: string | number, - yAxisId?: string | number, - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', - dot?: Boolean | any | React.ReactElement | Function, - activeDot?: Boolean | any | React.ReactElement | Function, - label?: Boolean | any | React.ReactElement | Function, - points: any[], - layout?: 'horizontal' | 'vertical', - connectNulls?: Boolean, - unit?: string | number, - name?: string | number, - isAnimationActive?: Boolean, - animationBegin?: number, - animationDuration?: number, - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class Line extends React.Component { -} - -interface LineChartProps { - layout?: 'horizontal' | 'vertical', - syncId?: string, - width?: number, - height?: number, - data?: any[], - margin?: any, - onClick?: Function, - onMouseEnter?: Function, - onMouseMove?: Function, - onMouseLeave?: Function, -} -export class LineChart extends React.Component { -} - -interface PieProps { - cx?: Percentage | number, - cy?: Percentage | number, - innerRadius?: Percentage | number, - outerRadius?: Percentage | number, - startAngle?: number, - endAngle?: number, - minAngle?: number, - paddingAngle?: number, - nameKey?: string, - valueKey?: string, - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', - label?: Boolean | any | React.ReactElement | Function, - labelLine?: Boolean | any | React.ReactElement | Function, - data: any[], - activeIndex: any[], - activeShape: any | React.ReactElement | Function, - isAnimationActive?: Boolean, - animationBegin?: number, - animationDuration?: number, - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear' | Function, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class Pie extends React.Component { -} - -interface PieChartProps { - width: number, - height: number, - margin?: any, - onClick?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class PieChart extends React.Component { -} - -interface PolarAngleAxisProps { - dataKey: string | number, - cx: number, - cy: number, - radius: Percentage | number, - axisLine?: boolean | any, - axisLineType?: string, - tickLine?: boolean | any, - tick?: boolean | any | React.ReactElement | Function, - ticks: any[], - orient?: string, - tickFormatter: Function, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class PolarAngleAxis extends React.Component { -} - -interface PolarGridProps { - cx: number, - cy: number, - innerRadius: number, - outerRadius: number, - polarAngles: any[], - polarRadius: any[], - gridType?: 'polygon' | 'circle', -} -export class PolarGrid extends React.Component { -} - -interface PolarRadiusAxisProps { - angle?: number, - cx: number, - cy: number, - domain?: any[], - label?: string | number | React.ReactElement | Function, - orientation?: "left" | "right" | "middle", - axisLine?: boolean | any, - tick?: boolean | any | Element | Function, - tickFormatter: Function, - tickCount?: number, - scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | Function, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class PolarRadiusAxis extends React.Component { -} - -interface PolygonProps { - points: any[], - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class Polygon extends React.Component { -} - -interface RadarProps { - dataKey: string | number, - points: any[], - shape: Element | Function, - dot?: boolean | any | Element | Function, - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', - label?: boolean | any | Element | Function, - isAnimationActive?: Boolean, - animationBegin?: number, - animationDuration?: number, - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', -} -export class Radar extends React.Component { -} - -interface RadarChartProps { - width: number, - height: number, - cx?: Percentage | number, - cy?: Percentage | number, - startAngle?: number, - innerRadius?: Percentage | number, - outerRadius?: Percentage | number, - margin?: any, - clockWise?: boolean, - onMouseEnter?: Function, - onMouseLeave?: Function, - onClick?: Function, -} -export class RadarChart extends React.Component { -} - -interface RadialBarProps { - cx?: number, - cy?: number, - startAngle?: number, - endAngle?: number, - maxAngle?: number, - minAngle?: number, - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', - label?: Boolean | any | React.ReactElement | Function, - background?: Boolean | any | React.ReactElement | Function, - data: any[], - isAnimationActive?: Boolean, - animationBegin?: number, - animationDuration?: number, - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class RadialBar extends React.Component { -} - -interface RadialBarChartProps { - width?: number, - height?: number, - data?: any[], - margin?: any, - barCategoryGap?: Percentage | number, - barGap?: number, - cx?: Percentage | number, - cy?: Percentage | number, - innerRadius?: Percentage | number, - outerRadius?: Percentage | number, - barSize?: number, - onMouseEnter?: Function, - onMouseLeave?: Function, - onClick?: Function, -} -export class RadialBarChart extends React.Component { -} - -interface RectangleProps { - x?: number, - y?: number, - width?: number, - height?: number, - radius?: number, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class Rectangle extends React.Component { -} - -interface ReferenceAreaProps { - xAxisId?: string | number, - yAxisId?: string | number, - x1?: number | string, - x2?: number | string, - y1?: number | string, - y2?: number | string, - alwaysShow?: Boolean, - viewBox: any, - xAxis: any, - yAxis: any, - label?: string | number | React.ReactElement | Function, - isFront?: Boolean, -} -export class ReferenceArea extends React.Component { -} - -interface ReferenceDotProps { - xAxisId?: string | number, - yAxisId?: string | number, - x: number | string, - y: number | string, - alwaysShow?: Boolean, - xAxis: any, - yAxis: any, - label?: string | number | React.ReactElement | Function, - isFront?: Boolean, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseMove?: Function, - onMouseLeave?: Function, -} -export class ReferenceDot extends React.Component { -} - -interface ReferenceLineProps { - xAxisId?: string | number, - yAxisId?: string | number, - x?: number | string, - y?: number | string, - alwaysShow?: Boolean, - viewBox: any, - xAxis: any, - yAxis: any, - label?: string | number | React.ReactElement | Function, - isFront?: Boolean, -} -export class ReferenceLine extends React.Component { -} - -interface ResponsiveContainerProps { - aspect?: number, - width?: Percentage | number, - height?: Percentage | number, - minWidth?: number, - minHeight?: number, - debounce?: number, -} -export class ResponsiveContainer extends React.Component { -} - -interface ScatterProps { - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none', - xAxisId?: string | number, - yAxisId?: string | number, - zAxisId?: string | number, - line?: Boolean | any | React.ReactElement | Function, - shape?: 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | React.ReactElement | Function, - lineType?: 'joint' | 'fitting', - points: any[], - isAnimationActive?: Boolean, - animationBegin?: number, - animationDuration?: number, - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class Scatter extends React.Component { -} - -interface ScatterChartProps { - width: number, - height: number, - margin?: any, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class ScatterChart extends React.Component { -} - -interface SectorProps { - cx?: number, - cy?: number, - innerRadius?: number, - outerRadius?: number, - startAngle?: number, - endAngle?: number, - cornerRadius?: number, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class Sector extends React.Component { -} - -interface TextProps { - scaleToFit?: Boolean, - angle?: number, - width?: number, - textAnchor?: 'start' | 'middle' | 'end' | 'inherit', - verticalAnchor?: 'start' | 'middle' | 'end', -} -export class Text extends React.Component { -} - -interface TooltipProps { - separator?: string, - offset?: number, - itemStyle?: any, - wrapperStyle?: any, - labelStyle?: any, - cursor?: Boolean | any | React.ReactElement, - viewBox: any, - active?: Boolean, - coordinate?: any, - payload?: any[], - label?: string | number, - content?: React.ReactElement | Function, - formatter?: Function, - labelFormatter?: Function, - itemSorter?: Function, - isAnimationActive?: Boolean, - animationBegin?: number, - animationDuration?: number, - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', -} -export class Tooltip extends React.Component { -} - -interface TreemapProps { - width: number, - height: number, - dataKey?: string, - aspectRatio: number, - isAnimationActive?: Boolean, - animationBegin?: number, - animationDuration?: number, - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear', -} -export class Treemap extends React.Component { -} - -interface XAxisProps { - hide?: Boolean, - dataKey?: string | number, - xAxisId?: string | number, - width?: number, - height?: number, - orientation?: 'bottom' | 'top', - type?: 'number' | 'category', - allowDecimals?: Boolean, - allowDataOverflow?: Boolean, - tickCount?: number, - domain?: any[], - interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number, - padding?: any, - minTickGap?: number, - axisLine?: Boolean | any, - tickLine?: Boolean | any, - tickSize?: number, - tickFormatter?: Function, - ticks?: any[], - tick?: Boolean | any | React.ReactElement, - mirror?: Boolean, - reversed?: Boolean, - label?: string | number | React.ReactElement, - scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | Function, - unit?: string | number, - name?: string | number, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class XAxis extends React.Component { -} - -interface YAxisProps { - hide?: Boolean, - dataKey?: string | number, - yAxisId?: string | number, - width?: number, - height?: number, - orientation?: 'left' | 'right', - type?: 'number' | 'category', - domain?: any[], - interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number, - padding?: any, - minTickGap?: number, - allowDecimals?: Boolean, - allowDataOverflow?: Boolean, - axisLine?: Boolean | any, - tickLine?: Boolean | any, - tickSize?: number, - tickFormatter?: Function, - ticks?: any[], - tick?: Boolean | any | React.ReactElement, - mirror?: Boolean, - reversed?: Boolean, - label?: string | number | React.ReactElement, - scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | Function, - unit?: string | number, - name?: string | number, - onClick?: Function, - onMouseDown?: Function, - onMouseUp?: Function, - onMouseMove?: Function, - onMouseOver?: Function, - onMouseOut?: Function, - onMouseEnter?: Function, - onMouseLeave?: Function, -} -export class YAxis extends React.Component { -} - -interface ZAxisProps { - dataKey: string | number, - zAxisId?: string | number, - range?: any[], - unit?: string | number, - name?: string | number, - scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | Function, -} -export class ZAxis extends React.Component { -} - diff --git a/types/recharts/tsconfig.json b/types/recharts/tsconfig.json index 41fddb0ef2..06e783c53b 100644 --- a/types/recharts/tsconfig.json +++ b/types/recharts/tsconfig.json @@ -6,9 +6,10 @@ "dom" ], "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, + "noImplicitThis": true, + "strictNullChecks": true, "baseUrl": "../", + "jsx": "react", "typeRoots": [ "../" ], @@ -19,6 +20,5 @@ "files": [ "index.d.ts", "test/index.tsx" - ], - "jsx": "react" + ] } diff --git a/types/recharts/tslint.json b/types/recharts/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/recharts/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From a55ce8b200e430e69967dde36d839dd76a8aacc8 Mon Sep 17 00:00:00 2001 From: Maarten Mulders Date: Mon, 17 Jul 2017 07:46:00 +0200 Subject: [PATCH 0057/1139] Rename test file --- types/recharts/{test/index.tsx => recharts-tests.tsx} | 0 types/recharts/tsconfig.json | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) rename types/recharts/{test/index.tsx => recharts-tests.tsx} (100%) diff --git a/types/recharts/test/index.tsx b/types/recharts/recharts-tests.tsx similarity index 100% rename from types/recharts/test/index.tsx rename to types/recharts/recharts-tests.tsx diff --git a/types/recharts/tsconfig.json b/types/recharts/tsconfig.json index 06e783c53b..1bd69f0d1e 100644 --- a/types/recharts/tsconfig.json +++ b/types/recharts/tsconfig.json @@ -19,6 +19,6 @@ }, "files": [ "index.d.ts", - "test/index.tsx" + "recharts-tests.tsx" ] } From 73d430abe6db9acb0bcbe812c86646d7ded6b51f Mon Sep 17 00:00:00 2001 From: Jianrong Yu Date: Mon, 17 Jul 2017 14:02:25 +0800 Subject: [PATCH 0058/1139] Add .d.ts files for npm module --- types/node-vault/index.d.ts | 127 +++++++++++++++++++++++++++ types/node-vault/node-vault-tests.ts | 28 ++++++ types/node-vault/tsconfig.json | 22 +++++ types/node-vault/tslint.json | 1 + 4 files changed, 178 insertions(+) create mode 100644 types/node-vault/index.d.ts create mode 100644 types/node-vault/node-vault-tests.ts create mode 100644 types/node-vault/tsconfig.json create mode 100644 types/node-vault/tslint.json diff --git a/types/node-vault/index.d.ts b/types/node-vault/index.d.ts new file mode 100644 index 0000000000..939da2bd2a --- /dev/null +++ b/types/node-vault/index.d.ts @@ -0,0 +1,127 @@ +// Type definitions for node-vault 0.5 +// Project: https://github.com/kr1sp1n/node-vault +// Definitions by: Jianrong Yu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as mustache from "mustache"; +import * as request from "request"; + +declare namespace NodeVault { + interface Option { + [p: string]: any; + } + + interface RequestOption extends Option { + path: string; + method: string; + } + + interface functionConf { + method: string; + path: string; + schema?: { + req?: Option; + query?: Option; + res?: Option; + }; + } + + interface client { + handleVaultResponse(res?: { statusCode: number, request: Option, body: any }): Promise; + apiVersion: string; + endpoint: string; + token: string; + + request(requestOptions: RequestOption): Promise; + + help(path: string, requestOptions?: Option): Promise; + write(path: string, data: any, requestOptions?: Option): Promise; + read(path: string, requestOptions?: Option): Promise; + list(path: string, requestOptions?: Option): Promise; + delete(path: string, requestOptions?: Option): Promise; + + generateFunction(name: string, conf: functionConf): void; + + status(options?: Option): Promise; + initialized(options?: Option): Promise; + init(options?: Option): Promise; + unseal(options?: Option): Promise; + seal(options?: Option): Promise; + generateRootStatus(options?: Option): Promise; + generateRootInit(options?: Option): Promise; + generateRootCancel(options?: Option): Promise; + generateRootUpdate(options?: Option): Promise; + mounts(options?: Option): Promise; + mount(options?: Option): Promise; + unmount(options?: Option): Promise; + remount(options?: Option): Promise; + policies(options?: Option): Promise; + addPolicy(options?: Option): Promise; + getPolicy(options?: Option): Promise; + removePolicy(options?: Option): Promise; + auths(options?: Option): Promise; + enableAuth(options?: Option): Promise; + disableAuth(options?: Option): Promise; + audits(options?: Option): Promise; + enableAudit(options?: Option): Promise; + disableAudit(options?: Option): Promise; + renew(options?: Option): Promise; + revoke(options?: Option): Promise; + revokePrefix(options?: Option): Promise; + rotate(options?: Option): Promise; + githubLogin(options?: Option): Promise; + userpassLogin(options?: Option): Promise; + tokenAccessors(options?: Option): Promise; + tokenCreate(options?: Option): Promise; + tokenCreateOrphan(options?: Option): Promise; + tokenCreateRole(options?: Option): Promise; + tokenLookup(options?: Option): Promise; + tokenLookupAccessor(options?: Option): Promise; + tokenLookupSelf(options?: Option): Promise; + tokenRenew(options?: Option): Promise; + tokenRenewSelf(options?: Option): Promise; + tokenRevoke(options?: Option): Promise; + tokenRevokeAccessor(options?: Option): Promise; + tokenRevokeOrphan(options?: Option): Promise; + tokenRevokeSelf(options?: Option): Promise; + tokenRoles(options?: Option): Promise; + addTokenRole(options?: Option): Promise; + getTokenRole(options?: Option): Promise; + removeTokenRole(options?: Option): Promise; + approleRoles(options?: Option): Promise; + addApproleRole(options?: Option): Promise; + getApproleRole(options?: Option): Promise; + deleteApproleRole(options?: Option): Promise; + getApproleRoleId(options?: Option): Promise; + updateApproleRoleId(options?: Option): Promise; + getApproleRoleSecret(options?: Option): Promise; + approleSecretAccessors(options?: Option): Promise; + approleSecretLookup(options?: Option): Promise; + approleSecretDestroy(options?: Option): Promise; + approleSecretAccessorLookup(options?: Option): Promise; + approleSecretAccessorDestroy(options?: Option): Promise; + approleLogin(options?: Option): Promise; + health(options?: Option): Promise; + leader(options?: Option): Promise; + stepDown(options?: Option): Promise; + } + + interface VaultOptions { + debug?(...args: any[]): any; + tv4?(...args: any[]): any; + commands?: Array<{ method: string, path: string, scheme: any }>; + mustache?: MustacheStatic; + "request-promise"?: any; + Promise?: PromiseConstructor; + + apiVersion?: string; + endpoint?: string; + token?: string; + requestOptions?: request.CoreOptions; + } +} + +type GetClient = (options?: NodeVault.VaultOptions) => NodeVault.client; + +declare const getClient: GetClient; +export = getClient; diff --git a/types/node-vault/node-vault-tests.ts b/types/node-vault/node-vault-tests.ts new file mode 100644 index 0000000000..966fe4869b --- /dev/null +++ b/types/node-vault/node-vault-tests.ts @@ -0,0 +1,28 @@ +import * as nv from "node-vault"; + +// Test code came from the sample code in README of the module. +const options = { + apiVersion: 'v1', // default + endpoint: 'http://127.0.0.1:8200', // default + token: '1234', // optional client token; can be fetched after valid initialization of the server +}; + +// get new instance of the client +let vault = nv(options); + +// init vault server +vault.init({ secret_shares: 1, secret_threshold: 1 }) +.then( (result) => { + let keys = result.keys; + // set token for all following requests + vault.token = result.root_token; + // unseal vault server + return vault.unseal({ secret_shares: 1, key: keys[0] }); +}) +.catch(console.error); + +// write, read and delete secrets +vault.write('secret/hello', { value: 'world', lease: '1s' }) +.then( () => vault.read('secret/hello')) +.then( () => vault.delete('secret/hello')) +.catch(console.error); diff --git a/types/node-vault/tsconfig.json b/types/node-vault/tsconfig.json new file mode 100644 index 0000000000..272b66070e --- /dev/null +++ b/types/node-vault/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "node-vault-tests.ts" + ] +} diff --git a/types/node-vault/tslint.json b/types/node-vault/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/node-vault/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From cf8d9038e5b3487a97b9a19221aecfb845369801 Mon Sep 17 00:00:00 2001 From: Lucas Hill Date: Sun, 16 Jul 2017 23:12:54 -0700 Subject: [PATCH 0059/1139] Create type defintions for through2-map. --- types/through2-map/index.d.ts | 31 +++++++++++++++++++++ types/through2-map/through2-map-tests.ts | 35 ++++++++++++++++++++++++ types/through2-map/tsconfig.json | 22 +++++++++++++++ types/through2-map/tslint.json | 1 + 4 files changed, 89 insertions(+) create mode 100644 types/through2-map/index.d.ts create mode 100644 types/through2-map/through2-map-tests.ts create mode 100644 types/through2-map/tsconfig.json create mode 100644 types/through2-map/tslint.json diff --git a/types/through2-map/index.d.ts b/types/through2-map/index.d.ts new file mode 100644 index 0000000000..c14982705b --- /dev/null +++ b/types/through2-map/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for through2-map 3.0 +// Project: https://github.com/brycebaril/through2-map +// Definitions by: Lucas Hill +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import through2 = require('through2'); +import stream = require('stream'); + +type MapCallback = (chunk: any, index: number) => void; + +interface Through2MapOptions extends stream.DuplexOptions { + wantStrings?: boolean; +} + +declare function through2_map(options?: Through2MapOptions, fn?: MapCallback): through2.Through2Constructor; +declare function through2_map(fn?: MapCallback): through2.Through2Constructor; + +declare namespace through2_map { + function ctor(options?: Through2MapOptions, fn?: MapCallback): through2.Through2Constructor; + function ctor(fn?: MapCallback): through2.Through2Constructor; + + function obj(options?: Through2MapOptions, fn?: MapCallback): through2.Through2Constructor; + function obj(fn?: MapCallback): through2.Through2Constructor; + + function objCtor(options?: Through2MapOptions, fn?: MapCallback): through2.Through2Constructor; + function objCtor(fn?: MapCallback): through2.Through2Constructor; +} + +export = through2_map; diff --git a/types/through2-map/through2-map-tests.ts b/types/through2-map/through2-map-tests.ts new file mode 100644 index 0000000000..88a26d2f24 --- /dev/null +++ b/types/through2-map/through2-map-tests.ts @@ -0,0 +1,35 @@ +import stream = require('stream'); +import map = require('through2-map'); + +const stripTags = map({wantStrings: true}, (str) => { + return str.replace(/<.*?>/g, ""); +}); + +process.stdin.pipe(stripTags); + +const truncate = map((chunk) => { + return chunk.slice(0, 10); +}); + +process.stdin.pipe(truncate); + +const Ctor = map.ctor((chunk) => { + return chunk.slice(0, 10); +}); + +new Ctor(); +new Ctor({ objectMode: true, allowHalfOpen: true }); + +const Obj = map.obj((chunk) => { + return chunk.slice(0, 10); +}); + +new Obj(); +new Obj({ objectMode: true, allowHalfOpen: true }); + +const Objctor = map.objCtor((chunk) => { + return chunk.slice(0, 10); +}); + +new Objctor(); +new Objctor({ objectMode: true, allowHalfOpen: true }); diff --git a/types/through2-map/tsconfig.json b/types/through2-map/tsconfig.json new file mode 100644 index 0000000000..b20edc8d85 --- /dev/null +++ b/types/through2-map/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "through2-map-tests.ts" + ] +} diff --git a/types/through2-map/tslint.json b/types/through2-map/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/through2-map/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c7c8a5ec56b7b289abebc82a2272cbf603b00e33 Mon Sep 17 00:00:00 2001 From: Ailrun Date: Mon, 17 Jul 2017 02:18:16 -0400 Subject: [PATCH 0060/1139] fix lodash type for orderBy --- types/lodash/index.d.ts | 51 ++++++++++++++++++++++------------------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index 5945f00035..a55cb6106c 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -1,6 +1,11 @@ // Type definitions for Lo-Dash 4.14 // Project: http://lodash.com/ -// Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk , Eric L Anderson , AJ Richardson +// Definitions by: Brian Zengel , +// Ilya Mochalov , +// Stepan Mikhaylyuk , +// Eric L Anderson , +// AJ Richardson , +// Junyoung Clare Jang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -9876,7 +9881,7 @@ declare namespace _ { */ orderBy( collection: List | null | undefined, - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): T[]; @@ -9885,7 +9890,7 @@ declare namespace _ { */ orderBy( collection: List | null | undefined, - iteratees: Many|string|Object>, + iteratees?: Many|string|Object>, orders?: Many ): T[]; @@ -9894,7 +9899,7 @@ declare namespace _ { */ orderBy( collection: NumericDictionary | null | undefined, - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): T[]; @@ -9903,7 +9908,7 @@ declare namespace _ { */ orderBy( collection: NumericDictionary | null | undefined, - iteratees: Many|string|Object>, + iteratees?: Many|string|Object>, orders?: Many ): T[]; @@ -9912,7 +9917,7 @@ declare namespace _ { */ orderBy( collection: Dictionary | null | undefined, - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): T[]; @@ -9921,7 +9926,7 @@ declare namespace _ { */ orderBy( collection: Dictionary | null | undefined, - iteratees: Many|string|Object>, + iteratees?: Many|string|Object>, orders?: Many ): T[]; } @@ -9931,7 +9936,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string>, + iteratees?: Many|string>, orders?: Many ): LoDashImplicitArrayWrapper; } @@ -9941,7 +9946,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): LoDashImplicitArrayWrapper; } @@ -9951,7 +9956,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): LoDashImplicitArrayWrapper; @@ -9959,7 +9964,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|Object>, + iteratees?: Many|string|Object>, orders?: Many ): LoDashImplicitArrayWrapper; @@ -9967,7 +9972,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): LoDashImplicitArrayWrapper; @@ -9975,7 +9980,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|Object>, + iteratees?: Many|string|Object>, orders?: Many ): LoDashImplicitArrayWrapper; @@ -9983,7 +9988,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): LoDashImplicitArrayWrapper; @@ -9991,7 +9996,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|Object>, + iteratees?: Many|string|Object>, orders?: Many ): LoDashImplicitArrayWrapper; } @@ -10001,7 +10006,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string>, + iteratees?: Many|string>, orders?: Many ): LoDashExplicitArrayWrapper; } @@ -10011,7 +10016,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|W|(ListIterator|string|W)>, + iteratees?: Many|string|W|(ListIterator|string|W)>, orders?: Many ): LoDashExplicitArrayWrapper; } @@ -10021,7 +10026,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): LoDashExplicitArrayWrapper; @@ -10029,7 +10034,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|Object>, + iteratees?: Many|string|Object>, orders?: Many ): LoDashExplicitArrayWrapper; @@ -10037,7 +10042,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): LoDashExplicitArrayWrapper; @@ -10045,7 +10050,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|Object>, + iteratees?: Many|string|Object>, orders?: Many ): LoDashExplicitArrayWrapper; @@ -10053,7 +10058,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|W>, + iteratees?: Many|string|W>, orders?: Many ): LoDashExplicitArrayWrapper; @@ -10061,7 +10066,7 @@ declare namespace _ { * @see _.orderBy */ orderBy( - iteratees: Many|string|Object>, + iteratees?: Many|string|Object>, orders?: Many ): LoDashExplicitArrayWrapper; } From 91c135589035a0bcbc500a8b9987b19b4a03af7f Mon Sep 17 00:00:00 2001 From: Giedrius Grabauskas Date: Mon, 17 Jul 2017 12:25:42 +0300 Subject: [PATCH 0061/1139] Created StoresList type. --- types/flux/lib/FluxContainer.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/flux/lib/FluxContainer.d.ts b/types/flux/lib/FluxContainer.d.ts index 54b578cc1d..4d49293fa6 100644 --- a/types/flux/lib/FluxContainer.d.ts +++ b/types/flux/lib/FluxContainer.d.ts @@ -37,8 +37,10 @@ export interface RealOptions { export type ComponentConstructor = React.ComponentClass | React.StatelessComponent; +export type StoresList = Array>; + export interface ComponentStatic { - getStores(maybeProps?: TProps, maybeContext?: TContext): Array>; + getStores(maybeProps?: TProps, maybeContext?: TContext): StoresList; calculateState(prevState: TState, maybeProps?: TProps, maybeContext?: TContext): TState; } From 528ba240c9704e7f31f0eaadacd3ea77f285fc54 Mon Sep 17 00:00:00 2001 From: Giedrius Grabauskas Date: Mon, 17 Jul 2017 12:28:19 +0300 Subject: [PATCH 0062/1139] Implemented StoresList in tests. --- types/flux/test/FluxUtils.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/flux/test/FluxUtils.tsx b/types/flux/test/FluxUtils.tsx index 1cd3705fab..38e06e71e4 100644 --- a/types/flux/test/FluxUtils.tsx +++ b/types/flux/test/FluxUtils.tsx @@ -38,7 +38,7 @@ interface State { } class CounterContainer extends React.Component { - static getStores() { + static getStores(): Container.StoresList { return [Store]; } From f8f5952e2cf820bc8c8a175a24ca32457258e6b8 Mon Sep 17 00:00:00 2001 From: Ian Shea Date: Mon, 17 Jul 2017 08:40:37 -0700 Subject: [PATCH 0063/1139] moving from {} to any for state pass --- types/react-transition-group/CSSTransition.d.ts | 2 +- types/react-transition-group/Transition.d.ts | 2 +- types/react-transition-group/TransitionGroup.d.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/react-transition-group/CSSTransition.d.ts b/types/react-transition-group/CSSTransition.d.ts index 7f0e398756..763ea80a0f 100644 --- a/types/react-transition-group/CSSTransition.d.ts +++ b/types/react-transition-group/CSSTransition.d.ts @@ -33,6 +33,6 @@ export interface CSSTransitionProps extends TransitionProps { classNames: string | CSSTransitionClassNames; } -declare class CSSTransition extends Component {} +declare class CSSTransition extends Component {} export default CSSTransition; diff --git a/types/react-transition-group/Transition.d.ts b/types/react-transition-group/Transition.d.ts index 29bc3e2bde..844561333c 100644 --- a/types/react-transition-group/Transition.d.ts +++ b/types/react-transition-group/Transition.d.ts @@ -66,6 +66,6 @@ export interface TransitionProps extends TransitionActions { * ``` * */ -declare class Transition extends Component {} +declare class Transition extends Component {} export default Transition; diff --git a/types/react-transition-group/TransitionGroup.d.ts b/types/react-transition-group/TransitionGroup.d.ts index 6aa8cd5bb1..e746d3ca77 100644 --- a/types/react-transition-group/TransitionGroup.d.ts +++ b/types/react-transition-group/TransitionGroup.d.ts @@ -71,6 +71,6 @@ export type TransitionGroupProps {} +declare class TransitionGroup extends Component {} export default TransitionGroup; From 1330e59c74a514b8fd5a23e03b23f8f77d9219b4 Mon Sep 17 00:00:00 2001 From: Sa-ryong Kang Date: Tue, 18 Jul 2017 01:57:27 +0900 Subject: [PATCH 0064/1139] remove trailing whitespaces --- types/react-daum-postcode/index.d.ts | 6 +++--- types/react-daum-postcode/react-daum-postcode-tests.tsx | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/react-daum-postcode/index.d.ts b/types/react-daum-postcode/index.d.ts index 6f3ea43b9d..d5256161f0 100644 --- a/types/react-daum-postcode/index.d.ts +++ b/types/react-daum-postcode/index.d.ts @@ -1,8 +1,8 @@ -// Type definitions for react-daum-postcode 1.2.1 +// Type definitions for react-daum-postcode 1.2 // Project: https://github.com/kimminsik-bernard/react-daum-postcode // Definitions by: Sa-ryong Kang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.2 import { Component } from 'react'; @@ -20,4 +20,4 @@ export interface DaumPostcodeProps { export default class DaumPostcode extends Component { render(): JSX.Element; -} \ No newline at end of file +} diff --git a/types/react-daum-postcode/react-daum-postcode-tests.tsx b/types/react-daum-postcode/react-daum-postcode-tests.tsx index 7e58d5f251..799d255719 100644 --- a/types/react-daum-postcode/react-daum-postcode-tests.tsx +++ b/types/react-daum-postcode/react-daum-postcode-tests.tsx @@ -4,8 +4,8 @@ import DaumPostcode from 'react-daum-postcode'; class Postcode extends React.Component { handleAddress = (data: any) => { let fullAddress: string = data.address; - let extraAddress = ''; - + let extraAddress = ''; + if (data.addressType === 'R') { if (data.bname !== '') { extraAddress += data.bname; @@ -26,4 +26,4 @@ class Postcode extends React.Component { /> ); } -} \ No newline at end of file +} From 3c6525ef95470cb33f16d79b5c727129c36ecd93 Mon Sep 17 00:00:00 2001 From: John Gainfort Jr Date: Mon, 17 Jul 2017 11:00:09 -0600 Subject: [PATCH 0065/1139] change VastAd creatives to match closer to library type --- types/vast-client/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/vast-client/index.d.ts b/types/vast-client/index.d.ts index 9886554e88..639b940a04 100644 --- a/types/vast-client/index.d.ts +++ b/types/vast-client/index.d.ts @@ -231,9 +231,14 @@ export interface VastError { ERRORCODE: string; } +export interface VastCreative { + 0: VastCreativeLinear, + 1: VastCreativeCompanion +} + export interface VastAd { advertiser: any; - creatives: VastCreativeLinear | VastCreativeCompanion[]; + creatives: VastCreative[]; description: string; errorURLTemplates: string[]; extensions: VastAdExtension[]; From 9abaa3c05f16baae0f4a4efe087ae581f02d7806 Mon Sep 17 00:00:00 2001 From: John Gainfort Jr Date: Mon, 17 Jul 2017 11:02:03 -0600 Subject: [PATCH 0066/1139] removing VastAd.creative as an array and using object index signature instead --- types/vast-client/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/vast-client/index.d.ts b/types/vast-client/index.d.ts index 639b940a04..7b01df7cd5 100644 --- a/types/vast-client/index.d.ts +++ b/types/vast-client/index.d.ts @@ -238,7 +238,7 @@ export interface VastCreative { export interface VastAd { advertiser: any; - creatives: VastCreative[]; + creatives: VastCreative; description: string; errorURLTemplates: string[]; extensions: VastAdExtension[]; From f565abfe39eb44d830e7a13993d28564b55ee42c Mon Sep 17 00:00:00 2001 From: John Gainfort Jr Date: Mon, 17 Jul 2017 11:04:20 -0600 Subject: [PATCH 0067/1139] fixed lint error --- types/vast-client/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/vast-client/index.d.ts b/types/vast-client/index.d.ts index 7b01df7cd5..79de29c6b0 100644 --- a/types/vast-client/index.d.ts +++ b/types/vast-client/index.d.ts @@ -232,8 +232,8 @@ export interface VastError { } export interface VastCreative { - 0: VastCreativeLinear, - 1: VastCreativeCompanion + 0: VastCreativeLinear; + 1: VastCreativeCompanion; } export interface VastAd { From a7c4d077982419a0644c6836c18bd407174dd76d Mon Sep 17 00:00:00 2001 From: Ben Windsor Date: Mon, 17 Jul 2017 18:39:39 +0100 Subject: [PATCH 0068/1139] Update SES nodemailer typings to match current implementation (#17888) * Update ses transport types to match current nodemailer * Updated tests * Updated version number * Update SES test to match new defintion * Set noemit to true in tsconfig * Change version to only have x.x * Added import aws-sdk to ses tests * Added package.json for aws dependency * Add missing semicolon --- types/nodemailer-ses-transport/index.d.ts | 13 +++---- .../nodemailer-ses-transport-tests.ts | 9 ++--- types/nodemailer/index.d.ts | 18 ++++------ types/nodemailer/nodemailer-tests.ts | 34 +++++++++---------- types/nodemailer/package.json | 5 +++ types/nodemailer/tsconfig.json | 1 + 6 files changed, 37 insertions(+), 43 deletions(-) create mode 100644 types/nodemailer/package.json diff --git a/types/nodemailer-ses-transport/index.d.ts b/types/nodemailer-ses-transport/index.d.ts index ecda97f189..98e54f51ce 100644 --- a/types/nodemailer-ses-transport/index.d.ts +++ b/types/nodemailer-ses-transport/index.d.ts @@ -1,22 +1,17 @@ -// Type definitions for nodemailer-ses-transport 1.4 +// Type definitions for nodemailer-ses-transport 3.1 // Project: https://github.com/andris9/nodemailer-ses-transport // Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as AWS from "aws-sdk"; -import { HTTPOptions } from "aws-sdk/lib/config"; import * as nodemailer from "nodemailer"; declare namespace sesTransport { interface SesOptions { - ses?: AWS.SES; - accessKeyId?: string; - secretAccessKey?: string; - sessionToken?: string; - region?: string; - httpOptions?: HTTPOptions; - rateLimit?: number; + SES: AWS.SES; + component?: string; maxConnections?: number; + sendingRate?: number; } } diff --git a/types/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts b/types/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts index 57e01c7627..393091816d 100644 --- a/types/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts +++ b/types/nodemailer-ses-transport/nodemailer-ses-transport-tests.ts @@ -1,11 +1,12 @@ -import * as AWS from 'aws-sdk'; +import * as AWS from "aws-sdk"; import * as nodemailer from "nodemailer"; import * as sesTransport from 'nodemailer-ses-transport'; const opts: sesTransport.SesOptions = { - ses: new AWS.SES(), - rateLimit: 5, - maxConnections: 3, + SES: new AWS.SES(), + component: "string", + sendingRate: 5, + maxConnections: 3 }; const transport: nodemailer.Transport = sesTransport(opts); diff --git a/types/nodemailer/index.d.ts b/types/nodemailer/index.d.ts index 833873c45e..1b745ed08c 100644 --- a/types/nodemailer/index.d.ts +++ b/types/nodemailer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Nodemailer 1.3.2 +// Type definitions for Nodemailer 3.1.5 // Project: https://github.com/andris9/Nodemailer // Definitions by: Rogier Schouten // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,6 +7,7 @@ import directTransport = require("nodemailer-direct-transport"); import smtpTransport = require("nodemailer-smtp-transport"); +import sesTransport = require("nodemailer-ses-transport") /** * Transporter plugin @@ -30,17 +31,6 @@ export interface Transporter { */ sendMail(mail: SendMailOptions): Promise; - /** - * Send mail using a template. - */ - templateSender(template?: any, defaults?: any): (mailData: any, context: any) => Promise; - - /** - * Send mail using a template with a callback. - */ - templateSender(template?: any, defaults?: any, callback?: (error: Error, info: SentMessageInfo) => void): void; - - /** * Attach a plugin. 'compile' and 'stream' plugins can be attached with use(plugin) method * @@ -73,6 +63,10 @@ export declare function createTransport(options?: directTransport.DirectOptions, * Create an SMTP transporter */ export declare function createTransport(options?: smtpTransport.SmtpOptions, defaults?: Object): Transporter; +/** + * Create an AWS SES transporter + */ +export declare function createTransport(options?: sesTransport.SesOptions, defaults?: Object): Transporter /** * Create a transporter from a given implementation */ diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index 56d2b01f65..2552b9696d 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -1,5 +1,5 @@ - import * as nodemailer from 'nodemailer' +import * as AWS from 'aws-sdk' // create reusable transporter object using SMTP transport var transporter: nodemailer.Transporter = nodemailer.createTransport({ @@ -10,6 +10,20 @@ var transporter: nodemailer.Transporter = nodemailer.createTransport({ } }); +// create reusable transporter object using SES transport and set default values for mail options. +transporter = nodemailer.createTransport({ + SES: new AWS.SES() +}) +// create reusable transporter object using SMTP transport and set default values for mail options. +transporter = nodemailer.createTransport({ + SES: new AWS.SES() +}, { + from: 'sender@address', + headers: { + 'My-Awesome-Header': '123' + } +}) + // create reusable transporter object using SMTP transport and set default values for mail options. transporter = nodemailer.createTransport({ service: 'Gmail', @@ -42,20 +56,4 @@ transporter.sendMail(mailOptions, (error: Error, info: nodemailer.SentMessageInf transporter .sendMail(mailOptions) .then(info => info.messageId) -// create template based sender function -var sendPwdReset = transporter.templateSender({ - subject: 'Password reset for {{username}}!', - text: 'Hello, {{username}}, Please go here to reset your password: {{ reset }}', - html: 'Hello, {{username}}, Please go here to reset your password: {{ reset }}

' -}, { - from: 'sender@example.com', -}); - -// use template based sender to send a message -sendPwdReset({ - to: 'receiver@example.com' -}, { - username: 'Node Mailer', - reset: 'https://www.example.com/reset?token=' -}) -.then(info => info.messageId); + .catch(err => {}) \ No newline at end of file diff --git a/types/nodemailer/package.json b/types/nodemailer/package.json new file mode 100644 index 0000000000..5d63df3979 --- /dev/null +++ b/types/nodemailer/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "aws-sdk": "^2.37.0" + } +} diff --git a/types/nodemailer/tsconfig.json b/types/nodemailer/tsconfig.json index cde9a08acf..22f8e695f7 100644 --- a/types/nodemailer/tsconfig.json +++ b/types/nodemailer/tsconfig.json @@ -11,6 +11,7 @@ "typeRoots": [ "../" ], + "allowJs": true, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true From 7ef13ce8d04a8955f2a951ed3f9bd0f020a35661 Mon Sep 17 00:00:00 2001 From: vitalii Date: Mon, 17 Jul 2017 18:47:05 +0100 Subject: [PATCH 0069/1139] update angular-resource interceptor (#17919) --- types/angular-resource/index.d.ts | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/types/angular-resource/index.d.ts b/types/angular-resource/index.d.ts index 9a036f336d..b95911ae2c 100644 --- a/types/angular-resource/index.d.ts +++ b/types/angular-resource/index.d.ts @@ -53,6 +53,20 @@ declare module 'angular' { interface IActionHash { [action: string]: IActionDescriptor; } + + interface IResourceResponse { + config: any; + data: any; + headers: any; + resource: any; + status: number; + statusText: string + } + + interface IResourceInterceptor { + response?(response: IResourceResponse): any; + responseError?(rejection: any): any; + } // Just a reference to facilitate describing new actions interface IActionDescriptor { @@ -73,7 +87,7 @@ declare module 'angular' { cancellable?: boolean; withCredentials?: boolean; responseType?: string; - interceptor?: angular.IHttpInterceptor; + interceptor?: IResourceInterceptor; } // Allow specify more resource methods From b15d47c31d421f963c5cc219e0543d1680cb82ee Mon Sep 17 00:00:00 2001 From: Bas Bosman Date: Mon, 17 Jul 2017 19:47:49 +0200 Subject: [PATCH 0070/1139] Tweak ShortcutsArray definition for simplemde (#17944) --- types/simplemde/index.d.ts | 2 +- types/simplemde/simplemde-tests.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/simplemde/index.d.ts b/types/simplemde/index.d.ts index c78d4fb408..693e4a2ca2 100644 --- a/types/simplemde/index.d.ts +++ b/types/simplemde/index.d.ts @@ -35,7 +35,7 @@ declare namespace SimpleMDE { } interface ShortcutsArray { - [action: string]: string; + [action: string]: string|undefined; toggleBlockquote?: string; toggleBold?: string; cleanBlock?: string; diff --git a/types/simplemde/simplemde-tests.ts b/types/simplemde/simplemde-tests.ts index e9be36b7cb..313b3c80d4 100644 --- a/types/simplemde/simplemde-tests.ts +++ b/types/simplemde/simplemde-tests.ts @@ -57,7 +57,8 @@ function testSimplemde() { codeSyntaxHighlighting: true }, shortcuts: { - drawTable: "Cmd-Alt-T" + drawTable: "Cmd-Alt-T", + toggleCodeBlock: null }, showIcons: ["code", "table"], spellChecker: false, From 86bc2813fbf24758aaf410b067cdfff3057a3b67 Mon Sep 17 00:00:00 2001 From: Rylan Cottrell Date: Mon, 17 Jul 2017 13:48:09 -0400 Subject: [PATCH 0071/1139] Added missing option maxViewMode (#17953) maxViewMode has the same type as minViewMode. http://bootstrap-datepicker.readthedocs.io/en/latest/options.html#maxviewmode --- types/bootstrap-datepicker/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/bootstrap-datepicker/index.d.ts b/types/bootstrap-datepicker/index.d.ts index 9287ee1ba3..34a40d60fa 100644 --- a/types/bootstrap-datepicker/index.d.ts +++ b/types/bootstrap-datepicker/index.d.ts @@ -36,6 +36,7 @@ interface DatepickerOptions { forceParse?: boolean; inputs?: any[]; minViewMode?: 0|"days"|1|"months"|2|"years"|3|"decades"|4|"centuries"|"millenium"; + maxViewMode?: 0|"days"|1|"months"|2|"years"|3|"decades"|4|"centuries"|"millenium"; multidate?: boolean|number; multidateSeparator?: string; orientation?: "auto"|"left top"|"left bottom"|"right top"|"right bottom"; From dc34e6c8312a6b06d7b4e4db18e848e2704b8571 Mon Sep 17 00:00:00 2001 From: Giedrius Grabauskas Date: Mon, 17 Jul 2017 20:53:29 +0300 Subject: [PATCH 0072/1139] Updated react-i18next types to 4.6.1 (#17715) * Create tslint.json * Moved v1 types to specified version folder. * Created types for react-i18next. * Exported as global UMD module. * Added more tests. * Fixed dtslint errors. * Removed @KostyaEsmukov from the authors list. * Added addition data for Trans component. * Added typescript 2.3 support. * Added generic TKey for translate method. * Removed path map to i18next/v2. * Fixed dtslint error. * Fixed ts error. --- types/react-i18next/index.d.ts | 74 ++++++--------- types/react-i18next/src/I18nextProvider.d.ts | 12 +++ types/react-i18next/src/interpolate.d.ts | 23 +++++ types/react-i18next/src/loadNamespaces.d.ts | 9 ++ types/react-i18next/src/trans.d.ts | 8 ++ types/react-i18next/src/translate.d.ts | 15 +++ .../test/react-i18next-tests.tsx | 92 +++++++++++++++++++ types/react-i18next/tsconfig.json | 12 +-- types/react-i18next/tslint.json | 1 + types/react-i18next/v1/index.d.ts | 57 ++++++++++++ .../{ => v1}/react-i18next-tests.tsx | 0 types/react-i18next/v1/tsconfig.json | 33 +++++++ 12 files changed, 283 insertions(+), 53 deletions(-) create mode 100644 types/react-i18next/src/I18nextProvider.d.ts create mode 100644 types/react-i18next/src/interpolate.d.ts create mode 100644 types/react-i18next/src/loadNamespaces.d.ts create mode 100644 types/react-i18next/src/trans.d.ts create mode 100644 types/react-i18next/src/translate.d.ts create mode 100644 types/react-i18next/test/react-i18next-tests.tsx create mode 100644 types/react-i18next/tslint.json create mode 100644 types/react-i18next/v1/index.d.ts rename types/react-i18next/{ => v1}/react-i18next-tests.tsx (100%) create mode 100644 types/react-i18next/v1/tsconfig.json diff --git a/types/react-i18next/index.d.ts b/types/react-i18next/index.d.ts index cf56874445..d7bb05a30f 100644 --- a/types/react-i18next/index.d.ts +++ b/types/react-i18next/index.d.ts @@ -1,57 +1,37 @@ -// Type definitions for react-i18next 1.7.0 +// Type definitions for react-i18next 4.6 // Project: https://github.com/i18next/react-i18next -// Definitions by: Kostya Esmukov +// Definitions by: Giedrius Grabauskas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as I18next from "i18next"; -import * as React from "react"; +import { TranslationFunction } from "i18next"; -export type TranslationFunction = I18next.TranslationFunction; +import I18nextProvider from "./src/I18nextProvider"; +import Interpolate from "./src/interpolate"; +import loadNamespaces from "./src/loadNamespaces"; +import Trans from "./src/trans"; +import translate from "./src/translate"; -// 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 { + I18nextProvider, + Interpolate, + loadNamespaces, + Trans, + translate, + // Exports for TypeScript only + 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 | undefined; -} - -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: (React.ComponentClass | React.StatelessComponent)[], i18n: I18next.I18n }): Promise; - -export as namespace ReactI18Next; +export as namespace reactI18Next; diff --git a/types/react-i18next/src/I18nextProvider.d.ts b/types/react-i18next/src/I18nextProvider.d.ts new file mode 100644 index 0000000000..2ecb87f4a1 --- /dev/null +++ b/types/react-i18next/src/I18nextProvider.d.ts @@ -0,0 +1,12 @@ +import * as React from "react"; +import { i18n } from "i18next"; + +// tslint:disable-next-line:interface-name +export interface I18nextProviderProps { + i18n: i18n; + children: React.ReactElement; + initialI18nStore?: any; + initialLanguage?: string; +} + +export default class I18nextProvider extends React.Component { } diff --git a/types/react-i18next/src/interpolate.d.ts b/types/react-i18next/src/interpolate.d.ts new file mode 100644 index 0000000000..e6f07893ed --- /dev/null +++ b/types/react-i18next/src/interpolate.d.ts @@ -0,0 +1,23 @@ +import * as React from "react"; +import { InterpolationOptions } from "i18next"; + +export type InterpolateValue = string | JSX.Element; + +export interface InterpolatePropsBase { + parent?: string; + regexp?: RegExp; + useDangerouslySetInnerHTML?: boolean; + dangerouslySetInnerHTMLPartElement?: string; + options?: InterpolationOptions; + i18nKey?: string; + className?: string; + style?: React.CSSProperties; +} + +export interface OtherInterpolateProps { + [regexKey: string]: InterpolateValue | RegExp | InterpolationOptions | boolean | undefined; +} + +export type InterpolateProps = InterpolatePropsBase & OtherInterpolateProps; + +export default class Interpolate extends React.Component { } diff --git a/types/react-i18next/src/loadNamespaces.d.ts b/types/react-i18next/src/loadNamespaces.d.ts new file mode 100644 index 0000000000..d0e0b372f5 --- /dev/null +++ b/types/react-i18next/src/loadNamespaces.d.ts @@ -0,0 +1,9 @@ +import * as React from "react"; +import { i18n } from "i18next"; + +export interface LoadNamespacesArguments { + components: Array | React.StatelessComponent>; + i18n: i18n; +} + +export default function loadNamespaces(args: LoadNamespacesArguments): Promise; diff --git a/types/react-i18next/src/trans.d.ts b/types/react-i18next/src/trans.d.ts new file mode 100644 index 0000000000..384e1605f9 --- /dev/null +++ b/types/react-i18next/src/trans.d.ts @@ -0,0 +1,8 @@ +import * as React from "react"; + +export interface TransProps { + i18nKey?: string; + [name: string]: any; +} + +export default class Trans extends React.Component { } diff --git a/types/react-i18next/src/translate.d.ts b/types/react-i18next/src/translate.d.ts new file mode 100644 index 0000000000..d41b4dc00a --- /dev/null +++ b/types/react-i18next/src/translate.d.ts @@ -0,0 +1,15 @@ +import * as React from "react"; +import { i18n } from "i18next"; + +export interface TranslateOptions { + withRef?: boolean; + bindI18n?: string; + bindStore?: string; + translateFuncName?: string; + wait?: boolean; + nsMode?: string; + i18n?: i18n; +} + +// tslint:disable-next-line:ban-types +export default function translate(namespaces?: TKey[] | TKey, options?: TranslateOptions): (WrappedComponent: C) => C; diff --git a/types/react-i18next/test/react-i18next-tests.tsx b/types/react-i18next/test/react-i18next-tests.tsx new file mode 100644 index 0000000000..6105ccf921 --- /dev/null +++ b/types/react-i18next/test/react-i18next-tests.tsx @@ -0,0 +1,92 @@ +import * as React from 'react'; +import * as i18n from 'i18next'; +import { translate, I18nextProvider, Interpolate, InjectedTranslateProps, TranslationFunction, loadNamespaces, Trans } from 'react-i18next'; + +interface InnerAnotherComponentProps { + _?: TranslationFunction; +} + +class InnerAnotherComponent extends React.Component { + render() { + const _ = this.props._!; + return

{_('content.text', { /* options t options */ })}

; + } +} + +const AnotherComponent = translate('view', { wait: true, translateFuncName: '_' })(InnerAnotherComponent); + +class InnerYetAnotherComponent extends React.Component { + render() { + const t = this.props.t!; + return

{t('usingDefaultNS', { /* options t options */ })}

; + } +} + +const YetAnotherComponent = translate()(InnerYetAnotherComponent); + +@translate(['view', 'nav'], { wait: true }) +class TranslatableView extends React.Component { + render() { + const t = this.props.t!; + const interpolateComponent = "a interpolated component"; + + return ( +
+

{t('common:appName')}

+ + + + + {t('nav:link1')} +
+ ); + } +} + +class App extends React.Component { + render() { + return ( +
+
+ +
+
+ ); + } +} + + + +; + +loadNamespaces({ components: [App], i18n }).then(() => { }).catch(error => { }); + +; +; + + +; + +type Key = "view" | "nav"; + +@translate(['view', 'nav']) +class GenericsTest extends React.Component { + render() { return null; } +} + +@translate('view') +class GenericsTest2 extends React.Component { + render() { return null; } +} diff --git a/types/react-i18next/tsconfig.json b/types/react-i18next/tsconfig.json index 4c473240eb..9228cf2075 100644 --- a/types/react-i18next/tsconfig.json +++ b/types/react-i18next/tsconfig.json @@ -13,11 +13,6 @@ "../" ], "types": [], - "paths": { - "i18next": [ - "i18next/v2" - ] - }, "noEmit": true, "forceConsistentCasingInFileNames": true, "jsx": "react", @@ -25,6 +20,11 @@ }, "files": [ "index.d.ts", - "react-i18next-tests.tsx" + "test/react-i18next-tests.tsx", + "src/I18nextProvider.d.ts", + "src/interpolate.d.ts", + "src/loadNamespaces.d.ts", + "src/trans.d.ts", + "src/translate.d.ts" ] } diff --git a/types/react-i18next/tslint.json b/types/react-i18next/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-i18next/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-i18next/v1/index.d.ts b/types/react-i18next/v1/index.d.ts new file mode 100644 index 0000000000..cf56874445 --- /dev/null +++ b/types/react-i18next/v1/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 +// TypeScript Version: 2.3 + +import * as I18next from "i18next"; +import * as React from "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 | undefined; +} + +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: (React.ComponentClass | React.StatelessComponent)[], i18n: I18next.I18n }): Promise; + +export as namespace ReactI18Next; diff --git a/types/react-i18next/react-i18next-tests.tsx b/types/react-i18next/v1/react-i18next-tests.tsx similarity index 100% rename from types/react-i18next/react-i18next-tests.tsx rename to types/react-i18next/v1/react-i18next-tests.tsx diff --git a/types/react-i18next/v1/tsconfig.json b/types/react-i18next/v1/tsconfig.json new file mode 100644 index 0000000000..d58a88810b --- /dev/null +++ b/types/react-i18next/v1/tsconfig.json @@ -0,0 +1,33 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "react-i18next": [ + "react-i18next/v1" + ], + "i18next": [ + "i18next/v2" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "experimentalDecorators": true + }, + "files": [ + "index.d.ts", + "react-i18next-tests.tsx" + ] +} From 65cb0f9e93a83fc9e888b6af900aee5785c2b496 Mon Sep 17 00:00:00 2001 From: ckddbs Date: Tue, 18 Jul 2017 02:56:06 +0900 Subject: [PATCH 0073/1139] Added FBXLoader (#17967) --- types/three/index.d.ts | 1 + types/three/three-fbxloader.d.ts | 14 ++++++++++++++ 2 files changed, 15 insertions(+) create mode 100644 types/three/three-fbxloader.d.ts diff --git a/types/three/index.d.ts b/types/three/index.d.ts index afe64c399e..f9dcc7a762 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -14,6 +14,7 @@ export * from "./three-ddsloader"; export * from "./three-editorcontrols"; export * from "./three-effectcomposer"; export * from "./three-examples"; +export * from "./three-fbxloader"; export * from "./three-FirstPersonControls"; export * from "./three-maskpass"; export * from "./three-mtlloader"; diff --git a/types/three/three-fbxloader.d.ts b/types/three/three-fbxloader.d.ts new file mode 100644 index 0000000000..7a77ea67f5 --- /dev/null +++ b/types/three/three-fbxloader.d.ts @@ -0,0 +1,14 @@ +// https://github.com/mrdoob/three.js/blob/master/examples/js/loaders/FBXLoader.js + +import {LoadingManager} from "./three-core"; +import {Group} from "./three-core"; + +export class FBXLoader { + + constructor(manager?: LoadingManager); + manager: LoadingManager; + + load(url: string, onLoad: (group: Group) => void, onProgress?: (event: ProgressEvent) => void, onError?: (event: ErrorEvent) => void): void; + parse(FBXText: string, resourceDirectory: string) : Group; + +} \ No newline at end of file From bd2b2731b114822ee06573332fe4820709fd9da3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn?= Date: Mon, 17 Jul 2017 19:56:26 +0200 Subject: [PATCH 0074/1139] Update archiver to 2.0 and define options argument (#17968) --- types/archiver/archiver-tests.ts | 26 ++++++++++++++-- types/archiver/index.d.ts | 52 +++++++++++++++++++------------- 2 files changed, 54 insertions(+), 24 deletions(-) diff --git a/types/archiver/archiver-tests.ts b/types/archiver/archiver-tests.ts index d4ea423a4f..bbbc7c7abf 100644 --- a/types/archiver/archiver-tests.ts +++ b/types/archiver/archiver-tests.ts @@ -1,6 +1,26 @@ import * as Archiver from 'archiver'; import * as fs from 'fs'; +const options: Archiver.ArchiverOptions = { + statConcurrency: 1, + allowHalfOpen: true, + readableObjectMode: true, + writeableObjectMode: true, + decodeStrings: true, + encoding: 'test', + highWaterMark: 1, + objectmode: true, + comment: 'test', + forceLocalTime: true, + forceZip64: true, + store: true, + zlib: {}, + gzip: true, + gzipOptions: {}, +}; + +Archiver('zip', options); + const archiver = Archiver.create('zip'); const writeStream = fs.createWriteStream('./archiver.d.ts'); @@ -14,8 +34,6 @@ archiver.append(readStream, { name: 'archiver.d.ts' }); archiver.append(readStream, {name: 'archiver.d.ts'}) .append(readStream, {name: 'archiver.d.ts'}); -archiver.bulk({ mappaing: {} }); - archiver.directory('./path', './someOtherPath'); archiver.directory('./path', { name: "testName" }); archiver.directory('./', "", {}); @@ -38,4 +56,6 @@ archiver.setModule(() => {}); archiver.pointer(); archiver.use(() => {}); -archiver.finalize(); +archiver.finalize().then(); + +archiver.symlink('./path', './target'); diff --git a/types/archiver/index.d.ts b/types/archiver/index.d.ts index 0dc91ec554..a8c7de0502 100644 --- a/types/archiver/index.d.ts +++ b/types/archiver/index.d.ts @@ -1,22 +1,11 @@ -// Type definitions for archiver 1.3 +// Type definitions for archiver 2.0 // Project: https://github.com/archiverjs/node-archiver -// Definitions by: Esri , Dolan Miu +// Definitions by: Esri , Dolan Miu , Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/* =================== USAGE =================== - - import Archiver = require('archiver); - var archiver = Archiver.create('zip'); - archiver.pipe(fs.createWriteStream('xxx')); - archiver.append(fs.createReadStream('xxx')); - archiver.finalize(); - - =============================================== */ - -/// - import * as stream from 'stream'; import * as glob from 'glob'; +import { ZlibOptions } from 'zlib'; declare function archiver(format: archiver.Format, options?: archiver.ArchiverOptions): archiver.Archiver; @@ -36,27 +25,48 @@ declare namespace archiver { abort(): this; append(source: stream.Readable | Buffer | string, name?: EntryData): this; - bulk(mappings: any): this; - directory(dirpath: string, options: EntryData | string, data?: EntryData): this; file(filename: string, data: EntryData): this; glob(pattern: string, options?: glob.IOptions, data?: EntryData): this; - finalize(): this; + finalize(): Promise; setFormat(format: string): this; setModule(module: Function): this; pointer(): number; use(plugin: Function): this; + + symlink(filepath: string, target: string): this; } - interface ArchiverOptions { + type ArchiverOptions = CoreOptions & TransformOptions & ZipOptions & TarOptions; + + interface CoreOptions { + statConcurrency?: number; + } + + interface TransformOptions { + allowHalfOpen?: boolean; + readableObjectMode?: boolean; + writeableObjectMode?: boolean; + decodeStrings?: boolean; + encoding?: string; + highWaterMark?: number; + objectmode?: boolean; + } + + interface ZipOptions { + comment?: string; + forceLocalTime?: boolean; + forceZip64?: boolean; store?: boolean; + zlib?: ZlibOptions; + } + + interface TarOptions { gzip?: boolean; - gzipOptions?: { - level: number, - }; + gzipOptions?: ZlibOptions; } } From fc32c1990c3bc4afcb1d6bde1c530af612ae9a49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juli=C3=ABn=20Hanssens?= Date: Mon, 17 Jul 2017 19:57:21 +0200 Subject: [PATCH 0075/1139] [highcharts] Implemented changes from v4.2.x => v5.0.10 (#17970) * Implemented specs from Highcharts v5.0.0 Conform changelog at https://www.highcharts.com/documentation/changelog, implemented the following changes: - Added styled mode for optional separation of SVG and CSS. - Added responsive option set. - Added accessibility option set. - Added new function, Chart.update in order to update the chart options after render time. - Added new function, Chart.addCredits. - Added new function, Chart.title.update. - Added new function, Chart.credits.update. - Added new function, Legend.update. - Added new option, Renderer.definition. - Added new option, exporting.error for catching errors in offline exporting. - Added new option, exporting.libURL for use with offline exporting. - Added new option, pane.background.className. - Added new option, xAxis.className. - Added new option, xAxis.crosshair.className. - Added new option, plotOptions.series.dataLabels.className. - Added new option, plotOptions.series.className for styling individual series. - Added new option, xAxis.plotBands.className. - Added new option, xAxis.plotLines.className. - Added new option, plotOptions.series.zones.className. - Added new option, chart.colorCount for use in styled mode. - Added new option, defs for defining reusable elements in styled mode. - Added new option, tooltip.padding. - Added new option, series.data.colorIndex for coloring points in styled mode. - Added new option, tooltip.split. - Added new option, chart.description for use with the accessibility module. - Added new option, chart.typeDescription for use with the accessibility module. - Added new option, xAxis.description for use with the accessibility module. - Added new option, plotOptions.series.description for use with the accessibility module. - Refactored build system to use ES6 imports and node-based build script. - Changed all default colors (except series data colors) to a simplified color scheme based on just a few shared colors. Additional improvements (found throughout the documentation): - Changed reference from `color?: string` to `color?: Color` throughout the different Options objects (this broke Typescript intellisense before) - ChartObject.xAxis now accepts also a single AxisObject, as well as Array - ChartObject.yAxis now accepts also a single AxisObject, as well as Array - Important: a handful changes already implemented by community contributors are left alone * Implemented specs from Highcharts 5.0.1 (2016-10-26) Conform changelog at https://www.highcharts.com/documentation/changelog, implemented the following changes: - Added new options, axis.softMin and axis.softMax. No further documentation linked on the following subjects/changes (= ignored): - Added Legend keyboard navigation to the accessibility module. - Added animation on hovering point markers. - Added offline PDF export support. * Implemented Highcharts 5.0.3 (2016-11-18) - Added new option, lang.numericSymbolMagnitude, to support numeric symbol shortening in Japanese, Korean and certain Chinese locales. - Added new option, threshold, for solid gauge series. - Added new CSS custom property, textOutline, and at the same time removed the textShadow shim. Closes #5849. Ignored due to being implementation-only, or lack of documentation: - Better implementation of the chart.pinchType option. Allow pinchType and zoomType to be set independently. When tooltip.followTouchMove is true, pinchType only applies to two-finger touches. Closes #5840. - Changed the Highcharts.addEvent function to return a callback to be used to remove the same event. - Implemented bubbles in the Boost module. - Improved alignment of ticks on multiple axes by allowing ticks to be placed at less strict intervals. - Refactored split tooltip connectors to use common callback shape instead. * Highcharts 5.0.7 (2017-01-17) - Added new option, global.timezone, as a convenient shortcut to timezones defined with moment.js. - Changed the Highcharts.error function to handle strings. Ignored due to being implementation-only, or lack of documentation: - Added Legend keyboard navigation to accessibility module. - Added chart render and predraw events needed by the new Boost module. - Added optional redraw to drillToNode, related to #6180. - Added support for marker.symbol setting on bubble charts. - Changed the Highcharts.addEvent function to return a callback to be used to remove the same event. * Highcharts 5.0.8 (2017-03-08) Conform changelog at https://www.highcharts.com/documentation/changelog, implemented the following changes: - Added animation on graph mouse over and mouse out. - Added new option, solidgauge.rounded. - Added support for relative chart.height as a percentage of the width. This allows for fixed aspect ratio. Ignored due to being implementation-only, or lack of documentation: - Added a refactored Boost module based on WebGL. Details and API to be announced. - Added hooks so that users can define their own log axis conversion functions, and can advertise that the log axis should allow negative values. * Highcharts 5.0.10 (2017-03-31) Conform changelog at https://www.highcharts.com/documentation/changelog, implemented the following changes: - Added new option, plotOptions.column.crisp, to allow disabling crisp columns and subsequent rendering issues with densely packed items. Closes #5755. - Added new option, findNearestPointBy to declare how the tooltip searches for points. #6231. Ignored due to being implementation-only, or lack of documentation: - Added !default statement to SASS variables for easier configuration. Closes #6436. - Refactored the Pane object to keep track of its own backgrounds, more decoupled from Axis. * Fixed dtslint warnings and errors for CI This fixes all tslint/dtslint errors, incl. historic errors. #vanity - Fixed: Array type using 'Array' is forbidden for simple types. Use 'T[]' instead. - Fixed: Exceeds maximum line length of 200 - Fixed: trailing whitespace - Fixed: missing semicolon - Fixed: Consecutive blank lines are forbidden - Fixed: non-arrow functions are forbidden - Fixed: missing whitespace - Fixed: Don't leave a blank line before/after '{' / '}' - Fixed: Do not use 'var' --- types/highcharts/index.d.ts | 465 ++++++++++++++++++++++++++++++-- types/highcharts/test/index.ts | 466 ++++++++++++++++++++++++++++++++- 2 files changed, 891 insertions(+), 40 deletions(-) diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 2bdc1b648d..4a252c899f 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -1,6 +1,9 @@ -// Type definitions for Highcharts 4.2 +// Type definitions for Highcharts 5.0.10 // Project: http://www.highcharts.com/ -// Definitions by: Damiano Gambarotto , Dan Lewi Harkestad , Albert Ozimek +// Definitions by: Damiano Gambarotto +// Dan Lewi Harkestad +// Albert Ozimek +// Juliën Hanssens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -238,6 +241,11 @@ declare namespace Highcharts { } interface PlotBands { + /** + * A custom class name, in addition to the default highcharts-plot-band, to apply to each individual band. + * @since 5.0.0 + */ + className?: string; /** * Border color for the plot band. Also requires borderWidth to be set. * @default null @@ -315,6 +323,11 @@ declare namespace Highcharts { * on one of the axes. */ interface PlotLines { + /** + * A custom class name, in addition to the default highcharts-plot-line, to apply to each individual line. + * @since 5.0.0 + */ + className?: string; /** * The color of the line. */ @@ -357,6 +370,104 @@ declare namespace Highcharts { zIndex?: number; } + /** + * Options for configuring accessibility for the chart. Requires the accessibility module to be loaded. + * For a description of the module and information on its features, see Highcharts Accessibility. + */ + interface AccessibilityOptions { + /** + * Whether or not to add series descriptions to charts with a single series. Defaults to false. + * @since 5.0.0 + */ + describeSingleSeries?: boolean; + + /** + * Enable accessibility features for the chart. + * @since 5.0.0 + * @default true + */ + enabled?: boolean; + + /** + * Options for keyboard navigation. + * @since 5.0.0 + */ + keyboardNavigation?: KeyboardNavigationOptions; + + /** + * Function to run upon clicking the "View as Data Table" link in the screen reader region. + * By default Highcharts will insert and set focus to a data table representation of the chart. + * @since 5.0.0 + */ + onTableAnchorClick?: Function; + + /** + * Date format to use for points on datetime axes when describing them to screen reader users. + * Defaults to the same format as in tooltip. + * For an overview of the replacement codes, see dateFormat. + * @since 5.0.0 + */ + pointDateFormat?: string; + + /** + * Formatter function to determine the date/time format used with points on datetime axes when describing them + * to screen reader users. Receives one argument, point, referring to the point to describe. + * Should return a date format string compatible with dateFormat. + * @since 5.0.0 + */ + pointDateFormatter?: Function; + + /** + * Formatter function to use instead of the default for point descriptions. Receives one argument, point, referring to the point to describe. + * Should return a String with the description of the point for a screen reader user. + * @since 5.0.0 + */ + pointDescriptionFormatter?: Function; + + /** + * When a series contains more points than this, we no longer expose information about individual points to screen readers. + * Set to false to disable. + * @since 5.0.0 + * @default 30 + */ + pointDescriptionThreshold?: number | boolean; + + /** + * A formatter function to create the HTML contents of the hidden screen reader information region. Receives one argument, chart, referring to the chart object. + * Should return a String with the HTML content of the region. + * @since 5.0.0 + * @default undefined + */ + screenReaderSectionFormatter?: Function; + + /** + * Formatter function to use instead of the default for series descriptions. Receives one argument, series, referring to the series to describe. + * Should return a String with the description of the series for a screen reader user. + * @since 5.0.0 + */ + seriesDescriptionFormatter?: Function; + } + + /** + * Options for keyboard navigation (accessibility.keyboardNavigation). + * @since 5.0.0 + */ + interface KeyboardNavigationOptions { + /** + * Enable keyboard navigation for the chart. + * @since 5.0.0 + * @default true + */ + enabled?: boolean; + + /** + * Skip null points when navigating through points with the keyboard. + * @since 5.0.0 + * @default false + */ + skipNullPoints?: boolean; + } + interface AxisTitle { /** * Alignment of the title relative to the axis values. Possible values are 'low', 'middle' or 'high'. @@ -470,6 +581,11 @@ declare namespace Highcharts { * @since 4.0 */ ceiling?: number; + /** + * A class name that opens for styling the axis by CSS, especially in Highcharts styled mode. The class name is applied to group elements for the grid, axis elements and labels. + * @since 5.0.0 + */ + className?: string; /** * Configure a crosshair that follows either the mouse pointer or the hovered point. */ @@ -479,6 +595,12 @@ declare namespace Highcharts { * string representations used for each unit. For an overview of the replacement codes, see dateFormat. */ dateTimeLabelFormats?: DateTimeFormats; + /** + * Description of the axis to screen reader users. + * @since 5.0.0 + * @default undefined + */ + description?: string; /** * Whether to force the axis to end on a tick. Use this option with the maxPadding option to control the axis end. * @default false @@ -728,6 +850,18 @@ declare namespace Highcharts { * @default true */ showLastLabel?: boolean; + /** + * A soft maximum for the axis. If the series data maximum is less than this, the axis will stay at this maximum, + * but if the series data maximum is higher, the axis will flex to show all data. + * @since 5.0.1 + */ + softMax?: number; + /** + * A soft minimum for the axis. If the series data minimum is greater than this, the axis will stay at this minimum, + * but if the series data minimum is lower, the axis will flex to show all data. + * @since 5.0.1 + */ + softMin?: number; /** * Show the total value for each bar in a stacked column or bar chart. * The label will be placed on top of positive columns and below negative columns. @@ -1605,21 +1739,36 @@ declare namespace Highcharts { * A CSS class name to apply to the charts container div, allowing unique CSS styling for each chart. */ className?: string; + /** + * In styled mode, this sets how many colors the class names should rotate between. With ten colors, + * series (or points) are given class names like highcharts-color-0, highcharts-color-0 [...] highcharts-color-9. + * The equivalent in non-styled mode is to set colors using the colors setting. + * @since 5.0.0 + * @default 10 + */ + colorCount?: number; /** * Alias of type. Defaults to line. * @default 'line' * @deprecated */ defaultSeriesType?: string; + /** + * + */ + description?: string; /** * Event listeners for the chart. */ events?: ChartEvents; /** - * An explicit height for the chart. By default the height is calculated from the offset height of the containing - * element, or 400 pixels if the containing element's height is 0. + * An explicit height for the chart. If a number, the height is given in pixels. If given a percentage string (for example '56%'), + * the height is given as the percentage of the actual chart width. This allows for preserving the aspect ratio across responsive sizes. + * By default (when null) the height is calculated from the offset height of the containing element, or 400 pixels if the containing element's height is 0. + * @default null + * @since 5.0.8 */ - height?: number; + height?: number | string; /** * If true, the axes will scale to the remaining visible series once one series is hidden. If false, hiding and * showing a series will not affect the axes or the other series. For stacks, once one series within the stack is @@ -1806,6 +1955,14 @@ declare namespace Highcharts { * @since 2.1.0 */ type?: string; + /** + * A text description of the chart type. + * If the Accessibility module is loaded, this will be included in the description of the chart in the screen reader information region. + * Highcharts will by default attempt to guess the chart type, but for more complex charts it is recommended to specify this property for clarity. + * @since 5.0.0 + * @default undefined + */ + typeDescription?: string; /** * An explicit width for the chart. By default the width is calculated from the offset width of the containing * element. @@ -1831,7 +1988,7 @@ declare namespace Highcharts { padding?: string | number; position?: string; top?: string; - textShadow?: string; + textOutline?: string; } interface CreditsOptions { @@ -1860,6 +2017,10 @@ declare namespace Highcharts { text?: string; } + interface CreditsObject extends CreditsOptions { + update(options: CreditsOptions): void; + } + interface DataSeriesMapping { [pointPropertyName: string]: number; } @@ -2347,6 +2508,14 @@ declare namespace Highcharts { * @since 4.1.0 */ getTimezoneOffset?(timestamp: number): number; + /** + * Requires moment.js. If the timezone option is specified, it creates a default getTimezoneOffset function that + * looks up the specified timezone in moment.js. If moment.js is not included, this throws a Highcharts error in + * the console, but does not crash the chart. + * @default undefined + * @since 5.0.7 + */ + timezone?: string; /** * The timezone offset in minutes. Positive values are west, negative values are east of UTC, as in the ECMAScript * getTimezoneOffset method. Use this to display UTC based data in a predefined time zone. @@ -2441,6 +2610,13 @@ declare namespace Highcharts { * @since 3.0.8 */ noData?: string; + /** + * The magnitude of numericSymbols replacements. + * Use 10000 for Japanese, Korean and various Chinese locales, which use symbols for 10^4, 10^8 and 10^12. + * @since 5.0.3 + * @default 1000 + */ + numericSymbolMagnitude?: number; /** * Metric prefixes used to shorten high numbers in axis labels. Replacing any of the positions with null causes the * full number to be written. Setting numericSymbols to null disables shortening altogether. @@ -2851,6 +3027,12 @@ declare namespace Highcharts { * @default 1 */ borderWidth?: number; + /** + * The class name for this background. + * @since 5.0.0 + * @default 'highcharts-pane' + */ + className?: string; /** * @default 0 */ @@ -2901,6 +3083,90 @@ declare namespace Highcharts { startAngle?: number; } + /** + * Allows setting a set of rules to apply for different screen or chart sizes. + * Each rule specifies additional chart options. + * @since 5.0.0 + */ + interface ResponsiveOptions { + /** + * A set of rules for responsive settings. The rules are executed from the top down. + * @since 5.0.0 + */ + rules?: RulesOptions[]; + } + + /** + * A set of rules for responsive settings. The rules are executed from the top down. + */ + interface RulesOptions { + /** + * A full set of chart options to apply as overrides to the general chart options. + * The chart options are applied when the given rule is active. + * + * A special case is configuration objects that take arrays, for example xAxis, yAxis or series. + * For these collections, an id option is used to map the new option set to an existing object. + * If an existing object of the same id is not found, the item of the same indexupdated. + * So for example, setting chartOptions with two series items without an id, will cause the existing + * chart's two series to be updated with respective options. + * @since 5.0.0 + */ + chartOptions?: ChartOptions; + + /** + * Under which conditions the rule applies. + * @since 5.0.0 + */ + condition?: ConditionOptions; + } + + interface TitleObject extends TitleOptions { + /** + * Update method that points back to Chart.setTitle. + * @since 5.0.0 + */ + update(options: TitleOptions): void; + } + + /** + * Under which conditions the rule applies. + */ + interface ConditionOptions { + /** + * A callback function to gain complete control on when the responsive rule applies. Return true if it applies. + * This opens for checking against other metrics than the chart size, or example the document size or other elements. + * The this keyword refers to the Chart object. + * @since 5.0.0 + */ + callback?: Function; + + /** + * The responsive rule applies if the chart height is less than this. + * @since 5.0.0 + */ + maxHeight?: number; + + /** + * The responsive rule applies if the chart height is less than this. + * @since 5.0.0 + */ + maxWidth?: number; + + /** + * The responsive rule applies if the chart height is greater than this. + * @since 5.0.0 + * @default 0 + */ + minHeight?: number; + + /** + * The responsive rule applies if the chart width is greater than this. + * @since 5.0.0 + * @default 0 + */ + minWidth?: number; + } + interface DataLabels { /** * The alignment of the data label compared to the point. If right, the right side of the label should be touching @@ -3354,6 +3620,12 @@ declare namespace Highcharts { } interface LineStates { + /** + * Animation setting for hovering the graph in line-type series. + * @default { "duration": 50 } + * @since 5.0.8 + */ + animation?: boolean | Animation; /** * Enable separate styles for the hovered series to visualize that the user hovers either the series itself or the * legend. @@ -3415,6 +3687,11 @@ declare namespace Highcharts { interface PieStates extends BarStates, LineStates { } interface AreaZone { + /** + * Styled mode only. A custom class name for the zone. + * @since 5.0.0 + */ + className?: string; /** * Defines the color of the series. * @since 4.1.0 @@ -3753,6 +4030,11 @@ declare namespace Highcharts { * @default true */ animation?: boolean | Animation; + /** + * A class name to apply to the series' graphical elements. + * @since 5.0.0 + */ + className?: string; /** * The main color or the series. In line type series it applies to the line and the point markers unless otherwise * specified. In bar type series it applies to the bars unless a color is specified per point. The default value is @@ -3810,6 +4092,15 @@ declare namespace Highcharts { */ enableMouseTracking?: boolean; events?: PlotEvents; + /** + * Determines whether the series should look for the nearest point in both dimensions or just the x-dimension when + * hovering the series. Defaults to 'xy' for scatter series and 'x' for most other series. If the data has duplicate + * x-values, it is recommended to set this to 'xy' to allow hovering over all points. + * + * Applies only to series types using nearest neighbor search (not direct hover) for tooltip. + * @since 5.0.10 + */ + findNearestPointBy?: string; /** * Whether to use the Y extremes of the total chart width or only the zoomed area when zooming in on parts of the X * axis. By default, the Y axis adjusts to the min and max of the visible data. Cartesian series only. @@ -4064,11 +4355,10 @@ declare namespace Highcharts { */ colorByPoint?: boolean; /** - * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is - * true. + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is true. * @since 3.0 */ - colors?: string[]; + colors?: Color[]; /** * Depth of the columns in a 3D column chart. Requires highcharts-3d.js. * @default 25 @@ -4286,11 +4576,10 @@ declare namespace Highcharts { */ colorByPoint?: boolean; /** - * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is - * true. + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is true. * @since 3.0 */ - colors?: string[]; + colors?: Color[]; /** * Depth of the columns in a 3D column chart. Requires highcharts-3d.js. * @default 25 @@ -4423,7 +4712,7 @@ declare namespace Highcharts { * A series specific or series type specific color set to use instead of the global colors. * @since 3.0 */ - colors?: string[]; + colors?: Color[]; dataLabels?: PieDataLabels; /** * The thickness of a 3D pie. Requires highcharts-3d.js @@ -4547,11 +4836,10 @@ declare namespace Highcharts { */ colorByPoint?: boolean; /** - * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is - * true. + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is true. * @since 3.0 */ - colors?: string[]; + colors?: Color[]; /** * The columns size - how many X axis units each column in the heatmap should span. * @default 1 @@ -4626,10 +4914,10 @@ declare namespace Highcharts { */ center?: [string | number, string | number]; /** - * A series specific or series type specific color set to use instead of the global colors. + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is true. * @since 3.0 */ - colors?: string[]; + colors?: Color[]; dataLabels?: PieDataLabels; /** * The thickness of a 3D pie. Requires highcharts-3d.js @@ -4730,10 +5018,10 @@ declare namespace Highcharts { */ center?: [string | number, string | number]; /** - * A series specific or series type specific color set to use instead of the global colors. + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is true. * @since 3.0 */ - colors?: string[]; + colors?: Color[]; dataLabels?: PieDataLabels; /** * The thickness of a 3D pie. Requires highcharts-3d.js @@ -4798,6 +5086,18 @@ declare namespace Highcharts { * @since 3.0.10 */ overshoot?: number; + /** + * Wether to draw rounded edges on the gauge. + * @default false + * @since 5.0.8 + */ + rounded?: boolean; + /** + * The threshold or base level for the gauge. + * @default null + * @since 5.0.3 + */ + threshold?: number; /** * When this option is true, the dial will wrap around the axes. For instance, in a full-range gauge going from 0 to * 360, a value of 400 will point to 40. When wrap is false, the dial stops at 360. @@ -4845,11 +5145,10 @@ declare namespace Highcharts { */ colorByPoint?: boolean; /** - * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is - * true. + * A series specific or series type specific color set to apply instead of the global colors when colorByPoint is true. * @since 3.0 */ - colors?: string[]; + colors?: Color[]; /** * This option decides if the user can interact with the parent nodes or just the leaf nodes. When this option is * undefined, it will be true by default. However when allowDrillToNode is true, then it will be false by default. @@ -4926,11 +5225,11 @@ declare namespace Highcharts { * @default '#333333' * @since 3.0 */ - lineColor?: string | Gradient; + lineColor?: Color; /** * The color used specifically for positive point columns. When not specified, the general series color is used. */ - upColor?: string; + upColor?: Color; } /** @@ -4978,6 +5277,20 @@ declare namespace Highcharts { * value is pulled from the options.colors array. */ color?: string | Gradient; + /** + * Styled mode only. A specific color index to use for the point, so its graphic representations are given the class name highcharts-color-{n}. + * @since 5.0.0 + */ + colorIndex?: number; + /** + * When true, each column edge is rounded to its nearest pixel in order to render sharp on screen. + * In some cases, when there are a lot of densely packed columns, this leads to visible difference + * in column widths or distance between columns. In these cases, setting crisp to false may look + * better, even though each column is rendered blurry. + * @default true + * @since 5.0.10 + */ + crisp?: boolean; /** * You can set the cursor to "pointer" if you have click events attached to the series, to signal to the user * that the points and lines can be clicked. @@ -5014,6 +5327,13 @@ declare namespace Highcharts { * }] */ data?: Array; + /** + * A description of the series to add to the screen reader information about the series. + * @since 5.0.0 + * @default undefined + */ + description?: string; + /** * An id for the series. This can be used after render time to get a pointer to the series object through * chart.get(). @@ -5316,10 +5636,33 @@ declare namespace Highcharts { } interface CrosshairObject { + /** + * A class name for the crosshair, especially as a hook for styling. + * @since 5.0.0 + */ + className?: string; + /** + * The color of the crosshair. Defaults to #cccccc for numeric and datetime axes, and rgba(204,214,235,0.25) for category axes, + * where the crosshair by default highlights the whole category. + * @since 4.1 + */ color?: string | Gradient; - width?: number; + /** + * The dash style for the crosshair. See series.dashStyle for possible values. Defaults to Solid. + * @since 4.1 + */ dashStyle?: string; // Solid ShortDash ShortDot ShortDashDot ShortDashDotDot Dot Dash LongDash DashDot LongDashDot LongDashDotDot + /** + * The Z index of the crosshair. Higher Z indices allow drawing the crosshair on top of the series or behind the grid lines. + * @since 4.1 + * @default 2 + */ zIndex?: number; + /** + * The pixel width of the crosshair. Defaults to 1 for numeric or datetime axes, and for one category width for category axes. + * @since 4.1 + */ + width?: number; } interface PlotPoint { @@ -5406,6 +5749,12 @@ declare namespace Highcharts { * The y value. */ formatter?(): boolean | string; + /** + * Padding inside the tooltip, in pixels. + * @since 5.0.0 + * @default 8 + */ + padding?: number; /** * A callback function to place the tooltip in a default position. The callback receives three parameters: * labelWidth, labelHeight and point, where point contains values for plotX and plotY telling where the reference @@ -5442,6 +5791,14 @@ declare namespace Highcharts { * @since 1.2.0 */ snap?: number; + /** + * Split the tooltip into one label per series, with the header close to the axis. + * This is recommended over shared tooltips for charts with multiple line series, + * generally making them easier to read. + * @since 5.0.0 + * @default false + */ + split?: boolean; /** * CSS styles for the tooltip. The tooltip can also be styled through the CSS class .highcharts-tooltip * @default { color: '#333333', fontSize: '12px', padding: '8px' } @@ -5542,6 +5899,12 @@ declare namespace Highcharts { } interface Options { + /** + * Options for configuring accessibility for the chart. Requires the accessibility module to be loaded. + * For a description of the module and information on its features, see Highcharts Accessibility. + * @since 5.0.0 + */ + accessibility?: AccessibilityOptions; /** * Options regarding the chart area and plot area as well as general chart options. */ @@ -5555,7 +5918,7 @@ declare namespace Highcharts { * * @default ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c', '#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'] */ - colors?: string[]; + colors?: Color[]; /** * Highchart by default puts a credits label in the lower right corner of the chart. This can be changed using these options. */ @@ -5570,6 +5933,11 @@ declare namespace Highcharts { * series.data option. */ data?: DataOptions; + /** + * Styled mode only. Configuration object for adding SVG definitions for reusable elements. + * See gradients, shadows and patterns for more information and code examples. + */ + defs?: any; // TODO: Unknown API interface, see also http://api.highcharts.com/highcharts/defs /** * Options for drill down, the concept of inspecting increasingly high resolution data through clicking on chart * items like columns or pie slices. @@ -5621,6 +5989,11 @@ declare namespace Highcharts { * that type, for example plotOptions.line. Next, options for one single series are given in the series array. */ plotOptions?: PlotOptions; + /** + * Allows setting a set of rules to apply for different screen or chart sizes. Each rule specifies additional chart options. + * @since 5.0.0 + */ + responsive?: ResponsiveOptions[]; /** * The actual series to append to the chart. In addition to the members listed below, any member of the plotOptions * for that specific type of plot can be added to a series individually. For example, even though a general @@ -5798,6 +6171,12 @@ declare namespace Highcharts { * @since 3.0 */ addAxis(options: AxisOptions, isX?: boolean, redraw?: boolean, animation?: boolean | Animation): AxisObject; + /** + * Set a new credits label for the chart. + * @param A configuration object for the credits as defined at credits. + * @since 5.0.0 + */ + addCredits(options: CreditsOptions): void; /** * Add a series to the chart after render time. Note that this method should never be used when adding data * synchronously at chart render time, as it adds expense to the calculations and rendering. When adding data at the @@ -5821,6 +6200,11 @@ declare namespace Highcharts { * @since 1.2.5 */ container: HTMLElement; + /** + * The chart's credits label. The label has an update method that allows setting new options as per the credits option set. + * + */ + credits: CreditsObject; /** * Removes the chart and purges memory. This method should be called before writing a new chart into the same * container. It is called internally on window unload to prevent leaks. @@ -5973,6 +6357,16 @@ declare namespace Highcharts { * @since 2.0.5 */ showLoading(str?: string): void; + /** + * The chart subtitle. The subtitle has an update method that allows modifying the options. + * @since 5.0.0 + */ + subtitle: TitleObject; + /** + * The chart title. The title has an update method that points back to Chart.setTitle. + * @since 5.0.0 + */ + title: TitleObject; /** * A generic function to update any element of the chart. Elements can be enabled and disabled, moved, re-styled, * re-formatted etc. @@ -6150,6 +6544,14 @@ declare namespace Highcharts { * @since 2.0 */ circle(centerX: number, centerY: number, radius: number): ElementObject; + /** + * Styled mode only. A hook for adding general definitions to the SVG's defs tag. Definitions can be referenced from + * the CSS by its id. Read more in Gradients, shadows and patterns. + * The definitions can also be added as configuration options, see defs. + * @param {def} A serialized form of an SVG definition, including children. + * @since 5.0.0 + */ + definition(def: object): Highcharts.ElementObject; /** * Add an SVG/VML group. * @param [string] name The name of the group. This will be used in the class name, which will be 'highcharts-'+ name. @@ -6259,6 +6661,15 @@ declare namespace Highcharts { * of the date. */ dateFormats: DateFormatSpecifiers; + /** + * The error handler function. By default is provides error messages for debugging, with links to the descriptions on Highcharts website. + * This function can be redefined to catch errors in client applications. + * @param {code} Number|String The error code. If this is a number, the default error function prints a link to a human readable error code + * description according to error definition file. If it's a string, the description is printed in the console. + * @param {fatal} Whether the error should stop execution. + * @since 5.0.6 + */ + error(code: number | string, fatal: boolean): Function; /** * Formats a JavaScript number with grouped thousands, a fixed amount of decimals and an optional decimal point. It * is a port of PHP's function with the same name. See PHP number_format for a full explanation of the parameters. diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index 622ebfa8be..5ddc56420c 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -33,7 +33,7 @@ function originalTests() { ] }; - const color = "#fcfcff"; + const color: Highcharts.Color = "#fcfcff"; const chart1 = new Highcharts.Chart({ chart: { @@ -42,6 +42,7 @@ function originalTests() { xAxis: {}, series: [ { data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], + description: "foo", type: "line", allowPointSelect: true }] @@ -49,11 +50,10 @@ function originalTests() { chart1.addSeries({ enableMouseTracking: true, - data: [1, 2, 3, 4, 5] + data: [1, 2, 3, 4, 5], + description: "some description" }); - console.log(( chart1.series[0].options).dashStyle); - const chart2 = new Highcharts.Chart({ chart: { renderTo: 'container', @@ -61,24 +61,26 @@ function originalTests() { height: 400, spacingRight: 20 }, - xAxis: [{ - type: 'logarithmic', + xAxis: [ { + description: 'x-foo', min: 1, max: 1000, endOnTick: true, tickInterval: 1, minorTickInterval: 0.1, - gridLineWidth: 1 + gridLineWidth: 1, + type: 'logarithmic' }], - yAxis: [{ - type: 'logarithmic', + yAxis: [ { + description: 'y-foo', min: 1, max: 1000, tickInterval: 1, minorTickInterval: 0.1, title: { text: null - } + }, + type: 'logarithmic' }], legend: { enabled: false @@ -230,7 +232,9 @@ function test_ChartOptions() { borderRadius: 20, borderWidth: 5, className: "class", + colorCount: 42, defaultSeriesType: "deprecated", + description: "an arbitrary description", events: { addSeries: () => { }, afterPrint: () => { }, @@ -314,6 +318,7 @@ function test_ChartOptions() { spacingTop: 5, style: {}, type: "spline", + typeDescription: "load accessibility module to read this", width: 100, zoomType: "x" }; @@ -520,6 +525,22 @@ function test_ChartOptions() { }] }); + // typedescription example + $('#container').highcharts({ + chart: { + borderColor: '#EBBA95', + borderRadius: 20, + borderWidth: 2, + type: 'line' + }, + xAxis: { + categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + }, + series: [{ + data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] + }] + }); + // zoom&pan example $('#container').highcharts({ chart: { @@ -573,6 +594,58 @@ function test_ChartOptions() { data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] }); + + // tooltip split example (incl. padding) + $('#container').highcharts({ + chart: { + type: 'spline' + }, + + title: { + text: 'Mountain house indoor temperatures' + }, + + subtitle: { + text: 'Split tooltips in Highcharts makes it easier to read overlapping line series' + }, + + tooltip: { + valueSuffix: '°C', + split: true, + padding: 5 + }, + + xAxis: { + }, + + yAxis: { + }, + + plotOptions: { + series: { + lineWidth: 1.5, + marker: { + radius: 2 + } + } + }, + + data: { + columns: [ + ["Time", 1451616120000, 1451865660000, 1451952060000, 1452038400000, 1452124800000, 1452211200000, + 1452297600000, 1452384000000, 1452470400000, 1452556800000, 1452643200000, 1452729600000, 1452816000000, + 1452902400000, 1452988800000, 1453075200000, 1453161600000, 1453248000000, 1453334400000, 1453420800000, + 1453507200000, 1453593600000, 1453680000000, 1453766400000, 1453852800000, 1453939200000, 1454025600000], + ["Kitchen", 5, 4, 5, 9, 6, 15, 19, 14, 6, 5, 6, 6, 15, 18, 15, 6, 6, 6, 6, 6, 6, 6, 16, 10, 6, 6, 6], + ["Living room", 9, 10, 16, 13, 6, 20, 24, 16, 7, 7, 6, 6, 20, 23, 18, 9, 7, 6, 6, 7, 6, 21, 20, 16, 6, 6, 6], + ["Hall", 7, 7, 13, 12, 5, 17, 22, 14, 4, 5, 5, 6, 18, 21, 17, 9, 5, 6, 5, 6, 6, 18, 20, 14, 5, 5, 5], + ["Bathroom", 7, 7, 13, 12, 5, 17, 22, 14, 4, 5, 5, 6, 18, 21, 17, 9, 5, 6, 5, 6, 6, 18, 20, 14, 5, 5, 5], + ["Bedroom 1", 6, 19, 19, 10, 5, 15, 21, 14, 6, 6, 5, 5, 17, 21, 16, 6, 5, 5, 5, 5, 5, 17, 18, 13, 5, 5, 5], + ["Bedroom 2", 7, 19, 19, 9, 5, 11, 19, 15, 6, 5, 6, 6, 16, 19, 17, 8, 9, 6, 5, 6, 5, 17, 19, 14, 6, 6, 6], + ["Shed", 6, 6, 5, 5, 6, 6, 6, 5, 5, 6, 6, 5, 6, 6, 6, 6, 6, 6, null, null, 6, 6, 6, 6, 6, 6, 6] + ] + } + }); } function test_CreditsOptions() { @@ -876,7 +949,11 @@ function test_Exporting() { series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }], - exporting: { + exporting: { + error: () => { + console.log('succesfully asserted exporting.error'); + }, + libURL: 'https://code.highcharts.com/{version}/lib', sourceWidth: 400, sourceHeight: 200, scale: 2, @@ -1366,6 +1443,32 @@ function test_Column() { // same options as bar chart } +function test_ColumnCrispFalse() { + // conform example: http://jsfiddle.net/gh/get/jquery/3.1.1/highslide-software/highcharts.com/tree/master/samples/highcharts/plotoptions/column-crisp-false/ + const numbers = () => { + let arr = []; + for (let i = 0; i < 100; i++) { + arr.push(i); + } + return arr; + }; + const chart = new Highcharts.Chart( { + title: { + text: 'Crisp columns are disabled' + }, + + subtitle: { + text: 'Resulting in blurry, but evenly spaced columns' + }, + + series: [{ + data: numbers(), + type: 'column', + crisp: false + }] + }); +} + function test_ColumnRange() { const allDefaults: Highcharts.ColumnRangeChartSeriesOptions = {}; @@ -1423,6 +1526,57 @@ function test_ErrorBar() { }); } +function test_FindNearestPointBy() { + // conform example: http://jsfiddle.net/gh/get/library/pure/highslide-software/highcharts.com/tree/master/samples/highcharts/series/findnearestpointby/ + const chart = new Highcharts.Chart({ + title: { + text: 'The top series snaps hover along X axis' + }, + + plotOptions: { + line: { + marker: { + enabled: true + } + } + }, + + series: [ { + findNearestPointBy: 'x', + // Hover at [3.5, 6] to demo x-dimension search + // Compare to Series 2 behavior at [5.5, 3] + data: [ + [0, 6], + [1, 6], + [1, 7], + [2, 6], + [3, 6], + [3.5, 4], + [4, 6], + [5, 6], + [6, 6], + [7, 6] + ] + }, { + findNearestPointBy: 'xy', + // Hover at [1, 4] to demo xy-dimension search. + // Useful when having multiple points on the same x-value. + data: [ + [0, 3], + [1, 3], + [1, 4], + [2, 3], + [3, 3], + [4, 3], + [5, 3], + [5.5, 5.5], + [6, 3], + [7, 3] + ] + }] + }); +} + function test_Funnel() { const allDefaults: Highcharts.FunnelChartSeriesOptions = {}; @@ -1693,7 +1847,7 @@ function test_Pie() { style: { fontWeight: 'bold', color: 'white', - textShadow: '0px 1px 2px black' + textOutline: '0px 1px 2px black' } }, startAngle: -90, @@ -1966,13 +2120,94 @@ function test_Waterfall() { style: { color: '#FFFFFF', fontWeight: 'bold', - textShadow: '0px 0px 3px black' + textOutline: '0px 0px 3px black' } }, pointPadding: 0 }; } +function test_AccessibilityOptions() { + const accessibilityOptions: Highcharts.AccessibilityOptions = { + describeSingleSeries: true, + enabled: true, + keyboardNavigation: { + enabled: true, + skipNullPoints: true + }, + onTableAnchorClick: () => { }, + pointDateFormat: 'dd-MM-yyyy', + pointDateFormatter: () => { }, + pointDescriptionFormatter: () => { }, + pointDescriptionThreshold: false, + screenReaderSectionFormatter: () => { }, + seriesDescriptionFormatter: () => { } + }; + + const chart = new Highcharts.Chart( { + accessibility: accessibilityOptions + }); +} + +function test_AddAndUpdateCredits() { + // example based on: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/credits/credits-update/ + let chart = new Highcharts.Chart({ + title: { + text: 'Credits update' + }, + + credits: { + enabled: false + }, + + xAxis: { + categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + }, + + series: [{ + data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] + }] + }); + + chart.addCredits({ + enabled: true + }); + + chart.credits.update({ + enabled: false + }); + + if (chart.credits) { + chart.credits.update({ + text: 'MyFancyCompany', + href: 'http://www.example.com', + position: { + align: 'left', + x: 10 + }, + style: { + fontSize: '2em', + color: 'blue' + } + }); + } + + if (chart.credits) { + chart.credits.update({ + text: 'Highcharts.com', + href: 'http://www.highcharts.com', + position: { + align: 'right', + x: -10 + }, + style: { + color: '#909090', + fontSize: '9px' + } + }); + } +} + function test_AxisOptions() { const allDefaults: Highcharts.AxisOptions = {}; @@ -1987,6 +2222,7 @@ function test_AxisOptions() { }], categories: ['A', 'B'], ceiling: 100, + className: 'highcharts-axis', dateTimeLabelFormats: { millisecond: "ms format" }, @@ -2099,6 +2335,8 @@ function test_AxisOptions() { showEmpty: false, showFirstLabel: true, showLastLabel: true, + softMax: 2, + softMin: 1, startOfWeek: 1, startOnTick: false, tickAmount: 10, @@ -2253,6 +2491,50 @@ function test_ElementObject() { group.toFront(); } +function test_NumericSymbolMagnitude() { + // conform example: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/lang/numericsymbolmagnitude/ + + let chart = new Highcharts.Chart({ + title: { + text: 'Numeric symbols magnitude' + }, + + subtitle: { + text: 'Japanese uses ten thousands (万) as numeric symbol' + }, + + xAxis: { + categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + }, + + series: [{ + data: [2990, 7150, 10640, 12920, 14400, 17600, + 13560, 14850, 21640, 19410, 9560, 5440], + type: 'column' + }] + }); + + chart.update( { + lang: { + numericSymbols: ['万', '億'], + numericSymbolMagnitude: 10000 + } + }); +} + +function test_PaneBackground() { + const pane = { + backgroundColor: 'blue', + borderColor: 'white', + borderWidth: 5, + className: 'good', + innerRadius: 10, + outerRadius: '110%', + shape: 'circle' + }; +} + function test_PointObject() { const point = $('#container').highcharts().get('point1'); const category = point.category; @@ -2286,6 +2568,7 @@ function test_RendererObject() { const renderer = $('#container').highcharts().renderer; renderer.arc(0, 0, 20, 10, 0, Math.PI); renderer.circle(0, 0, 100); + renderer.definition( {}); renderer.g('groupName'); renderer.image('http://source', 20, 20, 100, 100); renderer.label('Label', 200, 100, 'rect', 0, 0, false, false, 'class'); @@ -2294,6 +2577,29 @@ function test_RendererObject() { renderer.text('text', 10, 10); } +function test_ResponsiveOptions() { + const responsiveOptions: Highcharts.ResponsiveOptions = { + rules: [ + { + chartOptions: { + description: 'just a test' + }, + condition: { + callback: () => { }, + maxHeight: 420, + maxWidth: 420, + minHeight: 420, + minWidth: 420 + } + } + ] + }; + + const chart = new Highcharts.Chart( { + responsive: responsiveOptions + }); +} + function test_SeriesObject() { const series = $('#container').highcharts().get('series1'); series.addPoint(0); @@ -2340,3 +2646,137 @@ function test_LegendObject() { legend.update({}); legend.update({}, false); } + +function test_SeriesDataLabel() { + $('#container').highcharts({ + title: { + text: 'Styling data labels by CSS' + }, + + xAxis: { + categories: ['Jan', 'Feb', 'Mar', 'Apr'] + }, + + plotOptions: { + series: { + dataLabels: { + enabled: true, + borderRadius: 2, + y: -10, + shape: 'callout' + } + } + }, + + series: [{ + data: [100, 300, { + y: 500, + dataLabels: { + className: 'highlight' + } + }, 400] + }] + }); +} + +function test_SoftMinSoftMax() { + // conform example: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/yaxis/softmin-softmax/ + let chart: Highcharts.ChartObject = new Highcharts.Chart({ + title: { + text: 'Y axis softMax is 100' + }, + + subtitle: { + text: 'Click the button to change data max' + }, + + xAxis: { + categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + }, + + yAxis: { + softMax: 100, + title: { + text: 'Percentage' + } + }, + + series: [{ + data: [0, 1, 0, 2, 3, 5, 8, 5, 15, 14, 25, 54] + }] + }); + + let toggle = false; + chart.series[0].data[11].update((toggle = (!toggle)) ? 120 : 54); +} + +function test_StyledColorZones() { + $('#container').highcharts({ + title: { + text: 'Styled color zones' + }, + + yAxis: { + min: -10 + }, + + plotOptions: { + series: { + zones: [{ + value: 0, + className: 'zone-0' + }, { + value: 10, + className: 'zone-1' + }, { + className: 'zone-2' + }], + threshold: -10 + } + }, + + series: [{ + type: 'areaspline', + data: [-10, -5, 0, 5, 10, 15, 10, 10, 5, 0, -5] + }, { + type: 'column', + data: [1, 13, 2, -4, 6, 7, 5, 3, 2, -1, 2] + }] + }); +} + +function test_TitleUpdate() { + // conform example: http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/members/title-update/ + let i = 1; + + let chart = new Highcharts.Chart({ + subtitle: { + text: 'Subtitle' + }, + + xAxis: { + categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] + }, + + series: [{ + data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] + }] + }); + + chart.title.update({ text: 'New title ' + i }); + i += 1; + + chart.subtitle.update({ text: 'New title ' + i }); + i += 1; + + chart.title.update({ + style: { + color: 'red' + } + }); + chart.subtitle.update({ + style: { + color: 'green' + } + }); +} From cc8a3b49b42b6a859c28b8c9c12f904dab946bfe Mon Sep 17 00:00:00 2001 From: Shai Reznik Date: Mon, 17 Jul 2017 20:57:58 +0300 Subject: [PATCH 0076/1139] add optional done func to jasmine-given (#17971) --- types/jasmine-given/index.d.ts | 10 +++---- types/jasmine-given/jasmine-given-tests.ts | 32 +++++++++++++++++++++- 2 files changed, 36 insertions(+), 6 deletions(-) diff --git a/types/jasmine-given/index.d.ts b/types/jasmine-given/index.d.ts index 70a23d7e07..28338d7664 100644 --- a/types/jasmine-given/index.d.ts +++ b/types/jasmine-given/index.d.ts @@ -3,8 +3,8 @@ // Definitions by: Shai Reznik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function Given(func: () => void): void; -declare function When(func: () => void): void; -declare function Then(func: () => void): void; -declare function And(func: () => void): void; -declare function Invariant(func: () => void): void; +declare function Given(func: (done?: () => void) => void): void; +declare function When(func: (done?: () => void) => void): void; +declare function Then(func: (done?: () => void) => void): void; +declare function And(func: (done?: () => void) => void): void; +declare function Invariant(func: (done?: () => void) => void): void; diff --git a/types/jasmine-given/jasmine-given-tests.ts b/types/jasmine-given/jasmine-given-tests.ts index 8a994ecbbe..e9603e3aaf 100644 --- a/types/jasmine-given/jasmine-given-tests.ts +++ b/types/jasmine-given/jasmine-given-tests.ts @@ -6,4 +6,34 @@ Then(() => { }); And(() => { }); -Invariant(() => {}); +Invariant(() => { }); + +Given((done) => { + if (done) { + done(); + } +}); + +When((done) => { + if (done) { + done(); + } +}); + +Then((done) => { + if (done) { + done(); + } +}); + +And((done) => { + if (done) { + done(); + } +}); + +Invariant((done) => { + if (done) { + done(); + } +}); From 3a37a444808c9f2a11c3d15db4f7143e9a006f3b Mon Sep 17 00:00:00 2001 From: Panagiotis Rikarnto Siavelis Date: Mon, 17 Jul 2017 20:58:31 +0300 Subject: [PATCH 0077/1139] notifyjs - adding missing `requireInteraction` option (#17972) --- types/notifyjs/index.d.ts | 8 +++++++- types/notifyjs/notifyjs-tests.ts | 3 ++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/types/notifyjs/index.d.ts b/types/notifyjs/index.d.ts index 7e072688fc..e31753b69e 100644 --- a/types/notifyjs/index.d.ts +++ b/types/notifyjs/index.d.ts @@ -107,6 +107,12 @@ declare namespace notifyjs { /** * callback when user has denied permission */ - permissionDenied? : Function; + permissionDenied?: Function; + + /** + * whether we expect for user interaction or not + * in case value is true the timeout for closing the notification won't be set + */ + requireInteraction?: boolean; } } diff --git a/types/notifyjs/notifyjs-tests.ts b/types/notifyjs/notifyjs-tests.ts index 236209967c..4eb6890d77 100644 --- a/types/notifyjs/notifyjs-tests.ts +++ b/types/notifyjs/notifyjs-tests.ts @@ -20,7 +20,8 @@ function test_Notify_constructor() { notifyClick : ()=> console.log("notifyClick"), notifyError : ()=> console.log("notifyError"), permissionGranted : ()=> console.log("permissionGranted"), - permissionDenied : ()=> console.log("permissionDenied") + permissionDenied : ()=> console.log("permissionDenied"), + requireInteraction:true }); n.show(); From d6e51049558981c0cc3e468072d39cafde54af87 Mon Sep 17 00:00:00 2001 From: Michal Blaha Date: Mon, 17 Jul 2017 19:58:56 +0200 Subject: [PATCH 0078/1139] [seneca] Update Options.log definition (#17976) --- types/seneca/index.d.ts | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/types/seneca/index.d.ts b/types/seneca/index.d.ts index b03e1b4bf5..0ee6928b57 100644 --- a/types/seneca/index.d.ts +++ b/types/seneca/index.d.ts @@ -108,7 +108,8 @@ declare module "seneca" { }, // zig module settings for seneca.start() chaining. zig?: any; - log?: { + log?: LogSpec | { + level?: LogLevel; short?: boolean; }; errhandler?: GlobalErrorHandler; @@ -119,6 +120,21 @@ declare module "seneca" { //cmd?: string; } + type LogSpec = + 'quiet' | // { level: 'none' } + 'silent' | // { level: 'none' } + 'any' | // { level: 'debug+' } + 'all' | // { level: 'debug+' } + 'print' | // { level: 'debug+' } + 'standard' | // { level: 'info+' } + 'test' // { level: 'warn+' } + + type LogLevel = + 'none' | + 'debug+' | + 'info+' | + 'warn+' + interface Optioner { set: (input: string | Options) => Options; get: () => Options; From ee5246d60ac0bcdec1b63b0932d0c8a7bb4cd6f5 Mon Sep 17 00:00:00 2001 From: Denise Mauldin Date: Mon, 17 Jul 2017 10:59:41 -0700 Subject: [PATCH 0079/1139] Added searchPlaceholder to datatables.net (#17986) --- types/datatables.net/datatables.net-tests.ts | 2 ++ types/datatables.net/index.d.ts | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/types/datatables.net/datatables.net-tests.ts b/types/datatables.net/datatables.net-tests.ts index 8ec7ecb084..f4e322dcfc 100644 --- a/types/datatables.net/datatables.net-tests.ts +++ b/types/datatables.net/datatables.net-tests.ts @@ -12,6 +12,7 @@ $(document).ready(function () { "loadingRecords": "Loading...", "processing": "Processing...", "search": "Search:", + "searchPlaceholder": "Default text", "zeroRecords": "No matching records found", "paginate": { "first": "First", @@ -413,6 +414,7 @@ $(document).ready(function () { var modifier: DataTables.ObjectSelectorModifier = { order: "current", search: "none", + searchPlaceholder: "Default text", page: "all", }; diff --git a/types/datatables.net/index.d.ts b/types/datatables.net/index.d.ts index 68e26ee048..99a2aae7b8 100644 --- a/types/datatables.net/index.d.ts +++ b/types/datatables.net/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for JQuery DataTables 1.10.9 // Project: http://www.datatables.net -// Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander +// Definitions by: Kiarash Ghiaseddin , Omid Rad , Armin Sander , Denise Mauldin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -145,6 +145,11 @@ declare namespace DataTables { */ search?: string; + /** + * The searchPlaceholder modifier provides the ability to provide informational text for an input control when it has no value. + */ + searchPlaceholder?: string; + /** * The page modifier allows you to control if the selector should consider all data in the table, regardless of paging, or if only the rows in the currently disabled page should be used. * Values: 'all', 'current' @@ -1318,6 +1323,11 @@ declare namespace DataTables { */ search?: SearchSettings; + /** + * Set placeholder attribute for input type="text" tag elements. Since: 1.10 + */ + searchPlaceholder?: SearchSettings; + /** * Define an initial search for individual columns. Since: 1.10 */ @@ -1642,6 +1652,11 @@ declare namespace DataTables { * Set an initial filtering condition on the table. Since: 1.10 */ search?: string; + + /** + * Set a placeholder attribute for input type="text" tag elements. Since: 1.10.1 + */ + searchPlaceholder?: string; } //#endregion "other-settings" @@ -1720,6 +1735,7 @@ declare namespace DataTables { loadingRecords?: string; processing?: string; search?: string; + searchPlaceholder?: string; zeroRecords?: string; paginate?: LanguagePaginateSettings; aria?: LanguageAriaSettings; From 01366d96254cfed1ca5adb68c8e8aed3d48a227e Mon Sep 17 00:00:00 2001 From: Silas Rech Date: Mon, 17 Jul 2017 20:01:20 +0200 Subject: [PATCH 0080/1139] Add timing properties (#18000) --- types/request/index.d.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index 7ae56c10d4..3a861d6b6f 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -178,6 +178,22 @@ declare namespace request { export interface RequestResponse extends http.IncomingMessage { request: Options; body: any; + timingStart?: number; + timings?: { + socket: number; + lookup: number; + connect: number; + response: number; + end: number; + }; + timingPhases?: { + wait: number; + dns: number; + tcp: number; + firstByte: number; + download: number; + total: number; + }; } export interface HttpArchiveRequest { From 3fe5fe740363b7c9b04713629ef3b85e88c6f581 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?I=C3=B1aki=20Ibarrola=20Atxa?= Date: Mon, 17 Jul 2017 20:04:55 +0200 Subject: [PATCH 0081/1139] Add support for the classes option in Tabs and Dialog (#18015) * Add support for the classes option in Tabs and Dialog. * Add support for the classes option in Tabs and Dialog (Fix spacing). --- types/jqueryui/index.d.ts | 27 +++++++++++++++++++++++++++ types/jqueryui/jqueryui-tests.ts | 2 ++ 2 files changed, 29 insertions(+) diff --git a/types/jqueryui/index.d.ts b/types/jqueryui/index.d.ts index ee4752bb7f..ecb4d4b642 100644 --- a/types/jqueryui/index.d.ts +++ b/types/jqueryui/index.d.ts @@ -353,6 +353,7 @@ declare namespace JQueryUI { autoOpen?: boolean; buttons?: { [buttonText: string]: (event?: Event) => void } | DialogButtonOptions[]; closeOnEscape?: boolean; + classes?: DialogClasses; closeText?: string; appendTo?: string; dialogClass?: string; @@ -376,6 +377,20 @@ declare namespace JQueryUI { open?: DialogEvent; close?: DialogEvent; } + + interface DialogClasses { + "ui-dialog"?: string; + "ui-dialog-content"?: string; + "ui-dialog-dragging"?: string; + "ui-dialog-resizing"?: string; + "ui-dialog-buttons"?: string; + "ui-dialog-titlebar"?: string; + "ui-dialog-title"?: string; + "ui-dialog-titlebar-close"?: string; + "ui-dialog-buttonpane"?: string; + "ui-dialog-buttonset"?: string; + "ui-widget-overlay"?: string; + } interface DialogButtonOptions { icons?: any; @@ -802,6 +817,7 @@ declare namespace JQueryUI { interface TabsOptions extends TabsEvents { active?: any; // boolean or number + classes?: TabClasses; collapsible?: boolean; disabled?: any; // boolean or [] event?: string; @@ -810,6 +826,17 @@ declare namespace JQueryUI { show?: any; // boolean, number, string or object } + interface TabClasses { + "ui-tabs"?: string; + "ui-tabs-collapsible"?: string; + "ui-tabs-nav"?: string; + "ui-tabs-tab"?: string; + "ui-tabs-active"?: string; + "ui-tabs-loading"?: string; + "ui-tabs-anchor"?: string; + "ui-tabs-panel"?: string; + } + interface TabsActivationUIParams { newTab: JQuery; oldTab: JQuery; diff --git a/types/jqueryui/jqueryui-tests.ts b/types/jqueryui/jqueryui-tests.ts index 93384f576e..c2067574cd 100644 --- a/types/jqueryui/jqueryui-tests.ts +++ b/types/jqueryui/jqueryui-tests.ts @@ -1432,6 +1432,7 @@ function test_dialog() { $(".selector").dialog({ autoOpen: false }); $(".selector").dialog({ buttons: { Ok: function () { $(this).dialog("close"); } } }); $(".selector").dialog({ buttons: [ { text: "Ok", click: function () { $(this).dialog("close"); } } ] } ); + $(".selector").dialog({ classes: { "ui-dialog": "custom", "ui-dialog-content": "custom-content" } } ); $(".selector").dialog({ closeOnEscape: false }); $(".selector").dialog({ closeText: "hide" }); $(".selector").dialog({ appendTo: "appendTo" }); @@ -1712,6 +1713,7 @@ function test_tabs() { $("#tabs").tabs().addClass("ui-tabs-vertical ui-helper-clearfix"); $("#tabs li").removeClass("ui-corner-top").addClass("ui-corner-left"); $(".selector").tabs({ active: 1 }); + $(".selector").tabs({ classes: { "ui-tabs": "custom", "ui-tabs-panel": "custom-panel" } } ); $(".selector").tabs({ collapsible: true }); $(".selector").tabs({ disabled: [0, 2] }); $(".selector").tabs({ event: "mouseover" }); From 40e971e511afb76e0d808a47198efde512bba1b8 Mon Sep 17 00:00:00 2001 From: Max Winderbaum Date: Mon, 17 Jul 2017 11:06:58 -0700 Subject: [PATCH 0082/1139] Remove duplicate 'time' identifier in @types/request (#18077) --- types/request/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index 3a861d6b6f..bfa3901933 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -154,7 +154,6 @@ declare namespace request { ca?: string | Buffer | string[] | Buffer[]; har?: HttpArchiveRequest; useQuerystring?: boolean; - time?: boolean; } interface UriOptions { From d00caf8115ee4df76ffe6a80d5289c6805c1b82c Mon Sep 17 00:00:00 2001 From: cjbarth Date: Mon, 17 Jul 2017 14:11:28 -0400 Subject: [PATCH 0083/1139] REQUEST: Add version number for correct version of @types npm package (#18026) * Add version number for correct version of @types npm package * Remove duplicate property --- types/request/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/request/index.d.ts b/types/request/index.d.ts index bfa3901933..2e65c85253 100644 --- a/types/request/index.d.ts +++ b/types/request/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for request +// Type definitions for request 2.0 // Project: https://github.com/request/request // Definitions by: Carlos Ballesteros Velasco , bonnici , Bart van der Schoor , Joe Skeen , Christopher Currens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 2b52c98aeaeeb46bb2f5906672463562a3119287 Mon Sep 17 00:00:00 2001 From: Ika Date: Tue, 18 Jul 2017 02:12:12 +0800 Subject: [PATCH 0084/1139] feat(jest): add types for implementing custom interfaces (#18034) * refactor(jest): enable tslint * feat(jest): use global-modifying-module format * feat(jest): add types for implementing custom interfaces * fix(jest): should use interface instead of class, since it does not exist in jest environment * docs(jest): fix typo * revert: feat(jest): use global-modifying-module format This reverts commit 99f7db4eac4530423f9de99f0553dbbc5043fc1d. * docs(jest): fix typo * feat(jest): update TS version to 2.2 * fix(jest): flow's Maybe type --- types/jest/index.d.ts | 871 +++++++++++++++++++++++++++++++++------ types/jest/jest-tests.ts | 219 +++++----- types/jest/tslint.json | 1 + 3 files changed, 855 insertions(+), 236 deletions(-) create mode 100644 types/jest/tslint.json diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index ee7e25a9de..633af80085 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -1,8 +1,14 @@ -// Type definitions for Jest 20.0.5 +// Type definitions for Jest 20.0 // Project: http://facebook.github.io/jest/ -// Definitions by: Asana , Ivo Stratev , jwbay , Alexey Svetliakov , Alex Jover Morales , Allan Lukwago +// Definitions by: Asana +// Ivo Stratev +// jwbay +// Alexey Svetliakov +// Alex Jover Morales +// Allan Lukwago +// Ika // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 declare var beforeAll: jest.Lifecycle; declare var beforeEach: jest.Lifecycle; @@ -20,94 +26,160 @@ declare var xtest: jest.It; declare const expect: jest.Expect; interface NodeRequire { - /** Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. */ + /** + * 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. */ + /** + * 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 { - /** Provides a way to add Jasmine-compatible matchers into your Jest context. */ + /** + * Provides a way to add Jasmine-compatible matchers into your Jest context. + */ function addMatchers(matchers: jasmine.CustomMatcherFactories): typeof jest; - /** Disables automatic mocking in the module loader. */ + /** + * Disables automatic mocking in the module loader. + */ function autoMockOff(): typeof jest; - /** Enables automatic mocking in the module loader. */ + /** + * Enables automatic mocking in the module loader. + */ function autoMockOn(): typeof jest; /** * @deprecated use resetAllMocks instead */ function clearAllMocks(): typeof jest; - /** Clears the mock.calls and mock.instances properties of all mocks. Equivalent to calling .mockClear() on every mocked function. */ + /** + * Clears the mock.calls and mock.instances properties of all mocks. + * Equivalent to calling .mockClear() on every mocked function. + */ function resetAllMocks(): typeof jest; - /** 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. */ + /** + * 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(): typeof jest; - /** Indicates that the module system should never return a mocked version of the specified module, including all of the specificied module's dependencies. */ + /** + * 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): typeof jest; - /** Disables automatic mocking in the module loader. */ + /** + * Disables automatic mocking in the module loader. + */ function disableAutomock(): typeof jest; - /** Mocks a module with an auto-mocked version when it is being required. */ + /** + * Mocks a module with an auto-mocked version when it is being required. + */ function doMock(moduleName: string): typeof jest; - /** 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). */ + /** + * 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): typeof jest; - /** Enables automatic mocking in the module loader. */ + /** + * Enables automatic mocking in the module loader. + */ function enableAutomock(): typeof jest; - /** Creates a mock function. Optionally takes a mock implementation. */ + /** + * Creates a mock function. Optionally takes a mock implementation. + */ function fn(implementation: (...args: any[]) => T): Mock; - function fn(implementation?: Function): Mock; - /** Use the automatic mocking system to generate a mocked version of the given module. */ + function fn(implementation?: (...args: any[]) => any): 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. */ + /** + * 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. */ + /** + * Mocks a module with an auto-mocked version when it is being required. + */ function mock(moduleName: string, factory?: any, options?: MockOptions): typeof jest; - /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + /** + * 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(): typeof jest; - /** Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. */ + /** + * 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(): typeof jest; - /** Exhausts tasks queued by setImmediate(). */ + /** + * Exhausts tasks queued by setImmediate(). + */ function runAllImmediates(): typeof jest; - /** Exhausts the micro-task queue (usually interfaced in node via process.nextTick). */ + /** + * Exhausts the micro-task queue (usually interfaced in node via process.nextTick). + */ function runAllTicks(): typeof jest; - /** Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). */ + /** + * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout() and setInterval()). + */ function runAllTimers(): typeof jest; - /** 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. */ + /** + * 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(): typeof jest; - /** Executes only the macro task queue (i.e. all tasks queued by setTimeout() or setInterval() and setImmediate()). */ + /** + * Executes only the macro task queue (i.e. all tasks queued by setTimeout() + * or setInterval() and setImmediate()). + */ function runTimersToTime(msToRun: number): typeof jest; - /** Explicitly supplies the mock object that the module system should return for the specified module. */ + /** + * Explicitly supplies the mock object that the module system should return + * for the specified module. + */ function setMock(moduleName: string, moduleExports: T): typeof jest; - /** Creates a mock function similar to jest.fn but also tracks calls to object[methodName] */ + /** + * Creates a mock function similar to jest.fn but also tracks calls to object[methodName] + */ function spyOn(object: T, method: M): SpyInstance; - /** 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). */ + /** + * 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): typeof jest; - /** Instructs Jest to use fake versions of the standard timer functions. */ + /** + * Instructs Jest to use fake versions of the standard timer functions. + */ function useFakeTimers(): typeof jest; - /** Instructs Jest to use the real versions of the standard timer functions. */ + /** + * Instructs Jest to use the real versions of the standard timer functions. + */ function useRealTimers(): typeof jest; interface MockOptions { virtual?: boolean; } - interface EmptyFunction { - (): void; - } + type EmptyFunction = () => void; interface DoneCallback { - (...args: any[]): any + (...args: any[]): any; fail(error?: string | { message: string }): any; } - interface ProvidesCallback { - (cb: DoneCallback): any; - } + type ProvidesCallback = (cb: DoneCallback) => any; - interface Lifecycle { - (fn: ProvidesCallback): any; - } + type Lifecycle = (fn: ProvidesCallback) => any; - /** Creates a test closure */ + /** + * Creates a test closure + */ interface It { /** * Creates a test closure. @@ -117,14 +189,16 @@ declare namespace jest { * @param {timeout?} timeout The timeout for an async function test */ (name: string, fn?: ProvidesCallback, timeout?: number): void; - /** Only runs this test in the current file. */ + /** + * Only runs this test in the current file. + */ only: It; skip: It; concurrent: It; } interface Describe { - (name: string, fn: EmptyFunction): void + (name: string, fn: EmptyFunction): void; only: Describe; skip: Describe; } @@ -138,7 +212,9 @@ declare namespace jest { ensureExpectedIsNumber(actual: any, matcherName?: string): void; ensureNoExpected(actual: any, matcherName?: string): void; ensureNumbers(actual: any, expected: any, matcherName?: string): void; - /** get the type of a value with handling of edge cases like `typeof []` and `typeof null` */ + /** + * get the type of a value with handling of edge cases like `typeof []` and `typeof null` + */ getType(value: any): string; matcherHint(matcherName: string, received?: string, expected?: string, options?: { secondArgument?: string, isDirectExpectCall?: boolean }): string; pluralize(word: string, count: number): string; @@ -146,11 +222,11 @@ declare namespace jest { printReceived(value: any): string; printWithType(name: string, received: any, print: (value: any) => string): string; stringify(object: {}, maxDepth?: number): string; - } + }; } interface ExpectExtendMap { - [key: string]: (this: MatcherUtils, received: any, actual: any) => { message: () => string, pass: boolean }; + [key: string]: (this: MatcherUtils, received: any, actual: any) => { message(): string, pass: boolean }; } interface SnapshotSerializerOptions { @@ -162,7 +238,7 @@ declare namespace jest { indent?: number; maxDepth?: number; min?: boolean; - plugins?: Array + plugins?: SnapshotSerializerPlugin[]; printFunctionName?: boolean; theme?: SnapshotSerializerOptionsTheme; @@ -187,108 +263,215 @@ declare namespace jest { value: SnapshotSerializerColor; } interface SnapshotSerializerPlugin { - print(val:any, serialize:((val:any) => string), indent:((str:string) => string), opts:SnapshotSerializerOptions, colors: SnapshotSerializerColors) : string; - test(val:any) : boolean; + print(val: any, serialize: ((val: any) => string), indent: ((str: string) => string), opts: SnapshotSerializerOptions, colors: SnapshotSerializerColors): string; + test(val: any): boolean; } - /** The `expect` function is used every time you want to test a value. You will rarely call `expect` by itself. */ + /** + * The `expect` function is used every time you want to test a value. + * You will rarely call `expect` by itself. + */ interface Expect { /** - * The `expect` function is used every time you want to test a value. You will rarely call `expect` by itself. + * The `expect` function is used every time you want to test a value. + * You will rarely call `expect` by itself. * * @param {any} actual The value to apply matchers against. - */ + */ (actual: any): Matchers; anything(): any; - /** Matches anything that was created with the given constructor. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. */ + /** + * Matches anything that was created with the given constructor. + * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. + */ any(classType: any): any; - /** Matches any array made up entirely of elements in the provided array. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. */ + /** + * Matches any array made up entirely of elements in the provided array. + * You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. + */ arrayContaining(arr: any[]): any; - /** Verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called. */ + /** + * Verifies that a certain number of assertions are called during a test. + * This is often useful when testing asynchronous code, in order to + * make sure that assertions in a callback actually got called. + */ assertions(num: number): void; - /** Verifies that at least one assertion is called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called. */ + /** + * Verifies that at least one assertion is called during a test. + * This is often useful when testing asynchronous code, in order to + * make sure that assertions in a callback actually got called. + */ hasAssertions(): void; - /** You can use `expect.extend` to add your own matchers to Jest. */ + /** + * You can use `expect.extend` to add your own matchers to Jest. + */ extend(obj: ExpectExtendMap): void; - /** Adds a module to format application-specific data structures for serialization. */ - addSnapshotSerializer(serializer: SnapshotSerializerPlugin) : void; - /** Matches any object that recursively matches the provided keys. This is often handy in conjunction with other asymmetric matchers. */ + /** + * Adds a module to format application-specific data structures for serialization. + */ + addSnapshotSerializer(serializer: SnapshotSerializerPlugin): void; + /** + * Matches any object that recursively matches the provided keys. + * This is often handy in conjunction with other asymmetric matchers. + */ objectContaining(obj: {}): any; - /** Matches any string that contains the exact provided string */ + /** + * Matches any string that contains the exact provided string + */ stringMatching(str: string | RegExp): any; } interface Matchers { - /** If you know how to test something, `.not` lets you test its opposite. */ + /** + * If you know how to test something, `.not` lets you test its opposite. + */ not: Matchers; - /** Use resolves to unwrap the value of a fulfilled promise so any other matcher can be chained. If the promise is rejected the assertion fails. */ + /** + * Use resolves to unwrap the value of a fulfilled promise so any other + * matcher can be chained. If the promise is rejected the assertion fails. + */ resolves: Matchers>; - /** Unwraps the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails. */ + /** + * Unwraps the reason of a rejected promise so any other matcher can be chained. + * If the promise is fulfilled the assertion fails. + */ rejects: Matchers>; lastCalledWith(...args: any[]): R; - /** Checks that a value is what you expect. It uses `===` to check strict equality. Don't use `toBe` with floating-point numbers. */ + /** + * Checks that a value is what you expect. It uses `===` to check strict equality. + * Don't use `toBe` with floating-point numbers. + */ toBe(expected: any): R; - /** Ensures that a mock function is called. */ + /** + * Ensures that a mock function is called. + */ toBeCalled(): R; - /** Ensure that a mock function is called with specific arguments. */ + /** + * Ensure that a mock function is called with specific arguments. + */ toBeCalledWith(...args: any[]): R; - /** Using exact equality with floating point numbers is a bad idea. Rounding means that intuitive things fail. */ + /** + * Using exact equality with floating point numbers is a bad idea. + * Rounding means that intuitive things fail. + */ toBeCloseTo(expected: number, delta?: number): R; - /** Ensure that a variable is not undefined. */ + /** + * Ensure that a variable is not undefined. + */ toBeDefined(): R; - /** When you don't care what a value is, you just want to ensure a value is false in a boolean context. */ + /** + * When you don't care what a value is, you just want to + * ensure a value is false in a boolean context. + */ toBeFalsy(): R; - /** For comparing floating point numbers. */ + /** + * For comparing floating point numbers. + */ toBeGreaterThan(expected: number): R; - /** For comparing floating point numbers. */ + /** + * For comparing floating point numbers. + */ toBeGreaterThanOrEqual(expected: number): R; - /** Ensure that an object is an instance of a class. This matcher uses `instanceof` underneath. */ - toBeInstanceOf(expected: any): R - /** For comparing floating point numbers. */ + /** + * Ensure that an object is an instance of a class. + * This matcher uses `instanceof` underneath. + */ + toBeInstanceOf(expected: any): R; + /** + * For comparing floating point numbers. + */ toBeLessThan(expected: number): R; - /** For comparing floating point numbers. */ + /** + * For comparing floating point numbers. + */ toBeLessThanOrEqual(expected: number): R; - /** This is the same as `.toBe(null)` but the error messages are a bit nicer. So use `.toBeNull()` when you want to check that something is null. */ + /** + * This is the same as `.toBe(null)` but the error messages are a bit nicer. + * So use `.toBeNull()` when you want to check that something is null. + */ toBeNull(): R; - /** Use when you don't care what a value is, you just want to ensure a value is true in a boolean context. In JavaScript, there are six falsy values: `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. */ + /** + * Use when you don't care what a value is, you just want to ensure a value + * is true in a boolean context. In JavaScript, there are six falsy values: + * `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. + */ toBeTruthy(): R; - /** Used to check that a variable is undefined. */ + /** + * Used to check that a variable is undefined. + */ toBeUndefined(): R; - /** Used to check that a variable is NaN. */ + /** + * Used to check that a variable is NaN. + */ toBeNaN(): R; - /** Used when you want to check that an item is in a list. For testing the items in the list, this uses `===`, a strict equality check. */ + /** + * Used when you want to check that an item is in a list. + * For testing the items in the list, this uses `===`, a strict equality check. + */ toContain(expected: any): R; - /** Used when you want to check that an item is in a list. For testing the items in the list, this matcher recursively checks the equality of all fields, rather than checking for object identity. */ + /** + * Used when you want to check that an item is in a list. + * For testing the items in the list, this matcher recursively checks the + * equality of all fields, rather than checking for object identity. + */ toContainEqual(expected: any): R; - /** Used when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity. */ + /** + * Used when you want to check that two objects have the same value. + * This matcher recursively checks the equality of all fields, rather than checking for object identity. + */ toEqual(expected: any): R; - /** Ensures that a mock function is called. */ + /** + * Ensures that a mock function is called. + */ toHaveBeenCalled(): R; - /** Ensures that a mock function is called an exact number of times. */ + /** + * Ensures that a mock function is called an exact number of times. + */ toHaveBeenCalledTimes(expected: number): R; - /** Ensure that a mock function is called with specific arguments. */ + /** + * Ensure that a mock function is called with specific arguments. + */ toHaveBeenCalledWith(...params: any[]): R; - /** If you have a mock function, you can use `.toHaveBeenLastCalledWith` to test what arguments it was last called with. */ + /** + * If you have a mock function, you can use `.toHaveBeenLastCalledWith` + * to test what arguments it was last called with. + */ toHaveBeenLastCalledWith(...params: any[]): R; - /** Used to check that an object has a `.length` property and it is set to a certain numeric value. */ + /** + * Used to check that an object has a `.length` property + * and it is set to a certain numeric value. + */ toHaveLength(expected: number): R; toHaveProperty(propertyPath: string, value?: any): R; - /** Check that a string matches a regular expression. */ + /** + * Check that a string matches a regular expression. + */ toMatch(expected: string | RegExp): R; - /** Used to check that a JavaScript object matches a subset of the properties of an object */ + /** + * Used to check that a JavaScript object matches a subset of the properties of an object + */ toMatchObject(expected: {} | any[]): R; - /** This ensures that a value matches the most recent snapshot. Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. */ + /** + * This ensures that a value matches the most recent snapshot. + * Check out [the Snapshot Testing guide](http://facebook.github.io/jest/docs/snapshot-testing.html) for more information. + */ toMatchSnapshot(snapshotName?: string): R; - /** Used to test that a function throws when it is called. */ + /** + * Used to test that a function throws when it is called. + */ toThrow(error?: string | Constructable | RegExp): R; - /** If you want to test that a specific error is thrown inside a function. */ + /** + * If you want to test that a specific error is thrown inside a function. + */ toThrowError(error?: string | Constructable | RegExp): R; - /** Used to test that a function throws a error matching the most recent snapshot when it is called. */ + /** + * Used to test that a function throws a error matching the most recent snapshot when it is called. + */ toThrowErrorMatchingSnapshot(): R; } interface Constructable { - new (...args: any[]): any + new (...args: any[]): any; } interface Mock extends Function, MockInstance { @@ -302,6 +485,7 @@ declare namespace jest { /** * Wrap module with mock definitions + * * @example * jest.mock("../api"); * import { Api } from "../api"; @@ -317,8 +501,8 @@ declare namespace jest { mock: MockContext; mockClear(): void; mockReset(): void; - mockImplementation(fn: Function): Mock; - mockImplementationOnce(fn: Function): Mock; + mockImplementation(fn: (...args: any[]) => any): Mock; + mockImplementationOnce(fn: (...args: any[]) => any): Mock; mockReturnThis(): Mock; mockReturnValue(value: any): Mock; mockReturnValueOnce(value: any): Mock; @@ -330,23 +514,28 @@ declare namespace jest { } } -//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. +// 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. */ +/** + * 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. */ +/** + * Fails a test when called within one. + */ declare function fail(error?: any): void; declare namespace jasmine { - var DEFAULT_TIMEOUT_INTERVAL: number; - var clock: () => Clock; + let DEFAULT_TIMEOUT_INTERVAL: number; + function 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 createSpy(name: string, originalFn?: (...args: any[]) => any): Spy; function createSpyObj(baseName: string, methodNames: any[]): any; function createSpyObj(baseName: string, methodNames: any[]): T; function pp(value: any): string; @@ -357,7 +546,10 @@ declare namespace jasmine { 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. */ + /** + * Calls to any registered callback are triggered when the clock isticked forward + * via the jasmine.clock().tick function, which takes a number of milliseconds. + */ tick(ms: number): void; mockDate(date?: Date): void; } @@ -391,45 +583,93 @@ declare namespace jasmine { } 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * 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. */ + /** + * By chaining the spy with and.callFake, all calls to the spy + * will delegate to the supplied function. + */ + callFake(fn: (...args: any[]) => any): 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. */ + /** + * 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. */ + /** + * 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 */ + /** + * 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 */ + /** + * 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 */ + /** + * 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 */ + /** + * 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 */ + /** + * 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 */ + /** + * 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 */ + /** + * 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 */ + /** + * The context (the this) for the call + */ object: any; - /** All arguments passed to the call */ + /** + * All arguments passed to the call + */ args: any[]; - /** The return value of the call */ + /** + * The return value of the call + */ returnValue: any; } @@ -437,19 +677,15 @@ declare namespace jasmine { [index: string]: CustomMatcherFactory; } - interface CustomMatcherFactory { - (util: MatchersUtil, customEqualityTesters: Array): CustomMatcher; - } + type CustomMatcherFactory = (util: MatchersUtil, customEqualityTesters: CustomEqualityTester[]) => 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; + equals(a: any, b: any, customTesters?: CustomEqualityTester[]): boolean; + contains(haystack: ArrayLike | string, needle: any, customTesters?: CustomEqualityTester[]): boolean; + buildFailureMessage(matcherName: string, isNot: boolean, actual: any, ...expected: any[]): string; } - interface CustomEqualityTester { - (first: any, second: any): boolean; - } + type CustomEqualityTester = (first: any, second: any) => boolean; interface CustomMatcher { compare(actual: T, expected: T): CustomMatcherResult; @@ -466,3 +702,366 @@ declare namespace jasmine { [n: number]: T; } } + +declare namespace jest { + // types for implementing custom interfaces, from https://github.com/facebook/jest/tree/dd6c5c4/types + + // https://facebook.github.io/jest/docs/en/configuration.html#transform-object-string-string + // const transformer: Transformer; + + // https://facebook.github.io/jest/docs/en/configuration.html#reporters-array-modulename-modulename-options + // const reporter: Reporter; + + // https://facebook.github.io/jest/docs/en/configuration.html#testrunner-string + // const testRunner: TestFramework; + + // https://facebook.github.io/jest/docs/en/configuration.html#testresultsprocessor-string + // const testResultsProcessor: TestResultsProcessor; + + // leave above declarations for referening type-dependencies + // .vscode/settings.json: "typescript.referencesCodeLens.enabled": true + + // custom + + // flow's Maybe type https://flow.org/en/docs/types/primitives/#toc-maybe-types + type Maybe = void | null | undefined | T; // tslint:disable-line:void-return + + type TestResultsProcessor = (testResult: AggregatedResult) => AggregatedResult; + + type HasteResolver = any; // import HasteResolver from 'jest-resolve'; + type ModuleMocker = any; // import {ModuleMocker} from 'jest-mock'; + type ModuleMap = any; // import {ModuleMap} from 'jest-haste-map'; + type HasteFS = any; // import {FS as HasteFS} from 'jest-haste-map'; + type Runtime = any; // import Runtime from 'jest-runtime'; + type Script = any; // import {Script} from 'vm'; + + // Config + + type Path = string; + type Glob = string; + + interface HasteConfig { + defaultPlatform?: Maybe; + hasteImplModulePath?: string; + platforms?: string[]; + providesModuleNodeModules: string[]; + } + + type ReporterConfig = [string, object]; + + type ConfigGlobals = object; + + type SnapshotUpdateState = 'all' | 'new' | 'none'; + + interface GlobalConfig { + bail: boolean; + collectCoverage: boolean; + collectCoverageFrom: Glob[]; + collectCoverageOnlyFrom: Maybe<{[key: string]: boolean}>; + coverageDirectory: string; + coverageReporters: string[]; + coverageThreshold: {global: {[key: string]: number}}; + expand: boolean; + forceExit: boolean; + logHeapUsage: boolean; + mapCoverage: boolean; + noStackTrace: boolean; + notify: boolean; + projects: Glob[]; + replname: Maybe; + reporters: ReporterConfig[]; + rootDir: Path; + silent: boolean; + testNamePattern: string; + testPathPattern: string; + testResultsProcessor: Maybe; + updateSnapshot: SnapshotUpdateState; + useStderr: boolean; + verbose: Maybe; + watch: boolean; + watchman: boolean; + } + + interface ProjectConfig { + automock: boolean; + browser: boolean; + cache: boolean; + cacheDirectory: Path; + clearMocks: boolean; + coveragePathIgnorePatterns: string[]; + globals: ConfigGlobals; + haste: HasteConfig; + moduleDirectories: string[]; + moduleFileExtensions: string[]; + moduleLoader: Path; + moduleNameMapper: Array<[string, string]>; + modulePathIgnorePatterns: string[]; + modulePaths: string[]; + name: string; + resetMocks: boolean; + resetModules: boolean; + resolver: Maybe; + rootDir: Path; + roots: Path[]; + setupFiles: Path[]; + setupTestFrameworkScriptFile: Path; + skipNodeResolution: boolean; + snapshotSerializers: Path[]; + testEnvironment: string; + testMatch: Glob[]; + testPathIgnorePatterns: string[]; + testRegex: string; + testRunner: string; + testURL: string; + timers: 'real' | 'fake'; + transform: Array<[string, Path]>; + transformIgnorePatterns: Glob[]; + unmockedModulePathPatterns: Maybe; + } + + // Console + + type LogMessage = string; + interface LogEntry { + message: LogMessage; + origin: string; + type: LogType; + } + type LogType = 'log' | 'info' | 'warn' | 'error'; + type ConsoleBuffer = LogEntry[]; + + // Context + + interface Context { + config: ProjectConfig; + hasteFS: HasteFS; + moduleMap: ModuleMap; + resolver: HasteResolver; + } + + // Environment + + interface FakeTimers { + clearAllTimers(): void; + runAllImmediates(): void; + runAllTicks(): void; + runAllTimers(): void; + runTimersToTime(msToRun: number): void; + runOnlyPendingTimers(): void; + runWithRealTimers(callback: any): void; + useFakeTimers(): void; + useRealTimers(): void; + } + + interface $JestEnvironment { + global: Global; + fakeTimers: FakeTimers; + testFilePath: string; + moduleMocker: ModuleMocker; + + dispose(): void; + runScript(script: Script): any; + } + + type Environment = $JestEnvironment; + + // Global + + type Global = object; + + // Reporter + + interface ReporterOnStartOptions { + estimatedTime: number; + showStatus: boolean; + } + + // TestResult + + interface RawFileCoverage { + path: string; + s: {[statementId: number]: number}; + b: {[branchId: number]: number}; + f: {[functionId: number]: number}; + l: {[lineId: number]: number}; + fnMap: {[functionId: number]: any}; + statementMap: {[statementId: number]: any}; + branchMap: {[branchId: number]: any}; + inputSourceMap?: object; + } + + interface RawCoverage { + [filePath: string]: RawFileCoverage; + } + + interface FileCoverageTotal { + total: number; + covered: number; + skipped: number; + pct?: number; + } + + interface CoverageSummary { + lines: FileCoverageTotal; + statements: FileCoverageTotal; + branches: FileCoverageTotal; + functions: FileCoverageTotal; + } + + interface FileCoverage { + getLineCoverage(): object; + getUncoveredLines(): number[]; + getBranchCoverageByLine(): object; + toJSON(): object; + merge(other: object): void; + computeSimpleTotals(property: string): FileCoverageTotal; + computeBranchTotals(): FileCoverageTotal; + resetHits(): void; + toSummary(): CoverageSummary; + } + + interface CoverageMap { + merge(data: object): void; + getCoverageSummary(): FileCoverage; + data: RawCoverage; + addFileCoverage(fileCoverage: RawFileCoverage): void; + files(): string[]; + fileCoverageFor(file: string): FileCoverage; + } + + interface SerializableError { + code?: any; + message: string; + stack: Maybe; + type?: string; + } + + type Status = 'passed' | 'failed' | 'skipped' | 'pending'; + + type Bytes = number; + type Milliseconds = number; + + interface AssertionResult { + ancestorTitles: string[]; + duration?: Maybe; + failureMessages: string[]; + fullName: string; + numPassingAsserts: number; + status: Status; + title: string; + } + + interface AggregatedResult { + coverageMap?: Maybe; + numFailedTests: number; + numFailedTestSuites: number; + numPassedTests: number; + numPassedTestSuites: number; + numPendingTests: number; + numPendingTestSuites: number; + numRuntimeErrorTestSuites: number; + numTotalTests: number; + numTotalTestSuites: number; + snapshot: SnapshotSummary; + startTime: number; + success: boolean; + testResults: TestResult[]; + wasInterrupted: boolean; + } + + interface TestResult { + console: Maybe; + coverage?: RawCoverage; + memoryUsage?: Bytes; + failureMessage: Maybe; + numFailingTests: number; + numPassingTests: number; + numPendingTests: number; + perfStats: { + end: Milliseconds, + start: Milliseconds, + }; + skipped: boolean; + snapshot: { + added: number, + fileDeleted: boolean, + matched: number, + unchecked: number, + unmatched: number, + updated: number, + }; + sourceMaps: {[sourcePath: string]: string}; + testExecError?: SerializableError; + testFilePath: string; + testResults: AssertionResult[]; + } + + interface SnapshotSummary { + added: number; + didUpdate: boolean; + failure: boolean; + filesAdded: number; + filesRemoved: number; + filesUnmatched: number; + filesUpdated: number; + matched: number; + total: number; + unchecked: number; + unmatched: number; + updated: number; + } + + // TestRunner + + interface Test { + context: Context; + duration?: number; + path: Path; + } + + interface Reporter { + onTestResult?(test: Test, testResult: TestResult, aggregatedResult: AggregatedResult): void; + onRunStart?(results: AggregatedResult, options: ReporterOnStartOptions): void; + onTestStart?(test: Test): void; + onRunComplete?(contexts: Set, results: AggregatedResult): Maybe>; + getLastError?(): Maybe; + } + + type TestFramework = ( + globalConfig: GlobalConfig, + config: ProjectConfig, + environment: Environment, + runtime: Runtime, + testPath: string, + ) => Promise; + + // Transform + + interface TransformedSource { + code: string; + map: Maybe; + } + + interface TransformOptions { + instrument: boolean; + } + + interface Transformer { + canInstrument?: boolean; + createTransformer?(options: any): Transformer; + + getCacheKey?( + fileData: string, + filePath: Path, + configStr: string, + options: TransformOptions, + ): string; + + process( + sourceText: string, + sourcePath: Path, + config: ProjectConfig, + options?: TransformOptions, + ): string | TransformedSource; + } +} diff --git a/types/jest/jest-tests.ts b/types/jest/jest-tests.ts index ef62f9b1c2..4f780fd83b 100644 --- a/types/jest/jest-tests.ts +++ b/types/jest/jest-tests.ts @@ -5,24 +5,24 @@ declare var require: { requireMock(s: string): any; }; // TODO: use real jquery types? -declare var $: any; +declare let $: any; // Tests based on the Jest website jest.unmock('../sum'); -describe('sum', function() { - it('adds 1 + 2 to equal 3', function() { - var sum: (a: number, b: number) => number = require('../sum'); +describe('sum', () => { + it('adds 1 + 2 to equal 3', () => { + let sum: (a: number, b: number) => number = require('../sum'); expect(sum(1, 2)).toBe(3); }); }); -describe('fetchCurrentUser', function() { - it('calls the callback when $.ajax requests are finished', function() { - var fetchCurrentUser = require('../fetchCurrentUser'); +describe('fetchCurrentUser', () => { + it('calls the callback when $.ajax requests are finished', () => { + let fetchCurrentUser = require('../fetchCurrentUser'); // Create a mock function for our callback - var callback = jest.fn(); + let callback = jest.fn(); fetchCurrentUser(callback); // Now we emulate the process by which `$.ajax` would execute its own @@ -42,10 +42,10 @@ describe('fetchCurrentUser', function() { }); // unmock is the recommended approach for unmocking... -jest.unmock('../displayUser.js') +jest.unmock('../displayUser.js'); -describe('displayUser', function() { - it('displays a user after a click', function() { +describe('displayUser', () => { + it('displays a user after a click', () => { // Set up our document body document.body.innerHTML = '
' + @@ -53,13 +53,13 @@ describe('displayUser', function() { '
'; - var displayUser = require.requireActual('../displayUser'); - var $ = require('jquery'); - var fetchCurrentUser = require('../fetchCurrentUser'); + let displayUser = require.requireActual('../displayUser'); + let $ = require('jquery'); + let fetchCurrentUser = require('../fetchCurrentUser'); // Tell the fetchCurrentUser mock function to automatically invoke // its callback with some data - fetchCurrentUser.mockImplementation(function(cb: Function) { + fetchCurrentUser.mockImplementation((cb: (...args: any[]) => any) => { cb({ loggedIn: true, fullName: 'Johnny Cash' @@ -77,14 +77,14 @@ describe('displayUser', function() { }); jest.unmock('../CheckboxWithLabel.js'); -describe('CheckboxWithLabel', function() { - it('changes the text after click', function() { - var React = require('react/addons'); - var CheckboxWithLabel = require('../CheckboxWithLabel.js'); - var TestUtils = React.addons.TestUtils; +describe('CheckboxWithLabel', () => { + it('changes the text after click', () => { + let React = require('react/addons'); + let CheckboxWithLabel = require('../CheckboxWithLabel.js'); + let TestUtils = React.addons.TestUtils; // Render a checkbox with label in the document - var checkbox = TestUtils.renderIntoDocument( + let checkbox = TestUtils.renderIntoDocument( CheckboxWithLabel({ labelOn: "On", labelOff: "Off" @@ -92,12 +92,12 @@ describe('CheckboxWithLabel', function() { ); // Verify that it's Off by default - var label = TestUtils.findRenderedDOMComponentWithTag( + let label = TestUtils.findRenderedDOMComponentWithTag( checkbox, 'label'); expect(label.getDOMNode().textContent).toEqual('Off'); // Simulate a click and verify that it is now On - var input = TestUtils.findRenderedDOMComponentWithTag( + let input = TestUtils.findRenderedDOMComponentWithTag( checkbox, 'input'); TestUtils.Simulate.change(input); expect(label.getDOMNode().textContent).toEqual('On'); @@ -105,92 +105,92 @@ describe('CheckboxWithLabel', function() { }); jest.runAllTicks(); -xdescribe('Hooks and Suits', function () { +xdescribe('Hooks and Suits', () => { let tested: boolean; - beforeEach(function () { + beforeEach(() => { tested = false; }); - afterEach(function () { + afterEach(() => { tested = true; }); - test('tested', function () { + test('tested', () => { expect(tested).toBeTruthy(); expect(tested).not.toBeFalsy(); }); - fit('tested', function () { + fit('tested', () => { expect(tested).toBeDefined(); expect(tested).not.toBeUndefined(); }); - xit('expect null to be null', function () { + xit('expect null to be null', () => { expect(null).toBeNull(); }); - xit('expect NaN to be NaN', function () { + xit('expect NaN to be NaN', () => { expect(NaN).toBeNaN(); }); }); -describe('compartion', function () { - var sum: (a: number, b: number) => number = require.requireMock('../sum'); +describe('compartion', () => { + let sum: (a: number, b: number) => number = require.requireMock('../sum'); - it('compares is 7 + 2 greater than 3', function () { + it('compares is 7 + 2 greater than 3', () => { expect(sum(7, 2)).toBeGreaterThan(3); }); - it('compares is 2 + 7 greater than or equal to 3', function () { + it('compares is 2 + 7 greater than or equal to 3', () => { expect(sum(2, 7)).toBeGreaterThanOrEqual(3); }); - it('compares is 3 less than 3 + 4', function () { + it('compares is 3 less than 3 + 4', () => { expect(3).toBeLessThan(sum(3, 4)); }); - it('compares is 3 less than or equal to 4 + 3', function () { + it('compares is 3 less than or equal to 4 + 3', () => { expect(3).toBeLessThanOrEqual(sum(4, 3)); }); - it('works sanely with simple decimals', function () { + it('works sanely with simple decimals', () => { expect(0.2 + 0.1).toBeCloseTo(0.3, 5); }); - it('works sanely with simple decimals and the default delta', function () { + it('works sanely with simple decimals and the default delta', () => { expect(0.2 + 0.1).toBeCloseTo(0.3); }); }); -describe('toThrow API', function () { +describe('toThrow API', () => { function throwTypeError(): void { throw new TypeError('toThrow Definition was out of date'); } - it('throws', function () { + it('throws', () => { expect(throwTypeError()).toThrow(); expect(throwTypeError()).toThrowError(); }); - it('throws TypeError', function () { + it('throws TypeError', () => { expect(throwTypeError()).toThrow(TypeError); expect(throwTypeError()).toThrowError(TypeError); }); - it('throws \'Definition was out of date\'', function () { + it('throws \'Definition was out of date\'', () => { expect(throwTypeError()).toThrow(/Definition was out of date/); - expect(throwTypeError()).toThrowError(/Definition was out of date/); + expect(throwTypeError()).toThrowError(/Definition was out of date/); }); - it('throws \'toThorow Definition was out of date\'', function () { + it('throws \'toThorow Definition was out of date\'', () => { expect(throwTypeError()).toThrow('toThrow Definition was out of date'); - expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); + expect(throwTypeError()).toThrowError('toThrow Definition was out of date'); }); }); -describe('Assymetric matchers', function () { - it('works', function () { +describe('Assymetric matchers', () => { + it('works', () => { expect({ timestamp: 1480807810388, text: 'Some text content, but we care only about *this part*' @@ -202,7 +202,7 @@ describe('Assymetric matchers', function () { const callback = jest.fn(); expect(callback).toEqual(expect.any(Function)); callback(5, "test"); - expect(callback).toBeCalledWith(expect.any(Number), expect.any(String)) + expect(callback).toBeCalledWith(expect.any(Number), expect.any(String)); const obj = { items: [1] }; @@ -224,13 +224,13 @@ describe('Assymetric matchers', function () { const test: Test = { a: expect.any(Number), b: expect.anything() - } + }; expect(callback).toHaveBeenCalledWith(test); }); }); -describe('Extending extend', function () { - it('works', function () { +describe('Extending extend', () => { + it('works', () => { expect.extend({ toBeNumber(received: any, actual: any) { const pass = received === actual; @@ -256,20 +256,20 @@ describe('Extending extend', function () { }); }); -describe('missing tests', function () { - it('creates closures', function () { +describe('missing tests', () => { + it('creates closures', () => { class Closure { private arg: T; - public constructor(private fn: (arg: T) => void) { + constructor(private fn: (arg: T) => void) { this.fn = fn; } - public bind(arg: T): void { + bind(arg: T): void { this.arg = arg; } - public call(): void { + call(): void { this.fn(this.arg); } } @@ -284,10 +284,10 @@ describe('missing tests', function () { expect(jest.isMockFunction(spy)).toBeTruthy(); }); - it('tests all mising Mocks functionality', function () { - type FruitsGetter = () => Array; + it('tests all mising Mocks functionality', () => { + type FruitsGetter = () => string[]; let mock: jest.Mock = jest.fn(); - mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum']) + mock.mockImplementationOnce(() => ['Orange', 'Apple', 'Plum']); jest.setMock('./../tesks/getFruits', mock); const getFruits: FruitsGetter = require('./../tesks/getFruits'); expect(getFruits()).toContain('Orange'); @@ -295,53 +295,53 @@ describe('missing tests', function () { expect(mock()).not.toContain('Orange'); const myBeverage: any = {delicious: true, sour: false}; expect(myBeverage).toContainEqual({delicious: true, sour: false}); - mock.mockReturnValue([]); //Deprecated: Use jest.fn(() => value) instead. + 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 () { + it('creates snapshoter', () => { jest.disableAutomock().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 () { + it('runs only pending timers', () => { jest.useRealTimers(); setTimeout(() => expect(1).not.toEqual(0), 3000); jest.runOnlyPendingTimers().runTimersToTime(300); }); - it('runs all timers', function () { + it('runs all timers', () => { jest.clearAllTimers(); jest.useFakeTimers(); setTimeout(() => expect(0).not.toEqual(1), 3000); jest.runAllTimers(); }); - it('cleares cache', function () { + it('cleares cache', () => { const sum1 = require('../sum'); jest.resetModules(); const sum2 = require('../sum'); expect(sum1).not.toBe(sum2); - }) + }); }); -describe('toMatchSnapshot', function () { - it('compares snapshots', function () { +describe('toMatchSnapshot', () => { + it('compares snapshots', () => { expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot(); }); - it('can give name to snapshot', function () { + it('can give name to snapshot', () => { expect({ type: 'a', props: { href: 'https://www.facebook.com/' }, children: [ 'Facebook' ] }).toMatchSnapshot('given name'); }); }); -describe('toThrowErrorMatchingSnapshot', function () { - it('compares snapshots', function () { - expect(() => { throw new Error('descriptiton') }).toThrowErrorMatchingSnapshot(); +describe('toThrowErrorMatchingSnapshot', () => { + it('compares snapshots', () => { + expect(() => { throw new Error('descriptiton'); }).toThrowErrorMatchingSnapshot(); }); }); @@ -357,8 +357,8 @@ expect.addSnapshotSerializer({ return val && val.willOverwrite && val.willOverwrite !== testSerializerPluginString; }, }); -describe('addSnapshotSerializer', function () { - it('the plugin does its work', function () { +describe('addSnapshotSerializer', () => { + it('the plugin does its work', () => { testSerializerPluginCallCount = 0; expect({ willOverwrite: { x: 1, y: 2, } }).toMatchSnapshot(); expect({ willOverwrite: "this will get overwritten by testSerializerPlugin" }).toMatchSnapshot(); @@ -368,23 +368,22 @@ describe('addSnapshotSerializer', function () { }); }); - function testInstances() { - var mockFn = jest.fn(); - var a = new mockFn(); - var b = new mockFn(); + let mockFn = jest.fn<(...args: any[]) => any>(); + let a = new mockFn(); + let b = new mockFn(); mockFn.mock.instances[0] === a; // true mockFn.mock.instances[1] === b; // true } function testMockImplementation() { - var mockFn = jest.fn().mockImplementation(function (scalar:number):number { + let mockFn = jest.fn<(...args: any[]) => any>().mockImplementation((scalar: number): number => { return 42 + scalar; }); - var a = mockFn(0); - var b = mockFn(1); + let a = mockFn(0); + let b = mockFn(1); a === 42; // true b === 43; // true @@ -394,15 +393,15 @@ function testMockImplementation() { } // Test from jest Docs: -describe('genMockFromModule', function () { +describe('genMockFromModule', () => { // Interfaces: interface MockFiles { [index: string]: string; } interface MockedFS { - readdirSync: (dir: string) => string[]; - __setMockFiles: (newMockFiles: MockFiles) => void ; + readdirSync(dir: string): string[]; + __setMockFiles(newMockFiles: MockFiles): void ; } // ------------------------------------------------------------------------------------ @@ -417,7 +416,7 @@ describe('genMockFromModule', function () { })); } - //export default summarizeFilesInDirectorySync; // For sake of compilation + // export default summarizeFilesInDirectorySync; // For sake of compilation // ------------------------------------------------------------------------------------ // __mocks__/fs.js @@ -429,7 +428,7 @@ describe('genMockFromModule', function () { let mockFiles: any = Object.create(null); function __setMockFiles(newMockFiles: MockFiles): void { mockFiles = Object.create(null); - for(const file in newMockFiles) { + for (const file in newMockFiles) { const dir: string = path.dirname(file); if (!mockFiles[dir]) { @@ -446,7 +445,7 @@ describe('genMockFromModule', function () { mockedFS.readdirSync = readdirSync; mockedFS.__setMockFiles = __setMockFiles; - //export = mockedFS; // For sake of compilation + // export = mockedFS; // For sake of compilation // ------------------------------------------------------------------------------------ // __tests__/FileSummarizer-test.js @@ -475,14 +474,14 @@ describe('genMockFromModule', function () { /** * Pass strictNullChecks */ -describe('strictNullChecks', function () { +describe('strictNullChecks', () => { it('does not complain when using done callback', (done) => { done(); - }) + }); }); class TestApi { - constructor() { }; + constructor() { } testProp: boolean; private anotherProp: string; testMethod(a: number): string { return ""; } @@ -492,8 +491,8 @@ declare function mockedFunc(a: number): string; declare function mockedFuncWithApi(api: TestApi): void; -describe('Mocked type', function () { - it('Works', function () { +describe('Mocked type', () => { + it('Works', () => { const mock: jest.Mocked = new TestApi() as any; mock.testProp; mock.testMethod.mockImplementation(() => 'test'); @@ -503,8 +502,8 @@ describe('Mocked type', function () { }); }); -describe('Mocks', function () { - it('jest.fn() without args is a function type', function () { +describe('Mocks', () => { + it('jest.fn() without args is a function type', () => { const test = jest.fn(); test(); new test(); @@ -512,7 +511,7 @@ describe('Mocks', function () { test.mockImplementation(() => { }); }); - it('jest.fn() with returned object infers type', function () { + it('jest.fn() with returned object infers type', () => { const testMock = jest.fn(() => ({ a: 5, test: jest.fn() })); testMock(5, 5, 'a'); @@ -537,14 +536,14 @@ describe('Mocks', function () { }); // https://facebook.github.io/jest/docs/en/expect.html#resolves -describe('resolves', function() { - it('unwraps the expected Promise', function() { +describe('resolves', () => { + it('unwraps the expected Promise', () => { const expectation = expect(Promise.resolve('test')).resolves.toEqual('test'); expect(expectation instanceof Promise).toBeTruthy(); return expectation; }); - it('unwraps a .toHaveBeenCalledX', function(done) { + it('unwraps a .toHaveBeenCalledX', done => { expect.assertions(2); const fn = jest.fn(); @@ -554,7 +553,7 @@ describe('resolves', function() { }); }); - it('unwraps a not.toHaveBeenCalledX', function(done) { + it('unwraps a not.toHaveBeenCalledX', done => { expect.assertions(2); const fn = jest.fn(); @@ -566,10 +565,30 @@ describe('resolves', function() { }); // https://facebook.github.io/jest/docs/en/expect.html#rejects -describe('rejects', function() { - it('unwraps the expected Promise', function() { +describe('rejects', () => { + it('unwraps the expected Promise', () => { const expectation = expect(Promise.reject(new Error('error'))).rejects.toMatch('error'); expect(expectation instanceof Promise).toBeTruthy(); return expectation; }); }); + +class MyTransformer implements jest.Transformer { + process(text: string, path: string) { + return ` + // some comments + ${text} + `; + } +} + +class MyReporter implements jest.Reporter { + onRunStart() { + console.log('hello world'); + } +} + +declare const testResult: jest.TestResult; +const myTestRunner: jest.TestFramework = () => Promise.resolve(testResult); + +const testResultsProcessor: jest.TestResultsProcessor = result => ({...result, numFailedTests: 1}); diff --git a/types/jest/tslint.json b/types/jest/tslint.json new file mode 100644 index 0000000000..4e88071852 --- /dev/null +++ b/types/jest/tslint.json @@ -0,0 +1 @@ +{"extends": "dtslint/dt.json"} From 18747a4fced3a1e890efba380c85de3cefe612ee Mon Sep 17 00:00:00 2001 From: Renjith Date: Mon, 17 Jul 2017 23:42:33 +0530 Subject: [PATCH 0085/1139] [restify 5] Fix definition for AuditLogger and RouteOptions (#18036) * Fix definition for AuditLoggerOptions and RouteOptions * Beautify * Fix test cases --- types/restify/index.d.ts | 21 +++++++++++++++++++++ types/restify/restify-tests.ts | 4 ++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/types/restify/index.d.ts b/types/restify/index.d.ts index c4421ca625..b711a9cddf 100644 --- a/types/restify/index.d.ts +++ b/types/restify/index.d.ts @@ -990,6 +990,22 @@ export interface Route { } export interface RouteOptions { + name?: string; + + path?: string | RegExp; + + url?: string | RegExp; + + urlParamPattern?: RegExp; + + contentType?: string | string[]; + + version?: string; + + versions?: string[]; +} + +export interface MountOptions { name: string; method: string; @@ -1071,6 +1087,11 @@ export namespace plugins { */ log: Logger; + /** + * The event from the server which initiates the + * log, one of 'pre', 'routed', or 'after' + */ + event: 'pre' | 'routed' | 'after'; /** * Restify server. If passed in, causes server to emit 'auditlog' event after audit logs are flushed */ diff --git a/types/restify/restify-tests.ts b/types/restify/restify-tests.ts index 7e80e5290f..6427fb7869 100644 --- a/types/restify/restify-tests.ts +++ b/types/restify/restify-tests.ts @@ -142,7 +142,7 @@ server.use(restify.plugins.throttle({ } })); -server.on('after', restify.plugins.auditLogger({ log: {} as Logger })); +server.on('after', restify.plugins.auditLogger({ event: 'after', log: {} as Logger })); server.on('after', (req: restify.Request, res: restify.Response, route: restify.Route, err: any) => { route.spec.method === 'GET'; @@ -150,7 +150,7 @@ server.on('after', (req: restify.Request, res: restify.Response, route: restify. route.spec.path === '/some/path'; route.spec.path === /\/some\/path\/.*/; route.spec.versions === ['v1']; - restify.plugins.auditLogger({ log: {} as Logger })(req, res, route, err); + restify.plugins.auditLogger({ event: 'after', log: {} as Logger })(req, res, route, err); }); ( restify).defaultResponseHeaders = function(this: restify.Request, data: any) { From 1ad0e4dbc40a504e53aa8bca12e9f918cb95ff5d Mon Sep 17 00:00:00 2001 From: Chris Kelly Date: Mon, 17 Jul 2017 12:17:58 -0600 Subject: [PATCH 0086/1139] Make center point optional on Point.rotate (#18045) * Make center point optional on Point.rotate Since the second parameter is optional (and most don't use it), let's let TS know that one parameter is OK. * Update index.d.ts --- types/paper/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index c57b2c0516..45f1ac590f 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -470,7 +470,7 @@ declare module 'paper' { * @param angle - the rotation angle * @param center - the center point of the rotation */ - rotate(angle: number, center: Point): Point; + rotate(angle: number, center?: Point): Point; /** * Transforms the point by the matrix as a new point. The object itself is not modified! From 1af3158a5d57616180e090db1ee036f15bf0581d Mon Sep 17 00:00:00 2001 From: Mikhail Morozov Date: Tue, 18 Jul 2017 01:19:27 +0700 Subject: [PATCH 0087/1139] Reactstrap css modules (#18049) * reactstrap css modules * fixed module import * removed package-lock.json from git index --- types/reactstrap/index.d.ts | 4 ++++ types/reactstrap/lib/Alert.d.ts | 5 ++++- types/reactstrap/lib/Badge.d.ts | 5 ++++- types/reactstrap/lib/Breadcrumb.d.ts | 5 ++++- types/reactstrap/lib/BreadcrumbItem.d.ts | 3 +++ types/reactstrap/lib/Button.d.ts | 6 +++++- types/reactstrap/lib/ButtonGroup.d.ts | 5 ++++- types/reactstrap/lib/ButtonToolbar.d.ts | 5 ++++- types/reactstrap/lib/Card.d.ts | 3 +++ types/reactstrap/lib/CardBlock.d.ts | 3 +++ types/reactstrap/lib/CardColumns.d.ts | 5 ++++- types/reactstrap/lib/CardDeck.d.ts | 5 ++++- types/reactstrap/lib/CardFooter.d.ts | 5 ++++- types/reactstrap/lib/CardGroup.d.ts | 5 ++++- types/reactstrap/lib/CardHeader.d.ts | 5 ++++- types/reactstrap/lib/CardImg.d.ts | 5 ++++- types/reactstrap/lib/CardImgOverlay.d.ts | 5 ++++- types/reactstrap/lib/CardLink.d.ts | 5 ++++- types/reactstrap/lib/CardSubtitle.d.ts | 5 ++++- types/reactstrap/lib/CardText.d.ts | 3 +++ types/reactstrap/lib/CardTitle.d.ts | 5 ++++- types/reactstrap/lib/Collapse.d.ts | 5 ++++- types/reactstrap/lib/Container.d.ts | 5 ++++- types/reactstrap/lib/Dropdown.d.ts | 5 ++++- types/reactstrap/lib/DropdownItem.d.ts | 3 +++ types/reactstrap/lib/DropdownMenu.d.ts | 5 ++++- types/reactstrap/lib/DropdownToggle.d.ts | 5 ++++- types/reactstrap/lib/Fade.d.ts | 5 ++++- types/reactstrap/lib/Form.d.ts | 5 ++++- types/reactstrap/lib/FormFeedback.d.ts | 5 ++++- types/reactstrap/lib/FormGroup.d.ts | 3 +++ types/reactstrap/lib/FormText.d.ts | 5 ++++- types/reactstrap/lib/Input.d.ts | 5 ++++- types/reactstrap/lib/InputGroup.d.ts | 5 ++++- types/reactstrap/lib/InputGroupAddon.d.ts | 5 ++++- types/reactstrap/lib/InputGroupButton.d.ts | 5 ++++- types/reactstrap/lib/Jumbotron.d.ts | 5 ++++- types/reactstrap/lib/Label.d.ts | 2 ++ types/reactstrap/lib/ListGroup.d.ts | 5 ++++- types/reactstrap/lib/ListGroupItem.d.ts | 5 ++++- types/reactstrap/lib/ListGroupItemHeading.d.ts | 5 ++++- types/reactstrap/lib/ListGroupItemText.d.ts | 5 ++++- types/reactstrap/lib/Media.d.ts | 5 ++++- types/reactstrap/lib/Modal.d.ts | 5 ++++- types/reactstrap/lib/ModalBody.d.ts | 5 ++++- types/reactstrap/lib/ModalFooter.d.ts | 5 ++++- types/reactstrap/lib/ModalHeader.d.ts | 5 ++++- types/reactstrap/lib/Nav.d.ts | 3 +++ types/reactstrap/lib/NavItem.d.ts | 5 ++++- types/reactstrap/lib/NavLink.d.ts | 3 +++ types/reactstrap/lib/Navbar.d.ts | 5 ++++- types/reactstrap/lib/NavbarBrand.d.ts | 5 ++++- types/reactstrap/lib/NavbarToggler.d.ts | 5 ++++- types/reactstrap/lib/Pagination.d.ts | 5 ++++- types/reactstrap/lib/PaginationItem.d.ts | 5 ++++- types/reactstrap/lib/PaginationLink.d.ts | 5 ++++- types/reactstrap/lib/Popover.d.ts | 5 ++++- types/reactstrap/lib/PopoverContent.d.ts | 5 ++++- types/reactstrap/lib/PopoverTitle.d.ts | 5 ++++- types/reactstrap/lib/Progress.d.ts | 5 ++++- types/reactstrap/lib/Row.d.ts | 5 ++++- types/reactstrap/lib/TabContent.d.ts | 5 ++++- types/reactstrap/lib/TabPane.d.ts | 5 ++++- types/reactstrap/lib/Table.d.ts | 5 ++++- types/reactstrap/lib/Tag.d.ts | 5 ++++- types/reactstrap/lib/TetherContent.d.ts | 5 ++++- types/reactstrap/lib/Tooltip.d.ts | 5 ++++- types/reactstrap/reactstrap-tests.tsx | 10 ++++++++++ 68 files changed, 269 insertions(+), 57 deletions(-) diff --git a/types/reactstrap/index.d.ts b/types/reactstrap/index.d.ts index c612edf234..8bd00001b8 100644 --- a/types/reactstrap/index.d.ts +++ b/types/reactstrap/index.d.ts @@ -4,6 +4,10 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +export interface CSSModule { + [className: string]: string; +} + export { default as Alert } from './lib/Alert'; export { default as Badge } from './lib/Badge'; export { default as Breadcrumb } from './lib/Breadcrumb'; diff --git a/types/reactstrap/lib/Alert.d.ts b/types/reactstrap/lib/Alert.d.ts index ebe4f8cccc..8d76f3084c 100644 --- a/types/reactstrap/lib/Alert.d.ts +++ b/types/reactstrap/lib/Alert.d.ts @@ -1,5 +1,8 @@ +import {CSSModule} from '../index'; + export interface UncontrolledProps { className?: string; + cssModule?: CSSModule; color?: string; tag?: React.ReactType; transitionAppearTimeout?: number; @@ -13,4 +16,4 @@ interface Props extends UncontrolledProps { } declare var Alert: React.StatelessComponent; -export default Alert; \ No newline at end of file +export default Alert; diff --git a/types/reactstrap/lib/Badge.d.ts b/types/reactstrap/lib/Badge.d.ts index 0f9c66b691..4f88f48025 100644 --- a/types/reactstrap/lib/Badge.d.ts +++ b/types/reactstrap/lib/Badge.d.ts @@ -1,9 +1,12 @@ +import {CSSModule} from '../index'; + interface Props { color?: string; pill?: boolean; tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var Badge: React.StatelessComponent; -export default Badge; \ No newline at end of file +export default Badge; diff --git a/types/reactstrap/lib/Breadcrumb.d.ts b/types/reactstrap/lib/Breadcrumb.d.ts index a6be7ab9fc..e66c672a64 100644 --- a/types/reactstrap/lib/Breadcrumb.d.ts +++ b/types/reactstrap/lib/Breadcrumb.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: string; className?: string; + cssModule?: CSSModule; } declare var Breadcrumb: React.StatelessComponent; -export default Breadcrumb; \ No newline at end of file +export default Breadcrumb; diff --git a/types/reactstrap/lib/BreadcrumbItem.d.ts b/types/reactstrap/lib/BreadcrumbItem.d.ts index ce4e8ca522..66e56776be 100644 --- a/types/reactstrap/lib/BreadcrumbItem.d.ts +++ b/types/reactstrap/lib/BreadcrumbItem.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; active?: boolean; className?: string; + cssModule?: CSSModule; // if a is passed as a string // this could be href [others: string]: any; diff --git a/types/reactstrap/lib/Button.d.ts b/types/reactstrap/lib/Button.d.ts index 8ab27dfdcd..c0181c6374 100644 --- a/types/reactstrap/lib/Button.d.ts +++ b/types/reactstrap/lib/Button.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + interface Props extends React.HTMLProps { outline?: boolean; active?: boolean; @@ -10,7 +12,9 @@ interface Props extends React.HTMLProps { size?: any; id?: string; style?: React.CSSProperties; + + cssModule?: CSSModule; } declare var Button: React.StatelessComponent; -export default Button; \ No newline at end of file +export default Button; diff --git a/types/reactstrap/lib/ButtonGroup.d.ts b/types/reactstrap/lib/ButtonGroup.d.ts index a583a41ee0..ddabdb88d1 100644 --- a/types/reactstrap/lib/ButtonGroup.d.ts +++ b/types/reactstrap/lib/ButtonGroup.d.ts @@ -1,11 +1,14 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; 'aria-label'?: string; className?: string; + cssModule?: CSSModule; role?: string; size?: string; vertical?: boolean; } declare var ButtonGroup: React.StatelessComponent; -export default ButtonGroup; \ No newline at end of file +export default ButtonGroup; diff --git a/types/reactstrap/lib/ButtonToolbar.d.ts b/types/reactstrap/lib/ButtonToolbar.d.ts index 239c96c01e..3a33287f14 100644 --- a/types/reactstrap/lib/ButtonToolbar.d.ts +++ b/types/reactstrap/lib/ButtonToolbar.d.ts @@ -1,9 +1,12 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; 'aria-label'?: string; className?: string; + cssModule?: CSSModule; role?: string; } declare var ButtonToolbar: React.StatelessComponent; -export default ButtonToolbar; \ No newline at end of file +export default ButtonToolbar; diff --git a/types/reactstrap/lib/Card.d.ts b/types/reactstrap/lib/Card.d.ts index f300b09310..28acb6cbaf 100644 --- a/types/reactstrap/lib/Card.d.ts +++ b/types/reactstrap/lib/Card.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; inverse?: boolean; @@ -5,6 +7,7 @@ interface Props { block?: boolean; outline?: boolean; className?: string; + cssModule?: CSSModule; style?: React.CSSProperties; } diff --git a/types/reactstrap/lib/CardBlock.d.ts b/types/reactstrap/lib/CardBlock.d.ts index 406f4b8258..6b93fcafce 100644 --- a/types/reactstrap/lib/CardBlock.d.ts +++ b/types/reactstrap/lib/CardBlock.d.ts @@ -1,6 +1,9 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardBlock: React.StatelessComponent; diff --git a/types/reactstrap/lib/CardColumns.d.ts b/types/reactstrap/lib/CardColumns.d.ts index a4992b8ffe..12c0507d5a 100644 --- a/types/reactstrap/lib/CardColumns.d.ts +++ b/types/reactstrap/lib/CardColumns.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardColumns: React.StatelessComponent; -export default CardColumns; \ No newline at end of file +export default CardColumns; diff --git a/types/reactstrap/lib/CardDeck.d.ts b/types/reactstrap/lib/CardDeck.d.ts index 1b70bda457..6f3076577d 100644 --- a/types/reactstrap/lib/CardDeck.d.ts +++ b/types/reactstrap/lib/CardDeck.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardDeck: React.StatelessComponent; -export default CardDeck; \ No newline at end of file +export default CardDeck; diff --git a/types/reactstrap/lib/CardFooter.d.ts b/types/reactstrap/lib/CardFooter.d.ts index 8356b15aef..ab5434ae9c 100644 --- a/types/reactstrap/lib/CardFooter.d.ts +++ b/types/reactstrap/lib/CardFooter.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardFooter: React.StatelessComponent; -export default CardFooter; \ No newline at end of file +export default CardFooter; diff --git a/types/reactstrap/lib/CardGroup.d.ts b/types/reactstrap/lib/CardGroup.d.ts index c6e956c8a2..d258e08615 100644 --- a/types/reactstrap/lib/CardGroup.d.ts +++ b/types/reactstrap/lib/CardGroup.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardGroup: React.StatelessComponent; -export default CardGroup; \ No newline at end of file +export default CardGroup; diff --git a/types/reactstrap/lib/CardHeader.d.ts b/types/reactstrap/lib/CardHeader.d.ts index 6977abf238..01e60e345d 100644 --- a/types/reactstrap/lib/CardHeader.d.ts +++ b/types/reactstrap/lib/CardHeader.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardHeader: React.StatelessComponent; -export default CardHeader; \ No newline at end of file +export default CardHeader; diff --git a/types/reactstrap/lib/CardImg.d.ts b/types/reactstrap/lib/CardImg.d.ts index 6a8f85f3b8..6fa732ebca 100644 --- a/types/reactstrap/lib/CardImg.d.ts +++ b/types/reactstrap/lib/CardImg.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; top?: boolean; bottom?: boolean; className?: string; + cssModule?: CSSModule; src?: string; width?: string; height?: string; @@ -10,4 +13,4 @@ interface Props { } declare var CardImg: React.StatelessComponent; -export default CardImg; \ No newline at end of file +export default CardImg; diff --git a/types/reactstrap/lib/CardImgOverlay.d.ts b/types/reactstrap/lib/CardImgOverlay.d.ts index 40c958fd0e..0d366bc396 100644 --- a/types/reactstrap/lib/CardImgOverlay.d.ts +++ b/types/reactstrap/lib/CardImgOverlay.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardImgOverlay: React.StatelessComponent; -export default CardImgOverlay; \ No newline at end of file +export default CardImgOverlay; diff --git a/types/reactstrap/lib/CardLink.d.ts b/types/reactstrap/lib/CardLink.d.ts index 7db1d25a16..6c759033d7 100644 --- a/types/reactstrap/lib/CardLink.d.ts +++ b/types/reactstrap/lib/CardLink.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; href?: string; } declare var CardLink: React.StatelessComponent; -export default CardLink; \ No newline at end of file +export default CardLink; diff --git a/types/reactstrap/lib/CardSubtitle.d.ts b/types/reactstrap/lib/CardSubtitle.d.ts index 9a3100bdd1..923339aecd 100644 --- a/types/reactstrap/lib/CardSubtitle.d.ts +++ b/types/reactstrap/lib/CardSubtitle.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardSubtitle: React.StatelessComponent; -export default CardSubtitle; \ No newline at end of file +export default CardSubtitle; diff --git a/types/reactstrap/lib/CardText.d.ts b/types/reactstrap/lib/CardText.d.ts index a831497faa..effb2b81ad 100644 --- a/types/reactstrap/lib/CardText.d.ts +++ b/types/reactstrap/lib/CardText.d.ts @@ -1,6 +1,9 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardText: React.StatelessComponent; diff --git a/types/reactstrap/lib/CardTitle.d.ts b/types/reactstrap/lib/CardTitle.d.ts index 8b8871348d..61199b455c 100644 --- a/types/reactstrap/lib/CardTitle.d.ts +++ b/types/reactstrap/lib/CardTitle.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var CardTitle: React.StatelessComponent; -export default CardTitle; \ No newline at end of file +export default CardTitle; diff --git a/types/reactstrap/lib/Collapse.d.ts b/types/reactstrap/lib/Collapse.d.ts index ce17d102e3..d072e8fb46 100644 --- a/types/reactstrap/lib/Collapse.d.ts +++ b/types/reactstrap/lib/Collapse.d.ts @@ -1,6 +1,9 @@ +import {CSSModule} from '../index'; + interface Props extends React.HTMLProps { isOpen?: boolean; classNames?: string; + cssModule?: CSSModule; tag?: React.ReactType; navbar?: boolean; delay?: { @@ -12,4 +15,4 @@ interface Props extends React.HTMLProps { } declare var Collapse: React.StatelessComponent; -export default Collapse; \ No newline at end of file +export default Collapse; diff --git a/types/reactstrap/lib/Container.d.ts b/types/reactstrap/lib/Container.d.ts index bb0c9aa7a3..a7e02b2a72 100644 --- a/types/reactstrap/lib/Container.d.ts +++ b/types/reactstrap/lib/Container.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; fluid?: boolean; className?: string; + cssModule?: CSSModule; } declare var Container: React.StatelessComponent; -export default Container; \ No newline at end of file +export default Container; diff --git a/types/reactstrap/lib/Dropdown.d.ts b/types/reactstrap/lib/Dropdown.d.ts index c89150fd83..7ad85570b1 100644 --- a/types/reactstrap/lib/Dropdown.d.ts +++ b/types/reactstrap/lib/Dropdown.d.ts @@ -1,9 +1,12 @@ /// +import {CSSModule} from '../index'; + export interface UncontrolledProps { isOpen?: boolean; toggle?: () => void; className?: string; + cssModule?: CSSModule; } export interface Props extends UncontrolledProps { @@ -16,4 +19,4 @@ export interface Props extends UncontrolledProps { } declare var Dropdown: React.StatelessComponent; -export default Dropdown; \ No newline at end of file +export default Dropdown; diff --git a/types/reactstrap/lib/DropdownItem.d.ts b/types/reactstrap/lib/DropdownItem.d.ts index e28715e42f..46462984e0 100644 --- a/types/reactstrap/lib/DropdownItem.d.ts +++ b/types/reactstrap/lib/DropdownItem.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + interface Props { disabled?: boolean; divider?: boolean; @@ -5,6 +7,7 @@ interface Props { header?: boolean; onClick?: (event: React.MouseEvent) => void; className?: string; + cssModule?: CSSModule; href?: string; } diff --git a/types/reactstrap/lib/DropdownMenu.d.ts b/types/reactstrap/lib/DropdownMenu.d.ts index 08dd194288..e0a01f109d 100644 --- a/types/reactstrap/lib/DropdownMenu.d.ts +++ b/types/reactstrap/lib/DropdownMenu.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; right?: boolean; className?: boolean; + cssModule?: CSSModule; } declare var DropdownMenu: React.StatelessComponent; -export default DropdownMenu; \ No newline at end of file +export default DropdownMenu; diff --git a/types/reactstrap/lib/DropdownToggle.d.ts b/types/reactstrap/lib/DropdownToggle.d.ts index 753ef0045c..ac72251641 100644 --- a/types/reactstrap/lib/DropdownToggle.d.ts +++ b/types/reactstrap/lib/DropdownToggle.d.ts @@ -1,6 +1,9 @@ +import {CSSModule} from '../index'; + interface Props { caret?: boolean; className?: string; + cssModule?: CSSModule; disabled?: boolean; onClick?: React.MouseEventHandler; 'data-toggle'?: string; @@ -13,4 +16,4 @@ interface Props { } declare var DropdownToggle: React.StatelessComponent; -export default DropdownToggle; \ No newline at end of file +export default DropdownToggle; diff --git a/types/reactstrap/lib/Fade.d.ts b/types/reactstrap/lib/Fade.d.ts index f8776c2709..3bac4061a7 100644 --- a/types/reactstrap/lib/Fade.d.ts +++ b/types/reactstrap/lib/Fade.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { baseClass?: string; baseClassIn?: string; tag?: React.ReactType; className?: string; + cssModule?: CSSModule; transitionAppearTimeout?: number; transitionEnterTimeout?: number; transitionLeaveTimeout?: number; @@ -14,4 +17,4 @@ interface Props { } declare var Fade: React.StatelessComponent; -export default Fade; \ No newline at end of file +export default Fade; diff --git a/types/reactstrap/lib/Form.d.ts b/types/reactstrap/lib/Form.d.ts index 39f20c28da..d3a4497d0e 100644 --- a/types/reactstrap/lib/Form.d.ts +++ b/types/reactstrap/lib/Form.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props extends React.HTMLProps { inline?: boolean; tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var Form: React.StatelessComponent; -export default Form; \ No newline at end of file +export default Form; diff --git a/types/reactstrap/lib/FormFeedback.d.ts b/types/reactstrap/lib/FormFeedback.d.ts index 30ecaeea74..3e30e323a3 100644 --- a/types/reactstrap/lib/FormFeedback.d.ts +++ b/types/reactstrap/lib/FormFeedback.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: string; className?: string; + cssModule?: CSSModule; } declare var FormFeedback: React.StatelessComponent; -export default FormFeedback; \ No newline at end of file +export default FormFeedback; diff --git a/types/reactstrap/lib/FormGroup.d.ts b/types/reactstrap/lib/FormGroup.d.ts index 0bf94a82a2..800ce4ceb1 100644 --- a/types/reactstrap/lib/FormGroup.d.ts +++ b/types/reactstrap/lib/FormGroup.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + interface Props extends React.HTMLProps { row?: boolean; check?: boolean; @@ -5,6 +7,7 @@ interface Props extends React.HTMLProps { tag?: React.ReactType; color?: string; className?: string; + cssModule?: CSSModule; } declare var FormGroup: React.StatelessComponent; diff --git a/types/reactstrap/lib/FormText.d.ts b/types/reactstrap/lib/FormText.d.ts index 221a6de013..6bc2351582 100644 --- a/types/reactstrap/lib/FormText.d.ts +++ b/types/reactstrap/lib/FormText.d.ts @@ -1,9 +1,12 @@ +import {CSSModule} from '../index'; + interface Props { inline?: boolean; tag?: string; color?: string; className?: string; + cssModule?: CSSModule; } declare var FormText: React.StatelessComponent; -export default FormText; \ No newline at end of file +export default FormText; diff --git a/types/reactstrap/lib/Input.d.ts b/types/reactstrap/lib/Input.d.ts index c9d7a1329d..6177ccfce5 100644 --- a/types/reactstrap/lib/Input.d.ts +++ b/types/reactstrap/lib/Input.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + type InputType = | 'text' | 'email' @@ -38,9 +40,10 @@ interface InputProps extends Intermediate { tag?: React.ReactType; addon?: boolean; className?: string; + cssModule?: CSSModule; // We don't have the property 'static' here because 'static' is a reserved keyword in TypeScript // Maybe reactstrap will support an 'isStatic' alias in the future } declare var Input: React.StatelessComponent; -export default Input; \ No newline at end of file +export default Input; diff --git a/types/reactstrap/lib/InputGroup.d.ts b/types/reactstrap/lib/InputGroup.d.ts index 1d2cfb0633..40bba65097 100644 --- a/types/reactstrap/lib/InputGroup.d.ts +++ b/types/reactstrap/lib/InputGroup.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; size?: string; className?: string; + cssModule?: CSSModule; } declare var InputGroup: React.StatelessComponent; -export default InputGroup; \ No newline at end of file +export default InputGroup; diff --git a/types/reactstrap/lib/InputGroupAddon.d.ts b/types/reactstrap/lib/InputGroupAddon.d.ts index 379c6cc24d..07a4512809 100644 --- a/types/reactstrap/lib/InputGroupAddon.d.ts +++ b/types/reactstrap/lib/InputGroupAddon.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var InputGroupAddon: React.StatelessComponent; -export default InputGroupAddon; \ No newline at end of file +export default InputGroupAddon; diff --git a/types/reactstrap/lib/InputGroupButton.d.ts b/types/reactstrap/lib/InputGroupButton.d.ts index 43017e4a25..304eb660e0 100644 --- a/types/reactstrap/lib/InputGroupButton.d.ts +++ b/types/reactstrap/lib/InputGroupButton.d.ts @@ -1,10 +1,13 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; groupClassName?: string; groupAttributes?: any; className?: string; + cssModule?: CSSModule; color?: string; } declare var InputGroupButton: React.StatelessComponent; -export default InputGroupButton; \ No newline at end of file +export default InputGroupButton; diff --git a/types/reactstrap/lib/Jumbotron.d.ts b/types/reactstrap/lib/Jumbotron.d.ts index 65529d80e7..70f0919b7f 100644 --- a/types/reactstrap/lib/Jumbotron.d.ts +++ b/types/reactstrap/lib/Jumbotron.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; fluid?: boolean; className?: string; + cssModule?: CSSModule; } declare var Jumbotron: React.StatelessComponent; -export default Jumbotron; \ No newline at end of file +export default Jumbotron; diff --git a/types/reactstrap/lib/Label.d.ts b/types/reactstrap/lib/Label.d.ts index 383378dc4e..ab7dd820d3 100644 --- a/types/reactstrap/lib/Label.d.ts +++ b/types/reactstrap/lib/Label.d.ts @@ -1,3 +1,4 @@ +import {CSSModule} from '../index'; import { ColumnProps } from './Col'; interface Intermediate extends React.LabelHTMLAttributes { @@ -13,6 +14,7 @@ interface Props extends Intermediate { for?: string; tag?: string; className?: string; + cssModule?: CSSModule; xs?: ColumnProps; sm?: ColumnProps; md?: ColumnProps; diff --git a/types/reactstrap/lib/ListGroup.d.ts b/types/reactstrap/lib/ListGroup.d.ts index 50e5ecb247..4cb380922f 100644 --- a/types/reactstrap/lib/ListGroup.d.ts +++ b/types/reactstrap/lib/ListGroup.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; flush?: boolean; className?: string; + cssModule?: CSSModule; } declare var ListGroup: React.StatelessComponent; -export default ListGroup; \ No newline at end of file +export default ListGroup; diff --git a/types/reactstrap/lib/ListGroupItem.d.ts b/types/reactstrap/lib/ListGroupItem.d.ts index a85df43fc1..f7238ce2eb 100644 --- a/types/reactstrap/lib/ListGroupItem.d.ts +++ b/types/reactstrap/lib/ListGroupItem.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; active?: boolean; @@ -5,8 +7,9 @@ interface Props { color?: string; action?: boolean; className?: string; + cssModule?: CSSModule; href?: string; } declare var ListGroupItem: React.StatelessComponent; -export default ListGroupItem; \ No newline at end of file +export default ListGroupItem; diff --git a/types/reactstrap/lib/ListGroupItemHeading.d.ts b/types/reactstrap/lib/ListGroupItemHeading.d.ts index 35adbf4d5e..c8168682ab 100644 --- a/types/reactstrap/lib/ListGroupItemHeading.d.ts +++ b/types/reactstrap/lib/ListGroupItemHeading.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var ListGroupItemHeading: React.StatelessComponent; -export default ListGroupItemHeading; \ No newline at end of file +export default ListGroupItemHeading; diff --git a/types/reactstrap/lib/ListGroupItemText.d.ts b/types/reactstrap/lib/ListGroupItemText.d.ts index 51fc4b0459..394e524c3d 100644 --- a/types/reactstrap/lib/ListGroupItemText.d.ts +++ b/types/reactstrap/lib/ListGroupItemText.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var ListGroupItemText: React.StatelessComponent; -export default ListGroupItemText; \ No newline at end of file +export default ListGroupItemText; diff --git a/types/reactstrap/lib/Media.d.ts b/types/reactstrap/lib/Media.d.ts index be8c28ada9..6f11450323 100644 --- a/types/reactstrap/lib/Media.d.ts +++ b/types/reactstrap/lib/Media.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { body?: boolean; bottom?: boolean; className?: string; + cssModule?: CSSModule; heading?: boolean; left?: boolean; list?: boolean; @@ -15,4 +18,4 @@ interface Props { } declare var Media: React.StatelessComponent; -export default Media; \ No newline at end of file +export default Media; diff --git a/types/reactstrap/lib/Modal.d.ts b/types/reactstrap/lib/Modal.d.ts index 60d09d1cb4..06261e0ac1 100644 --- a/types/reactstrap/lib/Modal.d.ts +++ b/types/reactstrap/lib/Modal.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + interface Props { isOpen?: boolean; size?: string; @@ -7,6 +9,7 @@ interface Props { onEnter?: () => void; onExit?: () => void; className?: string; + cssModule?: CSSModule; wrapClassName?: string; modalClassName?: string; backdropClassName?: string; @@ -15,4 +18,4 @@ interface Props { } declare var Modal: React.StatelessComponent; -export default Modal; \ No newline at end of file +export default Modal; diff --git a/types/reactstrap/lib/ModalBody.d.ts b/types/reactstrap/lib/ModalBody.d.ts index 3a09dfed76..a32793459e 100644 --- a/types/reactstrap/lib/ModalBody.d.ts +++ b/types/reactstrap/lib/ModalBody.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var ModalBody: React.StatelessComponent; -export default ModalBody; \ No newline at end of file +export default ModalBody; diff --git a/types/reactstrap/lib/ModalFooter.d.ts b/types/reactstrap/lib/ModalFooter.d.ts index b3ec195ed9..ad50921f92 100644 --- a/types/reactstrap/lib/ModalFooter.d.ts +++ b/types/reactstrap/lib/ModalFooter.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var ModalFooter: React.StatelessComponent; -export default ModalFooter; \ No newline at end of file +export default ModalFooter; diff --git a/types/reactstrap/lib/ModalHeader.d.ts b/types/reactstrap/lib/ModalHeader.d.ts index decfdab4b0..73c95eae3e 100644 --- a/types/reactstrap/lib/ModalHeader.d.ts +++ b/types/reactstrap/lib/ModalHeader.d.ts @@ -1,9 +1,12 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; wrapTag?: React.ReactType; toggle?: () => void; } declare var ModalHeader: React.StatelessComponent; -export default ModalHeader; \ No newline at end of file +export default ModalHeader; diff --git a/types/reactstrap/lib/Nav.d.ts b/types/reactstrap/lib/Nav.d.ts index 981d5087b8..72792c29aa 100644 --- a/types/reactstrap/lib/Nav.d.ts +++ b/types/reactstrap/lib/Nav.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + interface Props extends React.HTMLProps { inline?: boolean; disabled?: boolean; @@ -7,6 +9,7 @@ interface Props extends React.HTMLProps { navbar?: boolean; tag?: React.ReactType; className?: string; + cssModule?: CSSModule; vertical?: boolean; } diff --git a/types/reactstrap/lib/NavItem.d.ts b/types/reactstrap/lib/NavItem.d.ts index ee83c5477e..ced648169d 100644 --- a/types/reactstrap/lib/NavItem.d.ts +++ b/types/reactstrap/lib/NavItem.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var NavItem: React.StatelessComponent; -export default NavItem; \ No newline at end of file +export default NavItem; diff --git a/types/reactstrap/lib/NavLink.d.ts b/types/reactstrap/lib/NavLink.d.ts index f0117c387c..e9a7ea1ef8 100644 --- a/types/reactstrap/lib/NavLink.d.ts +++ b/types/reactstrap/lib/NavLink.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props extends React.HTMLProps { tag?: React.ReactType; disabled?: boolean; active?: boolean; className?: string; + cssModule?: CSSModule; onClick?: React.MouseEventHandler; href?: string; } diff --git a/types/reactstrap/lib/Navbar.d.ts b/types/reactstrap/lib/Navbar.d.ts index e25aa7bdcb..0e187426d8 100644 --- a/types/reactstrap/lib/Navbar.d.ts +++ b/types/reactstrap/lib/Navbar.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + interface Props { light?: boolean; inverse?: boolean; @@ -8,8 +10,9 @@ interface Props { role?: string; tag?: React.ReactType; className?: string; + cssModule?: CSSModule; toggleable?: boolean | string; } declare var Navbar: React.StatelessComponent; -export default Navbar; \ No newline at end of file +export default Navbar; diff --git a/types/reactstrap/lib/NavbarBrand.d.ts b/types/reactstrap/lib/NavbarBrand.d.ts index c99fba6673..6af6777533 100644 --- a/types/reactstrap/lib/NavbarBrand.d.ts +++ b/types/reactstrap/lib/NavbarBrand.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface NavbarBrand { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var NavbarBrand: React.StatelessComponent>; -export default NavbarBrand; \ No newline at end of file +export default NavbarBrand; diff --git a/types/reactstrap/lib/NavbarToggler.d.ts b/types/reactstrap/lib/NavbarToggler.d.ts index 083e2920aa..4372607830 100644 --- a/types/reactstrap/lib/NavbarToggler.d.ts +++ b/types/reactstrap/lib/NavbarToggler.d.ts @@ -1,10 +1,13 @@ +import {CSSModule} from '../index'; + interface Props extends React.HTMLProps { tag?: React.ReactType; type?: string; className?: string; + cssModule?: CSSModule; right?: boolean; left?: boolean; } declare var NavbarToggler: React.StatelessComponent; -export default NavbarToggler; \ No newline at end of file +export default NavbarToggler; diff --git a/types/reactstrap/lib/Pagination.d.ts b/types/reactstrap/lib/Pagination.d.ts index c7f621f109..1a7eecb356 100644 --- a/types/reactstrap/lib/Pagination.d.ts +++ b/types/reactstrap/lib/Pagination.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { className?: string; + cssModule?: CSSModule; size?: string; } declare var Pagination: React.StatelessComponent; -export default Pagination; \ No newline at end of file +export default Pagination; diff --git a/types/reactstrap/lib/PaginationItem.d.ts b/types/reactstrap/lib/PaginationItem.d.ts index 9a85a09891..69f9f0e286 100644 --- a/types/reactstrap/lib/PaginationItem.d.ts +++ b/types/reactstrap/lib/PaginationItem.d.ts @@ -1,9 +1,12 @@ +import {CSSModule} from '../index'; + interface Props { className?: string; + cssModule?: CSSModule; active?: boolean; disabled?: boolean; tag?: React.ReactType; } declare var PaginationItem: React.StatelessComponent; -export default PaginationItem; \ No newline at end of file +export default PaginationItem; diff --git a/types/reactstrap/lib/PaginationLink.d.ts b/types/reactstrap/lib/PaginationLink.d.ts index a075aa6305..e3429ceb7b 100644 --- a/types/reactstrap/lib/PaginationLink.d.ts +++ b/types/reactstrap/lib/PaginationLink.d.ts @@ -1,10 +1,13 @@ +import {CSSModule} from '../index'; + interface Props extends React.HTMLProps { 'aria-label'?: string; className?: string; + cssModule?: CSSModule; next?: boolean; previous?: boolean; tag?: React.ReactType; } declare var PaginationLink: React.StatelessComponent; -export default PaginationLink; \ No newline at end of file +export default PaginationLink; diff --git a/types/reactstrap/lib/Popover.d.ts b/types/reactstrap/lib/Popover.d.ts index a1c7f30603..50d3bbd5fc 100644 --- a/types/reactstrap/lib/Popover.d.ts +++ b/types/reactstrap/lib/Popover.d.ts @@ -1,5 +1,7 @@ /// +import {CSSModule} from '../index'; + type Placement = 'top' | 'bottom' @@ -24,8 +26,9 @@ interface Props { isOpen?: boolean; tether?: Tether.ITetherOptions; className?: string; + cssModule?: CSSModule; toggle?: () => void; } declare var Popover: React.StatelessComponent; -export default Popover; \ No newline at end of file +export default Popover; diff --git a/types/reactstrap/lib/PopoverContent.d.ts b/types/reactstrap/lib/PopoverContent.d.ts index 5344b41804..9104824756 100644 --- a/types/reactstrap/lib/PopoverContent.d.ts +++ b/types/reactstrap/lib/PopoverContent.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var PopoverContent: React.StatelessComponent; -export default PopoverContent; \ No newline at end of file +export default PopoverContent; diff --git a/types/reactstrap/lib/PopoverTitle.d.ts b/types/reactstrap/lib/PopoverTitle.d.ts index 6c837868e6..ea1a01f415 100644 --- a/types/reactstrap/lib/PopoverTitle.d.ts +++ b/types/reactstrap/lib/PopoverTitle.d.ts @@ -1,7 +1,10 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var PopoverTitle: React.StatelessComponent; -export default PopoverTitle; \ No newline at end of file +export default PopoverTitle; diff --git a/types/reactstrap/lib/Progress.d.ts b/types/reactstrap/lib/Progress.d.ts index ea01393b3c..b8b683f5ae 100644 --- a/types/reactstrap/lib/Progress.d.ts +++ b/types/reactstrap/lib/Progress.d.ts @@ -1,3 +1,5 @@ +import {CSSModule} from '../index'; + interface Props { bar?: boolean; multi?: boolean; @@ -8,8 +10,9 @@ interface Props { striped?: boolean; color?: string; className?: string; + cssModule?: CSSModule; barClassName?: string; } declare var Progress: React.StatelessComponent; -export default Progress; \ No newline at end of file +export default Progress; diff --git a/types/reactstrap/lib/Row.d.ts b/types/reactstrap/lib/Row.d.ts index 61529c4a48..5b52a3fb71 100644 --- a/types/reactstrap/lib/Row.d.ts +++ b/types/reactstrap/lib/Row.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props extends React.HTMLProps< HTMLElement> { className?: string; + cssModule?: CSSModule; tag?: React.ReactType; noGutters?: boolean; } declare var Row: React.StatelessComponent; -export default Row; \ No newline at end of file +export default Row; diff --git a/types/reactstrap/lib/TabContent.d.ts b/types/reactstrap/lib/TabContent.d.ts index 7e5f9120c0..69fe513818 100644 --- a/types/reactstrap/lib/TabContent.d.ts +++ b/types/reactstrap/lib/TabContent.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; activeTab?: number | string; className?: string; + cssModule?: CSSModule; } declare var TabContent: React.StatelessComponent; -export default TabContent; \ No newline at end of file +export default TabContent; diff --git a/types/reactstrap/lib/TabPane.d.ts b/types/reactstrap/lib/TabPane.d.ts index 9add666c8e..d53961d5ff 100644 --- a/types/reactstrap/lib/TabPane.d.ts +++ b/types/reactstrap/lib/TabPane.d.ts @@ -1,8 +1,11 @@ +import {CSSModule} from '../index'; + interface Props { tag?: React.ReactType; className?: string; + cssModule?: CSSModule; tabId?: number | string; } declare var TabPane: React.StatelessComponent; -export default TabPane; \ No newline at end of file +export default TabPane; diff --git a/types/reactstrap/lib/Table.d.ts b/types/reactstrap/lib/Table.d.ts index 9c3f27abe8..970282dd9b 100644 --- a/types/reactstrap/lib/Table.d.ts +++ b/types/reactstrap/lib/Table.d.ts @@ -1,5 +1,8 @@ +import {CSSModule} from '../index'; + interface Props { className?: string; + cssModule?: CSSModule; size?: string; bordered?: boolean; striped?: boolean; @@ -12,4 +15,4 @@ interface Props { } declare var Table: React.StatelessComponent; -export default Table; \ No newline at end of file +export default Table; diff --git a/types/reactstrap/lib/Tag.d.ts b/types/reactstrap/lib/Tag.d.ts index 1ea80359aa..b3c7ca77ff 100644 --- a/types/reactstrap/lib/Tag.d.ts +++ b/types/reactstrap/lib/Tag.d.ts @@ -1,9 +1,12 @@ +import {CSSModule} from '../index'; + interface Props { color?: string; pill?: boolean; tag?: React.ReactType; className?: string; + cssModule?: CSSModule; } declare var Tag: React.StatelessComponent; -export default Tag; \ No newline at end of file +export default Tag; diff --git a/types/reactstrap/lib/TetherContent.d.ts b/types/reactstrap/lib/TetherContent.d.ts index 46a6a7745a..e372a77f07 100644 --- a/types/reactstrap/lib/TetherContent.d.ts +++ b/types/reactstrap/lib/TetherContent.d.ts @@ -1,7 +1,10 @@ /// +import {CSSModule} from '../index'; + interface Props { className?: string; + cssModule?: CSSModule; arrow?: string; disabled?: boolean; isOpen: boolean; @@ -12,4 +15,4 @@ interface Props { } declare var TetherContent: React.StatelessComponent; -export default TetherContent; \ No newline at end of file +export default TetherContent; diff --git a/types/reactstrap/lib/Tooltip.d.ts b/types/reactstrap/lib/Tooltip.d.ts index 19b45a581e..df8987e36d 100644 --- a/types/reactstrap/lib/Tooltip.d.ts +++ b/types/reactstrap/lib/Tooltip.d.ts @@ -1,5 +1,7 @@ /// +import {CSSModule} from '../index'; + type Placement = 'top' | 'bottom' @@ -25,6 +27,7 @@ export interface UncontrolledProps { tether?: Tether.ITetherOptions; tetherRef?: (tether: Tether) => void; className?: string; + cssModule?: CSSModule; autohide?: boolean; delay?: number | { show: number, hide: number }; } @@ -37,4 +40,4 @@ interface Props extends UncontrolledProps { declare var Tooltip: React.StatelessComponent; -export default Tooltip; \ No newline at end of file +export default Tooltip; diff --git a/types/reactstrap/reactstrap-tests.tsx b/types/reactstrap/reactstrap-tests.tsx index b3a8b03838..3e310c3f5e 100644 --- a/types/reactstrap/reactstrap-tests.tsx +++ b/types/reactstrap/reactstrap-tests.tsx @@ -3286,3 +3286,13 @@ function Example106() { ); } + +const CSSModuleExample = (props: any) => { + const cssModule = { + btn: 'hash' + }; + + return ( + + ); +}; From 45a98df70005501e6a7c94939afe85de0062187b Mon Sep 17 00:00:00 2001 From: Adam Lavin Date: Mon, 17 Jul 2017 19:24:12 +0100 Subject: [PATCH 0088/1139] Updated react-maskedinput for 4.0.0 (#18058) * Updated react-maskedinput for 4.0.0 * Add namespace back in, change the way component class is defined * Removed namespaces and export interfaces --- types/react-maskedinput/index.d.ts | 45 +++++++++---------- .../react-maskedinput-tests.tsx | 2 +- 2 files changed, 21 insertions(+), 26 deletions(-) diff --git a/types/react-maskedinput/index.d.ts b/types/react-maskedinput/index.d.ts index a8efa75a00..9dfdd6b91f 100644 --- a/types/react-maskedinput/index.d.ts +++ b/types/react-maskedinput/index.d.ts @@ -1,31 +1,26 @@ -// Type definitions for react-maskedinput 3.3 +// Type definitions for react-maskedinput 4.0 // Project: https://github.com/insin/react-maskedinput -// Definitions by: Karol Janyst +// Definitions by: Karol Janyst , +// Adam Lavin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { ComponentClass, HTMLAttributes } from "react"; +import * as React from "react"; -export as namespace MaskedInput; - -export = MaskedInput; - -declare const MaskedInput: MaskedInput; -type MaskedInput = ComponentClass; - -declare namespace MaskedInput { - interface FormatCharacter { - validate(char: string): string; - transform?(char: string): string; - } - - interface CharsFormatters { - [char: string]: FormatCharacter; - } - - interface MaskedInputProps extends HTMLAttributes { - mask: string; - formatCharacter?: CharsFormatters; - placeholderChar?: string; - } +export interface FormatCharacter { + validate(char: string): string; + transform?(char: string): string; } + +export interface CharsFormatters { + [char: string]: FormatCharacter; +} + +export interface MaskedInputProps extends React.HTMLAttributes { + mask: string; + formatCharacter?: CharsFormatters; + placeholderChar?: string; +} + +declare class MaskedInput extends React.Component {} +export default MaskedInput; diff --git a/types/react-maskedinput/react-maskedinput-tests.tsx b/types/react-maskedinput/react-maskedinput-tests.tsx index 3220f79882..cc0a12dcaf 100644 --- a/types/react-maskedinput/react-maskedinput-tests.tsx +++ b/types/react-maskedinput/react-maskedinput-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import * as MaskedInput from "react-maskedinput"; +import MaskedInput from "react-maskedinput"; class Test extends React.Component { render() { From a51f7ddc22892e2e2f4b94f03dd96636cc6d9a32 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 17 Jul 2017 20:26:12 +0200 Subject: [PATCH 0089/1139] [cucumber] fix confusing import --- types/svg4everybody/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/svg4everybody/index.d.ts b/types/svg4everybody/index.d.ts index 3b1ec96cff..376d10befb 100644 --- a/types/svg4everybody/index.d.ts +++ b/types/svg4everybody/index.d.ts @@ -3,12 +3,11 @@ // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { Svg4everybodyOpts } from "svg4everybody"; export as namespace svg4everybody; export = svg4everybody; -declare function svg4everybody(options?: Svg4everybodyOpts): void; +declare function svg4everybody(options?: svg4everybody.Svg4everybodyOpts): void; declare namespace svg4everybody { interface Svg4everybodyOpts { From df53469ea40d1c34bf5ba557426811b70c69f5ac Mon Sep 17 00:00:00 2001 From: Tom Crockett Date: Mon, 17 Jul 2017 11:37:16 -0700 Subject: [PATCH 0090/1139] [react-dropzone] Fix definitions URL --- types/react-dropzone/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-dropzone/index.d.ts b/types/react-dropzone/index.d.ts index 8225fa4ab8..c2ab8820de 100644 --- a/types/react-dropzone/index.d.ts +++ b/types/react-dropzone/index.d.ts @@ -5,7 +5,7 @@ // Luís Rodrigues , // Ben Bayard , // Karol Janyst -// Definitions: https://github.com/Vooban/DefinitelyTyped +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { CSSProperties, Component, DragEvent, InputHTMLAttributes } from "react"; From 095044055a5f547df00eccf1b330ccbdd6b5785f Mon Sep 17 00:00:00 2001 From: Maarten Mulders Date: Mon, 17 Jul 2017 21:12:55 +0200 Subject: [PATCH 0091/1139] Remove types-metadata.json, appears it shouldn't be under VC --- types/recharts/types-metadata.json | 25 ------------------------- 1 file changed, 25 deletions(-) delete mode 100644 types/recharts/types-metadata.json diff --git a/types/recharts/types-metadata.json b/types/recharts/types-metadata.json deleted file mode 100644 index 795b5eb678..0000000000 --- a/types/recharts/types-metadata.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "authors": "Maarten Mulders ", - "libraryDependencies": [ - "react" - ], - "moduleDependencies": [], - "libraryMajorVersion": 0, - "libraryMinorVersion": 12, - "typeScriptVersion": "2.0", - "libraryName": "recharts", - "typingsPackageName": "recharts", - "projectName": "http://recharts.org/", - "sourceRepoURL": "https://www.github.com/DefinitelyTyped/DefinitelyTyped", - "sourceBranch": "master", - "globals": [ - ], - "declaredModules": [ - "recharts" - ], - "files": [ - "index.d.ts" - ], - "hasPackageJson": false, - "contentHash": "be2be503d947ebda48e7af156e1b24198540234a732125ceb62c14ce759d98d5" -} From da174820872d5b8786a3c70b29a4434be299d410 Mon Sep 17 00:00:00 2001 From: Ryota Kameoka Date: Tue, 18 Jul 2017 04:25:30 +0900 Subject: [PATCH 0092/1139] Fix type definition for REPL module of Node.js (#18021) * Fix signature for repl.start() function * Complete type definition for REPLServer.context property --- types/node/index.d.ts | 3 ++- types/node/v0/index.d.ts | 2 +- types/node/v4/index.d.ts | 2 +- types/node/v6/index.d.ts | 2 +- types/node/v7/index.d.ts | 3 ++- 5 files changed, 7 insertions(+), 5 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 77fb750551..e32a481b3c 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1593,6 +1593,7 @@ declare module "repl" { } export interface REPLServer extends readline.ReadLine { + context: any; defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; displayPrompt(preserveCursor?: boolean): void; @@ -1627,7 +1628,7 @@ declare module "repl" { prependOnceListener(event: "reset", listener: (...args: any[]) => void): this; } - export function start(options: ReplOptions): REPLServer; + export function start(options?: string | ReplOptions): REPLServer; } declare module "readline" { diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index 1e457a755e..5a383ce9db 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -810,7 +810,7 @@ declare module "repl" { ignoreUndefined?: boolean; writer?: Function; } - export function start(options: ReplOptions): events.EventEmitter; + export function start(options?: string | ReplOptions): events.EventEmitter; } declare module "readline" { diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 290a4b85a4..51197e1da4 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -972,7 +972,7 @@ declare module "repl" { ignoreUndefined?: boolean; writer?: Function; } - export function start(options: ReplOptions): events.EventEmitter; + export function start(options?: string | ReplOptions): events.EventEmitter; } declare module "readline" { diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index ada3a665b6..49a6cf98a5 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -1420,7 +1420,7 @@ declare module "repl" { prependOnceListener(event: "reset", listener: Function): this; } - export function start(options: ReplOptions): REPLServer; + export function start(options?: string | ReplOptions): REPLServer; } declare module "readline" { diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 256e700b02..207843eb3d 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -1448,6 +1448,7 @@ declare module "repl" { } export interface REPLServer extends readline.ReadLine { + context: any; defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; displayPrompt(preserveCursor?: boolean): void; @@ -1482,7 +1483,7 @@ declare module "repl" { prependOnceListener(event: "reset", listener: Function): this; } - export function start(options: ReplOptions): REPLServer; + export function start(options?: string | ReplOptions): REPLServer; } declare module "readline" { From de39637f41244812a0399a8affb4623d5313faa1 Mon Sep 17 00:00:00 2001 From: John Gainfort Jr Date: Mon, 17 Jul 2017 15:06:39 -0600 Subject: [PATCH 0093/1139] updated VastCreative interface and its extensions --- types/vast-client/index.d.ts | 59 ++++++++++++++++++-------- types/vast-client/vast-client-tests.ts | 7 +++ 2 files changed, 48 insertions(+), 18 deletions(-) diff --git a/types/vast-client/index.d.ts b/types/vast-client/index.d.ts index 79de29c6b0..680e1e2dd8 100644 --- a/types/vast-client/index.d.ts +++ b/types/vast-client/index.d.ts @@ -232,13 +232,36 @@ export interface VastError { } export interface VastCreative { - 0: VastCreativeLinear; - 1: VastCreativeCompanion; + id: string; + adId: string; + trackingEvents: VastTrackingEvents; + apiFramework: any; + sequence: any; + type: string; +} + +export interface VastCreativeLinear extends VastCreative { + adParameters: any; + duration: number; + icons: string[]; + mediaFiles: VastMediaFile[]; + skipDelay: boolean; + videoClickThroughURLTemplate: string; + videoClickTrackingURLTemplates: string[]; + videoCustomClickURLTempaltes: string[]; +} + +export interface VastCreativeNonLinear extends VastCreative { + variations: VastNonLinearAd[]; +} + +export interface VastCreativeCompanion extends VastCreative { + variations: VastCompanionAd[]; } export interface VastAd { advertiser: any; - creatives: VastCreative; + creatives: VastCreative[]; description: string; errorURLTemplates: string[]; extensions: VastAdExtension[]; @@ -271,22 +294,22 @@ export interface VastAdChildAttributes { name: string; } -export interface VastCreativeLinear { - adParameters: any; - duration: number; - icons: string[]; - mediaFiles: VastMediaFile[]; - skipDelay: boolean; - trackingEvents: VastTrackingEvents; +export interface VastNonLinearAd { + nonLinearClickTrackingURLTemplates: string[]; + nonLinearClickThroughURLTemplate: string; + adParameters: string; type: string; - videoClickThroughURLTemplate: string; - videoClickTrackingURLTemplates: string[]; - videoCustomClickURLTempaltes: string[]; -} - -export interface VastCreativeCompanion { - type: string; - variations: VastCompanionAd[]; + iframeResource: string; + htmlResource: string; + id: string; + width: string; + height: string; + expandedWidth: string; + expandedHeight: string; + scalablle: boolean; + maintainAspectRatio: boolean; + minSuggestedDuration: number; + apiFramework: any; } export interface VastCompanionAd { diff --git a/types/vast-client/vast-client-tests.ts b/types/vast-client/vast-client-tests.ts index eed1416c7a..aadf2c8370 100644 --- a/types/vast-client/vast-client-tests.ts +++ b/types/vast-client/vast-client-tests.ts @@ -5,6 +5,13 @@ function cb(response: DMVAST.VastResponse, error: Error): void { if (error) return; // process the VAST response const ads: DMVAST.VastAd[] = response.ads; + const linearCreative = response.ads[0].creatives.filter(creative => { + return creative.type === 'linear'; + }); + if (linearCreative && linearCreative.length > 0) { + const creative = linearCreative[0] as DMVAST.VastCreativeLinear; + const mediaFiles = creative.mediaFiles; + } } // CLIENT From b4f85d23f5c117ffcafddfd6fe1028da126f72ef Mon Sep 17 00:00:00 2001 From: Gilbert Handy Date: Mon, 17 Jul 2017 17:36:35 -0400 Subject: [PATCH 0094/1139] Added types for geodesy latlon-spherical.js --- types/geodesy/geodesy-tests.ts | 52 +++++++++++++++++++++++++++++++++- types/geodesy/index.d.ts | 25 ++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/types/geodesy/geodesy-tests.ts b/types/geodesy/geodesy-tests.ts index e3ce4f627a..984b8e80c2 100644 --- a/types/geodesy/geodesy-tests.ts +++ b/types/geodesy/geodesy-tests.ts @@ -4,7 +4,7 @@ import { Dms, Vector3d, OsGridRef, - LatLonEllipsoidal as LatLon } from 'geodesy'; + LatLonEllipsoidal as LatLon, LatLonSpherical } from 'geodesy'; /** * Mgrs @@ -115,3 +115,53 @@ OsGridRef.latLonToOsGrid(latlon); OsGridRef.osGridToLatLon(gridref); OsGridRef.osGridToLatLon(gridref, LatLon.datum.OSGB36); OsGridRef.parse('TG 51409 13177'); + +/** + * LatLonSpherical + */ +const point1 = new LatLonSpherical(52.205, 0.119); +const point2 = new LatLonSpherical(48.857, 2.351); + +point1.distanceTo(point2); // 404.3 km +point1.distanceTo(point2, 6371e3); // 404.3 km +point1.bearingTo(point2); // 156.2° +point1.finalBearingTo(point2); // 157.9° +point1.midpointTo(point2); // 50.5363°N, 001.2746°E +point1.intermediatePointTo(point2, 0.25); // 51.3721°N, 000.7073°E +point1.destinationPoint(7794, 300.7); // 51.5135°N, 000.0983°W +point1.destinationPoint(7794, 300.7, 6371e3); // 51.5135°N, 000.0983°W + +const ctCurrent = new LatLonSpherical(53.2611, -0.7972); +const ct1 = new LatLonSpherical(53.3206, -1.7297); +const ct2 = new LatLonSpherical(53.1887, 0.1334); +ctCurrent.crossTrackDistanceTo(ct1, ct2); // -307.5 m +ctCurrent.crossTrackDistanceTo(ct1, ct2, 6371e3); // -307.5 m + +point1.maxLatitude(156); + +const rhumb1 = new LatLonSpherical(51.127, 1.338); +const rhumb2 = new LatLonSpherical(50.964, 1.853); +rhumb1.rhumbDistanceTo(rhumb2); // 40.31 km +rhumb1.rhumbDistanceTo(rhumb2, 6371e3); // 40.31 km +rhumb1.rhumbBearingTo(rhumb2); // 116.7° +rhumb1.rhumbDestinationPoint(40300, 116.7); // 50.9642°N, 001.8530°E +rhumb1.rhumbDestinationPoint(40300, 116.7, 6371e3); // 50.9642°N, 001.8530°E +rhumb1.rhumbMidpointTo(rhumb2); // 51.0455°N, 001.5957°E + +const eq1 = new LatLonSpherical(52.205, 0.119); +const eq2 = new LatLonSpherical(52.205, 0.119); +eq1.equals(eq2); // true + +eq1.toString(); +eq1.toString('dm'); +eq1.toString('d', 0); + +// Static functions +const brng1 = 108.547; +const brng2 = 32.435; +LatLonSpherical.intersection(point1, brng1, point2, brng2); // 50.9078°N, 004.5084°E +LatLonSpherical.crossingParallels(point1, point2, 30); + +const polygon = [new LatLonSpherical(0, 0), new LatLonSpherical(1, 0), new LatLonSpherical(0, 1)]; +LatLonSpherical.areaOf(polygon); // 6.18e9 m² +LatLonSpherical.areaOf(polygon, 6371e3); // 6.18e9 m² diff --git a/types/geodesy/index.d.ts b/types/geodesy/index.d.ts index 12adb4d7c1..be4d183526 100644 --- a/types/geodesy/index.d.ts +++ b/types/geodesy/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for geodesy 1.1 // Project: https://github.com/chrisveness/geodesy // Definitions by: Denis Carriere + Gilbert Handy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export type format = 'd' | 'dm' | 'dms'; @@ -147,3 +148,27 @@ export class LatLonEllipsoidal { static datum: Datums; static ellipsoid: Ellipsoids; } + +export class LatLonSpherical { + lat: number; + lon: number; + constructor(lat: number, lon: number) + distanceTo(point: LatLonSpherical, radius?: number): number; + bearingTo(point: LatLonSpherical): number; + finalBearingTo(point: LatLonSpherical): number; + midpointTo(point: LatLonSpherical): number; + intermediatePointTo(point: LatLonSpherical, fraction: number): LatLonSpherical; + destinationPoint(distance: number, bearing: number, radius?: number): LatLonSpherical; + static intersection(point1: LatLonSpherical, bearing1: number, point2: LatLonSpherical, bearing2: number): LatLonSpherical; + crossTrackDistanceTo(pathStart: LatLonSpherical, pathEnd: LatLonSpherical, radius?: number): number; + maxLatitude(bearing: number): number; + static crossingParallels(point1: LatLonSpherical, point2: LatLonSpherical, latitude: number): any; + rhumbDistanceTo(point: LatLonSpherical, radius?: number): number; + rhumbBearingTo(point: LatLonSpherical): number; + rhumbDestinationPoint(distance: number, bearing: number, radius?: number): LatLonSpherical; + rhumbMidpointTo(point: LatLonSpherical): LatLonSpherical; + equals(point: LatLonSpherical): boolean; + static areaOf(polygon: LatLonSpherical[], radius?: number): number; + toString(format?: string, dp?: number): string; +} + From 03136f65c818d5f2d88e1c68b0162c28d0f95265 Mon Sep 17 00:00:00 2001 From: Gilbert Handy Date: Mon, 17 Jul 2017 17:51:40 -0400 Subject: [PATCH 0095/1139] Fix formatting issues --- types/geodesy/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/geodesy/index.d.ts b/types/geodesy/index.d.ts index be4d183526..1d8ef3e110 100644 --- a/types/geodesy/index.d.ts +++ b/types/geodesy/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for geodesy 1.1 // Project: https://github.com/chrisveness/geodesy // Definitions by: Denis Carriere - Gilbert Handy +// Gilbert Handy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export type format = 'd' | 'dm' | 'dms'; @@ -171,4 +171,3 @@ export class LatLonSpherical { static areaOf(polygon: LatLonSpherical[], radius?: number): number; toString(format?: string, dp?: number): string; } - From 4753cb27edd3ec639b46da8f1ac85884cc00e522 Mon Sep 17 00:00:00 2001 From: Benjamin Fox Date: Tue, 18 Jul 2017 10:26:14 +1200 Subject: [PATCH 0096/1139] Add basic method name type checking to sinon.spy and sinon.stub --- types/sinon/index.d.ts | 8 ++++---- types/sinon/sinon-tests.ts | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/types/sinon/index.d.ts b/types/sinon/index.d.ts index 75e87baae1..30a64b9d81 100644 --- a/types/sinon/index.d.ts +++ b/types/sinon/index.d.ts @@ -96,8 +96,8 @@ declare namespace Sinon { interface SinonSpyStatic { (): SinonSpy; - (func: any): SinonSpy; - (obj: any, method: string): SinonSpy; + (func: Function): SinonSpy; + (obj: T, method: keyof T): SinonSpy; } interface SinonStatic { @@ -153,8 +153,8 @@ declare namespace Sinon { interface SinonStubStatic { (): SinonStub; (obj: any): SinonStub; - (obj: any, method: string): SinonStub; - (obj: any, method: string, func: any): SinonStub; + (obj: T, method: keyof T): SinonStub; + (obj: T, method: keyof T, func: Function): SinonStub; } interface SinonStatic { diff --git a/types/sinon/sinon-tests.ts b/types/sinon/sinon-tests.ts index 406c790a2b..cd48901dd0 100644 --- a/types/sinon/sinon-tests.ts +++ b/types/sinon/sinon-tests.ts @@ -30,7 +30,7 @@ function testTwo() { function testThree() { let obj = { thisObj: true }; - let callback = sinon.spy({}, "method"); + let callback = sinon.spy({}, "method"); let proxy = once(callback); proxy.call(obj, callback, 1, 2, 3); if (callback.calledOn(obj)) { console.log("test3 calledOn success"); } else { console.log("test3 calledOn failure"); } @@ -168,7 +168,7 @@ function testSetMatcher() { } function testGetterStub() { - const myObj: any = { + const myObj = { prop: 'foo' }; @@ -177,7 +177,7 @@ function testGetterStub() { } function testSetterStub() { - const myObj: any = { + const myObj = { prop: 'foo', prop2: 'bar' }; @@ -187,7 +187,7 @@ function testSetterStub() { } function testValueStub() { - const myObj: any = { + const myObj = { prop: 'foo' }; From 44d2a8c028233808daa318ce2404f69f7b0fc773 Mon Sep 17 00:00:00 2001 From: Yaroslav Admin Date: Tue, 18 Jul 2017 00:33:24 +0200 Subject: [PATCH 0097/1139] Added types for jasmine_dom_matchers --- types/jasmine_dom_matchers/index.d.ts | 135 ++++++++++++++++++ .../jasmine_dom_matchers-tests.ts | 25 ++++ types/jasmine_dom_matchers/tsconfig.json | 23 +++ types/jasmine_dom_matchers/tslint.json | 1 + 4 files changed, 184 insertions(+) create mode 100644 types/jasmine_dom_matchers/index.d.ts create mode 100644 types/jasmine_dom_matchers/jasmine_dom_matchers-tests.ts create mode 100644 types/jasmine_dom_matchers/tsconfig.json create mode 100644 types/jasmine_dom_matchers/tslint.json diff --git a/types/jasmine_dom_matchers/index.d.ts b/types/jasmine_dom_matchers/index.d.ts new file mode 100644 index 0000000000..f463a5ebce --- /dev/null +++ b/types/jasmine_dom_matchers/index.d.ts @@ -0,0 +1,135 @@ +// Type definitions for jasmine_dom_matchers 1.4 +// Project: http://github.com/charleshansen/jasmine_dom_matchers +// Definitions by: Yaroslav Admin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +declare namespace jasmine { + interface Matchers { + /** + * Checks if element has visibility `hidden` or `height` or `width = 0`. + * + * The reverse of {@link toBeVisible}. + * + * @return {boolean} + */ + toBeHidden(): boolean; + + /** + * Checks if element has visibility style not `hidden` and both `height` and `width > 0`. + * + * The reverse of {@link toBeHidden}. + * + * @return {boolean} + */ + toBeVisible(): boolean; + + /** + * Checks element attributes. + * `attributeValue` is optional, if omitted, will check that the attribute exists. + * + * @param {string} attributeName + * @param {string | number | RegExp} attributeValue + * @return {boolean} + */ + toHaveAttr(attributeName: string, attributeValue?: string | number | RegExp): boolean; + + /** + * Checks element properties. + * `propertyValue` is optional, if omitted, will check that the property exists. + * + * @param {string} propertyName + * @param {string | number | RegExp} propertyValue + * @return {boolean} + */ + toHaveProp(propertyName: string, propertyValue?: string | number | RegExp): boolean; + + /** + * Checks if all styles are present. + * `styles` is an object, all styles given in that object will be checked. + * + * @param {{[p: string]: string | number | RegExp}} styles + * @return {boolean} + */ + toHaveCss(styles: { [ cssProperty: string]: string | number | RegExp }): boolean; + + /** + * Checks the `value` of eligible elements (like inputs). + * + * @param {string | number | RegExp} value + * @return {boolean} + */ + toHaveValue(value: string | number | RegExp): boolean; + + /** + * Checks if element has a `checked` property, only useful for checkbox inputs. + * + * @return {boolean} + */ + toBeChecked(): boolean; + + /** + * Checks if element is focused. + * + * @return {boolean} + */ + toBeFocused(): boolean; + + /** + * Checks if element has a `selected` property, only useful for options. + * + * @return {boolean} + */ + toBeSelected(): boolean; + + /** + * Checks if element has a disabled property. + * + * @return {boolean} + */ + toBeDisabled(): boolean; + + /** + * Checks for presence of classes on the element. + * If `className` is an Array, checks for all classes in the array. + * + * @param {string | string[]} className + * @return {boolean} + */ + toHaveClass(className: string | string[]): boolean; + + /** + * Checks for exact match with text, after trimming whitespace. + * + * @param {string | number | RegExp} text + * @return {boolean} + */ + toHaveText(text: string | number | RegExp): boolean; + + /** + * Checks if text substring is contained within element. + * + * @param {string | number | RegExp} text + * @return {boolean} + */ + toContainText(text: string | number | RegExp): boolean; + + /** + * Checks for length number of html elements. + * Also works for plain Arrays. + * + * @param {number} length + * @return {boolean} + */ + toHaveLength(length: number): boolean; + + /** + * True if the element exists, does not have to be in the DOM. + * + * @return {boolean} + */ + toExist(): boolean; + } +} diff --git a/types/jasmine_dom_matchers/jasmine_dom_matchers-tests.ts b/types/jasmine_dom_matchers/jasmine_dom_matchers-tests.ts new file mode 100644 index 0000000000..3edd13ec89 --- /dev/null +++ b/types/jasmine_dom_matchers/jasmine_dom_matchers-tests.ts @@ -0,0 +1,25 @@ +let input: HTMLInputElement = new HTMLInputElement(); +let paragraph: HTMLParagraphElement = new HTMLParagraphElement(); +let option: HTMLOptionElement = new HTMLOptionElement(); + +expect(paragraph).toBeHidden(); +expect(paragraph).toBeVisible(); +expect(paragraph).toHaveAttr('alt'); +expect(paragraph).toHaveAttr('alt', 'Some text'); +expect(paragraph).toHaveProp('alt'); +expect(paragraph).toHaveProp('alt', 'Some text'); +expect(paragraph).toHaveCss({ display: 'block' }); +expect(paragraph).toHaveCss({ lineHeight: 0 }); +expect(paragraph).toHaveCss({ fontSize: /px/ }); +expect(input).toHaveValue('42'); +expect(input).toBeChecked(); +expect(input).toBeFocused(); +expect(paragraph).toBeSelected(); +expect(input).toBeDisabled(); +expect(paragraph).toHaveClass('someClass'); +expect(paragraph).toHaveText('Some text'); +expect(paragraph).toContainText('text'); +expect(paragraph).toContainText(/text/); +expect(paragraph).toContainText(42); +expect(paragraph).toHaveLength(42); +expect(paragraph).toExist(); diff --git a/types/jasmine_dom_matchers/tsconfig.json b/types/jasmine_dom_matchers/tsconfig.json new file mode 100644 index 0000000000..30a9ab129d --- /dev/null +++ b/types/jasmine_dom_matchers/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jasmine_dom_matchers-tests.ts" + ] +} diff --git a/types/jasmine_dom_matchers/tslint.json b/types/jasmine_dom_matchers/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jasmine_dom_matchers/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 2cde2fb1edb6952211f4b555583810c106dadb94 Mon Sep 17 00:00:00 2001 From: Angus Jones Date: Tue, 18 Jul 2017 10:00:28 +1000 Subject: [PATCH 0098/1139] Remove [index: string]: any; in IRootScopeService To bring it into line with both the documentation (https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/angular#a-word-on-scope-and-assigning-new-members) and the general guidelines (https://github.com/Microsoft/TypeScript/issues/12596#issuecomment-299976171). --- types/angular/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/types/angular/index.d.ts b/types/angular/index.d.ts index b37e1ba421..fcfcf183e2 100644 --- a/types/angular/index.d.ts +++ b/types/angular/index.d.ts @@ -451,8 +451,6 @@ declare namespace angular { * see https://docs.angularjs.org/api/ng/type/$rootScope.Scope and https://docs.angularjs.org/api/ng/service/$rootScope */ interface IRootScopeService { - [index: string]: any; - $apply(): any; $apply(exp: string): any; $apply(exp: (scope: IScope) => any): any; From 868ee465adb872d1971ba34063072477bb4509d4 Mon Sep 17 00:00:00 2001 From: Neek Sandhu Date: Mon, 17 Jul 2017 17:03:36 -0700 Subject: [PATCH 0099/1139] Create tslint.json --- types/css-modules/tslint.json | 1 + 1 file changed, 1 insertion(+) create mode 100644 types/css-modules/tslint.json diff --git a/types/css-modules/tslint.json b/types/css-modules/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/css-modules/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c95f362fff5af1a00715472b65d35a460ae58c5a Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Tue, 18 Jul 2017 02:16:32 +0200 Subject: [PATCH 0100/1139] [http-proxy-middleware] fix incomplete/incorrect typings, fix lint issues, add missing tests --- .../http-proxy-middleware-tests.ts | 116 +++++++++++++++++- types/http-proxy-middleware/index.d.ts | 103 ++++++++-------- types/http-proxy-middleware/tslint.json | 3 + 3 files changed, 168 insertions(+), 54 deletions(-) create mode 100644 types/http-proxy-middleware/tslint.json diff --git a/types/http-proxy-middleware/http-proxy-middleware-tests.ts b/types/http-proxy-middleware/http-proxy-middleware-tests.ts index db331eec3d..3e932bb838 100644 --- a/types/http-proxy-middleware/http-proxy-middleware-tests.ts +++ b/types/http-proxy-middleware/http-proxy-middleware-tests.ts @@ -1,7 +1,7 @@ -// Derived from https://github.com/chimurai/http-proxy-middleware#example - -import * as express from 'express'; -import * as proxy from 'http-proxy-middleware'; +import express = require('express'); +import proxy = require('http-proxy-middleware'); +import { IncomingMessage } from "http"; +import * as Winston from "winston"; const options = { target: 'http://www.example.org', @@ -16,8 +16,112 @@ const options = { } }; -const myProxy = proxy(options); +// create the proxy (without context) +const exampleProxy = proxy(options); +// mount `exampleProxy` in web server const app = express(); -app.use('/api', myProxy); +app.use('/api', exampleProxy); app.listen(3000); + +proxy(options); +proxy('/', options); +proxy('/api', options); +proxy(['/api', '/ajax', '/someotherpath'], options); + +const filter = (pathname: string, req: IncomingMessage) => { + return !!(pathname.match('^/api') && req.method === 'GET'); +}; +const apiProxy = proxy(filter, {target: 'http://www.example.org'}); + +proxy({pathRewrite: {'^/old/api': '/new/api'}}); +proxy({ + pathRewrite(path, req) { + return path.replace('/api', '/base/api') || ''; + } +}); + +proxy({ + router: { + 'integration.localhost:3000': 'http://localhost:8001', + 'staging.localhost:3000': 'http://localhost:8002', + 'localhost:3000/api': 'http://localhost:8003', + '/rest': 'http://localhost:8004', + } +}); +proxy({ + router(req) { + return 'http://localhost:8004'; + } +}); + +proxy({logLevel: 'debug'}); + +proxy({ + logProvider(provider) { + return Winston; + } +}); +proxy({ + logProvider(provider) { + const logger = new (Winston.Logger)(); + + return { + log: logger.log, + debug: logger.debug, + info: logger.info, + warn: logger.warn, + error: logger.error + }; + } +}); + +proxy({ + onError(err, req, res) { + res.writeHead(500, { + 'Content-Type': 'text/plain' + }); + res.end('Something went wrong. And we are reporting a custom error message.'); + } +}); +proxy({ + onProxyRes(proxyRes, req, res) { + proxyRes.headers['x-added'] = 'foobar'; + delete proxyRes.headers['x-removed']; + } +}); +proxy({ + onProxyReq(proxyReq, req, res) { + proxyReq.setHeader('x-added', 'foobar'); + } +}); +proxy({ + onProxyReqWs(proxyReq, req, socket, options, head) { + proxyReq.setHeader('X-Special-Proxy-Header', 'foobar'); + } +}); +proxy({ + onOpen(proxySocket) { + proxySocket.on('data', (data: Buffer) => { + }); + } +}); +proxy({ + onClose(res, socket, head) { + console.log('Client disconnected'); + } +}); + +proxy({cookieDomainRewrite: false}); +proxy({cookieDomainRewrite: "new.domain"}); +proxy({ + cookieDomainRewrite: { + "unchanged.domain": "unchanged.domain", + "old.domain": "new.domain", + "*": "" + } +}); + +proxy({ + headers: {host: 'www.example.org'} +}); diff --git a/types/http-proxy-middleware/index.d.ts b/types/http-proxy-middleware/index.d.ts index 516ba72709..47ebdd77fe 100644 --- a/types/http-proxy-middleware/index.d.ts +++ b/types/http-proxy-middleware/index.d.ts @@ -1,67 +1,74 @@ -// Type definitions for http-proxy-middleware +// Type definitions for http-proxy-middleware 0.17 // Project: https://github.com/chimurai/http-proxy-middleware // Definitions by: Zebulon McCorkle +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 /// -/// -import * as http from 'http'; -import * as net from 'net'; -import * as tls from 'tls'; -import * as connect from 'connect'; +import * as http from "http"; +import * as net from "net"; +import * as tls from "tls"; +import * as connect from "connect"; +import * as httpProxy from "http-proxy"; declare function proxy(config: proxy.Config): proxy.Proxy; -declare function proxy(contextOrUri: string, config: proxy.Config): proxy.Proxy; +declare function proxy(contextOrUri: string | string[] | proxy.Filter, config: proxy.Config): proxy.Proxy; declare namespace proxy { - type Logger = (...objs: any[]) => void; - export interface LogProvider { - log: Logger, - debug?: Logger, - info?: Logger, - warn?: Logger, - error?: Logger, + type Filter = (pathanme: string, req: http.IncomingMessage) => boolean; + type Logger = (...args: any[]) => void; + interface LogProvider { + log: Logger; + debug?: Logger; + info?: Logger; + warn?: Logger; + error?: Logger; } - export interface Config { - pathRewrite?: { [regexp: string]: string } | ((path: string, req: http.IncomingMessage) => string), - router?: { [hostOrPath: string]: string } | ((req: http.IncomingMessage) => string), - logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent', - logProvider?: (provider: LogProvider) => LogProvider, + interface Config { + pathRewrite?: { [regexp: string]: string } | ((path: string, req: http.IncomingMessage) => string); + router?: { [hostOrPath: string]: string } | ((req: http.IncomingMessage) => string); + logLevel?: 'debug' | 'info' | 'warn' | 'error' | 'silent'; + logProvider?(provider: LogProvider): LogProvider; - onError?: connect.HandleFunction, - onProxyRes?: (proxyRes: http.ServerResponse, req: http.IncomingMessage, res: http.ServerResponse) => void, - onProxyReq?: (proxyReq: http.ClientRequest, req: http.IncomingMessage, res: http.ServerResponse) => void, - onProxyReqWs?: (proxyReq: http.ClientRequest, req: http.IncomingMessage, socket: any, options: any, head: any) => void, // TODO: Figure out the types of the last 3 - onOpen?: (proxySocket: net.Socket) => void, - onClose?: (res: http.ServerResponse, socket: net.Socket) => void, + onError?(err: Error, req: http.IncomingMessage, res: http.ServerResponse): void; + onProxyRes?(proxyRes: http.IncomingMessage, req: http.IncomingMessage, res: http.ServerResponse): void; + onProxyReq?(proxyReq: http.ClientRequest, req: http.IncomingMessage, res: http.ServerResponse): void; + onProxyReqWs?(proxyReq: http.ClientRequest, req: http.IncomingMessage, socket: net.Socket, options: httpProxy.ServerOptions, head: any): void; + onOpen?(proxySocket: net.Socket): void; + onClose?(res: http.IncomingMessage, socket: net.Socket, head: any): void; - target?: string, - forward?: string, - agent?: http.Agent, - ssl?: tls.TlsOptions, - ws?: boolean, - xfwd?: boolean, - secure?: boolean, - toProxy?: boolean, - prependPath?: boolean, - ignorePath?: boolean, - localAddress?: string, - changeOrigin?: boolean, - auth?: string, - hostRewrite?: any, // TODO - autoRewrite?: any, // TODO - protocolRewrite?: any, // TODO - cookieDomainRewrite?: false | string | { [domain: string]: string }, - headers?: { [header: string]: string }, - proxyTimeout?: number, + target?: string; + forward?: string; + agent?: http.Agent; + ssl?: tls.TlsOptions; + ws?: boolean; + xfwd?: boolean; + secure?: boolean; + toProxy?: boolean; + prependPath?: boolean; + ignorePath?: boolean; + localAddress?: string; + changeOrigin?: boolean; + auth?: string; + hostRewrite?: string; + autoRewrite?: boolean; + protocolRewrite?: string; + cookieDomainRewrite?: false | string | { [domain: string]: string }; + headers?: { [header: string]: string }; + proxyTimeout?: number; + /** + * @deprecated + */ + proxyHost?: any; + /** + * @deprecated + */ + proxyTable?: any; } - export interface Proxy extends connect.NextHandleFunction { - - } + type Proxy = connect.NextHandleFunction; } export = proxy; diff --git a/types/http-proxy-middleware/tslint.json b/types/http-proxy-middleware/tslint.json new file mode 100644 index 0000000000..d88586e5bd --- /dev/null +++ b/types/http-proxy-middleware/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 3a9efcb75b2cf81bb4b876f4db1ee394a10983d2 Mon Sep 17 00:00:00 2001 From: Angus Date: Tue, 18 Jul 2017 11:50:28 +1000 Subject: [PATCH 0101/1139] Fixed failing tests --- .../angular-clipboard-tests.ts | 6 +++++- types/angular-locker/angular-locker-tests.ts | 7 ++++++- .../angular-material/angular-material-tests.ts | 18 +++++++++++------- types/angular-meteor/angular-meteor-tests.ts | 2 ++ types/angular-resource/index.d.ts | 4 ++-- .../angular-ui-scroll-tests.ts | 6 +++++- 6 files changed, 31 insertions(+), 12 deletions(-) diff --git a/types/angular-clipboard/angular-clipboard-tests.ts b/types/angular-clipboard/angular-clipboard-tests.ts index b043a85d5a..00c5074ec5 100644 --- a/types/angular-clipboard/angular-clipboard-tests.ts +++ b/types/angular-clipboard/angular-clipboard-tests.ts @@ -1,8 +1,12 @@ import * as angular from "angular"; import {ClipboardService} from "angular-clipboard"; +interface TestScope extends ng.IScope { + [index: string]: any; +} + const app = angular.module('testModule', ['angular-clipboard']); -app.controller('TestController', ($scope: ng.IScope, clipboard: ClipboardService) => { +app.controller('TestController', ($scope: TestScope, clipboard: ClipboardService) => { $scope['testCopy'] = () => { if (clipboard.supported) { clipboard.copyText('hiiiiiii'); diff --git a/types/angular-locker/angular-locker-tests.ts b/types/angular-locker/angular-locker-tests.ts index a82f6a86cb..368dd1d308 100644 --- a/types/angular-locker/angular-locker-tests.ts +++ b/types/angular-locker/angular-locker-tests.ts @@ -1,5 +1,10 @@ import * as angular from 'angular'; + +interface TestScope extends angular.IScope { + [index: string]: any; +} + angular .module('angular-locker-tests', ['angular-locker']) .config(['lockerProvider', function config(lockerProvider: angular.locker.ILockerProvider) { @@ -13,7 +18,7 @@ angular lockerProvider.defaults(lockerSettings); }]) -.controller('LockerController', ['$scope', 'locker', function ($scope: angular.IScope, locker: angular.locker.ILockerService) { +.controller('LockerController', ['$scope', 'locker', function ($scope: TestScope, locker: angular.locker.ILockerService) { locker.put('someKey', 'someVal'); // put an item into session storage diff --git a/types/angular-material/angular-material-tests.ts b/types/angular-material/angular-material-tests.ts index d1af7c8159..5766a81975 100644 --- a/types/angular-material/angular-material-tests.ts +++ b/types/angular-material/angular-material-tests.ts @@ -1,5 +1,9 @@ const myApp = angular.module('testModule', ['ngMaterial']); +interface TestScope extends ng.IScope { + [index: string]: any; +} + myApp.config(( $mdThemingProvider: ng.material.IThemingProvider, $mdIconProvider: ng.material.IIconProvider, @@ -50,7 +54,7 @@ myApp.config(( }); }); -myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng.material.IBottomSheetService, $q: ng.IQService) => { +myApp.controller('BottomSheetController', ($scope: TestScope, $mdBottomSheet: ng.material.IBottomSheetService, $q: ng.IQService) => { $scope['openBottomSheet'] = () => { $mdBottomSheet.show({ template: 'Hello!', @@ -84,7 +88,7 @@ myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng $scope['cancelBottomSheet'] = $mdBottomSheet.cancel.bind($mdBottomSheet, 'cancel'); }); -myApp.controller('ColorController', ($scope: ng.IScope, $mdColor: ng.material.IColorService) => { +myApp.controller('ColorController', ($scope: TestScope, $mdColor: ng.material.IColorService) => { const colorExpression: ng.material.IColorExpression = { color: '#FFFFFF' }; const element: Element = new Element(); @@ -99,7 +103,7 @@ myApp.controller('ColorController', ($scope: ng.IScope, $mdColor: ng.material.IC }; }); -myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.IDialogService, $q: ng.IQService) => { +myApp.controller('DialogController', ($scope: TestScope, $mdDialog: ng.material.IDialogService, $q: ng.IQService) => { $scope['openDialog'] = () => { $mdDialog.show({ template: 'Hello!' @@ -201,7 +205,7 @@ class IconDirective implements ng.IDirective { } myApp.directive('icon-directive', ($mdIcon: ng.material.IIcon) => new IconDirective($mdIcon)); -myApp.controller('MediaController', ($scope: ng.IScope, $mdMedia: ng.material.IMedia) => { +myApp.controller('MediaController', ($scope: TestScope, $mdMedia: ng.material.IMedia) => { $scope.$watch(() => $mdMedia('lg'), (big: boolean) => { $scope['bigScreen'] = big; }); @@ -210,7 +214,7 @@ myApp.controller('MediaController', ($scope: ng.IScope, $mdMedia: ng.material.IM $scope['anotherCustom'] = $mdMedia('max-width: 300px'); }); -myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.material.ISidenavService) => { +myApp.controller('SidenavController', ($scope: TestScope, $mdSidenav: ng.material.ISidenavService) => { const componentId = 'left'; $scope['toggle'] = () => $mdSidenav(componentId).toggle(); $scope['open'] = () => $mdSidenav(componentId).open(); @@ -229,7 +233,7 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia $scope['onClose'] = $mdSidenav(componentId).onClose(() => { }); }); -myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService, $q: ng.IQService) => { +myApp.controller('ToastController', ($scope: TestScope, $mdToast: ng.material.IToastService, $q: ng.IQService) => { $scope['openToast'] = () => { $mdToast.show($mdToast.simple().textContent('Hello!')); $mdToast.updateTextContent('New Content'); @@ -260,7 +264,7 @@ myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IT }; }); -myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService, $q: ng.IQService) => { +myApp.controller('PanelController', ($scope: TestScope, $mdPanel: ng.material.IPanelService, $q: ng.IQService) => { $scope['createPanel'] = () => { const config: ng.material.IPanelConfig = { id: 'myPanel', diff --git a/types/angular-meteor/angular-meteor-tests.ts b/types/angular-meteor/angular-meteor-tests.ts index 6a379b8bac..21cbb4e3a3 100644 --- a/types/angular-meteor/angular-meteor-tests.ts +++ b/types/angular-meteor/angular-meteor-tests.ts @@ -27,6 +27,8 @@ interface CustomScope extends angular.meteor.IScope { removeAll: () => void; removeAuto: (todo: ITodo) => void; toSticky: (todo: ITodo) => void; + + picture: any; } var Todos = new Mongo.Collection('todos'); diff --git a/types/angular-resource/index.d.ts b/types/angular-resource/index.d.ts index b95911ae2c..4bdc8cc007 100644 --- a/types/angular-resource/index.d.ts +++ b/types/angular-resource/index.d.ts @@ -53,14 +53,14 @@ declare module 'angular' { interface IActionHash { [action: string]: IActionDescriptor; } - + interface IResourceResponse { config: any; data: any; headers: any; resource: any; status: number; - statusText: string + statusText: string; } interface IResourceInterceptor { diff --git a/types/angular-ui-scroll/angular-ui-scroll-tests.ts b/types/angular-ui-scroll/angular-ui-scroll-tests.ts index e226b664bc..9be5609d16 100644 --- a/types/angular-ui-scroll/angular-ui-scroll-tests.ts +++ b/types/angular-ui-scroll/angular-ui-scroll-tests.ts @@ -23,8 +23,12 @@ namespace application { myApp.factory('DatasourceTest', factory); + interface TestScope extends ng.IScope { + [index: string]: any; + } + // demo/examples/adapter - myApp.controller('mainController', ['$scope', 'DatasourceTest', function($scope: ng.IScope, datasource: DatasourceTest) { + myApp.controller('mainController', ['$scope', 'DatasourceTest', function($scope: TestScope, datasource: DatasourceTest) { var firstListAdapter: ng.ui.IScrollAdapter, secondListAdapter: ng.ui.IScrollAdapter; $scope['datasource'] = datasource; From 3fc889ae586e15fd1b63000dd798ed313246a3a3 Mon Sep 17 00:00:00 2001 From: Ivica Veric Date: Mon, 17 Jul 2017 09:08:19 -0700 Subject: [PATCH 0102/1139] $$ returns an array of clients per documentation --- types/webdriverio/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/webdriverio/index.d.ts b/types/webdriverio/index.d.ts index 9f7a0e1be0..ea34a6c034 100644 --- a/types/webdriverio/index.d.ts +++ b/types/webdriverio/index.d.ts @@ -1561,7 +1561,7 @@ declare namespace WebdriverIO { $(selector: string): Client> & RawResult; $

(selector: string): Client

; - $$(selector: string): Client>> & Array>; + $$(selector: string): Array>> & Array>; $$

(selector: string): Client

; addCommand( From 1c3089e2a8d4cbc879a1e2bcb11a8d27cd040f2d Mon Sep 17 00:00:00 2001 From: Neek Sandhu Date: Mon, 17 Jul 2017 23:02:35 -0700 Subject: [PATCH 0103/1139] Update index.d.ts Add support for css pre-processors like `sass`, `less` etc. --- types/css-modules/index.d.ts | 47 ++++++++++++++++++++++++------------ 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/types/css-modules/index.d.ts b/types/css-modules/index.d.ts index 8b65145a52..7d7bd52abd 100644 --- a/types/css-modules/index.d.ts +++ b/types/css-modules/index.d.ts @@ -1,21 +1,38 @@ -// Type definitions for css-modules 1506 +// Type definitions for css-modules 1.0 // Project: https://github.com/css-modules/css-modules // Definitions by: NeekSandhu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +interface Stringifyable { + /** + * Stringifies the imported stylesheet for use with inline style tags + */ + toString(): string; +} +interface SelectorNode { + /** + * Returns the specific selector from imported stylesheet as string + */ + [key: string]: string; +} declare module '*.css' { - type Stringifyable = { - /** - * Stringifies the imported stylesheet for use with inline style tags - */ - toString: () => string - } - type SelectorNode = { - /** - * Returns the specific selector from imported stylesheet as string - */ - [key: string]: string - } - const styles: SelectorNode & Stringifyable - export default styles + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.scss' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.sass' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.less' { + const styles: SelectorNode & Stringifyable; + export default styles; } From ed7bf7126e9bb90bceeaa36324aa8d01692b89dc Mon Sep 17 00:00:00 2001 From: Neek Sandhu Date: Mon, 17 Jul 2017 23:03:38 -0700 Subject: [PATCH 0104/1139] Fulfill compliance with tslint.json --- types/css-modules/css-modules-tests.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/types/css-modules/css-modules-tests.ts b/types/css-modules/css-modules-tests.ts index 9456029319..5876f5beae 100644 --- a/types/css-modules/css-modules-tests.ts +++ b/types/css-modules/css-modules-tests.ts @@ -1,21 +1,21 @@ -import styles from './main.css' -import * as classNames from 'classnames' +import styles from './main.sass'; +import * as classNames from 'classnames'; class App { - private theme: string + private theme: string; constructor(theme: string) { - this.theme = theme + this.theme = theme; } render() { // as a style tag (using webpack's css-loader) - const tpl = `

` + const tpl = `
`; // or as scoped unique classes, also latest typescript versions allow prop access using dot like styles.darkUI instead of styles['darkUI'] return ` -
+
- ` + `; } } From e85330bab6a337f61cd7a245086df16bf22fdb88 Mon Sep 17 00:00:00 2001 From: smac89 Date: Tue, 18 Jul 2017 00:53:41 -0600 Subject: [PATCH 0105/1139] Updated merge streams to simply use readablestream rather than readwritestream because readablestream is a much better super type of the type of streams supported --- types/merge2/index.d.ts | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/types/merge2/index.d.ts b/types/merge2/index.d.ts index 3e9c30b6c9..67b2688058 100644 --- a/types/merge2/index.d.ts +++ b/types/merge2/index.d.ts @@ -1,23 +1,21 @@ -// Type definitions for merge2 v0.3.6 +// Type definitions for merge2 v1.1.0 // Project: https://github.com/teambition/merge2 // Definitions by: Tanguy Krotoff +// Chigozirim C. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +import {DuplexOptions} from 'stream'; -interface IOptions { - end?: boolean; - objectMode?: boolean; -} +type StreamType = NodeJS.ReadableStream | IMerge2Stream; interface IMerge2Stream extends NodeJS.ReadWriteStream { - add(...args: Array>): IMerge2Stream; + add(...args: Array>): IMerge2Stream; } -interface IMerge2 { - (...args: Array | IOptions>): IMerge2Stream; -} +declare function IMerge2 (...args: Array | DuplexOptions>): IMerge2Stream; -declare var _tmp: IMerge2; -export = _tmp; +declare namespace IMerge2 {} + +export = IMerge2; From eba786d187dabe0517ac57225624809bb923254f Mon Sep 17 00:00:00 2001 From: smac89 Date: Tue, 18 Jul 2017 00:54:17 -0600 Subject: [PATCH 0106/1139] Updated imports within the tests --- types/merge2/merge2-tests.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/types/merge2/merge2-tests.ts b/types/merge2/merge2-tests.ts index 8f95b82bda..c21db879a1 100644 --- a/types/merge2/merge2-tests.ts +++ b/types/merge2/merge2-tests.ts @@ -1,8 +1,5 @@ - - - -import gulp = require('gulp'); -import * as merge2 from "merge2"; +import * as gulp from 'gulp'; +import * as merge2 from 'merge2'; gulp.task('app-js', () => merge2( From 58a0af925b9f00bcb46514ed1cde3b402745b046 Mon Sep 17 00:00:00 2001 From: smac89 Date: Tue, 18 Jul 2017 01:08:29 -0600 Subject: [PATCH 0107/1139] Committing line feed changes --- types/css-modules/css-modules-tests.ts | 42 +++++++------- types/css-modules/index.d.ts | 76 +++++++++++++------------- types/css-modules/tsconfig.json | 42 +++++++------- 3 files changed, 80 insertions(+), 80 deletions(-) diff --git a/types/css-modules/css-modules-tests.ts b/types/css-modules/css-modules-tests.ts index 5876f5beae..e6479ba2d5 100644 --- a/types/css-modules/css-modules-tests.ts +++ b/types/css-modules/css-modules-tests.ts @@ -1,21 +1,21 @@ -import styles from './main.sass'; -import * as classNames from 'classnames'; - -class App { - private theme: string; - constructor(theme: string) { - this.theme = theme; - } - - render() { - // as a style tag (using webpack's css-loader) - const tpl = `
`; - // or as scoped unique classes, also latest typescript versions allow prop access using dot like styles.darkUI instead of styles['darkUI'] - return ` -
-
- `; - } -} +import styles from './main.sass'; +import * as classNames from 'classnames'; + +class App { + private theme: string; + constructor(theme: string) { + this.theme = theme; + } + + render() { + // as a style tag (using webpack's css-loader) + const tpl = `
`; + // or as scoped unique classes, also latest typescript versions allow prop access using dot like styles.darkUI instead of styles['darkUI'] + return ` +
+
+ `; + } +} diff --git a/types/css-modules/index.d.ts b/types/css-modules/index.d.ts index 7d7bd52abd..832ae27406 100644 --- a/types/css-modules/index.d.ts +++ b/types/css-modules/index.d.ts @@ -1,38 +1,38 @@ -// Type definitions for css-modules 1.0 -// Project: https://github.com/css-modules/css-modules -// Definitions by: NeekSandhu -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -interface Stringifyable { - /** - * Stringifies the imported stylesheet for use with inline style tags - */ - toString(): string; -} -interface SelectorNode { - /** - * Returns the specific selector from imported stylesheet as string - */ - [key: string]: string; -} - -declare module '*.css' { - const styles: SelectorNode & Stringifyable; - export default styles; -} - -declare module '*.scss' { - const styles: SelectorNode & Stringifyable; - export default styles; -} - -declare module '*.sass' { - const styles: SelectorNode & Stringifyable; - export default styles; -} - -declare module '*.less' { - const styles: SelectorNode & Stringifyable; - export default styles; -} +// Type definitions for css-modules 1.0 +// Project: https://github.com/css-modules/css-modules +// Definitions by: NeekSandhu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +interface Stringifyable { + /** + * Stringifies the imported stylesheet for use with inline style tags + */ + toString(): string; +} +interface SelectorNode { + /** + * Returns the specific selector from imported stylesheet as string + */ + [key: string]: string; +} + +declare module '*.css' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.scss' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.sass' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.less' { + const styles: SelectorNode & Stringifyable; + export default styles; +} diff --git a/types/css-modules/tsconfig.json b/types/css-modules/tsconfig.json index aff10df5a6..40a428a927 100644 --- a/types/css-modules/tsconfig.json +++ b/types/css-modules/tsconfig.json @@ -1,22 +1,22 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "css-modules-tests.ts" - ] +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "css-modules-tests.ts" + ] } \ No newline at end of file From c14f282ad2b02ffdc381b3fc8b9865a58bcb1817 Mon Sep 17 00:00:00 2001 From: smac89 Date: Tue, 18 Jul 2017 01:31:58 -0600 Subject: [PATCH 0108/1139] Added comments to the functions --- types/merge2/index.d.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/types/merge2/index.d.ts b/types/merge2/index.d.ts index 67b2688058..44b3aeaf21 100644 --- a/types/merge2/index.d.ts +++ b/types/merge2/index.d.ts @@ -11,9 +11,24 @@ import {DuplexOptions} from 'stream'; type StreamType = NodeJS.ReadableStream | IMerge2Stream; interface IMerge2Stream extends NodeJS.ReadWriteStream { + /** + * @brief Add more streams to an existing merged stream + * + * @param args streams to add + * + * @return The merged stream + */ add(...args: Array>): IMerge2Stream; } +/** + * @brief This function takes an arbitrary number of streams, but the duplexoption + * has to be the last parameter of the function. + * + * @param args The arguments + * + * @return A merged duplex stream + */ declare function IMerge2 (...args: Array | DuplexOptions>): IMerge2Stream; declare namespace IMerge2 {} From 6c49782ce42d0fea3b018c3c23761fc5ad0c279e Mon Sep 17 00:00:00 2001 From: william chang Date: Tue, 18 Jul 2017 15:55:50 +0800 Subject: [PATCH 0109/1139] [aws-lambda] S3CreateEvent.Records should be Array instead of Tuple --- types/aws-lambda/aws-lambda-tests.ts | 69 ++++++++++++++------------- types/aws-lambda/index.d.ts | 71 ++++++++++++++-------------- 2 files changed, 71 insertions(+), 69 deletions(-) diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 7f8b8fabdd..10b4fa1073 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -22,43 +22,44 @@ var snsEvtRec: AWSLambda.SNSEventRecord; var snsMsg: AWSLambda.SNSMessage; var snsMsgAttr: AWSLambda.SNSMessageAttribute; var snsMsgAttrs: AWSLambda.SNSMessageAttributes; -var S3CreateEvent: AWSLambda.S3CreateEvent = { - Records: [{ - eventVersion: 'string', - eventSource: 'string', - awsRegion: 'string', - eventTime: 'string', - eventName: 'string', - userIdentity: { - principalId: 'string' - }, - requestParameters: { - sourceIPAddress: 'string' - }, - responseElements: { - 'x-amz-request-id': 'string', - 'x-amz-id-2': 'string' - }, - s3: { - s3SchemaVersion: 'string', - configurationId: 'string', - bucket: { - name: 'string', - ownerIdentity: { - principalId: 'string' - }, - arn: 'string' +var S3EvtRec: AWSLambda.S3EventRecord = { + eventVersion: '2.0', + eventSource: 'aws:s3', + awsRegion: 'us-east-1', + eventTime: '1970-01-01T00:00:00.000Z', + eventName: 'ObjectCreated:Put', + userIdentity: { + principalId: 'AIDAJDPLRKLG7UEXAMPLE' + }, + requestParameters:{ + sourceIPAddress: '127.0.0.1' + }, + responseElements: { + 'x-amz-request-id': 'C3D13FE58DE4C810', + 'x-amz-id-2': 'FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD' + }, + s3: { + s3SchemaVersion: '1.0', + configurationId: 'testConfigRule', + bucket: { + name: 'mybucket', + ownerIdentity: { + principalId: 'A3NL1KOZZKExample' }, - object: { - key: 'string', - size: 1, - eTag: 'string', - versionId: 'string', - sequencer: 'string' - } + arn: 'arn:aws:s3:::mybucket' + }, + object: { + key: 'HappyFace.jpg', + size: 1024, + eTag: 'd41d8cd98f00b204e9800998ecf8427e', + versionId: '096fKKXTRTtl3on89fVO.nfljtsv6qko', + sequencer: '0055AED6DCD90281E5' } } - ] +}; + +var S3CreateEvent: AWSLambda.S3CreateEvent = { + Records: [S3EvtRec] }; var cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent; var cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent; diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index df8effb82b..1da094ac46 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for AWS Lambda // Project: http://docs.aws.amazon.com/lambda -// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath , Toby Hede , Rich Buggy , Yoriki Yamaguchi +// Definitions by: James Darbyshire , Michael Skarum , Stef Heyenrath , Toby Hede , Rich Buggy , Yoriki Yamaguchi , wwwy3y3 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // API Gateway "event" @@ -85,43 +85,44 @@ interface SNSEvent { * S3Create event * https://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html */ -interface S3CreateEvent { - Records: [{ - eventVersion: string; - eventSource: string; - awsRegion: string - eventTime: string; - eventName: string; - userIdentity: { - principalId: string; - }, - requestParameters: { - sourceIPAddress: string; - }, - responseElements: { - 'x-amz-request-id': string; - 'x-amz-id-2': string; - }, - s3: { - s3SchemaVersion: string; - configurationId: string; - bucket: { - name: string; - ownerIdentity: { - principalId: string; - }, - arn: string; +interface S3EventRecord { + eventVersion: string; + eventSource: string; + awsRegion: string + eventTime: string; + eventName: string; + userIdentity: { + principalId: string; + }, + requestParameters: { + sourceIPAddress: string; + }, + responseElements: { + 'x-amz-request-id': string; + 'x-amz-id-2': string; + }, + s3: { + s3SchemaVersion: string; + configurationId: string; + bucket: { + name: string; + ownerIdentity: { + principalId: string; }, - object: { - key: string; - size: number; - eTag: string; - versionId: string; - sequencer: string; - } + arn: string; + }, + object: { + key: string; + size: number; + eTag: string; + versionId: string; + sequencer: string; } } - ]; +} + +interface S3CreateEvent { + Records: Array; } /** From 352aa44c0ae255a06446286a68ba64eeff101a00 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Sat, 15 Jul 2017 12:27:54 +0200 Subject: [PATCH 0110/1139] Add react helpers to babel-types --- types/babel-types/babel-types-tests.ts | 27 ++++++++++++++++++++++++++ types/babel-types/index.d.ts | 13 +++++++++++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/types/babel-types/babel-types-tests.ts b/types/babel-types/babel-types-tests.ts index 5974a64885..394603ab31 100644 --- a/types/babel-types/babel-types-tests.ts +++ b/types/babel-types/babel-types-tests.ts @@ -29,3 +29,30 @@ t.assertBinaryExpression(ast); t.assertBinaryExpression(ast, { operator: "*" }); var exp: t.Expression = t.nullLiteral(); + +// React examples: + +// https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-plugin-transform-react-inline-elements/src/index.js#L61 +traverse(ast, { + JSXElement(path, file) { + const { node } = path; + const open = node.openingElement; + + // init + const type = open.name; + + let newType: t.StringLiteral; + if (t.isJSXIdentifier(type) && t.react.isCompatTag(type.name)) { + newType = t.stringLiteral(type.name); + } + + const args: any[] = []; + if (node.children.length) { + const children = t.react.buildChildren(node); + args.push( + t.unaryExpression("void", t.numericLiteral(0), true), + ...children, + ); + } + } +}); diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index 77ea8b54de..c3f77b559f 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for babel-types v6.7 +// Type definitions for babel-types v6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-types -// Definitions by: Troy Gerwien , Sam Baxter +// Definitions by: Troy Gerwien +// Sam Baxter +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface Comment { @@ -1226,6 +1228,13 @@ export function isUser(node: Object, opts?: Object): boolean; export function isGenerated(node: Object, opts?: Object): boolean; export function isPure(node: Object, opts?: Object): boolean; +// React specific +interface ReactHelpers { + isCompatTag(tagName?: string): boolean; + buildChildren(node: Object): Object[]; +} +export const react: ReactHelpers; + export function assertArrayExpression(node: Object, opts?: Object): void; export function assertAssignmentExpression(node: Object, opts?: Object): void; export function assertBinaryExpression(node: Object, opts?: Object): void; From 063908566cb59476420157b723d0068e092dd85c Mon Sep 17 00:00:00 2001 From: amiram Date: Tue, 18 Jul 2017 12:29:18 +0300 Subject: [PATCH 0111/1139] Add new KafkaClient more fixes to align with version 2 --- types/kafka-node/index.d.ts | 113 ++++++++++++++++++--------- types/kafka-node/kafka-node-tests.ts | 87 +++++++++++++++------ 2 files changed, 139 insertions(+), 61 deletions(-) diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index 06464d5602..ae1ced9f33 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -1,76 +1,73 @@ // Type definitions for kafka-node 1.3.3 // Project: https://github.com/SOHU-Co/kafka-node/ -// Definitions by: Daniel Imrie-Situnayake , Bill , Michael Haan +// Definitions by: Daniel Imrie-Situnayake , Bill , Michael Haan , Amiram Korach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - // # Classes export declare class Client { constructor(connectionString: string, clientId?: string, options?: ZKOptions, noBatchOptions?: AckBatchOptions, sslOptions?: any); close(callback?: Function): void; - topicExists(topics: Array, callback: Function): void; - refreshMetadata(topics: Array, cb?: (error: any, data: any) => any): void; - close(cb: (error: any) => any): void; - sendOffsetCommitV2Request(group: string, generationId: number, memberId: string, commits: Array, cb: (error: any, data: any) => any): void; + topicExists(topics: Array, callback: (err?: TopicsNotExistError | any) => any): void; + refreshMetadata(topics: Array, cb?: (error?: any) => any): void; + sendOffsetCommitV2Request(group: string, generationId: number, memberId: string, commits: Array, cb: Function): void; +} + +export declare class KafkaClient extends Client { + constructor(options?: KafkaClientOptions); + connect(): void; } export declare class Producer { - constructor(client: Client, options?: any, customPartitioner?: any); - on(eventName: string, cb: () => any): void; - on(eventName: string, cb: (error: any) => any): void; + constructor(client: Client, options?: ProducerOptions, customPartitioner?: any); + on(eventName: "ready", cb: () => any): void; + on(eventName: "error", cb: (error: any) => any): void; send(payloads: Array, cb: (error: any, data: any) => any): void; - createTopics(topics: Array, async: boolean, cb?: (error: any, data: any) => any): void; - close(cb: (error: any) => any): void; + createTopics(topics: Array, async: true, cb: (error?: any, data?: any) => any): void; + createTopics(topics: Array, async: false, cb: () => any): void; + createTopics(topics: Array, cb: (error?: any, data?: any) => any): void; + close(): void; } -export declare class HighLevelProducer { - constructor(client: Client, options?: any, customPartitioner?: any); - on(eventName: string, cb: () => any): void; - on(eventName: string, cb: (error: any) => any): void; - send(payloads: Array, cb: (error: any, data: any) => any): void; - createTopics(topics: Array, async: boolean, cb?: (error: any, data: any) => any): void; - close(cb: (error: any) => any): void; +export declare class HighLevelProducer extends Producer { } export declare class Consumer { - constructor(client: Client, fetchRequests: Array, options: ConsumerOptions); + constructor(client: Client, fetchRequests: Array, options: ConsumerOptions); client: Client; - on(eventName: string, cb: (message: string) => any): void; - on(eventName: string, cb: (error: any) => any): void; - addTopics(topics: Array, cb: (error: any, added: boolean) => any): void; - addTopics(topics: Array, cb: (error: any, added: boolean) => any, fromOffset: boolean): void; - removeTopics(topics: Array, cb: (error: any, removed: boolean) => any): void; + on(eventName: "message", cb: (message: Message) => any): void; + on(eventName: "error" | "offsetOutOfRange", cb: (error: any) => any): void; + addTopics(topics: Array | Array, cb: (error: any, added: Array | Array) => any): void; + addTopics(topics: Array | Array, cb: (error: any, added: Array | Array) => any, fromOffset: boolean): void; + removeTopics(topics: string | Array, cb: (error: any, removed: number) => any): void; commit(cb: (error: any, data: any) => any): void; + commit(force: boolean, cb: (error: any, data: any) => any): void; setOffset(topic: string, partition: number, offset: number): void; pause(): void; resume(): void; pauseTopics(topics: Array /* Array */): void; resumeTopics(topics: Array /* Array */): void; close(force: boolean, cb: () => any): void; + close(cb: () => any): void; } export declare class HighLevelConsumer { - constructor(client: Client, payloads: Array, options: ConsumerOptions); + constructor(client: Client, payloads: Array, options: HighLevelConsumerOptions); client: Client; - on(eventName: string, cb: (message: string) => any): void; - on(eventName: string, cb: (error: any) => any): void; - addTopics(topics: Array, cb: (error: any, added: boolean) => any): void; - addTopics(topics: Array, cb: (error: any, added: boolean) => any, fromOffset: boolean): void; - removeTopics(topics: Array, cb: (error: any, removed: boolean) => any): void; + on(eventName: "message", cb: (message: Message) => any): void; + on(eventName: "error" | "offsetOutOfRange", cb: (error: any) => any): void; + addTopics(topics: Array | Array, cb?: (error: any, added: Array | Array) => any): void; + removeTopics(topics: string | Array, cb: (error: any, removed: number) => any): void; commit(cb: (error: any, data: any) => any): void; + commit(force: boolean, cb: (error: any, data: any) => any): void; setOffset(topic: string, partition: number, offset: number): void; pause(): void; resume(): void; - pauseTopics(topics: Array /* Array */): void; - resumeTopics(topics: Array /* Array */): void; close(force: boolean, cb: () => any): void; + close(cb: () => any): void; } export declare class ConsumerGroup extends HighLevelConsumer { - constructor(options: ConsumerGroupOptions, topics: string[]); - on(eventName: string, cb: (message: string) => any): void; - on(eventName: string, cb: (error: any) => any): void; - close(force: boolean, cb: (error: any) => any): void; + constructor(options: ConsumerGroupOptions, topics: string[] | string); generationId: number; memberId: string; } @@ -91,6 +88,38 @@ export declare class KeyedMessage { } // # Interfaces + +export interface Message { + topic: string; + value: string; + offset: number; + partition: number; + highWaterOffset: number; + key: number; +} + +export interface ProducerOptions { + requireAcks?: number; + ackTimeoutMs?: number; + partitionerType?: number; +} + +export interface KafkaClientOptions { + kafkaHost?: string; + connectTimeout?: number; + requestTimeout?: number; + authConnect?: boolean; + connectRetryOptions?: ConnectRetryOptions; +} + +export interface ConnectRetryOptions { + retries?: number; + factor?: number; + minTimeout?: number; + maxTimeout?: number; + randomize?: boolean; +} + export interface AckBatchOptions { noAckBatchSize: number | null, noAckBatchAge: number | null @@ -112,7 +141,6 @@ export interface ProduceRequest { export interface ConsumerOptions { groupId?: string; - id?: string; autoCommit?: boolean; autoCommitIntervalMs?: number; fetchMaxWaitMs?: number; @@ -120,6 +148,11 @@ export interface ConsumerOptions { fetchMaxBytes?: number; fromOffset?: boolean; encoding?: string; + keyEncoding?: string; +} + +export interface HighLevelConsumerOptions extends ConsumerOptions { + id?: string; } export interface CustomPartitionAssignmentProtocol { @@ -134,7 +167,7 @@ export interface ConsumerGroupOptions { zk?: ZKOptions; batch?: AckBatchOptions; ssl?: boolean; - id: string; + id?: string; groupId: string; sessionTimeout?: number; protocol?: Array<"roundrobin" | "range" | CustomPartitionAssignmentProtocol>; @@ -180,3 +213,7 @@ export interface OffsetFetchRequest { partition?: number; offset?: number; } + +export declare class TopicsNotExistError extends Error { + topics: string | string[] +} diff --git a/types/kafka-node/kafka-node-tests.ts b/types/kafka-node/kafka-node-tests.ts index a348c8f771..8d99b98d63 100644 --- a/types/kafka-node/kafka-node-tests.ts +++ b/types/kafka-node/kafka-node-tests.ts @@ -12,9 +12,36 @@ var optionsClient = new kafka.Client('localhost:2181/', 'sendMessage', { }, { rejectUnauthorized: false }); +optionsClient.topicExists(['topic'], function (error: any){}); +optionsClient.refreshMetadata(['topic'], function (error: any){}); optionsClient.close(); +optionsClient.sendOffsetCommitV2Request('group', 0, 'memberId', [], function() {}); optionsClient.close(function(){}); +var basicKafkaClient = new kafka.KafkaClient(); + +var optionsKafkaClient = new kafka.KafkaClient({ + kafkaHost: 'localhost:2181', + connectTimeout: 1000, + requestTimeout: 1000, + authConnect: true, + connectRetryOptions: { + retries: 5, + factor: 0, + minTimeout: 1000, + maxTimeout: 1000, + randomize: true + } +}); + +optionsKafkaClient.connect(); + +var optionsProducer = new kafka.Producer(basicClient, { + requireAcks: 0, + ackTimeoutMs: 0, + partitionerType: 0 +}); + var producer = new kafka.Producer(basicClient); producer.on('error', function(error: Error){}); producer.on('ready', function(){ @@ -43,10 +70,10 @@ producer.on('ready', function(){ producer.send(messages, function(err: Error){}); producer.send(messages, function(err: Error, data: Object){}); - producer.createTopics(['t'], true, function (err: Error, data: Object) {}); - producer.createTopics(['t'], false, function (err, data) {}); - // producer.createTopics(['t'], function (err: Error, data: Object) {}); // Omitting middle argument is not possible in TS - + producer.createTopics(['t'], true, function (err: Error, data: any) {}); + producer.createTopics(['t'], function (err: Error, data: any) {}); + producer.createTopics(['t'], false, function () {}); + producer.close(); }); var highLevelProducer = new kafka.HighLevelProducer(basicClient); @@ -73,13 +100,13 @@ highLevelProducer.on('ready', function(){ messages: [new kafka.KeyedMessage('key', 'message')] }]; - producer.send(messages, function(err: Error){}); - producer.send(messages, function(err: Error, data: Object){}); - - producer.createTopics(['t'], true, function (err: Error, data: Object) {}); - producer.createTopics(['t'], false, function (err, data) {}); - // producer.createTopics(['t'], function (err: Error, data: Object) {}); // Omitting middle argument is not possible in TS + highLevelProducer.send(messages, function(err: Error){}); + highLevelProducer.send(messages, function(err: Error, data: Object){}); + producer.createTopics(['t'], true, function (err: Error, data: any) {}); + producer.createTopics(['t'], function (err: Error, data: any) {}); + producer.createTopics(['t'], false, function () {}); + producer.close(); }); var fetchRequests = [{ topic: 'awesome' }]; @@ -88,14 +115,24 @@ var consumer = new kafka.Consumer(basicClient, fetchRequests, { autoCommit: true }); consumer.on('error', function(error: Error){}); -consumer.on('message', function(message){}); +consumer.on('offsetOutOfRange', function(error: Error){}); +consumer.on('message', function(message: kafka.Message){ + var topic = message.topic; + var value = message.value; + var offset = message.offset; + var partition = message.partition; + var highWaterOffset = message.highWaterOffset; + var key = message.key; +}); consumer.addTopics(['t1', 't2'], function (err, added) {}); consumer.addTopics([{ topic: 't1', offset: 10 }], function (err, added) {}, true); -consumer.removeTopics(['t1', 't2'], function (err, removed) {}); +consumer.removeTopics(['t1', 't2'], function (err, removed: number) {}); +consumer.removeTopics('t2', function (err, removed: number) {}); consumer.commit(function (err, data) {}); +consumer.commit(true, function (err, data) {}); consumer.setOffset('topic', 0, 0); @@ -111,6 +148,7 @@ consumer.resumeTopics([ ]); consumer.close(true, function () {}); +consumer.close(function () {}); var fetchRequests = [{ topic: 'awesome' }]; var hlConsumer = new kafka.HighLevelConsumer(basicClient, fetchRequests, { @@ -119,28 +157,31 @@ var hlConsumer = new kafka.HighLevelConsumer(basicClient, fetchRequests, { }); hlConsumer.on('error', function(error: Error){}); -hlConsumer.on('message', function(message){}); +hlConsumer.on('offsetOutOfRange', function(error: Error){}); +hlConsumer.on('message', function(message: kafka.Message){ + var topic = message.topic; + var value = message.value; + var offset = message.offset; + var partition = message.partition; + var highWaterOffset = message.highWaterOffset; + var key = message.key; +}); hlConsumer.addTopics(['t1', 't2'], function (err, added) {}); -hlConsumer.addTopics([{ topic: 't1', offset: 10 }], function (err, added) {}, true); +hlConsumer.addTopics([{ topic: 't1', offset: 10 }], function (err, added) {}); -hlConsumer.removeTopics(['t1', 't2'], function (err, removed) {}); +hlConsumer.removeTopics(['t1', 't2'], function (err, removed: number) {}); +hlConsumer.removeTopics('t2', function (err, removed: number) {}); hlConsumer.commit(function (err, data) {}); +hlConsumer.commit(true, function (err, data) {}); hlConsumer.setOffset('topic', 0, 0); hlConsumer.pause(); hlConsumer.resume(); -hlConsumer.pauseTopics([ - 'topic1', - { topic: 'topic2', partition: 0 } -]); -hlConsumer.resumeTopics([ - 'topic1', - { topic: 'topic2', partition: 0 } -]); hlConsumer.close(true, function () {}); +hlConsumer.close(function () {}); var ackBatchOptions = {'noAckBatchSize': 1024, 'noAckBatchAge': 10}; var cgOptions: kafka.ConsumerGroupOptions = { From cc5bb4de9396a658ff12fdaf221cfec3932b3888 Mon Sep 17 00:00:00 2001 From: amiram Date: Tue, 18 Jul 2017 12:31:25 +0300 Subject: [PATCH 0112/1139] message properties optional --- types/kafka-node/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index ae1ced9f33..5fc3ef958e 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -92,10 +92,10 @@ export declare class KeyedMessage { export interface Message { topic: string; value: string; - offset: number; - partition: number; - highWaterOffset: number; - key: number; + offset?: number; + partition?: number; + highWaterOffset?: number; + key?: number; } export interface ProducerOptions { From 45cc08937da9f3d8f8524c050f97790a5fc5ad68 Mon Sep 17 00:00:00 2001 From: amiram Date: Tue, 18 Jul 2017 12:33:54 +0300 Subject: [PATCH 0113/1139] add tslint --- types/kafka-node/tsconfig.json | 4 ++-- types/kafka-node/tslint.json | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 types/kafka-node/tslint.json diff --git a/types/kafka-node/tsconfig.json b/types/kafka-node/tsconfig.json index f049d379df..616ae7507a 100644 --- a/types/kafka-node/tsconfig.json +++ b/types/kafka-node/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "kafka-node-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/kafka-node/tslint.json b/types/kafka-node/tslint.json new file mode 100644 index 0000000000..0967ef424b --- /dev/null +++ b/types/kafka-node/tslint.json @@ -0,0 +1 @@ +{} From 34f5e746e2a25d0769ce0c7bffb5768b06957b30 Mon Sep 17 00:00:00 2001 From: amiram Date: Tue, 18 Jul 2017 13:05:42 +0300 Subject: [PATCH 0114/1139] fix lint --- types/kafka-node/index.d.ts | 76 +++--- types/kafka-node/kafka-node-tests.ts | 335 +++++++++++++++------------ types/kafka-node/tslint.json | 4 +- 3 files changed, 229 insertions(+), 186 deletions(-) diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index 5fc3ef958e..5c93822a03 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -1,62 +1,61 @@ -// Type definitions for kafka-node 1.3.3 +// Type definitions for kafka-node 2.0 // Project: https://github.com/SOHU-Co/kafka-node/ // Definitions by: Daniel Imrie-Situnayake , Bill , Michael Haan , Amiram Korach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // # Classes -export declare class Client { +export class Client { constructor(connectionString: string, clientId?: string, options?: ZKOptions, noBatchOptions?: AckBatchOptions, sslOptions?: any); - close(callback?: Function): void; - topicExists(topics: Array, callback: (err?: TopicsNotExistError | any) => any): void; - refreshMetadata(topics: Array, cb?: (error?: any) => any): void; - sendOffsetCommitV2Request(group: string, generationId: number, memberId: string, commits: Array, cb: Function): void; + close(callback?: () => void): void; + topicExists(topics: string[], callback: (err?: TopicsNotExistError | any) => any): void; + refreshMetadata(topics: string[], cb?: (error?: any) => any): void; + sendOffsetCommitV2Request(group: string, generationId: number, memberId: string, commits: OffsetCommitRequest[], cb: () => void): void; } -export declare class KafkaClient extends Client { +export class KafkaClient extends Client { constructor(options?: KafkaClientOptions); connect(): void; } -export declare class Producer { +export class Producer { constructor(client: Client, options?: ProducerOptions, customPartitioner?: any); on(eventName: "ready", cb: () => any): void; on(eventName: "error", cb: (error: any) => any): void; - send(payloads: Array, cb: (error: any, data: any) => any): void; - createTopics(topics: Array, async: true, cb: (error?: any, data?: any) => any): void; - createTopics(topics: Array, async: false, cb: () => any): void; - createTopics(topics: Array, cb: (error?: any, data?: any) => any): void; + send(payloads: ProduceRequest[], cb: (error: any, data: any) => any): void; + createTopics(topics: string[], async: true, cb: (error?: any, data?: any) => any): void; + createTopics(topics: string[], async: false, cb: () => any): void; + createTopics(topics: string[], cb: (error?: any, data?: any) => any): void; close(): void; } -export declare class HighLevelProducer extends Producer { +export class HighLevelProducer extends Producer { } -export declare class Consumer { +export class Consumer { constructor(client: Client, fetchRequests: Array, options: ConsumerOptions); client: Client; on(eventName: "message", cb: (message: Message) => any): void; on(eventName: "error" | "offsetOutOfRange", cb: (error: any) => any): void; - addTopics(topics: Array | Array, cb: (error: any, added: Array | Array) => any): void; - addTopics(topics: Array | Array, cb: (error: any, added: Array | Array) => any, fromOffset: boolean): void; - removeTopics(topics: string | Array, cb: (error: any, removed: number) => any): void; + addTopics(topics: string[] | Topic[], cb: (error: any, added: string[] | Topic[]) => any, fromOffset?: boolean): void; + removeTopics(topics: string | string[], cb: (error: any, removed: number) => any): void; commit(cb: (error: any, data: any) => any): void; commit(force: boolean, cb: (error: any, data: any) => any): void; setOffset(topic: string, partition: number, offset: number): void; pause(): void; resume(): void; - pauseTopics(topics: Array /* Array */): void; - resumeTopics(topics: Array /* Array */): void; + pauseTopics(topics: any[] /* Array */): void; + resumeTopics(topics: any[] /* Array */): void; close(force: boolean, cb: () => any): void; close(cb: () => any): void; } -export declare class HighLevelConsumer { - constructor(client: Client, payloads: Array, options: HighLevelConsumerOptions); +export class HighLevelConsumer { + constructor(client: Client, payloads: Topic[], options: HighLevelConsumerOptions); client: Client; on(eventName: "message", cb: (message: Message) => any): void; on(eventName: "error" | "offsetOutOfRange", cb: (error: any) => any): void; - addTopics(topics: Array | Array, cb?: (error: any, added: Array | Array) => any): void; - removeTopics(topics: string | Array, cb: (error: any, removed: number) => any): void; + addTopics(topics: string[] | Topic[], cb?: (error: any, added: string[] | Topic[]) => any): void; + removeTopics(topics: string | string[], cb: (error: any, removed: number) => any): void; commit(cb: (error: any, data: any) => any): void; commit(force: boolean, cb: (error: any, data: any) => any): void; setOffset(topic: string, partition: number, offset: number): void; @@ -66,24 +65,23 @@ export declare class HighLevelConsumer { close(cb: () => any): void; } -export declare class ConsumerGroup extends HighLevelConsumer { +export class ConsumerGroup extends HighLevelConsumer { constructor(options: ConsumerGroupOptions, topics: string[] | string); generationId: number; memberId: string; } -export declare class Offset { +export class Offset { constructor(client: Client); - on(eventName: string, cb: () => any): void; - fetch(payloads: Array, cb: (error: any, data: any) => any): void; - commit(groupId: string, payloads: Array, cb: (error: any, data: any) => any): void; - fetchCommits(groupId: string, payloads: Array, cb: (error: any, data: any) => any): void; - fetchLatestOffsets(topics: Array, cb: (error: any, data: any) => any): void; - fetchEarliestOffsets(topics: Array, cb: (error: any, data: any) => any): void; - on(eventName: string, cb: (error: any) => any): void; + on(eventName: string, cb: (error?: any) => any): void; + fetch(payloads: OffsetRequest[], cb: (error: any, data: any) => any): void; + commit(groupId: string, payloads: OffsetCommitRequest[], cb: (error: any, data: any) => any): void; + fetchCommits(groupId: string, payloads: OffsetFetchRequest[], cb: (error: any, data: any) => any): void; + fetchLatestOffsets(topics: string[], cb: (error: any, data: any) => any): void; + fetchEarliestOffsets(topics: string[], cb: (error: any, data: any) => any): void; } -export declare class KeyedMessage { +export class KeyedMessage { constructor(key: string, message: string); } @@ -121,8 +119,8 @@ export interface ConnectRetryOptions { } export interface AckBatchOptions { - noAckBatchSize: number | null, - noAckBatchAge: number | null + noAckBatchSize: number | null; + noAckBatchAge: number | null; } export interface ZKOptions { @@ -133,7 +131,7 @@ export interface ZKOptions { export interface ProduceRequest { topic: string; - messages: any; // Array | Array | string | KeyedMessage + messages: any; // string[] | Array | string | KeyedMessage key?: any; partition?: number; attributes?: number; @@ -159,7 +157,7 @@ export interface CustomPartitionAssignmentProtocol { name: string; version: number; userData: {}; - assign: (topicPattern: any, groupMembers: any, callback: (error: any, result: any) => void) => void; + assign(topicPattern: any, groupMembers: any, callback: (error: any, result: any) => void): void; } export interface ConsumerGroupOptions { @@ -214,6 +212,6 @@ export interface OffsetFetchRequest { offset?: number; } -export declare class TopicsNotExistError extends Error { - topics: string | string[] +export class TopicsNotExistError extends Error { + topics: string | string[]; } diff --git a/types/kafka-node/kafka-node-tests.ts b/types/kafka-node/kafka-node-tests.ts index 8d99b98d63..8a3553a9c5 100644 --- a/types/kafka-node/kafka-node-tests.ts +++ b/types/kafka-node/kafka-node-tests.ts @@ -1,26 +1,30 @@ import kafka = require('kafka-node'); -var basicClient = new kafka.Client('localhost:2181/', 'sendMessage'); +const basicClient = new kafka.Client('localhost:2181/', 'sendMessage'); -var optionsClient = new kafka.Client('localhost:2181/', 'sendMessage', { - sessionTimeout: 30000, - spinDelay: 1000, - retries: 0 +const optionsClient = new kafka.Client('localhost:2181/', 'sendMessage', { + sessionTimeout: 30000, + spinDelay: 1000, + retries: 0 }, { noAckBatchSize: 1000, noAckBatchAge: 1000 * 10 }, { rejectUnauthorized: false }); -optionsClient.topicExists(['topic'], function (error: any){}); -optionsClient.refreshMetadata(['topic'], function (error: any){}); +optionsClient.topicExists(['topic'], (error: any) => { +}); +optionsClient.refreshMetadata(['topic'], (error: any) => { +}); optionsClient.close(); -optionsClient.sendOffsetCommitV2Request('group', 0, 'memberId', [], function() {}); -optionsClient.close(function(){}); +optionsClient.sendOffsetCommitV2Request('group', 0, 'memberId', [], () => { +}); +optionsClient.close(() => { +}); -var basicKafkaClient = new kafka.KafkaClient(); +const basicKafkaClient = new kafka.KafkaClient(); -var optionsKafkaClient = new kafka.KafkaClient({ +const optionsKafkaClient = new kafka.KafkaClient({ kafkaHost: 'localhost:2181', connectTimeout: 1000, requestTimeout: 1000, @@ -36,187 +40,226 @@ var optionsKafkaClient = new kafka.KafkaClient({ optionsKafkaClient.connect(); -var optionsProducer = new kafka.Producer(basicClient, { +const optionsProducer = new kafka.Producer(basicClient, { requireAcks: 0, ackTimeoutMs: 0, partitionerType: 0 }); -var producer = new kafka.Producer(basicClient); -producer.on('error', function(error: Error){}); -producer.on('ready', function(){ - - var messages = [{ - topic: 'topicName', - messages: ['message body'], - partition: 0, - attributes: 2 - }, { - topic: 'topicName', - messages: ['message body'], - partition: 0 - }, { - topic: 'topicName', - messages: ['message body'], - attributes: 0 - }, { - topic: 'topicName', - messages: ['message body'] - }, { - topic: 'topicName', - messages: [new kafka.KeyedMessage('key', 'message')] - }]; - - producer.send(messages, function(err: Error){}); - producer.send(messages, function(err: Error, data: Object){}); - - producer.createTopics(['t'], true, function (err: Error, data: any) {}); - producer.createTopics(['t'], function (err: Error, data: any) {}); - producer.createTopics(['t'], false, function () {}); - producer.close(); +const producer = new kafka.Producer(basicClient); +producer.on('error', (error: Error) => { }); +producer.on('ready', () => { + const messages = [{ + topic: 'topicName', + messages: ['message body'], + partition: 0, + attributes: 2 + }, { + topic: 'topicName', + messages: ['message body'], + partition: 0 + }, { + topic: 'topicName', + messages: ['message body'], + attributes: 0 + }, { + topic: 'topicName', + messages: ['message body'] + }, { + topic: 'topicName', + messages: [new kafka.KeyedMessage('key', 'message')] + }]; -var highLevelProducer = new kafka.HighLevelProducer(basicClient); -highLevelProducer.on('error', function(error: Error){}); -highLevelProducer.on('ready', function(){ + producer.send(messages, (err: Error) => { + }); + producer.send(messages, (err: Error, data: any) => { + }); - var messages = [{ - topic: 'topicName', - messages: ['message body'], - attributes: 2 - }, { - topic: 'topicName', - messages: ['message body'], - partition: 0 - }, { - topic: 'topicName', - messages: ['message body'], - attributes: 0 - }, { - topic: 'topicName', - messages: ['message body'] - }, { - topic: 'topicName', - messages: [new kafka.KeyedMessage('key', 'message')] - }]; - - highLevelProducer.send(messages, function(err: Error){}); - highLevelProducer.send(messages, function(err: Error, data: Object){}); - - producer.createTopics(['t'], true, function (err: Error, data: any) {}); - producer.createTopics(['t'], function (err: Error, data: any) {}); - producer.createTopics(['t'], false, function () {}); + producer.createTopics(['t'], true, (err: Error, data: any) => { + }); + producer.createTopics(['t'], (err: Error, data: any) => { + }); + producer.createTopics(['t'], false, () => { + }); producer.close(); }); -var fetchRequests = [{ topic: 'awesome' }]; -var consumer = new kafka.Consumer(basicClient, fetchRequests, { - groupId: 'abcde', - autoCommit: true +const highLevelProducer = new kafka.HighLevelProducer(basicClient); +highLevelProducer.on('error', (error: Error) => { }); -consumer.on('error', function(error: Error){}); -consumer.on('offsetOutOfRange', function(error: Error){}); -consumer.on('message', function(message: kafka.Message){ - var topic = message.topic; - var value = message.value; - var offset = message.offset; - var partition = message.partition; - var highWaterOffset = message.highWaterOffset; - var key = message.key; +highLevelProducer.on('ready', () => { + const messages = [{ + topic: 'topicName', + messages: ['message body'], + attributes: 2 + }, { + topic: 'topicName', + messages: ['message body'], + partition: 0 + }, { + topic: 'topicName', + messages: ['message body'], + attributes: 0 + }, { + topic: 'topicName', + messages: ['message body'] + }, { + topic: 'topicName', + messages: [new kafka.KeyedMessage('key', 'message')] + }]; + + highLevelProducer.send(messages, (err: Error) => { + }); + highLevelProducer.send(messages, (err: Error, data: any) => { + }); + + producer.createTopics(['t'], true, (err: Error, data: any) => { + }); + producer.createTopics(['t'], (err: Error, data: any) => { + }); + producer.createTopics(['t'], false, () => { + }); + producer.close(); }); -consumer.addTopics(['t1', 't2'], function (err, added) {}); -consumer.addTopics([{ topic: 't1', offset: 10 }], function (err, added) {}, true); +const fetchRequests = [{topic: 'awesome'}]; +const consumer = new kafka.Consumer(basicClient, fetchRequests, { + groupId: 'abcde', + autoCommit: true +}); +consumer.on('error', (error: Error) => { +}); +consumer.on('offsetOutOfRange', (error: Error) => { +}); +consumer.on('message', (message: kafka.Message) => { + const topic = message.topic; + const value = message.value; + const offset = message.offset; + const partition = message.partition; + const highWaterOffset = message.highWaterOffset; + const key = message.key; +}); -consumer.removeTopics(['t1', 't2'], function (err, removed: number) {}); -consumer.removeTopics('t2', function (err, removed: number) {}); +consumer.addTopics(['t1', 't2'], (err: any, added: any) => { +}); +consumer.addTopics([{topic: 't1', offset: 10}], (err: any, added: any) => { +}, true); -consumer.commit(function (err, data) {}); -consumer.commit(true, function (err, data) {}); +consumer.removeTopics(['t1', 't2'], (err: any, removed: number) => { +}); +consumer.removeTopics('t2', (err: any, removed: number) => { +}); + +consumer.commit((err: any, data: any) => { +}); +consumer.commit(true, (err: any, data: any) => { +}); consumer.setOffset('topic', 0, 0); consumer.pause(); consumer.resume(); consumer.pauseTopics([ - 'topic1', - { topic: 'topic2', partition: 0 } + 'topic1', + {topic: 'topic2', partition: 0} ]); consumer.resumeTopics([ - 'topic1', - { topic: 'topic2', partition: 0 } + 'topic1', + {topic: 'topic2', partition: 0} ]); -consumer.close(true, function () {}); -consumer.close(function () {}); - -var fetchRequests = [{ topic: 'awesome' }]; -var hlConsumer = new kafka.HighLevelConsumer(basicClient, fetchRequests, { - groupId: 'abcde', - autoCommit: true +consumer.close(true, () => { +}); +consumer.close(() => { }); -hlConsumer.on('error', function(error: Error){}); -hlConsumer.on('offsetOutOfRange', function(error: Error){}); -hlConsumer.on('message', function(message: kafka.Message){ - var topic = message.topic; - var value = message.value; - var offset = message.offset; - var partition = message.partition; - var highWaterOffset = message.highWaterOffset; - var key = message.key; +const fetchRequests1 = [{topic: 'awesome'}]; +const hlConsumer = new kafka.HighLevelConsumer(basicClient, fetchRequests1, { + groupId: 'abcde', + autoCommit: true }); -hlConsumer.addTopics(['t1', 't2'], function (err, added) {}); -hlConsumer.addTopics([{ topic: 't1', offset: 10 }], function (err, added) {}); -hlConsumer.removeTopics(['t1', 't2'], function (err, removed: number) {}); -hlConsumer.removeTopics('t2', function (err, removed: number) {}); +hlConsumer.on('error', (error: Error) => { +}); +hlConsumer.on('offsetOutOfRange', (error: Error) => { +}); +hlConsumer.on('message', (message: kafka.Message) => { + const topic = message.topic; + const value = message.value; + const offset = message.offset; + const partition = message.partition; + const highWaterOffset = message.highWaterOffset; + const key = message.key; +}); +hlConsumer.addTopics(['t1', 't2'], (err: any, added: any) => { +}); +hlConsumer.addTopics([{topic: 't1', offset: 10}], (err: any, added: any) => { +}); -hlConsumer.commit(function (err, data) {}); -hlConsumer.commit(true, function (err, data) {}); +hlConsumer.removeTopics(['t1', 't2'], (err: any, removed: number) => { +}); +hlConsumer.removeTopics('t2', (err: any, removed: number) => { +}); + +hlConsumer.commit((err: any, data: any) => { +}); +hlConsumer.commit(true, (err: any, data: any) => { +}); hlConsumer.setOffset('topic', 0, 0); hlConsumer.pause(); hlConsumer.resume(); -hlConsumer.close(true, function () {}); -hlConsumer.close(function () {}); +hlConsumer.close(true, () => { +}); +hlConsumer.close(() => { +}); -var ackBatchOptions = {'noAckBatchSize': 1024, 'noAckBatchAge': 10}; -var cgOptions: kafka.ConsumerGroupOptions = { - host: 'localhost:2181/', - batch: ackBatchOptions, - groupId: 'groupID', - id: 'consumerID', - sessionTimeout: 15000, - protocol: ["roundrobin"], - fromOffset: "latest", - migrateHLC: false, - migrateRolling: true +const ackBatchOptions = {noAckBatchSize: 1024, noAckBatchAge: 10}; +const cgOptions: kafka.ConsumerGroupOptions = { + host: 'localhost:2181/', + batch: ackBatchOptions, + groupId: 'groupID', + id: 'consumerID', + sessionTimeout: 15000, + protocol: ["roundrobin"], + fromOffset: "latest", + migrateHLC: false, + migrateRolling: true }; -var consumerGroup = new kafka.ConsumerGroup( cgOptions, ['topic1']); -consumerGroup.on('error', (err) => {}); -consumerGroup.on('message', (msg) => {}); -consumerGroup.close(true, () => {}); +const consumerGroup = new kafka.ConsumerGroup(cgOptions, ['topic1']); +consumerGroup.on('error', (err) => { +}); +consumerGroup.on('message', (msg) => { +}); +consumerGroup.close(true, () => { +}); -var offset = new kafka.Offset(basicClient); +const offset = new kafka.Offset(basicClient); -offset.on('ready', function(){}); +offset.on('ready', () => { +}); offset.fetch([ - { topic: 't', partition: 0, time: Date.now(), maxNum: 1 }, - { topic: 't' } -], function (err, data) { }); + {topic: 't', partition: 0, time: Date.now(), maxNum: 1}, + {topic: 't'} +], (err: any, data: any) => { +}); offset.commit('groupId', [ - { topic: 't', partition: 0, offset: 10 } -], function (err, data) { }); + {topic: 't', partition: 0, offset: 10} +], (err, data) => { +}); offset.fetchCommits('groupId', [ - { topic: 't', partition: 0 } -], function (err, data) {}); + {topic: 't', partition: 0} +], (err, data) => { +}); -offset.fetchLatestOffsets(['t'], (err, offsets) => {}) -offset.fetchEarliestOffsets(['t'], (err, offsets) => {}) +offset.fetchLatestOffsets(['t'], (err, offsets) => { +}); +offset.fetchEarliestOffsets(['t'], (err, offsets) => { +}); diff --git a/types/kafka-node/tslint.json b/types/kafka-node/tslint.json index 0967ef424b..d88586e5bd 100644 --- a/types/kafka-node/tslint.json +++ b/types/kafka-node/tslint.json @@ -1 +1,3 @@ -{} +{ + "extends": "dtslint/dt.json" +} From a3819eec0763fe88008dfc073c30695681c4974a Mon Sep 17 00:00:00 2001 From: Lukasz Zak Date: Tue, 18 Jul 2017 13:04:48 +0200 Subject: [PATCH 0115/1139] [mongoose] Add missing property for >=4.1.1 version DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`. See http://mongoosejs.com/docs/connections.html#use-mongo-client --- types/mongoose/index.d.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 12da9c180b..3c48f309f6 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for Mongoose 4.7.0 +// Type definitions for Mongoose 4.7.1 // Project: http://mongoosejs.com/ -// Definitions by: simonxca , horiuchi , sindrenm +// Definitions by: simonxca , horiuchi , sindrenm , lukasz-zak // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -388,6 +388,9 @@ declare module "mongoose" { /** sets the underlying driver's promise library (see http://mongodb.github.io/node-mongodb-native/2.1/api/MongoClient.html) */ promiseLibrary?: any; + + /** See http://mongoosejs.com/docs/connections.html#use-mongo-client **/ + useMongoClient?: boolean; } interface ConnectionOptions extends From 226ef5f14c338f1435fa2c6ca75c3e97e3a7ae48 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Tue, 18 Jul 2017 09:13:58 -0400 Subject: [PATCH 0116/1139] [jquery] Revert isEmptyObject() to returning boolean. While the type guard does narrow a value's type to an empty object, the interesting case is when the type is not an empty object. TypeScript narrows the type to never in that case which makes the type guard not very useful. --- types/jquery/index.d.ts | 2 +- types/jquery/jquery-tests.ts | 8 ++------ 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 4ebb4692f5..2fd196fd41 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -587,7 +587,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.isEmptyObject/} * @since 1.4 */ - isEmptyObject(obj: any): obj is {}; + isEmptyObject(obj: any): boolean; /** * Determine if the argument passed is a JavaScript function object. * diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 01cc4a345e..0485d05351 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -627,12 +627,8 @@ function JQueryStatic() { } function isEmptyObject() { - function type_guard(obj: object) { - if ($.isEmptyObject(obj)) { - // $ExpectType {} - obj; - } - } + // $ExpectType boolean + $.isEmptyObject({}); } function isFunction() { From ec2158f2d6f34297a2dc52b93537cd089cc68285 Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Tue, 18 Jul 2017 09:22:02 -0400 Subject: [PATCH 0117/1139] [jquery] Add tests for type of a type guard in the not case. Note that isPlainObject() fails the not case in the same manner that isEmptyObject() does. This might warrant changing it to return a boolean. However, unlike isEmptyObject(), isPlainObject() can be useful when the object is a plain object. --- types/jquery/jquery-tests.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 0485d05351..4bbe9c553e 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -622,6 +622,9 @@ function JQueryStatic() { if ($.isArray(obj)) { // $ExpectType any[] obj; + } else { + // $ExpectType object + obj; } } } @@ -636,6 +639,9 @@ function JQueryStatic() { if ($.isFunction(obj)) { // $ExpectType Function obj; + } else { + // $ExpectType object + obj; } } } @@ -645,6 +651,9 @@ function JQueryStatic() { if ($.isNumeric(obj)) { // $ExpectType (true & number) | (false & number) obj; + } else { + // $ExpectType boolean + obj; } } } @@ -663,6 +672,9 @@ function JQueryStatic() { if ($.isWindow(obj)) { // $ExpectType Window obj; + } else { + // $ExpectType object + obj; } } } From f234366096fd8dce2d466ee753c32cd8619ab0ca Mon Sep 17 00:00:00 2001 From: Leonard Thieu Date: Tue, 18 Jul 2017 10:35:27 -0400 Subject: [PATCH 0118/1139] [angular-resource] Lint. --- types/angular-resource/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/angular-resource/index.d.ts b/types/angular-resource/index.d.ts index b95911ae2c..4bdc8cc007 100644 --- a/types/angular-resource/index.d.ts +++ b/types/angular-resource/index.d.ts @@ -53,14 +53,14 @@ declare module 'angular' { interface IActionHash { [action: string]: IActionDescriptor; } - + interface IResourceResponse { config: any; data: any; headers: any; resource: any; status: number; - statusText: string + statusText: string; } interface IResourceInterceptor { From a790cd60fcc0a518659fa0b966b026f212b28abd Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 18 Jul 2017 09:13:17 -0700 Subject: [PATCH 0119/1139] Revert "react-transition-group Added {} state to remedy Component Requires 2 type arguments" --- types/react-transition-group/CSSTransition.d.ts | 2 +- types/react-transition-group/Transition.d.ts | 2 +- types/react-transition-group/TransitionGroup.d.ts | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/react-transition-group/CSSTransition.d.ts b/types/react-transition-group/CSSTransition.d.ts index 763ea80a0f..67b869edf6 100644 --- a/types/react-transition-group/CSSTransition.d.ts +++ b/types/react-transition-group/CSSTransition.d.ts @@ -33,6 +33,6 @@ export interface CSSTransitionProps extends TransitionProps { classNames: string | CSSTransitionClassNames; } -declare class CSSTransition extends Component {} +declare class CSSTransition extends Component {} export default CSSTransition; diff --git a/types/react-transition-group/Transition.d.ts b/types/react-transition-group/Transition.d.ts index 844561333c..24f0265ee2 100644 --- a/types/react-transition-group/Transition.d.ts +++ b/types/react-transition-group/Transition.d.ts @@ -66,6 +66,6 @@ export interface TransitionProps extends TransitionActions { * ``` * */ -declare class Transition extends Component {} +declare class Transition extends Component {} export default Transition; diff --git a/types/react-transition-group/TransitionGroup.d.ts b/types/react-transition-group/TransitionGroup.d.ts index e746d3ca77..3f04332bc8 100644 --- a/types/react-transition-group/TransitionGroup.d.ts +++ b/types/react-transition-group/TransitionGroup.d.ts @@ -1,4 +1,4 @@ -import { Component, HTMLProps, ReactElement, ReactType } from "react"; +import { Component, ReactType, HTMLProps, ReactElement } from "react"; import { TransitionActions, TransitionProps } from "react-transition-group/Transition"; export interface IntrinsicTransitionGroupProps extends TransitionActions { @@ -71,6 +71,6 @@ export type TransitionGroupProps {} +declare class TransitionGroup extends Component {} export default TransitionGroup; From d030e33b5e7eb078d9e5f106eeb2f8eb5a1a0200 Mon Sep 17 00:00:00 2001 From: stackia Date: Wed, 19 Jul 2017 01:37:50 +0800 Subject: [PATCH 0120/1139] react-native: Stylesheet.create() return registered style --- types/react-native/index.d.ts | 36 ++++++++++++++++++------------- types/react-native/test/index.tsx | 4 +++- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 3317eff673..782392ef30 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1659,7 +1659,8 @@ export interface ViewPropertiesAndroid { type Falsy = undefined | null | false interface RecursiveArray extends Array> {} -export type StyleProp = T | RecursiveArray | Falsy +interface RegisteredStyle extends Number {} +export type StyleProp = T | RegisteredStyle | RecursiveArray | Falsy> | Falsy /** * @see https://facebook.github.io/react-native/docs/view.html#props @@ -4913,7 +4914,9 @@ export namespace StyleSheet { /** * Creates a StyleSheet style reference from the given object. */ - export function create>( styles: T ): T; + export function create>( styles: T ): { + [P in keyof T]: RegisteredStyle; + }; /** * Flattens an array of style objects, into one aggregated style object. @@ -4954,6 +4957,7 @@ export namespace StyleSheet { * their respective objects, merged as one and then returned. This also explains * the alternative use. */ + export function flatten(style?: RegisteredStyle): T export function flatten(style?: StyleProp): ViewStyle export function flatten(style?: StyleProp): TextStyle export function flatten(style?: StyleProp): ImageStyle @@ -4977,12 +4981,13 @@ export namespace StyleSheet { */ export var hairlineWidth: number - /** - * A very common pattern is to create overlays with position absolute and zero positioning, - * so `absoluteFill` can be used for convenience and to reduce duplication of these repeated - * styles. - */ - export var absoluteFill: number + interface AbsoluteFillStyle { + position: "absolute" + left: 0 + right: 0 + top: 0 + bottom: 0 + } /** * Sometimes you may want `absoluteFill` but with a couple tweaks - `absoluteFillObject` can be @@ -4996,13 +5001,14 @@ export namespace StyleSheet { * }, * }); */ - export var absoluteFillObject: { - position: string - left: number - right: number - top: number - bottom: number - } + export var absoluteFillObject: AbsoluteFillStyle + + /** + * A very common pattern is to create overlays with position absolute and zero positioning, + * so `absoluteFill` can be used for convenience and to reduce duplication of these repeated + * styles. + */ + export var absoluteFill: RegisteredStyle } export interface RelayProfiler { diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 446cb176f1..954402f23c 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -100,11 +100,13 @@ const stylesAlt = StyleSheet.create( } ); +const welcomeFontSize = StyleSheet.flatten(styles.welcome).fontSize + class CustomView extends React.Component { render() { return ( - Custom View + Custom View ); } From b961f48fa62189a7416b1e1da52f7e92fdc7b34f Mon Sep 17 00:00:00 2001 From: stackia Date: Wed, 19 Jul 2017 01:50:42 +0800 Subject: [PATCH 0121/1139] react-native: add onShouldBlockNativeResponder() for PanResponderCallbacks --- types/react-native/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 3317eff673..ceb17d4c5a 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -7027,6 +7027,7 @@ export interface PanResponderCallbacks { onPanResponderStart?: (e: GestureResponderEvent, gestureState: PanResponderGestureState) => void onPanResponderEnd?: (e: GestureResponderEvent, gestureState: PanResponderGestureState) => void onPanResponderTerminationRequest?: (e: GestureResponderEvent, gestureState: PanResponderGestureState) => boolean + onShouldBlockNativeResponder?: (e: GestureResponderEvent, gestureState: PanResponderGestureState) => boolean } export interface PanResponderInstance { @@ -7043,7 +7044,7 @@ export interface PanResponderInstance { */ export interface PanResponderStatic { /** - * @param config Enhanced versions of all of the responder callbacks + * @param {PanResponderCallbacks} config Enhanced versions of all of the responder callbacks * that provide not only the typical `ResponderSyntheticEvent`, but also the * `PanResponder` gesture state. Simply replace the word `Responder` with * `PanResponder` in each of the typical `onResponder*` callbacks. For @@ -7061,6 +7062,7 @@ export interface PanResponderStatic { * - `onPanResponderMove: (e, gestureState) => {...}` * - `onPanResponderTerminate: (e, gestureState) => {...}` * - `onPanResponderTerminationRequest: (e, gestureState) => {...}` + * - `onShouldBlockNativeResponder: (e, gestureState) => {...}` * * In general, for events that have capture equivalents, we update the * gestureState once in the capture phase and can use it in the bubble phase From d4f6232b4ae7adcdb44afd8962ecaec236a40620 Mon Sep 17 00:00:00 2001 From: smac89 Date: Tue, 18 Jul 2017 12:27:04 -0600 Subject: [PATCH 0122/1139] Fixed indentation to use space rather than mixed tab and space --- types/merge2/index.d.ts | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/types/merge2/index.d.ts b/types/merge2/index.d.ts index 44b3aeaf21..f5664bbd7e 100644 --- a/types/merge2/index.d.ts +++ b/types/merge2/index.d.ts @@ -1,7 +1,7 @@ // Type definitions for merge2 v1.1.0 // Project: https://github.com/teambition/merge2 // Definitions by: Tanguy Krotoff -// Chigozirim C. +// Chigozirim C. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -11,24 +11,24 @@ import {DuplexOptions} from 'stream'; type StreamType = NodeJS.ReadableStream | IMerge2Stream; interface IMerge2Stream extends NodeJS.ReadWriteStream { - /** - * @brief Add more streams to an existing merged stream - * - * @param args streams to add - * - * @return The merged stream - */ + /** + * @brief Add more streams to an existing merged stream + * + * @param args streams to add + * + * @return The merged stream + */ add(...args: Array>): IMerge2Stream; } /** * @brief This function takes an arbitrary number of streams, but the duplexoption - * has to be the last parameter of the function. - * + * has to be the last parameter of the function. + * * @param args The arguments * * @return A merged duplex stream - */ + */ declare function IMerge2 (...args: Array | DuplexOptions>): IMerge2Stream; declare namespace IMerge2 {} From ba011a4e0d616153b16af2bc35c7f1f2e3ab48c6 Mon Sep 17 00:00:00 2001 From: Grant Nestor Date: Tue, 18 Jul 2017 11:38:53 -0700 Subject: [PATCH 0123/1139] Add declaration for Plotly.Plots --- types/plotly.js/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 667197c82f..b3b2dd209b 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -14,6 +14,8 @@ export interface StaticPlots { resize(root: Root): void; } +export const Plots: StaticPlots; + export interface Point { x: number; y: number; From aa245d6c8c1cebdb85ce5018892b5da5ca9316cc Mon Sep 17 00:00:00 2001 From: amiram Date: Tue, 18 Jul 2017 22:20:13 +0300 Subject: [PATCH 0124/1139] add missing kafkaClient options --- types/kafka-node/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index 5c93822a03..d025f849ae 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -108,6 +108,8 @@ export interface KafkaClientOptions { requestTimeout?: number; authConnect?: boolean; connectRetryOptions?: ConnectRetryOptions; + sslOptions?: any; + clientId?: string; } export interface ConnectRetryOptions { From 59932cbdd60a267ab18d479506c6108f48d58100 Mon Sep 17 00:00:00 2001 From: amiram Date: Tue, 18 Jul 2017 22:21:14 +0300 Subject: [PATCH 0125/1139] add test for missing kafkaClient options --- types/kafka-node/kafka-node-tests.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/kafka-node/kafka-node-tests.ts b/types/kafka-node/kafka-node-tests.ts index 8a3553a9c5..b1f10eb291 100644 --- a/types/kafka-node/kafka-node-tests.ts +++ b/types/kafka-node/kafka-node-tests.ts @@ -29,6 +29,8 @@ const optionsKafkaClient = new kafka.KafkaClient({ connectTimeout: 1000, requestTimeout: 1000, authConnect: true, + sslOptions: {}, + clientId: "client id", connectRetryOptions: { retries: 5, factor: 0, From 7660556dc2932833f6240d5e31bc452fe4329824 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 18 Jul 2017 12:24:00 -0700 Subject: [PATCH 0126/1139] css-modules: Use LF line endings (#18185) --- types/css-modules/css-modules-tests.ts | 42 +++++++------- types/css-modules/index.d.ts | 76 +++++++++++++------------- types/css-modules/tsconfig.json | 42 +++++++------- 3 files changed, 80 insertions(+), 80 deletions(-) diff --git a/types/css-modules/css-modules-tests.ts b/types/css-modules/css-modules-tests.ts index 5876f5beae..e6479ba2d5 100644 --- a/types/css-modules/css-modules-tests.ts +++ b/types/css-modules/css-modules-tests.ts @@ -1,21 +1,21 @@ -import styles from './main.sass'; -import * as classNames from 'classnames'; - -class App { - private theme: string; - constructor(theme: string) { - this.theme = theme; - } - - render() { - // as a style tag (using webpack's css-loader) - const tpl = `
`; - // or as scoped unique classes, also latest typescript versions allow prop access using dot like styles.darkUI instead of styles['darkUI'] - return ` -
-
- `; - } -} +import styles from './main.sass'; +import * as classNames from 'classnames'; + +class App { + private theme: string; + constructor(theme: string) { + this.theme = theme; + } + + render() { + // as a style tag (using webpack's css-loader) + const tpl = `
`; + // or as scoped unique classes, also latest typescript versions allow prop access using dot like styles.darkUI instead of styles['darkUI'] + return ` +
+
+ `; + } +} diff --git a/types/css-modules/index.d.ts b/types/css-modules/index.d.ts index 7d7bd52abd..832ae27406 100644 --- a/types/css-modules/index.d.ts +++ b/types/css-modules/index.d.ts @@ -1,38 +1,38 @@ -// Type definitions for css-modules 1.0 -// Project: https://github.com/css-modules/css-modules -// Definitions by: NeekSandhu -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -interface Stringifyable { - /** - * Stringifies the imported stylesheet for use with inline style tags - */ - toString(): string; -} -interface SelectorNode { - /** - * Returns the specific selector from imported stylesheet as string - */ - [key: string]: string; -} - -declare module '*.css' { - const styles: SelectorNode & Stringifyable; - export default styles; -} - -declare module '*.scss' { - const styles: SelectorNode & Stringifyable; - export default styles; -} - -declare module '*.sass' { - const styles: SelectorNode & Stringifyable; - export default styles; -} - -declare module '*.less' { - const styles: SelectorNode & Stringifyable; - export default styles; -} +// Type definitions for css-modules 1.0 +// Project: https://github.com/css-modules/css-modules +// Definitions by: NeekSandhu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +interface Stringifyable { + /** + * Stringifies the imported stylesheet for use with inline style tags + */ + toString(): string; +} +interface SelectorNode { + /** + * Returns the specific selector from imported stylesheet as string + */ + [key: string]: string; +} + +declare module '*.css' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.scss' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.sass' { + const styles: SelectorNode & Stringifyable; + export default styles; +} + +declare module '*.less' { + const styles: SelectorNode & Stringifyable; + export default styles; +} diff --git a/types/css-modules/tsconfig.json b/types/css-modules/tsconfig.json index aff10df5a6..40a428a927 100644 --- a/types/css-modules/tsconfig.json +++ b/types/css-modules/tsconfig.json @@ -1,22 +1,22 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "css-modules-tests.ts" - ] +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "css-modules-tests.ts" + ] } \ No newline at end of file From d1775959f96e5112c8fda94b171a691738b85c54 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Tue, 18 Jul 2017 21:55:47 +0200 Subject: [PATCH 0127/1139] [@ronomon/crypto-async] introduce typings --- types/ronomon__crypto-async/index.d.ts | 64 +++++++++ .../ronomon__crypto-async-tests.ts | 130 ++++++++++++++++++ types/ronomon__crypto-async/tsconfig.json | 22 +++ types/ronomon__crypto-async/tslint.json | 1 + 4 files changed, 217 insertions(+) create mode 100644 types/ronomon__crypto-async/index.d.ts create mode 100644 types/ronomon__crypto-async/ronomon__crypto-async-tests.ts create mode 100644 types/ronomon__crypto-async/tsconfig.json create mode 100644 types/ronomon__crypto-async/tslint.json diff --git a/types/ronomon__crypto-async/index.d.ts b/types/ronomon__crypto-async/index.d.ts new file mode 100644 index 0000000000..dfc533833a --- /dev/null +++ b/types/ronomon__crypto-async/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for @ronomon/crypto-async 2.0 +// Project: https://github.com/ronomon/crypto-async +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +// tslint:disable-next-line no-single-declare-module +declare module "@ronomon/crypto-async" { + function cipher(algorithm: string, + cipherDirection: CipherDirection, + key: Buffer, + iv: Buffer, + plaintext: Buffer, + cb: (error: Error | undefined, ciphertext: Buffer) => void): void; + + function cipher(algorithm: string, + cipherDirection: CipherDirection, + key: Buffer, + keyOffset: number, + keySize: number, + iv: Buffer, + ivOffset: number, + ivSize: number, + source: Buffer, + sourceOffset: number, + sourceSize: number, + target: Buffer, + targetOffset: number, + cb: (error: Error | undefined, targetSize: number) => void): void; + + function hash(algorithm: string, + source: Buffer, + cb: (error: Error | undefined, hash: Buffer) => void): void; + + function hash(algorithm: string, + source: Buffer, + sourceOffset: number, + sourceSize: number, + target: Buffer, + targetOffset: number, + cb: (error: Error | undefined, targetSize: number) => void): void; + + function hmac(algorithm: string, + key: Buffer, + source: Buffer, + cb: (error: Error | undefined, hmac: Buffer) => void): void; + + function hmac(algorithm: string, + key: Buffer, + keyOffset: number, + keySize: number, + source: Buffer, + sourceOffset: number, + sourceSize: number, + target: Buffer, + targetOffset: number, + cb: (error: Error | undefined, targetSize: number) => void): void; + + const enum CipherDirection { + Decrypt, + Encrypt + } +} diff --git a/types/ronomon__crypto-async/ronomon__crypto-async-tests.ts b/types/ronomon__crypto-async/ronomon__crypto-async-tests.ts new file mode 100644 index 0000000000..429affe3a3 --- /dev/null +++ b/types/ronomon__crypto-async/ronomon__crypto-async-tests.ts @@ -0,0 +1,130 @@ +import * as cryptoAsync from '@ronomon/crypto-async'; + +(() => { + const algorithm = 'AES-256-CTR'; + const encrypt = cryptoAsync.CipherDirection.Encrypt; + const key = Buffer.alloc(32); + const iv = Buffer.alloc(16); + const plaintext = Buffer.alloc(128); + cryptoAsync.cipher(algorithm, encrypt, key, iv, plaintext, + (error, ciphertext) => { + if (error) throw error; + console.log(ciphertext.toString('hex')); + cryptoAsync.cipher(algorithm, cryptoAsync.CipherDirection.Decrypt, key, iv, ciphertext, + (error, plaintext) => { + if (error) throw error; + console.log(plaintext.toString('hex')); + } + ); + } + ); +})(); + +(() => { + const algorithm = 'AES-256-CTR'; + const encrypt = 1; // 0 = Decrypt, 1 = Encrypt + const key = Buffer.alloc(1024); + const keyOffset = 4; + const keySize = 32; + const iv = Buffer.alloc(32); + const ivOffset = 2; + const ivSize = 16; + const source = Buffer.alloc(1024 * 1024); + const sourceOffset = 512; + const sourceSize = 32; + const target = Buffer.alloc(1024 * 1024); + const targetOffset = 32768; + cryptoAsync.cipher( + algorithm, + encrypt, + key, + keyOffset, + keySize, + iv, + ivOffset, + ivSize, + source, + sourceOffset, + sourceSize, + target, + targetOffset, + (error, targetSize) => { + if (error) throw error; + const slice = target.slice(targetOffset, targetOffset + targetSize); + console.log(slice.toString('hex')); + } + ); +})(); + +(() => { + const algorithm = 'SHA256'; + const source = Buffer.alloc(1024 * 1024); + cryptoAsync.hash(algorithm, source, + (error, hash) => { + if (error) throw error; + console.log(hash.toString('hex')); + } + ); +})(); + +(() => { + const algorithm = 'SHA256'; + const source = Buffer.alloc(1024 * 1024); + const sourceOffset = 512; + const sourceSize = 65536; + const target = Buffer.alloc(1024 * 1024); + const targetOffset = 32768; + cryptoAsync.hash( + algorithm, + source, + sourceOffset, + sourceSize, + target, + targetOffset, + (error, targetSize) => { + if (error) throw error; + const slice = target.slice(targetOffset, targetOffset + targetSize); + console.log(slice.toString('hex')); + } + ); +})(); + +(() => { + const algorithm = 'SHA256'; + const key = Buffer.alloc(1024); + const source = Buffer.alloc(1024 * 1024); + cryptoAsync.hmac(algorithm, key, source, + (error, hmac) => { + if (error) throw error; + console.log(hmac.toString('hex')); + } + ); +})(); + +(() => { + const algorithm = 'SHA256'; + const key = Buffer.alloc(1024); + const keyOffset = 4; + const keySize = 8; + const source = Buffer.alloc(1024 * 1024); + const sourceOffset = 512; + const sourceSize = 65536; + const target = Buffer.alloc(1024 * 1024); + const targetOffset = 32768; + cryptoAsync.hmac( + algorithm, + key, + keyOffset, + keySize, + source, + sourceOffset, + sourceSize, + target, + targetOffset, + (error, targetSize) => { + if (error) throw error; + const slice = target.slice(targetOffset, targetOffset + targetSize); + console.log(slice.toString('hex')); + } + ); +})(); diff --git a/types/ronomon__crypto-async/tsconfig.json b/types/ronomon__crypto-async/tsconfig.json new file mode 100644 index 0000000000..217a5f51db --- /dev/null +++ b/types/ronomon__crypto-async/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ronomon__crypto-async-tests.ts" + ] +} diff --git a/types/ronomon__crypto-async/tslint.json b/types/ronomon__crypto-async/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ronomon__crypto-async/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 84ab2cd275e5e3df93c24090f2fc05e1d826bfdd Mon Sep 17 00:00:00 2001 From: Ziggy Date: Tue, 18 Jul 2017 13:02:26 -0700 Subject: [PATCH 0128/1139] @types/angular-strap The type definition is missing the `prefixClass` option. https://github.com/mgcrea/angular-strap/blob/master/dist/modules/modal.js#L16 --- types/angular-strap/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/angular-strap/index.d.ts b/types/angular-strap/index.d.ts index 2b31f00148..cf0dc25481 100644 --- a/types/angular-strap/index.d.ts +++ b/types/angular-strap/index.d.ts @@ -45,6 +45,7 @@ declare namespace mgcrea.ngStrap { template?: string; templateUrl?: string; contentTemplate?: string; + prefixClass?: string; prefixEvent?: string; id?: string; scope?: ng.IScope; From 46ec03c7498b130ab35a6c548f9ef92f3425e707 Mon Sep 17 00:00:00 2001 From: Ziggy Date: Tue, 18 Jul 2017 13:39:09 -0700 Subject: [PATCH 0129/1139] Append missing callbacks --- types/angular-strap/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/angular-strap/index.d.ts b/types/angular-strap/index.d.ts index cf0dc25481..f7749a049b 100644 --- a/types/angular-strap/index.d.ts +++ b/types/angular-strap/index.d.ts @@ -49,6 +49,10 @@ declare namespace mgcrea.ngStrap { prefixEvent?: string; id?: string; scope?: ng.IScope; + onBeforeHide?: (modal: IModal) => void; + onHide?: (modal: IModal) => void; + onBeforeShow?: (modal: IModal) => void; + onShow?: (modal: IModal) => void; } interface IModalScope extends ng.IScope { From da842393a1f806dd7d5d379866a8eaf043c717de Mon Sep 17 00:00:00 2001 From: Yifan Wu Date: Tue, 18 Jul 2017 14:15:03 -0700 Subject: [PATCH 0130/1139] documentdb added UriFactory --- types/documentdb/documentdb-tests.ts | 12 +++ types/documentdb/index.d.ts | 105 ++++++++++++++++++++++++++- 2 files changed, 116 insertions(+), 1 deletion(-) diff --git a/types/documentdb/documentdb-tests.ts b/types/documentdb/documentdb-tests.ts index 3395716305..3ad362e4a0 100644 --- a/types/documentdb/documentdb-tests.ts +++ b/types/documentdb/documentdb-tests.ts @@ -240,3 +240,15 @@ const rpr2 = new ddb.RangePartitionResolver((obj: any) => obj.foo, [ partitionKe const rangePartitionKey1: any = rpr1.getPartitionKey(document1); const rangeCollectionLink1: string = rpr1.resolveForCreate(hashPartitionKey1); const rangeCollectionLinks1: string[] = rpr1.resolveForRead(hashPartitionKey1); + +/** UriFactory methods */ +const dbUri = ddb.UriFactory.createDatabaseUri('dbfoo'); +const colUri = ddb.UriFactory.createDocumentCollectionUri('dbfoo', 'colbar'); +const docUri = ddb.UriFactory.createDocumentUri('dbfoo', 'colbar', 'doc1'); +const permUri = ddb.UriFactory.createPermissionUri('dbfoo', 'userId', 'permission1'); +const sprocUri = ddb.UriFactory.createStoredProcedureUri('dbfoo', 'colbar', 'sproc1'); +const triggerUri = ddb.UriFactory.createTriggerUri('dbfoo', 'colbar', 'trigger1'); +const udfUri = ddb.UriFactory.createUserDefinedFunctionUri('dbfoo', 'colbar', 'udf1'); +const conflictUri = ddb.UriFactory.createConflictUri('dbfoo', 'colbar', 'conflict1'); +const attachUri = ddb.UriFactory.createAttachmentUri('dbfoo', 'colbar', 'doc1', 'attachment1'); +const partitionKeyRangeUri = ddb.UriFactory.createPartitionKeyRangesUri('dbfoo', 'colbar'); diff --git a/types/documentdb/index.d.ts b/types/documentdb/index.d.ts index 7e73926c7f..140470fbda 100644 --- a/types/documentdb/index.d.ts +++ b/types/documentdb/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for DocumentDB 1.10 // Project: https://github.com/Azure/azure-documentdb-node -// Definitions by: Noel Abrahams , Brett Gutstein , Chris Stone +// Definitions by: Noel Abrahams , Brett Gutstein , Chris Stone , Yifan Wu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/documentdb /// @@ -1340,6 +1340,109 @@ export class DocumentClient { getWriteEndpoint(callback: RequestCallback): void; } +export class UriFactory { + /** + * Given a database id, this creates a database link. + * @param {string} databaseId -The database id + * @returns {string} -A database link in the format of dbs/{0} with {0} being a Uri escaped version of the databaseId + * @description Would be used when creating or deleting a DocumentCollection or a User in Azure DocumentDB database service + */ + static createDatabaseUri(databaseId: string): string; + /** + * Given a database and collection id, this creates a collection link. + * @param {string} databaseId -The database id + * @param {string} collectionId -The collection id + * @returns {string} A collection link in the format of dbs/{0}/colls/{1} with {0} being a Uri escaped version of the databaseId and {1} being collectionId + * @description Would be used when updating or deleting a DocumentCollection, creating a Document, a StoredProcedure, a + * Trigger, a UserDefinedFunction, or when executing a query with CreateDocumentQuery in Azure DocumentDB database service. + */ + static createDocumentCollectionUri(databaseId: string, collectionId: string): string; + /** + * Given a database and collection id, this creates a collection link. + * @param {string} databaseId -The database id + * @param {string} collectionId -The collection id + * @param {string} documentId -The document id + * @returns {string} -A document link in the format of dbs/{0}/colls/{1}/docs/{2} with {0} + * being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the documentId + * @description Would be used when creating an Attachment, or when replacing or deleting a Document in Azure DocumentDB database service + */ + static createDocumentUri(databaseId: string, collectionId: string, documentId: string): string; + /** + * Given a database, collection and document id, this creates a document link. + * @param {string} databaseId -The database Id + * @param {string} userId -The user Id + * @param {string} permissionId - The permissionId + * @returns {string} A permission link in the format of dbs/{0}/users/{1}/permissions/{2} with {0} being a Uri escaped version of the databaseId, {1} being userId and {2} being permissionId + * @description Would be used when replacing or deleting a Permission in Azure DocumentDB database service. + */ + static createPermissionUri(databaseId: string, userId: string, permissionId: string): string; + + /** + * Given a database, collection and stored proc id, this creates a stored proc link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} storedProcedureId -The stored procedure Id + * @returns {string} -A stored procedure link in the format of dbs/{0}/colls/{1}/sprocs/{2} + * with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the storedProcedureId + * @description Would be used when replacing, executing, or deleting a StoredProcedure in Azure DocumentDB database service. + */ + static createStoredProcedureUri(databaseId: string, collectionId: string, storedProcedureId: string): string; + + /** + * @summary Given a database, collection and trigger id, this creates a trigger link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} triggerId -The trigger Id + * @returns {string} -A trigger link in the format of dbs/{0}/colls/{1}/triggers/{2} + * with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the triggerId + * @description Would be used when replacing, executing, or deleting a Trigger in Azure DocumentDB database service + */ + static createTriggerUri(databaseId: string, collectionId: string, triggerId: string): string; + + /** + * @summary Given a database, collection and udf id, this creates a udf link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} udfId -The User Defined Function Id + * @returns {string} -A udf link in the format of dbs/{0}/colls/{1}/udfs/{2} with {0} being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the udfId + * @description Would be used when replacing, executing, or deleting a UserDefinedFunction in Azure DocumentDB database service + */ + static createUserDefinedFunctionUri(databaseId: string, collectionId: string, udfId: string): string; + + /** + * @summary + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} conflictId -The conflict Id + * @returns {string} -A conflict link in the format of dbs/{0}/colls/{1}/conflicts/{2} + * with {0} being a Uri escaped version of the databaseId, {1} being collectionId and {2} being the conflictId + * @description Would be used when creating a Conflict in Azure DocumentDB database service. + */ + static createConflictUri(databaseId: string, collectionId: string, conflictId: string): string; + + /** + * @summary Given a database, collection and conflict id, this creates a conflict link. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @param {string} documentId -The document Id\ + * @param {string} attachmentId -The attachment Id + * @returns {string} -A conflict link in the format of dbs/{0}/colls/{1}/conflicts/{2} with {0} being a Uri escaped version of the databaseId, + * {1} being collectionId and {2} being the conflictId + * @description Would be used when creating a Conflict in Azure DocumentDB database service. + */ + static createAttachmentUri(databaseId: string, collectionId: string, documentId: string, attachmentId: string): string; + + /** + * @summary Given a database and collection, this creates a partition key ranges link in the Azure DocumentDB database service. + * @param {string} databaseId -The database Id + * @param {string} collectionId -The collection Id + * @returns {string} -A partition key ranges link in the format of dbs/{0}/colls/{1}/pkranges with {0} being a Uri escaped version of the databaseId and {1} being collectionId + */ + static createPartitionKeyRangesUri(databaseId: string, collectionId: string): string; +} + export type MediaReadMode = 'Buffered' | 'Streamed'; export type ConsistencyLevel = 'Strong' | 'BoundedStaleness' | 'Session' | 'Eventual'; export type IndexingMode = 'Consistent' | 'Lazy'; From d2bf22339445f9454c6835cff40c6e4dbcea18ad Mon Sep 17 00:00:00 2001 From: Franklin Yu Date: Tue, 18 Jul 2017 17:25:00 -0400 Subject: [PATCH 0131/1139] [gapi.auth2] Fix parameter according to latest official documentation (#17816) * [gapi.auth2] Fix parameter type of callback According to the [documentation][]: > The function called with the `GoogleAuth` object when it is fully > initialized. [documentation]: https://developers.google.com/identity/sign-in/web/reference#googleauththenoninit-onerror * [gapi.auth2] Convert documentation to type Types are better than description in documentation. * [gapi.auth2] Add parameter to `gapi.auth2.init()` See [official documentation][]. [official documentation]: https://developers.google.com/identity/sign-in/web/reference#gapiauth2initparams * [gapi.auth2] Fix indentation This change is best viewed with "histogram" or "patience" diffing algorithm. * [gapi.auth2] Add test and fix a bug * [gapi.auth2] Add linting --- types/gapi.auth2/gapi.auth2-tests.ts | 59 ++++++++------- types/gapi.auth2/index.d.ts | 108 ++++++++++++++------------- types/gapi.auth2/tslint.json | 8 ++ 3 files changed, 94 insertions(+), 81 deletions(-) create mode 100644 types/gapi.auth2/tslint.json diff --git a/types/gapi.auth2/gapi.auth2-tests.ts b/types/gapi.auth2/gapi.auth2-tests.ts index 0766f3b914..75d35737df 100644 --- a/types/gapi.auth2/gapi.auth2-tests.ts +++ b/types/gapi.auth2/gapi.auth2-tests.ts @@ -1,7 +1,7 @@ /// function test_init() { - var auth = gapi.auth2.init({ + const auth: gapi.auth2.GoogleAuth = gapi.auth2.init({ client_id: 'my-id', cookie_policy: 'single_host_origin', scope: 'https://www.googleapis.com/auth/plus.login', @@ -14,9 +14,11 @@ function test_getAuthInstance() { client_id: 'my-id', cookie_policy: 'single_host_origin', scope: 'https://www.googleapis.com/auth/plus.login', - fetch_basic_profile: true + fetch_basic_profile: true, + ux_mode: "popup", + redirect_uri: "https://www.example.com" }); - var auth = gapi.auth2.getAuthInstance(); + const auth: gapi.auth2.GoogleAuth = gapi.auth2.getAuthInstance(); } function test_signIn() { @@ -27,7 +29,7 @@ function test_signIn() { } function test_signInOptionsBuild() { - var options = new gapi.auth2.SigninOptionsBuilder(); + const options = new gapi.auth2.SigninOptionsBuilder(); options.setAppPackageName('com.example.app'); options.setFetchBasicProfile(true); options.setPrompt('select_account'); @@ -36,24 +38,24 @@ function test_signInOptionsBuild() { } function test_getAuthResponse() { - var user = gapi.auth2.getAuthInstance().currentUser.get(); - var authResponse = user.getAuthResponse(); - var authResponseWithAuth = user.getAuthResponse(true); + const user: gapi.auth2.GoogleUser = gapi.auth2.getAuthInstance().currentUser.get(); + const authResponse: gapi.auth2.AuthResponse = user.getAuthResponse(); + const authResponseWithAuth: gapi.auth2.AuthResponse = user.getAuthResponse(true); } function test_reloadAuthResponse() { gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse() .then(response => { - let token = response.access_token; - let expires_in = response.expires_in - }) + const token: string = response.access_token; + const expires_in: number = response.expires_in; + }); } function test_render() { - var success = (googleUser: gapi.auth2.GoogleUser): void => { + const success = (googleUser: gapi.auth2.GoogleUser): void => { console.log(googleUser); }; - var failure = (): void => { + const failure = (): void => { console.log('Failure callback'); }; @@ -71,7 +73,7 @@ function test_render() { /* Example taken from https://developers.google.com/identity/sign-in/web/ */ function onSignIn(googleUser: gapi.auth2.GoogleUser) { // Useful data for your client-side scripts: - var profile = googleUser.getBasicProfile(); + const profile = googleUser.getBasicProfile(); console.log("ID: " + profile.getId()); // Don't send this directly to your server! console.log('Full Name: ' + profile.getName()); console.log('Given Name: ' + profile.getGivenName()); @@ -80,42 +82,41 @@ function onSignIn(googleUser: gapi.auth2.GoogleUser) { console.log("Email: " + profile.getEmail()); // The ID token you need to pass to your backend: - var id_token = googleUser.getAuthResponse().id_token; + const id_token: string = googleUser.getAuthResponse().id_token; console.log("ID Token: " + id_token); -}; - +} /* Example taken from https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html */ // Enter an API key from the Google API Console: // https://console.developers.google.com/apis/credentials -var apiKey = 'YOUR_API_KEY'; +const apiKey = 'YOUR_API_KEY'; // Enter the API Discovery Docs that describes the APIs you want to // access. In this example, we are accessing the People API, so we load // Discovery Doc found here: https://developers.google.com/people/api/rest/ -var discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"]; +const discoveryDocs = ["https://people.googleapis.com/$discovery/rest?version=v1"]; // Enter a client ID for a web application from the Google API Console: // https://console.developers.google.com/apis/credentials?project=_ // In your API Console project, add a JavaScript origin that corresponds // to the domain where you will be running the script. -var clientId = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com'; +const clientId = 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com'; // Enter one or more authorization scopes. Refer to the documentation for // the API or https://developers.google.com/people/v1/how-tos/authorizing // for details. -var scopes = 'profile'; -var authorizeButton = document.getElementById('authorize-button'); -var signoutButton = document.getElementById('signout-button'); +const scopes = 'profile'; +const authorizeButton = document.getElementById('authorize-button'); +const signoutButton = document.getElementById('signout-button'); function handleClientLoad() { // Load the API client and auth2 library gapi.load('client:auth2', initClient); } function initClient() { gapi.client.init({ - apiKey: apiKey, - discoveryDocs: discoveryDocs, - clientId: clientId, + apiKey, + discoveryDocs, + clientId, scope: scopes - }).then(function () { + }).then(() => { // Listen for sign-in state changes. gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus); // Handle the initial sign-in state. @@ -144,9 +145,9 @@ function handleSignoutClick(event: MouseEvent) { function makeApiCall() { gapi.client.people.people.get({ resourceName: 'people/me' - }).then(function (resp) { - var p = document.createElement('p'); - var name = resp.result.names[0].givenName; + }).then((resp) => { + const p = document.createElement('p'); + const name = resp.result.names[0].givenName; p.appendChild(document.createTextNode('Hello, ' + name + '!')); document.getElementById('content').appendChild(p); }); diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index 6e9e5c4199..b1e0e925d4 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -7,13 +7,12 @@ /// declare namespace gapi.auth2 { - /** * GoogleAuth is a singleton class that provides methods to allow the user to sign in with a Google account, * get the user's current sign-in status, get specific data from the user's Google profile, * request additional scopes, and sign out from the current account. */ - export class GoogleAuth { + class GoogleAuth { isSignedIn: IsSignedIn; currentUser: CurrentUser; @@ -22,15 +21,11 @@ declare namespace gapi.auth2 { * Calls the onInit function when the GoogleAuth object is fully initialized, or calls the onFailure function if * initialization fails. */ - then(onInit: () => any, onFailure?: (reason: string) => any): any; - - /** - * Signs in the user with the options specified to gapi.auth2.init(). - */ - signIn(): any; + then(onInit: (googleAuth: GoogleAuth) => any, onFailure?: (reason: string) => any): any; /** * Signs in the user using the specified options. + * If no option specified here, fallback to the options specified to gapi.auth2.init(). */ signIn(options?: SigninOptions | SigninOptionsBuilder): any; @@ -60,7 +55,7 @@ declare namespace gapi.auth2 { onsuccess: (googleUser: GoogleUser) => any, onfailure: (reason: string) => any): any; } - export interface IsSignedIn { + interface IsSignedIn { /** * Returns whether the current user is currently signed in. */ @@ -72,7 +67,7 @@ declare namespace gapi.auth2 { listen(listener: (signedIn: boolean) => any): void; } - export interface CurrentUser { + interface CurrentUser { /** * Returns a GoogleUser object that represents the current user. Note that in a newly-initialized * GoogleAuth instance, the current user has not been set. Use the currentUser.listen() method or the @@ -86,7 +81,7 @@ declare namespace gapi.auth2 { listen(listener: (user: GoogleUser) => any): void; } - export interface SigninOptions { + interface SigninOptions { /** * The package name of the Android app to install over the air. * See Android app installs from your web site: @@ -112,14 +107,14 @@ declare namespace gapi.auth2 { scope?: string; } - export class SigninOptionsBuilder { + class SigninOptionsBuilder { setAppPackageName(name: string): any; setFetchBasicProfile(fetch: boolean): any; setPrompt(prompt: string): any; setScope(scope: string): any; } - export interface BasicProfile { + interface BasicProfile { getId(): string; getName(): string; getGivenName(): string; @@ -128,7 +123,7 @@ declare namespace gapi.auth2 { getEmail(): string; } - export interface AuthResponse { + interface AuthResponse { access_token: string; id_token: string; login_hint: string; @@ -141,7 +136,7 @@ declare namespace gapi.auth2 { /** * A GoogleUser object represents one user account. */ - export interface GoogleUser { + interface GoogleUser { /** * Get the user's unique ID string. */ @@ -208,52 +203,62 @@ declare namespace gapi.auth2 { disconnect(): void; } + function init(params: { + /** + * The app's client ID, found and created in the Google Developers Console. + */ + client_id?: string; - export function init(params: { - /** - * The app's client ID, found and created in the Google Developers Console. - */ - client_id?: string; + /** + * The domains for which to create sign-in cookies. Either a URI, single_host_origin, or none. + * Defaults to single_host_origin if unspecified. + */ + cookie_policy?: string; - /** - * The domains for which to create sign-in cookies. Either a URI, single_host_origin, or none. - * Defaults to single_host_origin if unspecified. - */ - cookie_policy?: string; + /** + * The scopes to request, as a space-delimited string. Optional if fetch_basic_profile is not set to false. + */ + scope?: string; - /** - * The scopes to request, as a space-delimited string. Optional if fetch_basic_profile is not set to false. - */ - scope?: string; + /** + * Fetch users' basic profile information when they sign in. Adds 'profile' and 'email' to the requested scopes. True if unspecified. + */ + fetch_basic_profile?: boolean; - /** - * Fetch users' basic profile information when they sign in. Adds 'profile' and 'email' to the requested scopes. True if unspecified. - */ - fetch_basic_profile?: boolean; + /** + * The Google Apps domain to which users must belong to sign in. This is susceptible to modification by clients, + * so be sure to verify the hosted domain property of the returned user. Use GoogleUser.getHostedDomain() on the client, + * and the hd claim in the ID Token on the server to verify the domain is what you expected. + */ + hosted_domain?: string; - /** - * The Google Apps domain to which users must belong to sign in. This is susceptible to modification by clients, - * so be sure to verify the hosted domain property of the returned user. Use GoogleUser.getHostedDomain() on the client, - * and the hd claim in the ID Token on the server to verify the domain is what you expected. - */ - hosted_domain?: string; + /** + * Used only for OpenID 2.0 client migration. Set to the value of the realm that you are currently using for OpenID 2.0, + * as described in OpenID 2.0 (Migration). + */ + openid_realm?: string; - /** - * Used only for OpenID 2.0 client migration. Set to the value of the realm that you are currently using for OpenID 2.0, - * as described in OpenID 2.0 (Migration). - */ - openid_realm?: string; + /** + * The UX mode to use for the sign-in flow. + * By default, it will open the consent flow in a popup. + */ + ux_mode?: "popup" | "redirect"; + + /** + * If using ux_mode='redirect', this parameter allows you to override the default redirect_uri that will be used at the end of the consent flow. + * The default redirect_uri is the current URL stripped of query parameters and hash fragment. + */ + redirect_uri?: string; }): GoogleAuth; /** * Returns the GoogleAuth object. You must initialize the GoogleAuth object with gapi.auth2.init() before calling this method. */ - export function getAuthInstance(): GoogleAuth; + function getAuthInstance(): GoogleAuth; } declare namespace gapi.signin2 { - - export function render(id: any, options: { + function render(id: any, options: { /** * The auth scope or scopes to authorize. Auth scopes for individual APIs can be found in their documentation. */ @@ -280,15 +285,14 @@ declare namespace gapi.signin2 { theme?: string; /** - * The callback function to call when a user successfully signs in. - * This function must take one argument: an instance of gapi.auth2.GoogleUser (default: none). + * The callback function to call when a user successfully signs in (default: none). */ - onsuccess?: any; + onsuccess?(user: auth2.GoogleUser): void; /** - * The callback function to call when sign-in fails. This function takes no arguments (default: none). + * The callback function to call when sign-in fails (default: none). */ - onfailure?: any; + onfailure?(): void; /** * The package name of the Android app to install over the air. See diff --git a/types/gapi.auth2/tslint.json b/types/gapi.auth2/tslint.json new file mode 100644 index 0000000000..5cd702e55e --- /dev/null +++ b/types/gapi.auth2/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "indent": { + "options": [true, "spaces", 2] + } + } +} From 25b5d3eadb3333167ac9c271270c20e0ab9aa4f4 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Wed, 19 Jul 2017 09:36:42 +0900 Subject: [PATCH 0132/1139] Add @types/filenamify --- types/filenamify/filenamify-tests.ts | 10 ++++++++++ types/filenamify/index.d.ts | 15 +++++++++++++++ types/filenamify/tsconfig.json | 22 ++++++++++++++++++++++ types/filenamify/tslint.json | 7 +++++++ 4 files changed, 54 insertions(+) create mode 100644 types/filenamify/filenamify-tests.ts create mode 100644 types/filenamify/index.d.ts create mode 100644 types/filenamify/tsconfig.json create mode 100644 types/filenamify/tslint.json diff --git a/types/filenamify/filenamify-tests.ts b/types/filenamify/filenamify-tests.ts new file mode 100644 index 0000000000..212ff424cf --- /dev/null +++ b/types/filenamify/filenamify-tests.ts @@ -0,0 +1,10 @@ +import * as filenamify from 'filenamify'; + +filenamify(''); +// => 'foo!bar' + +filenamify('foo:"bar"', {replacement: '🐴'}); +// => 'foo🐴bar' + +filenamify.path('/some/!path'); +// => '/some/path' diff --git a/types/filenamify/index.d.ts b/types/filenamify/index.d.ts new file mode 100644 index 0000000000..981b04443d --- /dev/null +++ b/types/filenamify/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for filenamify 2.0 +// Project: https://github.com/sindresorhus/filenamify +// Definitions by: Junyoung Choi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function filenamify(input: string, options?: filenamify.Options): string; + +declare namespace filenamify { + interface Options { + replacement: string; + } + function path(input: string, options?: filenamify.Options): string; +} + +export = filenamify; diff --git a/types/filenamify/tsconfig.json b/types/filenamify/tsconfig.json new file mode 100644 index 0000000000..aec1f33988 --- /dev/null +++ b/types/filenamify/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "filenamify-tests.ts" + ] +} diff --git a/types/filenamify/tslint.json b/types/filenamify/tslint.json new file mode 100644 index 0000000000..279473e356 --- /dev/null +++ b/types/filenamify/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // This package uses the Function type, and it will take effort to fix. + "ban-types": false + } +} From c1a7c7335a4840ab3554dd06e3e9fcaaebbbc62b Mon Sep 17 00:00:00 2001 From: Cayle Sharrock Date: Wed, 19 Jul 2017 09:48:11 +0200 Subject: [PATCH 0133/1139] Make bintrees TS 2.4 compliant --- types/bintrees/bintrees-tests.ts | 4 +++- types/bintrees/index.d.ts | 12 ++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/types/bintrees/bintrees-tests.ts b/types/bintrees/bintrees-tests.ts index 707d8e0adf..fa03ae5941 100644 --- a/types/bintrees/bintrees-tests.ts +++ b/types/bintrees/bintrees-tests.ts @@ -4,7 +4,6 @@ let treeA = new RBTree((a:number, b:number) => a - b); treeA.insert(5); treeA.insert(3); -treeA.remove(3); let treeB = new BinTree((a:string, b:string) => a.length - b.length); @@ -12,3 +11,6 @@ treeB.insert('hi'); treeB.insert('there'); treeB.insert('how'); treeB.insert('are'); + +treeB.remove('how'); + diff --git a/types/bintrees/index.d.ts b/types/bintrees/index.d.ts index 7a7b2c233e..743997dc03 100644 --- a/types/bintrees/index.d.ts +++ b/types/bintrees/index.d.ts @@ -5,8 +5,8 @@ declare module 'bintrees' { - type Callback = (item: T) => void; - type Comparator = (a: T, b: T) => number; + type Callback = (item: T) => void; + type Comparator = (a: T, b: T) => number; class Iterator { constructor(tree: TreeBase); @@ -37,14 +37,14 @@ declare module 'bintrees' { iterator(): Iterator; - each(cb: Callback): void; + each(cb: Callback): void; - reach(cb: Callback): void; + reach(cb: Callback): void; } export class RBTree extends TreeBase { - constructor(comparator: Comparator); + constructor(comparator: Comparator); insert(item: T): boolean; @@ -52,7 +52,7 @@ declare module 'bintrees' { } export class BinTree extends TreeBase { - constructor(comparator: Comparator); + constructor(comparator: Comparator); insert(item: T): boolean; From 3db20be3ee800c7eb4a160d9982d547663f3fd63 Mon Sep 17 00:00:00 2001 From: Cayle Sharrock Date: Wed, 19 Jul 2017 10:11:10 +0200 Subject: [PATCH 0134/1139] Mocha-fy and add test --- types/bintrees/bintrees-tests.ts | 52 ++++++++++++++++++++++++++------ 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/types/bintrees/bintrees-tests.ts b/types/bintrees/bintrees-tests.ts index fa03ae5941..fb4a22a3d8 100644 --- a/types/bintrees/bintrees-tests.ts +++ b/types/bintrees/bintrees-tests.ts @@ -1,16 +1,50 @@ +/// +/// +import assert = require('assert'); import { BinTree, RBTree } from 'bintrees'; -let treeA = new RBTree((a:number, b:number) => a - b); +describe('bintrees', () => { + it('builds a simple tree', () => { + let treeA = new RBTree((a: number, b: number) => a - b); -treeA.insert(5); -treeA.insert(3); + treeA.insert(5); + treeA.insert(3); + treeA.remove(3); -let treeB = new BinTree((a:string, b:string) => a.length - b.length); + assert.equal(treeA.size, 1); + }); -treeB.insert('hi'); -treeB.insert('there'); -treeB.insert('how'); -treeB.insert('are'); + it('builds a tree of strings', () => { + let treeB = new BinTree((a:string, b:string) => a.length - b.length); -treeB.remove('how'); + treeB.insert('hi'); + treeB.insert('there'); + treeB.insert('how'); + treeB.insert('are'); // ignored + treeB.remove('how'); + + assert.equal(treeB.size, 2); + assert.equal(treeB.min(), 'hi'); + }); + + it('maintains a tree of objects', () => { + + interface C { + id: number + } + + let treeC = new BinTree((a: C, b: C) => a.id - b.id); + + treeC.insert({ id: 100 }); + treeC.insert({ id: 110 }); + treeC.insert({ id: 105 }); + + let ids: number[] = []; + treeC.each((val: C) => { + ids.push(val.id); + }); + + assert.deepEqual(ids, [100, 105, 110]); + }); +}); From 0699b28ca125baa2ed5d0f55ecf0c8b493ed8de4 Mon Sep 17 00:00:00 2001 From: Ali Taheri Moghaddar Date: Tue, 18 Jul 2017 18:03:38 +0430 Subject: [PATCH 0135/1139] Improve exceljs typings and tests --- types/exceljs/exceljs-tests.ts | 454 ++++++++++++-- types/exceljs/index.d.ts | 1069 ++++++++++++++++++++++++++++---- 2 files changed, 1358 insertions(+), 165 deletions(-) diff --git a/types/exceljs/exceljs-tests.ts b/types/exceljs/exceljs-tests.ts index 95147c7726..12b3337cb8 100644 --- a/types/exceljs/exceljs-tests.ts +++ b/types/exceljs/exceljs-tests.ts @@ -1,4 +1,7 @@ import * as Excel from 'exceljs'; +import * as stream from 'stream'; +import * as fs from 'fs'; +import * as Bluebird from 'bluebird'; // most examples taken and adapted from README.md @@ -18,65 +21,446 @@ workbook.views = [ } ]; -const worksheet: Excel.Worksheet = workbook.addWorksheet('My Sheet'); +const worksheet = workbook.addWorksheet('My Sheet'); + +workbook.eachSheet((worksheet, sheetId) => null); + const worksheet2 = workbook.getWorksheet('My Sheet'); const worksheet3 = workbook.getWorksheet(1); -const sheet = workbook.addWorksheet('My Sheet', {views: [{showGridLines: false}]}); +const sheet1 = workbook.addWorksheet('My Sheet', { + pageSetup: { fitToPage: true, fitToHeight: 5, fitToWidth: 7 }, + properties: { tabColor: { argb: 'FFC0000' } }, +}); +const sheet2 = workbook.addWorksheet('My Sheet', { + pageSetup: { paperSize: 9, orientation: 'landscape' }, + views: [ + { state: 'frozen', xSplit: 1, ySplit: 1 }, + { state: 'normal', showGridLines: false }, + { state: 'split', activePane: 'bottomLeft', } + ] +}); + +worksheet.properties.outlineLevelCol = 2; +worksheet.properties.defaultRowHeight = 15; + +worksheet.pageSetup.margins = { + left: 0.7, right: 0.7, + top: 0.75, bottom: 0.75, + header: 0.3, footer: 0.3 +}; + +worksheet.pageSetup.printArea = 'A1:G20'; +worksheet.pageSetup.printTitlesRow = '1:3'; + +worksheet.views = [ + { state: 'frozen', xSplit: 2, ySplit: 3, topLeftCell: 'G10', activeCell: 'A1' }, + { state: 'split', xSplit: 2000, ySplit: 3000, topLeftCell: 'G10', activeCell: 'A1' }, +]; + +worksheet.autoFilter = { from: 'A1', to: 'C1' }; +worksheet.autoFilter = { from: { row: 3, column: 1 }, to: { row: 5, column: 12 } }; +worksheet.autoFilter = { from: 'D3', to: { row: 7, column: 5 } }; + +worksheet.columns = [ + { header: 'Id', key: 'id', width: 10 }, + { header: 'Name', key: 'name', width: 32 }, + { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } +]; + +const idCol = worksheet.getColumn('id'); +const nameCol = worksheet.getColumn('B'); +const dobCol = worksheet.getColumn(3); + +dobCol.header = 'Date of Birth'; +dobCol.header = ['Date of Birth', 'A.K.A. D.O.B.']; +dobCol.key = 'dob'; +dobCol.width = 15; +dobCol.hidden = true; +worksheet.getColumn(4).outlineLevel = 0; +const cl1 = worksheet.getColumn(4).collapsed; + +dobCol.eachCell((cell, rowNumber) => null); + +dobCol.eachCell({ includeEmpty: true }, (cell, rowNumber) => null); + +worksheet.spliceColumns(3, 2); + +const newCol3Values = [1, 2, 3, 4, 5]; +const newCol4Values = ['one', 'two', 'three', 'four', 'five']; +worksheet.spliceColumns(3, 1, newCol3Values, newCol4Values); + +worksheet.addRow({ id: 1, name: 'John Doe', dob: new Date(1970, 1, 1) }); +worksheet.addRow({ id: 2, name: 'Jane Doe', dob: new Date(1965, 1, 7) }); +worksheet.addRow([3, 'Sam', new Date()]); +const rowValues = []; +rowValues[1] = 4; +rowValues[5] = 'Kyle'; +rowValues[9] = new Date(); +worksheet.addRow(rowValues); +const rows = [ + [5, 'Bob', new Date()], + { id: 6, name: 'Barbara', dob: new Date() }, +]; +worksheet.addRows(rows); + +const row = worksheet.getRow(5); +const row1 = worksheet.lastRow; + +row.height = 42.5; +row.hidden = true; +worksheet.getRow(4).outlineLevel = 0; +worksheet.getRow(5).outlineLevel = 1; +worksheet.getRow(4).collapsed; -const row: Excel.Row = worksheet.addRow([3, 'Sam', new Date()]); row.getCell(1).value = 5; +row.getCell('name').value = 'Zeb'; +row.getCell('C').value = new Date(); -worksheet.eachRow((row: Excel.Row, rowNumber: number): void => { - // nothing -}); +const row2 = worksheet.getRow(4).values; -row.eachCell((cell: Excel.Cell, colNumber: number): void => { - // nothing -}); +row.values = [1, 2, 3]; + +const values = []; +values[5] = 7; +values[10] = 'Hello, World!'; +row.values = values; + +row.values = { id: 13, name: 'Thing 1', dob: new Date() }; + +worksheet.eachRow((row, rowNumber) => null); +worksheet.eachRow({ includeEmpty: true }, (row, rowNumber) => null); + +row.eachCell((cell, colNumber) => null); +row.eachCell({ includeEmpty: true }, (cell, colNumber) => null); + +worksheet.spliceRows(4, 3); + +const newRow3Values = [1, 2, 3, 4, 5]; +const newRow4Values = ['one', 'two', 'three', 'four', 'five']; +worksheet.spliceRows(3, 1, newRow3Values, newRow4Values); + +row.splice(3, 2); + +row.splice(4, 1, 'new value 1', 'new value 2'); + +row.commit(); + +const rowSize = row.cellCount; +const numValues = row.actualCellCount; + +worksheet.getCell('C3').value = new Date(1968, 5, 1); +const isDate = worksheet.getCell('C3').type === Excel.ValueType.Date; worksheet.mergeCells('A4:B5'); -worksheet.getCell('A1').numFmt = '0.00%'; -worksheet.getCell('A1').font = { - name: 'Comic Sans MS', - family: 4, - size: 16, - underline: true, - bold: true +worksheet.getCell('B5').value = 'Hello, World!'; +const master = worksheet.getCell('B5').master === worksheet.getCell('A4'); + +worksheet.unMergeCells('A4'); + +worksheet.mergeCells('G10', 'H11'); +worksheet.mergeCells(10, 11, 12, 13); + +worksheet.getCell('A1').name = 'PI'; +worksheet.getCell('A1').names = ['thing1', 'thing2']; +worksheet.getCell('A1').removeName('thing1'); + +worksheet.getCell('A1').dataValidation = { + type: 'list', + allowBlank: true, + formulae: ['"One,Two,Three,Four"'] }; +worksheet.getCell('A1').dataValidation = { + type: 'list', + allowBlank: true, + formulae: ['$D$5:$F$5'] +}; + +worksheet.getCell('A1').dataValidation = { + type: 'whole', + operator: 'notEqual', + showErrorMessage: true, + formulae: [5], + errorStyle: 'error', + errorTitle: 'Five', + error: 'The value must not be Five' +}; + +worksheet.getCell('A1').dataValidation = { + type: 'decimal', + operator: 'between', + allowBlank: true, + showInputMessage: true, + formulae: [1.5, 7], + promptTitle: 'Decimal', + prompt: 'The value must between 1.5 and 7' +}; + +worksheet.getCell('A1').dataValidation = { + type: 'textLength', + operator: 'lessThan', + showErrorMessage: true, + allowBlank: true, + formulae: [15] +}; + +worksheet.getCell('A1').dataValidation = { + type: 'date', + operator: 'lessThan', + showErrorMessage: true, + allowBlank: true, + formulae: [new Date(2016, 0, 1)] +}; + +worksheet.getCell('A1').value = null; +worksheet.getCell('A1').value = 5; +worksheet.getCell('A2').value = 3.14159; +worksheet.getCell('A1').value = 'Hello, World!'; +worksheet.getCell('A1').value = new Date(2017, 2, 15); +worksheet.getCell('A1').value = { text: 'www.mylink.com', hyperlink: 'http://www.mylink.com' }; +worksheet.getCell('A1').value = { text: 'Sheet2', hyperlink: '#\\"Sheet2\\"!A1' }; +worksheet.getCell('A3').value = { formula: 'A1+A2', result: 7 }; +worksheet.getCell('B3').value = { sharedFormula: 'A3', result: 10 }; +worksheet.getCell('A1').value = true; +worksheet.getCell('A2').value = false; +worksheet.getCell('A1').value = { error: '#N/A' }; +worksheet.getCell('A2').value = { error: '#VALUE!' }; +worksheet.getCell('A1').value = { + richText: [ + { text: 'This is ' }, + { font: { italic: true }, text: 'italic' } + ], +}; +worksheet.getCell('A3').formula === 'A1+A2'; +worksheet.getCell('A3').result === 7; + +const isMaster = worksheet.getCell('A3').formulaType === Excel.FormulaType.Master; +const isShared = worksheet.getCell('B3').formulaType === Excel.FormulaType.Shared; + +worksheet.getCell('A1').numFmt = '0.00%'; +worksheet.columns = [ + { header: 'Id', key: 'id', width: 10 }, + { header: 'Name', key: 'name', width: 32, style: { font: { name: 'Arial Black' } } }, + { header: 'D.O.B.', key: 'DOB', width: 10, style: { numFmt: 'dd/mm/yyyy' } } +]; + +worksheet.getColumn(3).numFmt = '"£"#,##0.00;[Red]\-"£"#,##0.00'; + +worksheet.getRow(2).font = { + name: 'Comic Sans MS', + family: 4, + size: 16, + underline: 'double', + bold: true, +}; + +worksheet.getCell('A1').numFmt = '# ?/?'; +worksheet.getCell('B1').numFmt = '0.00%'; + +worksheet.getCell('A1').font = { + name: 'Comic Sans MS', + family: 4, + size: 16, + underline: true, + bold: true +}; + +worksheet.getCell('A2').font = { + name: 'Arial Black', + color: { argb: 'FF00FF00' }, + family: 2, + size: 14, + italic: true +}; + +const font = { name: 'Arial', size: 12 }; +worksheet.getCell('A3').font = font; +font.size = 20; + worksheet.getCell('A1').alignment = { vertical: 'top', horizontal: 'left' }; worksheet.getCell('B1').alignment = { vertical: 'middle', horizontal: 'center' }; worksheet.getCell('C1').alignment = { vertical: 'bottom', horizontal: 'right' }; worksheet.getCell('D1').alignment = { wrapText: true }; worksheet.getCell('E1').alignment = { indent: 1 }; +worksheet.getCell('F1').alignment = { textRotation: 30 }; +worksheet.getCell('G1').alignment = { textRotation: -45 }; +worksheet.getCell('H1').alignment = { textRotation: 'vertical' }; worksheet.getCell('A1').border = { - top: {style: 'thin'}, - left: {style: 'thin'}, - bottom: {style: 'thin'}, - right: {style: 'thin'} + top: { style: 'thin' }, + left: { style: 'thin' }, + bottom: { style: 'thin' }, + right: { style: 'thin' } }; worksheet.getCell('A3').border = { - top: {style: 'double', color: {argb: 'FF00FF00'}}, - left: {style: 'double', color: {argb: 'FF00FF00'}}, - bottom: {style: 'double', color: {argb: 'FF00FF00'}}, - right: {style: 'double', color: {argb: 'FF00FF00'}} + top: { style: 'double', color: { argb: 'FF00FF00' } }, + left: { style: 'double', color: { argb: 'FF00FF00' } }, + bottom: { style: 'double', color: { argb: 'FF00FF00' } }, + right: { style: 'double', color: { argb: 'FF00FF00' } } +}; + +worksheet.getCell('A5').border = { + diagonal: { up: true, down: true, style: 'thick', color: { argb: 'FFFF0000' } } }; worksheet.getCell('A1').fill = { - type: 'pattern', - pattern: 'solid', - fgColor: {argb: 'FFFF0000'} + type: 'pattern', + pattern: 'darkVertical', + fgColor: { argb: 'FFFF0000' } }; -workbook.xlsx.readFile("/home/john/bla.xlsx") - .then((): void => { - // use workbook - }); +worksheet.getCell('A2').fill = { + type: 'pattern', + pattern: 'darkTrellis', + fgColor: { argb: 'FFFFFF00' }, + bgColor: { argb: 'FF0000FF' } +}; -workbook.xlsx.writeFile("/home/john/bla.xlsx") - .then((): void => { - // done - }); +worksheet.getCell('A3').fill = { + type: 'gradient', + gradient: 'angle', + degree: 0, + stops: [ + { position: 0, color: { argb: 'FF0000FF' } }, + { position: 0.5, color: { argb: 'FFFFFFFF' } }, + { position: 1, color: { argb: 'FF0000FF' } } + ] +}; + +worksheet.getCell('A2').fill = { + type: 'gradient', + gradient: 'path', + center: { left: 0.5, top: 0.5 }, + stops: [ + { position: 0, color: { argb: 'FFFF0000' } }, + { position: 1, color: { argb: 'FF00FF00' } } + ] +}; + +worksheet.getCell('A1').value = { + richText: [ + { + text: 'This is ', + font: { name: 'Calibri', size: 12, color: { theme: 0 }, family: 2, scheme: 'minor' }, + }, + { + text: 'a', + font: { italic: true, size: 12, color: { theme: 0 }, name: 'Calibri', scheme: 'minor' }, + }, + { + text: ' ', + font: { size: 12, color: { theme: 1 }, name: 'Calibri', family: 2, scheme: 'minor' }, + }, + { + text: 'colorful', + font: { size: 12, color: { argb: 'FFFF6600' }, name: 'Calibri', scheme: 'minor' }, + }, + { + text: ' text ', + font: { size: 12, color: { theme: 1 }, name: 'Calibri', family: 2, scheme: 'minor' }, + }, + { + text: 'with', + font: { size: 12, color: { argb: 'FFCCFFCC' }, name: 'Calibri', scheme: 'minor' }, + }, + { + text: ' in-cell ', + font: { size: 12, color: { theme: 1 }, name: 'Calibri', family: 2, scheme: 'minor' }, + }, + { + text: 'format', + font: { bold: true, size: 12, name: 'Calibri', family: 2, scheme: 'minor' }, + } + ] +}; + +worksheet.columns = [ + { header: 'Id', key: 'id', width: 10 }, + { header: 'Name', key: 'name', width: 32 }, + { header: 'D.O.B.', key: 'DOB', width: 10, outlineLevel: 1 } +]; +worksheet.getColumn(3).outlineLevel = 1; +worksheet.getRow(3).outlineLevel = 1; +worksheet.properties.outlineLevelCol = 1; +worksheet.properties.outlineLevelRow = 1; + +const imageId1 = workbook.addImage({ + filename: 'path/to/image.jpg', + extension: 'jpeg', +}); +const imageId2 = workbook.addImage({ + buffer: fs.readFileSync('path/to.image.png'), + extension: 'png', +}); + +worksheet.addBackgroundImage(imageId1); +worksheet.addImage(imageId2, 'B2:D6'); +worksheet.addImage(imageId2, { + tl: { col: 1.5, row: 1.5 }, + br: { col: 3.5, row: 5.5 } +}); + +workbook.xlsx.readFile('./1.xlsx').then(() => null); +(new stream.Stream()).pipe(workbook.xlsx.createInputStream()); + +workbook.xlsx.writeFile('./1.xlsx').then(() => null); +workbook.xlsx.write(new stream.Stream()).then(() => null); + +workbook.csv.readFile('./1.xlsx').then(worksheet => null); +workbook.csv.read(new stream.Stream()).then(worksheet => null); + +(new stream.Stream()).pipe(workbook.csv.createInputStream()); + +const options1 = { dateFormats: ['DD/MM/YYYY'] }; +workbook.csv.readFile('./1.xlsx', options1).then(worksheet => null); + +const options2 = { + map(value: any, index: number) { + switch (index) { + case 0: + // column 1 is string + return value; + case 1: + // column 2 is a date + return new Date(value); + case 2: + // column 3 is JSON of a formula value + return JSON.parse(value); + default: + // the rest are numbers + return parseFloat(value); + } + } +}; +workbook.csv.readFile('./1.xlsx', options2).then(worksheet => null); + +workbook.csv.writeFile('./1.xlsx').then(() => null); + +// write to a stream +workbook.csv.write(new stream.Stream()).then(() => null); + +const workbookWriter = new Excel.stream.xlsx.WorkbookWriter({ + filename: './streamed-workbook.xlsx', + useStyles: true, + useSharedStrings: true +}); + +worksheet.addRow({ + id: 'i', + name: 'theName', + etc: 'someOtherDetail' +}).commit(); + +worksheet.mergeCells('A1:B2'); +worksheet.getCell('A1').value = 'I am merged'; +worksheet.getCell('C1').value = 'I am not'; +worksheet.getCell('C2').value = 'Neither am I'; +worksheet.getRow(2).commit(); + +worksheet.commit(); + +workbook.commit().then(() => null); + +Excel.config.setValue('promise', Bluebird); diff --git a/types/exceljs/index.d.ts b/types/exceljs/index.d.ts index 259eaccae1..be82b7d7f9 100644 --- a/types/exceljs/index.d.ts +++ b/types/exceljs/index.d.ts @@ -1,7 +1,353 @@ -// Type definitions for exceljs 0.4 +// Type definitions for exceljs 0.5 // Project: https://github.com/guyonroche/exceljs // Definitions by: Rogier Schouten +// Ali Taheri Moghaddar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +import { Writable, Stream } from 'stream'; + +export const enum RelationshipType { + None = 0, + OfficeDocument = 1, + Worksheet = 2, + CalcChain = 3, + SharedStrings = 4, + Styles = 5, + Theme = 6, + Hyperlink = 7 +} + +export const enum DocumentType { + Xlsx = 1 +} + +export const enum PaperSize { + Legal = 5, + Executive = 7, + A4 = 9, + A5 = 11, + B5 = 13, + Envelope_10 = 20, + Envelope_DL = 27, + Envelope_C5 = 28, + Envelope_B5 = 34, + Envelope_Monarch = 37, + Double_Japan_Postcard_Rotated = 82, + K16_197x273_mm = 119, +} + +export interface WorksheetViewCommon { + /** + * Sets the worksheet view's orientation to right-to-left, `false` by default + */ + rightToLeft?: boolean; + + /** + * The currently selected cell + */ + activeCell?: string; + + /** + * Shows or hides the ruler in Page Layout, `true` by default + */ + showRuler?: boolean; + + /** + * Shows or hides the row and column headers (e.g. A1, B1 at the top and 1,2,3 on the left, + * `true` by default + */ + showRowColHeaders?: boolean; + + /** + * Shows or hides the gridlines (shown for cells where borders have not been defined), + * `true` by default + */ + showGridLines?: boolean; + + /** + * Percentage zoom to use for the view, `100` by default + */ + zoomScale?: number; + + /** + * Normal zoom for the view, `100` by default + */ + zoomScaleNormal?: number; +} + +export interface WorksheetViewNormal { + /** + * Controls the view state + */ + state?: 'normal'; + + /** + * Presentation style + */ + style?: 'pageBreakPreview' | 'pageLayout'; +} + +export interface WorksheetViewFrozen { + /** + * Where a number of rows and columns to the top and left are frozen in place. + * Only the bottom left section will scroll + */ + state: 'frozen'; + + /** + * Presentation style + */ + style?: 'pageBreakPreview'; + + /** + * How many columns to freeze. To freeze rows only, set this to 0 or undefined + */ + xSplit?: number; + + /** + * How many rows to freeze. To freeze columns only, set this to 0 or undefined + */ + ySplit?: number; + + /** + * Which cell will be top-left in the bottom-right pane. Note: cannot be a frozen cell. + * Defaults to first unfrozen cell + */ + topLeftCell?: string; +} + +export interface WorksheetViewSplit { + /** + * Where the view is split into 4 sections, each semi-independently scrollable. + */ + state: 'split'; + + /** + * Presentation style + */ + style?: 'pageBreakPreview' | 'pageLayout'; + + /** + * How many points from the left to place the splitter. + * To split vertically, set this to 0 or undefined + */ + xSplit?: number; + + /** + * How many points from the top to place the splitter. + * To split horizontally, set this to 0 or undefined + */ + ySplit?: number; + + /** + * Which cell will be top-left in the bottom-right pane + */ + topLeftCell?: string; + + /** + * Which pane will be active + */ + activePane?: 'topLeft' | 'topRight' | 'bottomLeft' | 'bottomRight'; +} + +export type WorksheetView = + & WorksheetViewCommon + & (WorksheetViewNormal | WorksheetViewFrozen | WorksheetViewSplit); + +export interface WorkbookView { + x?: number; + y?: number; + width?: number; + height?: number; + firstSheet?: number; + activeTab?: number; + visibility?: string; +} + +export type FillPatterns = + | 'none' | 'solid' + | 'darkVertical' | 'darkHorizontal' | 'darkGrid' | 'darkTrellis' | 'darkDown' | 'darkUp' + | 'lightVertical' | 'lightHorizontal' | 'lightGrid' | 'lightTrellis' | 'lightDown' | 'lightUp' + | 'darkGray' | 'mediumGray' | 'lightGray' | 'gray125' | 'gray0625'; + +export interface FillPattern { + type: 'pattern'; + pattern: FillPatterns; + fgColor?: Color; + bgColor?: Color; +} + +export interface GradientStop { + position: number; + color: Color; +} + +export interface FillGradientAngle { + type: 'gradient'; + gradient: 'angle'; + + /** + * For 'angle' gradient, specifies the direction of the gradient. 0 is from the left to the right. + * Values from 1 - 359 rotates the direction clockwise + */ + degree: number; + + /** + * Specifies the gradient colour sequence. Is an array of objects containing position and + * color starting with position 0 and ending with position 1. + * Intermediary positions may be used to specify other colours on the path. + */ + stops: GradientStop[]; +} + +export interface FillGradientPath { + type: 'gradient'; + gradient: 'path'; + + /** + * For 'path' gradient. Specifies the relative coordinates for the start of the path. + * 'left' and 'top' values range from 0 to 1 + */ + center: { left: number; top: number }; + + /** + * Specifies the gradient colour sequence. Is an array of objects containing position and + * color starting with position 0 and ending with position 1. + * Intermediary positions may be used to specify other colours on the path. + */ + stops: GradientStop[]; +} + +export type Fill = FillPattern | FillGradientAngle | FillGradientPath; + +export interface Font { + name?: string; + size?: number; + family?: number; + scheme?: 'minor' | 'major' | 'none'; + charset?: number; + color?: Color; + bold?: boolean; + italic?: boolean; + underline?: boolean | 'none' | 'single' | 'double' | 'singleAccounting' | 'doubleAccounting'; + strike?: boolean; + outline?: boolean; +} + +export type BorderStyle = + | 'thin' | 'dotted' | 'hair' | 'medium' | 'double' | 'thick' | 'dashDot' + | 'dashDotDot' | 'slantDashDot' | 'mediumDashed' | 'mediumDashDotDot' | 'mediumDashDot'; + +export interface Color { + /** + * Hex string for alpha-red-green-blue e.g. FF00FF00 + */ + argb?: string; + + /** + * Choose a theme by index + */ + theme?: number; +} + +export interface Border { + style?: BorderStyle; + color?: Color; +} + +export interface BorderDiagonal extends Border { + up?: boolean; + down?: boolean; +} + +export interface Borders { + top?: Border; + left?: Border; + bottom?: Border; + right?: Border; + diagonal?: BorderDiagonal; +} + +export interface Margins { + top?: number; + left?: number; + bottom?: number; + right?: number; + header?: number; + footer?: number; +} + +export const enum ReadingOrder { + LeftToRight = 1, + RightToLeft = 2, +} + +export interface Alignment { + horizontal?: 'left' | 'center' | 'right' | 'fill' | 'justify' | 'centerContinuous' | 'distributed'; + vertical?: 'top' | 'middle' | 'bottom' | 'distributed' | 'justify'; + wrapText?: boolean; + indent?: number; + readingOrder?: 'rtl' | 'ltr'; + textRotation?: number | 'vertical'; +} + +export interface Style { + numFmt?: string; + font?: Font; + alignment?: Alignment; + border?: Borders; + fill?: Fill; +} + +export type DataValidationOperator = + | 'between' | 'notBetween' | 'equal' | 'notEqual' | 'greaterThan' | 'lessThan' + | 'greaterThanOrEqual' | 'lessThanOrEqual'; + +export interface DataValidation { + type: 'list' | 'whole' | 'decimal' | 'date' | 'textLength' | 'custom'; + formulae: any[]; + allowBlank?: boolean; + operator?: DataValidationOperator; + error?: string; + errorTitle?: string; + errorStyle?: string; + prompt?: string; + promptTitle?: string; + showErrorMessage?: boolean; + showInputMessage?: boolean; +} + +export interface CellErrorValue { + error: '#N/A' | '#REF!' | '#NAME?' | '#DIV/0!' | '#NULL!' | '#VALUE!' | '#NUM!'; +} + +export interface RichText { + text: string; + font?: Font; +} + +export interface CellRichTextValue { + richText: RichText[]; +} + +export interface CellHyperlinkValue { + text: string; + hyperlink: string; +} + +export interface CellFormulaValue { + formula: string; + result: number | string | Date; +} + +export interface CellSharedFormulaValue { + sharedFormula: string; + readonly formula?: string; + result: number | string | Date; +} export const enum ValueType { Null = 0, @@ -23,170 +369,449 @@ export const enum FormulaType { Shared = 2 } -export const enum RelationshipType { - None = 0, - OfficeDocument = 1, - Worksheet = 2, - CalcChain = 3, - SharedStrings = 4, - Styles = 5, - Theme = 6, - Hyperlink = 7 -} +export type CellValue = + | null | number | string | boolean | Date + | CellErrorValue + | CellRichTextValue | CellHyperlinkValue + | CellFormulaValue | CellSharedFormulaValue; -export const enum DocumentType { - Xlsx = 1 -} - -export const enum ReadingOrder { - RightToLeft = 1, - LeftToRight = 2, -} - -export interface ErrorValue { - error: "#N/A" | "#REF!" | "#NAME?" | "#DIV/0!" | "#NULL!" | "#VALUE!" | "#NUM!"; -} - -export interface WorksheetView { - state?: "normal" | "split" | "frozen"; - showRuler?: boolean; - showRowColHeaders?: boolean; - showGridLines?: boolean; - zoomScale?: number; - zoomScaleNormal?: number; - style?: "pageBreakPreview" | "pageLayout"; -} - -export interface WorkbookView { - x?: number; - y?: number; - width?: number; - height?: number; - firstSheet?: number; - activeTab?: number; - visibility?: string; -} - -export interface Fill { - type: "pattern" | "gradient"; - pattern?: "none" | "solid"; - fgColor?: Color; - bgColor?: Color; -} - -export interface Font { - name: string; - size?: number; - family?: number; - schema?: "minor" | "major" | "none"; - charset?: number; - color?: Color; - bold?: boolean; - italic?: boolean; - underline?: true | false | "none" | "single" | "double" | "singleAccounting" | "doubleAccounting"; - strike?: boolean; - outline?: boolean; -} - -export type BorderStyle = - "thin" | "dotted" | "dashDot" | "hair" | "dashDotDot" | "slantDashDot" | "mediumDashed" | "mediumDashDotDot" | - "mediumDashDot" | "medium" | "double" | "thick"; - -export interface Color { +export interface Cell extends Style { /** - * Hex string for alpha-red-green-blue e.g. FF00FF00 + * Assign (or get) a name for a cell (will overwrite any other names that cell had) */ - argb: string; -} + name?: string; -export interface Border { - style?: BorderStyle; - color?: Color; -} - -export interface Borders { - top?: Border; - left?: Border; - bottom?: Border; - right?: Border; -} - -export interface Alignment { - horizontal?: "left" | "center" | "right" | "fill" | "justify" | "centerContinuous" | "distributed"; - vertical?: "top" | "middle" | "bottom" | "distributed" | "justify"; - wrapText?: boolean; - indent?: number; - readingOrder?: "rtl" | "ltr"; - textrotation?: number | "vertical"; -} - -export interface Cell { - border?: Borders; - font?: Font; - alignment?: Alignment; - numFmt?: string; - value?: any; - fill?: Fill; -} - -export interface Row { /** - * The row number + * Assign (or get) an array of names for a cell (cells can have more than one name) + */ + names?: string[]; + + /** + * Cells can define what values are valid or not and provide + * prompting to the user to help guide them. + */ + dataValidation?: DataValidation; + + /** + * Value of the cell + */ + value: CellValue; + + /** + * convenience getter to access the formula + */ + readonly formula: string; + + /** + * convenience getter to access the formula result + */ + readonly result: number | string | Date; + + /** + * The type of the cell's value + */ + readonly type: ValueType; + + /** + * The type of the cell's formula + */ + readonly formulaType: FormulaType; + + /** + * The master cell when the current cell is a merge cell + */ + master?: Cell; + + /** + * The styles of the cell + */ + style: Style; + + /** + * Remove a name from a cell + */ + removeName(name: string): void; +} + +export interface Row extends Style { + /** + * Set a specific row height */ - number: number; height: number; + + /** + * Make row hidden + */ hidden: boolean; - collapsed: boolean; - values: any[]; + + /** + * Get a row as a sparse array + */ + values: any[] | any; + + /** + * Set an outline level for rows + */ outlineLevel?: number; + /** + * Indicate the collapsed state based on outlineLevel + */ + readonly collapsed: boolean; + + /** + * Number of non-empty cells + */ readonly cellCount: number; + + /** + * Number of cells including empty ones + */ readonly actualCellCount: number; - getCell(index: number): Cell; + /** + * Get cell by number, column letter or column key + */ + getCell(indexOrKey: number | string): Cell; + /** + * Iterate over all non-null cells in a row + */ eachCell(callback: (cell: Cell, colNumber: number) => void): void; - eachCell(opts: { includeEmpty: boolean}, callback: (cell: Cell, colNumber: number) => void): void; + + /** + * Iterate over all cells in a row (including empty cells) + */ + eachCell(opt: { includeEmpty: boolean }, callback: (cell: Cell, colNumber: number) => void): void; + + /** + * Cut one or more cells (cells to the right are shifted left) + * + * Note: this operation will not affect other rows + */ + splice(start: number, count: number, ...insert: any[]): void; + + /** + * Commit a completed row to stream + */ + commit(): void; } export interface Column { + /** + * Can be a string to set one row high header or an array to set multi-row high header + */ + header: string | string[]; + + /** + * The name of the properties associated with this column in each row + */ + key: string; + + /** + * The width of the column + */ width: number; + + /** + * Set an outline level for columns + */ + outlineLevel?: number; + + /** + * Hides the column + */ + hidden?: boolean; + + /** + * Styles applied to the column + */ + style?: Style; +} + +export interface ColumnExtension extends Style { + /** + * indicate the collapsed state based on outlineLevel + */ + readonly collapsed: boolean; + + /** + * Iterate over all current cells in this column + */ + eachCell(callback: (cell: Cell, rowNumber: number) => void): void; + + /** + * Iterate over all current cells in this column including empty cells + */ + eachCell(opt: { includeEmpty: boolean }, callback: (cell: Cell, rowNumber: number) => void): void; +} + +export interface PageSetup { + /** + * Whitespace on the borders of the page. Units are inches. + */ + margins?: Margins; + + /** + * Orientation of the page - i.e. taller (`'portrait'`) or wider (`'landscape'`). + * + * `'portrait'` by default + */ + orientation?: 'portrait' | 'landscape'; + + /** + * Horizontal Dots per Inch. Default value is 4294967295 + */ + horizontalDpi?: number; + + /** + * Vertical Dots per Inch. Default value is 4294967295 + */ + verticalDpi?: number; + + /** + * Whether to use fitToWidth and fitToHeight or scale settings. + * + * Default is based on presence of these settings in the pageSetup object - if both are present, + * scale wins (i.e. default will be false) + */ + fitToPage?: boolean; + + /** + * How many pages wide the sheet should print on to. Active when fitToPage is true + * + * Default is 1 + */ + fitToWidth?: number; + + /** + * How many pages high the sheet should print on to. Active when fitToPage is true + * + * Default is 1 + */ + fitToHeight?: number; + + /** + * Percentage value to increase or reduce the size of the print. Active when fitToPage is false + * + * Default is 100 + */ + scale?: number; + + /** + * Which order to print the pages. + * + * Default is `downThenOver` + */ + pageOrder?: 'downThenOver' | 'overThenDown'; + + /** + * Print without colour + * + * false by default + */ + blackAndWhite?: boolean; + + /** + * Print with less quality (and ink) + * + * false by default + */ + draft?: boolean; + + /** + * Where to place comments + * + * Default is `None` + */ + cellComments?: 'atEnd' | 'asDisplayed' | 'None'; + + /** + * Where to show errors + * + * Default is `displayed` + */ + errors?: 'dash' | 'blank' | 'NA' | 'displayed'; + + /** + * What paper size to use (see below) + * + * | Name | Value | + * | ----------------------------- | --------- | + * | Letter | `undefined` | + * | Legal | `5` | + * | Executive | `7` | + * | A4 | `9` | + * | A5 | `11` | + * | B5 (JIS) | `13` | + * | Envelope #10 | `20` | + * | Envelope DL | `27` | + * | Envelope C5 | `28` | + * | Envelope B5 | `34` | + * | Envelope Monarch | `37` | + * | Double Japan Postcard Rotated | `82` | + * | 16K 197x273 mm | `119` | + */ + paperSize?: PaperSize; + + /** + * Whether to show the row numbers and column letters, `false` by default + */ + showRowColHeaders?: boolean; + + /** + * Whether to show grid lines, `false` by default + */ + showGridLines?: boolean; + + /** + * Which number to use for the first page + */ + firstPageNumber?: number; + + /** + * Whether to center the sheet data horizontally, `false` by default + */ + horizontalCentered?: boolean; + + /** + * Whether to center the sheet data vertically, `false` by default + */ + verticalCentered?: boolean; + + /** + * Set Print Area for a sheet, e.g. `'A1:G20'` + */ + printArea?: string; + + /** + * Repeat specific rows on every printed page, e.g. `'1:3'` + */ + printTitlesRow?: string; +} + +export type AutoFilter = string | { + from: string | { row: number; column: number }; + to: string | { row: number; column: number }; +}; + +export interface Image { + extension: 'jpeg' | 'png' | 'gif'; + filename?: string; + buffer?: Buffer; +} + +export interface ImageRange { + tl: { col: number; row: number }; + br: { col: number; row: number }; } export interface Worksheet { + /** + * Contains information related to how a worksheet is printed + */ + pageSetup: PageSetup; + + /** + * Worksheet Properties + */ + properties: WorksheetProperties; + + /** + * Open panes representing the sheet + */ + views: WorksheetView[]; + + /** + * Apply an auto filter to your worksheet. + */ + autoFilter?: AutoFilter; + + /** + * Add column headers and define column keys and widths. + * + * Note: these column structures are a workbook-building convenience only, + * apart from the column width, they will not be fully persisted. + */ + columns?: Column[]; + /** * The total row size of the document. Equal to the row number of the last row that has values. */ - rowCount: number; + readonly rowCount: number; + /** * A count of the number of rows that have values. If a mid-document row is empty, it will not be included in the count. */ - actualRowCount: number; + readonly actualRowCount: number; + /** * The total column size of the document. Equal to the maximum cell count from all of the rows */ - columnCount: number; + readonly columnCount: number; + /** * A count of the number of columns that have values. */ - actualColumnCount: number; + readonly actualColumnCount: number; /** - * Get or create a column + * Get the last editable row in a worksheet (or undefined if there are none) */ - getColumn(index: number): Column; + readonly lastRow: Row | undefined; /** - * Create a new row + * Access an individual columns by key, letter and 1-based column number */ - addRow(data: any[]): Row; + getColumn(indexOrKey: number | string): Column & ColumnExtension; + + /** + * Cut one or more columns (columns to the right are shifted left) + * and optionally insert more + * + * If column properties have been definde, they will be cut or moved accordingly + * + * Known Issue: If a splice causes any merged cells to move, the results may be unpredictable + * + * Also: If the worksheet has more rows than values in the colulmn inserts, + * the rows will still be shifted as if the values existed + */ + spliceColumns(start: number, count: number, ...insert: any[][]): void; + + /** + * Cut one or more rows (rows below are shifted up) + * and optionally insert more + * + * Known Issue: If a splice causes any merged cells to move, the results may be unpredictable + */ + spliceRows(start: number, count: number, ...insert: any[][]): void; + + /** + * Add a couple of Rows by key-value, after the last current row, using the column keys, + * or add a row by contiguous Array (assign to columns A, B & C) + */ + addRow(data: any[] | any): Row; + + /** + * Add multiple rows by providing an array of arrays or key-value pairs + */ + addRows(rows: any[]): void; /** * Get or create row by 0-based index */ getRow(index: number): Row; + + /** + * Iterate over all rows that have values in a worksheet + */ eachRow(callback: (row: Row, rowNumber: number) => void): void; + /** + * Iterate over all rows (including empty rows) in a worksheet + */ + eachRow(opt: { includeEmpty: boolean }, callback: (row: Row, rowNumber: number) => void): void; + /** * Get or create cell */ @@ -194,38 +819,222 @@ export interface Worksheet { /** * Merge cells, either: - * tlbr string - * tl string, br string - * t, l, b, r numbers + * + * tlbr string, e.g. `'A4:B5'` + * + * tl string, br string, e.g. `'G10', 'H11'` + * + * t, l, b, r numbers, e.g. `10,11,12,13` */ mergeCells(a: number | string, b?: number | string, c?: number, d?: number): void; + + /** + * unmerging the cells breaks the style links + */ + unMergeCells(cell: string): void; + + /** + * Using the image id from `Workbook.addImage`, set the background to the worksheet + */ + addBackgroundImage(imageId: string): void; + + /** + * Using the image id from `Workbook.addImage`, + * embed an image within the worksheet to cover a range + */ + addImage(imageId: string, range: string | ImageRange): void; + + /** + * Commit a completed worksheet to stream + */ + commit(): void; +} + +export interface WorksheetProperties { + /** + * Color of the tab + */ + tabColor?: Color; + + /** + * The worksheet column outline level (default: 0) + */ + outlineLevelCol?: number; + + /** + * The worksheet row outline level (default: 0) + */ + outlineLevelRow?: number; + + /** + * Default row height (default: 15) + */ + defaultRowHeight?: number; + + /** + * default: 55 + */ + dyDescent?: number; +} + +export interface AddWorksheetOptions { + properties?: WorksheetProperties; + pageSetup?: PageSetup; + views?: WorksheetView[]; +} + +export interface WorkbookProperties { + /** + * Set workbook dates to 1904 date system + */ + date1904: boolean; } export interface Xlsx { + /** + * read from a file + */ readFile(path: string): Promise; + + /** + * Create input stream for reading + */ + createInputStream(): Writable; + + /** + * write to a file + */ writeFile(path: string): Promise; + + /** + * write to a stream + */ + write(stream: Stream): Promise; } -export interface WorksheetProps { - showGridLines: boolean; +export interface CsvReadOptions { + dateFormats?: string[]; + map?(value: any, index: number): any; +} + +export interface CsvWriteOptions { + dateFormat?: string; +} + +export interface Csv { + /** + * read from a file + */ + readFile(path: string, options?: CsvReadOptions): Promise; + + /** + * read from a stream + */ + read(stream: Stream, options?: CsvReadOptions): Promise; + + /** + * Create input stream for reading + */ + createInputStream(): Writable; + + /** + * write to a file + */ + writeFile(path: string, options?: CsvWriteOptions): Promise; + + /** + * write to a stream + */ + write(stream: Stream, options?: CsvWriteOptions): Promise; } export class Workbook { - constructor(); - creator: string; lastModifiedBy: string; created: Date; modified: Date; lastPrinted: Date; - properties: { - date1904: boolean; - }; + properties: WorkbookProperties; + + /** + * xlsx file format operations + */ + readonly xlsx: Xlsx; + + /** + * csv file format operations + */ + readonly csv: Csv; + + /** + * The Workbook views controls how many separate windows Excel will open when viewing the workbook. + */ views: WorkbookView[]; - addWorksheet(name: string, opts?: { properties?: WorksheetProps, views?: WorksheetView[] }): Worksheet; + /** + * The list of worksheets added to this workbook + */ + worksheets: Worksheet[]; + /** + * Add a new worksheet and return a reference to it + */ + addWorksheet(name: string, options?: AddWorksheetOptions): Worksheet; + + /** + * fetch sheet by name or id + */ getWorksheet(indexOrName: number | string): Worksheet; - xlsx: Xlsx; + /** + * Iterate over all sheets. + * + * Note: `workbook.worksheets.forEach` will still work but this is better. + */ + eachSheet(callback: (worksheet: Worksheet, id: number) => void): void; + + /** + * Add Image to Workbook and return the id + */ + addImage(img: Image): string; + + /** + * Commit a completed workbook to stream and close the stream + */ + commit(): Promise; +} + +export namespace config { + function setValue(key: 'promise', promise: any): void; +} + +export namespace stream { + namespace xlsx { + interface WorkbookWriterOptions { + /** + * Specifies a writable stream to write the XLSX workbook to. + */ + stream?: Stream; + + /** + * If stream not specified, this field specifies the path to a file to write the XLSX workbook to. + */ + filename?: string; + + /** + * Specifies whether to use shared strings in the workbook. Default is false + */ + useSharedStrings?: boolean; + + /** + * Specifies whether to add style information to the workbook. + * Styles can add some performance overhead. Default is false + */ + useStyles?: boolean; + } + + class WorkbookWriter extends Workbook { + constructor(options: WorkbookWriterOptions); + } + } } From 9daad0b85191eaa2f612dec043d4f42b9fba43dc Mon Sep 17 00:00:00 2001 From: Stephen Ierodiaconou Date: Wed, 19 Jul 2017 10:06:19 +0100 Subject: [PATCH 0136/1139] Adding typings for next-redux-wrapper --- types/next-redux-wrapper/index.d.ts | 64 ++++++++++++++ .../next-redux-wrapper-tests.tsx | 87 +++++++++++++++++++ types/next-redux-wrapper/package.json | 5 ++ types/next-redux-wrapper/tsconfig.json | 24 +++++ types/next-redux-wrapper/tslint.json | 9 ++ 5 files changed, 189 insertions(+) create mode 100644 types/next-redux-wrapper/index.d.ts create mode 100644 types/next-redux-wrapper/next-redux-wrapper-tests.tsx create mode 100644 types/next-redux-wrapper/package.json create mode 100644 types/next-redux-wrapper/tsconfig.json create mode 100644 types/next-redux-wrapper/tslint.json diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts new file mode 100644 index 0000000000..f65f3f9d73 --- /dev/null +++ b/types/next-redux-wrapper/index.d.ts @@ -0,0 +1,64 @@ +// Type definitions for next-redux-wrapper 1.3 +// Project: https://github.com/kirill-konshin/next-redux-wrapper +// Definitions by: Steve +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// +/*~ Note that ES6 modules cannot directly export callable functions. + *~ This file should be imported using the CommonJS-style: + *~ import x = require('next-redux-wrapper'); + *~ + *~ Refer to the documentation to understand common + *~ workarounds for this limitation of ES6 modules. + */ + +import * as React from 'react'; +import { IncomingMessage } from 'http'; +import { + Store, Component, + MapDispatchToPropsParam, MapStateToPropsParam, + MergeProps, Options as ConnectOptions +} from 'react-redux'; + +export = nextReduxWrapper; + +interface NextPageComponentMethods { + getInitialProps(props: any): Promise; +} +type NextReduxWrappedComponent = React.Component & NextPageComponentMethods; + +type NextStoreCreator = ( + initialState: TInitialState, + options: nextReduxWrapper.StoreCreatorOptions +) => Store; + +declare function nextReduxWrapper( + options: nextReduxWrapper.Options +): (Component: Component) => NextReduxWrappedComponent; +declare function nextReduxWrapper( + createStore: NextStoreCreator, + mapStateToProps?: MapStateToPropsParam, + mapDispatchToProps?: MapDispatchToPropsParam, + mergeProps?: MergeProps, + options?: ConnectOptions +): (Component: Component) => NextReduxWrappedComponent; + +declare namespace nextReduxWrapper { + export interface Options { + createStore: NextStoreCreator; + debug?: boolean; + storeKey?: string; + mapStateToProps?: MapStateToPropsParam; + mapDispatchToProps?: MapDispatchToPropsParam; + mergeProps?: MergeProps; + connectOptions?: ConnectOptions; + } + export interface StoreCreatorOptions extends Options { + isServer: boolean; + req?: IncomingMessage; + } + + export function setPromise(Promise: any): void; + export function setDebug(debug: boolean): void; +} diff --git a/types/next-redux-wrapper/next-redux-wrapper-tests.tsx b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx new file mode 100644 index 0000000000..c432ae5ec9 --- /dev/null +++ b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx @@ -0,0 +1,87 @@ +import * as React from 'react'; +import withRedux = require('next-redux-wrapper'); +import { createStore, Store, AnyAction } from 'redux'; +import { StoreCreatorOptions } from 'next-redux-wrapper'; + +interface InitialState { + foo: string; +} + +const reducer = (state: InitialState = {foo: ''}, action: AnyAction) => { + switch (action.type) { + case 'FOO': + return {...state, foo: action.payload}; + default: + return state; + } +}; + +const makeStore = (initialState: InitialState): Store => { + return createStore(reducer, initialState); +}; + +interface Props { + foo: string; + custom: string; +} + +interface ReduxStore { + foo: string; +} + +class Page extends React.Component { + static getInitialProps({store, isServer, pathname, query}: any) { + store.dispatch({type: 'FOO', payload: 'foo'}); + return {custom: 'custom'}; + } + render() { + return ( +
+
Prop from Redux {this.props.foo}
+
Prop from getInitialProps {this.props.custom}
+
+ ); + } +} + +type ConnectStateProps = Props; +type DispatchProps = Props; +type OwnProps = Props; +type MergedProps = Props; + +// Test various typings +const com1 = withRedux(makeStore, (state: ReduxStore) => ({foo: state.foo}))(Page); + +const com2 = withRedux(makeStore, (state: ReduxStore) => ({foo: state.foo}))(Page); + +const com3 = withRedux(makeStore, (state: ReduxStore) => ({foo: state.foo}))(Page); + +const com4 = withRedux( + makeStore, + (state: ReduxStore) => ({foo: state.foo, custom: 'hi'}) +)(Page); + +const com5 = withRedux( + makeStore, + (state: ReduxStore) => ({foo: state.foo, custom: 'hi'}), + null, (state: Props) => ({foo: state.foo, custom: 'hi'}) +)(Page); + +const com6 = withRedux( + (initialState: InitialState, options: StoreCreatorOptions) => { + if (options.isServer) { + const a = 1; + } + return createStore(reducer, initialState); + }, + (state: ReduxStore) => ({foo: state.foo, custom: 'hi'}), + null, (state: Props) => ({foo: state.foo, custom: 'hi'}) +)(Page); + +const com7 = withRedux({ + createStore: makeStore, + mapStateToProps: (state: ReduxStore) => ({foo: state.foo}) +})(Page); + +withRedux.setPromise(Promise); +withRedux.setDebug(true); diff --git a/types/next-redux-wrapper/package.json b/types/next-redux-wrapper/package.json new file mode 100644 index 0000000000..e52256ea90 --- /dev/null +++ b/types/next-redux-wrapper/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "redux": "^3.6.0" + } +} \ No newline at end of file diff --git a/types/next-redux-wrapper/tsconfig.json b/types/next-redux-wrapper/tsconfig.json new file mode 100644 index 0000000000..f35fb6fa08 --- /dev/null +++ b/types/next-redux-wrapper/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "next-redux-wrapper-tests.tsx" + ] +} diff --git a/types/next-redux-wrapper/tslint.json b/types/next-redux-wrapper/tslint.json new file mode 100644 index 0000000000..98f9451050 --- /dev/null +++ b/types/next-redux-wrapper/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // All of the different "export default" lines in the index.d.ts + // appear to be triggering this. Remove this when I know of a way + // to declare a default export across multiple package/subpackages. + "strict-export-declare-modifiers": false + } +} From 9b935347f528101f20567a51d156c78a992907aa Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Tue, 18 Jul 2017 10:46:45 +0200 Subject: [PATCH 0137/1139] Fix linting errors for babel-types --- types/babel-types/babel-types-tests.ts | 8 +- types/babel-types/index.d.ts | 813 +++++++++++++------------ types/babel-types/tslint.json | 1 + 3 files changed, 433 insertions(+), 389 deletions(-) create mode 100644 types/babel-types/tslint.json diff --git a/types/babel-types/babel-types-tests.ts b/types/babel-types/babel-types-tests.ts index 394603ab31..0ef79f39f4 100644 --- a/types/babel-types/babel-types-tests.ts +++ b/types/babel-types/babel-types-tests.ts @@ -1,7 +1,3 @@ - -/// - - // Examples from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-types import traverse from "babel-traverse"; import * as t from "babel-types"; @@ -25,13 +21,13 @@ if (t.isBinaryExpression(ast)) { ast.right; ast.operator; } + t.assertBinaryExpression(ast); t.assertBinaryExpression(ast, { operator: "*" }); -var exp: t.Expression = t.nullLiteral(); +const exp: t.Expression = t.nullLiteral(); // React examples: - // https://github.com/babel/babel/blob/4e50b2d9d9c376cee7a2cbf56553fe5b982ea53c/packages/babel-plugin-transform-react-inline-elements/src/index.js#L61 traverse(ast, { JSXElement(path, file) { diff --git a/types/babel-types/index.d.ts b/types/babel-types/index.d.ts index c3f77b559f..1879c81e85 100644 --- a/types/babel-types/index.d.ts +++ b/types/babel-types/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for babel-types v6.25 +// Type definitions for babel-types 6.25 // Project: https://github.com/babel/babel/tree/master/packages/babel-types // Definitions by: Troy Gerwien // Sam Baxter // Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export interface Comment { value: string; @@ -34,9 +35,9 @@ export interface SourceLocation { export interface Node { type: string; - leadingComments?: Array; - innerComments?: Array; - trailingComments?: Array; + leadingComments?: Comment[]; + innerComments?: Comment[]; + trailingComments?: Comment[]; start: number; end: number; loc: SourceLocation; @@ -150,7 +151,7 @@ export interface ForStatement extends Node { export interface FunctionDeclaration extends Node { type: "FunctionDeclaration"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -161,7 +162,7 @@ export interface FunctionDeclaration extends Node { export interface FunctionExpression extends Node { type: "FunctionExpression"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -254,7 +255,7 @@ export interface ObjectMethod extends Node { value: Expression; decorators?: Decorator[]; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -361,14 +362,14 @@ export interface AssignmentPattern extends Node { export interface ArrayPattern extends Node { type: "ArrayPattern"; - elements: Array; + elements: Expression[]; typeAnnotation?: TypeAnnotation; } export interface ArrowFunctionExpression extends Node { type: "ArrowFunctionExpression"; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement | Expression; generator: boolean; async: boolean; @@ -474,7 +475,7 @@ export interface ClassMethod extends Node { static: boolean; decorators?: Decorator[]; id: Identifier; - params: Array; + params: LVal[]; body: BlockStatement; generator: boolean; async: boolean; @@ -872,12 +873,33 @@ export interface SpreadProperty extends Node { argument: Expression; } -export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; +export type Expression = ArrayExpression | AssignmentExpression | BinaryExpression | CallExpression + | ConditionalExpression | FunctionExpression | Identifier | StringLiteral | NumericLiteral | BooleanLiteral + | NullLiteral | RegExpLiteral | LogicalExpression | MemberExpression | NewExpression | ObjectExpression + | SequenceExpression | ThisExpression | UnaryExpression | UpdateExpression | ArrowFunctionExpression + | ClassExpression | MetaProperty | Super | TaggedTemplateExpression | TemplateLiteral | YieldExpression + | TypeCastExpression | JSXElement | JSXEmptyExpression | JSXIdentifier | JSXMemberExpression + | ParenthesizedExpression | AwaitExpression | BindExpression | DoExpression; + export type Binary = BinaryExpression | LogicalExpression; -export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; -export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression | ForOfStatement | ClassMethod; + +export type Scopable = BlockStatement | CatchClause | DoWhileStatement | ForInStatement | ForStatement + | FunctionDeclaration | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement + | ArrowFunctionExpression | ClassDeclaration | ClassExpression | ForOfStatement | ClassMethod; + +export type BlockParent = BlockStatement | DoWhileStatement | ForInStatement | ForStatement | FunctionDeclaration + | FunctionExpression | Program | ObjectMethod | SwitchStatement | WhileStatement | ArrowFunctionExpression + | ForOfStatement | ClassMethod; + export type Block = BlockStatement | Program; -export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + +export type Statement = BlockStatement | BreakStatement | ContinueStatement | DebuggerStatement | DoWhileStatement + | EmptyStatement | ExpressionStatement | ForInStatement | ForStatement | FunctionDeclaration | IfStatement + | LabeledStatement | ReturnStatement | SwitchStatement | ThrowStatement | TryStatement | VariableDeclaration + | WhileStatement | WithStatement | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration + | ExportNamedDeclaration | ForOfStatement | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface + | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + export type Terminatorless = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement | YieldExpression | AwaitExpression; export type CompletionStatement = BreakStatement | ContinueStatement | ReturnStatement | ThrowStatement; export type Conditional = ConditionalExpression | IfStatement; @@ -889,7 +911,11 @@ export type ForXStatement = ForInStatement | ForOfStatement; export type Function = FunctionDeclaration | FunctionExpression | ObjectMethod | ArrowFunctionExpression | ClassMethod; export type FunctionParent = FunctionDeclaration | FunctionExpression | Program | ObjectMethod | ArrowFunctionExpression | ClassMethod; export type Pureish = FunctionDeclaration | FunctionExpression | StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | ArrowFunctionExpression | ClassDeclaration | ClassExpression; -export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + +export type Declaration = FunctionDeclaration | VariableDeclaration | ClassDeclaration | ExportAllDeclaration + | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration | DeclareClass | DeclareFunction + | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; + export type LVal = Identifier | MemberExpression | RestElement | AssignmentPattern | ArrayPattern | ObjectPattern; export type Literal = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | RegExpLiteral | TemplateLiteral; export type Immutable = StringLiteral | NumericLiteral | BooleanLiteral | NullLiteral | JSXAttribute | JSXClosingElement | JSXElement | JSXExpressionContainer | JSXOpeningElement; @@ -903,15 +929,36 @@ export type Class = ClassDeclaration | ClassExpression; export type ModuleDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration | ImportDeclaration; export type ExportDeclaration = ExportAllDeclaration | ExportDefaultDeclaration | ExportNamedDeclaration; export type ModuleSpecifier = ExportSpecifier | ImportDefaultSpecifier | ImportNamespaceSpecifier | ImportSpecifier | ExportDefaultSpecifier | ExportNamespaceSpecifier; -export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | ClassImplements | ClassProperty | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | ExistentialTypeParam | FunctionTypeAnnotation | FunctionTypeParam | GenericTypeAnnotation | InterfaceExtends | InterfaceDeclaration | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameterDeclaration | TypeParameterInstantiation | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer | ObjectTypeProperty | QualifiedTypeIdentifier | UnionTypeAnnotation | VoidTypeAnnotation; -export type FlowTypeAnnotation = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | IntersectionTypeAnnotation | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation | TypeofTypeAnnotation | TypeAnnotation | ObjectTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation; + +export type Flow = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation | BooleanLiteralTypeAnnotation + | ClassImplements | ClassProperty | DeclareClass | DeclareFunction | DeclareInterface | DeclareModule + | DeclareTypeAlias | DeclareVariable | ExistentialTypeParam | FunctionTypeAnnotation | FunctionTypeParam + | GenericTypeAnnotation | InterfaceExtends | InterfaceDeclaration | IntersectionTypeAnnotation + | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation + | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation + | TypeofTypeAnnotation | TypeAlias | TypeAnnotation | TypeCastExpression | TypeParameterDeclaration + | TypeParameterInstantiation | ObjectTypeAnnotation | ObjectTypeCallProperty | ObjectTypeIndexer + | ObjectTypeProperty | QualifiedTypeIdentifier | UnionTypeAnnotation | VoidTypeAnnotation; + +export type FlowTypeAnnotation = AnyTypeAnnotation | ArrayTypeAnnotation | BooleanTypeAnnotation + | BooleanLiteralTypeAnnotation | FunctionTypeAnnotation | GenericTypeAnnotation | IntersectionTypeAnnotation + | MixedTypeAnnotation | NullableTypeAnnotation | NumericLiteralTypeAnnotation | NumberTypeAnnotation + | StringLiteralTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | TupleTypeAnnotation + | TypeofTypeAnnotation | TypeAnnotation | ObjectTypeAnnotation | UnionTypeAnnotation | VoidTypeAnnotation; + export type FlowBaseAnnotation = AnyTypeAnnotation | BooleanTypeAnnotation | MixedTypeAnnotation | NumberTypeAnnotation | StringTypeAnnotation | ThisTypeAnnotation | VoidTypeAnnotation; export type FlowDeclaration = DeclareClass | DeclareFunction | DeclareInterface | DeclareModule | DeclareTypeAlias | DeclareVariable | InterfaceDeclaration | TypeAlias; -export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText; + +export type JSX = JSXAttribute | JSXClosingElement | JSXElement | JSXEmptyExpression | JSXExpressionContainer + | JSXIdentifier | JSXMemberExpression | JSXNamespacedName | JSXOpeningElement | JSXSpreadAttribute | JSXText; export function arrayExpression(elements?: Array): ArrayExpression; export function assignmentExpression(operator?: string, left?: LVal, right?: Expression): AssignmentExpression; -export function binaryExpression(operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", left?: Expression, right?: Expression): BinaryExpression; +export function binaryExpression( + operator?: "+" | "-" | "/" | "%" | "*" | "**" | "&" | "|" | ">>" | ">>>" | "<<" | "^" | "==" | "===" | "!=" | "!==" | "in" | "instanceof" | ">" | "<" | ">=" | "<=", + left?: Expression, + right?: Expression +): BinaryExpression; export function directive(value?: DirectiveLiteral): Directive; export function directiveLiteral(value?: string): DirectiveLiteral; export function blockStatement(body?: Statement[], directives?: Directive[]): BlockStatement; @@ -927,8 +974,8 @@ export function expressionStatement(expression?: Expression): ExpressionStatemen export function file(program?: Program, comments?: Comment[], tokens?: any[]): File; export function forInStatement(left?: VariableDeclaration | LVal, right?: Expression, body?: Statement): ForInStatement; export function forStatement(init?: VariableDeclaration | Expression, test?: Expression, update?: Expression, body?: Statement): ForStatement; -export function functionDeclaration(id?: Identifier, params?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; -export function functionExpression(id?: Identifier, params?: Array, body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; +export function functionDeclaration(id?: Identifier, params?: LVal[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionDeclaration; +export function functionExpression(id?: Identifier, params?: LVal[], body?: BlockStatement, generator?: boolean, async?: boolean): FunctionExpression; export function identifier(name?: string): Identifier; export function ifStatement(test?: Expression, consequent?: Statement, alternate?: Statement): IfStatement; export function labeledStatement(label?: Identifier, body?: Statement): LabeledStatement; @@ -942,7 +989,7 @@ export function memberExpression(object?: Expression | Super, property?: Express export function newExpression(callee?: Expression | Super, _arguments?: Array): NewExpression; export function program(body?: Array, directives?: Directive[]): Program; export function objectExpression(properties?: Array): ObjectExpression; -export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: Array, body?: BlockStatement, computed?: boolean): ObjectMethod; +export function objectMethod(kind?: "get" | "set" | "method", key?: Expression, params?: LVal[], body?: BlockStatement, computed?: boolean): ObjectMethod; export function objectProperty(key?: Expression, value?: Expression, computed?: boolean, shorthand?: boolean, decorators?: Decorator[]): ObjectProperty; export function restElement(argument?: LVal, typeAnnotation?: TypeAnnotation): RestElement; export function returnStatement(argument?: Expression): ReturnStatement; @@ -959,8 +1006,8 @@ export function variableDeclarator(id?: LVal, init?: Expression): VariableDeclar export function whileStatement(test?: Expression, body?: BlockStatement | Statement): WhileStatement; export function withStatement(object?: Expression, body?: BlockStatement | Statement): WithStatement; export function assignmentPattern(left?: Identifier, right?: Expression): AssignmentPattern; -export function arrayPattern(elements?: Array, typeAnnotation?: TypeAnnotation): ArrayPattern; -export function arrowFunctionExpression(params?: Array, body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; +export function arrayPattern(elements?: Expression[], typeAnnotation?: TypeAnnotation): ArrayPattern; +export function arrowFunctionExpression(params?: LVal[], body?: BlockStatement | Expression, async?: boolean): ArrowFunctionExpression; export function classBody(body?: Array): ClassBody; export function classDeclaration(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassDeclaration; export function classExpression(id?: Identifier, superClass?: Expression, body?: ClassBody, decorators?: Decorator[]): ClassExpression; @@ -974,11 +1021,11 @@ export function importDefaultSpecifier(local?: Identifier): ImportDefaultSpecifi export function importNamespaceSpecifier(local?: Identifier): ImportNamespaceSpecifier; export function importSpecifier(local?: Identifier, imported?: Identifier): ImportSpecifier; export function metaProperty(meta?: string, property?: string): MetaProperty; -export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: Array, body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; +export function classMethod(kind?: "constructor" | "method" | "get" | "set", key?: Expression, params?: LVal[], body?: BlockStatement, computed?: boolean, _static?: boolean): ClassMethod; export function objectPattern(properties?: Array, typeAnnotation?: TypeAnnotation): ObjectPattern; export function spreadElement(argument?: Expression): SpreadElement; export function taggedTemplateExpression(tag?: Expression, quasi?: TemplateLiteral): TaggedTemplateExpression; -export function templateElement(value?: {cooked?: string; raw?: string;}, tail?: boolean): TemplateElement; +export function templateElement(value?: { cooked?: string; raw?: string; }, tail?: boolean): TemplateElement; export function templateLiteral(quasis?: TemplateElement[], expressions?: Expression[]): TemplateLiteral; export function yieldExpression(argument?: Expression, delegate?: boolean): YieldExpression; export function anyTypeAnnotation(): AnyTypeAnnotation; @@ -1044,367 +1091,367 @@ export function exportNamespaceSpecifier(exported?: Identifier): ExportNamespace export function restProperty(argument?: LVal): RestProperty; export function spreadProperty(argument?: Expression): SpreadProperty; -export function isArrayExpression(node: Object, opts?: Object): node is ArrayExpression; -export function isAssignmentExpression(node: Object, opts?: Object): node is AssignmentExpression; -export function isBinaryExpression(node: Object, opts?: Object): node is BinaryExpression; -export function isDirective(node: Object, opts?: Object): node is Directive; -export function isDirectiveLiteral(node: Object, opts?: Object): node is DirectiveLiteral; -export function isBlockStatement(node: Object, opts?: Object): node is BlockStatement; -export function isBreakStatement(node: Object, opts?: Object): node is BreakStatement; -export function isCallExpression(node: Object, opts?: Object): node is CallExpression; -export function isCatchClause(node: Object, opts?: Object): node is CatchClause; -export function isConditionalExpression(node: Object, opts?: Object): node is ConditionalExpression; -export function isContinueStatement(node: Object, opts?: Object): node is ContinueStatement; -export function isDebuggerStatement(node: Object, opts?: Object): node is DebuggerStatement; -export function isDoWhileStatement(node: Object, opts?: Object): node is DoWhileStatement; -export function isEmptyStatement(node: Object, opts?: Object): node is EmptyStatement; -export function isExpressionStatement(node: Object, opts?: Object): node is ExpressionStatement; -export function isFile(node: Object, opts?: Object): node is File; -export function isForInStatement(node: Object, opts?: Object): node is ForInStatement; -export function isForStatement(node: Object, opts?: Object): node is ForStatement; -export function isFunctionDeclaration(node: Object, opts?: Object): node is FunctionDeclaration; -export function isFunctionExpression(node: Object, opts?: Object): node is FunctionExpression; -export function isIdentifier(node: Object, opts?: Object): node is Identifier; -export function isIfStatement(node: Object, opts?: Object): node is IfStatement; -export function isLabeledStatement(node: Object, opts?: Object): node is LabeledStatement; -export function isStringLiteral(node: Object, opts?: Object): node is StringLiteral; -export function isNumericLiteral(node: Object, opts?: Object): node is NumericLiteral; -export function isNullLiteral(node: Object, opts?: Object): node is NullLiteral; -export function isBooleanLiteral(node: Object, opts?: Object): node is BooleanLiteral; -export function isRegExpLiteral(node: Object, opts?: Object): node is RegExpLiteral; -export function isLogicalExpression(node: Object, opts?: Object): node is LogicalExpression; -export function isMemberExpression(node: Object, opts?: Object): node is MemberExpression; -export function isNewExpression(node: Object, opts?: Object): node is NewExpression; -export function isProgram(node: Object, opts?: Object): node is Program; -export function isObjectExpression(node: Object, opts?: Object): node is ObjectExpression; -export function isObjectMethod(node: Object, opts?: Object): node is ObjectMethod; -export function isObjectProperty(node: Object, opts?: Object): node is ObjectProperty; -export function isRestElement(node: Object, opts?: Object): node is RestElement; -export function isReturnStatement(node: Object, opts?: Object): node is ReturnStatement; -export function isSequenceExpression(node: Object, opts?: Object): node is SequenceExpression; -export function isSwitchCase(node: Object, opts?: Object): node is SwitchCase; -export function isSwitchStatement(node: Object, opts?: Object): node is SwitchStatement; -export function isThisExpression(node: Object, opts?: Object): node is ThisExpression; -export function isThrowStatement(node: Object, opts?: Object): node is ThrowStatement; -export function isTryStatement(node: Object, opts?: Object): node is TryStatement; -export function isUnaryExpression(node: Object, opts?: Object): node is UnaryExpression; -export function isUpdateExpression(node: Object, opts?: Object): node is UpdateExpression; -export function isVariableDeclaration(node: Object, opts?: Object): node is VariableDeclaration; -export function isVariableDeclarator(node: Object, opts?: Object): node is VariableDeclarator; -export function isWhileStatement(node: Object, opts?: Object): node is WhileStatement; -export function isWithStatement(node: Object, opts?: Object): node is WithStatement; -export function isAssignmentPattern(node: Object, opts?: Object): node is AssignmentPattern; -export function isArrayPattern(node: Object, opts?: Object): node is ArrayPattern; -export function isArrowFunctionExpression(node: Object, opts?: Object): node is ArrowFunctionExpression; -export function isClassBody(node: Object, opts?: Object): node is ClassBody; -export function isClassDeclaration(node: Object, opts?: Object): node is ClassDeclaration; -export function isClassExpression(node: Object, opts?: Object): node is ClassExpression; -export function isExportAllDeclaration(node: Object, opts?: Object): node is ExportAllDeclaration; -export function isExportDefaultDeclaration(node: Object, opts?: Object): node is ExportDefaultDeclaration; -export function isExportNamedDeclaration(node: Object, opts?: Object): node is ExportNamedDeclaration; -export function isExportSpecifier(node: Object, opts?: Object): node is ExportSpecifier; -export function isForOfStatement(node: Object, opts?: Object): node is ForOfStatement; -export function isImportDeclaration(node: Object, opts?: Object): node is ImportDeclaration; -export function isImportDefaultSpecifier(node: Object, opts?: Object): node is ImportDefaultSpecifier; -export function isImportNamespaceSpecifier(node: Object, opts?: Object): node is ImportNamespaceSpecifier; -export function isImportSpecifier(node: Object, opts?: Object): node is ImportSpecifier; -export function isMetaProperty(node: Object, opts?: Object): node is MetaProperty; -export function isClassMethod(node: Object, opts?: Object): node is ClassMethod; -export function isObjectPattern(node: Object, opts?: Object): node is ObjectPattern; -export function isSpreadElement(node: Object, opts?: Object): node is SpreadElement; -export function isSuper(node: Object, opts?: Object): node is Super; -export function isTaggedTemplateExpression(node: Object, opts?: Object): node is TaggedTemplateExpression; -export function isTemplateElement(node: Object, opts?: Object): node is TemplateElement; -export function isTemplateLiteral(node: Object, opts?: Object): node is TemplateLiteral; -export function isYieldExpression(node: Object, opts?: Object): node is YieldExpression; -export function isAnyTypeAnnotation(node: Object, opts?: Object): node is AnyTypeAnnotation; -export function isArrayTypeAnnotation(node: Object, opts?: Object): node is ArrayTypeAnnotation; -export function isBooleanTypeAnnotation(node: Object, opts?: Object): node is BooleanTypeAnnotation; -export function isBooleanLiteralTypeAnnotation(node: Object, opts?: Object): node is BooleanLiteralTypeAnnotation; -export function isNullLiteralTypeAnnotation(node: Object, opts?: Object): node is NullLiteralTypeAnnotation; -export function isClassImplements(node: Object, opts?: Object): node is ClassImplements; -export function isClassProperty(node: Object, opts?: Object): node is ClassProperty; -export function isDeclareClass(node: Object, opts?: Object): node is DeclareClass; -export function isDeclareFunction(node: Object, opts?: Object): node is DeclareFunction; -export function isDeclareInterface(node: Object, opts?: Object): node is DeclareInterface; -export function isDeclareModule(node: Object, opts?: Object): node is DeclareModule; -export function isDeclareTypeAlias(node: Object, opts?: Object): node is DeclareTypeAlias; -export function isDeclareVariable(node: Object, opts?: Object): node is DeclareVariable; -export function isExistentialTypeParam(node: Object, opts?: Object): node is ExistentialTypeParam; -export function isFunctionTypeAnnotation(node: Object, opts?: Object): node is FunctionTypeAnnotation; -export function isFunctionTypeParam(node: Object, opts?: Object): node is FunctionTypeParam; -export function isGenericTypeAnnotation(node: Object, opts?: Object): node is GenericTypeAnnotation; -export function isInterfaceExtends(node: Object, opts?: Object): node is InterfaceExtends; -export function isInterfaceDeclaration(node: Object, opts?: Object): node is InterfaceDeclaration; -export function isIntersectionTypeAnnotation(node: Object, opts?: Object): node is IntersectionTypeAnnotation; -export function isMixedTypeAnnotation(node: Object, opts?: Object): node is MixedTypeAnnotation; -export function isNullableTypeAnnotation(node: Object, opts?: Object): node is NullableTypeAnnotation; -export function isNumericLiteralTypeAnnotation(node: Object, opts?: Object): node is NumericLiteralTypeAnnotation; -export function isNumberTypeAnnotation(node: Object, opts?: Object): node is NumberTypeAnnotation; -export function isStringLiteralTypeAnnotation(node: Object, opts?: Object): node is StringLiteralTypeAnnotation; -export function isStringTypeAnnotation(node: Object, opts?: Object): node is StringTypeAnnotation; -export function isThisTypeAnnotation(node: Object, opts?: Object): node is ThisTypeAnnotation; -export function isTupleTypeAnnotation(node: Object, opts?: Object): node is TupleTypeAnnotation; -export function isTypeofTypeAnnotation(node: Object, opts?: Object): node is TypeofTypeAnnotation; -export function isTypeAlias(node: Object, opts?: Object): node is TypeAlias; -export function isTypeAnnotation(node: Object, opts?: Object): node is TypeAnnotation; -export function isTypeCastExpression(node: Object, opts?: Object): node is TypeCastExpression; -export function isTypeParameterDeclaration(node: Object, opts?: Object): node is TypeParameterDeclaration; -export function isTypeParameterInstantiation(node: Object, opts?: Object): node is TypeParameterInstantiation; -export function isObjectTypeAnnotation(node: Object, opts?: Object): node is ObjectTypeAnnotation; -export function isObjectTypeCallProperty(node: Object, opts?: Object): node is ObjectTypeCallProperty; -export function isObjectTypeIndexer(node: Object, opts?: Object): node is ObjectTypeIndexer; -export function isObjectTypeProperty(node: Object, opts?: Object): node is ObjectTypeProperty; -export function isQualifiedTypeIdentifier(node: Object, opts?: Object): node is QualifiedTypeIdentifier; -export function isUnionTypeAnnotation(node: Object, opts?: Object): node is UnionTypeAnnotation; -export function isVoidTypeAnnotation(node: Object, opts?: Object): node is VoidTypeAnnotation; -export function isJSXAttribute(node: Object, opts?: Object): node is JSXAttribute; -export function isJSXClosingElement(node: Object, opts?: Object): node is JSXClosingElement; -export function isJSXElement(node: Object, opts?: Object): node is JSXElement; -export function isJSXEmptyExpression(node: Object, opts?: Object): node is JSXEmptyExpression; -export function isJSXExpressionContainer(node: Object, opts?: Object): node is JSXExpressionContainer; -export function isJSXIdentifier(node: Object, opts?: Object): node is JSXIdentifier; -export function isJSXMemberExpression(node: Object, opts?: Object): node is JSXMemberExpression; -export function isJSXNamespacedName(node: Object, opts?: Object): node is JSXNamespacedName; -export function isJSXOpeningElement(node: Object, opts?: Object): node is JSXOpeningElement; -export function isJSXSpreadAttribute(node: Object, opts?: Object): node is JSXSpreadAttribute; -export function isJSXText(node: Object, opts?: Object): node is JSXText; -export function isNoop(node: Object, opts?: Object): node is Noop; -export function isParenthesizedExpression(node: Object, opts?: Object): node is ParenthesizedExpression; -export function isAwaitExpression(node: Object, opts?: Object): node is AwaitExpression; -export function isBindExpression(node: Object, opts?: Object): node is BindExpression; -export function isDecorator(node: Object, opts?: Object): node is Decorator; -export function isDoExpression(node: Object, opts?: Object): node is DoExpression; -export function isExportDefaultSpecifier(node: Object, opts?: Object): node is ExportDefaultSpecifier; -export function isExportNamespaceSpecifier(node: Object, opts?: Object): node is ExportNamespaceSpecifier; -export function isRestProperty(node: Object, opts?: Object): node is RestProperty; -export function isSpreadProperty(node: Object, opts?: Object): node is SpreadProperty; -export function isExpression(node: Object, opts?: Object): node is Expression; -export function isBinary(node: Object, opts?: Object): node is Binary; -export function isScopable(node: Object, opts?: Object): node is Scopable; -export function isBlockParent(node: Object, opts?: Object): node is BlockParent; -export function isBlock(node: Object, opts?: Object): node is Block; -export function isStatement(node: Object, opts?: Object): node is Statement; -export function isTerminatorless(node: Object, opts?: Object): node is Terminatorless; -export function isCompletionStatement(node: Object, opts?: Object): node is CompletionStatement; -export function isConditional(node: Object, opts?: Object): node is Conditional; -export function isLoop(node: Object, opts?: Object): node is Loop; -export function isWhile(node: Object, opts?: Object): node is While; -export function isExpressionWrapper(node: Object, opts?: Object): node is ExpressionWrapper; -export function isFor(node: Object, opts?: Object): node is For; -export function isForXStatement(node: Object, opts?: Object): node is ForXStatement; -export function isFunction(node: Object, opts?: Object): node is Function; -export function isFunctionParent(node: Object, opts?: Object): node is FunctionParent; -export function isPureish(node: Object, opts?: Object): node is Pureish; -export function isDeclaration(node: Object, opts?: Object): node is Declaration; -export function isLVal(node: Object, opts?: Object): node is LVal; -export function isLiteral(node: Object, opts?: Object): node is Literal; -export function isImmutable(node: Object, opts?: Object): node is Immutable; -export function isUserWhitespacable(node: Object, opts?: Object): node is UserWhitespacable; -export function isMethod(node: Object, opts?: Object): node is Method; -export function isObjectMember(node: Object, opts?: Object): node is ObjectMember; -export function isProperty(node: Object, opts?: Object): node is Property; -export function isUnaryLike(node: Object, opts?: Object): node is UnaryLike; -export function isPattern(node: Object, opts?: Object): node is Pattern; -export function isClass(node: Object, opts?: Object): node is Class; -export function isModuleDeclaration(node: Object, opts?: Object): node is ModuleDeclaration; -export function isExportDeclaration(node: Object, opts?: Object): node is ExportDeclaration; -export function isModuleSpecifier(node: Object, opts?: Object): node is ModuleSpecifier; -export function isFlow(node: Object, opts?: Object): node is Flow; -export function isFlowBaseAnnotation(node: Object, opts?: Object): node is FlowBaseAnnotation; -export function isFlowDeclaration(node: Object, opts?: Object): node is FlowDeclaration; -export function isJSX(node: Object, opts?: Object): node is JSX; -export function isNumberLiteral(node: Object, opts?: Object): node is NumericLiteral; -export function isRegexLiteral(node: Object, opts?: Object): node is RegExpLiteral; +export function isArrayExpression(node: object, opts?: object): node is ArrayExpression; +export function isAssignmentExpression(node: object, opts?: object): node is AssignmentExpression; +export function isBinaryExpression(node: object, opts?: object): node is BinaryExpression; +export function isDirective(node: object, opts?: object): node is Directive; +export function isDirectiveLiteral(node: object, opts?: object): node is DirectiveLiteral; +export function isBlockStatement(node: object, opts?: object): node is BlockStatement; +export function isBreakStatement(node: object, opts?: object): node is BreakStatement; +export function isCallExpression(node: object, opts?: object): node is CallExpression; +export function isCatchClause(node: object, opts?: object): node is CatchClause; +export function isConditionalExpression(node: object, opts?: object): node is ConditionalExpression; +export function isContinueStatement(node: object, opts?: object): node is ContinueStatement; +export function isDebuggerStatement(node: object, opts?: object): node is DebuggerStatement; +export function isDoWhileStatement(node: object, opts?: object): node is DoWhileStatement; +export function isEmptyStatement(node: object, opts?: object): node is EmptyStatement; +export function isExpressionStatement(node: object, opts?: object): node is ExpressionStatement; +export function isFile(node: object, opts?: object): node is File; +export function isForInStatement(node: object, opts?: object): node is ForInStatement; +export function isForStatement(node: object, opts?: object): node is ForStatement; +export function isFunctionDeclaration(node: object, opts?: object): node is FunctionDeclaration; +export function isFunctionExpression(node: object, opts?: object): node is FunctionExpression; +export function isIdentifier(node: object, opts?: object): node is Identifier; +export function isIfStatement(node: object, opts?: object): node is IfStatement; +export function isLabeledStatement(node: object, opts?: object): node is LabeledStatement; +export function isStringLiteral(node: object, opts?: object): node is StringLiteral; +export function isNumericLiteral(node: object, opts?: object): node is NumericLiteral; +export function isNullLiteral(node: object, opts?: object): node is NullLiteral; +export function isBooleanLiteral(node: object, opts?: object): node is BooleanLiteral; +export function isRegExpLiteral(node: object, opts?: object): node is RegExpLiteral; +export function isLogicalExpression(node: object, opts?: object): node is LogicalExpression; +export function isMemberExpression(node: object, opts?: object): node is MemberExpression; +export function isNewExpression(node: object, opts?: object): node is NewExpression; +export function isProgram(node: object, opts?: object): node is Program; +export function isObjectExpression(node: object, opts?: object): node is ObjectExpression; +export function isObjectMethod(node: object, opts?: object): node is ObjectMethod; +export function isObjectProperty(node: object, opts?: object): node is ObjectProperty; +export function isRestElement(node: object, opts?: object): node is RestElement; +export function isReturnStatement(node: object, opts?: object): node is ReturnStatement; +export function isSequenceExpression(node: object, opts?: object): node is SequenceExpression; +export function isSwitchCase(node: object, opts?: object): node is SwitchCase; +export function isSwitchStatement(node: object, opts?: object): node is SwitchStatement; +export function isThisExpression(node: object, opts?: object): node is ThisExpression; +export function isThrowStatement(node: object, opts?: object): node is ThrowStatement; +export function isTryStatement(node: object, opts?: object): node is TryStatement; +export function isUnaryExpression(node: object, opts?: object): node is UnaryExpression; +export function isUpdateExpression(node: object, opts?: object): node is UpdateExpression; +export function isVariableDeclaration(node: object, opts?: object): node is VariableDeclaration; +export function isVariableDeclarator(node: object, opts?: object): node is VariableDeclarator; +export function isWhileStatement(node: object, opts?: object): node is WhileStatement; +export function isWithStatement(node: object, opts?: object): node is WithStatement; +export function isAssignmentPattern(node: object, opts?: object): node is AssignmentPattern; +export function isArrayPattern(node: object, opts?: object): node is ArrayPattern; +export function isArrowFunctionExpression(node: object, opts?: object): node is ArrowFunctionExpression; +export function isClassBody(node: object, opts?: object): node is ClassBody; +export function isClassDeclaration(node: object, opts?: object): node is ClassDeclaration; +export function isClassExpression(node: object, opts?: object): node is ClassExpression; +export function isExportAllDeclaration(node: object, opts?: object): node is ExportAllDeclaration; +export function isExportDefaultDeclaration(node: object, opts?: object): node is ExportDefaultDeclaration; +export function isExportNamedDeclaration(node: object, opts?: object): node is ExportNamedDeclaration; +export function isExportSpecifier(node: object, opts?: object): node is ExportSpecifier; +export function isForOfStatement(node: object, opts?: object): node is ForOfStatement; +export function isImportDeclaration(node: object, opts?: object): node is ImportDeclaration; +export function isImportDefaultSpecifier(node: object, opts?: object): node is ImportDefaultSpecifier; +export function isImportNamespaceSpecifier(node: object, opts?: object): node is ImportNamespaceSpecifier; +export function isImportSpecifier(node: object, opts?: object): node is ImportSpecifier; +export function isMetaProperty(node: object, opts?: object): node is MetaProperty; +export function isClassMethod(node: object, opts?: object): node is ClassMethod; +export function isObjectPattern(node: object, opts?: object): node is ObjectPattern; +export function isSpreadElement(node: object, opts?: object): node is SpreadElement; +export function isSuper(node: object, opts?: object): node is Super; +export function isTaggedTemplateExpression(node: object, opts?: object): node is TaggedTemplateExpression; +export function isTemplateElement(node: object, opts?: object): node is TemplateElement; +export function isTemplateLiteral(node: object, opts?: object): node is TemplateLiteral; +export function isYieldExpression(node: object, opts?: object): node is YieldExpression; +export function isAnyTypeAnnotation(node: object, opts?: object): node is AnyTypeAnnotation; +export function isArrayTypeAnnotation(node: object, opts?: object): node is ArrayTypeAnnotation; +export function isBooleanTypeAnnotation(node: object, opts?: object): node is BooleanTypeAnnotation; +export function isBooleanLiteralTypeAnnotation(node: object, opts?: object): node is BooleanLiteralTypeAnnotation; +export function isNullLiteralTypeAnnotation(node: object, opts?: object): node is NullLiteralTypeAnnotation; +export function isClassImplements(node: object, opts?: object): node is ClassImplements; +export function isClassProperty(node: object, opts?: object): node is ClassProperty; +export function isDeclareClass(node: object, opts?: object): node is DeclareClass; +export function isDeclareFunction(node: object, opts?: object): node is DeclareFunction; +export function isDeclareInterface(node: object, opts?: object): node is DeclareInterface; +export function isDeclareModule(node: object, opts?: object): node is DeclareModule; +export function isDeclareTypeAlias(node: object, opts?: object): node is DeclareTypeAlias; +export function isDeclareVariable(node: object, opts?: object): node is DeclareVariable; +export function isExistentialTypeParam(node: object, opts?: object): node is ExistentialTypeParam; +export function isFunctionTypeAnnotation(node: object, opts?: object): node is FunctionTypeAnnotation; +export function isFunctionTypeParam(node: object, opts?: object): node is FunctionTypeParam; +export function isGenericTypeAnnotation(node: object, opts?: object): node is GenericTypeAnnotation; +export function isInterfaceExtends(node: object, opts?: object): node is InterfaceExtends; +export function isInterfaceDeclaration(node: object, opts?: object): node is InterfaceDeclaration; +export function isIntersectionTypeAnnotation(node: object, opts?: object): node is IntersectionTypeAnnotation; +export function isMixedTypeAnnotation(node: object, opts?: object): node is MixedTypeAnnotation; +export function isNullableTypeAnnotation(node: object, opts?: object): node is NullableTypeAnnotation; +export function isNumericLiteralTypeAnnotation(node: object, opts?: object): node is NumericLiteralTypeAnnotation; +export function isNumberTypeAnnotation(node: object, opts?: object): node is NumberTypeAnnotation; +export function isStringLiteralTypeAnnotation(node: object, opts?: object): node is StringLiteralTypeAnnotation; +export function isStringTypeAnnotation(node: object, opts?: object): node is StringTypeAnnotation; +export function isThisTypeAnnotation(node: object, opts?: object): node is ThisTypeAnnotation; +export function isTupleTypeAnnotation(node: object, opts?: object): node is TupleTypeAnnotation; +export function isTypeofTypeAnnotation(node: object, opts?: object): node is TypeofTypeAnnotation; +export function isTypeAlias(node: object, opts?: object): node is TypeAlias; +export function isTypeAnnotation(node: object, opts?: object): node is TypeAnnotation; +export function isTypeCastExpression(node: object, opts?: object): node is TypeCastExpression; +export function isTypeParameterDeclaration(node: object, opts?: object): node is TypeParameterDeclaration; +export function isTypeParameterInstantiation(node: object, opts?: object): node is TypeParameterInstantiation; +export function isObjectTypeAnnotation(node: object, opts?: object): node is ObjectTypeAnnotation; +export function isObjectTypeCallProperty(node: object, opts?: object): node is ObjectTypeCallProperty; +export function isObjectTypeIndexer(node: object, opts?: object): node is ObjectTypeIndexer; +export function isObjectTypeProperty(node: object, opts?: object): node is ObjectTypeProperty; +export function isQualifiedTypeIdentifier(node: object, opts?: object): node is QualifiedTypeIdentifier; +export function isUnionTypeAnnotation(node: object, opts?: object): node is UnionTypeAnnotation; +export function isVoidTypeAnnotation(node: object, opts?: object): node is VoidTypeAnnotation; +export function isJSXAttribute(node: object, opts?: object): node is JSXAttribute; +export function isJSXClosingElement(node: object, opts?: object): node is JSXClosingElement; +export function isJSXElement(node: object, opts?: object): node is JSXElement; +export function isJSXEmptyExpression(node: object, opts?: object): node is JSXEmptyExpression; +export function isJSXExpressionContainer(node: object, opts?: object): node is JSXExpressionContainer; +export function isJSXIdentifier(node: object, opts?: object): node is JSXIdentifier; +export function isJSXMemberExpression(node: object, opts?: object): node is JSXMemberExpression; +export function isJSXNamespacedName(node: object, opts?: object): node is JSXNamespacedName; +export function isJSXOpeningElement(node: object, opts?: object): node is JSXOpeningElement; +export function isJSXSpreadAttribute(node: object, opts?: object): node is JSXSpreadAttribute; +export function isJSXText(node: object, opts?: object): node is JSXText; +export function isNoop(node: object, opts?: object): node is Noop; +export function isParenthesizedExpression(node: object, opts?: object): node is ParenthesizedExpression; +export function isAwaitExpression(node: object, opts?: object): node is AwaitExpression; +export function isBindExpression(node: object, opts?: object): node is BindExpression; +export function isDecorator(node: object, opts?: object): node is Decorator; +export function isDoExpression(node: object, opts?: object): node is DoExpression; +export function isExportDefaultSpecifier(node: object, opts?: object): node is ExportDefaultSpecifier; +export function isExportNamespaceSpecifier(node: object, opts?: object): node is ExportNamespaceSpecifier; +export function isRestProperty(node: object, opts?: object): node is RestProperty; +export function isSpreadProperty(node: object, opts?: object): node is SpreadProperty; +export function isExpression(node: object, opts?: object): node is Expression; +export function isBinary(node: object, opts?: object): node is Binary; +export function isScopable(node: object, opts?: object): node is Scopable; +export function isBlockParent(node: object, opts?: object): node is BlockParent; +export function isBlock(node: object, opts?: object): node is Block; +export function isStatement(node: object, opts?: object): node is Statement; +export function isTerminatorless(node: object, opts?: object): node is Terminatorless; +export function isCompletionStatement(node: object, opts?: object): node is CompletionStatement; +export function isConditional(node: object, opts?: object): node is Conditional; +export function isLoop(node: object, opts?: object): node is Loop; +export function isWhile(node: object, opts?: object): node is While; +export function isExpressionWrapper(node: object, opts?: object): node is ExpressionWrapper; +export function isFor(node: object, opts?: object): node is For; +export function isForXStatement(node: object, opts?: object): node is ForXStatement; +// tslint:disable-next-line ban-types +export function isFunction(node: object, opts?: object): node is Function; +export function isFunctionParent(node: object, opts?: object): node is FunctionParent; +export function isPureish(node: object, opts?: object): node is Pureish; +export function isDeclaration(node: object, opts?: object): node is Declaration; +export function isLVal(node: object, opts?: object): node is LVal; +export function isLiteral(node: object, opts?: object): node is Literal; +export function isImmutable(node: object, opts?: object): node is Immutable; +export function isUserWhitespacable(node: object, opts?: object): node is UserWhitespacable; +export function isMethod(node: object, opts?: object): node is Method; +export function isObjectMember(node: object, opts?: object): node is ObjectMember; +export function isProperty(node: object, opts?: object): node is Property; +export function isUnaryLike(node: object, opts?: object): node is UnaryLike; +export function isPattern(node: object, opts?: object): node is Pattern; +export function isClass(node: object, opts?: object): node is Class; +export function isModuleDeclaration(node: object, opts?: object): node is ModuleDeclaration; +export function isExportDeclaration(node: object, opts?: object): node is ExportDeclaration; +export function isModuleSpecifier(node: object, opts?: object): node is ModuleSpecifier; +export function isFlow(node: object, opts?: object): node is Flow; +export function isFlowBaseAnnotation(node: object, opts?: object): node is FlowBaseAnnotation; +export function isFlowDeclaration(node: object, opts?: object): node is FlowDeclaration; +export function isJSX(node: object, opts?: object): node is JSX; +export function isNumberLiteral(node: object, opts?: object): node is NumericLiteral; +export function isRegexLiteral(node: object, opts?: object): node is RegExpLiteral; -export function isReferencedIdentifier(node: Object, opts?: Object): boolean; -export function isReferencedMemberExpression(node: Object, opts?: Object): boolean; -export function isBindingIdentifier(node: Object, opts?: Object): boolean; -export function isScope(node: Object, opts?: Object): boolean; -export function isReferenced(node: Object, opts?: Object): boolean; -export function isBlockScoped(node: Object, opts?: Object): boolean; -export function isVar(node: Object, opts?: Object): boolean; -export function isUser(node: Object, opts?: Object): boolean; -export function isGenerated(node: Object, opts?: Object): boolean; -export function isPure(node: Object, opts?: Object): boolean; +export function isReferencedIdentifier(node: object, opts?: object): boolean; +export function isReferencedMemberExpression(node: object, opts?: object): boolean; +export function isBindingIdentifier(node: object, opts?: object): boolean; +export function isScope(node: object, opts?: object): boolean; +export function isReferenced(node: object, opts?: object): boolean; +export function isBlockScoped(node: object, opts?: object): boolean; +export function isVar(node: object, opts?: object): boolean; +export function isUser(node: object, opts?: object): boolean; +export function isGenerated(node: object, opts?: object): boolean; +export function isPure(node: object, opts?: object): boolean; // React specific -interface ReactHelpers { +export interface ReactHelpers { isCompatTag(tagName?: string): boolean; - buildChildren(node: Object): Object[]; + buildChildren(node: object): Node[]; } export const react: ReactHelpers; -export function assertArrayExpression(node: Object, opts?: Object): void; -export function assertAssignmentExpression(node: Object, opts?: Object): void; -export function assertBinaryExpression(node: Object, opts?: Object): void; -export function assertDirective(node: Object, opts?: Object): void; -export function assertDirectiveLiteral(node: Object, opts?: Object): void; -export function assertBlockStatement(node: Object, opts?: Object): void; -export function assertBreakStatement(node: Object, opts?: Object): void; -export function assertCallExpression(node: Object, opts?: Object): void; -export function assertCatchClause(node: Object, opts?: Object): void; -export function assertConditionalExpression(node: Object, opts?: Object): void; -export function assertContinueStatement(node: Object, opts?: Object): void; -export function assertDebuggerStatement(node: Object, opts?: Object): void; -export function assertDoWhileStatement(node: Object, opts?: Object): void; -export function assertEmptyStatement(node: Object, opts?: Object): void; -export function assertExpressionStatement(node: Object, opts?: Object): void; -export function assertFile(node: Object, opts?: Object): void; -export function assertForInStatement(node: Object, opts?: Object): void; -export function assertForStatement(node: Object, opts?: Object): void; -export function assertFunctionDeclaration(node: Object, opts?: Object): void; -export function assertFunctionExpression(node: Object, opts?: Object): void; -export function assertIdentifier(node: Object, opts?: Object): void; -export function assertIfStatement(node: Object, opts?: Object): void; -export function assertLabeledStatement(node: Object, opts?: Object): void; -export function assertStringLiteral(node: Object, opts?: Object): void; -export function assertNumericLiteral(node: Object, opts?: Object): void; -export function assertNullLiteral(node: Object, opts?: Object): void; -export function assertBooleanLiteral(node: Object, opts?: Object): void; -export function assertRegExpLiteral(node: Object, opts?: Object): void; -export function assertLogicalExpression(node: Object, opts?: Object): void; -export function assertMemberExpression(node: Object, opts?: Object): void; -export function assertNewExpression(node: Object, opts?: Object): void; -export function assertProgram(node: Object, opts?: Object): void; -export function assertObjectExpression(node: Object, opts?: Object): void; -export function assertObjectMethod(node: Object, opts?: Object): void; -export function assertObjectProperty(node: Object, opts?: Object): void; -export function assertRestElement(node: Object, opts?: Object): void; -export function assertReturnStatement(node: Object, opts?: Object): void; -export function assertSequenceExpression(node: Object, opts?: Object): void; -export function assertSwitchCase(node: Object, opts?: Object): void; -export function assertSwitchStatement(node: Object, opts?: Object): void; -export function assertThisExpression(node: Object, opts?: Object): void; -export function assertThrowStatement(node: Object, opts?: Object): void; -export function assertTryStatement(node: Object, opts?: Object): void; -export function assertUnaryExpression(node: Object, opts?: Object): void; -export function assertUpdateExpression(node: Object, opts?: Object): void; -export function assertVariableDeclaration(node: Object, opts?: Object): void; -export function assertVariableDeclarator(node: Object, opts?: Object): void; -export function assertWhileStatement(node: Object, opts?: Object): void; -export function assertWithStatement(node: Object, opts?: Object): void; -export function assertAssignmentPattern(node: Object, opts?: Object): void; -export function assertArrayPattern(node: Object, opts?: Object): void; -export function assertArrowFunctionExpression(node: Object, opts?: Object): void; -export function assertClassBody(node: Object, opts?: Object): void; -export function assertClassDeclaration(node: Object, opts?: Object): void; -export function assertClassExpression(node: Object, opts?: Object): void; -export function assertExportAllDeclaration(node: Object, opts?: Object): void; -export function assertExportDefaultDeclaration(node: Object, opts?: Object): void; -export function assertExportNamedDeclaration(node: Object, opts?: Object): void; -export function assertExportSpecifier(node: Object, opts?: Object): void; -export function assertForOfStatement(node: Object, opts?: Object): void; -export function assertImportDeclaration(node: Object, opts?: Object): void; -export function assertImportDefaultSpecifier(node: Object, opts?: Object): void; -export function assertImportNamespaceSpecifier(node: Object, opts?: Object): void; -export function assertImportSpecifier(node: Object, opts?: Object): void; -export function assertMetaProperty(node: Object, opts?: Object): void; -export function assertClassMethod(node: Object, opts?: Object): void; -export function assertObjectPattern(node: Object, opts?: Object): void; -export function assertSpreadElement(node: Object, opts?: Object): void; -export function assertSuper(node: Object, opts?: Object): void; -export function assertTaggedTemplateExpression(node: Object, opts?: Object): void; -export function assertTemplateElement(node: Object, opts?: Object): void; -export function assertTemplateLiteral(node: Object, opts?: Object): void; -export function assertYieldExpression(node: Object, opts?: Object): void; -export function assertAnyTypeAnnotation(node: Object, opts?: Object): void; -export function assertArrayTypeAnnotation(node: Object, opts?: Object): void; -export function assertBooleanTypeAnnotation(node: Object, opts?: Object): void; -export function assertBooleanLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertNullLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertClassImplements(node: Object, opts?: Object): void; -export function assertClassProperty(node: Object, opts?: Object): void; -export function assertDeclareClass(node: Object, opts?: Object): void; -export function assertDeclareFunction(node: Object, opts?: Object): void; -export function assertDeclareInterface(node: Object, opts?: Object): void; -export function assertDeclareModule(node: Object, opts?: Object): void; -export function assertDeclareTypeAlias(node: Object, opts?: Object): void; -export function assertDeclareVariable(node: Object, opts?: Object): void; -export function assertExistentialTypeParam(node: Object, opts?: Object): void; -export function assertFunctionTypeAnnotation(node: Object, opts?: Object): void; -export function assertFunctionTypeParam(node: Object, opts?: Object): void; -export function assertGenericTypeAnnotation(node: Object, opts?: Object): void; -export function assertInterfaceExtends(node: Object, opts?: Object): void; -export function assertInterfaceDeclaration(node: Object, opts?: Object): void; -export function assertIntersectionTypeAnnotation(node: Object, opts?: Object): void; -export function assertMixedTypeAnnotation(node: Object, opts?: Object): void; -export function assertNullableTypeAnnotation(node: Object, opts?: Object): void; -export function assertNumericLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertNumberTypeAnnotation(node: Object, opts?: Object): void; -export function assertStringLiteralTypeAnnotation(node: Object, opts?: Object): void; -export function assertStringTypeAnnotation(node: Object, opts?: Object): void; -export function assertThisTypeAnnotation(node: Object, opts?: Object): void; -export function assertTupleTypeAnnotation(node: Object, opts?: Object): void; -export function assertTypeofTypeAnnotation(node: Object, opts?: Object): void; -export function assertTypeAlias(node: Object, opts?: Object): void; -export function assertTypeAnnotation(node: Object, opts?: Object): void; -export function assertTypeCastExpression(node: Object, opts?: Object): void; -export function assertTypeParameterDeclaration(node: Object, opts?: Object): void; -export function assertTypeParameterInstantiation(node: Object, opts?: Object): void; -export function assertObjectTypeAnnotation(node: Object, opts?: Object): void; -export function assertObjectTypeCallProperty(node: Object, opts?: Object): void; -export function assertObjectTypeIndexer(node: Object, opts?: Object): void; -export function assertObjectTypeProperty(node: Object, opts?: Object): void; -export function assertQualifiedTypeIdentifier(node: Object, opts?: Object): void; -export function assertUnionTypeAnnotation(node: Object, opts?: Object): void; -export function assertVoidTypeAnnotation(node: Object, opts?: Object): void; -export function assertJSXAttribute(node: Object, opts?: Object): void; -export function assertJSXClosingElement(node: Object, opts?: Object): void; -export function assertJSXElement(node: Object, opts?: Object): void; -export function assertJSXEmptyExpression(node: Object, opts?: Object): void; -export function assertJSXExpressionContainer(node: Object, opts?: Object): void; -export function assertJSXIdentifier(node: Object, opts?: Object): void; -export function assertJSXMemberExpression(node: Object, opts?: Object): void; -export function assertJSXNamespacedName(node: Object, opts?: Object): void; -export function assertJSXOpeningElement(node: Object, opts?: Object): void; -export function assertJSXSpreadAttribute(node: Object, opts?: Object): void; -export function assertJSXText(node: Object, opts?: Object): void; -export function assertNoop(node: Object, opts?: Object): void; -export function assertParenthesizedExpression(node: Object, opts?: Object): void; -export function assertAwaitExpression(node: Object, opts?: Object): void; -export function assertBindExpression(node: Object, opts?: Object): void; -export function assertDecorator(node: Object, opts?: Object): void; -export function assertDoExpression(node: Object, opts?: Object): void; -export function assertExportDefaultSpecifier(node: Object, opts?: Object): void; -export function assertExportNamespaceSpecifier(node: Object, opts?: Object): void; -export function assertRestProperty(node: Object, opts?: Object): void; -export function assertSpreadProperty(node: Object, opts?: Object): void; -export function assertExpression(node: Object, opts?: Object): void; -export function assertBinary(node: Object, opts?: Object): void; -export function assertScopable(node: Object, opts?: Object): void; -export function assertBlockParent(node: Object, opts?: Object): void; -export function assertBlock(node: Object, opts?: Object): void; -export function assertStatement(node: Object, opts?: Object): void; -export function assertTerminatorless(node: Object, opts?: Object): void; -export function assertCompletionStatement(node: Object, opts?: Object): void; -export function assertConditional(node: Object, opts?: Object): void; -export function assertLoop(node: Object, opts?: Object): void; -export function assertWhile(node: Object, opts?: Object): void; -export function assertExpressionWrapper(node: Object, opts?: Object): void; -export function assertFor(node: Object, opts?: Object): void; -export function assertForXStatement(node: Object, opts?: Object): void; -export function assertFunction(node: Object, opts?: Object): void; -export function assertFunctionParent(node: Object, opts?: Object): void; -export function assertPureish(node: Object, opts?: Object): void; -export function assertDeclaration(node: Object, opts?: Object): void; -export function assertLVal(node: Object, opts?: Object): void; -export function assertLiteral(node: Object, opts?: Object): void; -export function assertImmutable(node: Object, opts?: Object): void; -export function assertUserWhitespacable(node: Object, opts?: Object): void; -export function assertMethod(node: Object, opts?: Object): void; -export function assertObjectMember(node: Object, opts?: Object): void; -export function assertProperty(node: Object, opts?: Object): void; -export function assertUnaryLike(node: Object, opts?: Object): void; -export function assertPattern(node: Object, opts?: Object): void; -export function assertClass(node: Object, opts?: Object): void; -export function assertModuleDeclaration(node: Object, opts?: Object): void; -export function assertExportDeclaration(node: Object, opts?: Object): void; -export function assertModuleSpecifier(node: Object, opts?: Object): void; -export function assertFlow(node: Object, opts?: Object): void; -export function assertFlowBaseAnnotation(node: Object, opts?: Object): void; -export function assertFlowDeclaration(node: Object, opts?: Object): void; -export function assertJSX(node: Object, opts?: Object): void; -export function assertNumberLiteral(node: Object, opts?: Object): void; -export function assertRegexLiteral(node: Object, opts?: Object): void; - +export function assertArrayExpression(node: object, opts?: object): void; +export function assertAssignmentExpression(node: object, opts?: object): void; +export function assertBinaryExpression(node: object, opts?: object): void; +export function assertDirective(node: object, opts?: object): void; +export function assertDirectiveLiteral(node: object, opts?: object): void; +export function assertBlockStatement(node: object, opts?: object): void; +export function assertBreakStatement(node: object, opts?: object): void; +export function assertCallExpression(node: object, opts?: object): void; +export function assertCatchClause(node: object, opts?: object): void; +export function assertConditionalExpression(node: object, opts?: object): void; +export function assertContinueStatement(node: object, opts?: object): void; +export function assertDebuggerStatement(node: object, opts?: object): void; +export function assertDoWhileStatement(node: object, opts?: object): void; +export function assertEmptyStatement(node: object, opts?: object): void; +export function assertExpressionStatement(node: object, opts?: object): void; +export function assertFile(node: object, opts?: object): void; +export function assertForInStatement(node: object, opts?: object): void; +export function assertForStatement(node: object, opts?: object): void; +export function assertFunctionDeclaration(node: object, opts?: object): void; +export function assertFunctionExpression(node: object, opts?: object): void; +export function assertIdentifier(node: object, opts?: object): void; +export function assertIfStatement(node: object, opts?: object): void; +export function assertLabeledStatement(node: object, opts?: object): void; +export function assertStringLiteral(node: object, opts?: object): void; +export function assertNumericLiteral(node: object, opts?: object): void; +export function assertNullLiteral(node: object, opts?: object): void; +export function assertBooleanLiteral(node: object, opts?: object): void; +export function assertRegExpLiteral(node: object, opts?: object): void; +export function assertLogicalExpression(node: object, opts?: object): void; +export function assertMemberExpression(node: object, opts?: object): void; +export function assertNewExpression(node: object, opts?: object): void; +export function assertProgram(node: object, opts?: object): void; +export function assertObjectExpression(node: object, opts?: object): void; +export function assertObjectMethod(node: object, opts?: object): void; +export function assertObjectProperty(node: object, opts?: object): void; +export function assertRestElement(node: object, opts?: object): void; +export function assertReturnStatement(node: object, opts?: object): void; +export function assertSequenceExpression(node: object, opts?: object): void; +export function assertSwitchCase(node: object, opts?: object): void; +export function assertSwitchStatement(node: object, opts?: object): void; +export function assertThisExpression(node: object, opts?: object): void; +export function assertThrowStatement(node: object, opts?: object): void; +export function assertTryStatement(node: object, opts?: object): void; +export function assertUnaryExpression(node: object, opts?: object): void; +export function assertUpdateExpression(node: object, opts?: object): void; +export function assertVariableDeclaration(node: object, opts?: object): void; +export function assertVariableDeclarator(node: object, opts?: object): void; +export function assertWhileStatement(node: object, opts?: object): void; +export function assertWithStatement(node: object, opts?: object): void; +export function assertAssignmentPattern(node: object, opts?: object): void; +export function assertArrayPattern(node: object, opts?: object): void; +export function assertArrowFunctionExpression(node: object, opts?: object): void; +export function assertClassBody(node: object, opts?: object): void; +export function assertClassDeclaration(node: object, opts?: object): void; +export function assertClassExpression(node: object, opts?: object): void; +export function assertExportAllDeclaration(node: object, opts?: object): void; +export function assertExportDefaultDeclaration(node: object, opts?: object): void; +export function assertExportNamedDeclaration(node: object, opts?: object): void; +export function assertExportSpecifier(node: object, opts?: object): void; +export function assertForOfStatement(node: object, opts?: object): void; +export function assertImportDeclaration(node: object, opts?: object): void; +export function assertImportDefaultSpecifier(node: object, opts?: object): void; +export function assertImportNamespaceSpecifier(node: object, opts?: object): void; +export function assertImportSpecifier(node: object, opts?: object): void; +export function assertMetaProperty(node: object, opts?: object): void; +export function assertClassMethod(node: object, opts?: object): void; +export function assertObjectPattern(node: object, opts?: object): void; +export function assertSpreadElement(node: object, opts?: object): void; +export function assertSuper(node: object, opts?: object): void; +export function assertTaggedTemplateExpression(node: object, opts?: object): void; +export function assertTemplateElement(node: object, opts?: object): void; +export function assertTemplateLiteral(node: object, opts?: object): void; +export function assertYieldExpression(node: object, opts?: object): void; +export function assertAnyTypeAnnotation(node: object, opts?: object): void; +export function assertArrayTypeAnnotation(node: object, opts?: object): void; +export function assertBooleanTypeAnnotation(node: object, opts?: object): void; +export function assertBooleanLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertNullLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertClassImplements(node: object, opts?: object): void; +export function assertClassProperty(node: object, opts?: object): void; +export function assertDeclareClass(node: object, opts?: object): void; +export function assertDeclareFunction(node: object, opts?: object): void; +export function assertDeclareInterface(node: object, opts?: object): void; +export function assertDeclareModule(node: object, opts?: object): void; +export function assertDeclareTypeAlias(node: object, opts?: object): void; +export function assertDeclareVariable(node: object, opts?: object): void; +export function assertExistentialTypeParam(node: object, opts?: object): void; +export function assertFunctionTypeAnnotation(node: object, opts?: object): void; +export function assertFunctionTypeParam(node: object, opts?: object): void; +export function assertGenericTypeAnnotation(node: object, opts?: object): void; +export function assertInterfaceExtends(node: object, opts?: object): void; +export function assertInterfaceDeclaration(node: object, opts?: object): void; +export function assertIntersectionTypeAnnotation(node: object, opts?: object): void; +export function assertMixedTypeAnnotation(node: object, opts?: object): void; +export function assertNullableTypeAnnotation(node: object, opts?: object): void; +export function assertNumericLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertNumberTypeAnnotation(node: object, opts?: object): void; +export function assertStringLiteralTypeAnnotation(node: object, opts?: object): void; +export function assertStringTypeAnnotation(node: object, opts?: object): void; +export function assertThisTypeAnnotation(node: object, opts?: object): void; +export function assertTupleTypeAnnotation(node: object, opts?: object): void; +export function assertTypeofTypeAnnotation(node: object, opts?: object): void; +export function assertTypeAlias(node: object, opts?: object): void; +export function assertTypeAnnotation(node: object, opts?: object): void; +export function assertTypeCastExpression(node: object, opts?: object): void; +export function assertTypeParameterDeclaration(node: object, opts?: object): void; +export function assertTypeParameterInstantiation(node: object, opts?: object): void; +export function assertObjectTypeAnnotation(node: object, opts?: object): void; +export function assertObjectTypeCallProperty(node: object, opts?: object): void; +export function assertObjectTypeIndexer(node: object, opts?: object): void; +export function assertObjectTypeProperty(node: object, opts?: object): void; +export function assertQualifiedTypeIdentifier(node: object, opts?: object): void; +export function assertUnionTypeAnnotation(node: object, opts?: object): void; +export function assertVoidTypeAnnotation(node: object, opts?: object): void; +export function assertJSXAttribute(node: object, opts?: object): void; +export function assertJSXClosingElement(node: object, opts?: object): void; +export function assertJSXElement(node: object, opts?: object): void; +export function assertJSXEmptyExpression(node: object, opts?: object): void; +export function assertJSXExpressionContainer(node: object, opts?: object): void; +export function assertJSXIdentifier(node: object, opts?: object): void; +export function assertJSXMemberExpression(node: object, opts?: object): void; +export function assertJSXNamespacedName(node: object, opts?: object): void; +export function assertJSXOpeningElement(node: object, opts?: object): void; +export function assertJSXSpreadAttribute(node: object, opts?: object): void; +export function assertJSXText(node: object, opts?: object): void; +export function assertNoop(node: object, opts?: object): void; +export function assertParenthesizedExpression(node: object, opts?: object): void; +export function assertAwaitExpression(node: object, opts?: object): void; +export function assertBindExpression(node: object, opts?: object): void; +export function assertDecorator(node: object, opts?: object): void; +export function assertDoExpression(node: object, opts?: object): void; +export function assertExportDefaultSpecifier(node: object, opts?: object): void; +export function assertExportNamespaceSpecifier(node: object, opts?: object): void; +export function assertRestProperty(node: object, opts?: object): void; +export function assertSpreadProperty(node: object, opts?: object): void; +export function assertExpression(node: object, opts?: object): void; +export function assertBinary(node: object, opts?: object): void; +export function assertScopable(node: object, opts?: object): void; +export function assertBlockParent(node: object, opts?: object): void; +export function assertBlock(node: object, opts?: object): void; +export function assertStatement(node: object, opts?: object): void; +export function assertTerminatorless(node: object, opts?: object): void; +export function assertCompletionStatement(node: object, opts?: object): void; +export function assertConditional(node: object, opts?: object): void; +export function assertLoop(node: object, opts?: object): void; +export function assertWhile(node: object, opts?: object): void; +export function assertExpressionWrapper(node: object, opts?: object): void; +export function assertFor(node: object, opts?: object): void; +export function assertForXStatement(node: object, opts?: object): void; +export function assertFunction(node: object, opts?: object): void; +export function assertFunctionParent(node: object, opts?: object): void; +export function assertPureish(node: object, opts?: object): void; +export function assertDeclaration(node: object, opts?: object): void; +export function assertLVal(node: object, opts?: object): void; +export function assertLiteral(node: object, opts?: object): void; +export function assertImmutable(node: object, opts?: object): void; +export function assertUserWhitespacable(node: object, opts?: object): void; +export function assertMethod(node: object, opts?: object): void; +export function assertObjectMember(node: object, opts?: object): void; +export function assertProperty(node: object, opts?: object): void; +export function assertUnaryLike(node: object, opts?: object): void; +export function assertPattern(node: object, opts?: object): void; +export function assertClass(node: object, opts?: object): void; +export function assertModuleDeclaration(node: object, opts?: object): void; +export function assertExportDeclaration(node: object, opts?: object): void; +export function assertModuleSpecifier(node: object, opts?: object): void; +export function assertFlow(node: object, opts?: object): void; +export function assertFlowBaseAnnotation(node: object, opts?: object): void; +export function assertFlowDeclaration(node: object, opts?: object): void; +export function assertJSX(node: object, opts?: object): void; +export function assertNumberLiteral(node: object, opts?: object): void; +export function assertRegexLiteral(node: object, opts?: object): void; diff --git a/types/babel-types/tslint.json b/types/babel-types/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-types/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e51079cdb2206f9efbc1a3e2879d2ca1938e480d Mon Sep 17 00:00:00 2001 From: Stephen Ierodiaconou Date: Wed, 19 Jul 2017 10:30:28 +0100 Subject: [PATCH 0138/1139] Lint fixed --- types/next-redux-wrapper/index.d.ts | 8 ++++---- types/next-redux-wrapper/next-redux-wrapper-tests.tsx | 10 ++++++---- types/next-redux-wrapper/tsconfig.json | 2 +- types/next-redux-wrapper/tslint.json | 10 +--------- 4 files changed, 12 insertions(+), 18 deletions(-) diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts index f65f3f9d73..e6c7ea600e 100644 --- a/types/next-redux-wrapper/index.d.ts +++ b/types/next-redux-wrapper/index.d.ts @@ -45,7 +45,7 @@ declare function nextReduxWrapper) => NextReduxWrappedComponent; declare namespace nextReduxWrapper { - export interface Options { + interface Options { createStore: NextStoreCreator; debug?: boolean; storeKey?: string; @@ -54,11 +54,11 @@ declare namespace nextReduxWrapper { mergeProps?: MergeProps; connectOptions?: ConnectOptions; } - export interface StoreCreatorOptions extends Options { + interface StoreCreatorOptions extends Options { isServer: boolean; req?: IncomingMessage; } - export function setPromise(Promise: any): void; - export function setDebug(debug: boolean): void; + function setPromise(Promise: any): void; + function setDebug(debug: boolean): void; } diff --git a/types/next-redux-wrapper/next-redux-wrapper-tests.tsx b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx index c432ae5ec9..664d793826 100644 --- a/types/next-redux-wrapper/next-redux-wrapper-tests.tsx +++ b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx @@ -1,13 +1,13 @@ import * as React from 'react'; import withRedux = require('next-redux-wrapper'); -import { createStore, Store, AnyAction } from 'redux'; +import { createStore, Reducer, Store, AnyAction } from 'redux'; import { StoreCreatorOptions } from 'next-redux-wrapper'; interface InitialState { foo: string; } -const reducer = (state: InitialState = {foo: ''}, action: AnyAction) => { +const reducer: Reducer = (state: InitialState = {foo: ''}, action: AnyAction): InitialState => { switch (action.type) { case 'FOO': return {...state, foo: action.payload}; @@ -64,7 +64,8 @@ const com4 = withRedux( const com5 = withRedux( makeStore, (state: ReduxStore) => ({foo: state.foo, custom: 'hi'}), - null, (state: Props) => ({foo: state.foo, custom: 'hi'}) + undefined, + (state: Props) => ({foo: state.foo, custom: 'hi'}) )(Page); const com6 = withRedux( @@ -75,7 +76,8 @@ const com6 = withRedux ({foo: state.foo, custom: 'hi'}), - null, (state: Props) => ({foo: state.foo, custom: 'hi'}) + undefined, + (state: Props) => ({foo: state.foo, custom: 'hi'}) )(Page); const com7 = withRedux({ diff --git a/types/next-redux-wrapper/tsconfig.json b/types/next-redux-wrapper/tsconfig.json index f35fb6fa08..75ef2fd85b 100644 --- a/types/next-redux-wrapper/tsconfig.json +++ b/types/next-redux-wrapper/tsconfig.json @@ -8,7 +8,7 @@ "jsx": "react", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/next-redux-wrapper/tslint.json b/types/next-redux-wrapper/tslint.json index 98f9451050..3db14f85ea 100644 --- a/types/next-redux-wrapper/tslint.json +++ b/types/next-redux-wrapper/tslint.json @@ -1,9 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - // All of the different "export default" lines in the index.d.ts - // appear to be triggering this. Remove this when I know of a way - // to declare a default export across multiple package/subpackages. - "strict-export-declare-modifiers": false - } -} +{ "extends": "dtslint/dt.json" } From d7e97abc4fe2925e075d0638dbf69f2b9bd71d69 Mon Sep 17 00:00:00 2001 From: Stephen Ierodiaconou Date: Wed, 19 Jul 2017 10:34:00 +0100 Subject: [PATCH 0139/1139] Fix spacing --- types/next-redux-wrapper/index.d.ts | 4 ++-- types/next-redux-wrapper/next-redux-wrapper-tests.tsx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts index e6c7ea600e..d86e446c2a 100644 --- a/types/next-redux-wrapper/index.d.ts +++ b/types/next-redux-wrapper/index.d.ts @@ -29,8 +29,8 @@ interface NextPageComponentMethods { type NextReduxWrappedComponent = React.Component & NextPageComponentMethods; type NextStoreCreator = ( - initialState: TInitialState, - options: nextReduxWrapper.StoreCreatorOptions + initialState: TInitialState, + options: nextReduxWrapper.StoreCreatorOptions ) => Store; declare function nextReduxWrapper( diff --git a/types/next-redux-wrapper/next-redux-wrapper-tests.tsx b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx index 664d793826..de911679d2 100644 --- a/types/next-redux-wrapper/next-redux-wrapper-tests.tsx +++ b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx @@ -81,8 +81,8 @@ const com6 = withRedux ({foo: state.foo}) + createStore: makeStore, + mapStateToProps: (state: ReduxStore) => ({foo: state.foo}) })(Page); withRedux.setPromise(Promise); From 4720cbbb8bc92434795935150e50b0b7a6488d52 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Wed, 19 Jul 2017 11:38:18 +0200 Subject: [PATCH 0140/1139] Fix babylon linting errors --- types/babylon/babylon-tests.ts | 1 - types/babylon/index.d.ts | 6 +++--- types/babylon/tslint.json | 1 + 3 files changed, 4 insertions(+), 4 deletions(-) create mode 100644 types/babylon/tslint.json diff --git a/types/babylon/babylon-tests.ts b/types/babylon/babylon-tests.ts index 769d635e89..d844b9a8f7 100644 --- a/types/babylon/babylon-tests.ts +++ b/types/babylon/babylon-tests.ts @@ -12,7 +12,6 @@ assert(node.start === 0); assert(node.end === 38); assert(node.loc.start > node.loc.end); - babylon.parse(code, { sourceType: "module", // default: "script" plugins: ["jsx"] // default: [] diff --git a/types/babylon/index.d.ts b/types/babylon/index.d.ts index eb35a5d799..eb22f30c13 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for babylon v6.16.1 +// Type definitions for babylon 6.16 // Project: https://github.com/babel/babylon // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// +// TypeScript Version: 2.3 import { File, Expression } from 'babel-types'; diff --git a/types/babylon/tslint.json b/types/babylon/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babylon/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c6e88dfb7c3663e0a1ea02600eb510d8d99c48f0 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Wed, 19 Jul 2017 11:58:52 +0200 Subject: [PATCH 0141/1139] Upgrade TS version to 2.3 for babel packages --- types/babel-core/index.d.ts | 2 ++ types/babel-template/index.d.ts | 2 ++ types/babel-traverse/index.d.ts | 2 ++ types/babelify/index.d.ts | 2 ++ 4 files changed, 8 insertions(+) diff --git a/types/babel-core/index.d.ts b/types/babel-core/index.d.ts index a3cd7019ab..029d5b5433 100644 --- a/types/babel-core/index.d.ts +++ b/types/babel-core/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for babel-core v6.7 // Project: https://github.com/babel/babel/tree/master/packages/babel-core // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/babel-template/index.d.ts b/types/babel-template/index.d.ts index 7d73adc466..fd0852127a 100644 --- a/types/babel-template/index.d.ts +++ b/types/babel-template/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for babel-template v6.7 // Project: https://github.com/babel/babel/tree/master/packages/babel-template // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// /// diff --git a/types/babel-traverse/index.d.ts b/types/babel-traverse/index.d.ts index 8d34144d0a..cb2dd53a84 100644 --- a/types/babel-traverse/index.d.ts +++ b/types/babel-traverse/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for babel-traverse v6.7 // Project: https://github.com/babel/babel/tree/master/packages/babel-traverse // Definitions by: Troy Gerwien +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// diff --git a/types/babelify/index.d.ts b/types/babelify/index.d.ts index c69eef42b2..f394d2ba44 100644 --- a/types/babelify/index.d.ts +++ b/types/babelify/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for babelify v7.3.0 // Project: https://github.com/babel/babelify // Definitions by: TeamworkGuy2 +// Marvin Hagemeister // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// From 8bf14fc21f3bafd0aa9fade2b06a50f9f028747d Mon Sep 17 00:00:00 2001 From: Saeed Tabrizi Date: Wed, 19 Jul 2017 18:36:11 +0430 Subject: [PATCH 0142/1139] orientjs d.ts update to support version 3.0.0 --- types/orientjs/index.d.ts | 1142 ++++++++++++++++++++++++++++------ types/orientjs/tsconfig.json | 2 +- types/orientjs/tslint.json | 1 + 3 files changed, 951 insertions(+), 194 deletions(-) create mode 100644 types/orientjs/tslint.json diff --git a/types/orientjs/index.d.ts b/types/orientjs/index.d.ts index 679fc7c70a..4fc16bffe3 100644 --- a/types/orientjs/index.d.ts +++ b/types/orientjs/index.d.ts @@ -1,83 +1,46 @@ -// Type definitions for orientjs v2.1.0 +// Type definitions for orientjs v3.0.0 // Project: https://github.com/orientechnologies/orientjs -// Definitions by: Saeed Tabrizi -// Definitions: https://github.com/borisyankov/DefinitelyTyped -// TypeScript Version: 2.3 - +// Definitions by: [Saeed Tabrizi] +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Last Update : 19-7-2017 +// Compatible with Orientdb >= 2.2.15 and orientjs >= 2.2.x features . // Developed with love in www.nowcando.com +// /// /* =================== USAGE =================== - import orientjs = require('orientjs'); - var dbserver = orientjs({ + let dbserver = orientjs({ host: 'localhost', port: 2424, username: 'root', password: 'root' }); - var db = dbserver.use({ + let db = dbserver.use({ name: 'mytestdb', username: 'root', password: 'root' }); - =============================================== */ +/** A lightweight definiton for orientjs module, Official node.js driver for OrientDB. + * + * @description Official node.js driver for OrientDB. Fast, lightweight, uses the binary protocol. + * + * @author Saeed Tabrizi (saeed a_t nowcando.com) + * @version 3.0.0 + * +*/ declare module "orientjs" { import events = require('events'); - import Promise = require('bluebird'); - function ojs(config: any): ojs.OrientJs; + import Promise = require('bluebird'); + function ojs(config: ojs.ServerConfig): ojs.OrientJs; module ojs { - module errors { - interface BaseError { - name: string; - init(name: string): void; - } - interface OperationError extends BaseError { - message: string; - date: any; - } - interface RequestError extends OperationError { } - } - - module Migration { - interface Migration { - name: string; - server: Server; - db: Db; - configure(config?: any): void; - up(): Promise; - down(): Promise; - - - } - - class Manager { - - constructor(config?: any); - name: string; - server: Server; - db: Db; - dir: string; - className: string; - create(param: string): Promise; - generateMigration(config: any): string; - list(): Promise; - listAvailable(): Promise; - ensureStructure: Promise; - listApplied(): Promise; - up(limit?: number): Promise; - down(limit?: number): Promise; - loadMigration(name: string): Migration; - applyMigration(name: string): Promise; - revertMigration(name: string): Promise; - } - } - + type Version = number | string; + type PropertyType = "Boolean" | "Integer" | "Short" | "Long" | "Float" | "Double" | "DateTime" | "String" | "Binary" | "Embedded" | "EmbeddedList" | "EmbeddedSet" | "EmbeddedMap" | "Link" | "LinkList" | "LinkSet" | "LinkMap" | "Byte" | "Transient" | "Date" | "Custom" | "Decimal" | "LinkBag"; enum DataTypes { Boolean = 0, Integer = 1, @@ -101,8 +64,129 @@ declare module "orientjs" { Date = 19, Custom = 20, Decimal = 21, - LinkBag = 22, + LinkBag = 22 + } + module errors { + interface BaseError { + name: string; + init(name: string): void; + } + interface OperationError extends BaseError { + message: string; + date: any; + } + interface RequestError extends OperationError { } + } + + module Migration { + type MigrationManagerConfig = { + name?: string, + db?: Db, + dir?: string, + className?: string + }; + + class Manager extends MigrationManager{ + constructor (config: MigrationManagerConfig); + } + interface Migration { + name: string; + server: Server; + db: Db; + configure(config?: any): void; + up(): Promise; + down(): Promise; + + } + + class MigrationManager { + /** + * # Migration Manager + * + * @param {Object} config The configuration for the migration manager. + */ + constructor(config?: MigrationManagerConfig); + + name: string; + server: Server; + db: Db; + dir: string; + className: string; + + /** + * Create a new migration. + * + * @param {String|Object} config The name or configuration for the new migration. + * @promise {String} The full path to the created migration. + */ + create(param: string): Promise; + /** + * Generate the content for a migration. + * @param {Object} config The configuration object. + * @return {String} The generated JavaScript source code. + */ + generateMigration(config: any): string; + /** + * List the migrations that have not yet been applied. + * + * @promise {String[]} An array of migration names + */ + list(): Promise; + /** + * List all the available migrations. + * + * @promise {String[]} The names of the available migrations. + */ + listAvailable(): Promise; + /** + * Ensure the migration class exists. + * + * @promise {MigrationManager} The manager instance with intact structure. + */ + ensureStructure: Promise; + /** + * Retrieve a list of applied migrations. + * + * @promise {Object[]} The applied migrations. + */ + listApplied(): Promise; + /** + * Perform the migration. + * + * @param {Integer} limit The maximum number of migrations to apply, if any. + * @promise {Mixed} The result of the migration. + */ + up(limit?: number): Promise; + /** + * Revert the migration. + * + * @param {Integer} limit The maximum number of migrations to revert, if any. + * @promise {Mixed} The result of the migration. + */ + down(limit?: number): Promise; + /** + * Load the migration with the given name. + * + * @param {String} name The name of the migation. + * @return {Migration} The loaded migration instance. + */ + loadMigration(name: string): Migration; + /** + * Apply the migration with the given name. + * + * @param {String} name The name of the migation. + * @promise {Mixed} The result of the migration. + */ + applyMigration(name: string): Promise; + /** + * Revert the migration with the given name. + * + * @param {String} name The name of the migation. + * @promise {Mixed} The result of the migration. + */ + revertMigration(name: string): Promise; + } } interface Logger { @@ -117,75 +201,245 @@ declare module "orientjs" { valueOf(): string; isValid?(): boolean; - equals?(rid: string): boolean; - equals?(rid: RID): boolean; - parse?(input: string): boolean; - parse?(input: string): RID; - parse?(input: string): RID[]; - isValid?(input: string): boolean; - isValid?(input: RID): boolean; - isValid?(input: any): boolean; - toRid?(cluster: number, position: number):any; + equals?(rid: string) + : boolean; + equals?(rid: RID) + : boolean; + parse?(input: string) + : boolean; + parse?(input: string) + : RID; + parse?(input: string) + : RID[]; + isValid?(input: string) + : boolean; + isValid?(input: RID) + : boolean; + isValid?(input: any) + : boolean; + toRid?(cluster: number, position: number) + : any; + } + + interface CustomField { + /** + * Get the value of the given custom field. + * + * @param {String} key The name of the field to get. + * @return {Mixed} The field value, or undefined if it doesn't exist. + */ + get(key: string): CustomField; + /** + * Set a custom field. + * + * @param {String|Object} key The key to set, or map of keys to values. + * @param {String} value The value to set, if `key` is not an object. + * @promise {Object|null} The new set of custom fields, or null if none are present. + */ + set(key: string, value: any): CustomField; + /** + * Unset the custom field with the given name, + * + * @param {String} key The name of the custom field to remove. + * @promise {Object|null} The new set of custom fields, or null if none are present. + */ + unset(key: string): CustomField; + } + + interface PropertyCreateConfig { + name: string; + type: PropertyType; + default?: any; + ifnotexist?: boolean; + unsafe?: boolean; + mandatory?: boolean; + readonly?: boolean; + notNull?: boolean; + collate?: string; + linkedClass?: string; + linkedType?: string; + regexp?: RegExp | string; + min?: number; + max?: number; + custom?: { + fields?: CustomField[] + } + } + + interface PropertyUpdateConfig { + name: string; + type: PropertyType; + default?: any; + mandatory?: boolean; + readonly?: boolean; + notNull?: boolean; + collate?: string; + linkedClass?: string; + linkedType?: string; + regexp?: RegExp | string; + min?: number; + max?: number; + custom?: { + fields?: CustomField[] + } } interface Property { - class: Class; - name: string; - originalName: string; - type: any; - mandatory: boolean; - readonly: boolean; - notNull: boolean; - collate: string; - linkedClass: Class; - regexp: RegExp; - min: any; - max: any; + class?: Class; + name?: string; + originalName?: string; + type?: PropertyType; + mandatory?: boolean; + readonly?: boolean; + notNull?: boolean; + collate?: string; + linkedClass?: string; + linkedType?: PropertyType; + regexp?: RegExp | string; + min?: number; + max?: number; + custom?: { + fields?: CustomField[] + } configure(config?: any): void; reload(): Promise; rename(newName: string): Promise; - list(): Promise & Promise; - create(config: string, reload?: boolean): Promise & Promise; - create(config?: any, reload?: boolean): Promise & Promise; - create(...config: any[]): Promise & Promise; - get(name: string): Promise & Promise; - update(config: any, reload?: boolean): Promise & Promise; - drop(name: string): Promise; - alter(name: string, setting?: any): Promise & Promise; - rename(oldName: string, newName: string): Promise; + list(): Promise; + /** + * Create a new property. + * + * @param {String|Object} config The property name or configuration. + * @param {Boolean} reload Whether to reload the property, default to true. + * @promise {Object} The created property. + */ + create(config?: PropertyCreateConfig | string, reload?: boolean): Promise; + create(config: PropertyCreateConfig[], reload?: boolean): Promise; + /** + * Get the property with the given name. + * + * @param {String} name The property to get. + * @promise {Object|null} The retrieved property. + */ + get(name: string): Promise; + /** + * Update the given property. + * + * @param {Object} property The property settings. + * @param {Boolean} reload Whether to reload the property, default to true. + * @promise {Object} The updated property. + */ + update(config: PropertyUpdateConfig, reload?: boolean): Promise; + drop(name: string, config?: { + ifexist?: boolean, + force?: boolean + }): Promise; + alter(name: string, setting?: any): Promise; + rename(oldName: string, newName: string): Promise; } + /** + * The class constructor. + * @param {Object} config The configuration for the class + */ interface Class { - db: Db; - name: string; - shortName: string; - defaultClusterId: any; - superClass: string; - originalName: string; - clusterIds: number[]; - + db?: Db; + name?: string; + shortName?: string; + defaultClusterId?: any; + superClass?: string; + originalName?: string; + clusterIds?: number[]; + /** + * Configure the class instance. + * @param {Object} config The configuration object. + */ configure(config?: any): void; - list(limit: number, offset: number): Promise & Promise & Promise; - list(config: any): Promise & Promise & Promise; - list(refresh: boolean): Promise & Promise & Promise; - find(attributes: any, limit: number, offset: number): Promise; - create(record: Record): Promise & Promise; - create(name: string, parentName?: string, cluster?: string, isAbstract?: boolean): Promise & Promise; - update(cls: any, reload: boolean): Promise & Promise; + /** + * Retreive a list of classes from the database. + * + * @param {Boolean} refresh Whether to refresh the list or not. + * @promise {Object[]} An array of class objects. + */ + list(limit: number, offset: number): Promise; + list(config: any): Promise; + list(refresh: boolean): Promise; + /** + * Find a list of records in the class. + * + * @param {Object} attributes The attributes to search with. + * @param {Integer} limit The maximum number of records to return + * @param {Integer} offset The offset to start returning records from. + * @promise {Object[]} An array of records in the class. + */ + find(attributes: any, limit ?: number, offset?: number): Promise; + /** + * Create a record for this class. + * + * @param {Object} record The record to create. + * @promise {Object} The created record. + */ + create(record: Record): Promise; + /** + * Create a new class. + * + * @param {String} name The name of the class to create. + * @param {String} parentName The name of the parent to extend, if any. + * @param {String|Integer} cluster The cluster name or id. + * @param {Boolean} isAbstract The flag for the abstract class + * @param {Boolean} ifnotexist The flag for the if not exist class + * @promise {Object} The created class object + */ + create(name: string, parentName?: string, cluster?: string, isAbstract?: boolean, ifnotexist?: boolean): Promise; + /** + * Update the given class. + * + * @param {Object} class The class settings. + * @param {Boolean} reload Whether to reload the class, default to true. + * @promise {Object} The updated class. + */ + update(cls: any, reload: boolean): Promise; + /** + * Reload the class instance. + * + * @promise {Class} The class instance. + */ reload(): Promise; - drop(name: string): Promise; - get(name: string, refresh?: boolean): Promise & Promise; - cacheData(classes: Class[] & any[]): Db; + /** + * Delete a class. + * + * @param {String} name The name of the class to delete. + * @param {Object} config The config. + * @promise {Db} The database instance. + */ + drop(name: string, config?: { + ifexist?: boolean, + force?: boolean + }): Promise; + /** + * Get a class by name. + * + * @param {Integer|String} name The name of the class. + * @param {Boolean} refresh Whether to refresh the data, defaults to false. + * @promise {Object} The class object if it exists. + */ + get(name: string, refresh?: boolean): Promise; + /** + * Cache the given class data for fast lookup later. + * + * @param {Object[]} classes The class objects to cache. + * @return {Db} The db instance. + */ + cacheData(classes: Class[]): Db; property: Property; } interface Cluster { - name: string; - location: string; + name?: string; + location?: string; list(refresh?: boolean): Promise; create(name: string, location?: string): Promise & Promise; get(nameOrId: string, refresh?: boolean): Promise & Promise; @@ -199,24 +453,195 @@ declare module "orientjs" { } + /** + * The sequence constructor. + * @param {Object} config The configuration for the sequence + */ + interface Sequence { + + db?: Db; + name?: string; + type?: string; + value?: number; + incr?: number; + start?: number; + cache?: number; + /** + * Configure the sequence instance. + * @param {Object} config The configuration object. + */ + configure(config?: any): void; + /** + * Retreive a list of sequences from the database. + * + * @param {Boolean} refresh Whether to refresh the list or not. + * @promise {Object[]} An array of class objects. + */ + + list(refresh: boolean): Promise; + + /** + * Create a new sequence. + * + * @param {String} name The name of the sequence to create. + * @param {String} type The type of sequence. + * @param {Integer} start The start number. + * @param {Integer} incerement The increment number. + * @param {Integer} cache The cache number + * @promise {Object} The created sequence object + */ + create(name: string, type: "ORDERED" | "CACHED", start?: number, incerement?: number, cache?: number): Promise; + /** + * update a sequence. + * + * @param {String} name The name of the sequence to create. + * @param {Integer} incerement The increment number. + * @param {Integer} cache The cache number + * @param {Integer} start The start number. + * @promise {Object} The created sequence object + */ + update(name: string, start?: number, incerement?: number, cache?: number): Promise; + /** + * Reload the sequence instance. + * + * @promise {Sequence} The class instance. + */ + reload(): Promise; + /** + * Delete a sequence. + * + * @param {String} name The name of the sequence to delete. + * @param {Object} config The config. + * @promise {Db} The database instance. + */ + drop(name: string, config?: { + }): Promise; + /** + * Get a sequence by name. + * + * @param {Integer|String} name The name of the sequence. + * @param {Boolean} refresh Whether to refresh the data, defaults to false. + * @promise {Object} The sequence object if it exists. + */ + get(name: string, refresh?: boolean): Promise; + /** + * Cache the given class data for fast lookup later. + * + * @param {Object[]} sequences The sequence objects to cache. + * @return {Db} The db instance. + */ + cacheData(sequences: Sequence[]): Db; + + } + interface RecordMeta { - "@rid": string|RID; - "@version": string|number; + "@rid": RID; + "@version": Version; } - interface Record { - rid: RID; - create(record: any, options?: any): Promise ; - get(record: Record | RID | string, options?: any): Promise; - resolveReferences(records: Record[] & any[]): any; - meta(record: Record | RID | string, options?: any): Promise ; - update(): Promise & Promise; - update(record: Record | RID | string, options?: any): Promise ; - delete(): Promise & Promise; - delete(record: Record | RID | string, options?: any): Promise ; + type ODocument = Record; + type BinaryRecord = Record & Buffer; + + + interface Record extends Object { + '@rid'?: RID; + '@type'?: 'd' | 'b'; + '@class'?: string, + '@version'?: Version; + rid?: RID; + /** + * Insert the given record into the database. + * + * @param {Object} record The record to insert. + * @param {Object} options The command options. + * @promise {Object} The inserted record. + */ + create(record: ODocument | Record | BinaryRecord, options?: any): Promise; + /** + * Insert the given record into the database. + * + * @param {Object} record The record to insert. + * @param {Object} options The command options. + * @promise {Object} The inserted record. + */ + create(records: ODocument[] | Record[] | BinaryRecord[], options?: any): Promise; + + /** + * Read the given record. + * + * @param {Object} record The record to load. + * @param {Object} options The query options. + * @promise {Object} The loaded record. + */ + get(record: Record | RID, options?: any): Promise; + /** + * Read the given record. + * + * @param {Object} records The record to load. + * @param {Object} options The query options. + * @promise {Object[]} The loaded record. + */ + get(records: Record[] | RID[], options?: any): Promise; + /** + * Resolve all references within the given collection of records. + * + * @param {Object[]} records The records to resolve. + * @return {Object} The records with references replaced. + */ + resolveReferences(records: Record[]): Record[]; + + /** + * Read the metadata for the given record. + * + * @param {Object} record The record to load. + * @param {Object} options The query options. + * @promise {Object} The record object with loaded meta data. + */ + meta(record: Record | RID | string, options?: any): Promise; + /** + * Read the metadata for the given record. + * + * @param {Object} record The record to load. + * @param {Object} options The query options. + * @promise {Object} The record object with loaded meta data. + */ + meta(records: Record[] | RID[], options?: any): Promise; + + update(): Promise; + /** + * Update the given record. + * + * @param {Object} record The record to update. + * @param {Object} options The query options. + * @promise {Object} The updated record. + */ + update(record: Record | RID, options?: any): Promise; + + delete(): Promise & Promise; + /** + * Delete the given record. + * + * @param {String|RID|Object} record The record or record id to delete. + * @param {Object} options The query options. + * @promise {Object} The deleted record object. + */ + delete(record: Record | RID, options?: any): Promise; + } + interface IndexConfig { + name: string, + class?: string, + properties?: string[], + type: "UNIQUE" | "NOTUNIQUE" | "FULLTEXT" | "DICTIONARY" | "UNIQUE_HASH_INDEX" | "NOTUNIQUE_HASH_INDEX" | "FULLTEXT_HASH_INDEX" | "DICTIONARY_HASH_INDEX" | "SPATIAL", + keyType?: string, + metadata?: any, + engine?: "LUCENE" | "COLA" | string } + interface IndexEntry { + key: string, + value: String | RID + } interface Index { cached: boolean; db: Db; @@ -225,35 +650,36 @@ declare module "orientjs" { clusters: Cluster[]; type: string; configure(config: any): void; - add(args: any): Promise; - add(args: any[]): Promise; + add(idx: IndexEntry): Promise; + add(idx: IndexEntry[]): Promise; get(key: string): Promise; set(key: string, value: string): Promise; set(key: string, value: RID): Promise; delete(name: string): Promise; select(): Statement; list(refresh?: boolean): Promise; - create(config: any): Promise; + create(config: IndexConfig): Promise; + create(configs: IndexConfig[]): Promise; drop(name: string): Promise; get(name: string, refresh?: boolean): Promise; cacheData(indices: any[]): Promise; } - + type SqlExpression = string | RawExpression | SqlFunction; interface Statement extends Query { - select(param: string | string[]): Statement; - traverse(param: string | string[]): Statement; - strategy(param: string): Statement; - insert(param: string | string[]): Statement; - update(param: string | string[]): Statement; - delete(param: string | string[]): Statement; - into(param: string): Statement; - create(paramtype: string, paramname: string): Statement; - from(param: string): Statement; - from(param: any): Statement; - to(param: any): Statement; - set(param: any): Statement; - content(param: any): Statement; - increment(property: string, value: any): Statement; + select(param?: string | string[]): Statement; + traverse(param?: string | string[]): Statement; + strategy(param?: string): Statement; + insert(param?: string | string[]): Statement; + update(param?: string | string[]): Statement; + delete(param?: string | string[]): Statement; + into(param?: string): Statement; + create(paramtype?: string, paramname?: string): Statement; + from(param?: string): Statement; + from(param?: any): Statement; + to(param?: any): Statement; + set(param?: any): Statement; + content(param?: any): Statement; + increment(property?: string, value?: any): Statement; add(property: string, value: any): Statement; remove(property: string, value: any): Statement; put(property: string, keysValues: any): Statement; @@ -266,16 +692,22 @@ declare module "orientjs" { group(param: any): Statement; order(param: any): Statement; skip(value: number): Statement; - offset(value: number): Statement; + offset(value?: number): Statement; limit(value: number): Statement; - fetch(param: any): Statement; + fetch(param?: any): Statement; let(name: string, value: string): Statement; let(name: string, value: Statement): Statement; lock(param: any): Statement; + + if(condition: SqlExpression, statements: Statement[]): Statement; + if(condition: SqlExpression, ...statements: Statement[]): Statement; + rollback(param?: any): Statement; + sleep(ms?: number): Statement; + commit(retryLimit?: number): Statement; retry(retryLimit?: number): Statement; wait(waitLimit: number): Statement; - return(value: string): Statement; + return(value: SqlExpression): Statement; lucene(property: string, luceneQuery: string): Statement; lucene(property: any, luceneQuery: string): Statement; near(latitudeProperty: string, longitudeProperty: string, longitude: number, latitude: number, maxDistanceInKms: number): Statement; @@ -290,11 +722,11 @@ declare module "orientjs" { interface Query { - transform(transformer: any): Query; + transform(transformer: (item: Record) => T): Query; column(name: string): Query; defaults(defaults: any): Query; - one(params?: any): Promise ; - all(params?: any): Promise ; + one(params?: any): Promise; + all(params?: any): Promise; scalar(params?: any): Promise; exec(params?: any): Promise; one(params?: any): Promise; @@ -308,31 +740,62 @@ declare module "orientjs" { id: number; commit(): Promise; - create(record: any): Transaction; - update(record: any): Transaction; - delete(record: any): Transaction; + create(record: Record): Transaction; + update(record: Record): Transaction; + delete(record: Record): Transaction; } interface DbConnectionConfig { - useToken: boolean; - name: string; - username: string; - password: string; - sessionId: number; - forcePrepare: boolean; - server: Server; - type: string; - storage: string; - token: any; - transformers: any; + useToken?: boolean; + name?: string; + username?: string; + password?: string; + sessionId?: number; + forcePrepare?: boolean; + server?: Server; + type?: string; + storage?: string; + token?: any; + transformers?: ((item: Record) => any)[]; } - interface DbConfig { - name: string; - type: string; - storage: string; + interface RawExpression { + db: Db; + value: string; + as(alias:string): RawExpression; + } + + + interface AbsSqlFunction { + new (field: number | string): AbsSqlFunction; + } + interface AvgSqlFunction { + new (field: string): AvgSqlFunction; + } + interface SequenceSqlFunction { + new (name: string): SequenceSqlFunction; + next(): number; + current(): number; + reset(): number; + } + + interface SqlFunction { + db: Db; + abs: AbsSqlFunction; + avg: AbsSqlFunction; + sequence: SequenceSqlFunction; + } + + interface QueryOptions { + params?:any; + mode?: "s" | "a" | "l"; + fetchPlan?: any; + limit?: number; + token?:any; + class?:string; + language?: "SQL" | "Javascript" } interface Db extends events.EventEmitter { @@ -340,8 +803,10 @@ declare module "orientjs" { forcePrepare: boolean; name: string; server: Server; - type: string; - storage: string; + type: "graph" | "document"; + storage: "plocal" | "memory"; + username: string; + password: string; token: any; dataSegments: any[]; transactionId: number; @@ -352,51 +817,210 @@ declare module "orientjs" { cluster: Cluster; record: Record; index: Index; - - + sequence: Sequence; + /** + * Configure the database instance. + * @param {Object} config The configuration for the database. + * @return {Db} The configured database object. + */ configure(config: DbConfig): Db; + /** + * Initialize the database instance. + */ init(): void; + /** + * Open the database. + * + * @promise {Db} The open db instance. + */ open(): Promise; + /** + * Close the database. + * + * @promise {Db} The now closed db instance. + */ close(): Promise; + /** + * Send the given operation to the server, ensuring the + * database is open first. + * + * @param {Integer} operation The operation to send. + * @param {Object} data The data for the operation. + * @promise {Mixed} The result of the operation. + */ send(operation: number, data: any): Promise; + /** + * Reload the configuration for the database. + * + * @promise {Db} The database with reloaded configuration. + */ reload(): Promise; + /** + * Begin a new transaction. + * + * @return {Transaction} The transaction instance. + */ begin(): Transaction; - exec(query: string, options?: any): Promise; - query(command: string, options?: any): Promise; - liveQuery(command: string, options?: any): Promise; + /** + * Execute an SQL query against the database and retreive the raw, parsed response. + * + * @param {String} query The query or command to execute. + * @param {Object} options The options for the query / command. + * @promise {Mixed} The results of the query / command. + */ + exec(query: string, options?: QueryOptions): Promise; + + /** + * Execute an SQL query against the database and retreive the results + * + * @param {String} query The query or command to execute. + * @param {Object} options The options for the query / command. + * @promise {Mixed} The results of the query / command. + */ + query(command: string, options?: QueryOptions): Promise; + /** + * Execute a live query against the database + * + * @param {String} query The query or command to execute. + * @param {Object} options The options for the query / command. + * @promise {Mixed} The token of the live query. + */ + liveQuery(command: string, options?: QueryOptions): Promise; + /** + * Normalize a result, where possible. + * @param {Object} result The result to normalize. + * @return {Object} The normalized result. + */ normalizeResult(result: any): any; + /** + * Normalize the content for a result. + * @param {Mixed} content The content to normalize. + * @return {Mixed} The normalized content. + */ normalizeResultContent(content: any): any; - registerTransformer(className: string, transformer: Function): Db; - transformDocument(document: any): any; + /** + * Register a transformer function for documents of the given class. + * This function will be invoked for each document of the specified class + * in all future result sets. + * + * @param {String} className The name of the document class. + * @param {Function} transformer The transformer function. + * @return {Db} The database instance. + */ + registerTransformer(className: string, transformer: (item: Record) => T): Db; + /** + * Transform a document according to its `@class` property, using the registered transformers. + * @param {Object} document The document to transform. + * @return {Mixed} The transformed document. + */ + transformDocument(document: ODocument): any; + + /** + * Create a query instance for this database. + * + * @return {Query} The query instance. + */ createQuery(): Statement; + /** + * Create a raw expression. + * + * @return {RawExpression} The raw expression instance. + */ + rawExpression(param: string): RawExpression; + + /** Create a sql Function. + * + * @return {SqlFunction} The sql function instance. + */ + sqlFunction(options?: any): SqlFunction; + + /** + * Create a create query. + * + * @return {Query} The query instance. + */ create(params?: any): Statement; create(paramtype: string, paramname: string): Statement; + /** + * Create a select query. + * + * @return {Query} The query instance. + */ select(params?: any): Statement; + /** + * Create a traverse query. + * + * @return {Query} The query instance. + */ traverse(params?: any): Statement; + /** + * Create an insert query. + * + * @return {Query} The query instance. + */ insert(params?: any): Statement; + /** + * Create an update query. + * + * @return {Query} The query instance. + */ update(params?: any): Statement; + /** + * Create a delete query. + * + * @return {Query} The query instance. + */ delete(params?: any): Statement; + insert(param: string | string[]): Statement; + update(param: string | string[]): Statement; + delete(param: string | string[]): Statement; + /** + * Create a transactional query. + * + * @return {Query} The query instance. + */ let(params?: any): Statement; - insert(param: string|string[]): Statement; - update(param: string|string[]): Statement; - delete(param: string|string[]): Statement; - let(name: string, value: string|Statement): Statement; + let(name: string, value: string | Statement): Statement; +/** Create a transactional query with if. + * + * @return {Query} The query instance. + */ + if(condition: SqlExpression, statements: Statement[]): Statement; + /** Create a transactional query with if. + * + * @return {Query} The query instance. + */ + if(condition: SqlExpression, ...statements: Statement[]): Statement; + /** + * Escape the given input. + * + * @param {String} input The input to escape. + * @return {String} The escaped input. + */ escape(input: string): string; + /** + * Create a context for a user, using their authentication token. + * The context includes the query builder methods, which will be executed + * on behalf of the user. + * + * @param {Buffer|String} token The authentication token. + * @return {Object} The object containing the query builder methods. + */ createUserContext(token: any): any; + + /** + * Create a orient function from a plain Javascript function + * + * @param {String} name The name of the function + * @param {Object} fn Plain Javascript function to stringify + * @param {Object} options Not currently used but will be used for 'IDEMPOTENT' arg + * @promise {Mixed} The results of the query / command. + */ createFn(name: string, fn: Function, options?: any): Promise; createFn(fn: Function, options?: any): Promise; } - interface ServerConfig { - constructor(config?: any):ServerConfig; - useToken: boolean; - host: string; - port: number; - username: string; - password: string; - } - interface ServerConfiguration { get(name: string): string; @@ -404,30 +1028,162 @@ declare module "orientjs" { list(): any; } + /** + * # Server + * Represents a connection to an orientdb server. + * + * @param {String|Object} options The server URL, or configuration object + */ interface Server { - + new (options?: ServerConfig): Server; config: ServerConfiguration; logger: Logger; + + /** + * Initialize the server instance. + */ init(): void; - configure(): Server; + /** + * Configure the server instance. + * + * @param {Object} config The configuration for the server. + * @return {Server} The configured server object. + */ + configure(config: ServerConfig): Server; + /** + * Configure the transport for the server. + * + * @param {Object} config The server config. + * @return {Server} The configured server object. + */ + configureTransport(config: any): Server; + /** + * Configure the logger for the server. + * + * @param {Object} config The logger config + * @return {Server} The server instance with the configured logger. + */ configureLogger(logger: Logger): Server; + /** + * Send an operation to the server, + * + * @param {Integer} operation The id of the operation to send. + * @param {Object} options The options for the operation. + * @promise {Mixed} The result of the operation. + */ send(operation: number, options: any): any; + /** + * Close the connection to the server. + * + * @return {Server} the disconnected server instance + */ close(): Server; - use(config: string): Db; - use(config?: any): Db; - create(config: string): Promise; + /** + * Use the database with the given name / config. + * + * @param {String|Object} config The database name, or configuration object. + * @return {Db} The database instance. + */ + use(name?: string): Db; + /** + * Use the database with the given name / config. + * + * @param {String|Object} config The database name, or configuration object. + * @return {Db} The database instance. + */ + use(config?: DbConfig): Db; + /** + * Create a database with the given name / config. + * + * @param {String|Object} config The database name or configuration object. + * @promise {Db} The database instance + */ + create(name: string): Promise; + /** +* Create a database with the given name / config. +* +* @param {String|Object} config The database name or configuration object. +* @promise {Db} The database instance +*/ create(config: DbConfig): Promise; - create(config: any): Promise; - drop(config: string): Promise; + /** + * Destroy a database with the given name / config. + * + * @param {String|Object} config The database name or configuration object. + * @promise {Mixed} The server response. + */ + drop(name: string): Promise; + /** + * Destroy a database with the given name / config. + * + * @param {String|Object} config The database name or configuration object. + * @promise {Mixed} The server response. + */ drop(config: DbConfig): Promise; + /** + * List all the databases on the server. + * + * @return {Db[]} An array of databases. + */ list(): Promise; + /** + * Determine whether a database exists with the given name. + * + * @param {String} name The database name. + * @param {String} storageType The storage type, defaults to `plocal`. + * @promise {Boolean} true if the database exists. + */ exists(name: string, storageType?: string): Promise; + /** + * Freeze the database with the given name. + * + * @param {String} name The database name. + * @param {String} storageType The storage type, defaults to `plocal`. + * @return {Object} The response from the server. + */ freeze(name: string, storageType?: string): any; + /** + * Release the database with the given name. + * + * @param {String} name The database name. + * @param {String} storageType The storage type, defaults to `plocal`. + * @return {Object} The response from the server. + */ release(name: string, storageType?: string): any; + + shutdown(): Promise; } - interface OrientJs extends Server { + + interface ODatabase extends Db { + new (config?: { + host: string, + port?: number, + username?: string, + password?: string, + name: string + }): ODatabase; } + + interface ServerConfig { + + useToken?: boolean; + host: string; + port?: number; + username?: string; + password?: string; + servers?: ServerConfig[] + } + + interface DbConfig { + name: string; + type?: string; + storage?: string; + username?: string; + password?: string; + } + + interface OrientJs extends Server { } } export = ojs; -} +} \ No newline at end of file diff --git a/types/orientjs/tsconfig.json b/types/orientjs/tsconfig.json index f0aee4d991..7c730bcc51 100644 --- a/types/orientjs/tsconfig.json +++ b/types/orientjs/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/orientjs/tslint.json b/types/orientjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/orientjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 60dce20e910d593a6c8a221bca63b0b98ca69f0b Mon Sep 17 00:00:00 2001 From: Ifiok Jr Date: Sun, 9 Jul 2017 16:45:37 +0100 Subject: [PATCH 0143/1139] add basic tests for rect-native-fbsdk remove unneeded namespace export fix typo in AppEventsFlushBehavior remove top level namespace Also fix typos. --- types/react-native-fbsdk/index.d.ts | 2049 +++++++++-------- .../react-native-fbsdk-tests.tsx | 127 +- types/react-native-fbsdk/tsconfig.json | 4 +- 3 files changed, 1141 insertions(+), 1039 deletions(-) diff --git a/types/react-native-fbsdk/index.d.ts b/types/react-native-fbsdk/index.d.ts index c27fdb7671..8a07d47e88 100644 --- a/types/react-native-fbsdk/index.d.ts +++ b/types/react-native-fbsdk/index.d.ts @@ -5,1035 +5,1066 @@ // TypeScript Version: 2.3 import { ComponentClass, Component } from 'react'; -import { StyleSheet } from 'react-native'; -import { LoginManager } from 'react-native-fbsdk'; -declare namespace FBSDK { +import { ViewStyle } from 'react-native'; + +/** + * Commonly used Facebook permissions + */ +export type Permissions = 'public_profile' + | 'user_friends' + | 'email' + | 'user_about_me' + | 'user_actions.books' + | 'user_actions.fitness' + | 'user_actions.music' + | 'user_actions.news' + | 'user_actions.video' + | 'user_birthday' + | 'user_education_history' + | 'user_events' + | 'user_games_activity' + | 'user_hometown' + | 'user_likes' + | 'user_location' + | 'user_managed_groups' + | 'user_photos' + | 'user_posts' + | 'user_relationships' + | 'user_relationship_details' + | 'user_religion_politics' + | 'user_tagged_places' + | 'user_videos' + | 'user_website' + | 'user_work_history' + | 'read_custom_friendlists' + | 'read_insights' + | 'read_audience_network_insights' + | 'read_page_mailboxes' + | 'manage_pages' + | 'publish_pages' + | 'publish_actions' + | 'rsvp_event' + | 'pages_show_list' + | 'pages_manage_cta' + | 'pages_manage_instant_articles' + | 'ads_read' + | 'ads_management' + | 'business_management' + | 'pages_messaging' + | 'pages_messaging_subscriptions' + | 'pages_messaging_payments' + | 'pages_messaging_phone_number' + | string; + +/** + * Specifies the privacy of a group. + */ +export type AppGroupPrivacy = + // Anyone can see the group, who's in in and what members post. + 'Open' | + // Anyone can see the group and who's in it, but only members can see posts. + 'Closed'; + +/** + * A model for app groups. + */ +export interface AppGroupCreationContent { /** - * Specifies the privacy of a group. + * The description of the group. */ - type AppGroupPrivacy = - // Anyone can see the group, who's in in and what members post. - 'Open' | - // Anyone can see the group and who's in it, but only members can see posts. - 'Closed'; + description: string; /** - * A model for app invites. + * The name of the group. */ - interface AppGroupCreationContent { - /** - * The description of the group. - */ - description: string; - - /** - * The name of the group. - */ - name: string; - - /** - * The privacy for the group. - */ - privacy: AppGroupPrivacy; - } + name: string; /** - * A model for app invites. + * The privacy for the group. */ - interface AppInviteContent { - /** - * A URL to a preview image that will be displayed with the app invite. - * This is optional. If you don't include it, a fallback image will be used. - */ - previewImageUrl?: string; - - /** - * An app link target that will be used as a target when the user accepts the invite. - */ - applinkUrl: string; - - /** - * Promotional code to be displayed while sending and receiving the invite. - * This is optional. This can be between 0 and 10 characters long and can contain - * alphanumeric characters only. To set a promo code, you need to set promo text. - */ - promotionCode?: string; - - /** - * Promotional text to be displayed while sending and receiving the invite. - * This is optional. This can be between 0 and 80 characters long and can contain - * alphanumeric and spaces only. - */ - promotionText?: string; - } - - type GameRequestActionType = - // The user is sending an object to their friends. - 'send' | - // The user is asking for an object from friends. - 'askfor' | - // It is the turn of the friends to play against the user in a match. - 'turn'; - - type GameRequestFilters = - // Friends using the app can be displayed. - 'app_users' | - // Friends not using the app can be displayed. - 'app_non_users'; - - /** - * A model for a game request. - */ - interface GameRequestContent { - /** - * A plain-text message to be sent as part of the request. Required. - */ - message: string; - - /** - * Used when defining additional context about the nature of the request. - * The parameter 'objectID' is required if the action type is either 'send' or 'ask-for'. - */ - actionType?: GameRequestActionType; - - /** - * Additional freeform data you may pass for tracking. The maximum length is 255 characters. - */ - data?: string; - - /** - * Controls the set of friends someone sees if a multi-friend selector is shown. - */ - filters?: GameRequestFilters; - - /** - * The Open Graph object ID of the object being sent/asked for. This cannot be null for ActionType SEND and - * ASKFOR. - */ - objectId?: string; - - /** - * An array of user IDs, usernames or invite tokens of people to send requests to. - */ - recipients?: string[]; - - /** - * An array of user IDs that will be included in the dialog as the first suggested friends. - * Can't be used together with filters. - */ - suggestions?: string[]; - - /** - * The title for the dialog. - */ - title?: string; - } - - type ObjectIdActionType = 'unknown' | 'open_graph' | 'page'; - - /** - * A base interface for content to be shared. - */ - interface ObjectIdAndType { - /** - * The object ID, this can be a URL or a Facebook ID. - */ - objectId: string; - - /** - * Encapsulates the valid values for the facebook:object_type - * attribute for a LikeView - */ - objectType: ObjectIdActionType; - } - - type ShareContent = ShareLinkContent | SharePhotoContent | ShareVideoContent | ShareOpenGraphContent; - /** - * A base interface for content to be shared. - */ - interface ShareContentCommonParameters { - /** - * List of IDs for taggable people to tag with this content. - */ - peopleIds?: string[]; - - /** - * The ID for a place to tag with this content. - */ - placeId?: string; - - /** - * A value to be added to the referrer URL when a person follows a link from - * this shared content on feed. - */ - ref?: string; - - /** - * A hashtag to be added to the share interface. The hashtag must be 32 characters or less. - */ - hashtag?: string; - } - - /** - * A model for status and link content to be shared. - */ - interface ShareLinkContent { - /** - * The type of content to be shared is link. - */ - contentType: 'link'; - - /** - * Common parameters for share content; - */ - commonParameters?: ShareContentCommonParameters; - - /** - * URL for the content being shared. - */ - contentUrl: string; - - /** - * The Description of the link. - * If not specified, this field is automatically populated by information scraped - * from the contentURL, typically the title of the page. - * @deprecated `contentDescription` is deprecated from Graph API 2.9. - * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. - */ - contentDescription?: string; - - /** - * The title to display for this link. - * @deprecated `contentTitle` is deprecated from Graph API 2.9. - * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. - */ - contentTitle?: string; - - /** - * The URL of a picture to attach to this comment. - * @deprecated `imageUrl` is deprecated from Graph API 2.9. - * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. - */ - imageUrl?: string; - - /** - * The predefined quote to attach to this comment. - * If specified, the quote text will render with custom styling on top of the link. - */ - quote?: string; - } - - interface OpenGraphProperties { - [key: string]: OpenGraphValue; - } + privacy: AppGroupPrivacy; +} - interface OpenGraphValue { - type: OpenGraphValueType; - - value: any; - } - - type OpenGraphValueType = - 'number' | - 'open-graph-object' | - 'photo' | - 'string'; - - interface ShareOpenGraphValueContainer { - /** - * Sets a number for the specified key. - */ - // tslint:disable-next-line:variable-name - putNumber(key: string, number: number): void; - - /** - * Sets an open graph object for the specified key. - */ - putObject(key: string, object: ShareOpenGraphValueContainer): void; - - /** - * Sets a photo for the specified key. - */ - putPhoto(key: string, photo: SharePhoto): void; - - /** - * Sets a string for the specified key. - */ - // tslint:disable-next-line:variable-name - putString(key: string, string: string): void; - - /** - * Gets an entry for the given key. - */ - getEntry(key: string): OpenGraphValue; - } - - /** - * Represents an interface for adding and retrieving values to open graph objects and actions. - */ - class ShareOpenGraphValueContainer { - private _properties: OpenGraphProperties; - - constructor(properties: OpenGraphProperties); - } - - /** - * Represents an open graph action. - */ - class ShareOpenGraphAction extends ShareOpenGraphValueContainer { - /** - * The action type. - */ - actionType: string; - - constructor(actionType: string); - } - - /** - * Represents a content object containing information about an Open Graph Action. - */ - interface ShareOpenGraphContent { - /** - * The type of content to be shared is open graph content. - */ - contentType: 'open-graph'; - - /** - * Common parameters for share content; - */ - commonParameters?: ShareContentCommonParameters; - - /** - * URL for the content being shared. - */ - contentUrl?: string; +/** + * A model for app invites. + */ +export interface AppInviteContent { + /** + * A URL to a preview image that will be displayed with the app invite. + * This is optional. If you don't include it, a fallback image will be used. + */ + previewImageUrl?: string; + + /** + * An app link target that will be used as a target when the user accepts the invite. + */ + applinkUrl: string; + + /** + * Promotional code to be displayed while sending and receiving the invite. + * This is optional. This can be between 0 and 10 characters long and can contain + * alphanumeric characters only. To set a promo code, you need to set promo text. + */ + promotionCode?: string; + + /** + * Promotional text to be displayed while sending and receiving the invite. + * This is optional. This can be between 0 and 80 characters long and can contain + * alphanumeric and spaces only. + */ + promotionText?: string; +} + +export type GameRequestActionType = + // The user is sending an object to their friends. + 'send' | + // The user is asking for an object from friends. + 'askfor' | + // It is the turn of the friends to play against the user in a match. + 'turn'; + +export type GameRequestFilters = + // Friends using the app can be displayed. + 'app_users' | + // Friends not using the app can be displayed. + 'app_non_users'; + +/** + * A model for a game request. + */ +export interface GameRequestContent { + /** + * A plain-text message to be sent as part of the request. Required. + */ + message: string; + + /** + * Used when defining additional context about the nature of the request. + * The parameter 'objectID' is required if the action type is either 'send' or 'ask-for'. + */ + actionType?: GameRequestActionType; + + /** + * Additional freeform data you may pass for tracking. The maximum length is 255 characters. + */ + data?: string; + + /** + * Controls the set of friends someone sees if a multi-friend selector is shown. + */ + filters?: GameRequestFilters; + + /** + * The Open Graph object ID of the object being sent/asked for. This cannot be null for ActionType SEND and + * ASKFOR. + */ + objectId?: string; + + /** + * An array of user IDs, usernames or invite tokens of people to send requests to. + */ + recipients?: string[]; + + /** + * An array of user IDs that will be included in the dialog as the first suggested friends. + * Can't be used together with filters. + */ + suggestions?: string[]; + + /** + * The title for the dialog. + */ + title?: string; +} + +export type ObjectIdActionType = 'unknown' | 'open_graph' | 'page'; + +/** + * A base interface for content to be shared. + */ +export interface ObjectIdAndType { + /** + * The object ID, this can be a URL or a Facebook ID. + */ + objectId: string; + + /** + * Encapsulates the valid values for the facebook:object_type + * attribute for a LikeView + */ + objectType: ObjectIdActionType; +} + +export type ShareContent = ShareLinkContent | SharePhotoContent | ShareVideoContent | ShareOpenGraphContent; +/** + * A base interface for content to be shared. + */ +export interface ShareContentCommonParameters { + /** + * List of IDs for taggable people to tag with this content. + */ + peopleIds?: string[]; + + /** + * The ID for a place to tag with this content. + */ + placeId?: string; + + /** + * A value to be added to the referrer URL when a person follows a link from + * this shared content on feed. + */ + ref?: string; - /** - * Open Graph Action to be shared. - */ - action: ShareOpenGraphAction; + /** + * A hashtag to be added to the share interface. The hashtag must be 32 characters or less. + */ + hashtag?: string; +} - /** - * Property name that points to the primary Open Graph Object in the action. - */ - previewPropertyName: string; - } +/** + * A model for status and link content to be shared. + */ +export interface ShareLinkContent { + /** + * The type of content to be shared is link. + */ + contentType: 'link'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl: string; + + /** + * The Description of the link. + * If not specified, this field is automatically populated by information scraped + * from the contentURL, typically the title of the page. + * @deprecated `contentDescription` is deprecated from Graph API 2.9. + * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. + */ + contentDescription?: string; /** - * Represents an open graph object. + * The title to display for this link. + * @deprecated `contentTitle` is deprecated from Graph API 2.9. + * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. */ - class ShareOpenGraphObject extends ShareOpenGraphValueContainer {} + contentTitle?: string; /** - * A photo for sharing. + * The URL of a picture to attach to this comment. + * @deprecated `imageUrl` is deprecated from Graph API 2.9. + * For more information, see https://developers.facebook.com/docs/apps/changelog#v2_9_deprecations. */ - interface SharePhoto { - /** - * The URL to the photo. - * Note that when sharing SharePhotoContent with Share Button, the imageUrl - * of a SharePhoto cannot be the Uri of an image on the web. - */ - imageUrl: string; - - /** - * Specifies whether the photo was generated by the user or the application. - */ - userGenerated?: boolean; - - /** - * The user generated caption for the photo. Note that the 'caption' must - * come from the user, as pre-filled content is forbidden by the platform - * Policies (2.3). - */ - caption?: string; - } + imageUrl?: string; /** - * A model for photo content to be shared. + * The predefined quote to attach to this comment. + * If specified, the quote text will render with custom styling on top of the link. */ - interface SharePhotoContent { - /** - * The type of content to be shared is photo. - */ - contentType: 'photo'; - - /** - * Common parameters for share content; - */ - commonParameters?: ShareContentCommonParameters; + quote?: string; +} - /** - * URL for the content being shared. - */ - contentUrl?: string; +export interface OpenGraphProperties { + [key: string]: OpenGraphValue; +} + +export interface OpenGraphValue { + type: OpenGraphValueType; + + value: any; +} + +export type OpenGraphValueType = + 'number' | + 'open-graph-object' | + 'photo' | + 'string'; + +export interface ShareOpenGraphValueContainer { + /** + * Sets a number for the specified key. + */ + // tslint:disable-next-line:variable-name + putNumber(key: string, number: number): void; + + /** + * Sets an open graph object for the specified key. + */ + putObject(key: string, object: ShareOpenGraphValueContainer): void; + + /** + * Sets a photo for the specified key. + */ + putPhoto(key: string, photo: SharePhoto): void; - /** - * Photos to be shared. - */ - photos: SharePhoto[]; - } - - /** - * A video for sharing. - */ - interface ShareVideo { - /** - * The URL to the video. Must point to the location of the video on disk. - */ - localUrl: string; - } - - /** - * A model for video content to be shared. - */ - interface ShareVideoContent { - /** - * The type of content to be shared is photo. - */ - contentType: 'video'; - - /** - * Common parameters for share content; - */ - commonParameters?: ShareContentCommonParameters; - - /** - * URL for the content being shared. - */ - contentUrl?: string; - - /** - * Video to be shared. - */ - video: ShareVideo; - - /** - * Description of the video. - */ - contentDescription?: string; - - /** - * Title of the video. - */ - contentTitle?: string; - - /** - * The photo that represents the video. - */ - previewPhoto?: SharePhoto; - } - - interface AccessTokenMap { - accessToken: string; - applicationID: string; - userID: string; - permissions: string[]; - declinedPermissions: string[]; - accessTokenSource?: string; - expirationTime: number; - lastRefreshTime: number; - } - - /** - * Represents an immutable access token for using Facebook services. - */ - class AccessToken { - /** - * The access token string. - */ - accessToken: string; - - /** - * The app ID. - */ - applicationID: string; - - /** - * The user ID. - */ - userID: string; - - /** - * The known granted permissions. - */ - permissions: string[]; - - /** - * The known declined permissions. - */ - declinedPermissions: string[]; - - /** - * The source of access token. - * @platform android - */ - accessTokenSource?: string; - - /** - * The expiration time of the access token. - * The value is the number of milliseconds since Jan. 1, 1970, midnight GMT. - */ - expirationTime: number; - - /** - * The last refresh time of the access token. - * The value is the number of milliseconds since Jan. 1, 1970, midnight GMT. - */ - lastRefreshTime: number; - /** - * Getter for the access token that is current for the application. - */ - static getCurrentAccessToken(): Promise; - - /** - * Setter for the access token that is current for the application. - */ - static setCurrentAccessToken(accessToken: AccessTokenMap): void; - - /** - * Updates the current access token with up to date permissions, - * and extends the expiration date, if extension is possible. - */ - - static refreshCurrentAccessTokenAsync(): Promise; - - constructor(tokenMap: AccessTokenMap); - - /** - * Gets the date at which the access token expires. The value is the number of - * milliseconds since Jan. 1, 1970, midnight GMT. - */ - getExpires(): number; - - /** - * Get the list of permissions associated with this access token. Note that the most up-to-date - * list of permissions is maintained by Facebook, so this list may be outdated if permissions - * have been added or removed since the time the AccessToken object was created. See - * https://developers.facebook.com/docs/reference/login/#permissions for details. - */ - getPermissions(): string[]; - - /** - * Gets the list of permissions declined by the user with this access token. It represents the - * entire set of permissions that have been requested and declined. Note that the most - * up-to-date list of permissions is maintained by Facebook, so this list may be outdated if - * permissions have been granted or declined since the last time an AccessToken object was - * created. See https://developers.facebook.com/docs/reference/login/#permissions for details. - */ - getDeclinedPermissions(): string[]; - - /** - * Gets the date at which the token was last refreshed. Since tokens expire, the Facebook SDK - * will attempt to renew them periodically. The value is the number of milliseconds since - * Jan. 1, 1970, midnight GMT. - */ - getLastRefresh(): number; - - /** - * Gets the ID of the Facebook Application associated with this access token. - */ - getApplicationId(): string; - - /** - * Gets user ID associated with this access token. - */ - getUserId(): string; - } - - /** - * Controls when an AppEventsLogger sends log events to the server - */ - type AppEventsFlushBehavior = - /** - * Flush automatically: periodically (every 15 seconds or after every 100 events), and - * always at app reactivation. This is the default value. - */ - 'auto' | - /** - * Only flush when AppEventsLogger.flush() is explicitly invoked. - */ - 'explicity-only'; - - interface Params { - [key: string]: string | number; - } - - interface AppEventsLogger { - /** - * Sets the current event flushing behavior specifying when events - * are sent back to Facebook servers. - */ - setFlushBehavior(flushBehavior: AppEventsFlushBehavior): void; - - /** - * Logs an event with eventName and optional arguments. - * This function supports the following usage: - * logEvent(eventName: string); - * logEvent(eventName: string, valueToSum: number); - * logEvent(eventName: string, parameters: {[key:string]:string|number}); - * logEvent(eventName: string, valueToSum: number, parameters: {[key:string]:string|number}); - * See https://developers.facebook.com/docs/app-events/android for detail. - */ - logEvent(eventName: string, ...args: Array): void; - - /** - * Logs a purchase. See http://en.wikipedia.org/wiki/ISO_4217 for currencyCode. - */ - logPurchase(purchaseAmount: number, currencyCode: string, parameters?: object): void; - - /** - * Logs an app event that tracks that the application was open via Push Notification. - */ - logPushNotificationOpen(payload?: object): void; - - /** - * Explicitly kicks off flushing of events to Facebook. - */ - flush(): void; - - /** - * For iOS only, sets and sends device token to register the current application for push notifications. - * @platform ios - */ - setPushNotificationsDeviceToken(deviceToken: string): void; - - /** - * For Android only, sets and sends registration id to register the current app for push notifications. - * @platform Android - */ - setPushNotificationsRegistrationId(registrationId: string): void; - } - - const AppEventsLogger: AppEventsLogger; - - interface AppInviteDialog { - /** - * Check if the dialog can be shown. - */ - canShow(): Promise; - - /** - * Shows the dialog using the specified content. - */ - show(appInviteContent: AppInviteContent): Promise; - } - - const AppInviteDialog: AppInviteDialog; - - interface GameRequestDialog { - /** - * Check if the dialog can be shown. - */ - canShow(): Promise; - - /** - * Shows the dialog using the specified content. - */ - show(gameRequestContent: GameRequestContent): Promise; - } - - const GameRequestDialog: GameRequestDialog; - - type GraphRequestCallback = (error?: object, result?: object) => void; - interface GraphRequestConfig { - /** - * The httpMethod to use for the request, for example "GET" or "POST". - */ - httpMethod?: string; - /** - * The Graph API version to use (e.g., "v2.0") - */ - version?: string; - /** - * The request parameters. - */ - parameters?: GraphRequestParameters; - /** - * The access token used by the request. - */ - accessToken?: string; - } - - interface GraphRequestParameters { - [key: string]: object; - } - - /** - * Represents a Graph API request and provides batch request supports. - */ - class GraphRequest { - /** - * The Graph API endpoint to use for the request, for example "me". - */ - graphPath: string; - - /** - * The optional config for the request. - */ - config?: GraphRequestConfig; - - /** - * Called upon completion or failure of the request. - */ - callback?: GraphRequestCallback; - - /** - * Constructs a new Graph API request. - */ - constructor(graphPath: string, config?: GraphRequestConfig | null, callback?: GraphRequestCallback); - - /** - * Adds a string parameter to the request. - */ - addStringParameter(paramString: string, key: string): void; - } - - class GraphRequestManager { - requestBatch: GraphRequest[]; - requestCallbacks: Array; - batchCallback: GraphRequestCallback; - constructor(); - - /** - * Add a graph request. - */ - addRequest(request: GraphRequest): GraphRequestManager; - - /** - * Add call back to the GraphRequestManager. Only one callback can be added. - * Note that invocation of the batch callback does not indicate success of every - * graph request made, only that the entire batch has finished executing. - */ - addBatchCallback(callback: GraphRequestCallback): GraphRequestManager; - - /** - * Executes requests in a batch. - * Note that when there's an issue with network connection the batch callback - * behavior differs in Android and iOS. - * On iOS, the batch callback returns an error if the batch fails with a network error. - * On Android, the batch callback always returns {"result": "batch finished executing"} - * after the batch time out. This is because detecting network status requires - * extra permission and it's unncessary for the sdk. Instead, you can use the NetInfo module - * in react-native to get the network status. - */ - start(timeout?: number): void; - } - - type AuxiliaryViewPosition = 'top' | 'bottom' | 'inline'; - type HorizontalAlignment = 'center' | 'left' | 'right'; - type LikeViewStyle = 'button'| // Note 'button' is only available on Android. - 'standard' | - 'box_count'; - - interface LikeViewProps { - /** - * The objectId and type for the object to like. - */ - objectIdAndType: ObjectIdAndType; - - /** - * The style to use for the receiver. Distinct from React styling. - */ - likeViewStyle?: LikeViewStyle; - - /** - * The position for the auxiliary view for the receiver. - */ - auxiliaryViewPosition?: AuxiliaryViewPosition; - - /** - * The text alignment of the social sentence. - */ - horizontalAlignment?: HorizontalAlignment; - - /** - * The foreground color to use for the content of the receiver. - */ - foregroundColor?: number; - - /** - * If true, a sound is played when the receiver is toggled. - */ - soundEnabled?: boolean; - - /** - * View style, if any. - */ - style?: StyleSheet.Style; - } - - class LikeView extends Component {} - - type TooltipBehaviorIOS = 'auto' | 'force_display' | 'disable'; - - interface LoginButtonProps { - /** - * Represents the read permissions to request when the login button - * is pressed. - */ - readPermissions?: string[]; - - /** - * Represents the publish permissions to request when the login - * button is pressed. - */ - publishPermissions?: string[]; - - /** - * The callback invoked upon error/completion of a login request. - */ - onLoginFinished?(error: object, result: LoginResult): void; - - /** - * The callback invoked upon completion of a logout request. - */ - onLogoutFinished?(): void; - - /** - * The behavior to use when attempting a login. - * @platform android - */ - loginBehaviorAndroid?: LoginBehaviorAndroid; - - /** - * The behavior to use when attempting a login. - * @platform ios - */ - loginBehaviorIOS?: LoginBehaviorIOS; - - /** - * The default audience to target when attempting a login. - */ - defaultAudience?: DefaultAudience; - - /** - * For iOS only, the desired tooltip behavior. - * @platform ios - */ - tooltipBehaviorIOS?: TooltipBehaviorIOS; - - /** - * View style, if any. - */ - style?: StyleSheet.Style; - } - - class LoginButton extends Component { - private _eventHandler(event: object): void; - } - - /** - * Indicates which default audience to use for sessions that post data to Facebook. - */ - type DefaultAudience = - // Indicates that the user's friends are able to see posts made by the application. - 'friends' | - // Indicates that all Facebook users are able to see posts made by the application. - 'everyone' | - // Indicates that only the user is able to see posts made by the application. - 'only_me'; - - type LoginBehavior = LoginBehaviorIOS | LoginBehaviorAndroid; - - /** - * Indicate how Facebook Login should be attempted on Android. - */ - type LoginBehaviorAndroid = - // Attempt login in using the Facebook App, and if that does not work fall back to web dialog auth. - 'native_with_fallback'| - // Only attempt to login using the Facebook App. - 'native_only'| - // Only the web dialog auth should be used. - 'web_only'; - - /** - * Indicate how Facebook Login should be attempted on iOS. - */ - type LoginBehaviorIOS = - // Attempts log in through the native Facebook app. - // The SDK may still use Safari instead. - // See details in https://developers.facebook.com/blog/post/2015/10/29/Facebook-Login-iOS9/ - 'native' | - // Attempts log in through the Safari browser. - 'browser' | - // Attempts log in through the Facebook account currently signed in through Settings. - 'system_account' | - // Attempts log in through a modal UIWebView pop-up. - 'web'; - - /** - * Shows the results of a login operation. - */ - interface LoginResult { - isCancelled: boolean; - grantedPermissions?: string[]; - declinedPermissions?: string[]; - } - - interface LoginManager { - /** - * Logs the user in with the requested read permissions. - */ - logInWithReadPermissions(permissions: string[]): Promise; - - /** - * Logs the user in with the requested publish permissions. - */ - logInWithPublishPermissions(permissions: string[]): Promise; - - /** - * Getter for the login behavior. - */ - getLoginBehavior(): Promise; - - /** - * Setter for the login behavior. - */ - setLoginBehavior(loginBehavior: LoginBehavior): void; - - /** - * Getter for the default audience. - */ - getDefaultAudience(): Promise; - - /** - * Setter for the default audience. - */ - setDefaultAudience(defaultAudience: DefaultAudience): void; - - /** - * Logs out the user. - */ - logOut(): void; - } - - const LoginManager: LoginManager; - - interface MessageDialog { - /** - * Check if the dialog can be shown. - */ - canShow(shareContent: ShareContent): Promise; - - /** - * Shows the dialog using the specified content. - */ - show(shareContent: ShareContent): Promise; - - /** - * Sets whether or not the native message dialog should fail when it encounters a data error. - */ - setShouldFailOnDataError(shouldFailOnDataError: boolean): void; - } - - const MessageDialog: MessageDialog; - - interface SendButtonProps { - /** - * Content to be shared. - */ - shareContent: ShareContent; - - /** - * View style, if any. - */ - style?: StyleSheet.Style; - } - - class SendButton extends Component {} - - interface ShareApi { - /** - * Check if the content can be shared via share api. - */ - canShare(shareContent: ShareContent): Promise; - - /** - * For iOS only, creates a User Owned Open Graph object without an action. - * NOTE: Only one share action can be performed at a time. - * @platform ios - */ - createOpenGraphObject(openGraphObject: ShareOpenGraphObject): Promise; - - /** - * Shares the specified content with a message. - * NOTE: Only one share action can be performed at a time. - */ - share(shareContent: ShareContent, graphNode: string, message: string): Promise; - } - - const ShareApi: ShareApi; - - interface ShareButtonProps { - /** - * Content to be shared. - */ - shareContent: ShareContent; - - /** - * View style, if any. - */ - style?: StyleSheet.Style; - } - - class ShareButton extends Component {} - - type ShareDialogMode = ShareDialogModeIOS | ShareDialogModeAndroid; - type ShareDialogModeAndroid = - /** - * The mode is determined automatically. - */ - 'automatic'| - /** - * The native dialog is used. - */ - 'native'| - /** - * The web dialog is used. - */ - 'web'| - /** - * The feed dialog is used. - */ - 'feed'; - type ShareDialogModeIOS = - /* - * Acts with the most appropriate mode that is available. - */ - 'automatic'| - /* - * Displays the dialog in Safari. - */ - 'browser'| - /* - * Displays the dialog in a UIWebView within the app. - */ - 'webview'; - - interface ShareDialog { - /** - * Check if the dialog can be shown. - */ - canShow(shareContent: ShareContent): Promise; - - /** - * Shows the dialog using the specified content. - */ - show(shareContent: ShareContent): Promise; - - /** - * Sets the mode for the share dialog. - */ - setMode(mode: ShareDialogMode): void; - - /** - * Sets whether or not the native share dialog should fail when it encounters a data error. - */ - setShouldFailOnDataError(shouldFailOnDataError: boolean): void; - } - - const ShareDialog: ShareDialog; + /** + * Sets a string for the specified key. + */ + // tslint:disable-next-line:variable-name + putString(key: string, string: string): void; + + /** + * Gets an entry for the given key. + */ + getEntry(key: string): OpenGraphValue; +} + +/** + * Represents an interface for adding and retrieving values to open graph objects and actions. + */ +export class ShareOpenGraphValueContainer { + private _properties: OpenGraphProperties; + + constructor(properties: OpenGraphProperties); +} + +/** + * Represents an open graph action. + */ +export class ShareOpenGraphAction extends ShareOpenGraphValueContainer { + /** + * The action type. + */ + actionType: string; + + constructor(actionType: string); +} + +/** + * Represents a content object containing information about an Open Graph Action. + */ +export interface ShareOpenGraphContent { + /** + * The type of content to be shared is open graph content. + */ + contentType: 'open-graph'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl?: string; + + /** + * Open Graph Action to be shared. + */ + action: ShareOpenGraphAction; + + /** + * Property name that points to the primary Open Graph Object in the action. + */ + previewPropertyName: string; +} + +/** + * Represents an open graph object. + */ +export class ShareOpenGraphObject extends ShareOpenGraphValueContainer {} + +/** + * A photo for sharing. + */ +export interface SharePhoto { + /** + * The URL to the photo. + * Note that when sharing SharePhotoContent with Share Button, the imageUrl + * of a SharePhoto cannot be the Uri of an image on the web. + */ + imageUrl: string; + + /** + * Specifies whether the photo was generated by the user or the application. + */ + userGenerated?: boolean; + + /** + * The user generated caption for the photo. Note that the 'caption' must + * come from the user, as pre-filled content is forbidden by the platform + * Policies (2.3). + */ + caption?: string; +} + +/** + * A model for photo content to be shared. + */ +export interface SharePhotoContent { + /** + * The type of content to be shared is photo. + */ + contentType: 'photo'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl?: string; + + /** + * Photos to be shared. + */ + photos: SharePhoto[]; +} + +/** + * A video for sharing. + */ +export interface ShareVideo { + /** + * The URL to the video. Must point to the location of the video on disk. + */ + localUrl: string; +} + +/** + * A model for video content to be shared. + */ +export interface ShareVideoContent { + /** + * The type of content to be shared is photo. + */ + contentType: 'video'; + + /** + * Common parameters for share content; + */ + commonParameters?: ShareContentCommonParameters; + + /** + * URL for the content being shared. + */ + contentUrl?: string; + + /** + * Video to be shared. + */ + video: ShareVideo; + + /** + * Description of the video. + */ + contentDescription?: string; + + /** + * Title of the video. + */ + contentTitle?: string; + + /** + * The photo that represents the video. + */ + previewPhoto?: SharePhoto; +} + +export interface AccessTokenMap { + accessToken: string; + applicationID: string; + userID: string; + permissions: Permissions[]; + declinedPermissions: Permissions[]; + accessTokenSource?: string; + expirationTime: number; + lastRefreshTime: number; +} + +/** + * Represents an immutable access token for using Facebook services. + */ +export class AccessToken { + /** + * The access token string. + */ + accessToken: string; + + /** + * The app ID. + */ + applicationID: string; + + /** + * The user ID. + */ + userID: string; + + /** + * The known granted permissions. + */ + permissions: Permissions[]; + + /** + * The known declined permissions. + */ + declinedPermissions: Permissions[]; + + /** + * The source of access token. + * @platform android + */ + accessTokenSource?: string; + + /** + * The expiration time of the access token. + * The value is the number of milliseconds since Jan. 1, 1970, midnight GMT. + */ + expirationTime: number; + + /** + * The last refresh time of the access token. + * The value is the number of milliseconds since Jan. 1, 1970, midnight GMT. + */ + lastRefreshTime: number; + /** + * Getter for the access token that is current for the application. + */ + static getCurrentAccessToken(): Promise; + + /** + * Setter for the access token that is current for the application. + */ + static setCurrentAccessToken(accessToken: AccessTokenMap): void; + + /** + * Updates the current access token with up to date permissions, + * and extends the expiration date, if extension is possible. + */ + + static refreshCurrentAccessTokenAsync(): Promise; + + constructor(tokenMap: AccessTokenMap); + + /** + * Gets the date at which the access token expires. The value is the number of + * milliseconds since Jan. 1, 1970, midnight GMT. + */ + getExpires(): number; + + /** + * Get the list of permissions associated with this access token. Note that the most up-to-date + * list of permissions is maintained by Facebook, so this list may be outdated if permissions + * have been added or removed since the time the AccessToken object was created. See + * https://developers.facebook.com/docs/reference/login/#permissions for details. + */ + getPermissions(): Permissions[]; + + /** + * Gets the list of permissions declined by the user with this access token. It represents the + * entire set of permissions that have been requested and declined. Note that the most + * up-to-date list of permissions is maintained by Facebook, so this list may be outdated if + * permissions have been granted or declined since the last time an AccessToken object was + * created. See https://developers.facebook.com/docs/reference/login/#permissions for details. + */ + getDeclinedPermissions(): Permissions[]; + + /** + * Gets the date at which the token was last refreshed. Since tokens expire, the Facebook SDK + * will attempt to renew them periodically. The value is the number of milliseconds since + * Jan. 1, 1970, midnight GMT. + */ + getLastRefresh(): number; + + /** + * Gets the ID of the Facebook Application associated with this access token. + */ + getApplicationId(): string; + + /** + * Gets user ID associated with this access token. + */ + getUserId(): string; +} + +/** + * Controls when an AppEventsLogger sends log events to the server + */ +export type AppEventsFlushBehavior = + /** + * Flush automatically: periodically (every 15 seconds or after every 100 events), and + * always at app reactivation. This is the default value. + */ + 'auto' | + /** + * Only flush when AppEventsLogger.flush() is explicitly invoked. + */ + 'explicitly-only'; + +export interface Params { + [key: string]: string | number; +} + +export namespace AppEventsLogger { + /** + * Sets the current event flushing behavior specifying when events + * are sent back to Facebook servers. + */ + function setFlushBehavior(flushBehavior: AppEventsFlushBehavior): void; + + /** + * Logs an event with eventName and optional arguments. + * This function supports the following usage: + * logEvent(eventName: string); + * logEvent(eventName: string, valueToSum: number); + * logEvent(eventName: string, parameters: {[key:string]:string|number}); + * logEvent(eventName: string, valueToSum: number, parameters: {[key:string]:string|number}); + * See https://developers.facebook.com/docs/app-events/android for detail. + */ + function logEvent(eventName: string, ...args: Array): void; + + /** + * Logs a purchase. See http://en.wikipedia.org/wiki/ISO_4217 for currencyCode. + */ + function logPurchase(purchaseAmount: number, currencyCode: string, parameters?: object): void; + + /** + * Logs an app event that tracks that the application was open via Push Notification. + */ + function logPushNotificationOpen(payload?: object): void; + + /** + * Explicitly kicks off flushing of events to Facebook. + */ + function flush(): void; + + /** + * For iOS only, sets and sends device token to register the current application for push notifications. + * @platform ios + */ + function setPushNotificationsDeviceToken(deviceToken: string): void; + + /** + * For Android only, sets and sends registration id to register the current app for push notifications. + * @platform Android + */ + function setPushNotificationsRegistrationId(registrationId: string): void; +} + +export namespace AppInviteDialog { + /** + * Check if the dialog can be shown. + */ + function canShow(): Promise; + + /** + * Shows the dialog using the specified content. + */ + function show(appInviteContent: AppInviteContent): Promise; +} + +export namespace GameRequestDialog { + /** + * Check if the dialog can be shown. + */ + function canShow(): Promise; + + /** + * Shows the dialog using the specified content. + */ + function show(gameRequestContent: GameRequestContent): Promise; +} + +export type GraphRequestCallback = (error?: object, result?: object) => void; +export interface GraphRequestConfig { + /** + * The httpMethod to use for the request, for example "GET" or "POST". + */ + httpMethod?: string; + /** + * The Graph API version to use (e.g., "v2.0") + */ + version?: string; + /** + * The request parameters. + */ + parameters?: GraphRequestParameters; + /** + * The access token used by the request. + */ + accessToken?: string; +} + +export interface GraphRequestParameters { + [key: string]: object; +} + +/** + * Represents a Graph API request and provides batch request supports. + */ +export class GraphRequest { + /** + * The Graph API endpoint to use for the request, for example "me". + */ + graphPath: string; + + /** + * The optional config for the request. + */ + config?: GraphRequestConfig; + + /** + * Called upon completion or failure of the request. + */ + callback?: GraphRequestCallback; + + /** + * Constructs a new Graph API request. + */ + constructor(graphPath: string, config?: GraphRequestConfig | null, callback?: GraphRequestCallback); + + /** + * Adds a string parameter to the request. + */ + addStringParameter(paramString: string, key: string): void; +} + +export class GraphRequestManager { + requestBatch: GraphRequest[]; + requestCallbacks: Array; + batchCallback: GraphRequestCallback; + constructor(); + + /** + * Add a graph request. + */ + addRequest(request: GraphRequest): GraphRequestManager; + + /** + * Add call back to the GraphRequestManager. Only one callback can be added. + * Note that invocation of the batch callback does not indicate success of every + * graph request made, only that the entire batch has finished executing. + */ + addBatchCallback(callback: GraphRequestCallback): GraphRequestManager; + + /** + * Executes requests in a batch. + * Note that when there's an issue with network connection the batch callback + * behavior differs in Android and iOS. + * On iOS, the batch callback returns an error if the batch fails with a network error. + * On Android, the batch callback always returns {"result": "batch finished executing"} + * after the batch time out. This is because detecting network status requires + * extra permission and it's unncessary for the sdk. Instead, you can use the NetInfo module + * in react-native to get the network status. + */ + start(timeout?: number): void; +} + +export type AuxiliaryViewPosition = 'top' | 'bottom' | 'inline'; +export type HorizontalAlignment = 'center' | 'left' | 'right'; +export type LikeViewStyle = 'button'| // Note 'button' is only available on Android. + 'standard' | + 'box_count'; + +export interface LikeViewProps { + /** + * The objectId and type for the object to like. + */ + objectIdAndType: ObjectIdAndType; + + /** + * The style to use for the receiver. Distinct from React styling. + */ + likeViewStyle?: LikeViewStyle; + + /** + * The position for the auxiliary view for the receiver. + */ + auxiliaryViewPosition?: AuxiliaryViewPosition; + + /** + * The text alignment of the social sentence. + */ + horizontalAlignment?: HorizontalAlignment; + + /** + * The foreground color to use for the content of the receiver. + */ + foregroundColor?: number; + + /** + * If true, a sound is played when the receiver is toggled. + */ + soundEnabled?: boolean; + + /** + * View style, if any. + */ + style?: ViewStyle; +} + +export class LikeView extends Component {} + +export type TooltipBehaviorIOS = 'auto' | 'force_display' | 'disable'; + +export interface LoginButtonProps { + /** + * Represents the read permissions to request when the login button + * is pressed. + */ + readPermissions?: Permissions[]; + + /** + * Represents the publish permissions to request when the login + * button is pressed. + */ + publishPermissions?: Permissions[]; + + /** + * The callback invoked upon error/completion of a login request. + */ + onLoginFinished?(error: object, result: LoginResult): void; + + /** + * The callback invoked upon completion of a logout request. + */ + onLogoutFinished?(): void; + + /** + * The behavior to use when attempting a login. + * @platform android + */ + loginBehaviorAndroid?: LoginBehaviorAndroid; + + /** + * The behavior to use when attempting a login. + * @platform ios + */ + loginBehaviorIOS?: LoginBehaviorIOS; + + /** + * The default audience to target when attempting a login. + */ + defaultAudience?: DefaultAudience; + + /** + * For iOS only, the desired tooltip behavior. + * @platform ios + */ + tooltipBehaviorIOS?: TooltipBehaviorIOS; + + /** + * View style, if any. + */ + style?: ViewStyle; +} + +export class LoginButton extends Component { + private _eventHandler(event: object): void; +} + +/** + * Indicates which default audience to use for sessions that post data to Facebook. + */ +export type DefaultAudience = + // Indicates that the user's friends are able to see posts made by the application. + 'friends' | + // Indicates that all Facebook users are able to see posts made by the application. + 'everyone' | + // Indicates that only the user is able to see posts made by the application. + 'only_me'; + +export type LoginBehavior = LoginBehaviorIOS | LoginBehaviorAndroid; + +/** + * Indicate how Facebook Login should be attempted on Android. + */ +export type LoginBehaviorAndroid = + // Attempt login in using the Facebook App, and if that does not work fall back to web dialog auth. + 'native_with_fallback'| + // Only attempt to login using the Facebook App. + 'native_only'| + // Only the web dialog auth should be used. + 'web_only'; + +/** + * Indicate how Facebook Login should be attempted on iOS. + */ +export type LoginBehaviorIOS = + // Attempts log in through the native Facebook app. + // The SDK may still use Safari instead. + // See details in https://developers.facebook.com/blog/post/2015/10/29/Facebook-Login-iOS9/ + 'native' | + // Attempts log in through the Safari browser. + 'browser' | + // Attempts log in through the Facebook account currently signed in through Settings. + 'system_account' | + // Attempts log in through a modal UIWebView pop-up. + 'web'; + +/** + * Shows the results of a login operation. + */ +export interface LoginResult { + error: any; + isCancelled: boolean; + grantedPermissions?: Permissions[]; + declinedPermissions?: Permissions[]; +} + +export namespace LoginManager { + /** + * Logs the user in with the requested read permissions. + */ + function logInWithReadPermissions(permissions: Permissions[]): Promise; + + /** + * Logs the user in with the requested publish permissions. + */ + function logInWithPublishPermissions(permissions: Permissions[]): Promise; + + /** + * Getter for the login behavior. + */ + function getLoginBehavior(): Promise; + + /** + * Setter for the login behavior. + */ + function setLoginBehavior(loginBehavior: LoginBehavior): void; + + /** + * Getter for the default audience. + */ + function getDefaultAudience(): Promise; + + /** + * Setter for the default audience. + */ + function setDefaultAudience(defaultAudience: DefaultAudience): void; + + /** + * Logs out the user. + */ + function logOut(): void; +} + +export namespace MessageDialog { + /** + * Check if the dialog can be shown. + */ + function canShow(shareContent: ShareContent): Promise; + + /** + * Shows the dialog using the specified content. + */ + function show(shareContent: ShareContent): Promise; + + /** + * Sets whether or not the native message dialog should fail when it encounters a data error. + */ + function setShouldFailOnDataError(shouldFailOnDataError: boolean): void; +} + +export interface SendButtonProps { + /** + * Content to be shared. + */ + shareContent: ShareContent; + + /** + * View style, if any. + */ + style?: ViewStyle; +} + +export class SendButton extends Component {} + +export namespace ShareApi { + /** + * Check if the content can be shared via share api. + */ + function canShare(shareContent: ShareContent): Promise; + + /** + * For iOS only, creates a User Owned Open Graph object without an action. + * NOTE: Only one share action can be performed at a time. + * @platform ios + */ + function createOpenGraphObject(openGraphObject: ShareOpenGraphObject): Promise; + + /** + * Shares the specified content with a message. + * NOTE: Only one share action can be performed at a time. + */ + function share(shareContent: ShareContent, graphNode: string, message: string): Promise; +} + +export interface ShareButtonProps { + /** + * Content to be shared. + */ + shareContent: ShareContent; + + /** + * View style, if any. + */ + style?: ViewStyle; +} + +export class ShareButton extends Component {} + +export type ShareDialogMode = ShareDialogModeIOS | ShareDialogModeAndroid; +export type ShareDialogModeAndroid = + /** + * The mode is determined automatically. + */ + 'automatic'| + /** + * The native dialog is used. + */ + 'native'| + /** + * The web dialog is used. + */ + 'web'| + /** + * The feed dialog is used. + */ + 'feed'; +export type ShareDialogModeIOS = + /* + * Acts with the most appropriate mode that is available. + */ + 'automatic'| + /* + * Displays the dialog in Safari. + */ + 'browser'| + /* + * Displays the dialog in a UIWebView within the app. + */ + 'webview'; + +export namespace ShareDialog { + /** + * Check if the dialog can be shown. + */ + function canShow(shareContent: ShareContent): Promise; + + /** + * Shows the dialog using the specified content. + */ + function show(shareContent: ShareContent): Promise; + + /** + * Sets the mode for the share dialog. + */ + function setMode(mode: ShareDialogMode): void; + + /** + * Sets whether or not the native share dialog should fail when it encounters a data error. + */ + function setShouldFailOnDataError(shouldFailOnDataError: boolean): void; } -export as namespace FBSDK; -// tslint:disable-next-line:export-just-namespace -export = FBSDK; diff --git a/types/react-native-fbsdk/react-native-fbsdk-tests.tsx b/types/react-native-fbsdk/react-native-fbsdk-tests.tsx index a6334f2cfc..7d1210f06a 100644 --- a/types/react-native-fbsdk/react-native-fbsdk-tests.tsx +++ b/types/react-native-fbsdk/react-native-fbsdk-tests.tsx @@ -1,36 +1,107 @@ import * as React from 'react'; import * as FBSDK from 'react-native-fbsdk'; import { View } from 'react-native'; -import render from '../react-dom/index'; const { - LoginButton, - AccessToken + LoginButton, + AccessToken, + LoginManager, + ShareDialog, + AppEventsLogger, + GraphRequest, + GraphRequestManager, } = FBSDK; -class Login extends React.Component { - render() { - return ( - - { - if (error) { - alert("login has error: " + result.error); - } else if (result.isCancelled) { - alert("login is cancelled."); - } else { - AccessToken.getCurrentAccessToken().then( - (data) => { - alert(data.accessToken.toString()) - } - ); - } - } - } - onLogoutFinished={() => alert("logout.")}/> - - ); - } +export class Login extends React.Component { + render() { + return ( + + { + if (error) { + alert("login has error: " + result.error); + } else if (result.isCancelled) { + alert("login is cancelled."); + } else { + AccessToken.getCurrentAccessToken().then( + (data) => { + if (data) { + alert(data.accessToken.toString()); + } + } + ); + } + } + } + onLogoutFinished={() => alert("logout.")} + /> + + ); + } } + +// Attempt a login using the Facebook login dialog asking for default permissions. +LoginManager.logInWithReadPermissions(['public_profile']).then( + (result) => { + if (result.isCancelled) { + alert('Login cancelled'); + } else { + alert(`Login success with permissions: ${result.grantedPermissions}`); + } + }, + (error) => { + alert(`Login fail with error: ${error}`); + } +); + +// Build up a shareable link. +const shareLinkContent: FBSDK.ShareLinkContent = { + contentType: 'link', + contentUrl: "https://facebook.com", + contentDescription: 'Wow, check out this great site!', +}; + +// Share the link using the share dialog. +export const shareLinkWithShareDialog = (): void => { + ShareDialog.canShow(shareLinkContent).then( + (canShow) => { + if (canShow) { + return ShareDialog.show(shareLinkContent); + } + } + ).then( + (result) => { + if (result.isCancelled) { + alert('Share cancelled'); + } else { + alert(`Share success with postId: ${result.postId}`); + } + }, + (error: Error) => { + alert(`Share fail with error: ${error}`); + } + ); +}; + +const obj = { param: 'value' }; +AppEventsLogger.logPurchase(15, 'USD', obj); + +const responseInfoCallback: FBSDK.GraphRequestCallback = (error, result) => { + if (error) { + alert(`Error fetching data: ${error}`); + } else { + alert(`Success fetching data: ${result}`); + } +}; + +// Create a graph request asking for user information with a callback to handle the response. +const infoRequest = new GraphRequest( + '/me', + null, + responseInfoCallback, +); + +// Start the graph request. +new GraphRequestManager().addRequest(infoRequest).start(); diff --git a/types/react-native-fbsdk/tsconfig.json b/types/react-native-fbsdk/tsconfig.json index 52ea75b5cb..d6dccb2d02 100644 --- a/types/react-native-fbsdk/tsconfig.json +++ b/types/react-native-fbsdk/tsconfig.json @@ -15,10 +15,10 @@ "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, - "jsx": "react" + "jsx": "react-native" }, "files": [ "index.d.ts", - "react-native-elements-tests.tsx" + "react-native-fbsdk-tests.tsx" ] } From b9f2a3e762933e54fee991fbd63c3d0f55ecaffa Mon Sep 17 00:00:00 2001 From: Saeed Tabrizi Date: Wed, 19 Jul 2017 19:06:21 +0430 Subject: [PATCH 0144/1139] a fix for tslint. --- types/orientjs/index.d.ts | 32 ++++++++++++++++---------------- types/orientjs/orientjs-tests.ts | 22 +++++----------------- 2 files changed, 21 insertions(+), 33 deletions(-) diff --git a/types/orientjs/index.d.ts b/types/orientjs/index.d.ts index 4fc16bffe3..e460074336 100644 --- a/types/orientjs/index.d.ts +++ b/types/orientjs/index.d.ts @@ -87,8 +87,8 @@ declare module "orientjs" { className?: string }; - class Manager extends MigrationManager{ - constructor (config: MigrationManagerConfig); + class Manager extends MigrationManager { + constructor(config: MigrationManagerConfig); } interface Migration { name: string; @@ -374,7 +374,7 @@ declare module "orientjs" { * @param {Integer} offset The offset to start returning records from. * @promise {Object[]} An array of records in the class. */ - find(attributes: any, limit ?: number, offset?: number): Promise; + find(attributes: any, limit?: number, offset?: number): Promise; /** * Create a record for this class. * @@ -764,18 +764,18 @@ declare module "orientjs" { interface RawExpression { db: Db; value: string; - as(alias:string): RawExpression; + as(alias: string): RawExpression; } interface AbsSqlFunction { - new (field: number | string): AbsSqlFunction; + new(field: number | string): AbsSqlFunction; } interface AvgSqlFunction { - new (field: string): AvgSqlFunction; + new(field: string): AvgSqlFunction; } interface SequenceSqlFunction { - new (name: string): SequenceSqlFunction; + new(name: string): SequenceSqlFunction; next(): number; current(): number; reset(): number; @@ -789,12 +789,12 @@ declare module "orientjs" { } interface QueryOptions { - params?:any; + params?: any; mode?: "s" | "a" | "l"; fetchPlan?: any; limit?: number; - token?:any; - class?:string; + token?: any; + class?: string; language?: "SQL" | "Javascript" } @@ -981,10 +981,10 @@ declare module "orientjs" { */ let(params?: any): Statement; let(name: string, value: string | Statement): Statement; -/** Create a transactional query with if. - * - * @return {Query} The query instance. - */ + /** Create a transactional query with if. + * + * @return {Query} The query instance. + */ if(condition: SqlExpression, statements: Statement[]): Statement; /** Create a transactional query with if. * @@ -1035,7 +1035,7 @@ declare module "orientjs" { * @param {String|Object} options The server URL, or configuration object */ interface Server { - new (options?: ServerConfig): Server; + new(options?: ServerConfig): Server; config: ServerConfiguration; logger: Logger; @@ -1155,7 +1155,7 @@ declare module "orientjs" { } interface ODatabase extends Db { - new (config?: { + new(config?: { host: string, port?: number, username?: string, diff --git a/types/orientjs/orientjs-tests.ts b/types/orientjs/orientjs-tests.ts index 82504077ed..464d416122 100644 --- a/types/orientjs/orientjs-tests.ts +++ b/types/orientjs/orientjs-tests.ts @@ -5,22 +5,10 @@ let dbserver = orientjs({ port: 2424, username: 'root', password: 'root' - }); +}); let db = dbserver.use({ - name: 'mytestdb', - username: 'root', - password: 'root' - }); + name: 'mytestdb', + username: 'root', + password: 'root' +}); - -{ - var manager = new orientjs.Migration.Manager({ - db: db, - dir: __dirname + '/migrations' - }); - - manager.up(1) - .then(function () { - console.log('migrated up by one!') - }); -} From 0ce5a31141dbad3b5e9eef42f7134cb5bca336df Mon Sep 17 00:00:00 2001 From: Kyle Roach Date: Wed, 19 Jul 2017 10:40:49 -0400 Subject: [PATCH 0145/1139] [react-native-vector-icons] TabBarIOS should've been TabBarItemIOS --- types/react-native-vector-icons/Icon.d.ts | 96 ++++++++++--------- .../react-native-vector-icons-tests.tsx | 43 ++++++++- 2 files changed, 91 insertions(+), 48 deletions(-) diff --git a/types/react-native-vector-icons/Icon.d.ts b/types/react-native-vector-icons/Icon.d.ts index 3ae4916eea..353cbbb08d 100644 --- a/types/react-native-vector-icons/Icon.d.ts +++ b/types/react-native-vector-icons/Icon.d.ts @@ -5,7 +5,7 @@ import { TextProperties, TouchableHighlightProperties, TouchableNativeFeedbackProperties, - TabBarIOSProperties, + TabBarItemProperties, ToolbarAndroidProperties } from 'react-native'; @@ -90,51 +90,6 @@ export interface IconButtonProps extends IconProps, TouchableHighlightProperties export type ImageSource = any; -export interface TabBarIOSProps extends TabBarIOSProperties { - /** - * Name of the default icon (similar to TabBarIOS.Item icon) - * - * @type {string} - * @memberof TabBarIOSProps - */ - iconName: string; - - /** - * Name of the selected icon (similar to TabBarIOS.Item selectedIcon). - * - * @default iconName - * @type {string} - * @memberof TabBarIOSProps - */ - selectedIconName: string; - - /** - * Size of the icon. - * - * @default 30 - * @type {number} - * @memberof TabBarIOSProps - */ - iconSize: number; - - /** - * Color of the icon - * - * @type {string} - * @memberof TabBarIOSProps - */ - iconColor: string; - - /** - * Color of the selected icon. - * - * @default iconColor - * @type {string} - * @memberof TabBarIOSProps - */ - selectedIconColor: string; -} - export interface ToolbarAndroidProps extends ToolbarAndroidProperties { /** * Name of the navigation logo icon @@ -182,6 +137,53 @@ export interface ToolbarAndroidProps extends ToolbarAndroidProperties { iconColor: string; } +export interface TabBarItemIOSProps extends TabBarItemProperties { + /** + * Name of the default icon (similar to TabBarIOS.Item icon) + * + * @type {string} + * @memberof TabBarIOSItemProps + */ + iconName: string; + + /** + * Name of the selected icon (similar to TabBarIOS.Item selectedIcon) + * + * Defaults to iconName + * + * @type {string} + * @memberof TabBarIOSItemProps + */ + selectedIconName?: string; + + /** + * Size of the icon + * + * @default 30 + * @type {number} + * @memberof TabBarIOSItemProps + */ + iconSize?: number; + + /** + * Color of the icon + * + * @type {string} + * @memberof TabBarIOSItemProps + */ + iconColor?: string; + + /** + * Color of the selected icon. + * + * Defaults to iconColor + * + * @type {string} + * @memberof TabBarIOSItemProps + */ + selectedIconColor?: string; +} + export class Icon extends React.Component { static getImageSource( name: string, @@ -192,6 +194,6 @@ export class Icon extends React.Component { export namespace Icon { class ToolbarAndroid extends React.Component {} - class TabBarIOS extends React.Component {} + class TabBarItemIOS extends React.Component {} class Button extends React.Component {} } diff --git a/types/react-native-vector-icons/react-native-vector-icons-tests.tsx b/types/react-native-vector-icons/react-native-vector-icons-tests.tsx index 270c8fbdc4..ea61e6690b 100644 --- a/types/react-native-vector-icons/react-native-vector-icons-tests.tsx +++ b/types/react-native-vector-icons/react-native-vector-icons-tests.tsx @@ -1,7 +1,8 @@ import * as React from 'react'; -import { View, Text } from 'react-native'; +import { View, Text, TabBarIOS } from 'react-native'; import MaterialIcon from 'react-native-vector-icons/MaterialIcons'; import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome'; +import Ionicon from 'react-native-vector-icons/Ionicons'; class Example extends React.Component<{}, {}> { handleButton() { @@ -28,3 +29,43 @@ class Example extends React.Component<{}, {}> { ); } } + +class TabTest extends React.Component { + constructor() { + super(); + + this.state = { + selectedTab: 'tab1' + }; + } + + render() { + return ( + + this.setState({selectedTab: 'tab1'})} + > + + + + this.setState({selectedTab: 'tab2'})} + > + + + + ); + } +} From 0072c8b729fee124408fc4a42275627b9dc2b16f Mon Sep 17 00:00:00 2001 From: Saeed Tabrizi Date: Wed, 19 Jul 2017 20:29:38 +0430 Subject: [PATCH 0146/1139] fix all lint errors and replacments . --- types/orientjs/index.d.ts | 977 ++++++++++++++----------------- types/orientjs/orientjs-tests.ts | 1 - 2 files changed, 454 insertions(+), 524 deletions(-) diff --git a/types/orientjs/index.d.ts b/types/orientjs/index.d.ts index e460074336..3eef7ace34 100644 --- a/types/orientjs/index.d.ts +++ b/types/orientjs/index.d.ts @@ -1,14 +1,17 @@ -// Type definitions for orientjs v3.0.0 +// Type definitions for orientjs 3.0 // Project: https://github.com/orientechnologies/orientjs // Definitions by: [Saeed Tabrizi] // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last Update : 19-7-2017 +// Last Update : 19-7-2017 // Compatible with Orientdb >= 2.2.15 and orientjs >= 2.2.x features . // Developed with love in www.nowcando.com -// +// /// +import events = require('events'); +import Promise = require('bluebird'); + /* =================== USAGE =================== import orientjs = require('orientjs'); let dbserver = orientjs({ @@ -25,22 +28,23 @@ =============================================== */ /** A lightweight definiton for orientjs module, Official node.js driver for OrientDB. - * + * * @description Official node.js driver for OrientDB. Fast, lightweight, uses the binary protocol. - * - * @author Saeed Tabrizi (saeed a_t nowcando.com) + * + * @author Saeed Tabrizi (saeed a_t nowcando.com) * @version 3.0.0 - * -*/ -declare module "orientjs" { - import events = require('events'); - import Promise = require('bluebird'); + * + */ +declare namespace orientjs { function ojs(config: ojs.ServerConfig): ojs.OrientJs; - module ojs { - + namespace ojs { type Version = number | string; - type PropertyType = "Boolean" | "Integer" | "Short" | "Long" | "Float" | "Double" | "DateTime" | "String" | "Binary" | "Embedded" | "EmbeddedList" | "EmbeddedSet" | "EmbeddedMap" | "Link" | "LinkList" | "LinkSet" | "LinkMap" | "Byte" | "Transient" | "Date" | "Custom" | "Decimal" | "LinkBag"; + type PropertyType = "Boolean" | "Integer" | "Short" | "Long" | + "Float" | "Double" | "DateTime" | "string" | "Binary" | + "Embedded" | "EmbeddedList" | "EmbeddedSet" | "EmbeddedMap" | + "Link" | "LinkList" | "LinkSet" | "LinkMap" | "Byte" | + "Transient" | "Date" | "Custom" | "Decimal" | "LinkBag"; enum DataTypes { Boolean = 0, Integer = 1, @@ -49,7 +53,7 @@ declare module "orientjs" { Float = 4, Double = 5, Datetime = 6, - String = 7, + string = 7, Binary = 8, Embedded = 9, EmbeddedList = 10, @@ -67,37 +71,36 @@ declare module "orientjs" { LinkBag = 22 } - module errors { - interface BaseError { + namespace errors { + class BaseError { name: string; init(name: string): void; } - interface OperationError extends BaseError { + class OperationError extends BaseError { message: string; date: any; } - interface RequestError extends OperationError { } + class RequestError extends OperationError { + } } - module Migration { - type MigrationManagerConfig = { - name?: string, - db?: Db, - dir?: string, - className?: string - }; - + namespace Migration { + interface MigrationManagerConfig { + name?: string; + db?: Db; + dir?: string; + className?: string; + } class Manager extends MigrationManager { constructor(config: MigrationManagerConfig); } - interface Migration { + class Migration { name: string; server: Server; db: Db; configure(config?: any): void; up(): Promise; down(): Promise; - } class MigrationManager { @@ -115,132 +118,119 @@ declare module "orientjs" { className: string; /** - * Create a new migration. - * - * @param {String|Object} config The name or configuration for the new migration. - * @promise {String} The full path to the created migration. - */ + * Create a new migration. + * + * @param {string|Object} config The name or configuration for the new migration. + * @promise {string} The full path to the created migration. + */ create(param: string): Promise; /** - * Generate the content for a migration. - * @param {Object} config The configuration object. - * @return {String} The generated JavaScript source code. - */ + * Generate the content for a migration. + * @param {Object} config The configuration object. + * @return {string} The generated JavaScript source code. + */ generateMigration(config: any): string; /** - * List the migrations that have not yet been applied. - * - * @promise {String[]} An array of migration names - */ + * List the migrations that have not yet been applied. + * + * @promise {string[]} An array of migration names + */ list(): Promise; /** - * List all the available migrations. - * - * @promise {String[]} The names of the available migrations. - */ + * List all the available migrations. + * + * @promise {string[]} The names of the available migrations. + */ listAvailable(): Promise; /** - * Ensure the migration class exists. - * - * @promise {MigrationManager} The manager instance with intact structure. - */ + * Ensure the migration class exists. + * + * @promise {MigrationManager} The manager instance with intact structure. + */ ensureStructure: Promise; /** - * Retrieve a list of applied migrations. - * - * @promise {Object[]} The applied migrations. - */ + * Retrieve a list of applied migrations. + * + * @promise {Object[]} The applied migrations. + */ listApplied(): Promise; /** - * Perform the migration. - * - * @param {Integer} limit The maximum number of migrations to apply, if any. - * @promise {Mixed} The result of the migration. - */ + * Perform the migration. + * + * @param {Integer} limit The maximum number of migrations to apply, if any. + * @promise {Mixed} The result of the migration. + */ up(limit?: number): Promise; /** - * Revert the migration. - * - * @param {Integer} limit The maximum number of migrations to revert, if any. - * @promise {Mixed} The result of the migration. - */ + * Revert the migration. + * + * @param {Integer} limit The maximum number of migrations to revert, if any. + * @promise {Mixed} The result of the migration. + */ down(limit?: number): Promise; /** - * Load the migration with the given name. - * - * @param {String} name The name of the migation. - * @return {Migration} The loaded migration instance. - */ + * Load the migration with the given name. + * + * @param {string} name The name of the migation. + * @return {Migration} The loaded migration instance. + */ loadMigration(name: string): Migration; /** - * Apply the migration with the given name. - * - * @param {String} name The name of the migation. - * @promise {Mixed} The result of the migration. - */ + * Apply the migration with the given name. + * + * @param {string} name The name of the migation. + * @promise {Mixed} The result of the migration. + */ applyMigration(name: string): Promise; /** - * Revert the migration with the given name. - * - * @param {String} name The name of the migation. - * @promise {Mixed} The result of the migration. - */ + * Revert the migration with the given name. + * + * @param {string} name The name of the migation. + * @promise {Mixed} The result of the migration. + */ revertMigration(name: string): Promise; } } interface Logger { - error?: Function; - log?: Function; - debug?: Function; + error(...args: any[]): void; + log(...args: any[]): void; + debug(...args: any[]): void; } - interface RID extends String { + class RID extends String { cluster?: number; position?: number; valueOf(): string; - isValid?(): boolean; - equals?(rid: string) - : boolean; - equals?(rid: RID) - : boolean; - parse?(input: string) - : boolean; - parse?(input: string) - : RID; - parse?(input: string) - : RID[]; - isValid?(input: string) - : boolean; - isValid?(input: RID) - : boolean; - isValid?(input: any) - : boolean; - toRid?(cluster: number, position: number) - : any; + isValid?(input?: string | RID | any): boolean; + equals?(rid: string | RID): boolean; + parse?(input: string): boolean; + parse?(input: string): RID; + parse?(input: string): RID[]; + toRid?(cluster: number, position: number): any; } interface CustomField { /** * Get the value of the given custom field. * - * @param {String} key The name of the field to get. + * @param {string} key The name of the field to get. * @return {Mixed} The field value, or undefined if it doesn't exist. */ get(key: string): CustomField; /** * Set a custom field. * - * @param {String|Object} key The key to set, or map of keys to values. - * @param {String} value The value to set, if `key` is not an object. + * @param {string|Object} key The key to set, or map of keys to values. + * @param {string} value The value to set, if `key` is not an object. * @promise {Object|null} The new set of custom fields, or null if none are present. */ set(key: string, value: any): CustomField; /** * Unset the custom field with the given name, * - * @param {String} key The name of the custom field to remove. + * @param {string} key The name of the custom field to remove. * @promise {Object|null} The new set of custom fields, or null if none are present. */ unset(key: string): CustomField; @@ -263,7 +253,7 @@ declare module "orientjs" { max?: number; custom?: { fields?: CustomField[] - } + }; } interface PropertyUpdateConfig { @@ -281,11 +271,10 @@ declare module "orientjs" { max?: number; custom?: { fields?: CustomField[] - } + }; } - interface Property { - + class Property { class?: Class; name?: string; originalName?: string; @@ -301,50 +290,48 @@ declare module "orientjs" { max?: number; custom?: { fields?: CustomField[] - } + }; configure(config?: any): void; reload(): Promise; - rename(newName: string): Promise; list(): Promise; /** * Create a new property. * - * @param {String|Object} config The property name or configuration. + * @param {string|Object} config The property name or configuration. * @param {Boolean} reload Whether to reload the property, default to true. * @promise {Object} The created property. */ create(config?: PropertyCreateConfig | string, reload?: boolean): Promise; create(config: PropertyCreateConfig[], reload?: boolean): Promise; /** - * Get the property with the given name. - * - * @param {String} name The property to get. - * @promise {Object|null} The retrieved property. - */ + * Get the property with the given name. + * + * @param {string} name The property to get. + * @promise {Object|null} The retrieved property. + */ get(name: string): Promise; /** - * Update the given property. - * - * @param {Object} property The property settings. - * @param {Boolean} reload Whether to reload the property, default to true. - * @promise {Object} The updated property. - */ + * Update the given property. + * + * @param {Object} property The property settings. + * @param {Boolean} reload Whether to reload the property, default to true. + * @promise {Object} The updated property. + */ update(config: PropertyUpdateConfig, reload?: boolean): Promise; drop(name: string, config?: { ifexist?: boolean, force?: boolean }): Promise; alter(name: string, setting?: any): Promise; - rename(oldName: string, newName: string): Promise; + rename(oldName: string, newName?: string): Promise; } /** - * The class constructor. - * @param {Object} config The configuration for the class - */ - interface Class { - + * The class constructor. + * @param {Object} config The configuration for the class + */ + class Class { db?: Db; name?: string; shortName?: string; @@ -353,64 +340,62 @@ declare module "orientjs" { originalName?: string; clusterIds?: number[]; /** - * Configure the class instance. - * @param {Object} config The configuration object. - */ + * Configure the class instance. + * @param {Object} config The configuration object. + */ configure(config?: any): void; /** - * Retreive a list of classes from the database. - * - * @param {Boolean} refresh Whether to refresh the list or not. - * @promise {Object[]} An array of class objects. - */ - list(limit: number, offset: number): Promise; - list(config: any): Promise; - list(refresh: boolean): Promise; + * Retreive a list of classes from the database. + * + * @param {Boolean} refresh Whether to refresh the list or not. + * @promise {Object[]} An array of class objects. + */ + list(limit: number | boolean | any, offset?: number): Promise; /** - * Find a list of records in the class. - * - * @param {Object} attributes The attributes to search with. - * @param {Integer} limit The maximum number of records to return - * @param {Integer} offset The offset to start returning records from. - * @promise {Object[]} An array of records in the class. - */ + * Find a list of records in the class. + * + * @param {Object} attributes The attributes to search with. + * @param {Integer} limit The maximum number of records to return + * @param {Integer} offset The offset to start returning records from. + * @promise {Object[]} An array of records in the class. + */ find(attributes: any, limit?: number, offset?: number): Promise; /** - * Create a record for this class. - * - * @param {Object} record The record to create. - * @promise {Object} The created record. - */ + * Create a record for this class. + * + * @param {Object} record The record to create. + * @promise {Object} The created record. + */ create(record: Record): Promise; /** - * Create a new class. - * - * @param {String} name The name of the class to create. - * @param {String} parentName The name of the parent to extend, if any. - * @param {String|Integer} cluster The cluster name or id. - * @param {Boolean} isAbstract The flag for the abstract class - * @param {Boolean} ifnotexist The flag for the if not exist class - * @promise {Object} The created class object - */ + * Create a new class. + * + * @param {string} name The name of the class to create. + * @param {string} parentName The name of the parent to extend, if any. + * @param {string|Integer} cluster The cluster name or id. + * @param {Boolean} isAbstract The flag for the abstract class + * @param {Boolean} ifnotexist The flag for the if not exist class + * @promise {Object} The created class object + */ create(name: string, parentName?: string, cluster?: string, isAbstract?: boolean, ifnotexist?: boolean): Promise; /** - * Update the given class. - * - * @param {Object} class The class settings. - * @param {Boolean} reload Whether to reload the class, default to true. - * @promise {Object} The updated class. - */ + * Update the given class. + * + * @param {Object} class The class settings. + * @param {Boolean} reload Whether to reload the class, default to true. + * @promise {Object} The updated class. + */ update(cls: any, reload: boolean): Promise; /** - * Reload the class instance. - * - * @promise {Class} The class instance. - */ + * Reload the class instance. + * + * @promise {Class} The class instance. + */ reload(): Promise; /** * Delete a class. * - * @param {String} name The name of the class to delete. + * @param {string} name The name of the class to delete. * @param {Object} config The config. * @promise {Db} The database instance. */ @@ -421,7 +406,7 @@ declare module "orientjs" { /** * Get a class by name. * - * @param {Integer|String} name The name of the class. + * @param {Integer|string} name The name of the class. * @param {Boolean} refresh Whether to refresh the data, defaults to false. * @promise {Object} The class object if it exists. */ @@ -434,31 +419,27 @@ declare module "orientjs" { */ cacheData(classes: Class[]): Db; property: Property; - } - interface Cluster { + class Cluster { name?: string; location?: string; list(refresh?: boolean): Promise; create(name: string, location?: string): Promise & Promise; get(nameOrId: string, refresh?: boolean): Promise & Promise; - get(nameOrId: number, refresh?: boolean): Promise & Promise; getByName(name: string, refresh?: boolean): Promise & Promise; getById(id: string, refresh?: boolean): Promise & Promise; drop(name: string): Promise; - count(name: string): Promise; + count(name: string): Promise; range(name: string): Promise; cacheData(clusters: Cluster[] & any[]): Db; - } /** * The sequence constructor. * @param {Object} config The configuration for the sequence */ - interface Sequence { - + class Sequence { db?: Db; name?: string; type?: string; @@ -467,62 +448,62 @@ declare module "orientjs" { start?: number; cache?: number; /** - * Configure the sequence instance. - * @param {Object} config The configuration object. - */ + * Configure the sequence instance. + * @param {Object} config The configuration object. + */ configure(config?: any): void; /** - * Retreive a list of sequences from the database. - * - * @param {Boolean} refresh Whether to refresh the list or not. - * @promise {Object[]} An array of class objects. - */ + * Retreive a list of sequences from the database. + * + * @param {Boolean} refresh Whether to refresh the list or not. + * @promise {Object[]} An array of class objects. + */ list(refresh: boolean): Promise; /** - * Create a new sequence. - * - * @param {String} name The name of the sequence to create. - * @param {String} type The type of sequence. - * @param {Integer} start The start number. - * @param {Integer} incerement The increment number. - * @param {Integer} cache The cache number - * @promise {Object} The created sequence object - */ + * Create a new sequence. + * + * @param {string} name The name of the sequence to create. + * @param {string} type The type of sequence. + * @param {Integer} start The start number. + * @param {Integer} incerement The increment number. + * @param {Integer} cache The cache number + * @promise {Object} The created sequence object + */ create(name: string, type: "ORDERED" | "CACHED", start?: number, incerement?: number, cache?: number): Promise; /** - * update a sequence. - * - * @param {String} name The name of the sequence to create. - * @param {Integer} incerement The increment number. - * @param {Integer} cache The cache number - * @param {Integer} start The start number. - * @promise {Object} The created sequence object - */ + * update a sequence. + * + * @param {string} name The name of the sequence to create. + * @param {Integer} incerement The increment number. + * @param {Integer} cache The cache number + * @param {Integer} start The start number. + * @promise {Object} The created sequence object + */ update(name: string, start?: number, incerement?: number, cache?: number): Promise; /** - * Reload the sequence instance. - * - * @promise {Sequence} The class instance. - */ + * Reload the sequence instance. + * + * @promise {Sequence} The class instance. + */ reload(): Promise; /** - * Delete a sequence. - * - * @param {String} name The name of the sequence to delete. - * @param {Object} config The config. - * @promise {Db} The database instance. - */ + * Delete a sequence. + * + * @param {string} name The name of the sequence to delete. + * @param {Object} config The config. + * @promise {Db} The database instance. + */ drop(name: string, config?: { }): Promise; /** - * Get a sequence by name. - * - * @param {Integer|String} name The name of the sequence. - * @param {Boolean} refresh Whether to refresh the data, defaults to false. - * @promise {Object} The sequence object if it exists. - */ + * Get a sequence by name. + * + * @param {Integer|string} name The name of the sequence. + * @param {Boolean} refresh Whether to refresh the data, defaults to false. + * @promise {Object} The sequence object if it exists. + */ get(name: string, refresh?: boolean): Promise; /** * Cache the given class data for fast lookup later. @@ -531,116 +512,111 @@ declare module "orientjs" { * @return {Db} The db instance. */ cacheData(sequences: Sequence[]): Db; - } interface RecordMeta { "@rid": RID; "@version": Version; - } type ODocument = Record; type BinaryRecord = Record & Buffer; - - - interface Record extends Object { + class Record extends Object { '@rid'?: RID; '@type'?: 'd' | 'b'; - '@class'?: string, + '@class'?: string; '@version'?: Version; rid?: RID; /** - * Insert the given record into the database. - * - * @param {Object} record The record to insert. - * @param {Object} options The command options. - * @promise {Object} The inserted record. - */ + * Insert the given record into the database. + * + * @param {Object} record The record to insert. + * @param {Object} options The command options. + * @promise {Object} The inserted record. + */ create(record: ODocument | Record | BinaryRecord, options?: any): Promise; /** - * Insert the given record into the database. - * - * @param {Object} record The record to insert. - * @param {Object} options The command options. - * @promise {Object} The inserted record. - */ + * Insert the given record into the database. + * + * @param {Object} record The record to insert. + * @param {Object} options The command options. + * @promise {Object} The inserted record. + */ create(records: ODocument[] | Record[] | BinaryRecord[], options?: any): Promise; /** - * Read the given record. - * - * @param {Object} record The record to load. - * @param {Object} options The query options. - * @promise {Object} The loaded record. - */ + * Read the given record. + * + * @param {Object} record The record to load. + * @param {Object} options The query options. + * @promise {Object} The loaded record. + */ get(record: Record | RID, options?: any): Promise; /** - * Read the given record. - * - * @param {Object} records The record to load. - * @param {Object} options The query options. - * @promise {Object[]} The loaded record. - */ + * Read the given record. + * + * @param {Object} records The record to load. + * @param {Object} options The query options. + * @promise {Object[]} The loaded record. + */ get(records: Record[] | RID[], options?: any): Promise; /** - * Resolve all references within the given collection of records. - * - * @param {Object[]} records The records to resolve. - * @return {Object} The records with references replaced. - */ + * Resolve all references within the given collection of records. + * + * @param {Object[]} records The records to resolve. + * @return {Object} The records with references replaced. + */ resolveReferences(records: Record[]): Record[]; /** - * Read the metadata for the given record. - * - * @param {Object} record The record to load. - * @param {Object} options The query options. - * @promise {Object} The record object with loaded meta data. - */ + * Read the metadata for the given record. + * + * @param {Object} record The record to load. + * @param {Object} options The query options. + * @promise {Object} The record object with loaded meta data. + */ meta(record: Record | RID | string, options?: any): Promise; /** - * Read the metadata for the given record. - * - * @param {Object} record The record to load. - * @param {Object} options The query options. - * @promise {Object} The record object with loaded meta data. - */ + * Read the metadata for the given record. + * + * @param {Object} record The record to load. + * @param {Object} options The query options. + * @promise {Object} The record object with loaded meta data. + */ meta(records: Record[] | RID[], options?: any): Promise; - update(): Promise; /** - * Update the given record. - * - * @param {Object} record The record to update. - * @param {Object} options The query options. - * @promise {Object} The updated record. - */ - update(record: Record | RID, options?: any): Promise; + * Update the given record. + * + * @param {Object} record The record to update. + * @param {Object} options The query options. + * @promise {Object} The updated record. + */ + update(record?: Record | RID, options?: any): Promise; delete(): Promise & Promise; /** - * Delete the given record. - * - * @param {String|RID|Object} record The record or record id to delete. - * @param {Object} options The query options. - * @promise {Object} The deleted record object. - */ + * Delete the given record. + * + * @param {string|RID|Object} record The record or record id to delete. + * @param {Object} options The query options. + * @promise {Object} The deleted record object. + */ delete(record: Record | RID, options?: any): Promise; } interface IndexConfig { - name: string, - class?: string, - properties?: string[], - type: "UNIQUE" | "NOTUNIQUE" | "FULLTEXT" | "DICTIONARY" | "UNIQUE_HASH_INDEX" | "NOTUNIQUE_HASH_INDEX" | "FULLTEXT_HASH_INDEX" | "DICTIONARY_HASH_INDEX" | "SPATIAL", - keyType?: string, - metadata?: any, - engine?: "LUCENE" | "COLA" | string + name: string; + class?: string; + properties?: string[]; + type: "UNIQUE" | "NOTUNIQUE" | "FULLTEXT" | "DICTIONARY" | "UNIQUE_HASH_INDEX" | "NOTUNIQUE_HASH_INDEX" | "FULLTEXT_HASH_INDEX" | "DICTIONARY_HASH_INDEX" | "SPATIAL"; + keyType?: string; + metadata?: any; + engine?: "LUCENE" | "COLA" | string; } interface IndexEntry { - key: string, - value: String | RID + key: string; + value: string | RID; } interface Index { cached: boolean; @@ -650,16 +626,12 @@ declare module "orientjs" { clusters: Cluster[]; type: string; configure(config: any): void; - add(idx: IndexEntry): Promise; - add(idx: IndexEntry[]): Promise; - get(key: string): Promise; - set(key: string, value: string): Promise; - set(key: string, value: RID): Promise; + add(idx: IndexEntry | IndexEntry[]): Promise; + set(key: string, value: string | RID): Promise; delete(name: string): Promise; select(): Statement; list(refresh?: boolean): Promise; - create(config: IndexConfig): Promise; - create(configs: IndexConfig[]): Promise; + create(config: IndexConfig | IndexConfig[]): Promise; drop(name: string): Promise; get(name: string, refresh?: boolean): Promise; cacheData(indices: any[]): Promise; @@ -674,8 +646,7 @@ declare module "orientjs" { delete(param?: string | string[]): Statement; into(param?: string): Statement; create(paramtype?: string, paramname?: string): Statement; - from(param?: string): Statement; - from(param?: any): Statement; + from(param?: string | any): Statement; to(param?: any): Statement; set(param?: any): Statement; content(param?: any): Statement; @@ -695,8 +666,7 @@ declare module "orientjs" { offset(value?: number): Statement; limit(value: number): Statement; fetch(param?: any): Statement; - let(name: string, value: string): Statement; - let(name: string, value: Statement): Statement; + let(name: string, value: string | Statement): Statement; lock(param: any): Statement; if(condition: SqlExpression, statements: Statement[]): Statement; @@ -708,20 +678,16 @@ declare module "orientjs" { retry(retryLimit?: number): Statement; wait(waitLimit: number): Statement; return(value: SqlExpression): Statement; - lucene(property: string, luceneQuery: string): Statement; - lucene(property: any, luceneQuery: string): Statement; - near(latitudeProperty: string, longitudeProperty: string, longitude: number, latitude: number, maxDistanceInKms: number): Statement; - near(prop: any, maxDistanceInKms: number, longitude: number, latitude: number): Statement; - within(latitudeProperty: string, longitudeProperty: string, box: Array): Statement; + lucene(property: string | any, luceneQuery: string): Statement; + near(latitudeProperty: string | any, longitudeProperty: string | number, longitude: number, latitude?: number, maxDistanceInKms?: number): Statement; + within(latitudeProperty: string, longitudeProperty: string, box: number[]): Statement; addParams(key: string, value: any): Statement; addParams(value: any): Statement; token(value: any): Statement; buildStatement(): string; - } interface Query { - transform(transformer: (item: Record) => T): Query; column(name: string): Query; defaults(defaults: any): Query; @@ -729,10 +695,6 @@ declare module "orientjs" { all(params?: any): Promise; scalar(params?: any): Promise; exec(params?: any): Promise; - one(params?: any): Promise; - all(params?: any): Promise; - scalar(params?: any): Promise; - exec(params?: any): Promise; } interface Transaction { @@ -743,11 +705,9 @@ declare module "orientjs" { create(record: Record): Transaction; update(record: Record): Transaction; delete(record: Record): Transaction; - } interface DbConnectionConfig { - useToken?: boolean; name?: string; username?: string; @@ -758,7 +718,7 @@ declare module "orientjs" { type?: string; storage?: string; token?: any; - transformers?: ((item: Record) => any)[]; + transformers?: Array<((item: Record) => any)>; } interface RawExpression { @@ -766,16 +726,14 @@ declare module "orientjs" { value: string; as(alias: string): RawExpression; } - - - interface AbsSqlFunction { - new(field: number | string): AbsSqlFunction; + class AbsSqlFunction { + constructor(field: number | string); } - interface AvgSqlFunction { - new(field: string): AvgSqlFunction; + class AvgSqlFunction { + constructor(field: string); } - interface SequenceSqlFunction { - new(name: string): SequenceSqlFunction; + class SequenceSqlFunction { + constructor(name: string); next(): number; current(): number; reset(): number; @@ -795,10 +753,10 @@ declare module "orientjs" { limit?: number; token?: any; class?: string; - language?: "SQL" | "Javascript" + language?: "SQL" | "Javascript"; } - interface Db extends events.EventEmitter { + class Db extends events.EventEmitter { sessionId: number; forcePrepare: boolean; name: string; @@ -825,94 +783,94 @@ declare module "orientjs" { */ configure(config: DbConfig): Db; /** - * Initialize the database instance. - */ + * Initialize the database instance. + */ init(): void; /** - * Open the database. - * - * @promise {Db} The open db instance. - */ + * Open the database. + * + * @promise {Db} The open db instance. + */ open(): Promise; /** - * Close the database. - * - * @promise {Db} The now closed db instance. - */ + * Close the database. + * + * @promise {Db} The now closed db instance. + */ close(): Promise; /** - * Send the given operation to the server, ensuring the - * database is open first. - * - * @param {Integer} operation The operation to send. - * @param {Object} data The data for the operation. - * @promise {Mixed} The result of the operation. - */ + * Send the given operation to the server, ensuring the + * database is open first. + * + * @param {Integer} operation The operation to send. + * @param {Object} data The data for the operation. + * @promise {Mixed} The result of the operation. + */ send(operation: number, data: any): Promise; /** - * Reload the configuration for the database. - * - * @promise {Db} The database with reloaded configuration. - */ + * Reload the configuration for the database. + * + * @promise {Db} The database with reloaded configuration. + */ reload(): Promise; /** - * Begin a new transaction. - * - * @return {Transaction} The transaction instance. - */ + * Begin a new transaction. + * + * @return {Transaction} The transaction instance. + */ begin(): Transaction; /** - * Execute an SQL query against the database and retreive the raw, parsed response. - * - * @param {String} query The query or command to execute. - * @param {Object} options The options for the query / command. - * @promise {Mixed} The results of the query / command. - */ + * Execute an SQL query against the database and retreive the raw, parsed response. + * + * @param {string} query The query or command to execute. + * @param {Object} options The options for the query / command. + * @promise {Mixed} The results of the query / command. + */ exec(query: string, options?: QueryOptions): Promise; /** * Execute an SQL query against the database and retreive the results * - * @param {String} query The query or command to execute. + * @param {string} query The query or command to execute. * @param {Object} options The options for the query / command. * @promise {Mixed} The results of the query / command. */ query(command: string, options?: QueryOptions): Promise; /** - * Execute a live query against the database - * - * @param {String} query The query or command to execute. - * @param {Object} options The options for the query / command. - * @promise {Mixed} The token of the live query. - */ + * Execute a live query against the database + * + * @param {string} query The query or command to execute. + * @param {Object} options The options for the query / command. + * @promise {Mixed} The token of the live query. + */ liveQuery(command: string, options?: QueryOptions): Promise; /** - * Normalize a result, where possible. - * @param {Object} result The result to normalize. - * @return {Object} The normalized result. - */ + * Normalize a result, where possible. + * @param {Object} result The result to normalize. + * @return {Object} The normalized result. + */ normalizeResult(result: any): any; /** - * Normalize the content for a result. - * @param {Mixed} content The content to normalize. - * @return {Mixed} The normalized content. - */ + * Normalize the content for a result. + * @param {Mixed} content The content to normalize. + * @return {Mixed} The normalized content. + */ normalizeResultContent(content: any): any; /** - * Register a transformer function for documents of the given class. - * This function will be invoked for each document of the specified class - * in all future result sets. - * - * @param {String} className The name of the document class. - * @param {Function} transformer The transformer function. - * @return {Db} The database instance. - */ + * Register a transformer function for documents of the given class. + * This function will be invoked for each document of the specified class + * in all future result sets. + * + * @param {string} className The name of the document class. + * @param {Function} transformer The transformer function. + * @return {Db} The database instance. + */ registerTransformer(className: string, transformer: (item: Record) => T): Db; /** - * Transform a document according to its `@class` property, using the registered transformers. - * @param {Object} document The document to transform. - * @return {Mixed} The transformed document. - */ + * Transform a document according to its `@class` property, using the registered transformers. + * @param {Object} document The document to transform. + * @return {Mixed} The transformed document. + */ transformDocument(document: ODocument): any; /** @@ -922,10 +880,10 @@ declare module "orientjs" { */ createQuery(): Statement; /** - * Create a raw expression. - * - * @return {RawExpression} The raw expression instance. - */ + * Create a raw expression. + * + * @return {RawExpression} The raw expression instance. + */ rawExpression(param: string): RawExpression; /** Create a sql Function. @@ -935,50 +893,47 @@ declare module "orientjs" { sqlFunction(options?: any): SqlFunction; /** - * Create a create query. - * - * @return {Query} The query instance. - */ + * Create a create query. + * + * @return {Query} The query instance. + */ create(params?: any): Statement; create(paramtype: string, paramname: string): Statement; /** - * Create a select query. - * - * @return {Query} The query instance. - */ + * Create a select query. + * + * @return {Query} The query instance. + */ select(params?: any): Statement; /** - * Create a traverse query. - * - * @return {Query} The query instance. - */ + * Create a traverse query. + * + * @return {Query} The query instance. + */ traverse(params?: any): Statement; /** - * Create an insert query. - * - * @return {Query} The query instance. - */ + * Create an insert query. + * + * @return {Query} The query instance. + */ insert(params?: any): Statement; /** - * Create an update query. - * - * @return {Query} The query instance. - */ + * Create an update query. + * + * @return {Query} The query instance. + */ update(params?: any): Statement; /** - * Create a delete query. - * - * @return {Query} The query instance. - */ + * Create a delete query. + * + * @return {Query} The query instance. + */ delete(params?: any): Statement; - insert(param: string | string[]): Statement; - update(param: string | string[]): Statement; - delete(param: string | string[]): Statement; /** - * Create a transactional query. - * - * @return {Query} The query instance. - */ + * Create a transactional query. + * + * @return {Query} The query instance. + */ let(params?: any): Statement; let(name: string, value: string | Statement): Statement; /** Create a transactional query with if. @@ -987,42 +942,40 @@ declare module "orientjs" { */ if(condition: SqlExpression, statements: Statement[]): Statement; /** Create a transactional query with if. - * - * @return {Query} The query instance. - */ + * + * @return {Query} The query instance. + */ if(condition: SqlExpression, ...statements: Statement[]): Statement; /** - * Escape the given input. - * - * @param {String} input The input to escape. - * @return {String} The escaped input. - */ + * Escape the given input. + * + * @param {string} input The input to escape. + * @return {string} The escaped input. + */ escape(input: string): string; /** - * Create a context for a user, using their authentication token. - * The context includes the query builder methods, which will be executed - * on behalf of the user. - * - * @param {Buffer|String} token The authentication token. - * @return {Object} The object containing the query builder methods. - */ + * Create a context for a user, using their authentication token. + * The context includes the query builder methods, which will be executed + * on behalf of the user. + * + * @param {Buffer|string} token The authentication token. + * @return {Object} The object containing the query builder methods. + */ createUserContext(token: any): any; /** * Create a orient function from a plain Javascript function * - * @param {String} name The name of the function + * @param {string} name The name of the function * @param {Object} fn Plain Javascript function to stringify * @param {Object} options Not currently used but will be used for 'IDEMPOTENT' arg * @promise {Mixed} The results of the query / command. */ - createFn(name: string, fn: Function, options?: any): Promise; - createFn(fn: Function, options?: any): Promise; - + createFn(name: string, fn: (...args: any[]) => any, options?: any): Promise; + createFn(fn: (...args: any[]) => any, options?: any): Promise; } interface ServerConfiguration { - get(name: string): string; set(key: string, value: string): string; list(): any; @@ -1032,10 +985,10 @@ declare module "orientjs" { * # Server * Represents a connection to an orientdb server. * - * @param {String|Object} options The server URL, or configuration object + * @param {string|Object} options The server URL, or configuration object */ - interface Server { - new(options?: ServerConfig): Server; + class Server { + constructor(options?: ServerConfig); config: ServerConfiguration; logger: Logger; @@ -1044,11 +997,11 @@ declare module "orientjs" { */ init(): void; /** - * Configure the server instance. - * - * @param {Object} config The configuration for the server. - * @return {Server} The configured server object. - */ + * Configure the server instance. + * + * @param {Object} config The configuration for the server. + * @return {Server} The configured server object. + */ configure(config: ServerConfig): Server; /** * Configure the transport for the server. @@ -1073,106 +1026,83 @@ declare module "orientjs" { */ send(operation: number, options: any): any; /** - * Close the connection to the server. - * - * @return {Server} the disconnected server instance - */ + * Close the connection to the server. + * + * @return {Server} the disconnected server instance + */ close(): Server; /** - * Use the database with the given name / config. - * - * @param {String|Object} config The database name, or configuration object. - * @return {Db} The database instance. - */ - use(name?: string): Db; + * Use the database with the given name / config. + * + * @param {string|Object} config The database name, or configuration object. + * @return {Db} The database instance. + */ + use(name?: string | DbConfig): Db; /** - * Use the database with the given name / config. - * - * @param {String|Object} config The database name, or configuration object. - * @return {Db} The database instance. - */ - use(config?: DbConfig): Db; + * Create a database with the given name / config. + * + * @param {string|Object} config The database name or configuration object. + * @promise {Db} The database instance + */ + create(name: string | DbConfig): Promise; /** - * Create a database with the given name / config. - * - * @param {String|Object} config The database name or configuration object. - * @promise {Db} The database instance - */ - create(name: string): Promise; + * Destroy a database with the given name / config. + * + * @param {string|Object} config The database name or configuration object. + * @promise {Mixed} The server response. + */ + drop(name: string | DbConfig): Promise; /** -* Create a database with the given name / config. -* -* @param {String|Object} config The database name or configuration object. -* @promise {Db} The database instance -*/ - create(config: DbConfig): Promise; - /** - * Destroy a database with the given name / config. - * - * @param {String|Object} config The database name or configuration object. - * @promise {Mixed} The server response. - */ - drop(name: string): Promise; - /** - * Destroy a database with the given name / config. - * - * @param {String|Object} config The database name or configuration object. - * @promise {Mixed} The server response. - */ - drop(config: DbConfig): Promise; - /** - * List all the databases on the server. - * - * @return {Db[]} An array of databases. - */ + * List all the databases on the server. + * + * @return {Db[]} An array of databases. + */ list(): Promise; /** - * Determine whether a database exists with the given name. - * - * @param {String} name The database name. - * @param {String} storageType The storage type, defaults to `plocal`. - * @promise {Boolean} true if the database exists. - */ + * Determine whether a database exists with the given name. + * + * @param {string} name The database name. + * @param {string} storageType The storage type, defaults to `plocal`. + * @promise {Boolean} true if the database exists. + */ exists(name: string, storageType?: string): Promise; /** - * Freeze the database with the given name. - * - * @param {String} name The database name. - * @param {String} storageType The storage type, defaults to `plocal`. - * @return {Object} The response from the server. - */ + * Freeze the database with the given name. + * + * @param {string} name The database name. + * @param {string} storageType The storage type, defaults to `plocal`. + * @return {Object} The response from the server. + */ freeze(name: string, storageType?: string): any; /** - * Release the database with the given name. - * - * @param {String} name The database name. - * @param {String} storageType The storage type, defaults to `plocal`. - * @return {Object} The response from the server. - */ + * Release the database with the given name. + * + * @param {string} name The database name. + * @param {string} storageType The storage type, defaults to `plocal`. + * @return {Object} The response from the server. + */ release(name: string, storageType?: string): any; shutdown(): Promise; } - interface ODatabase extends Db { - new(config?: { + class ODatabase extends Db { + constructor(config?: { host: string, port?: number, username?: string, password?: string, name: string - }): ODatabase; - + }); } interface ServerConfig { - useToken?: boolean; host: string; port?: number; username?: string; password?: string; - servers?: ServerConfig[] + servers?: ServerConfig[]; } interface DbConfig { @@ -1182,8 +1112,9 @@ declare module "orientjs" { username?: string; password?: string; } - - interface OrientJs extends Server { } + interface OrientJs extends Server { + name: string; + } } - export = ojs; -} \ No newline at end of file +} +export = orientjs.ojs; diff --git a/types/orientjs/orientjs-tests.ts b/types/orientjs/orientjs-tests.ts index 464d416122..06a16480bb 100644 --- a/types/orientjs/orientjs-tests.ts +++ b/types/orientjs/orientjs-tests.ts @@ -11,4 +11,3 @@ let db = dbserver.use({ username: 'root', password: 'root' }); - From 57efa884551cf33fcdbc45134c3f95c810e20efa Mon Sep 17 00:00:00 2001 From: Saeed Tabrizi Date: Wed, 19 Jul 2017 21:09:43 +0430 Subject: [PATCH 0147/1139] some enhancment in namespace and default function declare . --- types/orientjs/index.d.ts | 2149 ++++++++++++++++++------------------- 1 file changed, 1074 insertions(+), 1075 deletions(-) diff --git a/types/orientjs/index.d.ts b/types/orientjs/index.d.ts index 3eef7ace34..9be45a4fea 100644 --- a/types/orientjs/index.d.ts +++ b/types/orientjs/index.d.ts @@ -35,1086 +35,1085 @@ import Promise = require('bluebird'); * @version 3.0.0 * */ + +/** + * Make a orientdb server client in binary protocol . + * @param {orientjs.ServerConfig} config The configuration for server connection. + */ +declare function orientjs(config: orientjs.ServerConfig): orientjs.Server; declare namespace orientjs { - function ojs(config: ojs.ServerConfig): ojs.OrientJs; + type Version = number | string; + type PropertyType = "Boolean" | "Integer" | "Short" | "Long" | + "Float" | "Double" | "DateTime" | "string" | "Binary" | + "Embedded" | "EmbeddedList" | "EmbeddedSet" | "EmbeddedMap" | + "Link" | "LinkList" | "LinkSet" | "LinkMap" | "Byte" | + "Transient" | "Date" | "Custom" | "Decimal" | "LinkBag"; + enum DataTypes { + Boolean = 0, + Integer = 1, + Short = 2, + Long = 3, + Float = 4, + Double = 5, + Datetime = 6, + string = 7, + Binary = 8, + Embedded = 9, + EmbeddedList = 10, + EmbeddedSet = 11, + EmbeddedMap = 12, + Link = 13, + LinkList = 14, + LinkSet = 15, + LinkMap = 16, + Byte = 17, + Transient = 18, + Date = 19, + Custom = 20, + Decimal = 21, + LinkBag = 22 + } - namespace ojs { - type Version = number | string; - type PropertyType = "Boolean" | "Integer" | "Short" | "Long" | - "Float" | "Double" | "DateTime" | "string" | "Binary" | - "Embedded" | "EmbeddedList" | "EmbeddedSet" | "EmbeddedMap" | - "Link" | "LinkList" | "LinkSet" | "LinkMap" | "Byte" | - "Transient" | "Date" | "Custom" | "Decimal" | "LinkBag"; - enum DataTypes { - Boolean = 0, - Integer = 1, - Short = 2, - Long = 3, - Float = 4, - Double = 5, - Datetime = 6, - string = 7, - Binary = 8, - Embedded = 9, - EmbeddedList = 10, - EmbeddedSet = 11, - EmbeddedMap = 12, - Link = 13, - LinkList = 14, - LinkSet = 15, - LinkMap = 16, - Byte = 17, - Transient = 18, - Date = 19, - Custom = 20, - Decimal = 21, - LinkBag = 22 - } - - namespace errors { - class BaseError { - name: string; - init(name: string): void; - } - class OperationError extends BaseError { - message: string; - date: any; - } - class RequestError extends OperationError { - } - } - - namespace Migration { - interface MigrationManagerConfig { - name?: string; - db?: Db; - dir?: string; - className?: string; - } - class Manager extends MigrationManager { - constructor(config: MigrationManagerConfig); - } - class Migration { - name: string; - server: Server; - db: Db; - configure(config?: any): void; - up(): Promise; - down(): Promise; - } - - class MigrationManager { - /** - * # Migration Manager - * - * @param {Object} config The configuration for the migration manager. - */ - constructor(config?: MigrationManagerConfig); - - name: string; - server: Server; - db: Db; - dir: string; - className: string; - - /** - * Create a new migration. - * - * @param {string|Object} config The name or configuration for the new migration. - * @promise {string} The full path to the created migration. - */ - create(param: string): Promise; - /** - * Generate the content for a migration. - * @param {Object} config The configuration object. - * @return {string} The generated JavaScript source code. - */ - generateMigration(config: any): string; - /** - * List the migrations that have not yet been applied. - * - * @promise {string[]} An array of migration names - */ - list(): Promise; - /** - * List all the available migrations. - * - * @promise {string[]} The names of the available migrations. - */ - listAvailable(): Promise; - /** - * Ensure the migration class exists. - * - * @promise {MigrationManager} The manager instance with intact structure. - */ - ensureStructure: Promise; - /** - * Retrieve a list of applied migrations. - * - * @promise {Object[]} The applied migrations. - */ - listApplied(): Promise; - /** - * Perform the migration. - * - * @param {Integer} limit The maximum number of migrations to apply, if any. - * @promise {Mixed} The result of the migration. - */ - up(limit?: number): Promise; - /** - * Revert the migration. - * - * @param {Integer} limit The maximum number of migrations to revert, if any. - * @promise {Mixed} The result of the migration. - */ - down(limit?: number): Promise; - /** - * Load the migration with the given name. - * - * @param {string} name The name of the migation. - * @return {Migration} The loaded migration instance. - */ - loadMigration(name: string): Migration; - /** - * Apply the migration with the given name. - * - * @param {string} name The name of the migation. - * @promise {Mixed} The result of the migration. - */ - applyMigration(name: string): Promise; - /** - * Revert the migration with the given name. - * - * @param {string} name The name of the migation. - * @promise {Mixed} The result of the migration. - */ - revertMigration(name: string): Promise; - } - } - - interface Logger { - error(...args: any[]): void; - log(...args: any[]): void; - debug(...args: any[]): void; - } - - class RID extends String { - cluster?: number; - position?: number; - - valueOf(): string; - isValid?(input?: string | RID | any): boolean; - equals?(rid: string | RID): boolean; - parse?(input: string): boolean; - parse?(input: string): RID; - parse?(input: string): RID[]; - toRid?(cluster: number, position: number): any; - } - - interface CustomField { - /** - * Get the value of the given custom field. - * - * @param {string} key The name of the field to get. - * @return {Mixed} The field value, or undefined if it doesn't exist. - */ - get(key: string): CustomField; - /** - * Set a custom field. - * - * @param {string|Object} key The key to set, or map of keys to values. - * @param {string} value The value to set, if `key` is not an object. - * @promise {Object|null} The new set of custom fields, or null if none are present. - */ - set(key: string, value: any): CustomField; - /** - * Unset the custom field with the given name, - * - * @param {string} key The name of the custom field to remove. - * @promise {Object|null} The new set of custom fields, or null if none are present. - */ - unset(key: string): CustomField; - } - - interface PropertyCreateConfig { + namespace errors { + class BaseError { name: string; - type: PropertyType; - default?: any; - ifnotexist?: boolean; - unsafe?: boolean; - mandatory?: boolean; - readonly?: boolean; - notNull?: boolean; - collate?: string; - linkedClass?: string; - linkedType?: string; - regexp?: RegExp | string; - min?: number; - max?: number; - custom?: { - fields?: CustomField[] - }; + init(name: string): void; } - - interface PropertyUpdateConfig { - name: string; - type: PropertyType; - default?: any; - mandatory?: boolean; - readonly?: boolean; - notNull?: boolean; - collate?: string; - linkedClass?: string; - linkedType?: string; - regexp?: RegExp | string; - min?: number; - max?: number; - custom?: { - fields?: CustomField[] - }; + class OperationError extends BaseError { + message: string; + date: any; } - - class Property { - class?: Class; - name?: string; - originalName?: string; - type?: PropertyType; - mandatory?: boolean; - readonly?: boolean; - notNull?: boolean; - collate?: string; - linkedClass?: string; - linkedType?: PropertyType; - regexp?: RegExp | string; - min?: number; - max?: number; - custom?: { - fields?: CustomField[] - }; - - configure(config?: any): void; - reload(): Promise; - list(): Promise; - /** - * Create a new property. - * - * @param {string|Object} config The property name or configuration. - * @param {Boolean} reload Whether to reload the property, default to true. - * @promise {Object} The created property. - */ - create(config?: PropertyCreateConfig | string, reload?: boolean): Promise; - create(config: PropertyCreateConfig[], reload?: boolean): Promise; - /** - * Get the property with the given name. - * - * @param {string} name The property to get. - * @promise {Object|null} The retrieved property. - */ - get(name: string): Promise; - /** - * Update the given property. - * - * @param {Object} property The property settings. - * @param {Boolean} reload Whether to reload the property, default to true. - * @promise {Object} The updated property. - */ - update(config: PropertyUpdateConfig, reload?: boolean): Promise; - drop(name: string, config?: { - ifexist?: boolean, - force?: boolean - }): Promise; - alter(name: string, setting?: any): Promise; - rename(oldName: string, newName?: string): Promise; - } - - /** - * The class constructor. - * @param {Object} config The configuration for the class - */ - class Class { - db?: Db; - name?: string; - shortName?: string; - defaultClusterId?: any; - superClass?: string; - originalName?: string; - clusterIds?: number[]; - /** - * Configure the class instance. - * @param {Object} config The configuration object. - */ - configure(config?: any): void; - /** - * Retreive a list of classes from the database. - * - * @param {Boolean} refresh Whether to refresh the list or not. - * @promise {Object[]} An array of class objects. - */ - list(limit: number | boolean | any, offset?: number): Promise; - /** - * Find a list of records in the class. - * - * @param {Object} attributes The attributes to search with. - * @param {Integer} limit The maximum number of records to return - * @param {Integer} offset The offset to start returning records from. - * @promise {Object[]} An array of records in the class. - */ - find(attributes: any, limit?: number, offset?: number): Promise; - /** - * Create a record for this class. - * - * @param {Object} record The record to create. - * @promise {Object} The created record. - */ - create(record: Record): Promise; - /** - * Create a new class. - * - * @param {string} name The name of the class to create. - * @param {string} parentName The name of the parent to extend, if any. - * @param {string|Integer} cluster The cluster name or id. - * @param {Boolean} isAbstract The flag for the abstract class - * @param {Boolean} ifnotexist The flag for the if not exist class - * @promise {Object} The created class object - */ - create(name: string, parentName?: string, cluster?: string, isAbstract?: boolean, ifnotexist?: boolean): Promise; - /** - * Update the given class. - * - * @param {Object} class The class settings. - * @param {Boolean} reload Whether to reload the class, default to true. - * @promise {Object} The updated class. - */ - update(cls: any, reload: boolean): Promise; - /** - * Reload the class instance. - * - * @promise {Class} The class instance. - */ - reload(): Promise; - /** - * Delete a class. - * - * @param {string} name The name of the class to delete. - * @param {Object} config The config. - * @promise {Db} The database instance. - */ - drop(name: string, config?: { - ifexist?: boolean, - force?: boolean - }): Promise; - /** - * Get a class by name. - * - * @param {Integer|string} name The name of the class. - * @param {Boolean} refresh Whether to refresh the data, defaults to false. - * @promise {Object} The class object if it exists. - */ - get(name: string, refresh?: boolean): Promise; - /** - * Cache the given class data for fast lookup later. - * - * @param {Object[]} classes The class objects to cache. - * @return {Db} The db instance. - */ - cacheData(classes: Class[]): Db; - property: Property; - } - - class Cluster { - name?: string; - location?: string; - list(refresh?: boolean): Promise; - create(name: string, location?: string): Promise & Promise; - get(nameOrId: string, refresh?: boolean): Promise & Promise; - getByName(name: string, refresh?: boolean): Promise & Promise; - getById(id: string, refresh?: boolean): Promise & Promise; - drop(name: string): Promise; - count(name: string): Promise; - range(name: string): Promise; - cacheData(clusters: Cluster[] & any[]): Db; - } - - /** - * The sequence constructor. - * @param {Object} config The configuration for the sequence - */ - class Sequence { - db?: Db; - name?: string; - type?: string; - value?: number; - incr?: number; - start?: number; - cache?: number; - /** - * Configure the sequence instance. - * @param {Object} config The configuration object. - */ - configure(config?: any): void; - /** - * Retreive a list of sequences from the database. - * - * @param {Boolean} refresh Whether to refresh the list or not. - * @promise {Object[]} An array of class objects. - */ - - list(refresh: boolean): Promise; - - /** - * Create a new sequence. - * - * @param {string} name The name of the sequence to create. - * @param {string} type The type of sequence. - * @param {Integer} start The start number. - * @param {Integer} incerement The increment number. - * @param {Integer} cache The cache number - * @promise {Object} The created sequence object - */ - create(name: string, type: "ORDERED" | "CACHED", start?: number, incerement?: number, cache?: number): Promise; - /** - * update a sequence. - * - * @param {string} name The name of the sequence to create. - * @param {Integer} incerement The increment number. - * @param {Integer} cache The cache number - * @param {Integer} start The start number. - * @promise {Object} The created sequence object - */ - update(name: string, start?: number, incerement?: number, cache?: number): Promise; - /** - * Reload the sequence instance. - * - * @promise {Sequence} The class instance. - */ - reload(): Promise; - /** - * Delete a sequence. - * - * @param {string} name The name of the sequence to delete. - * @param {Object} config The config. - * @promise {Db} The database instance. - */ - drop(name: string, config?: { - }): Promise; - /** - * Get a sequence by name. - * - * @param {Integer|string} name The name of the sequence. - * @param {Boolean} refresh Whether to refresh the data, defaults to false. - * @promise {Object} The sequence object if it exists. - */ - get(name: string, refresh?: boolean): Promise; - /** - * Cache the given class data for fast lookup later. - * - * @param {Object[]} sequences The sequence objects to cache. - * @return {Db} The db instance. - */ - cacheData(sequences: Sequence[]): Db; - } - - interface RecordMeta { - "@rid": RID; - "@version": Version; - } - - type ODocument = Record; - type BinaryRecord = Record & Buffer; - class Record extends Object { - '@rid'?: RID; - '@type'?: 'd' | 'b'; - '@class'?: string; - '@version'?: Version; - rid?: RID; - /** - * Insert the given record into the database. - * - * @param {Object} record The record to insert. - * @param {Object} options The command options. - * @promise {Object} The inserted record. - */ - create(record: ODocument | Record | BinaryRecord, options?: any): Promise; - /** - * Insert the given record into the database. - * - * @param {Object} record The record to insert. - * @param {Object} options The command options. - * @promise {Object} The inserted record. - */ - create(records: ODocument[] | Record[] | BinaryRecord[], options?: any): Promise; - - /** - * Read the given record. - * - * @param {Object} record The record to load. - * @param {Object} options The query options. - * @promise {Object} The loaded record. - */ - get(record: Record | RID, options?: any): Promise; - /** - * Read the given record. - * - * @param {Object} records The record to load. - * @param {Object} options The query options. - * @promise {Object[]} The loaded record. - */ - get(records: Record[] | RID[], options?: any): Promise; - /** - * Resolve all references within the given collection of records. - * - * @param {Object[]} records The records to resolve. - * @return {Object} The records with references replaced. - */ - resolveReferences(records: Record[]): Record[]; - - /** - * Read the metadata for the given record. - * - * @param {Object} record The record to load. - * @param {Object} options The query options. - * @promise {Object} The record object with loaded meta data. - */ - meta(record: Record | RID | string, options?: any): Promise; - /** - * Read the metadata for the given record. - * - * @param {Object} record The record to load. - * @param {Object} options The query options. - * @promise {Object} The record object with loaded meta data. - */ - meta(records: Record[] | RID[], options?: any): Promise; - - /** - * Update the given record. - * - * @param {Object} record The record to update. - * @param {Object} options The query options. - * @promise {Object} The updated record. - */ - update(record?: Record | RID, options?: any): Promise; - - delete(): Promise & Promise; - /** - * Delete the given record. - * - * @param {string|RID|Object} record The record or record id to delete. - * @param {Object} options The query options. - * @promise {Object} The deleted record object. - */ - delete(record: Record | RID, options?: any): Promise; - } - interface IndexConfig { - name: string; - class?: string; - properties?: string[]; - type: "UNIQUE" | "NOTUNIQUE" | "FULLTEXT" | "DICTIONARY" | "UNIQUE_HASH_INDEX" | "NOTUNIQUE_HASH_INDEX" | "FULLTEXT_HASH_INDEX" | "DICTIONARY_HASH_INDEX" | "SPATIAL"; - keyType?: string; - metadata?: any; - engine?: "LUCENE" | "COLA" | string; - } - - interface IndexEntry { - key: string; - value: string | RID; - } - interface Index { - cached: boolean; - db: Db; - name: string; - algorithm: string; - clusters: Cluster[]; - type: string; - configure(config: any): void; - add(idx: IndexEntry | IndexEntry[]): Promise; - set(key: string, value: string | RID): Promise; - delete(name: string): Promise; - select(): Statement; - list(refresh?: boolean): Promise; - create(config: IndexConfig | IndexConfig[]): Promise; - drop(name: string): Promise; - get(name: string, refresh?: boolean): Promise; - cacheData(indices: any[]): Promise; - } - type SqlExpression = string | RawExpression | SqlFunction; - interface Statement extends Query { - select(param?: string | string[]): Statement; - traverse(param?: string | string[]): Statement; - strategy(param?: string): Statement; - insert(param?: string | string[]): Statement; - update(param?: string | string[]): Statement; - delete(param?: string | string[]): Statement; - into(param?: string): Statement; - create(paramtype?: string, paramname?: string): Statement; - from(param?: string | any): Statement; - to(param?: any): Statement; - set(param?: any): Statement; - content(param?: any): Statement; - increment(property?: string, value?: any): Statement; - add(property: string, value: any): Statement; - remove(property: string, value: any): Statement; - put(property: string, keysValues: any): Statement; - upsert(condition?: any, params?: any, comparisonOperator?: string): Statement; - where(params: any): Statement; - while(param: any): Statement; - containsText(param: any): Statement; - and(param: any): Statement; - or(param: any): Statement; - group(param: any): Statement; - order(param: any): Statement; - skip(value: number): Statement; - offset(value?: number): Statement; - limit(value: number): Statement; - fetch(param?: any): Statement; - let(name: string, value: string | Statement): Statement; - lock(param: any): Statement; - - if(condition: SqlExpression, statements: Statement[]): Statement; - if(condition: SqlExpression, ...statements: Statement[]): Statement; - rollback(param?: any): Statement; - sleep(ms?: number): Statement; - - commit(retryLimit?: number): Statement; - retry(retryLimit?: number): Statement; - wait(waitLimit: number): Statement; - return(value: SqlExpression): Statement; - lucene(property: string | any, luceneQuery: string): Statement; - near(latitudeProperty: string | any, longitudeProperty: string | number, longitude: number, latitude?: number, maxDistanceInKms?: number): Statement; - within(latitudeProperty: string, longitudeProperty: string, box: number[]): Statement; - addParams(key: string, value: any): Statement; - addParams(value: any): Statement; - token(value: any): Statement; - buildStatement(): string; - } - - interface Query { - transform(transformer: (item: Record) => T): Query; - column(name: string): Query; - defaults(defaults: any): Query; - one(params?: any): Promise; - all(params?: any): Promise; - scalar(params?: any): Promise; - exec(params?: any): Promise; - } - - interface Transaction { - db: Db; - id: number; - - commit(): Promise; - create(record: Record): Transaction; - update(record: Record): Transaction; - delete(record: Record): Transaction; - } - - interface DbConnectionConfig { - useToken?: boolean; - name?: string; - username?: string; - password?: string; - sessionId?: number; - forcePrepare?: boolean; - server?: Server; - type?: string; - storage?: string; - token?: any; - transformers?: Array<((item: Record) => any)>; - } - - interface RawExpression { - db: Db; - value: string; - as(alias: string): RawExpression; - } - class AbsSqlFunction { - constructor(field: number | string); - } - class AvgSqlFunction { - constructor(field: string); - } - class SequenceSqlFunction { - constructor(name: string); - next(): number; - current(): number; - reset(): number; - } - - interface SqlFunction { - db: Db; - abs: AbsSqlFunction; - avg: AbsSqlFunction; - sequence: SequenceSqlFunction; - } - - interface QueryOptions { - params?: any; - mode?: "s" | "a" | "l"; - fetchPlan?: any; - limit?: number; - token?: any; - class?: string; - language?: "SQL" | "Javascript"; - } - - class Db extends events.EventEmitter { - sessionId: number; - forcePrepare: boolean; - name: string; - server: Server; - type: "graph" | "document"; - storage: "plocal" | "memory"; - username: string; - password: string; - token: any; - dataSegments: any[]; - transactionId: number; - transformers: any; - transformerFunctions: any; - - class: Class; - cluster: Cluster; - record: Record; - index: Index; - sequence: Sequence; - /** - * Configure the database instance. - * @param {Object} config The configuration for the database. - * @return {Db} The configured database object. - */ - configure(config: DbConfig): Db; - /** - * Initialize the database instance. - */ - init(): void; - /** - * Open the database. - * - * @promise {Db} The open db instance. - */ - open(): Promise; - /** - * Close the database. - * - * @promise {Db} The now closed db instance. - */ - close(): Promise; - /** - * Send the given operation to the server, ensuring the - * database is open first. - * - * @param {Integer} operation The operation to send. - * @param {Object} data The data for the operation. - * @promise {Mixed} The result of the operation. - */ - send(operation: number, data: any): Promise; - /** - * Reload the configuration for the database. - * - * @promise {Db} The database with reloaded configuration. - */ - reload(): Promise; - /** - * Begin a new transaction. - * - * @return {Transaction} The transaction instance. - */ - begin(): Transaction; - /** - * Execute an SQL query against the database and retreive the raw, parsed response. - * - * @param {string} query The query or command to execute. - * @param {Object} options The options for the query / command. - * @promise {Mixed} The results of the query / command. - */ - exec(query: string, options?: QueryOptions): Promise; - - /** - * Execute an SQL query against the database and retreive the results - * - * @param {string} query The query or command to execute. - * @param {Object} options The options for the query / command. - * @promise {Mixed} The results of the query / command. - */ - query(command: string, options?: QueryOptions): Promise; - /** - * Execute a live query against the database - * - * @param {string} query The query or command to execute. - * @param {Object} options The options for the query / command. - * @promise {Mixed} The token of the live query. - */ - liveQuery(command: string, options?: QueryOptions): Promise; - /** - * Normalize a result, where possible. - * @param {Object} result The result to normalize. - * @return {Object} The normalized result. - */ - normalizeResult(result: any): any; - /** - * Normalize the content for a result. - * @param {Mixed} content The content to normalize. - * @return {Mixed} The normalized content. - */ - normalizeResultContent(content: any): any; - /** - * Register a transformer function for documents of the given class. - * This function will be invoked for each document of the specified class - * in all future result sets. - * - * @param {string} className The name of the document class. - * @param {Function} transformer The transformer function. - * @return {Db} The database instance. - */ - registerTransformer(className: string, transformer: (item: Record) => T): Db; - /** - * Transform a document according to its `@class` property, using the registered transformers. - * @param {Object} document The document to transform. - * @return {Mixed} The transformed document. - */ - transformDocument(document: ODocument): any; - - /** - * Create a query instance for this database. - * - * @return {Query} The query instance. - */ - createQuery(): Statement; - /** - * Create a raw expression. - * - * @return {RawExpression} The raw expression instance. - */ - rawExpression(param: string): RawExpression; - - /** Create a sql Function. - * - * @return {SqlFunction} The sql function instance. - */ - sqlFunction(options?: any): SqlFunction; - - /** - * Create a create query. - * - * @return {Query} The query instance. - */ - create(params?: any): Statement; - create(paramtype: string, paramname: string): Statement; - /** - * Create a select query. - * - * @return {Query} The query instance. - */ - select(params?: any): Statement; - /** - * Create a traverse query. - * - * @return {Query} The query instance. - */ - traverse(params?: any): Statement; - /** - * Create an insert query. - * - * @return {Query} The query instance. - */ - insert(params?: any): Statement; - /** - * Create an update query. - * - * @return {Query} The query instance. - */ - update(params?: any): Statement; - /** - * Create a delete query. - * - * @return {Query} The query instance. - */ - delete(params?: any): Statement; - /** - * Create a transactional query. - * - * @return {Query} The query instance. - */ - let(params?: any): Statement; - let(name: string, value: string | Statement): Statement; - /** Create a transactional query with if. - * - * @return {Query} The query instance. - */ - if(condition: SqlExpression, statements: Statement[]): Statement; - /** Create a transactional query with if. - * - * @return {Query} The query instance. - */ - if(condition: SqlExpression, ...statements: Statement[]): Statement; - /** - * Escape the given input. - * - * @param {string} input The input to escape. - * @return {string} The escaped input. - */ - escape(input: string): string; - /** - * Create a context for a user, using their authentication token. - * The context includes the query builder methods, which will be executed - * on behalf of the user. - * - * @param {Buffer|string} token The authentication token. - * @return {Object} The object containing the query builder methods. - */ - createUserContext(token: any): any; - - /** - * Create a orient function from a plain Javascript function - * - * @param {string} name The name of the function - * @param {Object} fn Plain Javascript function to stringify - * @param {Object} options Not currently used but will be used for 'IDEMPOTENT' arg - * @promise {Mixed} The results of the query / command. - */ - createFn(name: string, fn: (...args: any[]) => any, options?: any): Promise; - createFn(fn: (...args: any[]) => any, options?: any): Promise; - } - - interface ServerConfiguration { - get(name: string): string; - set(key: string, value: string): string; - list(): any; - } - - /** - * # Server - * Represents a connection to an orientdb server. - * - * @param {string|Object} options The server URL, or configuration object - */ - class Server { - constructor(options?: ServerConfig); - config: ServerConfiguration; - logger: Logger; - - /** - * Initialize the server instance. - */ - init(): void; - /** - * Configure the server instance. - * - * @param {Object} config The configuration for the server. - * @return {Server} The configured server object. - */ - configure(config: ServerConfig): Server; - /** - * Configure the transport for the server. - * - * @param {Object} config The server config. - * @return {Server} The configured server object. - */ - configureTransport(config: any): Server; - /** - * Configure the logger for the server. - * - * @param {Object} config The logger config - * @return {Server} The server instance with the configured logger. - */ - configureLogger(logger: Logger): Server; - /** - * Send an operation to the server, - * - * @param {Integer} operation The id of the operation to send. - * @param {Object} options The options for the operation. - * @promise {Mixed} The result of the operation. - */ - send(operation: number, options: any): any; - /** - * Close the connection to the server. - * - * @return {Server} the disconnected server instance - */ - close(): Server; - /** - * Use the database with the given name / config. - * - * @param {string|Object} config The database name, or configuration object. - * @return {Db} The database instance. - */ - use(name?: string | DbConfig): Db; - /** - * Create a database with the given name / config. - * - * @param {string|Object} config The database name or configuration object. - * @promise {Db} The database instance - */ - create(name: string | DbConfig): Promise; - /** - * Destroy a database with the given name / config. - * - * @param {string|Object} config The database name or configuration object. - * @promise {Mixed} The server response. - */ - drop(name: string | DbConfig): Promise; - /** - * List all the databases on the server. - * - * @return {Db[]} An array of databases. - */ - list(): Promise; - /** - * Determine whether a database exists with the given name. - * - * @param {string} name The database name. - * @param {string} storageType The storage type, defaults to `plocal`. - * @promise {Boolean} true if the database exists. - */ - exists(name: string, storageType?: string): Promise; - /** - * Freeze the database with the given name. - * - * @param {string} name The database name. - * @param {string} storageType The storage type, defaults to `plocal`. - * @return {Object} The response from the server. - */ - freeze(name: string, storageType?: string): any; - /** - * Release the database with the given name. - * - * @param {string} name The database name. - * @param {string} storageType The storage type, defaults to `plocal`. - * @return {Object} The response from the server. - */ - release(name: string, storageType?: string): any; - - shutdown(): Promise; - } - - class ODatabase extends Db { - constructor(config?: { - host: string, - port?: number, - username?: string, - password?: string, - name: string - }); - } - - interface ServerConfig { - useToken?: boolean; - host: string; - port?: number; - username?: string; - password?: string; - servers?: ServerConfig[]; - } - - interface DbConfig { - name: string; - type?: string; - storage?: string; - username?: string; - password?: string; - } - interface OrientJs extends Server { - name: string; + class RequestError extends OperationError { } } + + namespace Migration { + interface MigrationManagerConfig { + name?: string; + db?: Db; + dir?: string; + className?: string; + } + class Manager extends MigrationManager { + constructor(config: MigrationManagerConfig); + } + class Migration { + name: string; + server: Server; + db: Db; + configure(config?: any): void; + up(): Promise; + down(): Promise; + } + + class MigrationManager { + /** + * # Migration Manager + * + * @param {Object} config The configuration for the migration manager. + */ + constructor(config?: MigrationManagerConfig); + + name: string; + server: Server; + db: Db; + dir: string; + className: string; + + /** + * Create a new migration. + * + * @param {string|Object} config The name or configuration for the new migration. + * @promise {string} The full path to the created migration. + */ + create(param: string): Promise; + /** + * Generate the content for a migration. + * @param {Object} config The configuration object. + * @return {string} The generated JavaScript source code. + */ + generateMigration(config: any): string; + /** + * List the migrations that have not yet been applied. + * + * @promise {string[]} An array of migration names + */ + list(): Promise; + /** + * List all the available migrations. + * + * @promise {string[]} The names of the available migrations. + */ + listAvailable(): Promise; + /** + * Ensure the migration class exists. + * + * @promise {MigrationManager} The manager instance with intact structure. + */ + ensureStructure: Promise; + /** + * Retrieve a list of applied migrations. + * + * @promise {Object[]} The applied migrations. + */ + listApplied(): Promise; + /** + * Perform the migration. + * + * @param {Integer} limit The maximum number of migrations to apply, if any. + * @promise {Mixed} The result of the migration. + */ + up(limit?: number): Promise; + /** + * Revert the migration. + * + * @param {Integer} limit The maximum number of migrations to revert, if any. + * @promise {Mixed} The result of the migration. + */ + down(limit?: number): Promise; + /** + * Load the migration with the given name. + * + * @param {string} name The name of the migation. + * @return {Migration} The loaded migration instance. + */ + loadMigration(name: string): Migration; + /** + * Apply the migration with the given name. + * + * @param {string} name The name of the migation. + * @promise {Mixed} The result of the migration. + */ + applyMigration(name: string): Promise; + /** + * Revert the migration with the given name. + * + * @param {string} name The name of the migation. + * @promise {Mixed} The result of the migration. + */ + revertMigration(name: string): Promise; + } + } + + interface Logger { + error(...args: any[]): void; + log(...args: any[]): void; + debug(...args: any[]): void; + } + + class RID extends String { + cluster?: number; + position?: number; + + valueOf(): string; + isValid?(input?: string | RID | any): boolean; + equals?(rid: string | RID): boolean; + parse?(input: string): boolean; + parse?(input: string): RID; + parse?(input: string): RID[]; + toRid?(cluster: number, position: number): any; + } + + interface CustomField { + /** + * Get the value of the given custom field. + * + * @param {string} key The name of the field to get. + * @return {Mixed} The field value, or undefined if it doesn't exist. + */ + get(key: string): CustomField; + /** + * Set a custom field. + * + * @param {string|Object} key The key to set, or map of keys to values. + * @param {string} value The value to set, if `key` is not an object. + * @promise {Object|null} The new set of custom fields, or null if none are present. + */ + set(key: string, value: any): CustomField; + /** + * Unset the custom field with the given name, + * + * @param {string} key The name of the custom field to remove. + * @promise {Object|null} The new set of custom fields, or null if none are present. + */ + unset(key: string): CustomField; + } + + interface PropertyCreateConfig { + name: string; + type: PropertyType; + default?: any; + ifnotexist?: boolean; + unsafe?: boolean; + mandatory?: boolean; + readonly?: boolean; + notNull?: boolean; + collate?: string; + linkedClass?: string; + linkedType?: string; + regexp?: RegExp | string; + min?: number; + max?: number; + custom?: { + fields?: CustomField[] + }; + } + + interface PropertyUpdateConfig { + name: string; + type: PropertyType; + default?: any; + mandatory?: boolean; + readonly?: boolean; + notNull?: boolean; + collate?: string; + linkedClass?: string; + linkedType?: string; + regexp?: RegExp | string; + min?: number; + max?: number; + custom?: { + fields?: CustomField[] + }; + } + + class Property { + class?: Class; + name?: string; + originalName?: string; + type?: PropertyType; + mandatory?: boolean; + readonly?: boolean; + notNull?: boolean; + collate?: string; + linkedClass?: string; + linkedType?: PropertyType; + regexp?: RegExp | string; + min?: number; + max?: number; + custom?: { + fields?: CustomField[] + }; + + configure(config?: any): void; + reload(): Promise; + list(): Promise; + /** + * Create a new property. + * + * @param {string|Object} config The property name or configuration. + * @param {Boolean} reload Whether to reload the property, default to true. + * @promise {Object} The created property. + */ + create(config?: PropertyCreateConfig | string, reload?: boolean): Promise; + create(config: PropertyCreateConfig[], reload?: boolean): Promise; + /** + * Get the property with the given name. + * + * @param {string} name The property to get. + * @promise {Object|null} The retrieved property. + */ + get(name: string): Promise; + /** + * Update the given property. + * + * @param {Object} property The property settings. + * @param {Boolean} reload Whether to reload the property, default to true. + * @promise {Object} The updated property. + */ + update(config: PropertyUpdateConfig, reload?: boolean): Promise; + drop(name: string, config?: { + ifexist?: boolean, + force?: boolean + }): Promise; + alter(name: string, setting?: any): Promise; + rename(oldName: string, newName?: string): Promise; + } + + /** + * The class constructor. + * @param {Object} config The configuration for the class + */ + class Class { + db?: Db; + name?: string; + shortName?: string; + defaultClusterId?: any; + superClass?: string; + originalName?: string; + clusterIds?: number[]; + /** + * Configure the class instance. + * @param {Object} config The configuration object. + */ + configure(config?: any): void; + /** + * Retreive a list of classes from the database. + * + * @param {Boolean} refresh Whether to refresh the list or not. + * @promise {Object[]} An array of class objects. + */ + list(limit: number | boolean | any, offset?: number): Promise; + /** + * Find a list of records in the class. + * + * @param {Object} attributes The attributes to search with. + * @param {Integer} limit The maximum number of records to return + * @param {Integer} offset The offset to start returning records from. + * @promise {Object[]} An array of records in the class. + */ + find(attributes: any, limit?: number, offset?: number): Promise; + /** + * Create a record for this class. + * + * @param {Object} record The record to create. + * @promise {Object} The created record. + */ + create(record: Record): Promise; + /** + * Create a new class. + * + * @param {string} name The name of the class to create. + * @param {string} parentName The name of the parent to extend, if any. + * @param {string|Integer} cluster The cluster name or id. + * @param {Boolean} isAbstract The flag for the abstract class + * @param {Boolean} ifnotexist The flag for the if not exist class + * @promise {Object} The created class object + */ + create(name: string, parentName?: string, cluster?: string, isAbstract?: boolean, ifnotexist?: boolean): Promise; + /** + * Update the given class. + * + * @param {Object} class The class settings. + * @param {Boolean} reload Whether to reload the class, default to true. + * @promise {Object} The updated class. + */ + update(cls: any, reload: boolean): Promise; + /** + * Reload the class instance. + * + * @promise {Class} The class instance. + */ + reload(): Promise; + /** + * Delete a class. + * + * @param {string} name The name of the class to delete. + * @param {Object} config The config. + * @promise {Db} The database instance. + */ + drop(name: string, config?: { + ifexist?: boolean, + force?: boolean + }): Promise; + /** + * Get a class by name. + * + * @param {Integer|string} name The name of the class. + * @param {Boolean} refresh Whether to refresh the data, defaults to false. + * @promise {Object} The class object if it exists. + */ + get(name: string, refresh?: boolean): Promise; + /** + * Cache the given class data for fast lookup later. + * + * @param {Object[]} classes The class objects to cache. + * @return {Db} The db instance. + */ + cacheData(classes: Class[]): Db; + property: Property; + } + + class Cluster { + name?: string; + location?: string; + list(refresh?: boolean): Promise; + create(name: string, location?: string): Promise & Promise; + get(nameOrId: string, refresh?: boolean): Promise & Promise; + getByName(name: string, refresh?: boolean): Promise & Promise; + getById(id: string, refresh?: boolean): Promise & Promise; + drop(name: string): Promise; + count(name: string): Promise; + range(name: string): Promise; + cacheData(clusters: Cluster[] & any[]): Db; + } + + /** + * The sequence constructor. + * @param {Object} config The configuration for the sequence + */ + class Sequence { + db?: Db; + name?: string; + type?: string; + value?: number; + incr?: number; + start?: number; + cache?: number; + /** + * Configure the sequence instance. + * @param {Object} config The configuration object. + */ + configure(config?: any): void; + /** + * Retreive a list of sequences from the database. + * + * @param {Boolean} refresh Whether to refresh the list or not. + * @promise {Object[]} An array of class objects. + */ + + list(refresh: boolean): Promise; + + /** + * Create a new sequence. + * + * @param {string} name The name of the sequence to create. + * @param {string} type The type of sequence. + * @param {Integer} start The start number. + * @param {Integer} incerement The increment number. + * @param {Integer} cache The cache number + * @promise {Object} The created sequence object + */ + create(name: string, type: "ORDERED" | "CACHED", start?: number, incerement?: number, cache?: number): Promise; + /** + * update a sequence. + * + * @param {string} name The name of the sequence to create. + * @param {Integer} incerement The increment number. + * @param {Integer} cache The cache number + * @param {Integer} start The start number. + * @promise {Object} The created sequence object + */ + update(name: string, start?: number, incerement?: number, cache?: number): Promise; + /** + * Reload the sequence instance. + * + * @promise {Sequence} The class instance. + */ + reload(): Promise; + /** + * Delete a sequence. + * + * @param {string} name The name of the sequence to delete. + * @param {Object} config The config. + * @promise {Db} The database instance. + */ + drop(name: string, config?: { + }): Promise; + /** + * Get a sequence by name. + * + * @param {Integer|string} name The name of the sequence. + * @param {Boolean} refresh Whether to refresh the data, defaults to false. + * @promise {Object} The sequence object if it exists. + */ + get(name: string, refresh?: boolean): Promise; + /** + * Cache the given class data for fast lookup later. + * + * @param {Object[]} sequences The sequence objects to cache. + * @return {Db} The db instance. + */ + cacheData(sequences: Sequence[]): Db; + } + + interface RecordMeta { + "@rid": RID; + "@version": Version; + } + + type ODocument = Record; + type BinaryRecord = Record & Buffer; + class Record extends Object { + '@rid'?: RID; + '@type'?: 'd' | 'b'; + '@class'?: string; + '@version'?: Version; + rid?: RID; + /** + * Insert the given record into the database. + * + * @param {Object} record The record to insert. + * @param {Object} options The command options. + * @promise {Object} The inserted record. + */ + create(record: ODocument | Record | BinaryRecord, options?: any): Promise; + /** + * Insert the given record into the database. + * + * @param {Object} record The record to insert. + * @param {Object} options The command options. + * @promise {Object} The inserted record. + */ + create(records: ODocument[] | Record[] | BinaryRecord[], options?: any): Promise; + + /** + * Read the given record. + * + * @param {Object} record The record to load. + * @param {Object} options The query options. + * @promise {Object} The loaded record. + */ + get(record: Record | RID, options?: any): Promise; + /** + * Read the given record. + * + * @param {Object} records The record to load. + * @param {Object} options The query options. + * @promise {Object[]} The loaded record. + */ + get(records: Record[] | RID[], options?: any): Promise; + /** + * Resolve all references within the given collection of records. + * + * @param {Object[]} records The records to resolve. + * @return {Object} The records with references replaced. + */ + resolveReferences(records: Record[]): Record[]; + + /** + * Read the metadata for the given record. + * + * @param {Object} record The record to load. + * @param {Object} options The query options. + * @promise {Object} The record object with loaded meta data. + */ + meta(record: Record | RID | string, options?: any): Promise; + /** + * Read the metadata for the given record. + * + * @param {Object} record The record to load. + * @param {Object} options The query options. + * @promise {Object} The record object with loaded meta data. + */ + meta(records: Record[] | RID[], options?: any): Promise; + + /** + * Update the given record. + * + * @param {Object} record The record to update. + * @param {Object} options The query options. + * @promise {Object} The updated record. + */ + update(record?: Record | RID, options?: any): Promise; + + delete(): Promise & Promise; + /** + * Delete the given record. + * + * @param {string|RID|Object} record The record or record id to delete. + * @param {Object} options The query options. + * @promise {Object} The deleted record object. + */ + delete(record: Record | RID, options?: any): Promise; + } + interface IndexConfig { + name: string; + class?: string; + properties?: string[]; + type: "UNIQUE" | "NOTUNIQUE" | "FULLTEXT" | "DICTIONARY" | "UNIQUE_HASH_INDEX" | "NOTUNIQUE_HASH_INDEX" | "FULLTEXT_HASH_INDEX" | "DICTIONARY_HASH_INDEX" | "SPATIAL"; + keyType?: string; + metadata?: any; + engine?: "LUCENE" | "COLA" | string; + } + + interface IndexEntry { + key: string; + value: string | RID; + } + interface Index { + cached: boolean; + db: Db; + name: string; + algorithm: string; + clusters: Cluster[]; + type: string; + configure(config: any): void; + add(idx: IndexEntry | IndexEntry[]): Promise; + set(key: string, value: string | RID): Promise; + delete(name: string): Promise; + select(): Statement; + list(refresh?: boolean): Promise; + create(config: IndexConfig | IndexConfig[]): Promise; + drop(name: string): Promise; + get(name: string, refresh?: boolean): Promise; + cacheData(indices: any[]): Promise; + } + type SqlExpression = string | RawExpression | SqlFunction; + interface Statement extends Query { + select(param?: string | string[]): Statement; + traverse(param?: string | string[]): Statement; + strategy(param?: string): Statement; + insert(param?: string | string[]): Statement; + update(param?: string | string[]): Statement; + delete(param?: string | string[]): Statement; + into(param?: string): Statement; + create(paramtype?: string, paramname?: string): Statement; + from(param?: string | any): Statement; + to(param?: any): Statement; + set(param?: any): Statement; + content(param?: any): Statement; + increment(property?: string, value?: any): Statement; + add(property: string, value: any): Statement; + remove(property: string, value: any): Statement; + put(property: string, keysValues: any): Statement; + upsert(condition?: any, params?: any, comparisonOperator?: string): Statement; + where(params: any): Statement; + while(param: any): Statement; + containsText(param: any): Statement; + and(param: any): Statement; + or(param: any): Statement; + group(param: any): Statement; + order(param: any): Statement; + skip(value: number): Statement; + offset(value?: number): Statement; + limit(value: number): Statement; + fetch(param?: any): Statement; + let(name: string, value: string | Statement): Statement; + lock(param: any): Statement; + + if(condition: SqlExpression, statements: Statement[]): Statement; + if(condition: SqlExpression, ...statements: Statement[]): Statement; + rollback(param?: any): Statement; + sleep(ms?: number): Statement; + + commit(retryLimit?: number): Statement; + retry(retryLimit?: number): Statement; + wait(waitLimit: number): Statement; + return(value: SqlExpression): Statement; + lucene(property: string | any, luceneQuery: string): Statement; + near(latitudeProperty: string | any, longitudeProperty: string | number, longitude: number, latitude?: number, maxDistanceInKms?: number): Statement; + within(latitudeProperty: string, longitudeProperty: string, box: number[]): Statement; + addParams(key: string, value: any): Statement; + addParams(value: any): Statement; + token(value: any): Statement; + buildStatement(): string; + } + + interface Query { + transform(transformer: (item: Record) => T): Query; + column(name: string): Query; + defaults(defaults: any): Query; + one(params?: any): Promise; + all(params?: any): Promise; + scalar(params?: any): Promise; + exec(params?: any): Promise; + } + + class Transaction { + db: Db; + id: number; + + commit(): Promise; + create(record: Record): Transaction; + update(record: Record): Transaction; + delete(record: Record): Transaction; + } + + interface DbConnectionConfig { + useToken?: boolean; + name?: string; + username?: string; + password?: string; + sessionId?: number; + forcePrepare?: boolean; + server?: Server; + type?: string; + storage?: string; + token?: any; + transformers?: Array<((item: Record) => any)>; + } + + interface RawExpression { + db: Db; + value: string; + as(alias: string): RawExpression; + } + class AbsSqlFunction { + constructor(field: number | string); + } + class AvgSqlFunction { + constructor(field: string); + } + class SequenceSqlFunction { + constructor(name: string); + next(): number; + current(): number; + reset(): number; + } + + interface SqlFunction { + db: Db; + abs: AbsSqlFunction; + avg: AbsSqlFunction; + sequence: SequenceSqlFunction; + } + + interface QueryOptions { + params?: any; + mode?: "s" | "a" | "l"; + fetchPlan?: any; + limit?: number; + token?: any; + class?: string; + language?: "SQL" | "Javascript"; + } + + class Db extends events.EventEmitter { + sessionId: number; + forcePrepare: boolean; + name: string; + server: Server; + type: "graph" | "document"; + storage: "plocal" | "memory"; + username: string; + password: string; + token: any; + dataSegments: any[]; + transactionId: number; + transformers: any; + transformerFunctions: any; + + class: Class; + cluster: Cluster; + record: Record; + index: Index; + sequence: Sequence; + /** + * Configure the database instance. + * @param {Object} config The configuration for the database. + * @return {Db} The configured database object. + */ + configure(config: DbConfig): Db; + /** + * Initialize the database instance. + */ + init(): void; + /** + * Open the database. + * + * @promise {Db} The open db instance. + */ + open(): Promise; + /** + * Close the database. + * + * @promise {Db} The now closed db instance. + */ + close(): Promise; + /** + * Send the given operation to the server, ensuring the + * database is open first. + * + * @param {Integer} operation The operation to send. + * @param {Object} data The data for the operation. + * @promise {Mixed} The result of the operation. + */ + send(operation: number, data: any): Promise; + /** + * Reload the configuration for the database. + * + * @promise {Db} The database with reloaded configuration. + */ + reload(): Promise; + /** + * Begin a new transaction. + * + * @return {Transaction} The transaction instance. + */ + begin(): Transaction; + /** + * Execute an SQL query against the database and retreive the raw, parsed response. + * + * @param {string} query The query or command to execute. + * @param {Object} options The options for the query / command. + * @promise {Mixed} The results of the query / command. + */ + exec(query: string, options?: QueryOptions): Promise; + + /** + * Execute an SQL query against the database and retreive the results + * + * @param {string} query The query or command to execute. + * @param {Object} options The options for the query / command. + * @promise {Mixed} The results of the query / command. + */ + query(command: string, options?: QueryOptions): Promise; + /** + * Execute a live query against the database + * + * @param {string} query The query or command to execute. + * @param {Object} options The options for the query / command. + * @promise {Mixed} The token of the live query. + */ + liveQuery(command: string, options?: QueryOptions): Promise; + /** + * Normalize a result, where possible. + * @param {Object} result The result to normalize. + * @return {Object} The normalized result. + */ + normalizeResult(result: any): any; + /** + * Normalize the content for a result. + * @param {Mixed} content The content to normalize. + * @return {Mixed} The normalized content. + */ + normalizeResultContent(content: any): any; + /** + * Register a transformer function for documents of the given class. + * This function will be invoked for each document of the specified class + * in all future result sets. + * + * @param {string} className The name of the document class. + * @param {Function} transformer The transformer function. + * @return {Db} The database instance. + */ + registerTransformer(className: string, transformer: (item: Record) => T): Db; + /** + * Transform a document according to its `@class` property, using the registered transformers. + * @param {Object} document The document to transform. + * @return {Mixed} The transformed document. + */ + transformDocument(document: ODocument): any; + + /** + * Create a query instance for this database. + * + * @return {Query} The query instance. + */ + createQuery(): Statement; + /** + * Create a raw expression. + * + * @return {RawExpression} The raw expression instance. + */ + rawExpression(param: string): RawExpression; + + /** Create a sql Function. + * + * @return {SqlFunction} The sql function instance. + */ + sqlFunction(options?: any): SqlFunction; + + /** + * Create a create query. + * + * @return {Query} The query instance. + */ + create(params?: any): Statement; + create(paramtype: string, paramname: string): Statement; + /** + * Create a select query. + * + * @return {Query} The query instance. + */ + select(params?: any): Statement; + /** + * Create a traverse query. + * + * @return {Query} The query instance. + */ + traverse(params?: any): Statement; + /** + * Create an insert query. + * + * @return {Query} The query instance. + */ + insert(params?: any): Statement; + /** + * Create an update query. + * + * @return {Query} The query instance. + */ + update(params?: any): Statement; + /** + * Create a delete query. + * + * @return {Query} The query instance. + */ + delete(params?: any): Statement; + /** + * Create a transactional query. + * + * @return {Query} The query instance. + */ + let(params?: any): Statement; + let(name: string, value: string | Statement): Statement; + /** Create a transactional query with if. + * + * @return {Query} The query instance. + */ + if(condition: SqlExpression, statements: Statement[]): Statement; + /** Create a transactional query with if. + * + * @return {Query} The query instance. + */ + if(condition: SqlExpression, ...statements: Statement[]): Statement; + /** + * Escape the given input. + * + * @param {string} input The input to escape. + * @return {string} The escaped input. + */ + escape(input: string): string; + /** + * Create a context for a user, using their authentication token. + * The context includes the query builder methods, which will be executed + * on behalf of the user. + * + * @param {Buffer|string} token The authentication token. + * @return {Object} The object containing the query builder methods. + */ + createUserContext(token: any): any; + + /** + * Create a orient function from a plain Javascript function + * + * @param {string} name The name of the function + * @param {Object} fn Plain Javascript function to stringify + * @param {Object} options Not currently used but will be used for 'IDEMPOTENT' arg + * @promise {Mixed} The results of the query / command. + */ + createFn(name: string, fn: (...args: any[]) => any, options?: any): Promise; + createFn(fn: (...args: any[]) => any, options?: any): Promise; + } + + interface ServerConfiguration { + get(name: string): string; + set(key: string, value: string): string; + list(): any; + } + + /** + * # Server + * Represents a connection to an orientdb server. + * + * @param {string|Object} options The server URL, or configuration object + */ + class Server { + constructor(options?: ServerConfig); + config: ServerConfiguration; + logger: Logger; + + /** + * Initialize the server instance. + */ + init(): void; + /** + * Configure the server instance. + * + * @param {Object} config The configuration for the server. + * @return {Server} The configured server object. + */ + configure(config: ServerConfig): Server; + /** + * Configure the transport for the server. + * + * @param {Object} config The server config. + * @return {Server} The configured server object. + */ + configureTransport(config: any): Server; + /** + * Configure the logger for the server. + * + * @param {Object} config The logger config + * @return {Server} The server instance with the configured logger. + */ + configureLogger(logger: Logger): Server; + /** + * Send an operation to the server, + * + * @param {Integer} operation The id of the operation to send. + * @param {Object} options The options for the operation. + * @promise {Mixed} The result of the operation. + */ + send(operation: number, options: any): any; + /** + * Close the connection to the server. + * + * @return {Server} the disconnected server instance + */ + close(): Server; + /** + * Use the database with the given name / config. + * + * @param {string | DbConfig} config The database name, or configuration object. + * @return {Db} The database instance. + */ + use(name: string | DbConfig): Db; + /** + * Create a database with the given name / config. + * + * @param {string | DbConfig} config The database name or configuration object. + * @promise {Db} The database instance + */ + create(name: string | DbConfig): Promise; + /** + * Destroy a database with the given name / config. + * + * @param {string | DbConfig} config The database name or configuration object. + * @promise {Mixed} The server response. + */ + drop(name: string | DbConfig): Promise; + /** + * List all the databases on the server. + * + * @return {Db[]} An array of databases. + */ + list(): Promise; + /** + * Determine whether a database exists with the given name. + * + * @param {string} name The database name. + * @param {string} storageType The storage type, defaults to `plocal`. + * @promise {Boolean} true if the database exists. + */ + exists(name: string, storageType?: string): Promise; + /** + * Freeze the database with the given name. + * + * @param {string} name The database name. + * @param {string} storageType The storage type, defaults to `plocal`. + * @return {Object} The response from the server. + */ + freeze(name: string, storageType?: string): any; + /** + * Release the database with the given name. + * + * @param {string} name The database name. + * @param {string} storageType The storage type, defaults to `plocal`. + * @return {Object} The response from the server. + */ + release(name: string, storageType?: string): any; + + shutdown(): Promise; + } + + class ODatabase extends Db { + constructor(config?: { + host: string, + port?: number, + username?: string, + password?: string, + name: string + }); + } + + interface ServerConfig { + useToken?: boolean; + host: string; + port?: number; + username?: string; + password?: string; + servers?: ServerConfig[]; + } + + interface DbConfig { + name: string; + type?: string; + storage?: string; + username?: string; + password?: string; + } } -export = orientjs.ojs; +export = orientjs; From e0faf3a6ec4b775a0f4f0ea24417f9c1aee88046 Mon Sep 17 00:00:00 2001 From: Eric Byers Date: Wed, 19 Jul 2017 11:29:27 -0500 Subject: [PATCH 0148/1139] Adding safe-json-stringify module Exporting the function correctly Fixing pretty much everything Adding safe-json-stringify type --- types/safe-json-stringify/index.d.ts | 13 +++++++++++ .../safe-json-stringify-tests.ts | 5 +++++ types/safe-json-stringify/tsconfig.json | 22 +++++++++++++++++++ types/safe-json-stringify/tslint.json | 1 + 4 files changed, 41 insertions(+) create mode 100644 types/safe-json-stringify/index.d.ts create mode 100644 types/safe-json-stringify/safe-json-stringify-tests.ts create mode 100644 types/safe-json-stringify/tsconfig.json create mode 100644 types/safe-json-stringify/tslint.json diff --git a/types/safe-json-stringify/index.d.ts b/types/safe-json-stringify/index.d.ts new file mode 100644 index 0000000000..d3eb3eec75 --- /dev/null +++ b/types/safe-json-stringify/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for safe-json-stringify 1.0 +// Project: https://github.com/debitoor/safe-json-stringify +// Definitions by: Eric Byers +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped" +// TypeScript Version: 2.3 + +declare namespace safeJsonStringify { + function ensureProperties(obj: any): object; +} + +declare function safeJsonStringify(data: object): string; + +export = safeJsonStringify; diff --git a/types/safe-json-stringify/safe-json-stringify-tests.ts b/types/safe-json-stringify/safe-json-stringify-tests.ts new file mode 100644 index 0000000000..b35a4df368 --- /dev/null +++ b/types/safe-json-stringify/safe-json-stringify-tests.ts @@ -0,0 +1,5 @@ +import safeJsonStringify = require('safe-json-stringify'); + +const obj1 = {foo: 'bar'}; +safeJsonStringify(obj1); +safeJsonStringify.ensureProperties(obj1); diff --git a/types/safe-json-stringify/tsconfig.json b/types/safe-json-stringify/tsconfig.json new file mode 100644 index 0000000000..41137b8bfe --- /dev/null +++ b/types/safe-json-stringify/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "safe-json-stringify-tests.ts" + ] +} diff --git a/types/safe-json-stringify/tslint.json b/types/safe-json-stringify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/safe-json-stringify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From bc64561d764637313d5c6961d0e91907d046ecd9 Mon Sep 17 00:00:00 2001 From: Ashish Gaurav Date: Wed, 19 Jul 2017 23:33:09 +0530 Subject: [PATCH 0149/1139] @types/dygraphs: add legendFormatter in options (#18107) --- types/dygraphs/index.d.ts | 73 ++++++++++++++++++++++++++++++++++----- 1 file changed, 65 insertions(+), 8 deletions(-) diff --git a/types/dygraphs/index.d.ts b/types/dygraphs/index.d.ts index fb6f4b997d..d4774c4944 100644 --- a/types/dygraphs/index.d.ts +++ b/types/dygraphs/index.d.ts @@ -8,7 +8,7 @@ declare namespace dygraphs { type DataArray = number[][]; - type Data = string|DataArray|google.visualization.DataTable; + type Data = string | DataArray | google.visualization.DataTable; interface PerSeriesOptions { /** @@ -112,7 +112,7 @@ declare namespace dygraphs { * Function to call to format the tick values that appear along an axis. This is usually set * on a per-axis basis. */ - axisLabelFormatter?: (v: number|Date, granularity: number, opts: (name: string) => any, dygraph: Dygraph) => any; + axisLabelFormatter?: (v: number | Date, granularity: number, opts: (name: string) => any, dygraph: Dygraph) => any; /** * Width (in pixels) of the containing divs for x- and y-axis labels. For the y-axis, this @@ -224,7 +224,7 @@ declare namespace dygraphs { pixels: number, opts: (name: string) => any, dygraph: Dygraph, - vals: number[]) => Array<{v: number, label: string}>; + vals: number[]) => Array<{ v: number, label: string }>; /** @@ -267,6 +267,58 @@ declare namespace dygraphs { labelsKMG2?: boolean; } + interface SeriesLegendData { + /** + * Assigned or generated series color + */ + color: string; + /** + * Series line dash + */ + dashHTML: string; + /** + * Whether currently focused or not + */ + isHighlighted: boolean; + /** + * Whether the series line is inside the selected/zoomed region + */ + isVisible: boolean; + /** + * Assigned label to this series + */ + label: string; + /** + * Generated label html for this series + */ + labelHTML: string; + /** + * y value of this series + */ + y: number; + /** + * Generated html for y value + */ + yHTML: string; + } + interface LegendData { + /** + * x value of highlighted points + */ + x: number; + /** + * Generated HTML for x value + */ + xHTML: string; + /** + * Series data for the highlighted points + */ + series: SeriesLegendData[]; + /** + * Dygraph object for this graph + */ + dygraph: Dygraph; + } interface Options extends PerSeriesOptions, PerAxisOptions { /** * Set this option to animate the transition between zoom windows. Applies to programmatic @@ -510,14 +562,14 @@ declare namespace dygraphs { * Show data labels in an external div, rather than on the graph. This value can either be a * div element or a div id. */ - labelsDiv?: string|HTMLElement; + labelsDiv?: string | HTMLElement; /** * Additional styles to apply to the currently-highlighted points div. For example, { * 'fontWeight': 'bold' } will make the labels bold. In general, it is better to use CSS to * style the .dygraph-legend class than to use this property. */ - labelsDivStyles?: {[cssProperty: string]: string}; + labelsDivStyles?: { [cssProperty: string]: string }; /** * Width (in pixels) of the div which shows information on the currently-highlighted points. @@ -547,6 +599,11 @@ declare namespace dygraphs { */ legend?: 'always' | 'follow' | 'onmouseover'; + /** + * for details see https://github.com/danvk/dygraphs/pull/683 + */ + legendFormatter?: (legendData: LegendData) => string; + /** * A value representing the farthest a graph may be panned, in percent of the display. For * example, a value of 0.1 means that the graph can only be panned 10% pased the edges of the @@ -813,7 +870,7 @@ declare namespace dygraphs { * you specified in your CSV file, e.g. "2010-09-13". * You must set either x or xval. */ - x?: number|string; + x?: number | string; /** * numeric value of the point, or millis since epoch. @@ -867,7 +924,7 @@ declare namespace dygraphs { declare class Dygraph { constructor( container: HTMLElement | string, - data: dygraphs.Data|(()=>dygraphs.Data), + data: dygraphs.Data | (() => dygraphs.Data), options?: dygraphs.Options); /** @@ -1104,7 +1161,7 @@ declare class Dygraph { * over the graph, disabling closest-series highlighting. Call clearSelection() * to unlock it. */ - setSelection(row: number|boolean, seriesName?: string, locked?: boolean): void; + setSelection(row: number | boolean, seriesName?: string, locked?: boolean): void; /** * Clears the current selection (i.e. points that were highlighted by moving From 2a92293a59c19efb1aebd14b4104f62f29f43899 Mon Sep 17 00:00:00 2001 From: John Renner Date: Tue, 18 Jul 2017 16:15:06 -0700 Subject: [PATCH 0150/1139] Add types for fast-diff --- types/fast-diff/fast-diff-tests.ts | 16 ++++++++++++++++ types/fast-diff/index.d.ts | 16 ++++++++++++++++ types/fast-diff/tsconfig.json | 22 ++++++++++++++++++++++ types/fast-diff/tslint.json | 1 + 4 files changed, 55 insertions(+) create mode 100644 types/fast-diff/fast-diff-tests.ts create mode 100644 types/fast-diff/index.d.ts create mode 100644 types/fast-diff/tsconfig.json create mode 100644 types/fast-diff/tslint.json diff --git a/types/fast-diff/fast-diff-tests.ts b/types/fast-diff/fast-diff-tests.ts new file mode 100644 index 0000000000..93c512d99b --- /dev/null +++ b/types/fast-diff/fast-diff-tests.ts @@ -0,0 +1,16 @@ +import fastDiff = require('fast-diff'); + +let diffs: fastDiff.Diff[]; +diffs = fastDiff("hi there", "hi"); +diffs = fastDiff("hi there", "hi", 1); + +diffs.forEach((diff: fastDiff.Diff) => { + const operation: number = diff[0]; + const text: string = diff[1]; + + switch (diff[0]) { + case fastDiff.DIFF_EQUAL: break; + case fastDiff.DIFF_DELETE: break; + case fastDiff.DIFF_INSERT: break; + } +}); diff --git a/types/fast-diff/index.d.ts b/types/fast-diff/index.d.ts new file mode 100644 index 0000000000..484fca223f --- /dev/null +++ b/types/fast-diff/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for fast-diff 1.1 +// Project: https://github.com/jhchen/fast-diff#readme +// Definitions by: John Renner +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function diff(text1: string, text2: string, cursorPos?: number): diff.Diff[]; + +declare namespace diff { + type Diff = [-1 | 0 | 1, string]; + + const DIFF_DELETE: -1; + const DIFF_INSERT: 1; + const DIFF_EQUAL: 0; +} + +export = diff; diff --git a/types/fast-diff/tsconfig.json b/types/fast-diff/tsconfig.json new file mode 100644 index 0000000000..e89403e0ef --- /dev/null +++ b/types/fast-diff/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fast-diff-tests.ts" + ] +} diff --git a/types/fast-diff/tslint.json b/types/fast-diff/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fast-diff/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 788200b3f4fec38b063feb7ef5449adb860a08f4 Mon Sep 17 00:00:00 2001 From: Sicilica Date: Wed, 19 Jul 2017 14:32:58 -0600 Subject: [PATCH 0151/1139] typings for deasync --- types/deasync/deasync-tests.ts | 28 ++++++++++++++++++++++++++++ types/deasync/index.d.ts | 16 ++++++++++++++++ types/deasync/tsconfig.json | 22 ++++++++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 types/deasync/deasync-tests.ts create mode 100644 types/deasync/index.d.ts create mode 100644 types/deasync/tsconfig.json diff --git a/types/deasync/deasync-tests.ts b/types/deasync/deasync-tests.ts new file mode 100644 index 0000000000..fb2761d566 --- /dev/null +++ b/types/deasync/deasync-tests.ts @@ -0,0 +1,28 @@ +import * as deasync from "deasync" + + + +function asyncFunction(input: number, cb: (res: number) => void) {} +function handle(res: number) {} + + + +// base case +asyncFunction(42, handle) + +// deasync +let wrapped = deasync(asyncFunction) +handle(wrapped(42)) + +// deasync.loopWhile +let done = false +asyncFunction(42, () => { + done = true +}) +deasync.loopWhile(() => !done) + +// deasync.runLoopOnce +deasync.runLoopOnce() + +// deasync.sleep +deasync.sleep(100) diff --git a/types/deasync/index.d.ts b/types/deasync/index.d.ts new file mode 100644 index 0000000000..c87760c49b --- /dev/null +++ b/types/deasync/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for deasync +// Project: https://github.com/abbr/deasync +// Definitions by: Matt Rollins +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +declare function deasync(func: (...pn: any[])=>void): (...pn: any[])=>any; +declare namespace deasync { + + export function loopWhile(predicate: ()=>boolean): void + export function runLoopOnce(): void + export function sleep(ms: number): void + +} + +export = deasync diff --git a/types/deasync/tsconfig.json b/types/deasync/tsconfig.json new file mode 100644 index 0000000000..08469db6f6 --- /dev/null +++ b/types/deasync/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "deasync-tests.ts" + ] +} From 316c573bf4298c2998227a757742b8cee1c97282 Mon Sep 17 00:00:00 2001 From: Anthony Higa Date: Wed, 19 Jul 2017 13:48:18 -0700 Subject: [PATCH 0152/1139] Adding divide routine to Animated --- types/react-native/index.d.ts | 11 +++++++++++ types/react-native/test/animated.tsx | 1 + 2 files changed, 12 insertions(+) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 448d29a069..e8e9eca55c 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -7962,6 +7962,17 @@ export namespace Animated { class AnimatedAddition extends AnimatedInterpolation { } + /** + * Creates a new Animated value composed by dividing the first Animated + * value by the second Animated value. + */ + export function divide( + a: Animated, + b: Animated + ): AnimatedDivision; + + class AnimatedDivision extends AnimatedInterpolation { } + /** * Creates a new Animated value composed from two Animated values multiplied * together. diff --git a/types/react-native/test/animated.tsx b/types/react-native/test/animated.tsx index 8efd5fd171..b63a95cc85 100644 --- a/types/react-native/test/animated.tsx +++ b/types/react-native/test/animated.tsx @@ -59,6 +59,7 @@ function TestAnimatedAPI() { }); Animated.add(v1, v2); + Animated.divide(v1, v2); Animated.multiply(v1, v2); Animated.modulo(v1, 2); From 7aac62aceb42a9f1c7ae87ee9ccb608997262caf Mon Sep 17 00:00:00 2001 From: Sicilica Date: Wed, 19 Jul 2017 14:56:24 -0600 Subject: [PATCH 0153/1139] add lint for deasync --- types/deasync/deasync-tests.ts | 24 ++++++++++-------------- types/deasync/index.d.ts | 16 +++++++--------- types/deasync/tsconfig.json | 2 +- types/deasync/tslint.json | 4 ++++ 4 files changed, 22 insertions(+), 24 deletions(-) create mode 100644 types/deasync/tslint.json diff --git a/types/deasync/deasync-tests.ts b/types/deasync/deasync-tests.ts index fb2761d566..e4e77561e9 100644 --- a/types/deasync/deasync-tests.ts +++ b/types/deasync/deasync-tests.ts @@ -1,28 +1,24 @@ -import * as deasync from "deasync" - - +import * as deasync from "deasync"; function asyncFunction(input: number, cb: (res: number) => void) {} function handle(res: number) {} - - // base case -asyncFunction(42, handle) +asyncFunction(42, handle); // deasync -let wrapped = deasync(asyncFunction) -handle(wrapped(42)) +let wrapped = deasync(asyncFunction); +handle(wrapped(42)); // deasync.loopWhile -let done = false +let done = false; asyncFunction(42, () => { - done = true -}) -deasync.loopWhile(() => !done) + done = true; +}); +deasync.loopWhile(() => !done); // deasync.runLoopOnce -deasync.runLoopOnce() +deasync.runLoopOnce(); // deasync.sleep -deasync.sleep(100) +deasync.sleep(100); diff --git a/types/deasync/index.d.ts b/types/deasync/index.d.ts index c87760c49b..20440203e7 100644 --- a/types/deasync/index.d.ts +++ b/types/deasync/index.d.ts @@ -1,16 +1,14 @@ -// Type definitions for deasync +// Type definitions for deasync 0.1 // Project: https://github.com/abbr/deasync // Definitions by: Matt Rollins // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -declare function deasync(func: (...pn: any[])=>void): (...pn: any[])=>any; +export = deasync; + +declare function deasync(fn: (...args: any[]) => void): (...args: any[]) => any; declare namespace deasync { - - export function loopWhile(predicate: ()=>boolean): void - export function runLoopOnce(): void - export function sleep(ms: number): void - + function loopWhile(pred: () => boolean): void; + function runLoopOnce(): void; + function sleep(ms: number): void; } - -export = deasync diff --git a/types/deasync/tsconfig.json b/types/deasync/tsconfig.json index 08469db6f6..5b96318954 100644 --- a/types/deasync/tsconfig.json +++ b/types/deasync/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/deasync/tslint.json b/types/deasync/tslint.json new file mode 100644 index 0000000000..c6c6df5352 --- /dev/null +++ b/types/deasync/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": {} +} From 7b0267c18db68041f192daeaa293a8bf1e31dade Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Wed, 19 Jul 2017 23:19:44 +0200 Subject: [PATCH 0154/1139] [log-symbols] introduce typings --- types/log-symbols/index.d.ts | 9 +++++++++ types/log-symbols/log-symbols-tests.ts | 12 ++++++++++++ types/log-symbols/tsconfig.json | 22 ++++++++++++++++++++++ types/log-symbols/tslint.json | 1 + 4 files changed, 44 insertions(+) create mode 100644 types/log-symbols/index.d.ts create mode 100644 types/log-symbols/log-symbols-tests.ts create mode 100644 types/log-symbols/tsconfig.json create mode 100644 types/log-symbols/tslint.json diff --git a/types/log-symbols/index.d.ts b/types/log-symbols/index.d.ts new file mode 100644 index 0000000000..50b058e7d9 --- /dev/null +++ b/types/log-symbols/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for log-symbols 2.0 +// Project: https://github.com/sindresorhus/log-symbols#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const info: string; +export const success: string; +export const warning: string; +export const error: string; diff --git a/types/log-symbols/log-symbols-tests.ts b/types/log-symbols/log-symbols-tests.ts new file mode 100644 index 0000000000..aa47937cdf --- /dev/null +++ b/types/log-symbols/log-symbols-tests.ts @@ -0,0 +1,12 @@ +/// + +import * as logSymbols from 'log-symbols'; + +console.log(logSymbols.success, 'Finished successfully!'); + +let str: string; + +str = logSymbols.info; +str = logSymbols.success; +str = logSymbols.warning; +str = logSymbols.error; diff --git a/types/log-symbols/tsconfig.json b/types/log-symbols/tsconfig.json new file mode 100644 index 0000000000..a8255cad69 --- /dev/null +++ b/types/log-symbols/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "log-symbols-tests.ts" + ] +} diff --git a/types/log-symbols/tslint.json b/types/log-symbols/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/log-symbols/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 5d761ccef7341be9da1aee5eab3a6a5d1fd6a1e9 Mon Sep 17 00:00:00 2001 From: John Renner Date: Wed, 19 Jul 2017 17:31:33 -0700 Subject: [PATCH 0155/1139] Rename constants to match library --- types/fast-diff/fast-diff-tests.ts | 6 +++--- types/fast-diff/index.d.ts | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/fast-diff/fast-diff-tests.ts b/types/fast-diff/fast-diff-tests.ts index 93c512d99b..3177bfa7fc 100644 --- a/types/fast-diff/fast-diff-tests.ts +++ b/types/fast-diff/fast-diff-tests.ts @@ -9,8 +9,8 @@ diffs.forEach((diff: fastDiff.Diff) => { const text: string = diff[1]; switch (diff[0]) { - case fastDiff.DIFF_EQUAL: break; - case fastDiff.DIFF_DELETE: break; - case fastDiff.DIFF_INSERT: break; + case fastDiff.EQUAL: break; + case fastDiff.DELETE: break; + case fastDiff.INSERT: break; } }); diff --git a/types/fast-diff/index.d.ts b/types/fast-diff/index.d.ts index 484fca223f..1f306a6e9d 100644 --- a/types/fast-diff/index.d.ts +++ b/types/fast-diff/index.d.ts @@ -8,9 +8,9 @@ declare function diff(text1: string, text2: string, cursorPos?: number): diff.Di declare namespace diff { type Diff = [-1 | 0 | 1, string]; - const DIFF_DELETE: -1; - const DIFF_INSERT: 1; - const DIFF_EQUAL: 0; + const DELETE: -1; + const INSERT: 1; + const EQUAL: 0; } export = diff; From bec17f7f614543e385e9ad0dab92c32c4ab48a25 Mon Sep 17 00:00:00 2001 From: Junyoung Choi Date: Thu, 20 Jul 2017 10:26:08 +0900 Subject: [PATCH 0156/1139] Remove unncessary rules section from tslint.json --- types/filenamify/tslint.json | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/types/filenamify/tslint.json b/types/filenamify/tslint.json index 279473e356..f93cf8562a 100644 --- a/types/filenamify/tslint.json +++ b/types/filenamify/tslint.json @@ -1,7 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - // This package uses the Function type, and it will take effort to fix. - "ban-types": false - } + "extends": "dtslint/dt.json" } From ac247f70e2888f58896387b5fa177db755915f37 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 20 Jul 2017 13:01:43 +0900 Subject: [PATCH 0157/1139] Update redux-form to version 7 (#18168) * Refactor some of the definitions for v7 * Add definitions for formValues decorator * Refactor definitions for Field, Fields, FieldArray, add tests * Add files to tsconfig * Fix immutable version of exports * Clean up the code, change some types --- types/redux-form/immutable/index.d.ts | 17 +- types/redux-form/index.d.ts | 58 +- types/redux-form/lib/Field.d.ts | 318 ++-------- types/redux-form/lib/FieldArray.d.ts | 210 +------ types/redux-form/lib/Fields.d.ts | 109 +--- types/redux-form/lib/Form.d.ts | 23 +- types/redux-form/lib/FormSection.d.ts | 17 +- types/redux-form/lib/SubmissionError.d.ts | 7 + types/redux-form/lib/actions.d.ts | 178 +----- types/redux-form/lib/formValueSelector.d.ts | 6 + types/redux-form/lib/formValues.d.ts | 13 + types/redux-form/lib/reducer.d.ts | 11 - types/redux-form/lib/reduxForm.d.ts | 619 +++----------------- types/redux-form/lib/selectors.d.ts | 137 +---- types/redux-form/redux-form-tests.tsx | 359 +++++++----- types/redux-form/tsconfig.json | 15 +- types/redux-form/v6/index.d.ts | 46 ++ types/redux-form/v6/lib/Field.d.ts | 333 +++++++++++ types/redux-form/v6/lib/FieldArray.d.ts | 217 +++++++ types/redux-form/v6/lib/Fields.d.ts | 116 ++++ types/redux-form/v6/lib/Form.d.ts | 22 + types/redux-form/v6/lib/FormSection.d.ts | 15 + types/redux-form/v6/lib/actionTypes.d.ts | 37 ++ types/redux-form/v6/lib/actions.d.ts | 160 +++++ types/redux-form/v6/lib/reducer.d.ts | 49 ++ types/redux-form/v6/lib/reduxForm.d.ts | 571 ++++++++++++++++++ types/redux-form/v6/lib/selectors.d.ts | 120 ++++ types/redux-form/v6/package.json | 5 + types/redux-form/v6/redux-form-tests.tsx | 164 ++++++ types/redux-form/v6/tsconfig.json | 30 + 30 files changed, 2401 insertions(+), 1581 deletions(-) create mode 100644 types/redux-form/lib/SubmissionError.d.ts create mode 100644 types/redux-form/lib/formValueSelector.d.ts create mode 100644 types/redux-form/lib/formValues.d.ts create mode 100644 types/redux-form/v6/index.d.ts create mode 100644 types/redux-form/v6/lib/Field.d.ts create mode 100644 types/redux-form/v6/lib/FieldArray.d.ts create mode 100644 types/redux-form/v6/lib/Fields.d.ts create mode 100644 types/redux-form/v6/lib/Form.d.ts create mode 100644 types/redux-form/v6/lib/FormSection.d.ts create mode 100644 types/redux-form/v6/lib/actionTypes.d.ts create mode 100644 types/redux-form/v6/lib/actions.d.ts create mode 100644 types/redux-form/v6/lib/reducer.d.ts create mode 100644 types/redux-form/v6/lib/reduxForm.d.ts create mode 100644 types/redux-form/v6/lib/selectors.d.ts create mode 100644 types/redux-form/v6/package.json create mode 100644 types/redux-form/v6/redux-form-tests.tsx create mode 100644 types/redux-form/v6/tsconfig.json diff --git a/types/redux-form/immutable/index.d.ts b/types/redux-form/immutable/index.d.ts index eed5b5856f..3eacb2338c 100644 --- a/types/redux-form/immutable/index.d.ts +++ b/types/redux-form/immutable/index.d.ts @@ -1,8 +1,9 @@ -export { Field } from "../lib/Field"; -export { FieldArray } from "../lib/FieldArray"; -export { Fields } from '../lib/Fields'; - export { + Field, + FieldArray, + Fields, + reduxForm, + reducer, formValueSelector, getFormAsyncErrors, getFormInitialValues, @@ -19,10 +20,4 @@ export { isPristine, isSubmitting, isValid, -} from "../lib/selectors"; -export { - reduxForm, -} from "../lib/reduxForm"; -export { - reducer, -} from "../lib/reducer"; +} from "redux-form"; diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 8a51117530..d13226268c 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for redux-form 6.6 +// Type definitions for redux-form 7.0 // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full , Daniel Lytkin , Karol Janyst , Luka Zakrajsek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,37 +10,43 @@ import { ReactElement } from "react"; -export type FieldValue = any; - export type FieldType = "Field" | "FieldArray"; -export interface DataShape { - [fieldName: string]: FieldValue +export interface ErrorOther { + _error?: T; } -export type FormErrors = { - [P in keyof FormData]?: ReactElement | string | { _error?: string }; +export type FormErrors = { + [P in keyof FormData]?: ReactElement | string | ErrorOther; }; -export type FormWarnings = { - [P in keyof FormData]?: ReactElement | string | { _warning?: string }; +export interface WarningOther { + _warning?: T; +} + +export type FormWarnings = { + [P in keyof FormData]?: ReactElement | string | WarningOther; }; -/** - * A component class or stateless function component. - * Workaround for: ComponentClass

| SFC

which does - * not resolve due to a bug in TypeScript. - * https://github.com/Microsoft/TypeScript/pull/8674 - */ -export type ComponentConstructor

= ComponentClass

| StatelessComponent

; +export interface RegisteredFieldState { + name: string; + type: FieldType; +} -export * from "./lib/reduxForm"; -export * from "./lib/Field"; -export * from "./lib/Fields"; -export * from "./lib/FieldArray"; -export * from "./lib/Form"; -export * from "./lib/FormSection"; -export * from "./lib/actions"; -export * from "./lib/actionTypes"; -export * from "./lib/reducer"; -export * from "./lib/selectors"; + +export type Diff = ({ [P in T]: P } & { [P in U]: never } & { [x: string]: never })[T]; +export type Omit = Pick>; + +export * from "redux-form/lib/reduxForm"; +export * from "redux-form/lib/Field"; +export * from "redux-form/lib/Fields"; +export * from "redux-form/lib/FieldArray"; +export * from "redux-form/lib/Form"; +export * from "redux-form/lib/FormSection"; +export * from "redux-form/lib/formValues"; +export * from "redux-form/lib/formValueSelector"; +export * from "redux-form/lib/reducer"; +export * from "redux-form/lib/SubmissionError"; +export * from "redux-form/lib/actions"; +export * from "redux-form/lib/actionTypes"; +export * from "redux-form/lib/selectors"; diff --git a/types/redux-form/lib/Field.d.ts b/types/redux-form/lib/Field.d.ts index ecef15b4c7..81a3e4a517 100644 --- a/types/redux-form/lib/Field.d.ts +++ b/types/redux-form/lib/Field.d.ts @@ -1,333 +1,85 @@ import { Component, + ComponentType, ReactElement, ChangeEvent, DragEvent, FocusEvent } from "react"; import { Dispatch } from "redux"; -import { ComponentConstructor, DataShape, FieldValue } from "../index"; -/** - * These are the props to give to `Field`. - * Any others will be passed through to your component. - */ -interface BaseFieldProps { - /** - * A string path, in dot-and-bracket notation, corresponding to a value - * in the form values. It may be as simple as 'firstName' or as complicated - * as contact.billing.address[2].phones[1].areaCode. - * - * Required but made optional so interface can be used on decorated components. - */ - name?: string; +export type Normalizer = (value: any, previousValue?: any, allValues?: any, previousAllValues?: any) => any; +export type Formatter = (value: any, name: string) => any; +export type Parser = (value: any, name: string) => any; +export type Validator = (value: any, allValues?: any, props?: any) => any; - /** - * A Component, stateless function, or string corresponding to a default - * JSX element. - * - * Required but made optional so interface can be used on decorated components. - */ - component?: ComponentConstructor | "input" | "select" | "textarea", +interface CommonFieldProps { + name: string; + onBlur: EventOrValueHandler>; + onChange: EventOrValueHandler>; + onDragStart: EventOrValueHandler>; + onDrop: EventOrValueHandler>; + onFocus: EventOrValueHandler>; +} - /** - * Formats the value from the Redux store to be displayed in the field input. - * Common use cases are to format Numbers into currencies or Dates into a - * localized date format. - */ +interface BaseFieldProps

extends Partial { + name: string; + component?: ComponentType

| "input" | "select" | "textarea", format?: Formatter | null; - - /** - * A function to convert whatever value the user has entered into the value that you - * want stored in the Redux store for the field. - * - * For instance, if you want the value to be in all uppercase, you would pass - * value => value.toUpperCase() - */ normalize?: Normalizer; - - /** - * Don't use. - */ - props?: any; - - /** - * Parses the value given from the field input component to the type that you want - * stored in the Redux store. Common use cases are to parse currencies into Numbers into - * currencies or localized date formats into Dates. - */ + props?: P; parse?: Parser; - - /** - * Allows you to to provide a field-level validation rule. The function will be given the - * current value of the field and all the other form values. If the field is valid, it - * should return `undefined`, if the field is invalid, it should return an error - * (usually, but not necessarily, a `String`). - */ validate?: Validator | Validator[]; - - /** - * Allows you to to provide a field-level warning rule. The function will be given the - * current value of the field and all the other form values. If the field needs a warning, - * it should return the warning (usually, but not necessarily, a `String`). If the field - * does not need a warning, it should return `undefined`. - */ warn?: Validator | Validator[]; - - /** - * If true, the rendered component will be available with the - * getRenderedComponent() method. Defaults to false. Cannot be used if your - * component is a stateless function component. - */ withRef?: boolean; } -/** - * @param value The value entered by the user. - * @param previousValue The previous value for the field. - * @param allValues All the values in the entire form with the new value. - * This will be an Immutable Map if you are using Immutable JS. - * @param previousAllValues All the values in the entire form before the current change. - * This will be an Immutable Map if you are using Immutable JS. - */ -export type Normalizer = (value: FieldValue, previousValue?: FieldValue, allValues?: any, previousAllValues?: any) => FieldValue; - -export type Formatter = (value: FieldValue, name: string) => FieldValue; - -export type Parser = (value: FieldValue, name: string) => FieldValue; - -export type Validator = (value: FieldValue, allValues?: any, props?: any) => any; - -/** - * Declare Field as this interface to specify the generic. - */ -export interface GenericField extends Component { - /** - * true if the current value is different from the initialized value, - * false otherwise. - */ +export interface GenericField

extends Component { dirty: boolean; - - /** - * The name prop that you passed in. - */ name: string; - - /** - * true if the current value is the same as the initialized value, - * false otherwise. - */ pristine: boolean; - - /** - * The current value of the field. - */ - value: FieldValue; - - /** - * Returns the instance of the rendered component. For this to work, you must - * provide a withRef prop, and your component must not be a stateless function - * component. - */ - getRenderedComponent(): Component & FieldCustomProps>; + value: any; + getRenderedComponent(): Component; } -/** - * The Field Instance API. - */ -export class Field extends Component implements GenericField { - /** - * true if the current value is different from the initialized value, - * false otherwise. - */ +export class Field extends Component implements GenericField { dirty: boolean; - - /** - * The name prop that you passed in. - */ name: string; - - /** - * true if the current value is the same as the initialized value, - * false otherwise. - */ pristine: boolean; - - /** - * The current value of the field. - */ - value: FieldValue; - - /** - * Returns the instance of the rendered component. For this to work, you must - * provide a withRef prop, and your component must not be a stateless function - * component. - */ + value: any; getRenderedComponent(): Component; } -/** - * These are props that `Field` will pass to your wrapped component (not including custom props). - */ -interface WrappedFieldProps { - /** - * An object containing all the props that you will normally want to pass to - * your input component. - */ - input?: WrappedFieldInputProps; - - /** - * An object containing all the metadata props. - */ - meta: WrappedFieldMetaProps; +interface WrappedFieldProps { + input: WrappedFieldInputProps; + meta: WrappedFieldMetaProps; } -/** - * These props are meant to be destructured into your component. - */ interface EventOrValueHandler { (event: Event): void; - (value: FieldValue, newValue: FieldValue, previousValue: FieldValue): void; + (value: any, newValue: any, previousValue: any): void; } -interface WrappedFieldInputProps { - /** - * An alias for value only when value is a boolean. Provided for - * convenience of destructuring the whole field object into the props of a - * form element. - */ +interface WrappedFieldInputProps extends CommonFieldProps { checked?: boolean; - - /** - * The name prop passed in. - */ - name: string; - - /** - * A function to call when the form field loses focus. - */ - onBlur: EventOrValueHandler>; - - /** - * A function to call when the form field is changed. - */ - onChange: EventOrValueHandler>; - - /** - * A function to call when the form field receives a 'dragStart' event. - * Saves the field value in the event for giving the field it is dropped - * into. - */ - onDragStart: EventOrValueHandler>; - - /** - * A function to call when the form field receives a drop event. - */ - onDrop: EventOrValueHandler>; - - /** - * A function to call when the form field receives focus. - */ - onFocus: EventOrValueHandler>; - - /** - * The value of this form field. It will be a boolean for checkboxes, and - * a string for all other input types. If there is no value in the Redux - * state for this field, it will default to ''. This is to - * ensure that the input is controlled. - */ - value: FieldValue; + value: any; } -/** - * These props are metadata about the state of this field that redux-form is tracking for you. - */ -interface WrappedFieldMetaProps { - - /** - * true if this field currently has focus. It will only work if you are - * passing onFocus to your input element. - */ +interface WrappedFieldMetaProps { active?: boolean; - - /** - * true if this field has been set with the AUTOFILL action and has not since been changed - * with a CHANGE action. This is useful to render the field in a way that the user can tell - * that the value was autofilled for them. - */ autofilled: boolean; - - /** - * true if the form is currently running asynchronous validation because this - * field was blurred. - */ asyncValidating: boolean; - - /** - * true if the field value has changed from its initialized value. - * Opposite of pristine. - */ dirty: boolean; - - /** - * The Redux dispatch function. - */ - dispatch: Dispatch; - - /** - * The error for this field if its value is not passing validation. Both - * synchronous, asynchronous, and submit validation errors will be reported here. - */ + dispatch: Dispatch; error?: any; - - /** - * The name of the form. Could be useful if you want to manually dispatch actions. - */ - form?: string; - - /** - * true if the field value fails validation (has a validation error). - * Opposite of valid. - */ + form: string; + initial: any; invalid: boolean; - - /** - * true if the field value is the same as its initialized value. Opposite - * of dirty. - */ pristine: boolean; - - /** - * true if the field is currently being submitted - */ - submitting?: boolean; - - /** - * true if the form had onSubmit called and failed to submit for any reason. - * A subsequent successful submit will set it back to false. - */ - submitFailed?: boolean; - - /** - * true if the field has been touched. By default this will be set when - * the field is blurred. - */ + submitting: boolean; + submitFailed: boolean; touched: boolean; - - /** - * true if the field value passes validation (has no validation errors). - * Opposite of invalid. - */ valid: boolean; - - /** - * true if this field has ever had focus. It will only work if you are - * passing onFocus to your input element. - */ - visited?: boolean; - - /** - * The warning for this field if its value is not passing warning validation. - */ + visited: boolean; warning?: any; } diff --git a/types/redux-form/lib/FieldArray.d.ts b/types/redux-form/lib/FieldArray.d.ts index 9629eecb27..5b6e9dc73b 100644 --- a/types/redux-form/lib/FieldArray.d.ts +++ b/types/redux-form/lib/FieldArray.d.ts @@ -1,217 +1,57 @@ -import { Component } from "react"; -import { ComponentConstructor, Validator } from "../index"; +import { Component, ComponentType } from "react"; +import { Validator } from "redux-form"; -/** - * These are the props to give to `FieldArray`. - * Any others will be passed through to your component. - */ -interface BaseFieldArrayProps { - /** - * A string path, in dot-and-bracket notation, corresponding to a value - * in the form values. It may be as simple as 'firstName' or as complicated - * as contact.billing.address[2].phones[1].areaCode. - * - * Required but made optional so interface can be used on decorated components. - */ - name?: string; - - /** - * A Component or stateless function to render the field array. - * - * Required but made optional so interface can be used on decorated components. - */ - component?: ComponentConstructor, - - /** - * Allows you to to provide a field-level validation rule. The function will be given the - * current value of the field and all the other form values. If the field is valid, it - * should return `undefined`, if the field is invalid, it should return an error - * (usually, but not necessarily, a `String`). - */ +interface BaseFieldArrayProps

{ + name: string; + component: ComponentType

, validate?: Validator | Validator[]; - - /** - * Allows you to to provide a field-level warning rule. The function will be given the - * current value of the field and all the other form values. If the field needs a warning, - * it should return the warning (usually, but not necessarily, a `String`). If the field - * does not need a warning, it should return `undefined`. - */ warn?: Validator | Validator[]; - - /** - * If true, the rendered component will be available with the - * getRenderedComponent() method. Defaults to false. Cannot be used if your - * component is a stateless function component. - */ withRef?: boolean; - - props?: any; + props?: P; + rerenderOnEveryChange?: boolean; } -/** - * Declare FieldArray as this interface to specify the generics. - */ -export interface GenericFieldArray extends Component { - - /** - * The name prop that you passed in. - */ +export interface GenericFieldArray extends Component { name: string; - - /** - * true if this field passes validation, false otherwise. - */ valid: boolean; - - /** - * Returns the instance of the rendered component. For this to work, you must - * provide a withRef prop, and your component must not be a stateless function - * component. - */ - getRenderedComponent(): Component & FieldCustomProps>; + getRenderedComponent(): Component & P>; } -/** - * The FieldArray Instance API. - */ -export class FieldArray extends Component implements GenericFieldArray { - - /** - * The name prop that you passed in. - */ +export class FieldArray extends Component implements GenericFieldArray { name: string; - - /** - * true if this field passes validation, false otherwise. - */ valid: boolean; - - /** - * Returns the instance of the rendered component. For this to work, you must - * provide a withRef prop, and your component must not be a stateless function - * component. - */ - getRenderedComponent(): Component; + getRenderedComponent(): Component>; } -/** - * These are props that `FieldArray` will pass to your wrapped component. - */ -interface WrappedFieldArrayProps { - fields: FieldsProps; +interface WrappedFieldArrayProps { + fields: FieldsProps; meta: FieldArrayMetaProps; } -interface FieldsProps { - /** - * A method to iterate over each value of the array. - */ - forEach(callback: (name: string, index: number, fields: FieldsProps) => void): void; +type FieldIterate = (name: string, index: number, fields: FieldsProps) => R; - /** - * A method to get a single value from the array value. - */ - get(index: number): T; - - /** - * A method to get all the values in the array. - */ - getAll(): T[]; - - /** - * A function to insert a new value into the array at any arbitrary index. - */ - insert(index: number, value: T): void; - - /** - * The current length of the array. - */ +interface FieldsProps { + forEach(callback: FieldIterate): void; + get(index: number): FieldValue; + getAll(): FieldValue[]; + insert(index: number, value: FieldValue): void; length: number; - - /** - * A method to iterate over each value of the array. Returns an array of the - * results of each call to the callback. - */ - map(callback: (name: string, index: number, fields: FieldsProps) => any): any; - - /** - * Removes an item from the end of the array. Returns the item removed. - */ - pop(): T; - - /** - * Adds a value to the end of the array. - */ - push(value: T): void; - - /** - * Removes an item from the array at an arbitrary index. - */ + map(callback: FieldIterate): R[]; + pop(): FieldValue; + push(value: FieldValue): void; remove(index: number): void; - - /** - * Removes an item from beginning of the array. Returns the item removed. - */ - shift(): T; - - /** - * Swaps two items in the array at the given indexes. - */ + shift(): FieldValue; swap(indexA: number, indexB: number): void; - - /** - * Adds an item to the beginning of the array. - */ - unshift(value: T): void; + unshift(value: FieldValue): void; } interface FieldArrayMetaProps { - /** - * true if the any of the fields in the field array have changed from their - * initialized value. Opposite of pristine. - */ dirty: boolean; - - /** - * The error for this field array if its value is not passing validation. Both - * synchronous, asynchronous, and submit validation errors will be reported here. - * Array-specific errors should be returned from the validation function as an - * _error key on the array. - */ error?: string; - - /** - * Name of your form provided to `reduxForm()` as the `form` config property. - */ form: string; - - /** - * true if the field array value fails validation (has a validation error). - * Opposite of valid. - */ invalid: boolean; - - /** - * true if the all of the fields in the field array are the same as their - * initialized value. Opposite of dirty. - */ pristine: boolean; - - /** - * true if any of the fields have been touched. - */ - touched: boolean; - - /** - * true if the field value passes validation (has no validation errors). - * Opposite of invalid. - */ + submitting: boolean; valid: boolean; - - /** - * The warning for this field array if its values are not passing warning validation. - * Array-specific errors should be returned from the validation function as an - * `_warning` key on the array. - */ warning?: string; } diff --git a/types/redux-form/lib/Fields.d.ts b/types/redux-form/lib/Fields.d.ts index b2c210ba8c..29e06a519a 100644 --- a/types/redux-form/lib/Fields.d.ts +++ b/types/redux-form/lib/Fields.d.ts @@ -1,116 +1,31 @@ -import { Component } from "react"; -import { ComponentConstructor, Formatter, Parser, FieldValue, WrappedFieldProps } from "../index"; +import { Component, ComponentType } from "react"; +import { Formatter, Parser, WrappedFieldProps } from "redux-form"; -/** - * These are the props to give to `Field`. - * Any others will be passed through to your component. - */ -interface BaseFieldsProps { - /** - * An array of strings (or the pseudo-array fields provided by FieldArray), - * in dot-and-bracket notation, corresponding to form values. - * They may be as simple as 'firstName' or as complicated as - * 'contact.billing.address[2].phones[1].areaCode'. - */ +interface BaseFieldsProps

{ names: string[]; - - /** - * A Component or stateless function that will be given all the props necessary - * to render the field inputs. - */ - component?: ComponentConstructor; - - /** - * Formats the value from the Redux store to be displayed in the field input. - * Common use cases are to format Numbers into currencies or Dates into a localized date format. - * - * format is called with the field value and name as arguments and should return the new formatted - * value to be displayed in the field input. - * - * To respect React 15 input behavior there is defaultFormat = value => value == null ? '' : value - * internally used. To disable that you can pass null as format prop. - */ + component?: ComponentType; format?: Formatter | null; - - /** - * Don't use. - */ - props?: any; - - /** - * Parses the value given from the field input component to the type that you want stored in the Redux store. - * Common use cases are to parse currencies into Numbers into currencies or localized date formats into Dates. - * - * parse is called with the field value and name as arguments and should return the new parsed value to be - * stored in the Redux store. - */ + props?: P; parse?: Parser; - - /** - * If true, the rendered component will be available with the getRenderedComponent() method. - * Defaults to false. Cannot be used if your component is a stateless function component. - */ withRef?: boolean; } -/** - * Declare Fields as this interface to specify the generics. - */ -export interface GenericFields extends Component { - /** - * true if the current value of any of the fields is different from the initialized value, false otherwise. - */ +export interface GenericFields

extends Component { dirty: boolean; - - /** - * The names prop that you passed in. - */ names: string[]; - - /** - * true if the all of the current values are the same as the initialized values, false otherwise. - */ pristine: boolean; - - /** - * The current values of the fields. If they are nested, the values will duplicate the structure. - * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be - * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } - */ - values: { [name: string]: FieldValue }; - - getRenderedComponent(): Component; + values: { [name: string]: any }; + getRenderedComponent(): Component; } -/** - * The Fields Instance API. - */ -export class Fields extends Component implements GenericFields { - /** - * true if the current value of any of the fields is different from the initialized value, false otherwise. - */ +export class Fields extends Component implements GenericFields { dirty: boolean; - - /** - * The names prop that you passed in. - */ names: string[]; - - /** - * true if the all of the current values are the same as the initialized values, false otherwise. - */ pristine: boolean; - - /** - * The current values of the fields. If they are nested, the values will duplicate the structure. - * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be - * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } - */ - values: { [name: string]: FieldValue }; - + values: { [name: string]: any }; getRenderedComponent(): Component; } -interface WrappedFieldsProps { - [name: string]: WrappedFieldsProps & WrappedFieldProps +interface WrappedFieldsProps { + [name: string]: WrappedFieldsProps & WrappedFieldProps } diff --git a/types/redux-form/lib/Form.d.ts b/types/redux-form/lib/Form.d.ts index 9339348393..fd8321836d 100644 --- a/types/redux-form/lib/Form.d.ts +++ b/types/redux-form/lib/Form.d.ts @@ -1,22 +1,11 @@ -import { Component, HTMLProps, FormEvent } from "react"; +import { Component, FormHTMLAttributes, FormEvent, FormEventHandler } from "react"; import { Dispatch } from "redux"; -import { SubmitHandler, FormProps, FormErrors } from "../index" +import { FormProps, FormErrors, FormSubmitHandler, Omit } from "redux-form"; -interface FormSubmitHandler { - (values: any, dispatch?: Dispatch, props?: FormProps & { [prop: string]: any }): void | FormErrors | Promise; - //(e: FormEvent): void; +interface FormSubmitProp { + onSubmit?: FormSubmitHandler; } -export interface FormComponentProps extends HTMLProps { - /** - * The function to call when form submission is triggered. - */ - onSubmit: FormSubmitHandler; -} +export type FormProps = Omit, "onSubmit"> & FormSubmitProp; -/** - * The Form component is a simple wrapper for the React

component that - * allows the surrounding redux-form-decorated component to trigger its - * onSubmit function. - */ -export class Form extends Component {} +declare class Form extends Component {} diff --git a/types/redux-form/lib/FormSection.d.ts b/types/redux-form/lib/FormSection.d.ts index 9be46ebf80..8be6278f9b 100644 --- a/types/redux-form/lib/FormSection.d.ts +++ b/types/redux-form/lib/FormSection.d.ts @@ -1,15 +1,10 @@ -import { Component } from "react"; +import { Component, ComponentType } from "react"; -interface FormSectionProps { - /** - * The name all child fields should be prefixed with. - */ +export type GenericFormSection

= Component

>; + +export interface FormSectionProps

{ name: string; + component?: string | ComponentType

; } -/** - * The FormSection component makes it easy to split forms into smaller components that are resuable across - * multiple forms. It does this by prefixing the name of Field, Fields and FieldArray children, at any depth, - * with the value specified in the name prop. - */ -export class FormSection extends Component {} +declare class FormSection extends Component {} diff --git a/types/redux-form/lib/SubmissionError.d.ts b/types/redux-form/lib/SubmissionError.d.ts new file mode 100644 index 0000000000..ffe7a0064a --- /dev/null +++ b/types/redux-form/lib/SubmissionError.d.ts @@ -0,0 +1,7 @@ +import { FormErrors } from "redux-form"; + +export interface SubmissionErrorConstructor { + new (errors?: FormErrors): Error; +} + +declare const SubmissionError: SubmissionErrorConstructor; diff --git a/types/redux-form/lib/actions.d.ts b/types/redux-form/lib/actions.d.ts index b126549f68..8508fb2aec 100644 --- a/types/redux-form/lib/actions.d.ts +++ b/types/redux-form/lib/actions.d.ts @@ -1,5 +1,5 @@ import { Action } from "redux"; -import { FormErrors, FormWarnings, FieldType } from "../index"; +import { FormErrors, FormWarnings, FieldType } from "redux-form"; export interface FormAction extends Action { meta: { @@ -7,154 +7,40 @@ export interface FormAction extends Action { }; } -/** - * Inserts an item into a field array at the specified index - */ -export function arrayInsert(form: string, field: string, index: number, value: any): FormAction; +declare function arrayInsert(form: string, field: string, index: number, value: any): FormAction; +declare function arrayMove(form: string, field: string, from: number, to: number): FormAction; +declare function arrayPop(form: string, field: string): FormAction; +declare function arrayPush(form: string, field: string, value: any): FormAction; +declare function arrayRemove(form: string, field: string, index: number): FormAction; +declare function arrayRemoveAll(form: string, field: string): FormAction; +declare function arrayShift(form: string, field: string): FormAction; +declare function arraySplice(form: string, field: string, index: number, removeNum: number, value: any): FormAction; +declare function arraySwap(form: string, field: string, indexA: number, indexB: number): FormAction; +declare function arrayUnshift(form: string, field: string, value: any): FormAction; +declare function autofill(form: string, field: string, value: any): FormAction; +declare function blur(form: string, field: string, value: any): FormAction; +declare function change(form: string, field: string, value: any): FormAction; +declare function destroy(...form: string[]): FormAction; +declare function focus(form: string, field: string): FormAction; -/** - * Moves an item from one index in the array to another. In effect, it performs a remove and an - * insert, so the item already at the `to` position will be bumped to a higher index, not overwritten. - */ -export function arrayMove(form: string, field: string, from: number, to: number): FormAction; - -/** - * Removes an item from the end of a field array - */ -export function arrayPop(form: string, field: string): FormAction; - -/** - * Appends an item to the end of a field array - */ -export function arrayPush(form: string, field: string, value: any): FormAction; - -/** - * Removes an item at the specified index from a field array - */ -export function arrayRemove(form: string, field: string, index: number): FormAction; - -/** - * Removes all items from a field array - */ -export function arrayRemoveAll(form: string, field: string): FormAction; - -/** - * Removes an item from the beginning of a field array - */ -export function arrayShift(form: string, field: string): FormAction; - -/** - * ADVANCED USAGE - Inserts and/or removes items from a field array. Works similarly to Array.splice. - */ -export function arraySplice(form: string, field: string, index: number, removeNum: number, value: any): FormAction; - -/** - * Swaps two items at the specified indexes in a field array - */ -export function arraySwap(form: string, field: string, indexA: number, indexB: number): FormAction; - -/** - * Inserts an item at the beginning of a field array - */ -export function arrayUnshift(form: string, field: string, value: any): FormAction; - -/** - * Saves the value to the field and sets its `autofilled` property to `true`. - */ -export function autofill(form: string, field: string, value: any): FormAction; - -/** - * Saves the value to the field - */ -export function blur(form: string, field: string, value: any): FormAction; - -/** - * Saves the value to the field - */ -export function change(form: string, field: string, value: any): FormAction; - -/** - * Destroys the form, removing all it's state - */ -export function destroy(...form: string[]): FormAction; - -/** - * Marks the given field as active and visited - */ -export function focus(form: string, field: string): FormAction; - -/** - * Sets the initial values in the form with which future data values will be compared to calculate dirty and pristine. - * The data parameter may contain deep nested array and object values that match the shape of your form fields. - * If the keepDirty parameter is true, the values of the currently dirty fields will be retained to avoid overwriting - * user edits. - */ interface InitializeOptions { keepDirty : boolean; keepSubmitSucceeded: boolean; } -export function initialize(form: string, data: any, keepDirty?: boolean | InitializeOptions, options?: InitializeOptions): FormAction; - -/** - * Registers a field with the form. - */ -export function registerField(form: string, name: string, type: FieldType): FormAction; - -/** - * Resets the values in the form back to the values past in with the most recent initialize action. - */ -export function reset(form: string): FormAction; - -/** - * Flips the asyncValidating flag true - */ -export function startAsyncValidation(form: string): FormAction; - -/** - * Flips the asyncValidating flag false and populates asyncError for each field. - */ -export function stopAsyncValidation(form: string, errors?: any): FormAction; - -export function setSubmitFailed(form: string, ...fields: string[]): FormAction; - -export function setSubmitSucceeded(form: string, ...fields: string[]): FormAction; - -/** - * Flips the submitting flag true. - */ -export function startSubmit(form: string): FormAction; - -/** - * Flips the submitting flag false and populates submitError for each field. - */ -export function stopSubmit(form: string, errors?: any): FormAction; - -/** - * Flips the asyncValidating flag false and populates asyncError for each field. - */ -export function stopAsyncValidation(form: string, errors?: any): FormAction; - -/** - * Triggers a submission of the specified form. - */ -export function submit(form: string): FormAction; - -/** - * Marks all the fields passed in as touched. - */ -export function touch(form: string, ...fields: string[]): FormAction; - -/** - * Unregisters a field with the form. - */ -export function unregisterField(form: string, name: string): FormAction; - -/** - * Resets the 'touched' flag for all the fields passed in. - */ -export function untouch(form: string, ...fields: string[]): FormAction; - -export function updateSyncErrors(from: string, syncErrors: FormErrors, error: any): FormAction; - -export function updateSyncWarnings(form: string, syncWarnings: FormWarnings, warning: any): FormAction; +declare function initialize(form: string, data: any, keepDirty?: boolean | InitializeOptions, options?: InitializeOptions): FormAction; +declare function registerField(form: string, name: string, type: FieldType): FormAction; +declare function reset(form: string): FormAction; +declare function startAsyncValidation(form: string): FormAction; +declare function stopAsyncValidation(form: string, errors?: any): FormAction; +declare function setSubmitFailed(form: string, ...fields: string[]): FormAction; +declare function setSubmitSucceeded(form: string, ...fields: string[]): FormAction; +declare function startSubmit(form: string): FormAction; +declare function stopSubmit(form: string, errors?: any): FormAction; +declare function stopAsyncValidation(form: string, errors?: any): FormAction; +declare function submit(form: string): FormAction; +declare function touch(form: string, ...fields: string[]): FormAction; +declare function unregisterField(form: string, name: string): FormAction; +declare function untouch(form: string, ...fields: string[]): FormAction; +declare function updateSyncErrors(from: string, syncErrors: FormErrors, error: any): FormAction; +declare function updateSyncWarnings(form: string, syncWarnings: FormWarnings, warning: any): FormAction; diff --git a/types/redux-form/lib/formValueSelector.d.ts b/types/redux-form/lib/formValueSelector.d.ts new file mode 100644 index 0000000000..579b62b049 --- /dev/null +++ b/types/redux-form/lib/formValueSelector.d.ts @@ -0,0 +1,6 @@ +import { FormStateMap } from "redux-form"; + +declare function formValueSelector( + form: string, + getFormState?: (state: State) => FormStateMap +): (state: State, ...field: string[]) => any; diff --git a/types/redux-form/lib/formValues.d.ts b/types/redux-form/lib/formValues.d.ts new file mode 100644 index 0000000000..fe389e1dff --- /dev/null +++ b/types/redux-form/lib/formValues.d.ts @@ -0,0 +1,13 @@ +import { ComponentClass, ComponentType } from "react"; +import { InjectedFormProps } from "redux-form"; + +declare function formValues< + Values, + P = {} +>(obj: Values): (component: ComponentType

) => ComponentClass

; + +declare function formValues< + FormData = {}, + K extends keyof FormData = keyof FormData, + P = {} +>(...names: K[]): (component: ComponentType

>) => ComponentClass

>; diff --git a/types/redux-form/lib/reducer.d.ts b/types/redux-form/lib/reducer.d.ts index f1dc6315bf..41e077ce56 100644 --- a/types/redux-form/lib/reducer.d.ts +++ b/types/redux-form/lib/reducer.d.ts @@ -2,13 +2,6 @@ import { Action, Reducer } from "redux"; import { FieldType } from "../index"; export interface FormReducer extends Reducer { - /** - * Returns a form reducer that will also pass each action through - * additional reducers specified. The parameter should be an object mapping - * from formName to a (state, action) => nextState reducer. The state - * passed to each reducer will only be the slice that pertains to that - * form. - */ plugin(reducers: FormReducerMapObject): Reducer; } @@ -18,10 +11,6 @@ export interface FormReducerMapObject { [formName: string]: Reducer; } -/** - * Store state - */ - export interface FormStateMap { [formName: string]: FormState; } diff --git a/types/redux-form/lib/reduxForm.d.ts b/types/redux-form/lib/reduxForm.d.ts index f1eac8d928..3f4a615d19 100644 --- a/types/redux-form/lib/reduxForm.d.ts +++ b/types/redux-form/lib/reduxForm.d.ts @@ -1,571 +1,140 @@ import { Component, ComponentClass, + ComponentType, ReactElement, SyntheticEvent, - ReactEventHandler, - StatelessComponent + StatelessComponent, + FormEventHandler } from "react"; import { Dispatch } from "redux"; -import { DataShape, FieldValue, FormErrors, FormWarnings, RegisteredFieldState, ComponentConstructor } from "../index"; +import { + FormErrors, + ErrorOther, + FormWarnings, + WarningOther, + RegisteredFieldState, + FormStateMap +} from "redux-form"; -export function reduxForm( - config: Config -): FormDecorator; +export type FormSubmitHandler = + (values: Partial, dispatch: Dispatch, props: P) => void | FormErrors | Promise; -export function reduxForm( - config: Config -): FormDecorator; - -export function reduxForm( - config: Config -): FormDecorator; - -/** - * This is not entirely correct but Typescript expect input and output for decorators to be the same type. - * Because of that, React HoCs can't be fully defined. https://www.typescriptlang.org/docs/handbook/decorators.html - */ -export interface FormDecorator { - >>(component: T): T; +export interface SubmitHandler { + (handler: FormSubmitHandler): FormEventHandler; + (event: SyntheticEvent): void; } -export interface Config { - /** - * the name of your form and the key to where your form's state will be - * mounted under the redux-form reducer - */ - form?: string; - - /** - * field names for which onBlur should trigger a call to the asyncValidate - * function. Defaults to []. - * - * See Asynchronous Blur Validation Example for more details. - */ - asyncBlurFields?: string[]; - - /** - * a function that takes all the form values, the dispatch function, and - * the props given to your component, and returns a Promise that will - * resolve if the validation is passed, or will reject with an object of - * validation errors in the form { field1: , field2: }. - * - * See Asynchronous Blur Validation Example for more details. - */ - asyncValidate?(values: FormData, dispatch: Dispatch, props: P, blurredField: string): Promise; - - /** - * Whether or not to automatically destroy your form's state in the Redux - * store when your component is unmounted. Defaults to true. - */ - destroyOnUnmount?: boolean; - - /** - * Reinitialize the form every time the initialValues prop changes. - * Defaults to false. - */ - enableReinitialize?: boolean; - - /** - * Whether or not to force unregistration of fields -- use in conjunction - * with destroyOnUnmount. Useful for wizard-type forms where you want to destroy - * fields as they unmount, but not the form's state. Defaults to false, as forms - * are normally unregistered on unmount. - */ - forceUnregisterOnUnmount?: boolean; - - /** - * A function that takes the entire Redux state and returns the state slice - * which corresponds to where the redux-form reducer was mounted. This - * functionality is rarely needed, and defaults to assuming that the reducer - * is mounted under the "form" key. - */ - getFormState?(state: S): any; - - /** - * When set to true and enableReinitialize is also set, the form will retain the value of dirty fields when - * reinitializing. When this option is not set (the default), reinitializing the form replaces all field values. - * This option is useful in situations where the form has live updates or continues to be editable after - * form submission; it prevents reinitialization from overwriting user changes. Defaults to false. - */ - keepDirtyOnReinitialize?: boolean; - - /** - * The values with which to initialize your form in componentWillMount(). - * Particularly useful when Editing Multiple Records, but can also be used - * with single-record forms. The values should be in the form - * { field1: 'value1', field2: 'value2' }. - */ - initialValues?: Partial; - - /** - * A callback function that will be called with all the form values any time - * any of the form values change. - */ - onChange?: (values: any) => void; - - /** - * The function to call with the form data when the handleSubmit() is fired - * from within the form component. If you do not specify it as a prop here, - * you must pass it as a parameter to handleSubmit() inside your form - * component. - */ - onSubmit?: SubmitHandler; - - /** - * A callback function that will be called when a submission fails for whatever reason. - * - * @param errors The errors that caused the submission to fail. - * @param dispatch The Redux `dispatch` function. - * @param submitError The error object that caused the submission to fail. If `errors` is set this will be most - * likely a `SubmissionError`, otherwise it can be any error or null. - * @param props The props passed into your decorated component. - */ - onSubmitFail?(errors: FormErrors, dispatch: Dispatch, submitError: any, props: P): void; - - /** - * A callback function that will be called when a submission succeeds. - * - * @param result Any result that onSubmit has returned - * @param dispatch The Redux dispatch function - * @param props The props passed into your decorated component - */ - onSubmitSuccess?(result: any, dispatch: Dispatch, props: P): void; - - /** - * If specified, all the props normally passed into your decorated - * component directly will be passed under the key specified. Useful if - * using other decorator libraries on the same component to avoid prop - * namespace collisions. - */ - propNamespace?: string; - - /** - * If true, implements `shouldComponentUpdate` and shallowly compares _only_ - * the Redux-connected props that are needed to manage the form state. This - * prevents unnecessary updates, but assumes the component is a "pure" - * component and does not rely on any input or state other than its props and - * the selected Redux store's state. Defaults to true. - */ - pure?: boolean; - - /** - * An optional function you may provide to have full control over when sync validation happens. - */ - shouldValidate?(params: ValidateCallback): boolean; - - /** - * An optional function you may provide to have full control over when async - * validation happens. - */ - shouldAsyncValidate?(params: AsyncValidateCallback): boolean; - - /** - * marks fields as touched when the blur action is fired. Defaults to true. - */ - touchOnBlur?: boolean; - - /** - * marks fields as touched when the change action is fired. Defaults to - * false. - */ - touchOnChange?: boolean; - - /** - * Do not remove submit errors when the change action is fired. Defaults to false. - */ - persistentSubmitErrors?: boolean; - - /** - * a synchronous validation function that takes the form values and props - * passed into your component. If validation passes, it should return {}. - * If validation fails, it should return the validation errors in the form - * { field1: , field2: }. - * Defaults to (values, props) => ({}). - */ - validate?(values: FormData, props: FormProps & P): FormErrors; - - /** - * A synchronous warning function that takes the form values and props passed into your component. - * Warnings work the same as validations, but do not mark a form as invalid. If the warning check passes, - * it should return {}. If the check fails, it should return the warnings in the form - * { field1: , field2: }. Defaults to (values, props) => ({}). - */ - warn?(values: FormData, props: FormProps & P): FormWarnings; -} - -/** - * If your onSubmit function returns a promise, the submitting property will be set to true - * until the promise has been resolved or rejected. If it is rejected with a redux-form - * SubmissionError containing errors in the form { field1: 'error', field2: 'error' } then - * the submission errors will be added to each field (to the error prop) just like async - * validation errors are. If there is an error that is not specific to any field, but applicable - * to the entire form, you may pass that as if it were the error for a field called _error, - * and it will be given as the error prop. - */ -export interface SubmitHandler { - (values: FormData, dispatch: Dispatch, props: FormProps & P): void | FormErrors | Promise; -} - -interface ValidateCallback { - /** - * The values. - */ +export interface ValidateCallback { values: FormData; - - /** - * The next props. - */ - nextProps: any; - - /** - * The current props. - */ - props: any; - - /** - * true if the form is being initially rendered. - */ + nextProps: P & InjectedFormProps; + props: P & InjectedFormProps; initialRender: boolean; - - /** - * The structure object being used internally for values. You may wish to use 'deepEqual' from the structure. - */ structure: any; } -interface AsyncValidateCallback { - /** - * Any existing asynchronous validation errors - */ +export interface AsyncValidateCallback { asyncErrors?: FormErrors; - - /** - * true if the form has ever been initialized with initial values - */ initialized: boolean; - - /** - * The reason to possibly run async validation. It will either be: 'blur' or - * 'submit', depending on whether an async blur field had triggered the async - * validation or if submitting the form has triggered it, respectively. - */ trigger: "blur" | "submit"; - - /** - * The name of the field that has triggered the async validation. May be undefined. - */ blurredField?: string; - - /** - * true if the form is pristine, false if it is dirty - */ pristine: boolean; - - /** - * true if synchronous validation is passing, false if it is failing. - */ syncValidationPasses: boolean; } -/** - * A throwable error that is used to return submit validation errors from onSubmit. - * The purpose being to distinguish promise rejection because of validation errors - * from promise rejection because of AJAX I/O problems or other server errors. - */ -export class SubmissionError extends Error { - errors: FormErrors; - - constructor(errors?: FormErrors); +export interface InjectedArrayProps { + insert(field: string, index: number, value: any): void; + move(field: string, from: number, to: number): void; + pop(field: string): void; + push(field: string, value: any): void; + remove(field: string, index: number): void; + removeAll(field: string): void; + shift(field: string): void; + splice(field: string, index: number, removeNum: number, value: any): void; + swap(field: string, indexA: number, indexB: number): void; + unshift(field: string, value: any): void; } -/** - * The following are methods or properties that you can access on an instance - * of your decorated form component (outermost component named "ReduxForm"). - */ -export interface FormComponent extends ComponentClass

{ - /** - * true if the form data has changed from its initialized values. Opposite - * of pristine. - */ - dirty: boolean; - - /** - * true if the form has validation errors. Opposite of valid. - */ - invalid: boolean; - - /** - * true if the form data is the same as its initialized values. Opposite - * of dirty. - */ - pristine: boolean; - - /** - * An array of objects with fields `name` and `type` for each field - * representing all the fields in the form. Mainly useful for testing. - */ - registeredFields: RegisteredFieldState[]; - - /** - * Resets all the values in the form to the initialized state, making it - * pristine again. - */ - reset(): void; - - /** - * Submits the form. Returns a promise that will be resolved when the form - * is submitted successfully, or rejected if the submission fails. - */ - submit(): Promise; - - /** - * true if the form passes validation (has no validation errors). Opposite - * of invalid. - */ - valid: boolean; - - /** - * The current values of all the fields in the form. - */ - values: FormData; - - /** - * A reference to the instance of the component you decorated with reduxForm(). - * Mainly useful for testing. - */ - wrappedInstance: ReactElement

> -} - -/** - * These are the props that will be passed to your form component. - * Your form component's props can extend this interface if you want - * to use strict checks. - */ -export interface StrictFormProps { - /** - * true if any of the fields have been marked as touched, false otherwise. - */ +export interface InjectedFormProps { anyTouched: boolean; - - /** - * A set of pre-bound action creators for you to operate on array fields in your form. - */ - array: { - /** - * Inserts a value into the given array field in your form. - */ - insert(field: string, index: number, value: FieldValue): void; - - /** - * Moves a value at the given from index to the given to index in - * the given array field in your form. - */ - move(field: string, from: number, to: number): void; - - /** - * Pops a value off of the end of a given array field in your form. - */ - pop(field: string): void; - - /** - * Pushes the given value onto the end of the given array field in your form. - */ - push(field: string, value: FieldValue): void; - - /** - * Removes a value at the given index from the given array field in your form. - */ - remove(field: string, index: number): void; - - /** - * Removes all the values from the given array field in your form. - */ - removeAll(field: string): void; - - /** - * Shifts a value out of the beginning of the given array in your form. - */ - shift(field: string): void; - - /** - * Performs an Array.splice operation on the given array in your form. - */ - splice(field: string, index: number, removeNum: number, value: FieldValue): void; - - /** - * Swaps two values at the given indexes of the given array field in your form. - */ - swap(field: string, indexA: number, indexB: number): void; - - /** - * Unshifts the given value into the beginning of the given array field in your form. - */ - unshift(field: string, value: FieldValue): void; - } - - /** - * A function that may be called to initiate asynchronous validation if - * asynchronous validation is enabled. - */ + array: InjectedArrayProps; asyncValidate: () => void; - - /** - * This value will be either: - * - false - No asynchronous validation is currently happening - * - true - Asynchronous validation is currently running in preparation to submit a form - * - a string - The name of the field that just blurred to trigger asynchronous validation - */ asyncValidating: string | boolean; - - /** - * Sets the value and marks the field as autofilled in the Redux Store. This is useful when a field - * needs to be set programmatically, but in a way that lets the user know (via a styling change using - * the autofilled prop in Field) that it has been autofilled for them programmatically. - */ - autofill(field: string, value: FieldValue): void; - - /** - * Marks a field as blurred in the Redux store. - */ - blur(field: string, value: FieldValue): void; - - /** - * Changes the value of a field in the Redux store. - */ - change(field: string, value: FieldValue): void; - - /** - * Clear async error of a field in the Redux store. - */ + autofill(field: string, value: any): void; + blur(field: string, value: any): void; + change(field: string, value: any): void; clearAsyncError(field: string): void; - - /** - * Destroys the form state in the Redux store. By default, this will be - * called for you in componentWillUnmount(). - */ destroy(): void; - - /** - * true if the form data has changed from its initialized values. Opposite - * of pristine. - */ dirty: boolean; - - /** - * A generic error for the entire form given by the _error key in the - * result from the synchronous validation function, the asynchronous - * validation, or the rejected promise from onSubmit. - */ error: string; - - /** - * The form name that you gave to the reduxForm() decorator or the prop you - * passed in to your decorated form component. - */ form: string; - - /** - * A function meant to be passed to or to - * - -

- - ); + ) } -// Decorate with reduxForm(). It will read the initialValues prop provided by connect() -const DecoratedInitializeFromStateFormFunction = reduxForm({ - form: 'initializeFromState' // a unique identifier for this form -})(InitializeFromStateFormFunction) +type TestProps = {} & InjectedFormProps; +const Test = reduxForm({ + form : "test" +})( + class Test extends Component { -// You have to connect() to any reducers that you wish to connect to yourself -const ConnectedDecoratedInitializeFromStateFormFunction = connect( - state => ({ - initialValues: state.account.data // pull initial values from account reducer - }), -)(DecoratedInitializeFromStateFormFunction); + handleSubmitForm = (values: Partial, dispatch: Dispatch, props: TestProps) => {}; -// React ComponentClass instead of StatelessComponent + handleSubmitFormAny = (event: any) => {}; -class InitializeFromStateFormClass extends React.Component> { - render() { - return InitializeFromStateFormFunction(this.props); + render() { + const { handleSubmit } = this.props; + + return ( +
+
+ + + + + + + + + + + + + + + + null } + /> + + null } + foo="bar" + /> + + + + + + +
+ ) + } } -} - -// Decorate with reduxForm(). It will read the initialValues prop provided by connect() -const DecoratedInitializeFromStateFormClass = reduxForm({ - form: 'initializeFromState' // a unique identifier for this form -})(InitializeFromStateFormClass); - -// You have to connect() to any reducers that you wish to connect to yourself -const mapStateToProps = (state: any) => ({ - initialValues: { firstName: state.account.data.firstName } // pull initial values from account reducer -} as {initialValues?: Partial}); -const ConnectedDecoratedInitializeFromStateFormClass = connect(mapStateToProps)(DecoratedInitializeFromStateFormClass); - -class ImmutableCustomField extends Component { - render() { - const F = ImmutableField as new () => GenericField; - return ; - } -} - -@immutableReduxForm({ - form: 'myForm' -}) -class MyImmutableForm extends Component { - render() { - return ( -
- - -
- ); - } -} +); reducer({}, { - type: 'ACTION' + type: "ACTION" }); reducer.plugin({ - myform: (state: any, action: FormAction) => { - if (action.type === actionTypes.CHANGE && action.meta.form === 'securitySettings') { + myForm: (state: any, action: FormAction) => { + if (action.type === actionTypes.CHANGE && action.meta.form === "securitySettings") { return { ...state, values: { diff --git a/types/redux-form/tsconfig.json b/types/redux-form/tsconfig.json index 625f4b9492..eea8fb4b64 100644 --- a/types/redux-form/tsconfig.json +++ b/types/redux-form/tsconfig.json @@ -22,6 +22,19 @@ "files": [ "index.d.ts", "redux-form-tests.tsx", - "immutable/index.d.ts" + "immutable/index.d.ts", + "lib/actions.d.ts", + "lib/actionTypes.d.ts", + "lib/Field.d.ts", + "lib/Fields.d.ts", + "lib/FieldArray.d.ts", + "lib/Form.d.ts", + "lib/FormSection.d.ts", + "lib/formValues.d.ts", + "lib/formValueSelector.d.ts", + "lib/reducer.d.ts", + "lib/reduxForm.d.ts", + "lib/selectors.d.ts", + "lib/SubmissionError.d.ts" ] } diff --git a/types/redux-form/v6/index.d.ts b/types/redux-form/v6/index.d.ts new file mode 100644 index 0000000000..8a51117530 --- /dev/null +++ b/types/redux-form/v6/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for redux-form 6.6 +// Project: https://github.com/erikras/redux-form +// Definitions by: Carson Full , Daniel Lytkin , Karol Janyst , Luka Zakrajsek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { + ComponentClass, + StatelessComponent, + ReactElement +} from "react"; + +export type FieldValue = any; + +export type FieldType = "Field" | "FieldArray"; + +export interface DataShape { + [fieldName: string]: FieldValue +} + +export type FormErrors = { + [P in keyof FormData]?: ReactElement | string | { _error?: string }; +}; + +export type FormWarnings = { + [P in keyof FormData]?: ReactElement | string | { _warning?: string }; +}; + +/** + * A component class or stateless function component. + * Workaround for: ComponentClass

| SFC

which does + * not resolve due to a bug in TypeScript. + * https://github.com/Microsoft/TypeScript/pull/8674 + */ +export type ComponentConstructor

= ComponentClass

| StatelessComponent

; + +export * from "./lib/reduxForm"; +export * from "./lib/Field"; +export * from "./lib/Fields"; +export * from "./lib/FieldArray"; +export * from "./lib/Form"; +export * from "./lib/FormSection"; +export * from "./lib/actions"; +export * from "./lib/actionTypes"; +export * from "./lib/reducer"; +export * from "./lib/selectors"; diff --git a/types/redux-form/v6/lib/Field.d.ts b/types/redux-form/v6/lib/Field.d.ts new file mode 100644 index 0000000000..ecef15b4c7 --- /dev/null +++ b/types/redux-form/v6/lib/Field.d.ts @@ -0,0 +1,333 @@ +import { + Component, + ReactElement, + ChangeEvent, + DragEvent, + FocusEvent +} from "react"; +import { Dispatch } from "redux"; +import { ComponentConstructor, DataShape, FieldValue } from "../index"; + +/** + * These are the props to give to `Field`. + * Any others will be passed through to your component. + */ +interface BaseFieldProps { + /** + * A string path, in dot-and-bracket notation, corresponding to a value + * in the form values. It may be as simple as 'firstName' or as complicated + * as contact.billing.address[2].phones[1].areaCode. + * + * Required but made optional so interface can be used on decorated components. + */ + name?: string; + + /** + * A Component, stateless function, or string corresponding to a default + * JSX element. + * + * Required but made optional so interface can be used on decorated components. + */ + component?: ComponentConstructor | "input" | "select" | "textarea", + + /** + * Formats the value from the Redux store to be displayed in the field input. + * Common use cases are to format Numbers into currencies or Dates into a + * localized date format. + */ + format?: Formatter | null; + + /** + * A function to convert whatever value the user has entered into the value that you + * want stored in the Redux store for the field. + * + * For instance, if you want the value to be in all uppercase, you would pass + * value => value.toUpperCase() + */ + normalize?: Normalizer; + + /** + * Don't use. + */ + props?: any; + + /** + * Parses the value given from the field input component to the type that you want + * stored in the Redux store. Common use cases are to parse currencies into Numbers into + * currencies or localized date formats into Dates. + */ + parse?: Parser; + + /** + * Allows you to to provide a field-level validation rule. The function will be given the + * current value of the field and all the other form values. If the field is valid, it + * should return `undefined`, if the field is invalid, it should return an error + * (usually, but not necessarily, a `String`). + */ + validate?: Validator | Validator[]; + + /** + * Allows you to to provide a field-level warning rule. The function will be given the + * current value of the field and all the other form values. If the field needs a warning, + * it should return the warning (usually, but not necessarily, a `String`). If the field + * does not need a warning, it should return `undefined`. + */ + warn?: Validator | Validator[]; + + /** + * If true, the rendered component will be available with the + * getRenderedComponent() method. Defaults to false. Cannot be used if your + * component is a stateless function component. + */ + withRef?: boolean; +} + +/** + * @param value The value entered by the user. + * @param previousValue The previous value for the field. + * @param allValues All the values in the entire form with the new value. + * This will be an Immutable Map if you are using Immutable JS. + * @param previousAllValues All the values in the entire form before the current change. + * This will be an Immutable Map if you are using Immutable JS. + */ +export type Normalizer = (value: FieldValue, previousValue?: FieldValue, allValues?: any, previousAllValues?: any) => FieldValue; + +export type Formatter = (value: FieldValue, name: string) => FieldValue; + +export type Parser = (value: FieldValue, name: string) => FieldValue; + +export type Validator = (value: FieldValue, allValues?: any, props?: any) => any; + +/** + * Declare Field as this interface to specify the generic. + */ +export interface GenericField extends Component { + /** + * true if the current value is different from the initialized value, + * false otherwise. + */ + dirty: boolean; + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if the current value is the same as the initialized value, + * false otherwise. + */ + pristine: boolean; + + /** + * The current value of the field. + */ + value: FieldValue; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component & FieldCustomProps>; +} + +/** + * The Field Instance API. + */ +export class Field extends Component implements GenericField { + /** + * true if the current value is different from the initialized value, + * false otherwise. + */ + dirty: boolean; + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if the current value is the same as the initialized value, + * false otherwise. + */ + pristine: boolean; + + /** + * The current value of the field. + */ + value: FieldValue; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component; +} + +/** + * These are props that `Field` will pass to your wrapped component (not including custom props). + */ +interface WrappedFieldProps { + /** + * An object containing all the props that you will normally want to pass to + * your input component. + */ + input?: WrappedFieldInputProps; + + /** + * An object containing all the metadata props. + */ + meta: WrappedFieldMetaProps; +} + +/** + * These props are meant to be destructured into your component. + */ +interface EventOrValueHandler { + (event: Event): void; + (value: FieldValue, newValue: FieldValue, previousValue: FieldValue): void; +} + +interface WrappedFieldInputProps { + /** + * An alias for value only when value is a boolean. Provided for + * convenience of destructuring the whole field object into the props of a + * form element. + */ + checked?: boolean; + + /** + * The name prop passed in. + */ + name: string; + + /** + * A function to call when the form field loses focus. + */ + onBlur: EventOrValueHandler>; + + /** + * A function to call when the form field is changed. + */ + onChange: EventOrValueHandler>; + + /** + * A function to call when the form field receives a 'dragStart' event. + * Saves the field value in the event for giving the field it is dropped + * into. + */ + onDragStart: EventOrValueHandler>; + + /** + * A function to call when the form field receives a drop event. + */ + onDrop: EventOrValueHandler>; + + /** + * A function to call when the form field receives focus. + */ + onFocus: EventOrValueHandler>; + + /** + * The value of this form field. It will be a boolean for checkboxes, and + * a string for all other input types. If there is no value in the Redux + * state for this field, it will default to ''. This is to + * ensure that the input is controlled. + */ + value: FieldValue; +} + +/** + * These props are metadata about the state of this field that redux-form is tracking for you. + */ +interface WrappedFieldMetaProps { + + /** + * true if this field currently has focus. It will only work if you are + * passing onFocus to your input element. + */ + active?: boolean; + + /** + * true if this field has been set with the AUTOFILL action and has not since been changed + * with a CHANGE action. This is useful to render the field in a way that the user can tell + * that the value was autofilled for them. + */ + autofilled: boolean; + + /** + * true if the form is currently running asynchronous validation because this + * field was blurred. + */ + asyncValidating: boolean; + + /** + * true if the field value has changed from its initialized value. + * Opposite of pristine. + */ + dirty: boolean; + + /** + * The Redux dispatch function. + */ + dispatch: Dispatch; + + /** + * The error for this field if its value is not passing validation. Both + * synchronous, asynchronous, and submit validation errors will be reported here. + */ + error?: any; + + /** + * The name of the form. Could be useful if you want to manually dispatch actions. + */ + form?: string; + + /** + * true if the field value fails validation (has a validation error). + * Opposite of valid. + */ + invalid: boolean; + + /** + * true if the field value is the same as its initialized value. Opposite + * of dirty. + */ + pristine: boolean; + + /** + * true if the field is currently being submitted + */ + submitting?: boolean; + + /** + * true if the form had onSubmit called and failed to submit for any reason. + * A subsequent successful submit will set it back to false. + */ + submitFailed?: boolean; + + /** + * true if the field has been touched. By default this will be set when + * the field is blurred. + */ + touched: boolean; + + /** + * true if the field value passes validation (has no validation errors). + * Opposite of invalid. + */ + valid: boolean; + + /** + * true if this field has ever had focus. It will only work if you are + * passing onFocus to your input element. + */ + visited?: boolean; + + /** + * The warning for this field if its value is not passing warning validation. + */ + warning?: any; +} diff --git a/types/redux-form/v6/lib/FieldArray.d.ts b/types/redux-form/v6/lib/FieldArray.d.ts new file mode 100644 index 0000000000..9629eecb27 --- /dev/null +++ b/types/redux-form/v6/lib/FieldArray.d.ts @@ -0,0 +1,217 @@ +import { Component } from "react"; +import { ComponentConstructor, Validator } from "../index"; + +/** + * These are the props to give to `FieldArray`. + * Any others will be passed through to your component. + */ +interface BaseFieldArrayProps { + /** + * A string path, in dot-and-bracket notation, corresponding to a value + * in the form values. It may be as simple as 'firstName' or as complicated + * as contact.billing.address[2].phones[1].areaCode. + * + * Required but made optional so interface can be used on decorated components. + */ + name?: string; + + /** + * A Component or stateless function to render the field array. + * + * Required but made optional so interface can be used on decorated components. + */ + component?: ComponentConstructor, + + /** + * Allows you to to provide a field-level validation rule. The function will be given the + * current value of the field and all the other form values. If the field is valid, it + * should return `undefined`, if the field is invalid, it should return an error + * (usually, but not necessarily, a `String`). + */ + validate?: Validator | Validator[]; + + /** + * Allows you to to provide a field-level warning rule. The function will be given the + * current value of the field and all the other form values. If the field needs a warning, + * it should return the warning (usually, but not necessarily, a `String`). If the field + * does not need a warning, it should return `undefined`. + */ + warn?: Validator | Validator[]; + + /** + * If true, the rendered component will be available with the + * getRenderedComponent() method. Defaults to false. Cannot be used if your + * component is a stateless function component. + */ + withRef?: boolean; + + props?: any; +} + +/** + * Declare FieldArray as this interface to specify the generics. + */ +export interface GenericFieldArray extends Component { + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if this field passes validation, false otherwise. + */ + valid: boolean; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component & FieldCustomProps>; +} + +/** + * The FieldArray Instance API. + */ +export class FieldArray extends Component implements GenericFieldArray { + + /** + * The name prop that you passed in. + */ + name: string; + + /** + * true if this field passes validation, false otherwise. + */ + valid: boolean; + + /** + * Returns the instance of the rendered component. For this to work, you must + * provide a withRef prop, and your component must not be a stateless function + * component. + */ + getRenderedComponent(): Component; +} + +/** + * These are props that `FieldArray` will pass to your wrapped component. + */ +interface WrappedFieldArrayProps { + fields: FieldsProps; + meta: FieldArrayMetaProps; +} + +interface FieldsProps { + /** + * A method to iterate over each value of the array. + */ + forEach(callback: (name: string, index: number, fields: FieldsProps) => void): void; + + /** + * A method to get a single value from the array value. + */ + get(index: number): T; + + /** + * A method to get all the values in the array. + */ + getAll(): T[]; + + /** + * A function to insert a new value into the array at any arbitrary index. + */ + insert(index: number, value: T): void; + + /** + * The current length of the array. + */ + length: number; + + /** + * A method to iterate over each value of the array. Returns an array of the + * results of each call to the callback. + */ + map(callback: (name: string, index: number, fields: FieldsProps) => any): any; + + /** + * Removes an item from the end of the array. Returns the item removed. + */ + pop(): T; + + /** + * Adds a value to the end of the array. + */ + push(value: T): void; + + /** + * Removes an item from the array at an arbitrary index. + */ + remove(index: number): void; + + /** + * Removes an item from beginning of the array. Returns the item removed. + */ + shift(): T; + + /** + * Swaps two items in the array at the given indexes. + */ + swap(indexA: number, indexB: number): void; + + /** + * Adds an item to the beginning of the array. + */ + unshift(value: T): void; +} + +interface FieldArrayMetaProps { + /** + * true if the any of the fields in the field array have changed from their + * initialized value. Opposite of pristine. + */ + dirty: boolean; + + /** + * The error for this field array if its value is not passing validation. Both + * synchronous, asynchronous, and submit validation errors will be reported here. + * Array-specific errors should be returned from the validation function as an + * _error key on the array. + */ + error?: string; + + /** + * Name of your form provided to `reduxForm()` as the `form` config property. + */ + form: string; + + /** + * true if the field array value fails validation (has a validation error). + * Opposite of valid. + */ + invalid: boolean; + + /** + * true if the all of the fields in the field array are the same as their + * initialized value. Opposite of dirty. + */ + pristine: boolean; + + /** + * true if any of the fields have been touched. + */ + touched: boolean; + + /** + * true if the field value passes validation (has no validation errors). + * Opposite of invalid. + */ + valid: boolean; + + /** + * The warning for this field array if its values are not passing warning validation. + * Array-specific errors should be returned from the validation function as an + * `_warning` key on the array. + */ + warning?: string; +} diff --git a/types/redux-form/v6/lib/Fields.d.ts b/types/redux-form/v6/lib/Fields.d.ts new file mode 100644 index 0000000000..b2c210ba8c --- /dev/null +++ b/types/redux-form/v6/lib/Fields.d.ts @@ -0,0 +1,116 @@ +import { Component } from "react"; +import { ComponentConstructor, Formatter, Parser, FieldValue, WrappedFieldProps } from "../index"; + +/** + * These are the props to give to `Field`. + * Any others will be passed through to your component. + */ +interface BaseFieldsProps { + /** + * An array of strings (or the pseudo-array fields provided by FieldArray), + * in dot-and-bracket notation, corresponding to form values. + * They may be as simple as 'firstName' or as complicated as + * 'contact.billing.address[2].phones[1].areaCode'. + */ + names: string[]; + + /** + * A Component or stateless function that will be given all the props necessary + * to render the field inputs. + */ + component?: ComponentConstructor; + + /** + * Formats the value from the Redux store to be displayed in the field input. + * Common use cases are to format Numbers into currencies or Dates into a localized date format. + * + * format is called with the field value and name as arguments and should return the new formatted + * value to be displayed in the field input. + * + * To respect React 15 input behavior there is defaultFormat = value => value == null ? '' : value + * internally used. To disable that you can pass null as format prop. + */ + format?: Formatter | null; + + /** + * Don't use. + */ + props?: any; + + /** + * Parses the value given from the field input component to the type that you want stored in the Redux store. + * Common use cases are to parse currencies into Numbers into currencies or localized date formats into Dates. + * + * parse is called with the field value and name as arguments and should return the new parsed value to be + * stored in the Redux store. + */ + parse?: Parser; + + /** + * If true, the rendered component will be available with the getRenderedComponent() method. + * Defaults to false. Cannot be used if your component is a stateless function component. + */ + withRef?: boolean; +} + +/** + * Declare Fields as this interface to specify the generics. + */ +export interface GenericFields extends Component { + /** + * true if the current value of any of the fields is different from the initialized value, false otherwise. + */ + dirty: boolean; + + /** + * The names prop that you passed in. + */ + names: string[]; + + /** + * true if the all of the current values are the same as the initialized values, false otherwise. + */ + pristine: boolean; + + /** + * The current values of the fields. If they are nested, the values will duplicate the structure. + * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be + * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } + */ + values: { [name: string]: FieldValue }; + + getRenderedComponent(): Component; +} + +/** + * The Fields Instance API. + */ +export class Fields extends Component implements GenericFields { + /** + * true if the current value of any of the fields is different from the initialized value, false otherwise. + */ + dirty: boolean; + + /** + * The names prop that you passed in. + */ + names: string[]; + + /** + * true if the all of the current values are the same as the initialized values, false otherwise. + */ + pristine: boolean; + + /** + * The current values of the fields. If they are nested, the values will duplicate the structure. + * For example, if your names are [ 'name.first', 'name.last', 'email' ], the values will be + * { name: { first: 'John', last: 'Smith' }, email: 'john@email.com' } + */ + values: { [name: string]: FieldValue }; + + getRenderedComponent(): Component; +} + +interface WrappedFieldsProps { + [name: string]: WrappedFieldsProps & WrappedFieldProps +} diff --git a/types/redux-form/v6/lib/Form.d.ts b/types/redux-form/v6/lib/Form.d.ts new file mode 100644 index 0000000000..9339348393 --- /dev/null +++ b/types/redux-form/v6/lib/Form.d.ts @@ -0,0 +1,22 @@ +import { Component, HTMLProps, FormEvent } from "react"; +import { Dispatch } from "redux"; +import { SubmitHandler, FormProps, FormErrors } from "../index" + +interface FormSubmitHandler { + (values: any, dispatch?: Dispatch, props?: FormProps & { [prop: string]: any }): void | FormErrors | Promise; + //(e: FormEvent): void; +} + +export interface FormComponentProps extends HTMLProps { + /** + * The function to call when form submission is triggered. + */ + onSubmit: FormSubmitHandler; +} + +/** + * The Form component is a simple wrapper for the React

component that + * allows the surrounding redux-form-decorated component to trigger its + * onSubmit function. + */ +export class Form extends Component {} diff --git a/types/redux-form/v6/lib/FormSection.d.ts b/types/redux-form/v6/lib/FormSection.d.ts new file mode 100644 index 0000000000..9be46ebf80 --- /dev/null +++ b/types/redux-form/v6/lib/FormSection.d.ts @@ -0,0 +1,15 @@ +import { Component } from "react"; + +interface FormSectionProps { + /** + * The name all child fields should be prefixed with. + */ + name: string; +} + +/** + * The FormSection component makes it easy to split forms into smaller components that are resuable across + * multiple forms. It does this by prefixing the name of Field, Fields and FieldArray children, at any depth, + * with the value specified in the name prop. + */ +export class FormSection extends Component {} diff --git a/types/redux-form/v6/lib/actionTypes.d.ts b/types/redux-form/v6/lib/actionTypes.d.ts new file mode 100644 index 0000000000..ce1ba5d208 --- /dev/null +++ b/types/redux-form/v6/lib/actionTypes.d.ts @@ -0,0 +1,37 @@ +export interface ActionTypes { + ARRAY_INSERT: string; + ARRAY_MOVE: string; + ARRAY_POP: string; + ARRAY_PUSH: string; + ARRAY_REMOVE: string; + ARRAY_REMOVE_ALL: string; + ARRAY_SHIFT: string; + ARRAY_SPLICE: string; + ARRAY_UNSHIFT: string; + ARRAY_SWAP: string; + AUTOFILL: string; + BLUR: string; + CHANGE: string; + CLEAR_SUBMIT: string; + CLEAR_SUBMIT_ERRORS: string; + CLEAR_ASYNC_ERROR: string; + DESTROY: string; + FOCUS: string; + INITIALIZE: string; + REGISTER_FIELD: string; + RESET: string; + SET_SUBMIT_FAILED: string; + SET_SUBMIT_SUCCEEDED: string; + START_ASYNC_VALIDATION: string; + START_SUBMIT: string; + STOP_ASYNC_VALIDATION: string; + STOP_SUBMIT: string; + SUBMIT: string; + TOUCH: string; + UNREGISTER_FIELD: string; + UNTOUCH: string; + UPDATE_SYNC_ERRORS: string; + UPDATE_SYNC_WARNINGS: string; +} + +export const actionTypes: ActionTypes; diff --git a/types/redux-form/v6/lib/actions.d.ts b/types/redux-form/v6/lib/actions.d.ts new file mode 100644 index 0000000000..b126549f68 --- /dev/null +++ b/types/redux-form/v6/lib/actions.d.ts @@ -0,0 +1,160 @@ +import { Action } from "redux"; +import { FormErrors, FormWarnings, FieldType } from "../index"; + +export interface FormAction extends Action { + meta: { + form: string; + }; +} + +/** + * Inserts an item into a field array at the specified index + */ +export function arrayInsert(form: string, field: string, index: number, value: any): FormAction; + +/** + * Moves an item from one index in the array to another. In effect, it performs a remove and an + * insert, so the item already at the `to` position will be bumped to a higher index, not overwritten. + */ +export function arrayMove(form: string, field: string, from: number, to: number): FormAction; + +/** + * Removes an item from the end of a field array + */ +export function arrayPop(form: string, field: string): FormAction; + +/** + * Appends an item to the end of a field array + */ +export function arrayPush(form: string, field: string, value: any): FormAction; + +/** + * Removes an item at the specified index from a field array + */ +export function arrayRemove(form: string, field: string, index: number): FormAction; + +/** + * Removes all items from a field array + */ +export function arrayRemoveAll(form: string, field: string): FormAction; + +/** + * Removes an item from the beginning of a field array + */ +export function arrayShift(form: string, field: string): FormAction; + +/** + * ADVANCED USAGE - Inserts and/or removes items from a field array. Works similarly to Array.splice. + */ +export function arraySplice(form: string, field: string, index: number, removeNum: number, value: any): FormAction; + +/** + * Swaps two items at the specified indexes in a field array + */ +export function arraySwap(form: string, field: string, indexA: number, indexB: number): FormAction; + +/** + * Inserts an item at the beginning of a field array + */ +export function arrayUnshift(form: string, field: string, value: any): FormAction; + +/** + * Saves the value to the field and sets its `autofilled` property to `true`. + */ +export function autofill(form: string, field: string, value: any): FormAction; + +/** + * Saves the value to the field + */ +export function blur(form: string, field: string, value: any): FormAction; + +/** + * Saves the value to the field + */ +export function change(form: string, field: string, value: any): FormAction; + +/** + * Destroys the form, removing all it's state + */ +export function destroy(...form: string[]): FormAction; + +/** + * Marks the given field as active and visited + */ +export function focus(form: string, field: string): FormAction; + +/** + * Sets the initial values in the form with which future data values will be compared to calculate dirty and pristine. + * The data parameter may contain deep nested array and object values that match the shape of your form fields. + * If the keepDirty parameter is true, the values of the currently dirty fields will be retained to avoid overwriting + * user edits. + */ +interface InitializeOptions { + keepDirty : boolean; + keepSubmitSucceeded: boolean; +} + +export function initialize(form: string, data: any, keepDirty?: boolean | InitializeOptions, options?: InitializeOptions): FormAction; + +/** + * Registers a field with the form. + */ +export function registerField(form: string, name: string, type: FieldType): FormAction; + +/** + * Resets the values in the form back to the values past in with the most recent initialize action. + */ +export function reset(form: string): FormAction; + +/** + * Flips the asyncValidating flag true + */ +export function startAsyncValidation(form: string): FormAction; + +/** + * Flips the asyncValidating flag false and populates asyncError for each field. + */ +export function stopAsyncValidation(form: string, errors?: any): FormAction; + +export function setSubmitFailed(form: string, ...fields: string[]): FormAction; + +export function setSubmitSucceeded(form: string, ...fields: string[]): FormAction; + +/** + * Flips the submitting flag true. + */ +export function startSubmit(form: string): FormAction; + +/** + * Flips the submitting flag false and populates submitError for each field. + */ +export function stopSubmit(form: string, errors?: any): FormAction; + +/** + * Flips the asyncValidating flag false and populates asyncError for each field. + */ +export function stopAsyncValidation(form: string, errors?: any): FormAction; + +/** + * Triggers a submission of the specified form. + */ +export function submit(form: string): FormAction; + +/** + * Marks all the fields passed in as touched. + */ +export function touch(form: string, ...fields: string[]): FormAction; + +/** + * Unregisters a field with the form. + */ +export function unregisterField(form: string, name: string): FormAction; + +/** + * Resets the 'touched' flag for all the fields passed in. + */ +export function untouch(form: string, ...fields: string[]): FormAction; + +export function updateSyncErrors(from: string, syncErrors: FormErrors, error: any): FormAction; + +export function updateSyncWarnings(form: string, syncWarnings: FormWarnings, warning: any): FormAction; diff --git a/types/redux-form/v6/lib/reducer.d.ts b/types/redux-form/v6/lib/reducer.d.ts new file mode 100644 index 0000000000..f1dc6315bf --- /dev/null +++ b/types/redux-form/v6/lib/reducer.d.ts @@ -0,0 +1,49 @@ +import { Action, Reducer } from "redux"; +import { FieldType } from "../index"; + +export interface FormReducer extends Reducer { + /** + * Returns a form reducer that will also pass each action through + * additional reducers specified. The parameter should be an object mapping + * from formName to a (state, action) => nextState reducer. The state + * passed to each reducer will only be the slice that pertains to that + * form. + */ + plugin(reducers: FormReducerMapObject): Reducer; +} + +export const reducer: FormReducer; + +export interface FormReducerMapObject { + [formName: string]: Reducer; +} + +/** + * Store state + */ + +export interface FormStateMap { + [formName: string]: FormState; +} + +export interface FormState { + registeredFields: RegisteredFieldState[]; + fields?: {[name: string]: FieldState}; + values?: { [fieldName: string]: string }; + active?: string; + anyTouched?: boolean; + submitting?: boolean; + submitErrors?: { [fieldName: string]: string }; + submitFailed?: boolean; +} + +export interface RegisteredFieldState { + name: string; + type: FieldType; +} + +export interface FieldState { + active?: boolean; + touched?: boolean; + visited?: boolean; +} diff --git a/types/redux-form/v6/lib/reduxForm.d.ts b/types/redux-form/v6/lib/reduxForm.d.ts new file mode 100644 index 0000000000..f1eac8d928 --- /dev/null +++ b/types/redux-form/v6/lib/reduxForm.d.ts @@ -0,0 +1,571 @@ +import { + Component, + ComponentClass, + ReactElement, + SyntheticEvent, + ReactEventHandler, + StatelessComponent +} from "react"; +import { Dispatch } from "redux"; +import { DataShape, FieldValue, FormErrors, FormWarnings, RegisteredFieldState, ComponentConstructor } from "../index"; + +export function reduxForm( + config: Config +): FormDecorator; + +export function reduxForm( + config: Config +): FormDecorator; + +export function reduxForm( + config: Config +): FormDecorator; + +/** + * This is not entirely correct but Typescript expect input and output for decorators to be the same type. + * Because of that, React HoCs can't be fully defined. https://www.typescriptlang.org/docs/handbook/decorators.html + */ +export interface FormDecorator { + >>(component: T): T; +} + +export interface Config { + /** + * the name of your form and the key to where your form's state will be + * mounted under the redux-form reducer + */ + form?: string; + + /** + * field names for which onBlur should trigger a call to the asyncValidate + * function. Defaults to []. + * + * See Asynchronous Blur Validation Example for more details. + */ + asyncBlurFields?: string[]; + + /** + * a function that takes all the form values, the dispatch function, and + * the props given to your component, and returns a Promise that will + * resolve if the validation is passed, or will reject with an object of + * validation errors in the form { field1: , field2: }. + * + * See Asynchronous Blur Validation Example for more details. + */ + asyncValidate?(values: FormData, dispatch: Dispatch, props: P, blurredField: string): Promise; + + /** + * Whether or not to automatically destroy your form's state in the Redux + * store when your component is unmounted. Defaults to true. + */ + destroyOnUnmount?: boolean; + + /** + * Reinitialize the form every time the initialValues prop changes. + * Defaults to false. + */ + enableReinitialize?: boolean; + + /** + * Whether or not to force unregistration of fields -- use in conjunction + * with destroyOnUnmount. Useful for wizard-type forms where you want to destroy + * fields as they unmount, but not the form's state. Defaults to false, as forms + * are normally unregistered on unmount. + */ + forceUnregisterOnUnmount?: boolean; + + /** + * A function that takes the entire Redux state and returns the state slice + * which corresponds to where the redux-form reducer was mounted. This + * functionality is rarely needed, and defaults to assuming that the reducer + * is mounted under the "form" key. + */ + getFormState?(state: S): any; + + /** + * When set to true and enableReinitialize is also set, the form will retain the value of dirty fields when + * reinitializing. When this option is not set (the default), reinitializing the form replaces all field values. + * This option is useful in situations where the form has live updates or continues to be editable after + * form submission; it prevents reinitialization from overwriting user changes. Defaults to false. + */ + keepDirtyOnReinitialize?: boolean; + + /** + * The values with which to initialize your form in componentWillMount(). + * Particularly useful when Editing Multiple Records, but can also be used + * with single-record forms. The values should be in the form + * { field1: 'value1', field2: 'value2' }. + */ + initialValues?: Partial; + + /** + * A callback function that will be called with all the form values any time + * any of the form values change. + */ + onChange?: (values: any) => void; + + /** + * The function to call with the form data when the handleSubmit() is fired + * from within the form component. If you do not specify it as a prop here, + * you must pass it as a parameter to handleSubmit() inside your form + * component. + */ + onSubmit?: SubmitHandler; + + /** + * A callback function that will be called when a submission fails for whatever reason. + * + * @param errors The errors that caused the submission to fail. + * @param dispatch The Redux `dispatch` function. + * @param submitError The error object that caused the submission to fail. If `errors` is set this will be most + * likely a `SubmissionError`, otherwise it can be any error or null. + * @param props The props passed into your decorated component. + */ + onSubmitFail?(errors: FormErrors, dispatch: Dispatch, submitError: any, props: P): void; + + /** + * A callback function that will be called when a submission succeeds. + * + * @param result Any result that onSubmit has returned + * @param dispatch The Redux dispatch function + * @param props The props passed into your decorated component + */ + onSubmitSuccess?(result: any, dispatch: Dispatch, props: P): void; + + /** + * If specified, all the props normally passed into your decorated + * component directly will be passed under the key specified. Useful if + * using other decorator libraries on the same component to avoid prop + * namespace collisions. + */ + propNamespace?: string; + + /** + * If true, implements `shouldComponentUpdate` and shallowly compares _only_ + * the Redux-connected props that are needed to manage the form state. This + * prevents unnecessary updates, but assumes the component is a "pure" + * component and does not rely on any input or state other than its props and + * the selected Redux store's state. Defaults to true. + */ + pure?: boolean; + + /** + * An optional function you may provide to have full control over when sync validation happens. + */ + shouldValidate?(params: ValidateCallback): boolean; + + /** + * An optional function you may provide to have full control over when async + * validation happens. + */ + shouldAsyncValidate?(params: AsyncValidateCallback): boolean; + + /** + * marks fields as touched when the blur action is fired. Defaults to true. + */ + touchOnBlur?: boolean; + + /** + * marks fields as touched when the change action is fired. Defaults to + * false. + */ + touchOnChange?: boolean; + + /** + * Do not remove submit errors when the change action is fired. Defaults to false. + */ + persistentSubmitErrors?: boolean; + + /** + * a synchronous validation function that takes the form values and props + * passed into your component. If validation passes, it should return {}. + * If validation fails, it should return the validation errors in the form + * { field1: , field2: }. + * Defaults to (values, props) => ({}). + */ + validate?(values: FormData, props: FormProps & P): FormErrors; + + /** + * A synchronous warning function that takes the form values and props passed into your component. + * Warnings work the same as validations, but do not mark a form as invalid. If the warning check passes, + * it should return {}. If the check fails, it should return the warnings in the form + * { field1: , field2: }. Defaults to (values, props) => ({}). + */ + warn?(values: FormData, props: FormProps & P): FormWarnings; +} + +/** + * If your onSubmit function returns a promise, the submitting property will be set to true + * until the promise has been resolved or rejected. If it is rejected with a redux-form + * SubmissionError containing errors in the form { field1: 'error', field2: 'error' } then + * the submission errors will be added to each field (to the error prop) just like async + * validation errors are. If there is an error that is not specific to any field, but applicable + * to the entire form, you may pass that as if it were the error for a field called _error, + * and it will be given as the error prop. + */ +export interface SubmitHandler { + (values: FormData, dispatch: Dispatch, props: FormProps & P): void | FormErrors | Promise; +} + +interface ValidateCallback { + /** + * The values. + */ + values: FormData; + + /** + * The next props. + */ + nextProps: any; + + /** + * The current props. + */ + props: any; + + /** + * true if the form is being initially rendered. + */ + initialRender: boolean; + + /** + * The structure object being used internally for values. You may wish to use 'deepEqual' from the structure. + */ + structure: any; +} + +interface AsyncValidateCallback { + /** + * Any existing asynchronous validation errors + */ + asyncErrors?: FormErrors; + + /** + * true if the form has ever been initialized with initial values + */ + initialized: boolean; + + /** + * The reason to possibly run async validation. It will either be: 'blur' or + * 'submit', depending on whether an async blur field had triggered the async + * validation or if submitting the form has triggered it, respectively. + */ + trigger: "blur" | "submit"; + + /** + * The name of the field that has triggered the async validation. May be undefined. + */ + blurredField?: string; + + /** + * true if the form is pristine, false if it is dirty + */ + pristine: boolean; + + /** + * true if synchronous validation is passing, false if it is failing. + */ + syncValidationPasses: boolean; +} + +/** + * A throwable error that is used to return submit validation errors from onSubmit. + * The purpose being to distinguish promise rejection because of validation errors + * from promise rejection because of AJAX I/O problems or other server errors. + */ +export class SubmissionError extends Error { + errors: FormErrors; + + constructor(errors?: FormErrors); +} + +/** + * The following are methods or properties that you can access on an instance + * of your decorated form component (outermost component named "ReduxForm"). + */ +export interface FormComponent extends ComponentClass

{ + /** + * true if the form data has changed from its initialized values. Opposite + * of pristine. + */ + dirty: boolean; + + /** + * true if the form has validation errors. Opposite of valid. + */ + invalid: boolean; + + /** + * true if the form data is the same as its initialized values. Opposite + * of dirty. + */ + pristine: boolean; + + /** + * An array of objects with fields `name` and `type` for each field + * representing all the fields in the form. Mainly useful for testing. + */ + registeredFields: RegisteredFieldState[]; + + /** + * Resets all the values in the form to the initialized state, making it + * pristine again. + */ + reset(): void; + + /** + * Submits the form. Returns a promise that will be resolved when the form + * is submitted successfully, or rejected if the submission fails. + */ + submit(): Promise; + + /** + * true if the form passes validation (has no validation errors). Opposite + * of invalid. + */ + valid: boolean; + + /** + * The current values of all the fields in the form. + */ + values: FormData; + + /** + * A reference to the instance of the component you decorated with reduxForm(). + * Mainly useful for testing. + */ + wrappedInstance: ReactElement

> +} + +/** + * These are the props that will be passed to your form component. + * Your form component's props can extend this interface if you want + * to use strict checks. + */ +export interface StrictFormProps { + /** + * true if any of the fields have been marked as touched, false otherwise. + */ + anyTouched: boolean; + + /** + * A set of pre-bound action creators for you to operate on array fields in your form. + */ + array: { + /** + * Inserts a value into the given array field in your form. + */ + insert(field: string, index: number, value: FieldValue): void; + + /** + * Moves a value at the given from index to the given to index in + * the given array field in your form. + */ + move(field: string, from: number, to: number): void; + + /** + * Pops a value off of the end of a given array field in your form. + */ + pop(field: string): void; + + /** + * Pushes the given value onto the end of the given array field in your form. + */ + push(field: string, value: FieldValue): void; + + /** + * Removes a value at the given index from the given array field in your form. + */ + remove(field: string, index: number): void; + + /** + * Removes all the values from the given array field in your form. + */ + removeAll(field: string): void; + + /** + * Shifts a value out of the beginning of the given array in your form. + */ + shift(field: string): void; + + /** + * Performs an Array.splice operation on the given array in your form. + */ + splice(field: string, index: number, removeNum: number, value: FieldValue): void; + + /** + * Swaps two values at the given indexes of the given array field in your form. + */ + swap(field: string, indexA: number, indexB: number): void; + + /** + * Unshifts the given value into the beginning of the given array field in your form. + */ + unshift(field: string, value: FieldValue): void; + } + + /** + * A function that may be called to initiate asynchronous validation if + * asynchronous validation is enabled. + */ + asyncValidate: () => void; + + /** + * This value will be either: + * - false - No asynchronous validation is currently happening + * - true - Asynchronous validation is currently running in preparation to submit a form + * - a string - The name of the field that just blurred to trigger asynchronous validation + */ + asyncValidating: string | boolean; + + /** + * Sets the value and marks the field as autofilled in the Redux Store. This is useful when a field + * needs to be set programmatically, but in a way that lets the user know (via a styling change using + * the autofilled prop in Field) that it has been autofilled for them programmatically. + */ + autofill(field: string, value: FieldValue): void; + + /** + * Marks a field as blurred in the Redux store. + */ + blur(field: string, value: FieldValue): void; + + /** + * Changes the value of a field in the Redux store. + */ + change(field: string, value: FieldValue): void; + + /** + * Clear async error of a field in the Redux store. + */ + clearAsyncError(field: string): void; + + /** + * Destroys the form state in the Redux store. By default, this will be + * called for you in componentWillUnmount(). + */ + destroy(): void; + + /** + * true if the form data has changed from its initialized values. Opposite + * of pristine. + */ + dirty: boolean; + + /** + * A generic error for the entire form given by the _error key in the + * result from the synchronous validation function, the asynchronous + * validation, or the rejected promise from onSubmit. + */ + error: string; + + /** + * The form name that you gave to the reduxForm() decorator or the prop you + * passed in to your decorated form component. + */ + form: string; + + /** + * A function meant to be passed to or to + * + + + + ); +} + +// Decorate with reduxForm(). It will read the initialValues prop provided by connect() +const DecoratedInitializeFromStateFormFunction = reduxForm({ + form: 'initializeFromState' // a unique identifier for this form +})(InitializeFromStateFormFunction) + +// You have to connect() to any reducers that you wish to connect to yourself +const ConnectedDecoratedInitializeFromStateFormFunction = connect( + state => ({ + initialValues: state.account.data // pull initial values from account reducer + }), +)(DecoratedInitializeFromStateFormFunction); + +// React ComponentClass instead of StatelessComponent + +class InitializeFromStateFormClass extends React.Component> { + render() { + return InitializeFromStateFormFunction(this.props); + } +} + +// Decorate with reduxForm(). It will read the initialValues prop provided by connect() +const DecoratedInitializeFromStateFormClass = reduxForm({ + form: 'initializeFromState' // a unique identifier for this form +})(InitializeFromStateFormClass); + +// You have to connect() to any reducers that you wish to connect to yourself +const mapStateToProps = (state: any) => ({ + initialValues: { firstName: state.account.data.firstName } // pull initial values from account reducer +} as {initialValues?: Partial}); +const ConnectedDecoratedInitializeFromStateFormClass = connect(mapStateToProps)(DecoratedInitializeFromStateFormClass); + +reducer({}, { + type: 'ACTION' +}); + +reducer.plugin({ + myform: (state: any, action: FormAction) => { + if (action.type === actionTypes.CHANGE && action.meta.form === 'securitySettings') { + return { + ...state, + values: { + ...state.values, + downloadLinkAutoPassword: true, + }, + }; + } else { + return state; + } + } +}); diff --git a/types/redux-form/v6/tsconfig.json b/types/redux-form/v6/tsconfig.json new file mode 100644 index 0000000000..1903e7055b --- /dev/null +++ b/types/redux-form/v6/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "experimentalDecorators": true, + "noImplicitAny": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "strictNullChecks": true, + "jsx": "react", + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "redux-form": ["redux-form/v6"], + "redux-form/*": ["redux-form/v6/*"] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "redux-form-tests.tsx" + ] +} From ca2ddc81136af7fb3d34962624ac5bc8b7f521cb Mon Sep 17 00:00:00 2001 From: agasbzj Date: Thu, 20 Jul 2017 16:08:31 +0800 Subject: [PATCH 0158/1139] =?UTF-8?q?Init=20types=20for=20wx=EF=BC=88?= =?UTF-8?q?=E5=BE=AE=E4=BF=A1=EF=BC=89js=20sdk=20(#18207)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Init types for wx(微信)js sdk * rename to wx-js-sdk-dt * fix lint errors * Change some definitions and add some tests. * Update comments * Update comments * Fix a type error and update comments --- types/wx-js-sdk-dt/index.d.ts | 626 +++++++++++++++++++++++ types/wx-js-sdk-dt/tsconfig.json | 22 + types/wx-js-sdk-dt/tslint.json | 1 + types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts | 127 +++++ 4 files changed, 776 insertions(+) create mode 100644 types/wx-js-sdk-dt/index.d.ts create mode 100644 types/wx-js-sdk-dt/tsconfig.json create mode 100644 types/wx-js-sdk-dt/tslint.json create mode 100644 types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts diff --git a/types/wx-js-sdk-dt/index.d.ts b/types/wx-js-sdk-dt/index.d.ts new file mode 100644 index 0000000000..ec93e37efa --- /dev/null +++ b/types/wx-js-sdk-dt/index.d.ts @@ -0,0 +1,626 @@ +// Type definitions for wx-js-sdk 1.2 +// Project: https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115 +// Definitions by: Bian Zhongjie +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace wx { + /** + * 微信配置对象 + */ + interface WxConfig { + /** + * 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来,若要查看传入的参数,可以在 pc 端打开,参数信息会通过 log 打出,仅在 pc 端时才会打印。 + */ + debug?: boolean; + + /** + * 公众号的唯一标识 + */ + appId: string; + + /** + * 签名的时间戳 + */ + timestamp: number; + + /** + * 签名的随机串 + */ + nonceStr: string; + + /** + * 签名 + */ + signature: string; + + /** + * 需要使用的JS接口列表 + */ + jsApiList: string[]; + } + + /** + * 初始化,做任何操作前必须调用该方法 + * @param setting 配置对象 + */ + function config(setting: WxConfig): void; + + /** + * 配置微信初始化成功后的回调 + * @param x 回调 + */ + function ready(x: () => void ): void; + + /** + * 配置微信初始化失败后的回调 + * @param err 失败回调 + */ + function error(err: (res: any) => void): void; + + /** + * 判断当前客户端版本是否支持指定 JS 接口, checkJsApi 接口是客户端6.0.2新引入的一个预留接口,第一期开放的接口均可不使用 checkJsApi 来检测 + */ + interface CheckApiConfig { + /** + * 需要检测的JS接口列表 + */ + jsApiList: string[]; + + /** + * 以键值对的形式返回,可用的 api 值 true,不可用为 false + * 如:{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"} + */ + success(res: { checkResult: { [methodName: string]: boolean }, errMsg: { msg: string } }): void; + } + + /** + * 判断当前客户端版本是否支持指定 JS 接口 + */ + function checkJsApi(setting: CheckApiConfig): void; + + interface ShareTimelineConfig { + /** + * 分享标题 + */ + title: string; + + /** + * 分享链接,该链接域名或路径必须与当前页面对应的公众号 JS 安全域名一致 + */ + link: string; + + /** + * 分享图标 + */ + imgUrl?: string; + + /** + * 分享成功后的回调 + */ + success?(): void; + + /** + * 分享失败后的回调 + */ + cancel?(): void; + } + + /** + * 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口 + */ + function onMenuShareTimeline(setting: ShareTimelineConfig): void; + + /** + * 消息分享对象 + */ + interface SharedAppMessage extends ShareTimelineConfig { + /** + * 分享描述 + */ + desc: string; + + /** + * 分享类型, music、video 或 link,不填默认为 link + */ + type?: string; + + /** + * 如果 type 是 music 或 video,则要提供数据链接,默认为空 + */ + dataUrl?: string; + } + + /** + * 获取“分享给朋友”按钮点击状态及自定义分享内容接口 + */ + function onMenuShareAppMessage(setting: SharedAppMessage): void; + + interface MenuShareQQ extends ShareTimelineConfig { + /** + * 分享描述 + */ + desc: string; + } + + /** + * “分享到QQ”按钮点击状态及自定义分享内容接口 + */ + function onMenuShareQQ(config: MenuShareQQ): void; + + interface MenuShareWeibo extends ShareTimelineConfig { + /** + * 分享描述 + */ + desc: string; + } + + /** + * 获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口 + */ + function onMenuShareWeibo(config: MenuShareWeibo): void; + + /** + * 获取“分享到QQ空间”按钮点击状态及自定义分享内容接口 + */ + function onMenuShareQzone(config: MenuShareWeibo): void; + + interface ChooseImageConfig { + /** + * 照片数,默认9 + */ + count?: number; + + /** + * 可以指定是原图还是压缩图,默认二者都有 + */ + sizeType?: string[]; + + /** + * 可以指定来源是相册还是相机,默认二者都有 + */ + sourceType?: string[]; + + /** + * 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 + */ + success(res: { localIds: string[]}): void; + } + + /** + * 拍照或从手机相册中选图接口 + */ + function chooseImage(config: ChooseImageConfig): void; + + /** + * 显示照片预览用的配置对象 + */ + interface PreviewImageConfig { + /** + * 当前显示图片的 http 链接 + */ + current: string; + /** + * 需要预览的图片 http 链接列表 + */ + urls: string[]; + } + + /** + * 预览图片接口 + */ + function previewImage(config: PreviewImageConfig): void; + + interface UploadImageConfig { + /** + * 要上传的图片的本地 ID,由 chooseImage 接口获得 + */ + localId: string; + + /** + * 默认为1,显示进度提示 + */ + isShowProgressTips?: number; + + /** + * res: var serverId = res.serverId; 返回图片的服务器端 ID + */ + success(res: any): void; + } + + /** + * 上传图片 + */ + function uploadImage(config: UploadImageConfig): void; + + interface DownLoadImageConfig { + /** + * serverId: 需要下载的图片的服务器端ID,由 uploadImage 接口获得 + */ + serverId: string; + + isShowProgressTips?: number; + + /** + * var localId = res.localId; 返回图片下载后的本地 ID + */ + success?(res: { localId: string }): void; + } + + function downloadImage(config: DownLoadImageConfig): void; + + interface GetLocalImgDataConfig { + /** + * 图片的 localID + */ + localId: string; + + /** + * 成功后的回调, localData是图片的base64数据,可以用img标签显示 + */ + success(res: { localData: string} ): void; + } + + /** + * 获取本地图片接口,此接口仅在 iOS WKWebview 下提供,用于兼容 iOS WKWebview 不支持 localId 直接显示图片的问题 + */ + function getLocalImgData(config: GetLocalImgDataConfig): void; + + /** + * 开始录音 + */ + function startRecord(): void; + + /** + * 停止录音 + */ + function stopRecord(success: (res: {localId: string}) => void): void; + + /** + * 录音时间超过一分钟没有停止的时候会执行回调 + */ + function onVoiceRecordEnd(complete: (res: { localId: string }) => void): void; + + /** + * 播放音频 + */ + function playVoice(localId: string): void; + + /** + * 暂停音频 + */ + function pauseVoice(localId: string): void; + + /** + * 停止播放音频 + */ + function stopVoice(localId: string): void; + + /** + * 停止播放后的回调 + */ + function onVoicePlayEnd(success: (res: { localId: string }) => void): void; + + interface UploadVoiceConfig { + localId: string; + isShowProgressTips?: number; + success(res: any): void; + } + + /** + * 上传语音接口, 上传语音有效期3天,可用微信多媒体接口下载语音到自己的服务器, + */ + function uploadVoice(config: UploadVoiceConfig): void; + + interface downloadVoiceConfig { + /** + * 需要下载的音频的服务器端 ID,由 uploadVoice 接口获得 + */ + serverId: string; + + /** + * 默认为1,显示进度提示 + */ + isShowProgressTips?: number; + + /** + * 下载成功回调 + */ + success(res: any): void; + } + + function downloadVoice(config: downloadVoiceConfig): void; + + /** + * 识别音频并返回识别结果接口 + */ + function translateVoice(config: UploadVoiceConfig): void; + + /** + * 获取网络状态, var networkType = res.networkType; 返回网络类型 2g,3g,4g,wifi + */ + function getNetworkType(success: (res: { networkType: string }) => void): void; + + interface OpenLocationConfig { + latitude?: number; + longitude?: number; + + /** + * 位置名 + */ + name?: string; + + /** + * 地址详情说明 + */ + address?: string; + + /** + * 地图缩放级别,整形值,范围从1~28。默认为最大 + */ + scale?: number; + + /** + * 在查看位置界面底部显示的超链接, 可点击跳转 + */ + infoUrl?: string; + } + + /** + * 微信内置地图查看位置 + */ + function openLocation(config: OpenLocationConfig): void; + + interface Location { + latitude: number; + longitude: number; + + /** + * 速度,以米/每秒计 + */ + speed: number; + + /** + * 位置精度 + */ + accuracy: number; + } + + interface GetLocationConfig { + /** + * 默认为 wgs84 的 gps 坐标,如果要返回直接给 openLocation 用的火星坐标,可传入'gcj02' + */ + type?: string; + + success(res: Location): void; + } + + /** + * 获取地理位置接口 + */ + function getLocation(config: GetLocationConfig): void; + + interface StartSearchBeaconsConfig { + /** + * 摇周边的业务ticket, 系统自动添加在摇出来的页面链接后面 + */ + ticket: string; + + /** + * 完成后的回调 + */ + complete(argv: any): void; + } + + /** + * 开启查找周边 ibeacon 设备接口 + */ + function startSearchBeacons(config: StartSearchBeaconsConfig): void; + + interface StopSearchBeaconsConfig { + complete(res: any): void; + } + + /** + * 关闭查找完成后的回调函数 + */ + function stopSearchBeacons(config: StopSearchBeaconsConfig): void; + + interface OnSearchBeaconsConfig { + complete(argv: any): void; + } + /** + * 监听周边 ibeacon 设备接口, + * 摇一摇周边接口使用注意事项及更多返回结果说明,请参考:摇一摇周边获取设备信息 + */ + function onSearchBeacons(config: OnSearchBeaconsConfig): void; + + /** + * 关闭当前网页窗口接口 + */ + function closeWindow(): void; + + interface MenuItemsConfig { + /** + * 要隐藏/显示的菜单项,只能隐藏“传播类”和“保护类”按钮 + */ + menuList: string[]; + } + + /** + * 批量隐藏功能按钮接口 + */ + function hideMenuItems(config: MenuItemsConfig): void; + + /** + * 批量显示功能按钮接口 + */ + function showMenuItems(config: MenuItemsConfig): void; + + /** + * 隐藏所有非基础按钮接口 + */ + function hideAllNonBaseMenuItem(): void; + + /** + * 显示所有功能按钮接口 + */ + function showAllNonBaseMenuItem(): void; + + interface ScanQRCodeConfig { + /** + * 默认为0,扫描结果由微信处理,1则直接返回扫描结果, + */ + needResult?: number; + + /** + * ["qrCode","barCode"], 可以指定扫二维码还是一维码,默认二者都有 + */ + scanType?: string[]; + + /** + * resultStr 是当 needResult 为 1 时,扫码返回的结果 + */ + success?(res: { resultStr: string }): void; + } + + /** + * 调起微信扫一扫接口 + */ + function scanQRCode(config: ScanQRCodeConfig): void; + + interface OpenProductSpecificViewConfig { + /** + * 商品id + */ + productId: string; + + /** + * 0.默认值,普通商品详情页; 1.扫一扫商品详情页; 2.小店商品详情页 + */ + viewType?: number; + } + + /** + * 跳转微信商品页接口 + */ + function openProductSpecificView(config: OpenProductSpecificViewConfig): void; + + interface ChooseCardConfig { + /** + * 门店Id + */ + shopId?: string; + + /** + * 卡券类型 + */ + cardType?: string; + + /** + * 卡券Id + */ + cardId?: string; + + /** + * 卡券签名时间戳 + */ + timestamp: number; + + /** + * 卡券签名随机串 + */ + nonceStr: string; + + /** + * 签名方式,默认'SHA1' + */ + signType: string; + + /** + * 卡券签名 + */ + cardSign: string; + + /** + * var cardList= res.cardList; 用户选中的卡券列表信息 + */ + success?(res: { cardList: Card[] }): void; + } + + /** + * 卡券对象 + */ + interface Card { + cardId: string; + cardExt: string; + } + + /** + * 拉取适用卡券列表并获取用户选择信息 + */ + function chooseCard(config: ChooseCardConfig): void; + + interface AddCardConfig { + cardList: Card[]; + success?(res: { cardList: Card[] }): void; + } + + /** + * 批量添加卡券接口 + */ + function addCard(config: AddCardConfig): void; + + class OpenCardObj { + cardId: string; + code: string; + } + + /** + * 需要打开的卡券列表 + */ + interface OpenCardConfig { + cardList: OpenCardObj[]; + } + + /** + * 查看微信卡包中的卡券接口 + */ + function openCard(config: OpenCardConfig): void; + + interface ChooseWXPayConfig { + /** + * 支付签名时间戳,注意微信jssdk中的所有使用 timestamp 字段均为小写。但最新版的支付后台生成签名使用的 timeStamp 字段名需大写其中的S字符 + */ + timestamp: number; + + /** + * 支付签名随机串,不长于 32 位 + */ + nonceStr: string; + + /** + * 统一支付接口返回的 prepay_id 参数值,提交格式如:prepay_id=*** + */ + package: string; + + /** + * 签名方式,默认为'SHA1',使用新版支付需传入'MD5' + */ + signType?: string; + + /** + * 支付签名 + */ + paySign: string; + + /** + * 支付成功后的回调函数 + */ + success(res: any): void; + } + + /** + * 发起一个微信支付请求 + */ + function chooseWXPay(config: ChooseWXPayConfig): void; +} diff --git a/types/wx-js-sdk-dt/tsconfig.json b/types/wx-js-sdk-dt/tsconfig.json new file mode 100644 index 0000000000..780e3ab13c --- /dev/null +++ b/types/wx-js-sdk-dt/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "wx-js-sdk-dt-tests.ts" + ] +} diff --git a/types/wx-js-sdk-dt/tslint.json b/types/wx-js-sdk-dt/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/wx-js-sdk-dt/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts b/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts new file mode 100644 index 0000000000..deeb753b29 --- /dev/null +++ b/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts @@ -0,0 +1,127 @@ +// No npm package for wx-js-sdk, source location is: https://res.wx.qq.com/open/js/jweixin-1.2.0.js + +wx.config({ + appId: '', + timestamp: 123, + nonceStr: '', + signature: '', + jsApiList: [''] +}); + +wx.ready(() => { +}); + +wx.error((res: any) => { +}); + +wx.checkJsApi({ + jsApiList: [''], + success: (res) => { + } +}); + +wx.onMenuShareAppMessage({ + desc: '', + title: '', + link: '', + imgUrl: '' +}); + +wx.onMenuShareTimeline({ + title: '', + link: '' +}); + +wx.scanQRCode({ +}); + +wx.closeWindow(); + +wx.downloadImage({ + serverId: '' +}); + +wx.addCard({ + cardList: [ + { + cardId: '', + cardExt: '' + } + ] +}); + +wx.chooseImage({ + success: (res) => { + res.localIds; + } +}); + +wx.chooseWXPay({ + timestamp: 0, + nonceStr: '', + package: '', + paySign: '', + success: (res) => {} +}); + +wx.getLocation({ + success: (res) => { + if (res) { + res.accuracy; + res.latitude; + res.longitude; + res.speed; + } + } +}); + +wx.getNetworkType((res) => { + if (res) { + res.networkType; + } +}); + +wx.hideMenuItems({ + menuList: [] +}); + +wx.hideAllNonBaseMenuItem(); + +wx.onMenuShareQQ({ + title: '', + link: '', + desc: '' +}); + +wx.openLocation({ + name: '', + latitude: 123.2, + longitude: -12.23 +}); + +wx.openProductSpecificView({ + productId: '1', + viewType: 0 +}); + +wx.chooseCard({ + cardId: '', + shopId: '', + cardType: '', + cardSign: '', + nonceStr: '', + timestamp: 1, + signType: '' +}); + +wx.onVoiceRecordEnd((res) => { + res.localId; +}); + +wx.onVoicePlayEnd((res) => { + res.localId; +}); + +wx.openProductSpecificView({ + productId: '' +}); From e9a7480b3cb5c7610b9d6b6b52f3fdbf277ec501 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Thu, 20 Jul 2017 10:13:16 +0200 Subject: [PATCH 0159/1139] [editorconfig] change default indentation to 4 spaces as suggested in the common mistakes section (#18244) --- .editorconfig | 1 + 1 file changed, 1 insertion(+) diff --git a/.editorconfig b/.editorconfig index 5ebf4a129c..c81d04c547 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,6 +1,7 @@ root = true [*] +indent_size = 4 trim_trailing_whitespace = true insert_final_newline = true From 90189c120b3148d7ea7eb3090396fedaff6e971d Mon Sep 17 00:00:00 2001 From: Tom Crockett Date: Thu, 20 Jul 2017 01:22:12 -0700 Subject: [PATCH 0160/1139] Remove myself from credits (#18234) I don't currently use enzyme and don't want to be responsible reviewing PRs for this repo --- types/enzyme/index.d.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index 01ecfa90d8..a5c2a72308 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -3,7 +3,6 @@ // Definitions by: Marian Palkus // Cap3 // Ivo Stratev -// Tom Crockett // jwbay // huhuanming // MartynasZilinskas From 9f3facc8704af0d4376775506d806ee9264d6827 Mon Sep 17 00:00:00 2001 From: TitaneBoy Date: Thu, 20 Jul 2017 04:24:53 -0400 Subject: [PATCH 0161/1139] Use last version of i18next package for i18next-express-middleware (#18228) --- types/i18next-express-middleware/index.d.ts | 7 ++++--- types/i18next-express-middleware/tsconfig.json | 5 ----- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/types/i18next-express-middleware/index.d.ts b/types/i18next-express-middleware/index.d.ts index 6676c5c9fa..f9877b2659 100644 --- a/types/i18next-express-middleware/index.d.ts +++ b/types/i18next-express-middleware/index.d.ts @@ -2,6 +2,7 @@ // Project: http://i18next.com/ // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 declare namespace I18next { interface I18nextOptions extends i18nextExpressMiddleware.I18nextOptions { } @@ -94,8 +95,8 @@ declare module "i18next-express-middleware" { init(services: any, options?: Object, allOptions?: Object): void; } - export function getResourcesHandler(i18next: i18next.I18n, options: Object): express.Handler; - export function handle(i18next: i18next.I18n, options?: Object): express.Handler; + export function getResourcesHandler(i18next: i18next.i18n, options: Object): express.Handler; + export function handle(i18next: i18next.i18n, options?: Object): express.Handler; /** * @summary Gets handler for missing key. @@ -103,5 +104,5 @@ declare module "i18next-express-middleware" { * @param {Object} options The options. * @return {express.Handler} The express handler. */ - export function missingKeyHandler(i18next: i18next.I18n, options: Object): express.Handler; + export function missingKeyHandler(i18next: i18next.i18n, options: Object): express.Handler; } diff --git a/types/i18next-express-middleware/tsconfig.json b/types/i18next-express-middleware/tsconfig.json index a194e6465c..6f42d82105 100644 --- a/types/i18next-express-middleware/tsconfig.json +++ b/types/i18next-express-middleware/tsconfig.json @@ -11,11 +11,6 @@ "typeRoots": [ "../" ], - "paths": { - "i18next": [ - "i18next/v2" - ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true From 947453935b6b57b45ef34fae4848fd5b0cd16d3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tomek=20=C5=81aziuk?= Date: Thu, 20 Jul 2017 10:25:23 +0200 Subject: [PATCH 0162/1139] tag may be any component type (#18226) --- types/mithril/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mithril/index.d.ts b/types/mithril/index.d.ts index 006e649d6e..e4f8694f6a 100644 --- a/types/mithril/index.d.ts +++ b/types/mithril/index.d.ts @@ -175,7 +175,7 @@ declare namespace Mithril { /** Virtual DOM nodes, or vnodes, are Javascript objects that represent an element (or parts of the DOM). */ interface Vnode> { /** The nodeName of a DOM element. It may also be the string [ if a vnode is a fragment, # if it's a text vnode, or < if it's a trusted HTML vnode. Additionally, it may be a component. */ - tag: string | Component; + tag: string | ComponentTypes; /** A hashmap of DOM attributes, events, properties and lifecycle methods. */ attrs: Attrs; /** An object that is persisted between redraws. In component vnodes, state is a shallow clone of the component object. */ From 2005e7e6ee75f75321693a141c5880a704e4d777 Mon Sep 17 00:00:00 2001 From: Dan Date: Thu, 20 Jul 2017 18:29:02 +1000 Subject: [PATCH 0163/1139] Added definitions for 'clear-require' (#18238) --- types/clear-require/clear-require-tests.ts | 8 ++++++++ types/clear-require/index.d.ts | 14 ++++++++++++++ types/clear-require/tsconfig.json | 22 ++++++++++++++++++++++ types/clear-require/tslint.json | 1 + 4 files changed, 45 insertions(+) create mode 100644 types/clear-require/clear-require-tests.ts create mode 100644 types/clear-require/index.d.ts create mode 100644 types/clear-require/tsconfig.json create mode 100644 types/clear-require/tslint.json diff --git a/types/clear-require/clear-require-tests.ts b/types/clear-require/clear-require-tests.ts new file mode 100644 index 0000000000..53aea4d832 --- /dev/null +++ b/types/clear-require/clear-require-tests.ts @@ -0,0 +1,8 @@ +import * as clear from 'clear-require'; + +clear('my-module'); // clear specific module from require cache + +clear.all(); // clear all of the require cache + +clear.match(new RegExp('^.*$')); // clear all modules which match the RegExp +clear.match(/^.*$/); // similar to above but using /regex/ notation diff --git a/types/clear-require/index.d.ts b/types/clear-require/index.d.ts new file mode 100644 index 0000000000..4b9118a008 --- /dev/null +++ b/types/clear-require/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for clear-require 2.0 +// Project: https://github.com/sindresorhus/clear-module +// Definitions by: dan-j +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface ClearRequire { + (moduleId: string): boolean; + all(): void; + match(regex: RegExp): void; +} + +declare const clear: ClearRequire; + +export = clear; diff --git a/types/clear-require/tsconfig.json b/types/clear-require/tsconfig.json new file mode 100644 index 0000000000..9c28741f0b --- /dev/null +++ b/types/clear-require/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clear-require-tests.ts" + ] +} diff --git a/types/clear-require/tslint.json b/types/clear-require/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/clear-require/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 76241738dc82cead94f4b5c1a4333d14ceed7cb2 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Thu, 20 Jul 2017 17:41:12 +0900 Subject: [PATCH 0164/1139] Update redux-auth-wrapper to v2 (#18236) * Update redux-auth-wrapper to version 2 * Fix linter errors * Add redirectAction optiona to router decorator --- types/redux-auth-wrapper/authWrapper.d.ts | 15 ++ .../connectedAuthWrapper.d.ts | 9 + .../redux-auth-wrapper/history3/redirect.d.ts | 55 ++++++ .../redux-auth-wrapper/history4/redirect.d.ts | 25 +++ types/redux-auth-wrapper/index.d.ts | 32 +-- .../redux-auth-wrapper-tests.tsx | 184 +++++++++++++++--- types/redux-auth-wrapper/tsconfig.json | 8 +- types/redux-auth-wrapper/v1/index.d.ts | 33 ++++ .../v1/redux-auth-wrapper-tests.tsx | 28 +++ types/redux-auth-wrapper/v1/tsconfig.json | 29 +++ types/redux-auth-wrapper/v1/tslint.json | 1 + 11 files changed, 371 insertions(+), 48 deletions(-) create mode 100644 types/redux-auth-wrapper/authWrapper.d.ts create mode 100644 types/redux-auth-wrapper/connectedAuthWrapper.d.ts create mode 100644 types/redux-auth-wrapper/history3/redirect.d.ts create mode 100644 types/redux-auth-wrapper/history4/redirect.d.ts create mode 100644 types/redux-auth-wrapper/v1/index.d.ts create mode 100644 types/redux-auth-wrapper/v1/redux-auth-wrapper-tests.tsx create mode 100644 types/redux-auth-wrapper/v1/tsconfig.json create mode 100644 types/redux-auth-wrapper/v1/tslint.json diff --git a/types/redux-auth-wrapper/authWrapper.d.ts b/types/redux-auth-wrapper/authWrapper.d.ts new file mode 100644 index 0000000000..0b92331e3b --- /dev/null +++ b/types/redux-auth-wrapper/authWrapper.d.ts @@ -0,0 +1,15 @@ +import { ReactType } from "react"; +import { AuthConfig, AuthWrapperDecorator } from "redux-auth-wrapper"; + +export interface InjectedAuthProps { + isAuthenticated: boolean; + isAuthenticating: boolean; +} + +export interface AuthWrapperConfig extends AuthConfig { + FailureComponent?: ReactType; +} + +export function authWrapper( + config: AuthWrapperConfig +): AuthWrapperDecorator; diff --git a/types/redux-auth-wrapper/connectedAuthWrapper.d.ts b/types/redux-auth-wrapper/connectedAuthWrapper.d.ts new file mode 100644 index 0000000000..2beb0b1180 --- /dev/null +++ b/types/redux-auth-wrapper/connectedAuthWrapper.d.ts @@ -0,0 +1,9 @@ +import { ReactType } from "react"; +import { AuthBaseConfig, AuthWrapperDecorator } from "redux-auth-wrapper"; +import { AuthWrapperConfig, InjectedAuthProps } from "redux-auth-wrapper/authWrapper"; + +export type ConnectedAuthWrapperConfig = AuthWrapperConfig & AuthBaseConfig; + +export function connectedAuthWrapper( + config: ConnectedAuthWrapperConfig +): AuthWrapperDecorator; diff --git a/types/redux-auth-wrapper/history3/redirect.d.ts b/types/redux-auth-wrapper/history3/redirect.d.ts new file mode 100644 index 0000000000..a5ef70b3e1 --- /dev/null +++ b/types/redux-auth-wrapper/history3/redirect.d.ts @@ -0,0 +1,55 @@ +import { Action, Store } from "redux"; +import { Location, LocationDescriptorObject } from "history"; +import { AuthBaseConfig, AuthConfig, AuthWrapperDecorator, StateSelector } from "redux-auth-wrapper"; +import { InjectedAuthProps } from "redux-auth-wrapper/authWrapper"; +import { ConnectedAuthWrapperConfig } from "redux-auth-wrapper/connectedAuthWrapper"; + +export interface InjectedAuthReduxProps extends InjectedAuthProps { + redirectPath: string; +} + +export interface InjectedAuthRouterProps Action> extends InjectedAuthReduxProps { + redirect: Redirect; +} + +export interface ConnectedRouterRedirectConfig extends AuthBaseConfig { + redirectPath: string | StateSelector; + redirectAction?(location: Location): Action; + allowRedirectBack?: boolean | StateSelector; + redirectQueryParamName?: string; +} + +export function connectedRouterRedirect( + config: ConnectedRouterRedirectConfig +): AuthWrapperDecorator; + +export type ConnectedReduxRedirectConfig = ConnectedRouterRedirectConfig; + +export function connectedReduxRedirect( + config: ConnectedReduxRedirectConfig +): AuthWrapperDecorator; + +export type StateMutateSelector = (state: State, nextState: State) => R; + +export interface CreateOnEnterConfig extends AuthConfig { + redirectPath: string | StateMutateSelector; + authenticatedSelector: StateMutateSelector; + authenticatingSelector?: StateMutateSelector; + allowRedirectBack?: boolean | StateMutateSelector; + redirectQueryParamName?: string; +} + +export function createOnEnter(config: CreateOnEnterConfig): + (store: Store, nextState: State, redirect: (location: LocationDescriptorObject) => void) => void; + +export interface LocationHelperConfig { + redirectQueryParamName?: string; + locationSelector?(props: Props): LocationDescriptorObject; +} + +export interface LocationHelper { + getRedirectQueryParam(props: Props): string; + createRedirectLoc(props: Props, redirectPath: string): LocationDescriptorObject; +} + +export function locationHelperBuilder(config: LocationHelperConfig): LocationHelper; diff --git a/types/redux-auth-wrapper/history4/redirect.d.ts b/types/redux-auth-wrapper/history4/redirect.d.ts new file mode 100644 index 0000000000..74b4655bc1 --- /dev/null +++ b/types/redux-auth-wrapper/history4/redirect.d.ts @@ -0,0 +1,25 @@ +import { Action } from "redux"; +import { Location } from "history"; +import { AuthWrapperDecorator } from "redux-auth-wrapper"; +import { + ConnectedRouterRedirectConfig, + InjectedAuthReduxProps +} from "redux-auth-wrapper/history3/redirect"; + +export { + connectedRouterRedirect, + ConnectedRouterRedirectConfig, + InjectedAuthReduxProps, + InjectedAuthRouterProps, + locationHelperBuilder, + LocationHelper, + LocationHelperConfig +} from "redux-auth-wrapper/history3/redirect"; + +export interface ConnectedReduxRedirectConfig extends ConnectedRouterRedirectConfig { + redirectAction(location: Location): Action; +} + +export function connectedReduxRedirect( + config: ConnectedReduxRedirectConfig +): AuthWrapperDecorator; diff --git a/types/redux-auth-wrapper/index.d.ts b/types/redux-auth-wrapper/index.d.ts index 453a4e7e02..52bea44218 100644 --- a/types/redux-auth-wrapper/index.d.ts +++ b/types/redux-auth-wrapper/index.d.ts @@ -1,33 +1,21 @@ -// Type definitions for redux-auth-wrapper 1.0 +// Type definitions for redux-auth-wrapper 2.0 // Project: https://github.com/mjrussell/redux-auth-wrapper // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { ComponentClass, StatelessComponent, ReactType } from "react"; -import { Action } from "redux"; -import { Location } from "history"; +import { ComponentClass, StatelessComponent, ComponentType, ReactType } from "react"; -export type ComponentConstructor

= ComponentClass

| StatelessComponent

; +export type StateSelector = (state: State, props: OwnProps) => R; -export interface InjectedProps { - authData?: AuthData; -} +export type AuthWrapperDecorator = (component: ComponentType) => ComponentClass; -export interface AuthWrapperConfig { - allowRedirectBack?: boolean | ((location: Location, redirectPath: string) => boolean); - authenticatingSelector?(state: State, ownProps?: Props): boolean; - authSelector(state: State, ownProps?: Props): AuthData; - FailureComponent?: ReactType; - failureRedirectPath?: string | ((state: State, ownProps?: Props) => string); - LoadingComponent?: ReactType; - redirectQueryParamName?: string; +export interface AuthConfig { + AuthenticatingComponent?: ReactType; wrapperDisplayName?: string; - predicate?(authData: AuthData): boolean; - propMapper?(ownProps: Props): InjectedProps & Props; - redirectAction?(...args: any[]): Action; } -export type AuthDecorator = (component: ComponentConstructor) => ComponentClass; - -export function UserAuthWrapper(config: AuthWrapperConfig): AuthDecorator; +export interface AuthBaseConfig extends AuthConfig { + authenticatedSelector: StateSelector; + authenticatingSelector?: StateSelector; +} diff --git a/types/redux-auth-wrapper/redux-auth-wrapper-tests.tsx b/types/redux-auth-wrapper/redux-auth-wrapper-tests.tsx index e37390410e..a009bdcc7f 100644 --- a/types/redux-auth-wrapper/redux-auth-wrapper-tests.tsx +++ b/types/redux-auth-wrapper/redux-auth-wrapper-tests.tsx @@ -1,28 +1,168 @@ import * as React from "react"; -import { StatelessComponent } from "react"; -import { UserAuthWrapper } from "redux-auth-wrapper"; +import { Component, StatelessComponent } from "react"; +import { createStore } from "redux"; +import { push } from "react-router-redux"; +import { LocationDescriptorObject } from "history"; -const Auth = UserAuthWrapper({ +import { + connectedRouterRedirect as H3connectedRouterRedirect, + connectedReduxRedirect as H3connectedReduxRedirect, + createOnEnter, + locationHelperBuilder as H3locationHelperBuilder +} from "redux-auth-wrapper/history3/redirect"; + +import { + connectedRouterRedirect, + connectedReduxRedirect, + locationHelperBuilder +} from "redux-auth-wrapper/history4/redirect"; + +import { authWrapper } from "redux-auth-wrapper/authWrapper"; +import { connectedAuthWrapper } from "redux-auth-wrapper/connectedAuthWrapper"; + +interface TestReduxState { + foo: string; +} + +interface TestComponentProps { + foo: string; +} + +const stringSelector = (state: TestReduxState, ownProps: TestComponentProps) => "fizz"; +const boolSelector = (state: TestReduxState, ownProps: TestComponentProps) => true; +const stringStateSelector = (state: TestReduxState, nextState: TestReduxState) => "buzz"; +const boolStateSelector = (state: TestReduxState, nextState: TestReduxState) => true; + +/* History 3 */ + +H3connectedRouterRedirect({ + redirectPath: "/login", + authenticatedSelector: boolSelector, + authenticatingSelector: boolSelector, + AuthenticatingComponent: "div", + wrapperDisplayName: "Auth", allowRedirectBack: true, - authenticatingSelector(state: any) { - return state.auth.loading; - }, - authSelector(state: any) { - return state.auth; - }, - FailureComponent: () => (

), - failureRedirectPath: "/401", - LoadingComponent: () => (
), - redirectAction: () => ({ type : "redirect" }), - redirectQueryParamName: "next", - predicate(authData: any) { - return authData.authorized; - }, - wrapperDisplayName: "TestAuth" + redirectQueryParamName: "redirect" +})( + ({ + foo, + isAuthenticated, + isAuthenticating, + redirect, + redirectPath + }) => null +); + +H3connectedReduxRedirect({ + redirectPath: stringSelector, + authenticatedSelector: boolSelector, + authenticatingSelector: boolSelector, + AuthenticatingComponent: "div", + wrapperDisplayName: "Auth", + allowRedirectBack: boolSelector, + redirectQueryParamName: "redirect" +})( + ({ + foo, + isAuthenticated, + isAuthenticating, + redirectPath + }) => null +); + +const store = createStore(() => ({})); + +const enter = createOnEnter({ + redirectPath: "/login", + authenticatedSelector: boolStateSelector, + authenticatingSelector: boolStateSelector, + allowRedirectBack: true, + redirectQueryParamName: "redirect" }); +enter(store, { foo : "bar" }, (location: LocationDescriptorObject) => {}); -export const TestAuthComponent: StatelessComponent = () => { - return (
); -}; +const H3helper = H3locationHelperBuilder({ + redirectQueryParamName: "redirect", + locationSelector: ({ foo }) => ({ pathname : "foo" }) +}); +H3helper.getRedirectQueryParam({ foo : "bar" }); +H3helper.createRedirectLoc({ foo : "bar" }, "redirect"); -const TestAuth = Auth(TestAuthComponent); +/* History 4 */ + +connectedRouterRedirect({ + redirectPath: "/login", + authenticatedSelector: boolSelector, + authenticatingSelector: boolSelector, + AuthenticatingComponent: (props: any) => null, + wrapperDisplayName: "Auth", + allowRedirectBack: true, + redirectQueryParamName: "redirect" +})( + ({ + foo, + isAuthenticated, + isAuthenticating, + redirect, + redirectPath + }) => null +); + +class Loading extends Component { + render() { + return null; + } +} + +connectedReduxRedirect({ + redirectPath: "/login", + redirectAction: push, + authenticatedSelector: boolSelector, + authenticatingSelector: boolSelector, + AuthenticatingComponent: Loading, + wrapperDisplayName: "Auth", + allowRedirectBack: true, + redirectQueryParamName: "redirect" +})( + ({ + foo, + isAuthenticated, + isAuthenticating, + redirectPath + }) => null +); + +const helper = locationHelperBuilder({ + redirectQueryParamName: "redirect", + locationSelector: ({ foo }) => ({ pathname : "foo" }) +}); +helper.getRedirectQueryParam({ foo : "bar" }); +helper.createRedirectLoc({ foo : "bar" }, "redirect"); + +/* Other Wrappers */ + +authWrapper({ + AuthenticatingComponent: "div", + FailureComponent: "div", + wrapperDisplayName: "Auth" +})( + ({ + foo, + isAuthenticated, + isAuthenticating + }) => null +); + +connectedAuthWrapper({ + authenticatedSelector: boolSelector, + authenticatingSelector: boolSelector, + AuthenticatingComponent: "div", + FailureComponent: "div", + wrapperDisplayName: "Auth" +})( + ({ + foo, + isAuthenticated, + isAuthenticating + }) => null +); diff --git a/types/redux-auth-wrapper/tsconfig.json b/types/redux-auth-wrapper/tsconfig.json index 5aae706c27..33b9707503 100644 --- a/types/redux-auth-wrapper/tsconfig.json +++ b/types/redux-auth-wrapper/tsconfig.json @@ -10,16 +10,16 @@ "strictNullChecks": true, "baseUrl": "../", "typeRoots": ["../"], - "paths": { - "history": ["history/v3"], - "history/*": ["history/v3/*"] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, "jsx": "react" }, "files": [ + "history3/redirect.d.ts", + "history4/redirect.d.ts", + "authWrapper.d.ts", + "connectedAuthWrapper.d.ts", "index.d.ts", "redux-auth-wrapper-tests.tsx" ] diff --git a/types/redux-auth-wrapper/v1/index.d.ts b/types/redux-auth-wrapper/v1/index.d.ts new file mode 100644 index 0000000000..453a4e7e02 --- /dev/null +++ b/types/redux-auth-wrapper/v1/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for redux-auth-wrapper 1.0 +// Project: https://github.com/mjrussell/redux-auth-wrapper +// Definitions by: Karol Janyst +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { ComponentClass, StatelessComponent, ReactType } from "react"; +import { Action } from "redux"; +import { Location } from "history"; + +export type ComponentConstructor

= ComponentClass

| StatelessComponent

; + +export interface InjectedProps { + authData?: AuthData; +} + +export interface AuthWrapperConfig { + allowRedirectBack?: boolean | ((location: Location, redirectPath: string) => boolean); + authenticatingSelector?(state: State, ownProps?: Props): boolean; + authSelector(state: State, ownProps?: Props): AuthData; + FailureComponent?: ReactType; + failureRedirectPath?: string | ((state: State, ownProps?: Props) => string); + LoadingComponent?: ReactType; + redirectQueryParamName?: string; + wrapperDisplayName?: string; + predicate?(authData: AuthData): boolean; + propMapper?(ownProps: Props): InjectedProps & Props; + redirectAction?(...args: any[]): Action; +} + +export type AuthDecorator = (component: ComponentConstructor) => ComponentClass; + +export function UserAuthWrapper(config: AuthWrapperConfig): AuthDecorator; diff --git a/types/redux-auth-wrapper/v1/redux-auth-wrapper-tests.tsx b/types/redux-auth-wrapper/v1/redux-auth-wrapper-tests.tsx new file mode 100644 index 0000000000..e37390410e --- /dev/null +++ b/types/redux-auth-wrapper/v1/redux-auth-wrapper-tests.tsx @@ -0,0 +1,28 @@ +import * as React from "react"; +import { StatelessComponent } from "react"; +import { UserAuthWrapper } from "redux-auth-wrapper"; + +const Auth = UserAuthWrapper({ + allowRedirectBack: true, + authenticatingSelector(state: any) { + return state.auth.loading; + }, + authSelector(state: any) { + return state.auth; + }, + FailureComponent: () => (

), + failureRedirectPath: "/401", + LoadingComponent: () => (
), + redirectAction: () => ({ type : "redirect" }), + redirectQueryParamName: "next", + predicate(authData: any) { + return authData.authorized; + }, + wrapperDisplayName: "TestAuth" +}); + +export const TestAuthComponent: StatelessComponent = () => { + return (
); +}; + +const TestAuth = Auth(TestAuthComponent); diff --git a/types/redux-auth-wrapper/v1/tsconfig.json b/types/redux-auth-wrapper/v1/tsconfig.json new file mode 100644 index 0000000000..ec5711a05e --- /dev/null +++ b/types/redux-auth-wrapper/v1/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "history": ["history/v3"], + "history/*": ["history/v3/*"], + "redux-auth-wrapper": ["redux-auth-wrapper/v1"] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "redux-auth-wrapper-tests.tsx" + ] +} diff --git a/types/redux-auth-wrapper/v1/tslint.json b/types/redux-auth-wrapper/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/redux-auth-wrapper/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 484883ab602b113167d92034c87675fd8dfac488 Mon Sep 17 00:00:00 2001 From: Silas Rech Date: Thu, 20 Jul 2017 17:58:40 +0200 Subject: [PATCH 0165/1139] [catbox] Fix classes (#18072) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [catbox] Fix classes * Class extends Class => Class implements Interface * Add TSLint configuration * Add initial tests (Basically testing if I understood how the tests here work 😏) * Fix tests * Don't set Memory to any --- types/catbox/catbox-tests.ts | 27 ++++++++ types/catbox/index.d.ts | 119 ++++++++++++++++++++++++++--------- types/catbox/tsconfig.json | 5 +- types/catbox/tslint.json | 1 + 4 files changed, 122 insertions(+), 30 deletions(-) create mode 100644 types/catbox/catbox-tests.ts create mode 100644 types/catbox/tslint.json diff --git a/types/catbox/catbox-tests.ts b/types/catbox/catbox-tests.ts new file mode 100644 index 0000000000..565573adad --- /dev/null +++ b/types/catbox/catbox-tests.ts @@ -0,0 +1,27 @@ +import Catbox = require("catbox"); + +const Memory: Catbox.EnginePrototypeOrObject = { + start(callback: Catbox.CallBackNoResult) {}, + stop() {}, + get() {}, + set() {}, + drop() {}, + isReady(): boolean { return true; }, + validateSegmentName(segment: string): null { return null; }, +}; + +const client = new Catbox.Client(Memory, { partition: 'cache' }); + +const cache = new Catbox.Policy({ + expiresIn: 5000, +}, client, 'cache'); + +cache.set('foo', 'bar', 5000, () => {}); + +cache.get('foo', () => {}); + +cache.drop('foo', () => {}); + +cache.isReady(); + +cache.stats(); diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index 5dad5af29a..e34059d618 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -6,12 +6,8 @@ import * as Boom from 'boom'; -export interface CallBackNoResult { - (err?: Boom.BoomError): void; -} -export interface CallBackWithResult { - (err: Boom.BoomError | null | undefined, result: T): void; -} +export type CallBackNoResult = (err?: Boom.BoomError) => void; +export type CallBackWithResult = (err: Boom.BoomError | null | undefined, result: T) => void; /** * Client @@ -20,14 +16,44 @@ export interface CallBackWithResult { * * function - a prototype function with the signature function(options). catbox will call new func(options). * * object - a pre instantiated client implementation object. Does not support passing options. * options - the strategy configuration object. Each strategy defines its own configuration options with the following common options: - * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. + * * partition - the partition name used to isolate the cached results across multiple clients. The partition name is used as the MongoDB database name, + * the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. * @see {@link https://github.com/hapijs/catbox#client} */ -export interface Client extends ClientApi { - new(engine: EnginePrototypeOrObject, options: ClientOptions): Client; +export class Client implements ClientApi { + constructor(engine: EnginePrototypeOrObject, options: ClientOptions); + + /** start(callback) - creates a connection to the cache server. Must be called before any other method is available. The callback signature is function(err). */ + start(callback: CallBackNoResult): void; + /** stop() - terminates the connection to the cache server. */ + stop(): void; + /** + * get(key, callback) - retrieve an item from the cache engine if found where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned + */ + get(key: CacheKey, callback: CallBackWithResult): CacheItem; + /** + * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: + * * key - a cache key object (see [ICacheKey]). + * * value - the string or object value to be stored. + * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * * callback - a function with the signature function(err). + */ + set(key: CacheKey, value: CacheItem, ttl: number, callback: CallBackNoResult): void; + /** + * drop(key, callback) - remove an item from cache where: + * * key - a cache key object (see [ICacheKey]). + * * callback - a function with the signature function(err). + */ + drop(key: CacheKey, callback: CallBackNoResult): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready. */ + isReady(): boolean; + /** validateSegmentName(segment) - returns null if the segment name is valid (see below), otherwise should return an instance of Error with an appropriate message. */ + validateSegmentName(segment: string): null | Boom.BoomError; } -type EnginePrototypeOrObject = EnginePrototype | ClientApi; +export type EnginePrototypeOrObject = EnginePrototype | ClientApi; /** * A prototype CatBox engine function @@ -50,7 +76,7 @@ export interface ClientApi { * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). * * callback - a function with the signature function(err, cached). If the item is not found, both err and cached are null. If found, the cached object is returned - */ + */ get(key: CacheKey, callback: CallBackWithResult): CacheItem; /** * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: @@ -92,21 +118,52 @@ export interface CachedObject { ttl: number; } -type CacheItem = any; +export type CacheItem = any; export interface ClientOptions { partition: string; } /** - * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. The object is constructed using new Policy(options, [cache, segment]) where: + * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. + * The object is constructed using new Policy(options, [cache, segment]) where: * * options - an object with the IPolicyOptions structure * * cache - a Client instance (which has already been started). * * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface Policy extends PolicyAPI { - new(options: PolicyOptions, cache: Client, segment: string): Policy; +export class Policy implements PolicyAPI { + constructor(options: PolicyOptions, cache: Client, segment: string); + /** + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. + * * callback - the return function. + */ + get(id: string | {id: string}, callback: PolicyGetCallback): CacheItem; + /** + * set(id, value, ttl, callback) - store an item in the cache where: + * * id - the unique item identifier (within the policy segment). + * * value - the string or object value to be stored. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * callback - a function with the signature function(err). + */ + set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; + /** + * drop(id, callback) - remove the item from cache where: + * * id - the unique item identifier (within the policy segment). + * * callback - a function with the signature function(err). + */ + drop(id: string | {id: string}, callback: CallBackNoResult): void; + /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ + ttl(created: number): number; + /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ + rules(options: PolicyOptions): void; + /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ + isReady(): boolean; + /** stats - an object with cache statistics */ + stats(): CacheStatisticsObject; } /** @@ -116,7 +173,8 @@ export interface Policy extends PolicyAPI { */ export interface PolicyAPI { /** - * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: + * get(id, callback) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. * * callback - the return function. */ @@ -125,7 +183,8 @@ export interface PolicyAPI { * set(id, value, ttl, callback) - store an item in the cache where: * * id - the unique item identifier (within the policy segment). * * value - the string or object value to be stored. - * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). This should be set to 0 in order to use the caching rules configured when creating the Policy object. + * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * This should be set to 0 in order to use the caching rules configured when creating the Policy object. * * callback - a function with the signature function(err). */ set(id: string | {id: string}, value: CacheItem, ttl: number | null, callback: CallBackNoResult): void; @@ -152,9 +211,7 @@ export interface PolicyAPI { * @param cached - null if a valid item was not found in the cache, or IPolicyGetCallbackCachedOptions * @param report - an object with logging information about the generation operation */ -export interface PolicyGetCallback{ - (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog): void; -} +export type PolicyGetCallback = (err: null | Boom.BoomError, value: CacheItem, cached: PolicyGetCallbackCachedOptions, report: PolicyGetCallbackReportLog) => void; export interface PolicyGetCallbackCachedOptions { /** item - the cached value. */ @@ -178,14 +235,19 @@ export interface PolicyOptions { /** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */ generateFunc?: GenerateFunc; /** - * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: + * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. + * Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: * * stored - the timestamp when the item was stored in the cache (in milliseconds). * * ttl - the remaining time-to-live (not the original value used when storing the object). - */ + */ staleIn?: number | ((stored: number, ttl: number) => number); /** staleTimeout - number of milliseconds to wait before returning a stale value while generateFunc is generating a fresh value. */ staleTimeout?: number; - /** generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. Set to false to disable timeouts which may cause all get() requests to get stuck forever. */ + /** + * generateTimeout - number of milliseconds to wait before returning a timeout error when the generateFunc function takes too long to return a value. + * When the value is eventually returned, it is stored in the cache for future requests. Required if generateFunc is present. + * Set to false to disable timeouts which may cause all get() requests to get stuck forever. + */ generateTimeout?: number | false; /** dropOnError - if true, an error or timeout in the generateFunc causes the stale value to be evicted from the cache. Defaults to true. */ dropOnError?: boolean; @@ -193,7 +255,10 @@ export interface PolicyOptions { generateOnReadError?: boolean; /** generateIgnoreWriteError - if false, an upstream cache write error will be passed back with the generated value when calling the get() method. Defaults to true. */ generateIgnoreWriteError?: boolean; - /** pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. */ + /** + * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. + * Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. + */ pendingGenerateTimeout?: number; } @@ -208,9 +273,7 @@ export interface PolicyOptions { * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface GenerateFunc { - (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)): void; -} +export type GenerateFunc = (id: string, next: ((err: null | Boom.BoomError, value: CacheItem, ttl?: number) => void)) => void; /** * An object with logging information about the generation operation containing the following keys (as relevant): @@ -242,6 +305,6 @@ export interface CacheStatisticsObject { stales: number; /** generates - number of calls to the generate function. */ generates: number; - /** errors - cache operations errors. TODO check this*/ + /** errors - cache operations errors. TODO check this */ errors: number; } diff --git a/types/catbox/tsconfig.json b/types/catbox/tsconfig.json index 3bc13b0278..b04177a675 100644 --- a/types/catbox/tsconfig.json +++ b/types/catbox/tsconfig.json @@ -16,6 +16,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "catbox-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/catbox/tslint.json b/types/catbox/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/catbox/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 052ce68076d859145601fb3a60194d75d38d1322 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Thu, 20 Jul 2017 18:49:33 +0200 Subject: [PATCH 0166/1139] [pretty-ms] introduce typings (#18258) --- types/pretty-ms/index.d.ts | 17 +++++++++++++++++ types/pretty-ms/pretty-ms-tests.ts | 9 +++++++++ types/pretty-ms/tsconfig.json | 22 ++++++++++++++++++++++ types/pretty-ms/tslint.json | 1 + 4 files changed, 49 insertions(+) create mode 100644 types/pretty-ms/index.d.ts create mode 100644 types/pretty-ms/pretty-ms-tests.ts create mode 100644 types/pretty-ms/tsconfig.json create mode 100644 types/pretty-ms/tslint.json diff --git a/types/pretty-ms/index.d.ts b/types/pretty-ms/index.d.ts new file mode 100644 index 0000000000..e23b26826b --- /dev/null +++ b/types/pretty-ms/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for pretty-ms 3.0 +// Project: https://github.com/sindresorhus/pretty-ms#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = prettyMs; + +declare function prettyMs(input: number, options?: prettyMs.PrettyMsOptions): string; + +declare namespace prettyMs { + interface PrettyMsOptions { + secDecimalDigits?: number; + msDecimalDigits?: number; + compact?: boolean; + verbose?: boolean; + } +} diff --git a/types/pretty-ms/pretty-ms-tests.ts b/types/pretty-ms/pretty-ms-tests.ts new file mode 100644 index 0000000000..14bff61304 --- /dev/null +++ b/types/pretty-ms/pretty-ms-tests.ts @@ -0,0 +1,9 @@ +import prettyMs = require('pretty-ms'); + +let str: string; +str = prettyMs(133); +str = prettyMs(1337, {compact: true}); +str = prettyMs(1335669000, {verbose: true}); +str = prettyMs(1335669000, {secDecimalDigits: 1}); +str = prettyMs(1335669000, {msDecimalDigits: 2}); +str = prettyMs(new Date(2014, 0, 1, 10, 40).getTime() - new Date(2014, 0, 1, 10, 5).getTime()); diff --git a/types/pretty-ms/tsconfig.json b/types/pretty-ms/tsconfig.json new file mode 100644 index 0000000000..ebb5c1f0e3 --- /dev/null +++ b/types/pretty-ms/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pretty-ms-tests.ts" + ] +} diff --git a/types/pretty-ms/tslint.json b/types/pretty-ms/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pretty-ms/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 239ac8e81ece0fba29be3736212a069a850ce2bc Mon Sep 17 00:00:00 2001 From: Toru Nagashima Date: Fri, 21 Jul 2017 01:55:31 +0900 Subject: [PATCH 0167/1139] Fix estree ForXStatement#left to Pattern (#18100) --- types/estree/estree-tests.ts | 33 ++++++++++++++++++++++++++++++++- types/estree/index.d.ts | 2 +- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/types/estree/estree-tests.ts b/types/estree/estree-tests.ts index ace67225a4..ac2516f18b 100644 --- a/types/estree/estree-tests.ts +++ b/types/estree/estree-tests.ts @@ -89,6 +89,7 @@ declare var awaitExpression: ESTree.AwaitExpression; declare var toplevelStatement: ESTree.Statement | ESTree.ModuleDeclaration; declare var expressionOrPattern: ESTree.Expression | ESTree.Pattern; declare var variableDeclaratorOrExpression: ESTree.VariableDeclaration | ESTree.Expression; +declare var variableDeclaratorOrPattern: ESTree.VariableDeclaration | ESTree.Pattern; declare var literalOrIdentifier: ESTree.Literal | ESTree.Identifier; declare var blockStatementOrExpression: ESTree.BlockStatement | ESTree.Expression; declare var identifierOrExpression: ESTree.Identifier | ESTree.Expression; @@ -156,7 +157,7 @@ var expressionMaybe: ESTree.Expression | null | undefined = forStatement.update; // ForInStatement var forInStatement: ESTree.ForInStatement; -variableDeclaratorOrExpression = forInStatement.left; +variableDeclaratorOrPattern = forInStatement.left; expression = forInStatement.right; // Expression @@ -723,3 +724,33 @@ switch (moduleSpecifier.type) { default: never = moduleSpecifier; } + +switch (forInStatement.left.type) { + case 'Identifier': + identifier = forInStatement.left; + break; + case 'ObjectPattern': + objectPattern = forInStatement.left; + break; + case 'ArrayPattern': + arrayPattern = forInStatement.left; + break; + case 'MemberExpression': + memberExpression = forInStatement.left; + break; +} + +switch (forOfStatement.left.type) { + case 'Identifier': + identifier = forOfStatement.left; + break; + case 'ObjectPattern': + objectPattern = forOfStatement.left; + break; + case 'ArrayPattern': + arrayPattern = forOfStatement.left; + break; + case 'MemberExpression': + memberExpression = forOfStatement.left; + break; +} diff --git a/types/estree/index.d.ts b/types/estree/index.d.ts index b7a4005add..64731a6895 100644 --- a/types/estree/index.d.ts +++ b/types/estree/index.d.ts @@ -169,7 +169,7 @@ export interface ForStatement extends BaseStatement { } interface BaseForXStatement extends BaseStatement { - left: VariableDeclaration | Expression; + left: VariableDeclaration | Pattern; right: Expression; body: Statement; } From bdb2b5e94b281789ab966399f88f863d8d278b5a Mon Sep 17 00:00:00 2001 From: Alan Agius Date: Thu, 20 Jul 2017 18:58:16 +0200 Subject: [PATCH 0168/1139] feat(fs-extra): update to match api for `4.x.x` (#18096) * feat(fs-extra): update to match api for `4.x.x` * style(fs-extra): add missing colons * fs-extra: add missing breakline between interfaces --- types/fs-extra/fs-extra-tests.ts | 14 ++++++++++++-- types/fs-extra/index.d.ts | 18 ++++++++++++++---- 2 files changed, 26 insertions(+), 6 deletions(-) diff --git a/types/fs-extra/fs-extra-tests.ts b/types/fs-extra/fs-extra-tests.ts index 39f3a9d37a..903474e273 100644 --- a/types/fs-extra/fs-extra-tests.ts +++ b/types/fs-extra/fs-extra-tests.ts @@ -1,5 +1,5 @@ -import * as fs from 'fs-extra'; -import * as Path from 'path'; +import * as fs from "fs-extra"; +import * as Path from "path"; const len = 2; const src = ""; @@ -213,6 +213,16 @@ fs.lchmodSync(path, modeStr); fs.statSync(path); fs.lstatSync(path); +fs.read(0, new Buffer(""), 0, 0, null).then(x => { + const a = x.buffer; + const b = x.bytesRead; +}); + +fs.write(0, new Buffer(""), 0, 0, null).then(x => { + const a = x.buffer; + const b = x.bytesWritten; +}); + // $ExpectType Promise fs.writeFile("foo.txt", "i am foo", { encoding: "utf-8" }); diff --git a/types/fs-extra/index.d.ts b/types/fs-extra/index.d.ts index 49a056bce7..0231cac2d2 100644 --- a/types/fs-extra/index.d.ts +++ b/types/fs-extra/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for fs-extra 3.0 +// Type definitions for fs-extra 4.0 // Project: https://github.com/jprichardson/node-fs-extra // Definitions by: Alan Agius , // midknight41 , @@ -172,7 +172,7 @@ export function open(path: string | Buffer, flags: string | number, mode: number export function open(path: string | Buffer, flags: string | number, mode?: number): Promise; export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; -export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise<[number, Buffer]>; +export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): Promise; export function readFile(file: string | Buffer | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; export function readFile(file: string | Buffer | number, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; @@ -233,8 +233,8 @@ export function write(fd: number, buffer: Buffer, offset: number, length: number export function write(fd: number, data: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; export function write(fd: number, data: any, offset: number, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; export function write(fd: number, data: any, offset: number, encoding: string, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; -export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise<[number, Buffer]>; -export function write(fd: number, data: any, offset: number, encoding?: string): Promise<[number, string]>; +export function write(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): Promise; +export function write(fd: number, data: any, offset: number, encoding?: string): Promise; export function writeFile(file: string | Buffer | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; export function writeFile(file: string | Buffer | number, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): Promise; @@ -292,3 +292,13 @@ export interface WriteOptions { flag?: string; mode?: number; } + +export interface ReadResult { + bytesRead: number; + buffer: Buffer; +} + +export interface WriteResult { + bytesWritten: number; + buffer: Buffer; +} From 3b95a7158075fb8795e1de774740610ba5d99a64 Mon Sep 17 00:00:00 2001 From: Mika Kuitunen Date: Thu, 20 Jul 2017 19:59:37 +0300 Subject: [PATCH 0169/1139] [react-redux-toastr] Rewrite types for package v7.0.0 and TypeScript 2.4 (#18024) * react-redux-toastr: unify code style * react-redux-toastr: Change React.Component types to use state and props * react-redux-toastr: change to named imports * react-redux-toastr: remove module declaration * react-redux-toastr: add union types for known strings * react-redux-toastr: rename ToastrConfirmOptions to ConfirmToastrOptions for unified style, refine properties * react-redux-toastr: Add interfaces for all of the Toastr option objects * react-redux-toastr: Refactor some variables to alphabetical order * react-redux-toastr: Add interfaces to toastrs in reducer state, add toastr action payload, toastr reducer state * react-redux-toastr: Rename ToastOptions to ToastrOptions to unify style * react-redux-toastr: Rename ToastrOptions to ReduxToastrProps and rewrite properties * react-redux-toastr: Slight refactor of ReduxToastrProps * react-redux-toastr: Remove confirmOptions interface * react-redux-toastr: Remove duplicate ConfirmToastrOptions interface * react-redux-toastr: Rewrite ToastrEmitter, modify tests to comply with version 7.0.0 * react-redux-toastr: rewrite action creators, start using ToastrState * react-redux-toastr: Slight refactor, alphabetize stuff * react-redux-toastr: remove unused Component state and props * react-redux-toastr: fix TS version * Fix version number for TypeScript --- types/react-redux-toastr/index.d.ts | 223 ++++++++++-------- .../react-redux-toastr-tests.ts | 2 +- 2 files changed, 121 insertions(+), 104 deletions(-) diff --git a/types/react-redux-toastr/index.d.ts b/types/react-redux-toastr/index.d.ts index 012b6eb751..0f5b66903f 100644 --- a/types/react-redux-toastr/index.d.ts +++ b/types/react-redux-toastr/index.d.ts @@ -1,112 +1,129 @@ -// Type definitions for react-redux-toastr 3.7.0 +// Type definitions for react-redux-toastr 7.0.0 // Project: https://github.com/diegoddox/react-redux-toastr // Definitions by: Aleksandar Ivanov // Artyom Stukans +// Mika Kuitunen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -declare module "react-redux-toastr" { - import * as React from "react"; - import * as Redux from "redux"; +import { Component } from 'react'; +import { Action, ActionCreator, Reducer } from '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, - confirmOptions?: ConfirmOptions, - preventDuplicates?: boolean, - transitionIn?: 'bounceIn' | 'bounceInDown' | 'fadeIn', - transitionOut?: 'bounceOut' | 'bounceOutUp' | 'fadeOut', - progressBar?: boolean, - } +export type iconType = 'success' | 'info' | 'warning' | 'error'; +export type positionType = 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-ceter' | 'bottom-right'; +export type toastType = 'success' | 'info' | 'warning' | 'light' | 'error' | 'confirm' | 'message'; +export type transitionInType = 'bounceIn' | 'bounceInDown' | 'fadeIn'; +export type transitionOutType = 'bounceOut' | 'bounceOutUp' | 'fadeOut'; - interface ConfirmOptions { - okText: string, - cancelText: string - } - - /** - * Toastr react component. - */ - export default class ReduxToastr extends React.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?: React.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): void; - } - - /** - * 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; +interface BasicToastrOptions { + attention?: boolean; + className?: string; + component?: Component; + icon?: Component; + onCloseButtonClick?: () => void; + onHideComplete?: () => void; + onShowComplete?: () => void; + progressBar?: boolean; + removeOnHover?: boolean; + showCloseButton?: boolean; + timeOut?: number; + transitionIn?: transitionInType; + transitionOut?: transitionOutType; } + +interface LightToastrOptions { + attention?: boolean; + className?: string; + component?: Component; + icon?: iconType | Component; + onCloseButtonClick?: () => void; + onHideComplete?: () => void; + onShowComplete?: () => void; + progressBar?: boolean; + removeOnHover?: boolean; + showCloseButton?: boolean; + status?: iconType; + timeOut?: number; + transitionIn?: transitionInType; + transitionOut?: transitionOutType; +} + +interface ConfirmToastrOptions { + disableCancel?: boolean; + onCancel?: () => void; + onOk?: () => void; +} + +interface ConfirmToastrCustomOptions { + component: Component; +} + +export interface Toastr { + id: string; + message?: string; + options: BasicToastrOptions | LightToastrOptions; + position: positionType; + title?: string; + type: toastType; +} + +export interface AddToastPayload { + id?: string; + message?: string; + options?: BasicToastrOptions | LightToastrOptions; + position?: positionType; + title?: string; + type: toastType; +} + +export interface ToastrState { + confirm?: { + id: string; + message: string; + options: ConfirmToastrOptions | ConfirmToastrCustomOptions; + show: boolean; + }; + toastrs: Toastr[]; +} + +interface ReduxToastrProps { + confirmOptions?: { + cancelText: string; + okText: string; + }; + newestOnTop?: boolean; + options?: any; // This is currently not used, waiting for response from the package author to remove + position?: positionType + preventDuplicates?: boolean; + progressBar?: boolean; + timeOut?: number; + toastr?: ToastrState; + transitionIn?: transitionInType; + transitionOut?: transitionOutType; +} + +interface ToastrEmitter { + clean: () => void; + confirm: (message: string, options: ConfirmToastrOptions) => void; + error: (title: string, message: string, options?: BasicToastrOptions) => void; + info: (title: string, message: string, options?: BasicToastrOptions) => void; + light: (title: string, message: string, options?: LightToastrOptions) => void; + message: (title: string, message: string, options?: BasicToastrOptions) => void; + removeByType: (type: string) => void; + success: (title: string, message: string, options?: BasicToastrOptions) => void; + warning: (title: string, message: string, options?: BasicToastrOptions) => void; +} + +interface ToastrActionCreators { + add: (toastr: AddToastPayload) => Action; + clean: () => Action; + hideConfirm: () => Action; + remove: (id: string) => Action; + removeByType: (type: toastType) => Action; + showConfirm: (confirm: ConfirmToastrOptions | ConfirmToastrCustomOptions) => Action; +} + +export default class ReduxToastr extends Component {} +export const actions: ToastrActionCreators; +export const reducer: Reducer; +export const toastr: ToastrEmitter; diff --git a/types/react-redux-toastr/react-redux-toastr-tests.ts b/types/react-redux-toastr/react-redux-toastr-tests.ts index 6583c18211..c76208171c 100644 --- a/types/react-redux-toastr/react-redux-toastr-tests.ts +++ b/types/react-redux-toastr/react-redux-toastr-tests.ts @@ -17,7 +17,7 @@ function test() { 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.info("Info", "Info test", { timeOut: 1000, removeOnHover: true, onShowComplete: callback }); toastr.success("Test", "Test message", { component: new React.Component() }); } From 466067a98909f94284a0efec5b94c870e7e5c9f7 Mon Sep 17 00:00:00 2001 From: Stephen Ierodiaconou Date: Thu, 20 Jul 2017 18:05:29 +0100 Subject: [PATCH 0170/1139] [next-redux-wrapper] Add missing options paramter to definition (#18249) --- types/next-redux-wrapper/index.d.ts | 1 + types/next-redux-wrapper/next-redux-wrapper-tests.tsx | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts index d86e446c2a..dae0cf3841 100644 --- a/types/next-redux-wrapper/index.d.ts +++ b/types/next-redux-wrapper/index.d.ts @@ -57,6 +57,7 @@ declare namespace nextReduxWrapper { interface StoreCreatorOptions extends Options { isServer: boolean; req?: IncomingMessage; + query?: any; } function setPromise(Promise: any): void; diff --git a/types/next-redux-wrapper/next-redux-wrapper-tests.tsx b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx index de911679d2..37bd8af4b8 100644 --- a/types/next-redux-wrapper/next-redux-wrapper-tests.tsx +++ b/types/next-redux-wrapper/next-redux-wrapper-tests.tsx @@ -70,7 +70,7 @@ const com5 = withRedux( (initialState: InitialState, options: StoreCreatorOptions) => { - if (options.isServer) { + if (options.isServer || options.req || options.query) { const a = 1; } return createStore(reducer, initialState); From d94fa4a42e4988bb3bef20668df5ac2768f34a0f Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Thu, 20 Jul 2017 19:06:52 +0200 Subject: [PATCH 0171/1139] [editorconfig] change default indentation to 4 spaces for json and yaml files (#18245) --- .editorconfig | 1 - 1 file changed, 1 deletion(-) diff --git a/.editorconfig b/.editorconfig index c81d04c547..d3bd86c3ba 100644 --- a/.editorconfig +++ b/.editorconfig @@ -7,4 +7,3 @@ insert_final_newline = true [{*.json,*.yml}] indent_style = space -indent_size = 2 From 60f71e1cee12aee11b16617bd1cf7f417a197ca1 Mon Sep 17 00:00:00 2001 From: Ashish Gaurav Date: Thu, 20 Jul 2017 22:38:00 +0530 Subject: [PATCH 0172/1139] [dygraphs] vesions update (#18235) * @types/dygraphs: add legendFormatter in options * version update increment version to reflect changes in https://github.com/DefinitelyTyped/DefinitelyTyped/pull/18107 --- types/dygraphs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/dygraphs/index.d.ts b/types/dygraphs/index.d.ts index d4774c4944..33db704b3b 100644 --- a/types/dygraphs/index.d.ts +++ b/types/dygraphs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for dygraphs 1.1.1 +// Type definitions for dygraphs 1.1.2 // Project: http://dygraphs.com // Definitions by: Dan Vanderkam // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From e046dbc3bc95795584427fe398545146fc6e0090 Mon Sep 17 00:00:00 2001 From: Maarten Mulders Date: Thu, 20 Jul 2017 22:10:22 +0200 Subject: [PATCH 0173/1139] Improved type definitions for Recharts (#18256) * merged definitions with my own. therefor added some types and made changed the namespace back to a module. * fixxed lint errors * Remove ignore rules from tslint.json * Put everything in one module declaration --- types/recharts/index.d.ts | 1509 +++++++++++++++-------------- types/recharts/recharts-tests.tsx | 28 +- types/recharts/tslint.json | 2 +- 3 files changed, 790 insertions(+), 749 deletions(-) diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index b858309147..515cf6b297 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -1,747 +1,780 @@ // Type definitions for Recharts 0.22 // Project: http://recharts.org/ // Definitions by: Maarten Mulders +// Raphael Mueller // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as React from 'react'; -export namespace Recharts { - type Percentage = string; - type RechartsFunction = () => void; +export type Percentage = string; +export type RechartsFunction = () => void; - interface AreaProps { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; - dataKey?: string | number; - xAxisId?: string | number; - yAxisId?: string | number; - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; - dot?: boolean | any | React.ReactElement | RechartsFunction; - activeDot?: boolean | any | React.ReactElement | RechartsFunction; - label?: boolean | any | React.ReactElement | RechartsFunction; - stroke?: string; - layout?: 'horizontal' | 'vertical'; - baseLine?: number | any[]; - points?: any[]; - stackId?: string | number; - connectNulls?: boolean; - unit?: string | number; - name?: string | number; - isAnimationActive?: boolean; - animationBegin?: number; - animationDuration?: number; - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Area extends React.Component { - } - interface AreaChartProps { - layout?: 'horizontal' | 'vertical'; - syncId?: string; - width: number; - height: number; - data: any[]; - margin?: any; - stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette'; - baseValue?: number | 'dataMin' | 'dataMax' | 'auto'; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class AreaChart extends React.Component { - } - interface BarProps { - layout?: 'horizontal' | 'vertical'; - dataKey?: string | number; - xAxisId?: string | number; - yAxisId?: string | number; - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; - label?: boolean | any | React.ReactElement | RechartsFunction; - data?: any[]; - barSize?: number; - maxBarSize?: number; - minPointSize?: number; - shape?: React.ReactElement | RechartsFunction; - stackId?: string | number; - unit?: string | number; - name?: string | number; - isAnimationActive?: boolean; - animationBegin?: number; - animationDuration?: number; - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Bar extends React.Component { - } - interface BarChartProps { - layout?: 'horizontal' | 'vertical'; - syncId?: string; - width?: number; - height?: number; - data?: any[]; - margin?: any; - barCategoryGap?: Percentage | number; - barGap?: Percentage | number; - barSize?: number; - maxBarSize?: number; - stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette' | 'sign'; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class BarChart extends React.Component { - } - interface BrushProps { - dataKey: number | string; - x?: number; - y?: number; - width?: number; - height?: number; - data: any[]; - travellerWidth?: number; - startIndex?: number; - endIndex?: number; - tickFormatter?: RechartsFunction; - onChange?: RechartsFunction; - } - class Brush extends React.Component { - } - interface CartesianAxisProps { - x?: number; - y?: number; - width?: number; - height?: number; - orientation?: 'top' | 'bottom' | 'left' | 'right'; - viewBox?: any; - axisLine?: boolean | any; - tickLine?: boolean | any; - minTickGap?: number; - tickSize?: number; - interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; - tick?: boolean | any | React.ReactElement | RechartsFunction; - label?: string | number | React.ReactElement | RechartsFunction; - mirror?: boolean; - } - class CartesianAxis extends React.Component { - } - interface CartesianGridProps { - x?: number; - y?: number; - width?: number; - height?: number; - horizontal?: boolean; - vertical?: boolean; - horizontalPoints?: any[]; - verticalPoints?: any[]; - } - class CartesianGrid extends React.Component { - } - interface CellProps { - fill?: string; - stroke?: string; - } - class Cell extends React.Component { - } - interface ComposedChartProps { - layout?: 'horizontal' | 'vertical'; - syncId?: string; - width?: number; - height?: number; - data?: any[]; - margin?: any; - barCategoryGap?: Percentage | number; - barGap?: number; - barSize?: number; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class ComposedChart extends React.Component { - } - interface CrossProps { - x?: number; - y?: number; - top?: number; - left?: number; - width?: number; - height?: number; - } - class Cross extends React.Component { - } - interface CurveProps { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; - points: any[]; - layout?: 'horizontal' | 'vertical'; - baseLine?: number | any[]; - connectNulls?: boolean; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Curve extends React.Component { - } - interface DotProps { - cx: number; - cy: number; - r: number; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Dot extends React.Component { - } - interface ErrorBarProps { - dataKey?: string | number; - width?: number; - strokeWidth?: string; - stroke?: string; - direction?: string; - } - class ErrorBar extends React.Component { - } - interface LegendProps { - width?: number; - height?: number; - layout?: 'horizontal' | 'vertical'; - align?: 'left' | 'center' | 'right'; - verticalAlign?: 'top' | 'middle' | 'bottom'; - iconSize?: number; - iconType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye'; - payload?: any[]; - chartWidth: number; - chartHeight: number; - margin?: any; - content?: React.ReactElement | RechartsFunction; - wrapperStyle?: any; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Legend extends React.Component { - } - interface LineProps { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; - dataKey: string | number; - xAxisId?: string | number; - yAxisId?: string | number; - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; - dot?: boolean | any | React.ReactElement | RechartsFunction; - activeDot?: boolean | any | React.ReactElement | RechartsFunction; - label?: boolean | any | React.ReactElement | RechartsFunction; - points: any[]; - layout?: 'horizontal' | 'vertical'; - connectNulls?: boolean; - unit?: string | number; - name?: string | number; - isAnimationActive?: boolean; - animationBegin?: number; - animationDuration?: number; - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Line extends React.Component { - } - interface LineChartProps { - layout?: 'horizontal' | 'vertical'; - syncId?: string; - width?: number; - height?: number; - data?: any[]; - margin?: any; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class LineChart extends React.Component { - } - interface PieProps { - cx?: Percentage | number; - cy?: Percentage | number; - innerRadius?: Percentage | number; - outerRadius?: Percentage | number; - startAngle?: number; - endAngle?: number; - minAngle?: number; - paddingAngle?: number; - nameKey?: string; - valueKey?: string; - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; - label?: boolean | any | React.ReactElement | RechartsFunction; - labelLine?: boolean | any | React.ReactElement | RechartsFunction; - data: any[]; - activeIndex: any[]; - activeShape: any | React.ReactElement | RechartsFunction; - isAnimationActive?: boolean; - animationBegin?: number; - animationDuration?: number; - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear' | RechartsFunction; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Pie extends React.Component { - } - interface PieChartProps { - width: number; - height: number; - margin?: any; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class PieChart extends React.Component { - } - interface PolarAngleAxisProps { - dataKey: string | number; - cx: number; - cy: number; - radius: Percentage | number; - axisLine?: boolean | any; - axisLineType?: string; - tickLine?: boolean | any; - tick?: boolean | any | React.ReactElement | RechartsFunction; - ticks: any[]; - orient?: string; - tickFormatter: RechartsFunction; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class PolarAngleAxis extends React.Component { - } - interface PolarGridProps { - cx: number; - cy: number; - innerRadius: number; - outerRadius: number; - polarAngles: any[]; - polarRadius: any[]; - gridType?: 'polygon' | 'circle'; - } - class PolarGrid extends React.Component { - } - interface PolarRadiusAxisProps { - angle?: number; - cx: number; - cy: number; - domain?: any[]; - label?: string | number | React.ReactElement | RechartsFunction; - orientation?: "left" | "right" | "middle"; - axisLine?: boolean | any; - tick?: boolean | any | Element | RechartsFunction; - tickFormatter: RechartsFunction; - tickCount?: number; - scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | RechartsFunction; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class PolarRadiusAxis extends React.Component { - } - interface PolygonProps { - points: any[]; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Polygon extends React.Component { - } - interface RadarProps { - dataKey: string | number; - points: any[]; - shape: Element | RechartsFunction; - dot?: boolean | any | Element | RechartsFunction; - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; - label?: boolean | any | Element | RechartsFunction; - isAnimationActive?: boolean; - animationBegin?: number; - animationDuration?: number; - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; - } - class Radar extends React.Component { - } - interface RadarChartProps { - width: number; - height: number; - cx?: Percentage | number; - cy?: Percentage | number; - startAngle?: number; - innerRadius?: Percentage | number; - outerRadius?: Percentage | number; - margin?: any; - clockWise?: boolean; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - onClick?: RechartsFunction; - } - class RadarChart extends React.Component { - } - interface RadialBarProps { - cx?: number; - cy?: number; - startAngle?: number; - endAngle?: number; - maxAngle?: number; - minAngle?: number; - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; - label?: boolean | any | React.ReactElement | RechartsFunction; - background?: boolean | any | React.ReactElement | RechartsFunction; - data: any[]; - isAnimationActive?: boolean; - animationBegin?: number; - animationDuration?: number; - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class RadialBar extends React.Component { - } - interface RadialBarChartProps { - width?: number; - height?: number; - data?: any[]; - margin?: any; - barCategoryGap?: Percentage | number; - barGap?: number; - cx?: Percentage | number; - cy?: Percentage | number; - innerRadius?: Percentage | number; - outerRadius?: Percentage | number; - barSize?: number; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - onClick?: RechartsFunction; - } - class RadialBarChart extends React.Component { - } - interface RectangleProps { - x?: number; - y?: number; - width?: number; - height?: number; - radius?: number; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Rectangle extends React.Component { - } - interface ReferenceAreaProps { - xAxisId?: string | number; - yAxisId?: string | number; - x1?: number | string; - x2?: number | string; - y1?: number | string; - y2?: number | string; - alwaysShow?: boolean; - viewBox: any; - xAxis: any; - yAxis: any; - label?: string | number | React.ReactElement | RechartsFunction; - isFront?: boolean; - } - class ReferenceArea extends React.Component { - } - interface ReferenceDotProps { - xAxisId?: string | number; - yAxisId?: string | number; - x: number | string; - y: number | string; - alwaysShow?: boolean; - xAxis: any; - yAxis: any; - label?: string | number | React.ReactElement | RechartsFunction; - isFront?: boolean; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class ReferenceDot extends React.Component { - } - interface ReferenceLineProps { - xAxisId?: string | number; - yAxisId?: string | number; - x?: number | string; - y?: number | string; - alwaysShow?: boolean; - viewBox: any; - xAxis: any; - yAxis: any; - label?: string | number | React.ReactElement | RechartsFunction; - isFront?: boolean; - } - class ReferenceLine extends React.Component { - } - interface ResponsiveContainerProps { - aspect?: number; - width?: Percentage | number; - height?: Percentage | number; - minWidth?: number; - minHeight?: number; - debounce?: number; - } - class ResponsiveContainer extends React.Component { - } - interface ScatterProps { - legendType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; - xAxisId?: string | number; - yAxisId?: string | number; - zAxisId?: string | number; - line?: boolean | any | React.ReactElement | RechartsFunction; - shape?: 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | React.ReactElement | RechartsFunction; - lineType?: 'joint' | 'fitting'; - points: any[]; - isAnimationActive?: boolean; - animationBegin?: number; - animationDuration?: number; - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Scatter extends React.Component { - } - interface ScatterChartProps { - width: number; - height: number; - margin?: any; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class ScatterChart extends React.Component { - } - interface SectorProps { - cx?: number; - cy?: number; - innerRadius?: number; - outerRadius?: number; - startAngle?: number; - endAngle?: number; - cornerRadius?: number; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class Sector extends React.Component { - } - interface TextProps { - scaleToFit?: boolean; - angle?: number; - width?: number; - textAnchor?: 'start' | 'middle' | 'end' | 'inherit'; - verticalAnchor?: 'start' | 'middle' | 'end'; - } - class Text extends React.Component { - } - interface TooltipProps { - separator?: string; - offset?: number; - itemStyle?: any; - wrapperStyle?: any; - labelStyle?: any; - cursor?: boolean | any | React.ReactElement; - viewBox: any; - active?: boolean; - coordinate?: any; - payload?: any[]; - label?: string | number; - content?: React.ReactElement | RechartsFunction; - formatter?: RechartsFunction; - labelFormatter?: RechartsFunction; - itemSorter?: RechartsFunction; - isAnimationActive?: boolean; - animationBegin?: number; - animationDuration?: number; - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; - } - class Tooltip extends React.Component { - } - interface TreemapProps { - width: number; - height: number; - dataKey?: string; - aspectRatio: number; - isAnimationActive?: boolean; - animationBegin?: number; - animationDuration?: number; - animationEasing?: 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; - } - class Treemap extends React.Component { - } - interface XAxisProps { - hide?: boolean; - dataKey?: string | number; - xAxisId?: string | number; - width?: number; - height?: number; - orientation?: 'bottom' | 'top'; - type?: 'number' | 'category'; - allowDecimals?: boolean; - allowDataOverflow?: boolean; - tickCount?: number; - domain?: any[]; - interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; - padding?: any; - minTickGap?: number; - axisLine?: boolean | any; - tickLine?: boolean | any; - tickSize?: number; - tickFormatter?: RechartsFunction; - ticks?: any[]; - tick?: boolean | any | React.ReactElement; - mirror?: boolean; - reversed?: boolean; - label?: string | number | React.ReactElement; - scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | RechartsFunction; - unit?: string | number; - name?: string | number; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class XAxis extends React.Component { - } - interface YAxisProps { - hide?: boolean; - dataKey?: string | number; - yAxisId?: string | number; - width?: number; - height?: number; - orientation?: 'left' | 'right'; - type?: 'number' | 'category'; - domain?: any[]; - interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; - padding?: any; - minTickGap?: number; - allowDecimals?: boolean; - allowDataOverflow?: boolean; - axisLine?: boolean | any; - tickLine?: boolean | any; - tickSize?: number; - tickFormatter?: RechartsFunction; - ticks?: any[]; - tick?: boolean | any | React.ReactElement; - mirror?: boolean; - reversed?: boolean; - label?: string | number | React.ReactElement; - scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | RechartsFunction; - unit?: string | number; - name?: string | number; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - } - class YAxis extends React.Component { - } - interface ZAxisProps { - dataKey: string | number; - zAxisId?: string | number; - range?: any[]; - unit?: string | number; - name?: string | number; - scale?: 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold' | RechartsFunction; - } - class ZAxis extends React.Component { - } +export type LegendType = 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; +export type LayoutType = 'horizontal' | 'vertical'; +export type AnimationEasingType = 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; +export type ScaleType = 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold'; + +export interface Margin { + top: number; + right: number; + bottom: number; + left: number; } + +export interface AreaProps { + type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; + dataKey?: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + legendType?: LegendType; + dot?: boolean | any | React.ReactElement | RechartsFunction; + activeDot?: boolean | any | React.ReactElement | RechartsFunction; + label?: boolean | any | React.ReactElement | RechartsFunction; + stroke?: string; + layout?: LayoutType; + baseLine?: number | any[]; + points?: any[]; + stackId?: string | number; + connectNulls?: boolean; + unit?: string | number; + name?: string | number; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Area extends React.Component {} + +export interface AreaChartProps { + layout?: LayoutType; + syncId?: string; + width: number; + height: number; + data: any[]; + margin?: Margin; + stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette'; + baseValue?: number | 'dataMin' | 'dataMax' | 'auto'; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class AreaChart extends React.Component {} + +export interface BarProps { + layout?: LayoutType; + dataKey?: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + legendType?: LegendType; + label?: boolean | any | React.ReactElement | RechartsFunction; + data?: any[]; + barSize?: number; + maxBarSize?: number; + minPointSize?: number; + shape?: React.ReactElement | RechartsFunction; + stackId?: string | number; + unit?: string | number; + name?: string | number; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Bar extends React.Component {} + +export interface BarChartProps { + layout?: LayoutType; + syncId?: string; + width?: number; + height?: number; + data?: any[]; + margin?: Margin; + barCategoryGap?: Percentage | number; + barGap?: Percentage | number; + barSize?: number; + maxBarSize?: number; + stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette' | 'sign'; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class BarChart extends React.Component {} + +export interface BrushProps { + dataKey: number | string; + x?: number; + y?: number; + width?: number; + height?: number; + data: any[]; + travellerWidth?: number; + startIndex?: number; + endIndex?: number; + tickFormatter?: RechartsFunction; + onChange?: RechartsFunction; +} +export class Brush extends React.Component {} + +export interface CartesianAxisProps { + x?: number; + y?: number; + width?: number; + height?: number; + orientation?: 'top' | 'bottom' | 'left' | 'right'; + viewBox?: any; + axisLine?: boolean | any; + tickLine?: boolean | any; + minTickGap?: number; + tickSize?: number; + interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; + tick?: boolean | any | React.ReactElement | RechartsFunction; + label?: string | number | React.ReactElement | RechartsFunction; + mirror?: boolean; +} +export class CartesianAxis extends React.Component {} + +export interface CartesianGridProps { + x?: number; + y?: number; + width?: number; + height?: number; + horizontal?: boolean; + vertical?: boolean; + horizontalPoints?: any[]; + verticalPoints?: any[]; +} +export class CartesianGrid extends React.Component {} + +export interface CellProps { + fill?: string; + stroke?: string; +} +export class Cell extends React.Component {} + +export interface ComposedChartProps { + layout?: LayoutType; + syncId?: string; + width?: number; + height?: number; + data?: any[]; + margin?: Margin; + barCategoryGap?: Percentage | number; + barGap?: number; + barSize?: number; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class ComposedChart extends React.Component {} + +export interface CrossProps { + x?: number; + y?: number; + top?: number; + left?: number; + width?: number; + height?: number; +} +export class Cross extends React.Component {} + +export interface CurveProps { + type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; + points: any[]; + layout?: LayoutType; + baseLine?: number | any[]; + connectNulls?: boolean; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Curve extends React.Component {} + +export interface DotProps { + cx: number; + cy: number; + r: number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Dot extends React.Component {} + +export interface ErrorBarProps { + dataKey?: string | number; + width?: number; + strokeWidth?: string; + stroke?: string; + direction?: string; +} +export class ErrorBar extends React.Component {} + +export interface LegendProps { + width?: number; + height?: number; + layout?: LayoutType; + align?: 'left' | 'center' | 'right'; + verticalAlign?: 'top' | 'middle' | 'bottom'; + iconSize?: number; + iconType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye'; + payload?: any[]; + chartWidth: number; + chartHeight: number; + margin?: Margin; + content?: React.ReactElement | RechartsFunction; + wrapperStyle?: any; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Legend extends React.Component {} + +export interface LineProps { + type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; + dataKey: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + legendType?: LegendType; + dot?: boolean | any | React.ReactElement | RechartsFunction; + activeDot?: boolean | any | React.ReactElement | RechartsFunction; + label?: boolean | any | React.ReactElement | RechartsFunction; + points: any[]; + layout?: LayoutType; + connectNulls?: boolean; + unit?: string | number; + name?: string | number; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Line extends React.Component {} + +export interface LineChartProps { + layout?: LayoutType; + syncId?: string; + width?: number; + height?: number; + data?: any[]; + margin?: Margin; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class LineChart extends React.Component {} + +export interface PieProps { + cx?: Percentage | number; + cy?: Percentage | number; + innerRadius?: Percentage | number; + outerRadius?: Percentage | number; + startAngle?: number; + endAngle?: number; + minAngle?: number; + paddingAngle?: number; + nameKey?: string; + valueKey?: string; + legendType?: LegendType; + label?: boolean | any | React.ReactElement | RechartsFunction; + labelLine?: boolean | any | React.ReactElement | RechartsFunction; + data: any[]; + activeIndex: any[]; + activeShape: any | React.ReactElement | RechartsFunction; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType | RechartsFunction; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Pie extends React.Component {} + +export interface PieChartProps { + width: number; + height: number; + margin?: Margin; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class PieChart extends React.Component {} + +export interface PolarAngleAxisProps { + dataKey: string | number; + cx: number; + cy: number; + radius: Percentage | number; + axisLine?: boolean | any; + axisLineType?: string; + tickLine?: boolean | any; + tick?: boolean | any | React.ReactElement | RechartsFunction; + ticks: any[]; + orient?: string; + tickFormatter: RechartsFunction; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class PolarAngleAxis extends React.Component {} + +export interface PolarGridProps { + cx: number; + cy: number; + innerRadius: number; + outerRadius: number; + polarAngles: any[]; + polarRadius: any[]; + gridType?: 'polygon' | 'circle'; +} +export class PolarGrid extends React.Component {} + +export interface PolarRadiusAxisProps { + angle?: number; + cx: number; + cy: number; + domain?: any[]; + label?: string | number | React.ReactElement | RechartsFunction; + orientation?: "left" | "right" | "middle"; + axisLine?: boolean | any; + tick?: boolean | any | Element | RechartsFunction; + tickFormatter: RechartsFunction; + tickCount?: number; + scale?: ScaleType | RechartsFunction; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class PolarRadiusAxis extends React.Component {} + +export interface PolygonProps { + points: any[]; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Polygon extends React.Component {} + +export interface RadarProps { + dataKey: string | number; + points: any[]; + shape: Element | RechartsFunction; + dot?: boolean | any | Element | RechartsFunction; + legendType?: LegendType; + label?: boolean | any | Element | RechartsFunction; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; +} +export class Radar extends React.Component {} + +export interface RadarChartProps { + width: number; + height: number; + cx?: Percentage | number; + cy?: Percentage | number; + startAngle?: number; + innerRadius?: Percentage | number; + outerRadius?: Percentage | number; + margin?: Margin; + clockWise?: boolean; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onClick?: RechartsFunction; +} +export class RadarChart extends React.Component {} + +export interface RadialBarProps { + cx?: number; + cy?: number; + startAngle?: number; + endAngle?: number; + maxAngle?: number; + minAngle?: number; + legendType?: LegendType; + label?: boolean | any | React.ReactElement | RechartsFunction; + background?: boolean | any | React.ReactElement | RechartsFunction; + data: any[]; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class RadialBar extends React.Component {} + +export interface RadialBarChartProps { + width?: number; + height?: number; + data?: any[]; + margin?: Margin; + barCategoryGap?: Percentage | number; + barGap?: number; + cx?: Percentage | number; + cy?: Percentage | number; + innerRadius?: Percentage | number; + outerRadius?: Percentage | number; + barSize?: number; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onClick?: RechartsFunction; +} +export class RadialBarChart extends React.Component {} + +export interface RectangleProps { + x?: number; + y?: number; + width?: number; + height?: number; + radius?: number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Rectangle extends React.Component {} + +export interface ReferenceAreaProps { + xAxisId?: string | number; + yAxisId?: string | number; + x1?: number | string; + x2?: number | string; + y1?: number | string; + y2?: number | string; + alwaysShow?: boolean; + viewBox: any; + xAxis: any; + yAxis: any; + label?: string | number | React.ReactElement | RechartsFunction; + isFront?: boolean; +} +export class ReferenceArea extends React.Component {} + +export interface ReferenceDotProps { + xAxisId?: string | number; + yAxisId?: string | number; + x: number | string; + y: number | string; + alwaysShow?: boolean; + xAxis: any; + yAxis: any; + label?: string | number | React.ReactElement | RechartsFunction; + isFront?: boolean; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class ReferenceDot extends React.Component {} + +export interface ReferenceLineProps { + xAxisId?: string | number; + yAxisId?: string | number; + x?: number | string; + y?: number | string; + alwaysShow?: boolean; + viewBox: any; + xAxis: any; + yAxis: any; + label?: string | number | React.ReactElement | RechartsFunction; + isFront?: boolean; +} +export class ReferenceLine extends React.Component {} + +export interface ResponsiveContainerProps { + aspect?: number; + width?: Percentage | number; + height?: Percentage | number; + minWidth?: number; + minHeight?: number; + debounce?: number; +} +export class ResponsiveContainer extends React.Component {} + +export interface ScatterProps { + legendType?: LegendType; + xAxisId?: string | number; + yAxisId?: string | number; + zAxisId?: string | number; + line?: boolean | any | React.ReactElement | RechartsFunction; + shape?: 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | React.ReactElement | RechartsFunction; + lineType?: 'joint' | 'fitting'; + points: any[]; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Scatter extends React.Component {} + +export interface ScatterChartProps { + width: number; + height: number; + margin?: Margin; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class ScatterChart extends React.Component {} + +export interface SectorProps { + cx?: number; + cy?: number; + innerRadius?: number; + outerRadius?: number; + startAngle?: number; + endAngle?: number; + cornerRadius?: number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class Sector extends React.Component {} + +export interface TextProps { + scaleToFit?: boolean; + angle?: number; + width?: number; + textAnchor?: 'start' | 'middle' | 'end' | 'inherit'; + verticalAnchor?: 'start' | 'middle' | 'end'; +} +export class Text extends React.Component {} + +export interface ViewBox { + x: number; + y: number; + width: number; + height: number; +} +export interface Coordinate { + x: number; + y: number; +} +export interface TooltipPayload { + name: string; + value: number; + unit: string; +} +export interface TooltipProps { + separator?: string; + offset?: number; + itemStyle?: any; + wrapperStyle?: any; + labelStyle?: any; + cursor?: boolean | any | React.ReactElement; + viewBox: ViewBox; + active?: boolean; + coordinate?: Coordinate; + payload?: TooltipPayload[]; + label?: string | number; + content?: React.ReactElement | RechartsFunction; + formatter?: RechartsFunction; + labelFormatter?: RechartsFunction; + itemSorter?: RechartsFunction; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; +} +export class Tooltip extends React.Component {} + +export interface TreemapProps { + width: number; + height: number; + dataKey?: string; + aspectRatio: number; + isAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; +} +export class Treemap extends React.Component {} + +export interface XPadding { + left: number; + right: number; +} +export interface XAxisProps { + hide?: boolean; + dataKey?: string | number; + xAxisId?: string | number; + width?: number; + height?: number; + orientation?: 'bottom' | 'top'; + type?: 'number' | 'category'; + allowDecimals?: boolean; + allowDataOverflow?: boolean; + tickCount?: number; + domain?: any[]; + interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; + padding?: XPadding; + minTickGap?: number; + axisLine?: boolean | any; + tickLine?: boolean | any; + tickSize?: number; + tickFormatter?: RechartsFunction; + ticks?: any[]; + tick?: boolean | any | React.ReactElement; + mirror?: boolean; + reversed?: boolean; + label?: string | number | React.ReactElement; + scale?: ScaleType | RechartsFunction; + unit?: string | number; + name?: string | number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class XAxis extends React.Component {} + +export interface YPadding { + top: number; + bottom: number; +} +export interface YAxisProps { + hide?: boolean; + dataKey?: string | number; + yAxisId?: string | number; + width?: number; + height?: number; + orientation?: 'left' | 'right'; + type?: 'number' | 'category'; + domain?: any[]; + interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; + padding?: YPadding; + minTickGap?: number; + allowDecimals?: boolean; + allowDataOverflow?: boolean; + axisLine?: boolean | any; + tickLine?: boolean | any; + tickSize?: number; + tickFormatter?: RechartsFunction; + ticks?: any[]; + tick?: boolean | any | React.ReactElement; + mirror?: boolean; + reversed?: boolean; + label?: string | number | React.ReactElement; + scale?: ScaleType | RechartsFunction; + unit?: string | number; + name?: string | number; + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; +} +export class YAxis extends React.Component {} + +export interface ZAxisProps { + dataKey: string | number; + zAxisId?: string | number; + range?: any[]; + unit?: string | number; + name?: string | number; + scale?: ScaleType | RechartsFunction; +} +export class ZAxis extends React.Component {} diff --git a/types/recharts/recharts-tests.tsx b/types/recharts/recharts-tests.tsx index 62d3b6f830..70f60d5d74 100644 --- a/types/recharts/recharts-tests.tsx +++ b/types/recharts/recharts-tests.tsx @@ -1,19 +1,27 @@ import * as React from 'react'; import * as ReactDOM from 'react-dom'; -import { Recharts } from 'recharts'; - -const data: any[] = []; +import { CartesianGrid, Line, LineChart, XAxis, YAxis } from 'recharts'; const Component = (props: {}) => { + const data = [ + {name: 'Page A', uv: 4000, pv: 2400, amt: 2400}, + {name: 'Page B', uv: 3000, pv: 1398, amt: 2210}, + {name: 'Page C', uv: 2000, pv: 9800, amt: 2290}, + {name: 'Page D', uv: 2780, pv: 3908, amt: 2000}, + {name: 'Page E', uv: 1890, pv: 4800, amt: 2181}, + {name: 'Page F', uv: 2390, pv: 3800, amt: 2500}, + {name: 'Page G', uv: 3490, pv: 4300, amt: 2100}, + ]; + return ( - - - - - - - + + + + + + + ); }; diff --git a/types/recharts/tslint.json b/types/recharts/tslint.json index d88586e5bd..b4b47a0378 100644 --- a/types/recharts/tslint.json +++ b/types/recharts/tslint.json @@ -1,3 +1,3 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json" } From 2b0f00ff2771a92e82055d38282800d0cb04fe8d Mon Sep 17 00:00:00 2001 From: Bill Kim Date: Thu, 20 Jul 2017 15:53:43 -0700 Subject: [PATCH 0174/1139] Update kafka node (#18267) * updating types for kafka-node * fixed typos * linter errors * typo --- types/kafka-node/index.d.ts | 44 ++++++++++++++++++---------- types/kafka-node/kafka-node-tests.ts | 2 +- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/types/kafka-node/index.d.ts b/types/kafka-node/index.d.ts index d025f849ae..1a20c7f969 100644 --- a/types/kafka-node/index.d.ts +++ b/types/kafka-node/index.d.ts @@ -6,26 +6,27 @@ // # Classes export class Client { constructor(connectionString: string, clientId?: string, options?: ZKOptions, noBatchOptions?: AckBatchOptions, sslOptions?: any); - close(callback?: () => void): void; - topicExists(topics: string[], callback: (err?: TopicsNotExistError | any) => any): void; + close(cb?: () => void): void; + topicExists(topics: string[], cb: (error?: TopicsNotExistError | any) => any): void; refreshMetadata(topics: string[], cb?: (error?: any) => any): void; - sendOffsetCommitV2Request(group: string, generationId: number, memberId: string, commits: OffsetCommitRequest[], cb: () => void): void; + sendOffsetCommitV2Request(group: string, generationId: number, memberId: string, commits: OffsetCommitRequest[], cb: (error: any, data: any) => any): void; } export class KafkaClient extends Client { constructor(options?: KafkaClientOptions); + on(eventName: "ready", cb: () => any): this; + on(eventName: "error", cb: (error: any) => any): this; connect(): void; } export class Producer { - constructor(client: Client, options?: ProducerOptions, customPartitioner?: any); + constructor(client: Client, options?: ProducerOptions, customPartitioner?: CustomPartitioner); on(eventName: "ready", cb: () => any): void; on(eventName: "error", cb: (error: any) => any): void; send(payloads: ProduceRequest[], cb: (error: any, data: any) => any): void; - createTopics(topics: string[], async: true, cb: (error?: any, data?: any) => any): void; - createTopics(topics: string[], async: false, cb: () => any): void; - createTopics(topics: string[], cb: (error?: any, data?: any) => any): void; - close(): void; + createTopics(topics: string[], async: boolean, cb: (error: any, data: any) => any): void; + createTopics(topics: string[], cb: (error: any, data: any) => any): void; + close(cb?: () => any): void; } export class HighLevelProducer extends Producer { @@ -54,14 +55,16 @@ export class HighLevelConsumer { client: Client; on(eventName: "message", cb: (message: Message) => any): void; on(eventName: "error" | "offsetOutOfRange", cb: (error: any) => any): void; + on(eventName: "rebalancing" | "rebalanced", cb: () => any): void; addTopics(topics: string[] | Topic[], cb?: (error: any, added: string[] | Topic[]) => any): void; removeTopics(topics: string | string[], cb: (error: any, removed: number) => any): void; commit(cb: (error: any, data: any) => any): void; commit(force: boolean, cb: (error: any, data: any) => any): void; + sendOffsetCommitRequest(commits: OffsetCommitRequest[], cb: (error: any, data: any) => any): void; setOffset(topic: string, partition: number, offset: number): void; pause(): void; resume(): void; - close(force: boolean, cb: () => any): void; + close(force: boolean, cb: (error: any) => any): void; close(cb: () => any): void; } @@ -69,11 +72,13 @@ export class ConsumerGroup extends HighLevelConsumer { constructor(options: ConsumerGroupOptions, topics: string[] | string); generationId: number; memberId: string; + client: KafkaClient & Client; } export class Offset { constructor(client: Client); - on(eventName: string, cb: (error?: any) => any): void; + on(eventName: "ready" | "connect", cb: () => any): void; + on(eventName: "error", cb: (error: any) => any): void; fetch(payloads: OffsetRequest[], cb: (error: any, data: any) => any): void; commit(groupId: string, payloads: OffsetCommitRequest[], cb: (error: any, data: any) => any): void; fetchCommits(groupId: string, payloads: OffsetFetchRequest[], cb: (error: any, data: any) => any): void; @@ -106,13 +111,13 @@ export interface KafkaClientOptions { kafkaHost?: string; connectTimeout?: number; requestTimeout?: number; - authConnect?: boolean; - connectRetryOptions?: ConnectRetryOptions; + autoConnect?: boolean; + connectRetryOptions?: RetryOptions; sslOptions?: any; clientId?: string; } -export interface ConnectRetryOptions { +export interface RetryOptions { retries?: number; factor?: number; minTimeout?: number; @@ -153,17 +158,21 @@ export interface ConsumerOptions { export interface HighLevelConsumerOptions extends ConsumerOptions { id?: string; + maxNumSegments?: number; + maxTickMessages?: number; + rebalanceRetry?: RetryOptions; } export interface CustomPartitionAssignmentProtocol { name: string; version: number; userData: {}; - assign(topicPattern: any, groupMembers: any, callback: (error: any, result: any) => void): void; + assign(topicPattern: any, groupMembers: any, cb: (error: any, result: any) => void): void; } export interface ConsumerGroupOptions { - host: string; + kafkaHost?: string; + host?: string; zk?: ZKOptions; batch?: AckBatchOptions; ssl?: boolean; @@ -172,13 +181,14 @@ export interface ConsumerGroupOptions { sessionTimeout?: number; protocol?: Array<"roundrobin" | "range" | CustomPartitionAssignmentProtocol>; fromOffset?: "earliest" | "latest" | "none"; + outOfRangeOffset?: "earliest" | "latest" | "none"; migrateHLC?: boolean; migrateRolling?: boolean; autoCommit?: boolean; autoCommitIntervalMs?: number; fetchMaxWaitMs?: number; - paused?: boolean; maxNumSegments?: number; + maxTickMessages?: number; fetchMinBytes?: number; fetchMaxBytes?: number; retries?: number; @@ -217,3 +227,5 @@ export interface OffsetFetchRequest { export class TopicsNotExistError extends Error { topics: string | string[]; } + +export type CustomPartitioner = (partitions: number[], key: any) => number; diff --git a/types/kafka-node/kafka-node-tests.ts b/types/kafka-node/kafka-node-tests.ts index b1f10eb291..0ffe5d86b7 100644 --- a/types/kafka-node/kafka-node-tests.ts +++ b/types/kafka-node/kafka-node-tests.ts @@ -28,7 +28,7 @@ const optionsKafkaClient = new kafka.KafkaClient({ kafkaHost: 'localhost:2181', connectTimeout: 1000, requestTimeout: 1000, - authConnect: true, + autoConnect: true, sslOptions: {}, clientId: "client id", connectRetryOptions: { From b50f4e455651dc8f93e4657bd0984e800de1eb19 Mon Sep 17 00:00:00 2001 From: Markus Chmelar Date: Fri, 21 Jul 2017 00:53:59 +0200 Subject: [PATCH 0175/1139] Leaflet: Polygon Constructor with Multi-Dimensional Array (#18260) --- types/leaflet/index.d.ts | 4 ++-- types/leaflet/leaflet-tests.ts | 10 ++++++++++ 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 5589ad9303..119f5d3006 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -615,13 +615,13 @@ declare namespace L { function polyline(latlngs: LatLngExpression[], options?: PolylineOptions): Polyline; class Polygon extends InternalPolyline { - constructor(latlngs: LatLngExpression[], options?: PolylineOptions); + constructor(latlngs: LatLngExpression[] | LatLngExpression[][], options?: PolylineOptions); toGeoJSON(): GeoJSONFeature; feature?: GeoJSONFeature; } - function polygon(latlngs: LatLngExpression[], options?: PolylineOptions): Polygon; + function polygon(latlngs: LatLngExpression[] | LatLngExpression[][], options?: PolylineOptions): Polygon; class Rectangle extends Polygon { constructor(latLngBounds: LatLngBoundsExpression, options?: PolylineOptions); diff --git a/types/leaflet/leaflet-tests.ts b/types/leaflet/leaflet-tests.ts index 1aa11c3442..7b3872f6bc 100644 --- a/types/leaflet/leaflet-tests.ts +++ b/types/leaflet/leaflet-tests.ts @@ -450,6 +450,16 @@ L.marker([1, 2], { className: 'my-div-icon' })); +const latLngs = [ + { lat: 0, lng: 0 }, + { lat: 1, lng: 1 } +]; +let polygon = new L.Polygon(latLngs); +let polygonExclusion = new L.Polygon([latLngs, latLngs]); + +L.polygon(latLngs).addTo(map); +L.polygon([latLngs, latLngs]).addTo(map); + L.Util.extend({}); L.Util.create({}); L.Util.bind(() => {}, {}); From d00f967ff826ddb226f6d90d6252e314fdae8d24 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Thu, 20 Jul 2017 15:54:19 -0700 Subject: [PATCH 0176/1139] Improve types for node 'fs' module (#18052) --- .../fs-extra-promise-tests.ts | 3 +- types/node/index.d.ts | 1626 ++++++++++++++--- types/node/node-tests.ts | 62 +- types/snekfetch/snekfetch-tests.ts | 5 +- types/tabtab/tabtab-tests.ts | 4 +- 5 files changed, 1469 insertions(+), 231 deletions(-) diff --git a/types/fs-extra-promise/fs-extra-promise-tests.ts b/types/fs-extra-promise/fs-extra-promise-tests.ts index c50115871b..30794946f3 100644 --- a/types/fs-extra-promise/fs-extra-promise-tests.ts +++ b/types/fs-extra-promise/fs-extra-promise-tests.ts @@ -15,6 +15,7 @@ let path: string; let data: any; let object: object; let buf: Buffer; +let strOrBuf: string | Buffer; let buffer: NodeBuffer; let modeNum: number; let modeStr: string; @@ -167,7 +168,7 @@ fs.readFile(filename, (err: Error, data: NodeBuffer) => { }); buffer = fs.readFileSync(filename); str = fs.readFileSync(filename, encoding); -buf = fs.readFileSync(filename, openOpts); +strOrBuf = fs.readFileSync(filename, openOpts); fs.writeFile(filename, data, errorCallback); fs.writeFile(filename, data, { encoding }, errorCallback); diff --git a/types/node/index.d.ts b/types/node/index.d.ts index e32a481b3c..48aa44a874 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1870,18 +1870,43 @@ declare module "child_process" { uid?: number; gid?: number; } + export interface ExecOptionsWithStringEncoding extends ExecOptions { encoding: BufferEncoding; } + export interface ExecOptionsWithBufferEncoding extends ExecOptions { - encoding: string; // specify `null`. + encoding: string | null; // specify `null`. } + + // no `options` definitely means stdout/stderr are `string`. export function exec(command: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function exec(command: string, options: ExecOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.exec("tsc", {encoding: null as string}, (err, stdout, stderr) => {}); - export function exec(command: string, options: ExecOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + export function exec(command: string, options: { encoding: "buffer" | null } & ExecOptions, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + export function exec(command: string, options: { encoding: BufferEncoding } & ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + export function exec(command: string, options: { encoding: string } & ExecOptions, callback?: (error: Error, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. export function exec(command: string, options: ExecOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + export function exec(command: string, options: ({ encoding?: string | null } & ExecOptions) | undefined | null, callback?: (error: Error, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace exec { + export function __promisify__(command: string): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(command: string, options: { encoding: "buffer" | null } & ExecOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; + export function __promisify__(command: string, options: { encoding: BufferEncoding } & ExecOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(command: string, options: ExecOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(command: string, options?: ({ encoding?: string | null } & ExecOptions) | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + } + export interface ExecFileOptions { cwd?: string; env?: any; @@ -1895,18 +1920,52 @@ declare module "child_process" { encoding: BufferEncoding; } export interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { - encoding: string; // specify `null`. + encoding: string | null; // specify `null`. + } + + export function execFile(file: string): ChildProcess; + export function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + export function execFile(file: string, args: string[] | undefined | null): ChildProcess; + export function execFile(file: string, args: string[] | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): ChildProcess; + + // no `options` definitely means stdout/stderr are `string`. + export function execFile(file: string, callback: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + export function execFile(file: string, options: { encoding: "buffer" | null } & ExecFileOptions, callback: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args: string[] | undefined | null, options: { encoding: "buffer" | null } & ExecFileOptions, callback: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + export function execFile(file: string, options: { encoding: BufferEncoding } & ExecFileOptions, callback: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + export function execFile(file: string, args: string[] | undefined | null, options: { encoding: BufferEncoding } & ExecFileOptions, callback: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; + + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + export function execFile(file: string, options: { encoding: string } & ExecFileOptions, callback: (error: Error, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + export function execFile(file: string, args: string[] | undefined | null, options: { encoding: string } & ExecFileOptions, callback: (error: Error, stdout: string | Buffer, stderr: string | Buffer) => void): ChildProcess; + + // `options` without an `encoding` means stdout/stderr are definitely `string`. + export function execFile(file: string, options: ExecFileOptions, callback: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + export function execFile(file: string, args: string[] | undefined | null, options: ExecFileOptions, callback: (error: Error, stdout: string, stderr: string) => void): ChildProcess; + + // fallback if nothing else matches. Worst case is always `string | Buffer`. + export function execFile(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, callback: ((error: Error, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null): ChildProcess; + export function execFile(file: string, args: string[] | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null, callback: ((error: Error, stdout: string | Buffer, stderr: string | Buffer) => void) | undefined | null): ChildProcess; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace execFile { + export function __promisify__(file: string): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, options: { encoding: "buffer" | null } & ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: { encoding: "buffer" | null } & ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, options: { encoding: BufferEncoding } & ExecFileOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: { encoding: BufferEncoding } & ExecFileOptions): Promise<{ stdout: Buffer, stderr: Buffer }>; + export function __promisify__(file: string, options: { encoding: string } & ExecFileOptions): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: { encoding: string } & ExecFileOptions): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + export function __promisify__(file: string, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: ExecFileOptions): Promise<{ stdout: string, stderr: string }>; + export function __promisify__(file: string, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; + export function __promisify__(file: string, args: string[] | undefined | null, options: ({ encoding?: string | null } & ExecFileOptions) | undefined | null): Promise<{ stdout: string | Buffer, stderr: string | Buffer }>; } - export function execFile(file: string, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.execFile("file.sh", {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithStringEncoding, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; - // usage. child_process.execFile("file.sh", ["foo"], {encoding: null as string}, (err, stdout, stderr) => {}); - export function execFile(file: string, args?: string[], options?: ExecFileOptionsWithBufferEncoding, callback?: (error: Error, stdout: Buffer, stderr: Buffer) => void): ChildProcess; - export function execFile(file: string, args?: string[], options?: ExecFileOptions, callback?: (error: Error, stdout: string, stderr: string) => void): ChildProcess; export interface ForkOptions { cwd?: string; @@ -2114,6 +2173,13 @@ declare module "dns" { export function lookup(hostname: string, options: LookupOptions, callback: (err: NodeJS.ErrnoException, address: string | LookupAddress[], family: number) => void): void; export function lookup(hostname: string, callback: (err: NodeJS.ErrnoException, address: string, family: number) => void): void; + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lookup { + export function __promisify__(hostname: string, options: LookupAllOptions): Promise<{ address: LookupAddress[] }>; + export function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise<{ address: string, family: number }>; + export function __promisify__(hostname: string, options?: LookupOptions | number): Promise<{ address: string | LookupAddress[], family?: number }>; + } + export interface ResolveOptions { ttl: boolean; } @@ -2171,14 +2237,39 @@ declare module "dns" { export function resolve(hostname: string, rrtype: "TXT", callback: (err: NodeJS.ErrnoException, addresses: string[][]) => void): void; export function resolve(hostname: string, rrtype: string, callback: (err: NodeJS.ErrnoException, addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][]) => void): void; + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace resolve { + export function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + export function __promisify__(hostname: string, rrtype: "MX"): Promise; + export function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + export function __promisify__(hostname: string, rrtype: "SOA"): Promise; + export function __promisify__(hostname: string, rrtype: "SRV"): Promise; + export function __promisify__(hostname: string, rrtype: "TXT"): Promise; + export function __promisify__(hostname: string, rrtype?: string): Promise; + } + export function resolve4(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; export function resolve4(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; export function resolve4(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace resolve4 { + export function __promisify__(hostname: string): Promise; + export function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + export function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + export function resolve6(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; export function resolve6(hostname: string, options: ResolveWithTtlOptions, callback: (err: NodeJS.ErrnoException, addresses: RecordWithTtl[]) => void): void; export function resolve6(hostname: string, options: ResolveOptions, callback: (err: NodeJS.ErrnoException, addresses: string[] | RecordWithTtl[]) => void): void; + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace resolve6 { + export function __promisify__(hostname: string): Promise; + export function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + export function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + export function resolveCname(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: string[]) => void): void; export function resolveMx(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: MxRecord[]) => void): void; export function resolveNaptr(hostname: string, callback: (err: NodeJS.ErrnoException, addresses: NaptrRecord[]) => void): void; @@ -2518,9 +2609,14 @@ declare module "dgram" { declare module "fs" { import * as stream from "stream"; import * as events from "events"; - import * as url from "url"; + import { URL } from "url"; - interface Stats { + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + + export interface Stats { isFile(): boolean; isDirectory(): boolean; isBlockDevice(): boolean; @@ -2544,7 +2640,7 @@ declare module "fs" { birthtime: Date; } - interface FSWatcher extends events.EventEmitter { + export interface FSWatcher extends events.EventEmitter { close(): void; /** @@ -2637,245 +2733,1253 @@ declare module "fs" { } /** - * Asynchronous rename. - * @param oldPath - * @param newPath - * @param callback No arguments other than a possible exception are given to the completion callback. + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. */ - export function rename(oldPath: string, newPath: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function rename(oldPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** - * Synchronous rename - * @param oldPath - * @param newPath + * Synchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function truncate(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function __promisify__(path: PathLike, len?: number | null): Promise; + } + + /** + * Synchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + export function truncateSync(path: PathLike, len?: number | null): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function __promisify__(fd: number, len?: number | null): Promise; + } + + /** + * Synchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + export function ftruncateSync(fd: number, len?: number | null): void; + + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function chown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + export function fchown(fd: number, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number, uid: number, gid: number): Promise; + } + + /** + * Synchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. */ - export function renameSync(oldPath: string, newPath: string): void; - export function truncate(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncate(path: string | Buffer, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function truncateSync(path: string | Buffer, len?: number): void; - export function ftruncate(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncate(fd: number, len: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function ftruncateSync(fd: number, len?: number): void; - export function chown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chownSync(path: string | Buffer, uid: number, gid: number): void; - export function fchown(fd: number, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function fchownSync(fd: number, uid: number, gid: number): void; - export function lchown(path: string | Buffer, uid: number, gid: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchownSync(path: string | Buffer, uid: number, gid: number): void; - export function chmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function chmodSync(path: string | Buffer, mode: number): void; - export function chmodSync(path: string | Buffer, mode: string): void; - export function fchmod(fd: number, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmod(fd: number, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function fchmodSync(fd: number, mode: number): void; - export function fchmodSync(fd: number, mode: string): void; - export function lchmod(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmod(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function lchmodSync(path: string | Buffer, mode: number): void; - export function lchmodSync(path: string | Buffer, mode: string): void; - export function stat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function lstat(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function fstat(fd: number, callback?: (err: NodeJS.ErrnoException, stats: Stats) => any): void; - export function statSync(path: string | Buffer): Stats; - export function lstatSync(path: string | Buffer): Stats; + + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + + /** + * Synchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function chmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function chmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function fchmod(fd: number, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function __promisify__(fd: number, mode: string | number): Promise; + } + + /** + * Synchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function fchmodSync(fd: number, mode: string | number): void; + + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function lchmod(path: PathLike, mode: string | number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function __promisify__(path: PathLike, mode: string | number): Promise; + } + + /** + * Synchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + export function lchmodSync(path: PathLike, mode: string | number): void; + + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function statSync(path: PathLike): Stats; + + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ export function fstatSync(fd: number): Stats; - export function link(srcpath: string | Buffer, dstpath: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function linkSync(srcpath: string | Buffer, dstpath: string | Buffer): void; - export function symlink(srcpath: string | Buffer, dstpath: string | Buffer, type?: string, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function symlinkSync(srcpath: string | Buffer, dstpath: string | Buffer, type?: string): void; - export function readlink(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, linkString: string) => any): void; - export function readlinkSync(path: string | Buffer): string; - export function realpath(path: string | Buffer, callback?: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpath(path: string | Buffer, cache: { [path: string]: string }, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => any): void; - export function realpathSync(path: string | Buffer, cache?: { [path: string]: string }): string; + /** - * Asynchronous unlink - deletes the file specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ - export function unlink(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException, stats: Stats) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike): Promise; + } + /** - * Synchronous unlink - deletes the file specified in {path} - * - * @param path + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. */ - export function unlinkSync(path: string | Buffer): void; + export function lstatSync(path: PathLike): Stats; + /** - * Asynchronous rmdir - removes the directory specified in {path} - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. */ - export function rmdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function link(existingPath: PathLike, newPath: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function link(existingPath: PathLike, newPath: PathLike): Promise; + } + /** - * Synchronous rmdir - removes the directory specified in {path} - * - * @param path + * Synchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. */ - export function rmdirSync(path: string | Buffer): void; + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param callback No arguments other than a possible exception are given to the completion callback. + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. */ - export function mkdir(path: string | Buffer, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlink(target: PathLike, path: PathLike, type: string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + /** - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. */ - export function mkdir(path: string | Buffer, mode: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlink(target: PathLike, path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + export function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + } + /** - * Asynchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. + * Synchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. */ - export function mkdir(path: string | Buffer, mode: string, callback?: (err?: NodeJS.ErrnoException) => void): void; + export function symlinkSync(target: PathLike, path: PathLike, type?: string | null): void; + /** - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function mkdirSync(path: string | Buffer, mode?: number): void; + export function readlink(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + /** - * Synchronous mkdir - creates the directory specified in {path}. Parameter {mode} defaults to 0777. - * - * @param path - * @param mode - * @param callback No arguments other than a possible exception are given to the completion callback. + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function mkdirSync(path: string | Buffer, mode?: string): void; + export function readlink(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, linkString: Buffer) => void): void; + /** - * Asynchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @param callback The created folder path is passed as a string to the callback's second parameter. + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. */ - export function mkdtemp(prefix: string, callback?: (err: NodeJS.ErrnoException, folder: string) => void): void; + export function readlink(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, linkString: string | Buffer) => void): void; + /** - * Synchronous mkdtemp - Creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory. - * - * @param prefix - * @returns Returns the created folder path. + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException, linkString: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, resolvedPath: Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, resolvedPath: string | Buffer) => void): void; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException, resolvedPath: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function unlink(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function unlinkSync(path: PathLike): void; + + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function rmdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function rmdirSync(path: PathLike): void; + + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir(path: PathLike, mode: number | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function __promisify__(path: PathLike, mode?: number | string | null): Promise; + } + + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, mode?: number | string | null): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: { encoding?: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: "buffer" | { encoding: "buffer" }, callback: (err: NodeJS.ErrnoException, folder: Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp(prefix: string, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, folder: string | Buffer) => void): void; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException, folder: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(prefix: string, options: { encoding: "buffer" } | "buffer"): Promise; + + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(prefix: string, options?: { encoding?: string | null } | string | null): Promise; + } + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: { encoding?: BufferEncoding | null } | BufferEncoding | null): string; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: { encoding: "buffer" } | "buffer"): Buffer; + + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: { encoding?: string | null } | string | null): string | Buffer; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: PathLike, options: { encoding: BufferEncoding | null } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: PathLike, options: { encoding: "buffer" } | "buffer", callback: (err: NodeJS.ErrnoException, files: Buffer[]) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir(path: PathLike, options: { encoding?: string | null } | string | undefined | null, callback: (err: NodeJS.ErrnoException, files: Array) => void): void; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options: "buffer" | { encoding: "buffer" }): Promise; + + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function __promisify__(path: PathLike, options?: { encoding?: string | null } | string | null): Promise>; + } + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options?: { encoding: BufferEncoding | null } | BufferEncoding | null): string[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options: { encoding: "buffer" } | "buffer"): Buffer[]; + + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync(path: PathLike, options?: { encoding?: string | null } | string | null): Array; + + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + export function close(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number): Promise; + } + + /** + * Synchronous close(2) - close a file descriptor. + * @param fd A file descriptor. */ - export function mkdtempSync(prefix: string): string; - export function readdir(path: string | Buffer, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdir(path: string | Buffer, options: string | {}, callback: (err: NodeJS.ErrnoException, files: string[]) => void): void; - export function readdirSync(path: string | Buffer, options?: string | {}): string[]; - export function close(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; export function closeSync(fd: number): void; - export function open(path: string | Buffer, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - export function open(path: string | Buffer, flags: string | number, mode: number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; - export function openSync(path: string | Buffer, flags: string | number, mode?: number): number; - export function utimes(path: string | Buffer, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimes(path: string | Buffer, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function utimesSync(path: string | Buffer, atime: number, mtime: number): void; - export function utimesSync(path: string | Buffer, atime: Date, mtime: Date): void; - export function futimes(fd: number, atime: number, mtime: number, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimes(fd: number, atime: Date, mtime: Date, callback?: (err?: NodeJS.ErrnoException) => void): void; - export function futimesSync(fd: number, atime: number, mtime: number): void; - export function futimesSync(fd: number, atime: Date, mtime: Date): void; - export function fsync(fd: number, callback?: (err?: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function open(path: PathLike, flags: string | number, mode: string | number | undefined | null, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, flags: string | number, callback: (err: NodeJS.ErrnoException, fd: number) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function __promisify__(path: PathLike, flags: string | number, mode?: string | number | null): Promise; + } + + /** + * Synchronous open(2) - open and possibly create a file, returning a file descriptor.. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + export function openSync(path: PathLike, flags: string | number, mode?: string | number | null): number; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function __promisify__(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function futimes(fd: number, atime: string | number | Date, mtime: string | number | Date, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function __promisify__(fd: number, atime: string | number | Date, mtime: string | number | Date): Promise; + } + + /** + * Synchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + export function futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + export function fsync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ export function fsyncSync(fd: number): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, buffer: Buffer, offset: number, length: number, callback?: (err: NodeJS.ErrnoException, written: number, buffer: Buffer) => void): void; - export function write(fd: number, data: any, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function write(fd: number, data: any, offset: number, encoding: string, callback?: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; - export function writeSync(fd: number, buffer: Buffer, offset: number, length: number, position?: number | null): number; - export function writeSync(fd: number, data: any, position?: number | null, enconding?: string): number; - export function read(fd: number, buffer: Buffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: Buffer) => void): void; - export function readSync(fd: number, buffer: Buffer, offset: number, length: number, position: number | null): number; + /** - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. */ - export function readFile(filename: string, encoding: null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - export function readFile(filename: string, encoding: string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - export function readFile(filename: string, encoding: string | null, callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void): void; + export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + /** - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. */ - export function readFile(filename: string, options: { encoding: null; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; - export function readFile(filename: string, options: { encoding: string; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string) => void): void; - export function readFile(filename: string, options: { encoding: string | null; flag?: string; }, callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void): void; + export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, length: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + /** - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFile returns a string; otherwise it returns a Buffer. - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. */ - export function readFile(filename: string, options: { flag?: string; }, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + export function write(fd: number, buffer: TBuffer, offset: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + /** - * Asynchronous readFile - Asynchronously reads the entire contents of a file. - * - * @param fileName - * @param callback - The callback is passed two arguments (err, data), where data is the contents of the file. + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. */ - export function readFile(filename: string, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + export function write(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException, written: number, buffer: TBuffer) => void): void; + /** - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param encoding + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. */ - export function readFileSync(filename: string, encoding: null): Buffer; - export function readFileSync(filename: string, encoding: string): string; - export function readFileSync(filename: string, encoding: string | null): string | Buffer; + export function write(fd: number, string: any, position: number | undefined | null, encoding: string | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + /** - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. */ - export function readFileSync(filename: string, options: { encoding: null; flag?: string; }): Buffer; - export function readFileSync(filename: string, options: { encoding: string; flag?: string; }): string; - export function readFileSync(filename: string, options: { encoding: string | null; flag?: string; }): string | Buffer; + export function write(fd: number, string: any, position: number | undefined | null, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + /** - * Synchronous readFile - Synchronously reads the entire contents of a file. - * - * @param fileName - * @param options An object with optional {encoding} and {flag} properties. If {encoding} is specified, readFileSync returns a string; otherwise it returns a Buffer. + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. */ - export function readFileSync(filename: string, options?: { flag?: string; }): Buffer; - export function writeFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, encoding: string, callback: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function writeFileSync(filename: string, data: any, encoding: string): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function writeFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function appendFile(filename: string, data: any, encoding: string, callback: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: number; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, options: { encoding?: string; mode?: string; flag?: string; }, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFile(filename: string, data: any, callback?: (err: NodeJS.ErrnoException) => void): void; - export function appendFileSync(filename: string, data: any, encoding: string): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: number; flag?: string; }): void; - export function appendFileSync(filename: string, data: any, options?: { encoding?: string; mode?: string; flag?: string; }): void; - export function watchFile(filename: string, listener: (curr: Stats, prev: Stats) => void): void; - export function watchFile(filename: string, options: { persistent?: boolean; interval?: number; }, listener: (curr: Stats, prev: Stats) => void): void; - export function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void; - export function watch(filename: string, listener?: (event: string, filename: string) => any): FSWatcher; - export function watch(filename: string, encoding: string, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; - export function watch(filename: string, options: { persistent?: boolean; recursive?: boolean; encoding?: string }, listener?: (event: string, filename: string | Buffer) => any): FSWatcher; - export function exists(path: string | Buffer, callback?: (exists: boolean) => void): void; - export function existsSync(path: string | Buffer): boolean; + export function write(fd: number, string: any, callback: (err: NodeJS.ErrnoException, written: number, str: string) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function __promisify__(fd: number, buffer?: TBuffer, offset?: number, length?: number, position?: number | null): Promise<{ bytesWritten: number, buffer: TBuffer }>; + + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function __promisify__(fd: number, string: any, position?: number | null, encoding?: string | null): Promise<{ bytesWritten: number, buffer: string }>; + } + + /** + * Synchronously writes `buffer` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function writeSync(fd: number, buffer: Buffer | Uint8Array, offset?: number | null, length?: number | null, position?: number | null): number; + + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. If something other than a string is supplied it will be coerced to a string. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync(fd: number, string: any, position?: number | null, encoding?: string | null): number; + + /** + * Asynchronously reads data from the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function read(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null, callback?: (err: NodeJS.ErrnoException, bytesRead: number, buffer: TBuffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function __promisify__(fd: number, buffer: TBuffer, offset: number, length: number, position: number | null): Promise<{ bytesRead: number, buffer: TBuffer }>; + } + + /** + * Synchronously reads data from the file referenced by the supplied file descriptor, returning the number of bytes read. + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + export function readSync(fd: number, buffer: Buffer | Uint8Array, offset: number, length: number, position: number | null): number; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile(path: PathLike | number, options: { encoding?: null; flag?: string; } | undefined | null, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile(path: PathLike | number, options: { encoding: string; flag?: string; } | string, callback: (err: NodeJS.ErrnoException, data: string) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile(path: PathLike | number, options: { encoding?: string | null; flag?: string; } | string | undefined | null, callback: (err: NodeJS.ErrnoException, data: string | Buffer) => void): void; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile(path: PathLike | number, callback: (err: NodeJS.ErrnoException, data: Buffer) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function __promisify__(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function __promisify__(path: PathLike | number, options: { encoding: string; flag?: string; } | string): Promise; + + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function __promisify__(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): Promise; + } + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options?: { encoding?: null; flag?: string; } | null): Buffer; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options: { encoding: string; flag?: string; } | string): string; + + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync(path: PathLike | number, options?: { encoding?: string | null; flag?: string; } | string | null): string | Buffer; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function writeFile(path: PathLike | number, data: any, options: { encoding?: string | null; mode?: number | string; flag?: string; } | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile(path: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function __promisify__(path: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): Promise; + } + + /** + * Synchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + export function writeFileSync(path: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function appendFile(file: PathLike | number, data: any, options: { encoding?: string | null, mode?: string | number, flag?: string } | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathLike | number, data: any, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function __promisify__(file: PathLike | number, data: any, options?: { encoding?: string | null, mode?: string | number, flag?: string } | string | null): Promise; + } + + /** + * Synchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + export function appendFileSync(file: PathLike | number, data: any, options?: { encoding?: string | null; mode?: number | string; flag?: string; } | string | null): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + */ + export function watchFile(filename: PathLike, options: { persistent?: boolean; interval?: number; } | undefined, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void; + + /** + * Stop watching for changes on `filename`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: { encoding?: BufferEncoding | null, persistent?: boolean, recursive?: boolean } | BufferEncoding | undefined | null, listener?: (event: string, filename: string) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: { encoding: "buffer", persistent?: boolean, recursive?: boolean } | "buffer", listener?: (event: string, filename: Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch(filename: PathLike, options: { encoding?: string | null, persistent?: boolean, recursive?: boolean } | string | null, listener?: (event: string, filename: string | Buffer) => void): FSWatcher; + + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function watch(filename: PathLike, listener?: (event: string, filename: string) => any): FSWatcher; + + /** + * Asynchronously tests whether or not the given path exists by checking with the file system. + * @deprecated + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + + /** + * Synchronously tests whether or not the given path exists by checking with the file system. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function existsSync(path: PathLike): boolean; export namespace constants { // File Access Constants @@ -3004,12 +4108,43 @@ declare module "fs" { export const S_IXOTH: number; } - /** 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; - /** Synchronous version of fs.access. This throws if any accessibility checks fail, and does nothing otherwise. */ - export function accessSync(path: string | Buffer, mode?: number): void; - export function createReadStream(path: string | Buffer | url.URL, options?: string | { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function access(path: PathLike, mode: number | undefined, callback: (err: NodeJS.ErrnoException) => void): void; + + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function access(path: PathLike, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function __promisify__(path: PathLike, mode?: number): Promise; + } + + /** + * Synchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function accessSync(path: PathLike, mode?: number): void; + + /** + * Returns a new `ReadStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function createReadStream(path: PathLike, options?: string | { flags?: string; encoding?: string; fd?: number; @@ -3018,7 +4153,13 @@ declare module "fs" { start?: number; end?: number; }): ReadStream; - export function createWriteStream(path: string | Buffer | url.URL, options?: string | { + + /** + * Returns a new `WriteStream` object. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + export function createWriteStream(path: PathLike, options?: string | { flags?: string; defaultEncoding?: string; fd?: number; @@ -3026,7 +4167,26 @@ declare module "fs" { autoClose?: boolean; start?: number; }): WriteStream; - export function fdatasync(fd: number, callback: Function): void; + + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + export function fdatasync(fd: number, callback: (err: NodeJS.ErrnoException) => void): void; + + // NOTE: This namespace provides design-time support for util.promisify. Exported members do not exist at runtime. + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + export function __promisify__(fd: number): Promise; + } + + /** + * Synchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ export function fdatasyncSync(fd: number): void; } @@ -4011,9 +5171,25 @@ declare module "util" { export function isSymbol(object: any): object is symbol; export function isUndefined(object: any): object is undefined; export function deprecate(fn: Function, message: string): Function; - export var promisify: { - (fn: Function): Function; - custom: symbol + + export interface CustomPromisify extends Function { + __promisify__: TCustom; + } + + export function promisify(fn: CustomPromisify): TCustom; + export function promisify(fn: (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1, arg2: T2) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + const custom: symbol; } } diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 6b268d8862..defd7aa6f4 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -166,7 +166,7 @@ namespace fs_tests { "Do unto others as you would have them do unto you.", assert.ifError); - fs.write(1234, "test"); + fs.write(1234, "test", () => {}); fs.writeFile("Harry Potter", "\"You be wizzing, Harry,\" jived Dumbledore.", @@ -278,6 +278,64 @@ namespace fs_tests { fs.accessSync(Buffer.from(''), fs.constants.W_OK | fs.constants.X_OK); } + + { + let s: string; + let b: Buffer; + fs.readlink('/path/to/folder', (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', undefined, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', 'utf8', (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', 'buffer', (err, linkString) => b = linkString); + fs.readlink('/path/to/folder', s, (err, linkString) => typeof linkString === 'string' ? s = linkString : b = linkString); + fs.readlink('/path/to/folder', { }, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', { encoding: undefined }, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', { encoding: 'utf8' }, (err, linkString) => s = linkString); + fs.readlink('/path/to/folder', { encoding: 'buffer' }, (err, linkString) => b = linkString); + fs.readlink('/path/to/folder', { encoding: s }, (err, linkString) => typeof linkString === "string" ? s = linkString : b = linkString); + + s = fs.readlinkSync('/path/to/folder'); + s = fs.readlinkSync('/path/to/folder', undefined); + s = fs.readlinkSync('/path/to/folder', 'utf8'); + b = fs.readlinkSync('/path/to/folder', 'buffer'); + const v1 = fs.readlinkSync('/path/to/folder', s); + typeof v1 === "string" ? s = v1 : b = v1; + + s = fs.readlinkSync('/path/to/folder', { }); + s = fs.readlinkSync('/path/to/folder', { encoding: undefined }); + s = fs.readlinkSync('/path/to/folder', { encoding: 'utf8' }); + b = fs.readlinkSync('/path/to/folder', { encoding: 'buffer' }); + const v2 = fs.readlinkSync('/path/to/folder', { encoding: s }); + typeof v2 === "string" ? s = v2 : b = v2; + } + + { + let s: string; + let b: Buffer; + fs.realpath('/path/to/folder', (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', undefined, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', 'utf8', (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', 'buffer', (err, resolvedPath) => b = resolvedPath); + fs.realpath('/path/to/folder', s, (err, resolvedPath) => typeof resolvedPath === 'string' ? s = resolvedPath : b = resolvedPath); + fs.realpath('/path/to/folder', { }, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', { encoding: undefined }, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', { encoding: 'utf8' }, (err, resolvedPath) => s = resolvedPath); + fs.realpath('/path/to/folder', { encoding: 'buffer' }, (err, resolvedPath) => b = resolvedPath); + fs.realpath('/path/to/folder', { encoding: s }, (err, resolvedPath) => typeof resolvedPath === "string" ? s = resolvedPath : b = resolvedPath); + + s = fs.realpathSync('/path/to/folder'); + s = fs.realpathSync('/path/to/folder', undefined); + s = fs.realpathSync('/path/to/folder', 'utf8'); + b = fs.realpathSync('/path/to/folder', 'buffer'); + const v1 = fs.realpathSync('/path/to/folder', s); + typeof v1 === "string" ? s = v1 : b = v1; + + s = fs.realpathSync('/path/to/folder', { }); + s = fs.realpathSync('/path/to/folder', { encoding: undefined }); + s = fs.realpathSync('/path/to/folder', { encoding: 'utf8' }); + b = fs.realpathSync('/path/to/folder', { encoding: 'buffer' }); + const v2 = fs.realpathSync('/path/to/folder', { encoding: s }); + typeof v2 === "string" ? s = v2 : b = v2; + } } /////////////////////////////////////////////////////// @@ -584,7 +642,7 @@ namespace util_tests { assert(typeof util.inspect.custom === 'symbol') // util.promisify var readPromised = util.promisify(fs.readFile) - var sampleRead: Promise = readPromised(__filename).then((data: string): void => {}).catch((error: Error): void => {}) + var sampleRead: Promise = readPromised(__filename).then((data: Buffer): void => { }).catch((error: Error): void => {}) assert(typeof util.promisify.custom === 'symbol') } } diff --git a/types/snekfetch/snekfetch-tests.ts b/types/snekfetch/snekfetch-tests.ts index b05c02628a..69e9743f83 100644 --- a/types/snekfetch/snekfetch-tests.ts +++ b/types/snekfetch/snekfetch-tests.ts @@ -1,8 +1,11 @@ import * as fs from 'fs'; +import * as util from 'util'; import * as snekfetch from 'snekfetch'; +const writeFile = util.promisify(fs.writeFile); + snekfetch.get('https://s.gus.host/o-SNAKES-80.jpg') - .then(r => fs.writeFile('download.jpg', r.body)); + .then(r => writeFile('download.jpg', r.body)); snekfetch.get('https://s.gus.host/o-SNAKES-80.jpg') .pipe(fs.createWriteStream('download.jpg')); diff --git a/types/tabtab/tabtab-tests.ts b/types/tabtab/tabtab-tests.ts index 8330d7c2cd..e0187662ff 100644 --- a/types/tabtab/tabtab-tests.ts +++ b/types/tabtab/tabtab-tests.ts @@ -12,7 +12,7 @@ if (process.argv.slice(2)[0] === 'completion') { if (/^-\w?/.test(data.last)) return tabtab.log(['n', 'o', 'd', 'e'], data, '-'); tabtab.log(['list', 'of', 'commands'], data); - child_process.exec('rake -H', {encoding: null as string}, function(err, stdout, stderr) { + child_process.exec('rake -H', {encoding: null}, function(err, stdout, stderr) { if (err) return; var decoder = new string_decoder.StringDecoder('utf8'); var parsed = tabtab.parseOut(decoder.write(stdout)); @@ -20,7 +20,7 @@ if (process.argv.slice(2)[0] === 'completion') { if (/^-\w?/.test(data.last)) return tabtab.log(parsed.shorts, data, '-'); }); - child_process.exec('cake', {encoding: null as string}, function(err, stdout, stderr) { + child_process.exec('cake', {encoding: null}, function(err, stdout, stderr) { if (err) return; var decoder = new string_decoder.StringDecoder('utf8'); var tasks = tabtab.parseTasks(decoder.write(stdout), 'cake'); From 7ac090dcfc6fb418eb01f4e4ca622be9f9bffa4e Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Fri, 21 Jul 2017 00:55:25 +0200 Subject: [PATCH 0177/1139] [figures] introduce typings (#18266) --- types/figures/figures-tests.ts | 5 +++ types/figures/index.d.ts | 67 ++++++++++++++++++++++++++++++++++ types/figures/tsconfig.json | 22 +++++++++++ types/figures/tslint.json | 1 + 4 files changed, 95 insertions(+) create mode 100644 types/figures/figures-tests.ts create mode 100644 types/figures/index.d.ts create mode 100644 types/figures/tsconfig.json create mode 100644 types/figures/tslint.json diff --git a/types/figures/figures-tests.ts b/types/figures/figures-tests.ts new file mode 100644 index 0000000000..f2c25bbe4b --- /dev/null +++ b/types/figures/figures-tests.ts @@ -0,0 +1,5 @@ +import figures = require('figures'); + +let str: string; +str = figures('✔︎ check'); +str = figures.tick; diff --git a/types/figures/index.d.ts b/types/figures/index.d.ts new file mode 100644 index 0000000000..2867326034 --- /dev/null +++ b/types/figures/index.d.ts @@ -0,0 +1,67 @@ +// Type definitions for figures 2.0 +// Project: https://github.com/sindresorhus/figures#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = figures; + +declare function figures(input: string): string; + +declare namespace figures { + const tick: string; + const cross: string; + const star: string; + const square: string; + const squareSmall: string; + const squareSmallFilled: string; + const play: string; + const circle: string; + const circleFilled: string; + const circleDotted: string; + const circleDouble: string; + const circleCircle: string; + const circleCross: string; + const circlePipe: string; + const circleQuestionMark: string; + const bullet: string; + const dot: string; + const line: string; + const ellipsis: string; + const pointer: string; + const pointerSmall: string; + const info: string; + const warning: string; + const hamburger: string; + const smiley: string; + const mustache: string; + const heart: string; + const arrowUp: string; + const arrowDown: string; + const arrowLeft: string; + const arrowRight: string; + const radioOn: string; + const radioOff: string; + const checkboxOn: string; + const checkboxOff: string; + const checkboxCircleOn: string; + const checkboxCircleOff: string; + const questionMarkPrefix: string; + const oneHalf: string; + const oneThird: string; + const oneQuarter: string; + const oneFifth: string; + const oneSixth: string; + const oneSeventh: string; + const oneEighth: string; + const oneNinth: string; + const oneTenth: string; + const twoThirds: string; + const twoFifths: string; + const threeQuarters: string; + const threeFifths: string; + const threeEighths: string; + const fourFifths: string; + const fiveSixths: string; + const fiveEighths: string; + const sevenEighth: string; +} diff --git a/types/figures/tsconfig.json b/types/figures/tsconfig.json new file mode 100644 index 0000000000..595779c25d --- /dev/null +++ b/types/figures/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "figures-tests.ts" + ] +} diff --git a/types/figures/tslint.json b/types/figures/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/figures/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 0fefe6de390edfed5ce39d6cdda9544d14af3053 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Fri, 21 Jul 2017 00:55:47 +0200 Subject: [PATCH 0178/1139] [log-update] introduce typings (#18263) --- types/log-update/index.d.ts | 17 +++++++++++++++++ types/log-update/log-update-tests.ts | 19 +++++++++++++++++++ types/log-update/tsconfig.json | 22 ++++++++++++++++++++++ types/log-update/tslint.json | 1 + 4 files changed, 59 insertions(+) create mode 100644 types/log-update/index.d.ts create mode 100644 types/log-update/log-update-tests.ts create mode 100644 types/log-update/tsconfig.json create mode 100644 types/log-update/tslint.json diff --git a/types/log-update/index.d.ts b/types/log-update/index.d.ts new file mode 100644 index 0000000000..544223a766 --- /dev/null +++ b/types/log-update/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for log-update 2.0 +// Project: https://github.com/sindresorhus/log-update#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = logUpdate; + +declare function logUpdate(...text: string[]): void; + +declare namespace logUpdate { + function clear(): void; + function done(): void; + const stderr: typeof logUpdate; + function create(stream: NodeJS.WritableStream): typeof logUpdate; +} diff --git a/types/log-update/log-update-tests.ts b/types/log-update/log-update-tests.ts new file mode 100644 index 0000000000..9a0955f7d4 --- /dev/null +++ b/types/log-update/log-update-tests.ts @@ -0,0 +1,19 @@ +import logUpdate = require('log-update'); + +logUpdate(` + ♥♥ + unicorns + ♥♥ +`); + +logUpdate.clear(); +logUpdate.done(); + +logUpdate.stderr('oh', 'my', 'oh', 'my'); +logUpdate.stderr.clear(); +logUpdate.stderr.done(); + +const logStdOut = logUpdate.create(process.stdout); +logStdOut('oh', 'my', 'oh', 'my'); +logStdOut.clear(); +logStdOut.done(); diff --git a/types/log-update/tsconfig.json b/types/log-update/tsconfig.json new file mode 100644 index 0000000000..cfc1ac94e3 --- /dev/null +++ b/types/log-update/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "log-update-tests.ts" + ] +} diff --git a/types/log-update/tslint.json b/types/log-update/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/log-update/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 5b68a7c6bbf2a53fe100c78fb342c7ca976be7a6 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Fri, 21 Jul 2017 00:57:27 +0200 Subject: [PATCH 0179/1139] [is-svg] introduce typings (#18265) --- types/is-svg/index.d.ts | 8 ++++++++ types/is-svg/is-svg-tests.ts | 3 +++ types/is-svg/tsconfig.json | 22 ++++++++++++++++++++++ types/is-svg/tslint.json | 1 + 4 files changed, 34 insertions(+) create mode 100644 types/is-svg/index.d.ts create mode 100644 types/is-svg/is-svg-tests.ts create mode 100644 types/is-svg/tsconfig.json create mode 100644 types/is-svg/tslint.json diff --git a/types/is-svg/index.d.ts b/types/is-svg/index.d.ts new file mode 100644 index 0000000000..21e85cd2e2 --- /dev/null +++ b/types/is-svg/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for is-svg 2.1 +// Project: https://github.com/sindresorhus/is-svg#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = isSvg; + +declare function isSvg(input: string): boolean; diff --git a/types/is-svg/is-svg-tests.ts b/types/is-svg/is-svg-tests.ts new file mode 100644 index 0000000000..d556a944f9 --- /dev/null +++ b/types/is-svg/is-svg-tests.ts @@ -0,0 +1,3 @@ +import isSvg = require('is-svg'); + +const result: boolean = isSvg(''); diff --git a/types/is-svg/tsconfig.json b/types/is-svg/tsconfig.json new file mode 100644 index 0000000000..9776ba1c77 --- /dev/null +++ b/types/is-svg/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-svg-tests.ts" + ] +} diff --git a/types/is-svg/tslint.json b/types/is-svg/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-svg/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 4de32d67a56423d3568334e97f02fd66180f29bc Mon Sep 17 00:00:00 2001 From: Saeed Tabrizi Date: Fri, 21 Jul 2017 03:34:58 +0430 Subject: [PATCH 0180/1139] fix string case in PropertyType - a minor patch (#18268) --- types/orientjs/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/orientjs/index.d.ts b/types/orientjs/index.d.ts index 9be45a4fea..e57fc8d076 100644 --- a/types/orientjs/index.d.ts +++ b/types/orientjs/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/orientechnologies/orientjs // Definitions by: [Saeed Tabrizi] // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last Update : 19-7-2017 +// Last Update : 20-7-2017 // Compatible with Orientdb >= 2.2.15 and orientjs >= 2.2.x features . // Developed with love in www.nowcando.com // @@ -32,7 +32,7 @@ import Promise = require('bluebird'); * @description Official node.js driver for OrientDB. Fast, lightweight, uses the binary protocol. * * @author Saeed Tabrizi (saeed a_t nowcando.com) - * @version 3.0.0 + * @version 3.0.1 * */ @@ -44,7 +44,7 @@ declare function orientjs(config: orientjs.ServerConfig): orientjs.Server; declare namespace orientjs { type Version = number | string; type PropertyType = "Boolean" | "Integer" | "Short" | "Long" | - "Float" | "Double" | "DateTime" | "string" | "Binary" | + "Float" | "Double" | "DateTime" | "String" | "Binary" | "Embedded" | "EmbeddedList" | "EmbeddedSet" | "EmbeddedMap" | "Link" | "LinkList" | "LinkSet" | "LinkMap" | "Byte" | "Transient" | "Date" | "Custom" | "Decimal" | "LinkBag"; From 1be93dbab9b3ebf0284115bbcfd5f14f5b33fe99 Mon Sep 17 00:00:00 2001 From: Benjamin Svobodny Date: Fri, 21 Jul 2017 12:39:21 -0400 Subject: [PATCH 0181/1139] Update index.d.ts (#18140) Add parameters used for doughnut charts : http://www.chartjs.org/docs/latest/charts/doughnut.html --- types/chart.js/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index f1a39c84c4..a465806797 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -159,6 +159,8 @@ declare namespace Chart { elements?: ChartElementsOptions; scales?: ChartScales; cutoutPercentage?: number; + circumference?: number; + rotation?: number; } interface ChartFontOptions { From 168bb317b17e783adfaaeb3ea88a424030dbc488 Mon Sep 17 00:00:00 2001 From: Willis Plummer Date: Fri, 21 Jul 2017 12:40:00 -0400 Subject: [PATCH 0182/1139] add possibility of null return value from RichUtils.handleKeyCommand (#18277) * add possibility of null return from RichUtils.handleKeyCommand * more specifically, the function returns null in the overload case * make key for RichUtils.toggleLink potentially null * add definitions by credit --- types/draft-js/index.d.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 1019df8fce..73c248df03 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -5,6 +5,7 @@ // Yale Cason // Ryan Schwers // Michael Wu +// Willis Plummer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -863,7 +864,7 @@ declare namespace Draft { static getDataObjectForLinkURL(uri: URI): Object; static handleKeyCommand(editorState: EditorState, command: DraftEditorCommand): EditorState; - static handleKeyCommand(editorState: EditorState, command: string): EditorState; + static handleKeyCommand(editorState: EditorState, command: string): null; static insertSoftNewline(editorState: EditorState): EditorState; @@ -888,7 +889,7 @@ declare namespace Draft { */ static toggleInlineStyle(editorState: EditorState, inlineStyle: string): EditorState; - static toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string): EditorState; + static toggleLink(editorState: EditorState, targetSelection: SelectionState, entityKey: string | null): EditorState; /** * When a collapsed cursor is at the start of an empty styled block, allow From b33275b2f48d9ee35de31015298bdef3bf92a4fc Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Fri, 21 Jul 2017 18:40:26 +0200 Subject: [PATCH 0183/1139] [make-dir] add more specific type to `fs` config option (#18286) --- types/make-dir/index.d.ts | 6 +++++- types/make-dir/make-dir-tests.ts | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/types/make-dir/index.d.ts b/types/make-dir/index.d.ts index e23dfba939..905343c883 100644 --- a/types/make-dir/index.d.ts +++ b/types/make-dir/index.d.ts @@ -1,8 +1,12 @@ // Type definitions for make-dir 1.0 // Project: https://github.com/sindresorhus/make-dir // Definitions by: Ika +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/// +import * as fs from 'fs'; + export = makeDir; /** @@ -33,6 +37,6 @@ declare namespace makeDir { * * Use a custom `fs` implementation. For example [`graceful-fs`](https://github.com/isaacs/node-graceful-fs). */ - fs?: any; + fs?: typeof fs; } } diff --git a/types/make-dir/make-dir-tests.ts b/types/make-dir/make-dir-tests.ts index 817d793b70..2767706bf6 100644 --- a/types/make-dir/make-dir-tests.ts +++ b/types/make-dir/make-dir-tests.ts @@ -1,7 +1,13 @@ import makeDir = require('make-dir'); +import * as fs from 'fs'; +import * as gfs from 'graceful-fs'; makeDir('path/to/somewhere').then(dirname => { // do something }); const dirname = makeDir.sync('path/to/somewhere'); + +makeDir('path/to/somewhere', {mode: parseInt('777', 8)}); +makeDir('path/to/somewhere', {fs}); +makeDir('path/to/somewhere', {fs: gfs}); From e030446e88f136de1d2a827bc7bc84ae91c9474c Mon Sep 17 00:00:00 2001 From: Bradley Ayers Date: Sat, 22 Jul 2017 02:40:56 +1000 Subject: [PATCH 0184/1139] Fix Decoration.widget signature. (#18201) --- types/prosemirror-view/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/prosemirror-view/index.d.ts b/types/prosemirror-view/index.d.ts index c5fda64a87..1c0678d046 100644 --- a/types/prosemirror-view/index.d.ts +++ b/types/prosemirror-view/index.d.ts @@ -12,7 +12,7 @@ import * as dom from './dom'; export class Decoration { spec: object; - static widget(pos: number, dom: Node, spec?: { side?: number | null, stopEvent?: ((event: Event) => boolean) | null, key?: string | null }): Decoration; + static widget(pos: number, dom: dom.Node, spec?: { side?: number | null, stopEvent?: ((event: Event) => boolean) | null, key?: string | null }): Decoration; static inline(from: number, to: number, attrs: DecorationAttrs, spec?: { inclusiveStart?: boolean | null, inclusiveEnd?: boolean | null }): Decoration; static node(from: number, to: number, attrs: DecorationAttrs, spec?: object): Decoration; } From 527914c2a342d4e79bae08346b520efb5cb050e4 Mon Sep 17 00:00:00 2001 From: Daniel Imms Date: Fri, 21 Jul 2017 09:41:56 -0700 Subject: [PATCH 0185/1139] node: Fix net.Socket definition (#18275) v0.12.x: https://nodejs.org/docs/latest-v0.12.x/api/net.html#net_new_net_socket_options v4: https://nodejs.org/dist/latest-v4.x/docs/api/net.html#net_new_net_socket_options v6: https://nodejs.org/dist/latest-v6.x/docs/api/net.html#net_new_net_socket_options v7: https://nodejs.org/dist/latest-v7.x/docs/api/net.html#net_new_net_socket_options v8: https://nodejs.org/api/net.html#net_new_net_socket_options --- types/node/index.d.ts | 3 ++- types/node/node-tests.ts | 7 ++++++- types/node/v0/index.d.ts | 2 +- types/node/v0/node-tests.ts | 18 ++++++++++++++++++ types/node/v4/index.d.ts | 2 +- types/node/v4/node-tests.ts | 12 ++++++++++++ types/node/v6/index.d.ts | 2 +- types/node/v6/node-tests.ts | 7 ++++++- types/node/v7/index.d.ts | 3 ++- types/node/v7/node-tests.ts | 7 ++++++- 10 files changed, 55 insertions(+), 8 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 48aa44a874..518b1d5d00 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -10,6 +10,7 @@ // Chigozirim C. // Flarna // Mariusz Wiktorczyk +// Daniel Imms // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -2426,7 +2427,7 @@ declare module "net" { } export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + new (options?: { fd?: number; allowHalfOpen?: boolean; readable?: boolean; writable?: boolean; }): Socket; }; export interface ListenOptions { diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index defd7aa6f4..10ce35e723 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -2193,7 +2193,12 @@ namespace net_tests { * 7. lookup * 8. timeout */ - let _socket: net.Socket; + let _socket: net.Socket = new net.Socket({ + fd: 1, + allowHalfOpen: false, + readable: false, + writable: false + }); let bool: boolean; let buffer: Buffer; diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index 5a383ce9db..fdbf9dd518 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -1027,7 +1027,7 @@ declare module "net" { } export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + new (options?: { fd?: number; allowHalfOpen?: boolean; readable?: boolean; writable?: boolean; }): Socket; }; export interface Server extends events.EventEmitter { diff --git a/types/node/v0/node-tests.ts b/types/node/v0/node-tests.ts index 57019bfe86..6c94757bf7 100644 --- a/types/node/v0/node-tests.ts +++ b/types/node/v0/node-tests.ts @@ -80,6 +80,24 @@ fs.readFile('testfile', (err, data) => { }); +/////////////////////////////////////////////////// +/// Net Tests : https://nodejs.org/api/net.html /// +/////////////////////////////////////////////////// + +namespace net_tests { + { + /** + * net.Socket - events.EventEmitter + */ + let _socket: net.Socket = new net.Socket({ + fd: 1, + allowHalfOpen: false, + readable: false, + writable: false + }); + } +} + /////////////////////////////////////////////////////// /// Buffer tests : https://nodejs.org/api/buffer.html /////////////////////////////////////////////////////// diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 51197e1da4..4e6d0290c1 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1406,7 +1406,7 @@ declare module "net" { } export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + new (options?: { fd?: number; allowHalfOpen?: boolean; readable?: boolean; writable?: boolean; }): Socket; }; export interface ListenOptions { diff --git a/types/node/v4/node-tests.ts b/types/node/v4/node-tests.ts index 654f397b73..16a035f08e 100644 --- a/types/node/v4/node-tests.ts +++ b/types/node/v4/node-tests.ts @@ -1002,6 +1002,18 @@ namespace net_tests { // Make sure .listen() and .close() retuern a Server instance net.createServer().listen(0).close().address(); } + + { + /** + * net.Socket - events.EventEmitter + */ + let _socket: net.Socket = new net.Socket({ + fd: 1, + allowHalfOpen: false, + readable: false, + writable: false + }); + } } /////////////////////////////////////////////////// diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 49a6cf98a5..c85ecf68be 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -2057,7 +2057,7 @@ declare module "net" { } export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + new (options?: { fd?: number; allowHalfOpen?: boolean; readable?: boolean; writable?: boolean; }): Socket; }; export interface ListenOptions { diff --git a/types/node/v6/node-tests.ts b/types/node/v6/node-tests.ts index 7be75e162b..492b9e36df 100644 --- a/types/node/v6/node-tests.ts +++ b/types/node/v6/node-tests.ts @@ -1868,7 +1868,12 @@ namespace net_tests { * 7. lookup * 8. timeout */ - let _socket: net.Socket; + let _socket: net.Socket = new net.Socket({ + fd: 1, + allowHalfOpen: false, + readable: false, + writable: false + }); let bool: boolean; let buffer: Buffer; diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 207843eb3d..b435b56c96 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -6,6 +6,7 @@ // Roberto Desideri // Christian Vaagland Tellnes // Wilco Bakker +// Daniel Imms // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -2186,7 +2187,7 @@ declare module "net" { } export var Socket: { - new (options?: { fd?: string; type?: string; allowHalfOpen?: boolean; }): Socket; + new (options?: { fd?: number; allowHalfOpen?: boolean; readable?: boolean; writable?: boolean; }): Socket; }; export interface ListenOptions { diff --git a/types/node/v7/node-tests.ts b/types/node/v7/node-tests.ts index dad54bed49..b89adb57ae 100644 --- a/types/node/v7/node-tests.ts +++ b/types/node/v7/node-tests.ts @@ -1979,7 +1979,12 @@ namespace net_tests { * 7. lookup * 8. timeout */ - let _socket: net.Socket; + let _socket: net.Socket = new net.Socket({ + fd: 1, + allowHalfOpen: false, + readable: false, + writable: false + }); let bool: boolean; let buffer: Buffer; From 9dc4f81823ce9d660e4434ad93d7e60a8649ef2a Mon Sep 17 00:00:00 2001 From: zbarbuto Date: Sat, 22 Jul 2017 02:14:36 +0930 Subject: [PATCH 0186/1139] Add missing maildev options (#18252) * Add missing maildev options * Update maildev tests --- types/maildev/index.d.ts | 66 +++++++++++++++++++++++++++++++++- types/maildev/maildev-tests.ts | 9 ++++- 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/types/maildev/index.d.ts b/types/maildev/index.d.ts index 2114f05866..091e6362e5 100644 --- a/types/maildev/index.d.ts +++ b/types/maildev/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for maildev 0.11.0 +// Type definitions for maildev 1.0.0-rc3 // Project: https://github.com/djfarrelly/maildev // Definitions by: Cyril Schumacher +// Zak Barbuto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -9,6 +10,13 @@ * Interface for {@link MailDev} options. */ interface MailDevOptions { + /** + * IP Address to bind SMTP service to', '0.0.0.0' + * + * @type {string} + */ + ip?: string; + /** * SMTP host for outgoing emails * @@ -37,12 +45,68 @@ interface MailDevOptions { */ outgoingUser?: string; + /** + * Use SMTP SSL for outgoing emails + * + * @type {boolean} + */ + outgoingSecure?: boolean; + /** * SMTP port to catch emails. * * @type {number} */ smtp?: number; + + /** + * Port to use for web UI + * + * @type {number} + */ + web?: number; + + /** + * IP Address to bind HTTP service to + * + * @type {string} + */ + webIp?: string; + + /** + * Do not start web UI + * + * @type {boolean} + */ + disableWeb?: boolean; + + /** + * Do not output console.log messages + * + * @type {boolean} + */ + silent?: boolean; + + /** + * HTTP user for GUI + * + * @type {string} + */ + webUser?: string; + + /** + * HTTP password for GUI + * + * @type {string} + */ + webPass?: string; + + /** + * Open the Web GUI after startup + * + * @type {boolean} + */ + open?: boolean; } /** diff --git a/types/maildev/maildev-tests.ts b/types/maildev/maildev-tests.ts index 153cc18f0d..b03de3a63a 100644 --- a/types/maildev/maildev-tests.ts +++ b/types/maildev/maildev-tests.ts @@ -1,6 +1,13 @@ import MailDev = require("maildev") -var options: MailDevOptions = {smtp: 1025}; +var options: MailDevOptions = { + silent: true, + disableWeb: true, + smtp: 1025, + web: 1080, + webUser: 'admin', + webPass: 'secret' +}; var maildev = new MailDev(options); var errorCallback = (error: Error): void => {}; From 3f0193af10c8ea15ad1f8f1799426861f70f8503 Mon Sep 17 00:00:00 2001 From: Matus Gura Date: Fri, 21 Jul 2017 18:46:58 +0200 Subject: [PATCH 0187/1139] [email-templates] Compliant with the latest version 2.6.0 (#18254) * Made email-templates complaint with the latest version 2.6.0 * Added linter and updated a test --- .../email-templates/email-templates-tests.ts | 20 ++-- types/email-templates/index.d.ts | 111 +++++++++++++++--- types/email-templates/tsconfig.json | 2 +- types/email-templates/tslint.json | 6 + 4 files changed, 116 insertions(+), 23 deletions(-) create mode 100644 types/email-templates/tslint.json diff --git a/types/email-templates/email-templates-tests.ts b/types/email-templates/email-templates-tests.ts index 9f9097609e..3c4493402c 100644 --- a/types/email-templates/email-templates-tests.ts +++ b/types/email-templates/email-templates-tests.ts @@ -1,9 +1,9 @@ import EmailTemplates = require('email-templates'); -var EmailTemplate = EmailTemplates.EmailTemplate; -var template = new EmailTemplate("./"); -var templateWithOptions = new EmailTemplate('./', {sassOptions: {}, juiceOptions: {}}); -var users = [ +const EmailTemplate = EmailTemplates.EmailTemplate; +const template = new EmailTemplate("./"); +const templateWithOptions = new EmailTemplate('./', {disableJuice: true, sassOptions: {}, juiceOptions: {}}); +const users = [ { email: 'pappa.pizza@spaghetti.com', name: { @@ -18,8 +18,12 @@ var users = [ last: 'Geppetto' } } -] +]; -var templates = users.map(function(user) { - return template.render(user); -}) +const templates = users.map((user) => { + return template.render(user) + .then((results) => { + const {html, subject, text} = results; + return html; + }); +}); diff --git a/types/email-templates/index.d.ts b/types/email-templates/index.d.ts index 5fdd7054f3..d76c23aed3 100644 --- a/types/email-templates/index.d.ts +++ b/types/email-templates/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for node-email-templates +// Type definitions for node-email-templates 2.6 // Project: https://github.com/niftylettuce/node-email-templates // Definitions by: Cyril Schumacher +// Matus Gura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** @@ -28,23 +29,18 @@ interface EmailTemplateResults { } /** - * @summary Interface for callback of email callback. - * @interface + * @summary Callback signature. */ -interface EmailTemplateCallback { - /** - * @summary Callback signature. - */ - (err: Object, results: EmailTemplateResults): void; -} +type EmailTemplateCallback = (err: any, results: EmailTemplateResults) => void; /** * @summary Interface for email-template options * @interface */ interface EmailTemplateOptions { - sassOptions?: any; + disableJuice?: boolean; juiceOptions?: any; + sassOptions?: any; } declare module "email-templates" { @@ -52,7 +48,7 @@ declare module "email-templates" { * @summary Email template class. * @class */ - export class EmailTemplate { + class EmailTemplate { /** * @summary Constructor. * @param {string} templateDir The template directory. @@ -61,9 +57,96 @@ declare module "email-templates" { /** * @summary Render a single template. - * @param {EmailTemplateCallback|Object} locals The variables or callback function. - * @param {EmailTemplateCallback} callback The callback function. + * @param locals The template variables. + * @param locale The language code. */ - render(locals: EmailTemplateCallback|Object, callback?: EmailTemplateCallback): void | Promise; + render(locals: any, locale?: string): Promise; + + /** + * @summary Render a single template. + * @param callback The callback function. + */ + render(callback: EmailTemplateCallback): void; + + /** + * @summary Render a single template. + * @param locals The template variables. + * @param callback The callback function. + */ + render(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render a single template. + * @param locals The template variables. + * @param locale The language code. + * @param callback The callback function. + */ + render(locals: any, locale: string, callback: EmailTemplateCallback): void; + + /** + * @summary Render text + * @param locals The template variables. + * @param locale The language code. + */ + renderText(locals: any, locale?: string): Promise; + + /** + * @summary Render text + * @param locals The template variables. + * @param callback The language code. + */ + renderText(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render text + * @param locals The template variables. + * @param locale The language code. + * @param callback The language code. + */ + renderText(locals: any, locale: string, callback: EmailTemplateCallback): void; + + /** + * @summary Render subject + * @param locals The template variables. + * @param locale The language code. + */ + renderSubject(locals: any, locale?: string): Promise; + + /** + * @summary Render subject + * @param locals The template variables. + * @param callback The language code. + */ + renderSubject(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render subject + * @param locals The template variables. + * @param locale The language code. + * @param callback The language code. + */ + renderSubject(locals: any, locale: string, callback: EmailTemplateCallback): void; + + /** + * @summary Render HTML + * @param locals The template variables. + * @param locale The language code. + */ + renderHtml(locals: any, locale?: string): Promise; + + /** + * @summary Render HTML + * @param locals The template variables. + * @param callback The language code. + */ + renderHtml(locals: any, callback: EmailTemplateCallback): void; + + /** + * @summary Render HTML + * @param locals The template variables. + * @param locale The language code. + * @param callback The language code. + */ + renderHtml(locals: any, locale: string, callback: EmailTemplateCallback): void; } } diff --git a/types/email-templates/tsconfig.json b/types/email-templates/tsconfig.json index bc97b20dbc..cf59410224 100644 --- a/types/email-templates/tsconfig.json +++ b/types/email-templates/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "email-templates-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/email-templates/tslint.json b/types/email-templates/tslint.json new file mode 100644 index 0000000000..e765bc9e16 --- /dev/null +++ b/types/email-templates/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-single-declare-module": false + } +} From 3f1a9ccec07ab1f5c9518cee294792a03467373f Mon Sep 17 00:00:00 2001 From: Tom Doggett Date: Fri, 21 Jul 2017 09:47:36 -0700 Subject: [PATCH 0188/1139] Updating React.HTMLAttributes used by Enzyme to new React.AllHTMLAttributes interface introduced in @types/react-15.0.38 (#18269) --- types/enzyme/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index a5c2a72308..e1fdba2027 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -10,7 +10,7 @@ // TypeScript Version: 2.3 /// -import { ReactElement, Component, HTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; +import { ReactElement, Component, AllHTMLAttributes as ReactHTMLAttributes, SVGAttributes as ReactSVGAttributes } from "react"; export type HTMLAttributes = ReactHTMLAttributes<{}> & ReactSVGAttributes<{}>; From 5fb85c244c8f9215c1cdbfa71aafe2e5536a23da Mon Sep 17 00:00:00 2001 From: Tom Wanzek Date: Fri, 21 Jul 2017 12:48:03 -0400 Subject: [PATCH 0189/1139] [d3] Update to Minor Version 4.10 (#18103) * [d3-zoom] Update to 1.5 * [Feature] Add `translateTo(...)` * [Doc] Update some JSDoc comments * [Chore] Bump minor version number * [d3-zoom] Bump Minor Version number. * [d3-shape] * [Fix] Change `pointRadius` to `pointRadial` * [d3-shape] Fix test for pointRadial * [d3-axis] * [Doc] Update some comments. * [d3-time] [Doc] Some JSDoc updates. * [d3] [Chore] Bump minor version to 4.10 --- types/d3-axis/index.d.ts | 38 +++++- types/d3-shape/d3-shape-tests.ts | 4 +- types/d3-shape/index.d.ts | 4 +- types/d3-time/index.d.ts | 4 +- types/d3-zoom/d3-zoom-tests.ts | 100 ++++++++++++++++ types/d3-zoom/index.d.ts | 198 ++++++++++++++++++++++++++----- types/d3/index.d.ts | 2 +- 7 files changed, 310 insertions(+), 40 deletions(-) diff --git a/types/d3-axis/index.d.ts b/types/d3-axis/index.d.ts index 9cee537067..1c7820c809 100644 --- a/types/d3-axis/index.d.ts +++ b/types/d3-axis/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.4 +// Last module patch version validated against: 1.0.8 import { Selection, TransitionLike } from 'd3-selection'; @@ -82,6 +82,10 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * This method is also a convenience function for axis.tickArguments. + * * @param count Number of ticks that should be rendered * @param specifier An optional format specifier to customize how the tick values are formatted. */ @@ -91,6 +95,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * This method is also a convenience function for axis.tickArguments. + * * @param interval A time interval used to generate date-based ticks. This is typically a TimeInterval/CountableTimeInterval as defined * in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). * @param specifier An optional format specifier to customize how the tick values are formatted. @@ -99,17 +105,31 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. + * + * The meaning of the arguments depends on the axis’ scale type: most commonly, the arguments are a suggested count for the number of ticks + * (or a time interval for time scales), and an optional format specifier to customize how the tick values are formatted. + * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * This method is also a convenience function for axis.tickArguments. */ ticks(arg0: any, ...args: any[]): this; /** - * Get an array containing the currently set arguments to be passed into scale.ticks and scale.tickFormat. + * Get an array containing the currently set arguments to be passed into scale.ticks and scale.tickFormat, which defaults to the empty array. */ tickArguments(): any[]; /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array containing a single element representing the count, i.e. number of ticks to be rendered. */ tickArguments(args: [number]): this; @@ -117,6 +137,11 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array containing two elements. The first element represents the count, i.e. number of ticks to be rendered. The second * element is a string representing the format specifier to customize how the tick values are formatted. */ @@ -126,6 +151,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * See also axis.ticks. + * * @param args An array containing a single element representing a time interval used to generate date-based ticks. * This is typically a TimeInterval/CountableTimeInterval as defined in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). */ @@ -135,6 +162,8 @@ export interface Axis { * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * Use with a TIME SCALE ONLY. * + * See also axis.ticks. + * * @param args An array containing two elements. The first element represents a time interval used to generate date-based ticks. * This is typically a TimeInterval/CountableTimeInterval as defined in d3-time. E.g. as obtained by passing in d3.timeMinute.every(15). * The second element is a string representing the format specifier to customize how the tick values are formatted. @@ -144,6 +173,11 @@ export interface Axis { /** * Sets the arguments that will be passed to scale.ticks and scale.tickFormat when the axis is rendered, and returns the axis generator. * + * This method has no effect if the scale does not implement scale.ticks, as with band and point scales. + * To set the tick values explicitly, use axis.tickValues. To set the tick format explicitly, use axis.tickFormat. + * + * See also axis.ticks. + * * @param args An array with arguments suitable for the scale to be used for tick generation */ tickArguments(args: any[]): this; diff --git a/types/d3-shape/d3-shape-tests.ts b/types/d3-shape/d3-shape-tests.ts index 6e0fa97d96..ee9a8fbb98 100644 --- a/types/d3-shape/d3-shape-tests.ts +++ b/types/d3-shape/d3-shape-tests.ts @@ -1319,10 +1319,10 @@ customSymbol = d3Shape.symbolTriangle; customSymbol = d3Shape.symbolWye; // ----------------------------------------------------------------------------------- -// Test pointRadius +// Test pointRadial // ----------------------------------------------------------------------------------- -let coordinatates: [number, number] = d3Shape.pointRadius(0, 12); +let coordinatates: [number, number] = d3Shape.pointRadial(0, 12); // ----------------------------------------------------------------------------------- // Test Stacks diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index 010c2108e9..27a92a79fe 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -2436,7 +2436,7 @@ export const symbolTriangle: SymbolType; export const symbolWye: SymbolType; // ----------------------------------------------------------------------------------- -// pointRadius +// pointRadial // ----------------------------------------------------------------------------------- /** @@ -2444,7 +2444,7 @@ export const symbolWye: SymbolType; * @param angle Angle in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise. * @param radius Radius. */ -export function pointRadius(angle: number, radius: number): [number, number]; +export function pointRadial(angle: number, radius: number): [number, number]; // ----------------------------------------------------------------------------------- // STACKS diff --git a/types/d3-time/index.d.ts b/types/d3-time/index.d.ts index 5e2b66718f..3d88edbf27 100644 --- a/types/d3-time/index.d.ts +++ b/types/d3-time/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.0.4 +// Last module patch version validated against: 1.0.7 // --------------------------------------------------------------- // Interfaces @@ -151,6 +151,8 @@ export interface CountableTimeInterval extends TimeInterval { * * This method can be used in conjunction with interval.range to ensure that two overlapping ranges are consistent. * + * The returned filtered interval does not support interval.count. See also interval.filter. + * * @param step Number of steps. */ every(step: number): TimeInterval | null; diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index 185b9fd45a..02f7120e79 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -385,6 +385,106 @@ svgZoom.translateBy( return 30; }); +// translateTo() ------------------------------------------------------------------------------------- + +// use on selection +svgZoom.translateTo(svgOverlay, 20, 50); +// svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismachtes DOM Element type and datum type + +svgZoom.translateTo( + svgOverlay, + 20, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }); +svgZoom.translateTo( + svgOverlay, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }, + 50); +svgZoom.translateTo( + svgOverlay, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }); + +// use on transition +svgZoom.translateTo(svgOverlayTransition, 20, 50); +// svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismachtes DOM Element type and datum type + +svgZoom.translateTo( + svgOverlayTransition, + 20, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }); +svgZoom.translateTo( + svgOverlayTransition, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }, + 50); +svgZoom.translateTo( + svgOverlayTransition, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }, + function(datum, index, groups) { + const that: SVGRectElement = this; + const d: SVGDatum = datum; + const i: number = index; + const g: SVGRectElement[] | ArrayLike = groups; + console.log('Owner SVG Element of svg rect: ', this.ownerSVGElement); // this is of type SVGRectElement + console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum + return 30; + }); + // scaleBy() ------------------------------------------------------------------------------------- // use on selection diff --git a/types/d3-zoom/index.d.ts b/types/d3-zoom/index.d.ts index a0980344bb..a633644ded 100644 --- a/types/d3-zoom/index.d.ts +++ b/types/d3-zoom/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for d3JS d3-zoom module 1.3 +// Type definitions for d3JS d3-zoom module 1.5 // Project: https://github.com/d3/d3-zoom/ // Definitions by: Tom Wanzek , Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last module patch version validated against: 1.3.0 +// Last module patch version validated against: 1.5.0 import { ArrayLike, Selection, TransitionLike, ValueFn } from 'd3-selection'; import { ZoomView, ZoomInterpolator } from 'd3-interpolate'; @@ -127,7 +127,7 @@ export interface ZoomBehavior, x: number, y: number): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x A value function which is evaluated for each selected element, @@ -156,13 +156,13 @@ export interface ZoomBehavior, x: ValueFn, y: number): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x Amount of translation in x-direction. @@ -173,13 +173,13 @@ export interface ZoomBehavior, x: number, y: ValueFn): void; /** * Translates the current zoom transform of the selected elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param x A value function which is evaluated for each selected element, @@ -192,13 +192,13 @@ export interface ZoomBehavior, x: ValueFn, y: ValueFn): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x Amount of translation in x-direction. @@ -207,13 +207,13 @@ export interface ZoomBehavior, x: number, y: number): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x A value function which is evaluated for each selected element, @@ -224,13 +224,13 @@ export interface ZoomBehavior, x: ValueFn, y: number): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided as a constant for all elements. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x Amount of translation in x-direction. @@ -241,13 +241,13 @@ export interface ZoomBehavior, x: number, y: ValueFn): void; /** * Defines a “zoom” tween translating the current transform for the transitioning elements by x and y, - * such that the new t(x1) = t(x0) + k × x and t(y1) = t(y0) + k × y. + * such that the new t(x1) = t(x0) + kx and t(y1) = t(y0) + ky. * * x is provided by a value function evaluated for each element in the selection. * y is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param x A value function which is evaluated for each selected element, @@ -260,24 +260,158 @@ export interface ZoomBehavior, x: ValueFn, y: ValueFn): void; /** - * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided as a constant for all elements. + * + * @param selection A D3 selection of elements. + * @param x Target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(selection: Selection, x: number, y: number): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(selection: Selection, x: ValueFn, y: number): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x Target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(selection: Selection, x: number, y: ValueFn): void; + /** + * Translates the current zoom transform of the selected elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param selection A D3 selection of elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(selection: Selection, x: ValueFn, y: ValueFn): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x Target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(transition: TransitionLike, x: number, y: number): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided as a constant for all elements. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y Target y-position of translation. + */ + translateTo(transition: TransitionLike, x: ValueFn, y: number): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided as a constant for all elements. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x Target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(transition: TransitionLike, x: number, y: ValueFn): void; + /** + * Defines a “zoom” tween translating the current transform for the transitioning elements such that the specified position ⟨x,y⟩ appears at the center of the viewport extent. + * The new tx = cx - kx and ty = cy - ky, where ⟨cx,cy⟩ is the center. + * + * x is provided by a value function evaluated for each element in the selection. + * y is provided by a value function evaluated for each element in the selection. + * + * This method is a convenience method for zoom.transform. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. + * + * @param transition A D3 transition on elements. + * @param x A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target x-position of translation. + * @param y A value function which is evaluated for each selected element, + * in order, being passed the current datum (d), the current index (i), and the current group (nodes), + * with this as the current DOM element.The function returns the target y-position of translation. + */ + translateTo(transition: TransitionLike, x: ValueFn, y: ValueFn): void; + + /** + * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param k Scale factor. */ scaleBy(selection: Selection, k: number): void; /** - * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Scales the current zoom transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param selection A D3 selection of elements. * @param k A value function which is evaluated for each selected element, @@ -286,24 +420,24 @@ export interface ZoomBehavior, k: ValueFn): void; /** - * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided as a constant for all elements. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param k Scale factor. */ scaleBy(transition: TransitionLike, k: number): void; /** - * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0) × k. + * Defines a “zoom” tween translating scaling the current transform of the selected elements by k, such that the new k(1) = k(0)k. * * k is provided by a value function evaluated for each element in the selection. * * This method is a convenience method for zoom.transform. - * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExten, and zoom.translateExtent. + * In contrast to zoom.transform, however, it is subject to the constraints imposed by zoom.extent, zoom.scaleExtent, and zoom.translateExtent. * * @param transition A D3 transition on elements. * @param k A value function which is evaluated for each selected element, @@ -318,7 +452,7 @@ export interface ZoomBehavior, Alex Ford , Boris Yankov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From ae0493cdc6ea9719c34b0ce2ed172ccb20cc889d Mon Sep 17 00:00:00 2001 From: George MacKerron Date: Fri, 21 Jul 2017 17:48:38 +0100 Subject: [PATCH 0190/1139] Updated ClientConfig to accept TlsOptions instead of just boolean (#18117) --- types/pg/index.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/pg/index.d.ts b/types/pg/index.d.ts index 6718fb3f12..da6f4db575 100644 --- a/types/pg/index.d.ts +++ b/types/pg/index.d.ts @@ -29,8 +29,10 @@ export interface Defaults extends ConnectionConfig { parseInt8?: boolean; } +import { TlsOptions } from "tls"; + export interface ClientConfig extends ConnectionConfig { - ssl?: boolean; + ssl?: boolean | TlsOptions; } export interface PoolConfig extends ClientConfig { From 379d9ca112f0837822a5ecee1cfa10ba2f655760 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Fri, 21 Jul 2017 18:49:20 +0200 Subject: [PATCH 0191/1139] [is-stream] introduce typings (#18285) --- types/is-stream/index.d.ts | 18 ++++++++++++++++++ types/is-stream/is-stream-tests.ts | 24 ++++++++++++++++++++++++ types/is-stream/tsconfig.json | 22 ++++++++++++++++++++++ types/is-stream/tslint.json | 1 + 4 files changed, 65 insertions(+) create mode 100644 types/is-stream/index.d.ts create mode 100644 types/is-stream/is-stream-tests.ts create mode 100644 types/is-stream/tsconfig.json create mode 100644 types/is-stream/tslint.json diff --git a/types/is-stream/index.d.ts b/types/is-stream/index.d.ts new file mode 100644 index 0000000000..0c24d084d9 --- /dev/null +++ b/types/is-stream/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for is-stream 1.1 +// Project: https://github.com/sindresorhus/is-stream#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as stream from "stream"; + +export = isStream; + +declare function isStream(maybeStream: any): maybeStream is stream.Stream; + +declare namespace isStream { + function writable(maybeWritable: any): maybeWritable is stream.Writable; + function readable(maybeReadable: any): maybeReadable is stream.Readable; + function duplex(maybeDuplex: any): maybeDuplex is stream.Duplex; + function transform(maybeTransform: any): maybeTransform is stream.Transform; +} diff --git a/types/is-stream/is-stream-tests.ts b/types/is-stream/is-stream-tests.ts new file mode 100644 index 0000000000..9d9eb315b4 --- /dev/null +++ b/types/is-stream/is-stream-tests.ts @@ -0,0 +1,24 @@ +import isStream = require('is-stream'); +import * as stream from 'stream'; + +const anyStream: any = new stream.Stream(); + +if (isStream(anyStream)) { + const justStream: stream.Stream = anyStream; +} + +if (isStream.writable(anyStream)) { + const writableStream: stream.Writable = anyStream; +} + +if (isStream.readable(anyStream)) { + const readableStream: stream.Readable = anyStream; +} + +if (isStream.duplex(anyStream)) { + const duplexStream: stream.Duplex = anyStream; +} + +if (isStream.transform(anyStream)) { + const transformStream: stream.Transform = anyStream; +} diff --git a/types/is-stream/tsconfig.json b/types/is-stream/tsconfig.json new file mode 100644 index 0000000000..926737569f --- /dev/null +++ b/types/is-stream/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-stream-tests.ts" + ] +} diff --git a/types/is-stream/tslint.json b/types/is-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 0dd0b27c90397221dbbfda722eaf5e58eb889aea Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Fri, 21 Jul 2017 18:50:03 +0200 Subject: [PATCH 0192/1139] [hasha] introduce typings (#18284) --- types/hasha/hasha-tests.ts | 19 +++++++++++++++++++ types/hasha/index.d.ts | 38 ++++++++++++++++++++++++++++++++++++++ types/hasha/tsconfig.json | 22 ++++++++++++++++++++++ types/hasha/tslint.json | 1 + 4 files changed, 80 insertions(+) create mode 100644 types/hasha/hasha-tests.ts create mode 100644 types/hasha/index.d.ts create mode 100644 types/hasha/tsconfig.json create mode 100644 types/hasha/tslint.json diff --git a/types/hasha/hasha-tests.ts b/types/hasha/hasha-tests.ts new file mode 100644 index 0000000000..d0054de81a --- /dev/null +++ b/types/hasha/hasha-tests.ts @@ -0,0 +1,19 @@ +import hasha = require('hasha'); + +let str: string | null; +let buf: Buffer | null; + +str = hasha('unicorn'); +str = hasha('unicorn', {algorithm: 'md5'}); +str = hasha('unicorn', {algorithm: 'md5', encoding: 'latin1'}); +buf = hasha('unicorn', {algorithm: 'md5', encoding: 'buffer'}); + +process.stdin.pipe(hasha.stream()).pipe(process.stdout); + +hasha.fromStream(process.stdin).then(hash => str = hash); +hasha.fromStream(process.stdin, {encoding: 'hex'}).then(hash => str = hash); +hasha.fromStream(process.stdin, {encoding: 'buffer'}).then(hash => buf = hash); + +hasha.fromFile('unicorn.png').then(hash => str = hash); +hasha.fromFile('unicorn.png', {encoding: 'base64'}).then(hash => str = hash); +hasha.fromFile('unicorn.png', {encoding: 'buffer'}).then(hash => buf = hash); diff --git a/types/hasha/index.d.ts b/types/hasha/index.d.ts new file mode 100644 index 0000000000..a158af88a3 --- /dev/null +++ b/types/hasha/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for hasha 3.0 +// Project: https://github.com/sindresorhus/hasha +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// +import * as crypto from "crypto"; + +export = hasha; + +declare function hasha(input: hasha.HashaInput): string; +declare function hasha(input: hasha.HashaInput, options: hasha.HashaOptions): string; +declare function hasha(input: hasha.HashaInput, options: hasha.HashaOptions): Buffer; + +declare namespace hasha { + type HashaInput = string | string[] | Buffer | Buffer[]; + type ToStringEncoding = 'hex' | 'base64' | 'latin1' | 'binary' | undefined; + type HashaEncoding = ToStringEncoding | 'buffer'; + + interface HashaOptions { + encoding?: E; + algorithm?: string; + } + + function stream(options?: HashaOptions): crypto.Hash; + + function fromStream(stream: NodeJS.ReadableStream): Promise; + function fromStream(stream: NodeJS.ReadableStream, options?: HashaOptions): Promise; + function fromStream(stream: NodeJS.ReadableStream, options?: HashaOptions): Promise; + + function fromFile(filePath: string): Promise; + function fromFile(filePath: string, options: HashaOptions): Promise; + function fromFile(filePath: string, options: HashaOptions): Promise; + + function fromFileSync(filePath: string): string; + function fromFileSync(filePath: string, options: HashaOptions): string; + function fromFileSync(filePath: string, options: HashaOptions): Buffer; +} diff --git a/types/hasha/tsconfig.json b/types/hasha/tsconfig.json new file mode 100644 index 0000000000..3aeb5973e8 --- /dev/null +++ b/types/hasha/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hasha-tests.ts" + ] +} diff --git a/types/hasha/tslint.json b/types/hasha/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hasha/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From cfb448f0ac3576fad1e17013dac0cad4ac4ef793 Mon Sep 17 00:00:00 2001 From: Douglas Duteil Date: Fri, 21 Jul 2017 18:50:48 +0200 Subject: [PATCH 0193/1139] feat(tempy): add typings for tempy (#18246) * feat(tempy): add typings for tempy * test(tempy): use promise instead of async/await * test(tempy): remove use of console.log API --- types/tempy/index.d.ts | 9 +++++++++ types/tempy/tempy-tests.ts | 12 ++++++++++++ types/tempy/tsconfig.json | 22 ++++++++++++++++++++++ types/tempy/tslint.json | 1 + 4 files changed, 44 insertions(+) create mode 100644 types/tempy/index.d.ts create mode 100644 types/tempy/tempy-tests.ts create mode 100644 types/tempy/tsconfig.json create mode 100644 types/tempy/tslint.json diff --git a/types/tempy/index.d.ts b/types/tempy/index.d.ts new file mode 100644 index 0000000000..ec210e0829 --- /dev/null +++ b/types/tempy/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for tempy 0.1 +// Project: https://github.com/sindresorhus/tempy#readme +// Definitions by: Douglas Duteil +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function directoryAsync(): Promise; +export function directory(): string; +export function file(options?: {extension: string}): string; +export const root: string; diff --git a/types/tempy/tempy-tests.ts b/types/tempy/tempy-tests.ts new file mode 100644 index 0000000000..56ec437e55 --- /dev/null +++ b/types/tempy/tempy-tests.ts @@ -0,0 +1,12 @@ +import { directoryAsync, directory, file, root } from 'tempy'; + +// + +directoryAsync().then((tempDir1: string) => tempDir1 === '/tmp/123456789'); + +const tempDir2: string = directory(); + +const tempFile: string = file(); +const pngFile: string = file({extension: 'png'}); + +const tmpRoot: string = root; diff --git a/types/tempy/tsconfig.json b/types/tempy/tsconfig.json new file mode 100644 index 0000000000..a0716fb0c9 --- /dev/null +++ b/types/tempy/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "tempy-tests.ts" + ] +} diff --git a/types/tempy/tslint.json b/types/tempy/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/tempy/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From d7a3309b4e06ba488e893d2584a3644570280de6 Mon Sep 17 00:00:00 2001 From: Marvin Hagemeister Date: Fri, 21 Jul 2017 18:52:37 +0200 Subject: [PATCH 0194/1139] Add babel-plugin-syntax-jsx package (#18282) --- .../babel-plugin-syntax-jsx-tests.ts | 10 +++++++++ types/babel-plugin-syntax-jsx/index.d.ts | 13 +++++++++++ types/babel-plugin-syntax-jsx/tsconfig.json | 22 +++++++++++++++++++ types/babel-plugin-syntax-jsx/tslint.json | 1 + 4 files changed, 46 insertions(+) create mode 100644 types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts create mode 100644 types/babel-plugin-syntax-jsx/index.d.ts create mode 100644 types/babel-plugin-syntax-jsx/tsconfig.json create mode 100644 types/babel-plugin-syntax-jsx/tslint.json diff --git a/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts b/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts new file mode 100644 index 0000000000..4dcb7b4882 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/babel-plugin-syntax-jsx-tests.ts @@ -0,0 +1,10 @@ +import jsx from "babel-plugin-syntax-jsx"; + +// Example taken from the babel plugin handbook: +// https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#-enabling-syntax-in-plugins +export default function myBabelPlugin() { + return { + visitor: {}, + inherits: jsx, + }; +} diff --git a/types/babel-plugin-syntax-jsx/index.d.ts b/types/babel-plugin-syntax-jsx/index.d.ts new file mode 100644 index 0000000000..c7b0ede972 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for babel-plugin-syntax-jsx 6.18 +// Project: https://github.com/babel/babel/tree/master/packages/babel-plugin-syntax-jsx +// Definitions by: Marvin Hagemeister +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// NB: This export doesn't match the handbook example, where `jsx` is the default export. +// But it does match the runtime behaviour (at least at the time of this writing). For some reason, +// babel-plugin-syntax-jsx/lib/index.js has this line at the bottom: module.exports = exports["default"]; +declare function jsx(): { + manipulateOptions(opts: any, parserOpts: { plugins: string[] }): void; +}; + +export default jsx; diff --git a/types/babel-plugin-syntax-jsx/tsconfig.json b/types/babel-plugin-syntax-jsx/tsconfig.json new file mode 100644 index 0000000000..bb19fbf329 --- /dev/null +++ b/types/babel-plugin-syntax-jsx/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "babel-plugin-syntax-jsx-tests.ts" + ] +} diff --git a/types/babel-plugin-syntax-jsx/tslint.json b/types/babel-plugin-syntax-jsx/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/babel-plugin-syntax-jsx/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From a07f6d8f8a66af5cf0572bc856af6459930900f7 Mon Sep 17 00:00:00 2001 From: coderslagoon Date: Fri, 21 Jul 2017 10:01:15 -0700 Subject: [PATCH 0195/1139] Type definitions for is-ip (#18272) --- types/is-ip/index.d.ts | 35 +++++++++++++++++++++++++++++++++++ types/is-ip/is-ip-tests.ts | 28 ++++++++++++++++++++++++++++ types/is-ip/tsconfig.json | 22 ++++++++++++++++++++++ types/is-ip/tslint.json | 1 + 4 files changed, 86 insertions(+) create mode 100644 types/is-ip/index.d.ts create mode 100644 types/is-ip/is-ip-tests.ts create mode 100644 types/is-ip/tsconfig.json create mode 100644 types/is-ip/tslint.json diff --git a/types/is-ip/index.d.ts b/types/is-ip/index.d.ts new file mode 100644 index 0000000000..930cb8951d --- /dev/null +++ b/types/is-ip/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for is-ip 2.0 +// Project: https://github.com/sindresorhus/is-ip#readme +// Definitions by: coderslagoon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Check if input is IPv4 or IPv6. + * + * @param {input} input + * + * @returns {boolean} + */ +declare function isIp(input: string): boolean; + +declare namespace isIp { + /** + * Check if input is IPv4. + * + * @param {input} input + * + * @returns {boolean} + */ + function v4(input: string): boolean; + + /** + * Check if input is IPv6. + * + * @param {input} input + * + * @returns {boolean} + */ + function v6(input: string): boolean; +} + +export = isIp; diff --git a/types/is-ip/is-ip-tests.ts b/types/is-ip/is-ip-tests.ts new file mode 100644 index 0000000000..d062f6dde9 --- /dev/null +++ b/types/is-ip/is-ip-tests.ts @@ -0,0 +1,28 @@ +import * as isIp from "is-ip"; + +isIp("nope"); +// => false + +isIp("127.0.0.1"); +// => true + +isIp("0.0.0.0"); +// => true + +isIp("127.0.0.256"); +// => false + +isIp.v4("127.0.0.1"); +// => true + +isIp.v4("1:2:3:4:5:6:7:8"); +// => false + +isIp.v6("1:2:3:4:5:6:7:8"); +// => true + +isIp.v6("::"); +// => true + +isIp.v6("127.0.0.1"); +// => false diff --git a/types/is-ip/tsconfig.json b/types/is-ip/tsconfig.json new file mode 100644 index 0000000000..be6e5c55e0 --- /dev/null +++ b/types/is-ip/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "is-ip-tests.ts" + ] +} diff --git a/types/is-ip/tslint.json b/types/is-ip/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-ip/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From af323c27a4affb66c5789720bc63b6af1295cace Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Fri, 21 Jul 2017 19:02:09 +0200 Subject: [PATCH 0196/1139] [ora] introduce typings for v1 (#18233) * [ora] move old typings to subdir * [ora] introduce typings for v1 * [ora] change indentation to 4 spaces * [ora] change indentation to 4 spaces * [ora] change indentation to 4 spaces * [ora] make factory parameter optional * [ora] fix indentation, correct profile url for Christian Rackerseder --- types/ora/index.d.ts | 125 +++++++++++++++++++++++++++++++++---- types/ora/ora-tests.ts | 45 ++++++++++++- types/ora/tsconfig.json | 2 +- types/ora/tslint.json | 1 + types/ora/v0/index.d.ts | 34 ++++++++++ types/ora/v0/ora-tests.ts | 8 +++ types/ora/v0/tsconfig.json | 27 ++++++++ 7 files changed, 226 insertions(+), 16 deletions(-) create mode 100644 types/ora/tslint.json create mode 100644 types/ora/v0/index.d.ts create mode 100644 types/ora/v0/ora-tests.ts create mode 100644 types/ora/v0/tsconfig.json diff --git a/types/ora/index.d.ts b/types/ora/index.d.ts index e45a585442..2d45e458c7 100644 --- a/types/ora/index.d.ts +++ b/types/ora/index.d.ts @@ -1,34 +1,133 @@ -// Type definitions for ora v0.3.0 +// Type definitions for ora 1.3 // Project: https://github.com/sindresorhus/ora -// Definitions by: Basarat Ali Syed , Christian Rackerseder +// Definitions by: Basarat Ali Syed +// Christian Rackerseder +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +type SpinnerName = + 'dots' + | 'dots2' + | 'dots3' + | 'dots4' + | 'dots5' + | 'dots6' + | 'dots7' + | 'dots8' + | 'dots9' + | 'dots10' + | 'dots11' + | 'dots12' + | 'line' + | 'line2' + | 'pipe' + | 'simpleDots' + | 'simpleDotsScrolling' + | 'star' + | 'star2' + | 'flip' + | 'hamburger' + | 'growVertical' + | 'growHorizontal' + | 'balloon' + | 'balloon2' + | 'noise' + | 'bounce' + | 'boxBounce' + | 'boxBounce2' + | 'triangle' + | 'arc' + | 'circle' + | 'squareCorners' + | 'circleQuarters' + | 'circleHalves' + | 'squish' + | 'toggle' + | 'toggle2' + | 'toggle3' + | 'toggle4' + | 'toggle5' + | 'toggle6' + | 'toggle7' + | 'toggle8' + | 'toggle9' + | 'toggle10' + | 'toggle11' + | 'toggle12' + | 'toggle13' + | 'arrow' + | 'arrow2' + | 'arrow3' + | 'bouncingBar' + | 'bouncingBall' + | 'smiley' + | 'monkey' + | 'hearts' + | 'clock' + | 'earth' + | 'moon' + | 'runner' + | 'pong' + | 'shark' + | 'dqpb'; + type Color = 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'; + interface Options { text?: string; - spinner?: string | Spinner; + spinner?: SpinnerName | Spinner; color?: Color; interval?: number; stream?: NodeJS.WritableStream; enabled?: boolean; } + +interface PersistOptions { + symbol?: string; + text?: string; +} + interface Spinner { interval?: number; frames: string[]; } -interface Instance { - start(): Instance; - stop(): Instance; - succeed(): Instance; - fail(): Instance; - stopAndPersist(symbol?: string): Instance; - clear(): Instance; - render(): Instance; - frame(): Instance; + +declare class Ora { + start(text?: string): Ora; + + stop(): Ora; + + succeed(text?: string): Ora; + + fail(text?: string): Ora; + + warn(text?: string): Ora; + + info(text?: string): Ora; + + stopAndPersist(options?: PersistOptions | string): Ora; + + clear(): Ora; + + render(): Ora; + + frame(): Ora; + text: string; + color: Color; + + promise(action: PromiseLike, options?: Options | string): Ora; } -declare function ora(options: Options | string): Instance; + +interface oraFactory { + (options?: Options | string): Ora; + + new (options?: Options | string): Ora; +} + +declare const ora: oraFactory; + export = ora; diff --git a/types/ora/ora-tests.ts b/types/ora/ora-tests.ts index b6e2a671dc..ca5db9d70d 100644 --- a/types/ora/ora-tests.ts +++ b/types/ora/ora-tests.ts @@ -1,8 +1,49 @@ -import ora = require('ora'); +import { PassThrough } from 'stream'; +import Ora = require('ora'); -const spinner = ora('Loading unicorns').start(); +const spinner = Ora('Loading unicorns').start(); + +const spinnerNothing = Ora().start(); + +const spinnerNew = new Ora({ + text: 'Loading unicorns', + spinner: 'squish' +}); + +const spinnerNew2 = new Ora({ + stream: new PassThrough(), + text: 'foo', + color: 'cyan', + enabled: true +}); + +spinner.start(); +spinner.start('Test text'); setTimeout(() => { spinner.color = 'yellow'; spinner.text = 'Loading rainbows'; }, 1000); + +setTimeout(() => { + spinner.succeed(); +}, 2000); + +spinner.succeed(); +spinner.succeed('fooed'); +spinner.fail(); +spinner.fail('failed to foo'); +spinner.warn(); +spinner.info(); +spinner.stopAndPersist(); +spinner.stopAndPersist('@'); +spinner.stopAndPersist({text: 'all done'}); +spinner.stopAndPersist({symbol: '@', text: 'all done'}); + +const resolves = Promise.resolve(1); +spinner.promise(resolves, { + stream: new PassThrough(), + text: 'foo', + color: 'blue', + enabled: true +}); diff --git a/types/ora/tsconfig.json b/types/ora/tsconfig.json index 62d5a8b2b7..464459407a 100644 --- a/types/ora/tsconfig.json +++ b/types/ora/tsconfig.json @@ -19,4 +19,4 @@ "index.d.ts", "ora-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/ora/tslint.json b/types/ora/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ora/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ora/v0/index.d.ts b/types/ora/v0/index.d.ts new file mode 100644 index 0000000000..536d858bd7 --- /dev/null +++ b/types/ora/v0/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for ora v0.3.0 +// Project: https://github.com/sindresorhus/ora +// Definitions by: Basarat Ali Syed , Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +type Color = 'black' | 'red' | 'green' | 'yellow' | 'blue' | 'magenta' | 'cyan' | 'white' | 'gray'; +interface Options { + text?: string; + spinner?: string | Spinner; + color?: Color; + interval?: number; + stream?: NodeJS.WritableStream; + enabled?: boolean; +} +interface Spinner { + interval?: number; + frames: string[]; +} +interface Instance { + start(): Instance; + stop(): Instance; + succeed(): Instance; + fail(): Instance; + stopAndPersist(symbol?: string): Instance; + clear(): Instance; + render(): Instance; + frame(): Instance; + text: string; + color: Color; +} +declare function ora(options: Options | string): Instance; +export = ora; diff --git a/types/ora/v0/ora-tests.ts b/types/ora/v0/ora-tests.ts new file mode 100644 index 0000000000..b6e2a671dc --- /dev/null +++ b/types/ora/v0/ora-tests.ts @@ -0,0 +1,8 @@ +import ora = require('ora'); + +const spinner = ora('Loading unicorns').start(); + +setTimeout(() => { + spinner.color = 'yellow'; + spinner.text = 'Loading rainbows'; +}, 1000); diff --git a/types/ora/v0/tsconfig.json b/types/ora/v0/tsconfig.json new file mode 100644 index 0000000000..f611efce94 --- /dev/null +++ b/types/ora/v0/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "ora": [ + "ora/v0" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ora-tests.ts" + ] +} From d06eee332a1ccf37514dd82075c0106372927ac8 Mon Sep 17 00:00:00 2001 From: Maxime Kjaer Date: Fri, 21 Jul 2017 19:03:22 +0200 Subject: [PATCH 0197/1139] Add Rangy Class Applier module to Rangy (#18259) * Add Rangy Class Applier module type definition * Make RangyClassApplier extend the options And allow strings in tagName * Remove reference path in test file This should hopefully Make the Build Green Again * Remove call to unexisting method This was meant for another PR, and I got things a bit mixed up... (I'll submit the other PR that adds the missing rangy-core properties when I have a bit more experience with the whole process of writing type declarations) * Incorporate previous contributor's feedback Thanks for the great feedback :smiley: --- types/rangy/rangy-classapplier.d.ts | 36 ++++++++++++++++++ types/rangy/rangy-tests.ts | 58 ++++++++++++++++++++++++++++- types/rangy/tsconfig.json | 3 +- 3 files changed, 94 insertions(+), 3 deletions(-) create mode 100644 types/rangy/rangy-classapplier.d.ts diff --git a/types/rangy/rangy-classapplier.d.ts b/types/rangy/rangy-classapplier.d.ts new file mode 100644 index 0000000000..bebf581b2e --- /dev/null +++ b/types/rangy/rangy-classapplier.d.ts @@ -0,0 +1,36 @@ +// Type definitions for Rangy Class Applier module +// Project: https://github.com/timdown/rangy +// Definitions by: Maxime Kjaer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface RangyStatic { + createClassApplier(theClass: string, options?: RangyClassApplierOptions, tagNames?: string|string[]): RangyClassApplier; +} + +interface RangyClassApplierOptions { + elementTagName?: string; + elementProperties?: {[property: string]: string}; + elementAttributes?: {[attribute: string]: string}; + ignoreWhiteSpace?: boolean; + applyToEditableOnly?: boolean; + tagNames?: string|string[]; + normalize?: boolean; + onElementCreate?: (element: Element, classApplier: RangyClassApplier) => void; + useExistingElements?: boolean; +} + +interface RangyClassApplier extends RangyClassApplierOptions { + applyToSelection(win?: Window): void; + undoToSelection(win?: Window): void; + isAppliedToSelection(win?: Window): boolean; + toggleSelection(win?: Window): void; + applyToRange(range: RangyRange): void; + undoToRange(range: RangyRange): void; + isAppliedToRange(range: RangyRange): boolean; + toggleRange(range: RangyRange): void; + detach(doc?: Document|Window|HTMLIFrameElement): void; + className: string; + cssClass: string; +} diff --git a/types/rangy/rangy-tests.ts b/types/rangy/rangy-tests.ts index 3b177a46b3..a11eb7d25e 100644 --- a/types/rangy/rangy-tests.ts +++ b/types/rangy/rangy-tests.ts @@ -1,5 +1,3 @@ - - declare function assertAny(a:any):any; declare function assertBoolean(b:boolean):any; declare function assertString(s:string):any; @@ -101,3 +99,59 @@ function testSelection() { selection.restoreCharacterRanges(node, object); assertString(selection.toHtml()); } + + +function testRangyClassApplier() { + function elementCreateFunction(element: Element, classApplier: RangyClassApplier): number { + return 1; + } + + let options: RangyClassApplierOptions = { + elementTagName: 'span', + elementProperties: { + name: 'test-name', + disabled: 'true' + }, + elementAttributes: { + id: 'test-id', + type: 'test-type' + }, + ignoreWhiteSpace: false, + applyToEditableOnly: true, + tagNames: ["span", "b", "strong", "a"], + normalize: false, + onElementCreate: elementCreateFunction, + useExistingElements: false + }; + + let options2: RangyClassApplierOptions = { + tagNames: 'span, b, strong, a' + }; + + let classApplier: RangyClassApplier; + classApplier = rangy.createClassApplier('test', options, ['test1', 'test2']); + classApplier = rangy.createClassApplier('test', options, 'test1, test2'); + + let rangyRange: RangyRange = rangy.createRange(); + + classApplier.applyToSelection(); + classApplier.applyToSelection(window); + classApplier.undoToSelection(); + classApplier.undoToSelection(window); + assertBoolean(classApplier.isAppliedToSelection()); + assertBoolean(classApplier.isAppliedToSelection(window)); + classApplier.toggleSelection(); + classApplier.toggleSelection(window); + classApplier.applyToRange(rangyRange); + classApplier.undoToRange(rangyRange); + assertBoolean(classApplier.isAppliedToRange(rangyRange)); + classApplier.toggleRange(rangyRange); + classApplier.detach(document); + classApplier.detach(window); + classApplier.detach(new HTMLIFrameElement); + classApplier.detach(); + + let className: string = classApplier.className; + className = classApplier.cssClass; + +} diff --git a/types/rangy/tsconfig.json b/types/rangy/tsconfig.json index d803035059..37d0419d65 100644 --- a/types/rangy/tsconfig.json +++ b/types/rangy/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "rangy-classapplier.d.ts", "rangy-tests.ts" ] -} \ No newline at end of file +} From ff94dce8df43ae206c9c5d770a09882fdeb1a009 Mon Sep 17 00:00:00 2001 From: Karol Janyst Date: Sat, 22 Jul 2017 02:05:25 +0900 Subject: [PATCH 0198/1139] Fix problem with generic form inputs props on Field in redux-form (#18276) * Refactor some of the definitions for v7 * Add definitions for formValues decorator * Refactor definitions for Field, Fields, FieldArray, add tests * Add files to tsconfig * Fix immutable version of exports * Clean up the code, change some types * Add improvement to generic components * Remove accidentally added files * Remove conflicting tests file --- types/redux-form/lib/Field.d.ts | 13 +++++++++---- types/redux-form/lib/FieldArray.d.ts | 6 +++--- types/redux-form/lib/Fields.d.ts | 8 ++++---- types/redux-form/redux-form-tests.tsx | 1 + 4 files changed, 17 insertions(+), 11 deletions(-) diff --git a/types/redux-form/lib/Field.d.ts b/types/redux-form/lib/Field.d.ts index 81a3e4a517..b84954657b 100644 --- a/types/redux-form/lib/Field.d.ts +++ b/types/redux-form/lib/Field.d.ts @@ -4,7 +4,10 @@ import { ReactElement, ChangeEvent, DragEvent, - FocusEvent + FocusEvent, + InputHTMLAttributes, + SelectHTMLAttributes, + TextareaHTMLAttributes } from "react"; import { Dispatch } from "redux"; @@ -34,7 +37,7 @@ interface BaseFieldProps

extends Partial { withRef?: boolean; } -export interface GenericField

extends Component { +export interface GenericField

extends Component & P> { dirty: boolean; name: string; pristine: boolean; @@ -42,12 +45,14 @@ export interface GenericField

extends Component { getRenderedComponent(): Component; } -export class Field extends Component implements GenericField { +type GenericFieldHTMLAttributes = InputHTMLAttributes | SelectHTMLAttributes | TextareaHTMLAttributes; + +export class Field

extends Component & P> implements GenericField

{ dirty: boolean; name: string; pristine: boolean; value: any; - getRenderedComponent(): Component; + getRenderedComponent(): Component; } interface WrappedFieldProps { diff --git a/types/redux-form/lib/FieldArray.d.ts b/types/redux-form/lib/FieldArray.d.ts index 5b6e9dc73b..724f1f19c6 100644 --- a/types/redux-form/lib/FieldArray.d.ts +++ b/types/redux-form/lib/FieldArray.d.ts @@ -11,16 +11,16 @@ interface BaseFieldArrayProps

{ rerenderOnEveryChange?: boolean; } -export interface GenericFieldArray extends Component { +export interface GenericFieldArray extends Component & P> { name: string; valid: boolean; getRenderedComponent(): Component & P>; } -export class FieldArray extends Component implements GenericFieldArray { +export class FieldArray

extends Component & P> implements GenericFieldArray { name: string; valid: boolean; - getRenderedComponent(): Component>; + getRenderedComponent(): Component & P>; } interface WrappedFieldArrayProps { diff --git a/types/redux-form/lib/Fields.d.ts b/types/redux-form/lib/Fields.d.ts index 29e06a519a..d3a29dcb13 100644 --- a/types/redux-form/lib/Fields.d.ts +++ b/types/redux-form/lib/Fields.d.ts @@ -10,20 +10,20 @@ interface BaseFieldsProps

{ withRef?: boolean; } -export interface GenericFields

extends Component { +export interface GenericFields

extends Component & P> { dirty: boolean; names: string[]; pristine: boolean; values: { [name: string]: any }; - getRenderedComponent(): Component; + getRenderedComponent(): Component; } -export class Fields extends Component implements GenericFields { +export class Fields

extends Component & P> implements GenericFields

{ dirty: boolean; names: string[]; pristine: boolean; values: { [name: string]: any }; - getRenderedComponent(): Component; + getRenderedComponent(): Component; } interface WrappedFieldsProps { diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 99bc239778..71ff7206da 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -172,6 +172,7 @@ const Test = reduxForm({ From e228e20b8b0f931c517c882dd03efbbee0790b2e Mon Sep 17 00:00:00 2001 From: Ika Date: Sat, 22 Jul 2017 01:30:34 +0800 Subject: [PATCH 0199/1139] feat(prettier): initial commit (#18280) * feat(prettier): initial commit * style(prettier): fix indentation * fix(prettier): fix typo * fix(prettier): replace AST with babylon root node * refactor(prettier): remove unnecessary export --- types/prettier/index.d.ts | 103 +++++++++++++++++++++++++++++++ types/prettier/prettier-tests.ts | 19 ++++++ types/prettier/tsconfig.json | 22 +++++++ types/prettier/tslint.json | 3 + 4 files changed, 147 insertions(+) create mode 100644 types/prettier/index.d.ts create mode 100644 types/prettier/prettier-tests.ts create mode 100644 types/prettier/tsconfig.json create mode 100644 types/prettier/tslint.json diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts new file mode 100644 index 0000000000..e02fd9a587 --- /dev/null +++ b/types/prettier/index.d.ts @@ -0,0 +1,103 @@ +// Type definitions for prettier 1.5 +// Project: https://github.com/prettier/prettier +// Definitions by: Ika +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +import { File } from 'babel-types'; + +export type AST = File; + +export type BuiltInParser = (text: string, options?: any) => AST; +export type BuiltInParserName = 'babylon' | 'flow' | 'typescript' | 'postcss' | 'json' | 'graphql'; + +export type CustomParser = (text: string, parsers: Record, options: Options) => AST; + +export interface Options { + /** + * Specify the line length that the printer will wrap on. + */ + printWidth?: number; + /** + * Specify the number of spaces per indentation-level. + */ + tabWidth?: number; + /** + * Indent lines with tabs instead of spaces + */ + useTabs?: boolean; + /** + * Print semicolons at the ends of statements. + */ + semi?: boolean; + /** + * Use single quotes instead of double quotes. + */ + singleQuote?: boolean; + /** + * Print trailing commas wherever possible. + */ + trailingComma?: 'none' | 'es5' | 'all'; + /** + * Print spaces between brackets in object literals. + */ + bracketSpacing?: boolean; + /** + * Put the `>` of a multi-line JSX element at the end of the last line instead of being alone on the next line. + */ + jsxBracketSameLine?: boolean; + /** + * Format only a segment of a file. + */ + rangeStart?: number; + /** + * Format only a segment of a file. + */ + rangeEnd?: number; + /** + * Specify which parser to use. + */ + parser?: BuiltInParserName | CustomParser; + /** + * Specify the input filepath. This will be used to do parser inference. + */ + filepath?: string; +} + +export interface CursorOptions extends Options { + /** + * Specify where the cursor is. + */ + cursorOffset: number; + rangeStart?: never; + rangeEnd?: never; +} + +export interface CursorResult { + formatted: string; + cursorOffset: number; +} + +/** + * `format` is used to format text using Prettier. [Options](https://github.com/prettier/prettier#options) may be provided to override the defaults. + */ +export function format(source: string, options?: Options): string; + +/** + * `check` checks to see if the file has been formatted with Prettier given those options and returns a `Boolean`. + * This is similar to the `--list-different` parameter in the CLI and is useful for running Prettier in CI scenarios. + */ +export function check(source: string, options?: Options): boolean; + +/** + * `formatWithCursor` both formats the code, and translates a cursor position from unformatted code to formatted code. + * This is useful for editor integrations, to prevent the cursor from moving when code is formatted. + * + * The `cursorOffset` option should be provided, to specify where the cursor is. This option cannot be used with `rangeStart` and `rangeEnd`. + */ +export function formatWithCursor(source: string, options: CursorOptions): CursorResult; + +/** + * `version` field in `package.json` + */ +export const version: string; diff --git a/types/prettier/prettier-tests.ts b/types/prettier/prettier-tests.ts new file mode 100644 index 0000000000..d50cc47c98 --- /dev/null +++ b/types/prettier/prettier-tests.ts @@ -0,0 +1,19 @@ +import * as prettier from 'prettier'; +import { ExpressionStatement, CallExpression, Identifier } from 'babel-types'; + +const formatted = prettier.format("foo ( );", { semi: false }); + +const isFormatted = prettier.check("foo ( );", { semi: false }); + +const result = prettier.formatWithCursor(" 1", { cursorOffset: 2 }); + +const customFormatted = prettier.format("lodash ( )", { + parser(text, { babylon }) { + const ast = babylon(text); + const statement = ast.program.body[0] as ExpressionStatement; + const expression = statement.expression as CallExpression; + const identifier = expression.callee as Identifier; + identifier.name = "_"; + return ast; + } +}); diff --git a/types/prettier/tsconfig.json b/types/prettier/tsconfig.json new file mode 100644 index 0000000000..5a6c388e91 --- /dev/null +++ b/types/prettier/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "prettier-tests.ts" + ] +} diff --git a/types/prettier/tslint.json b/types/prettier/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/prettier/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 0e7282527982f8ab5217d48b49b6118ab94914a4 Mon Sep 17 00:00:00 2001 From: Sean Tan Date: Sat, 22 Jul 2017 01:40:27 +0800 Subject: [PATCH 0200/1139] Add support for use_index in pouchdb-find 6.3.4 (#18164) --- types/pouchdb-find/index.d.ts | 5 ++++- types/pouchdb-find/pouchdb-find-tests.ts | 8 +++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/types/pouchdb-find/index.d.ts b/types/pouchdb-find/index.d.ts index f598b5311d..d45b8c40bc 100644 --- a/types/pouchdb-find/index.d.ts +++ b/types/pouchdb-find/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for pouchdb-find 0.10 +// Type definitions for pouchdb-find 6.3 // Project: https://pouchdb.com/ // Definitions by: Jakub Navratil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -96,6 +96,9 @@ declare namespace PouchDB { /** Number of docs to skip before returning. */ skip?: number; + + /** Set which index to use for the query. It can be “design-doc-name” or “[‘design-doc-name’, ‘name’]”. */ + use_index?: string | [string, string]; } interface FindResponse { diff --git a/types/pouchdb-find/pouchdb-find-tests.ts b/types/pouchdb-find/pouchdb-find-tests.ts index 411b6c1b00..9b0eb0f01d 100644 --- a/types/pouchdb-find/pouchdb-find-tests.ts +++ b/types/pouchdb-find/pouchdb-find-tests.ts @@ -6,7 +6,13 @@ function testFind() { fields: ['fieldName'], sort: ['fieldName'], limit: 1, - skip: 1 + skip: 1, + use_index: 'ddocName' + }); + + db.find({ + selector: {}, + use_index: ['ddocName', 'name'] }); db.find({ From 0cdbd800951024acaeaba85b8c8aaaccf937f74c Mon Sep 17 00:00:00 2001 From: Petr Kosikhin Date: Sat, 22 Jul 2017 04:13:20 +0300 Subject: [PATCH 0201/1139] [react-router-redux] update to use redux 3.7.2 AnyAction to allow ts 2.4 usage (#18071) * update to use redux 3.7.2 anyaction pattern allowing ts 2.4 upgrade * move away from anyaction concept for router action and location change action. use redux reducer generic to desribe routerReducer --- types/react-router-redux/index.d.ts | 10 +++++----- types/react-router-redux/package.json | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/react-router-redux/index.d.ts b/types/react-router-redux/index.d.ts index cf7a6cc410..3af56972e3 100644 --- a/types/react-router-redux/index.d.ts +++ b/types/react-router-redux/index.d.ts @@ -7,8 +7,8 @@ import { Store, Dispatch, - Action, - Middleware + Middleware, + Reducer } from 'redux'; import { History, @@ -31,7 +31,7 @@ export interface RouterState { location: Location | null; } -export function routerReducer(state?: RouterState, action?: RouterAction): RouterState; +export const routerReducer: Reducer; export const CALL_HISTORY_METHOD: string; @@ -54,12 +54,12 @@ export interface LocationActionPayload { args?: any[]; } -export interface RouterAction extends Action { +export interface RouterAction { type: typeof CALL_HISTORY_METHOD; payload: LocationActionPayload; } -export interface LocationChangeAction extends Action { +export interface LocationChangeAction { type: typeof LOCATION_CHANGE; payload: Location & { props?: { diff --git a/types/react-router-redux/package.json b/types/react-router-redux/package.json index 36ce503807..e536fb50eb 100644 --- a/types/react-router-redux/package.json +++ b/types/react-router-redux/package.json @@ -1,5 +1,5 @@ { "dependencies": { - "redux": "^3.6.0" + "redux": "^3.7.2" } } From cad18fc7adb11cf422ccbb2682f8b69afc0b40e5 Mon Sep 17 00:00:00 2001 From: AJ Richardson Date: Fri, 21 Jul 2017 22:00:07 -0400 Subject: [PATCH 0202/1139] lodash: fix issues with null/undefined parameters (#18120) --- types/lodash/index.d.ts | 33 ++++++++++------- types/lodash/lodash-tests.ts | 71 +++++++++++++++++++++--------------- 2 files changed, 60 insertions(+), 44 deletions(-) diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index a55cb6106c..2c996d99be 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -17083,12 +17083,12 @@ declare namespace _ { */ omit( - object: T, + object: T | null | undefined, ...predicate: Array> ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitObjectWrapperBase { /** * @see _.omit */ @@ -17097,7 +17097,7 @@ declare namespace _ { ): LoDashImplicitObjectWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitObjectWrapperBase { /** * @see _.omit */ @@ -17127,12 +17127,12 @@ declare namespace _ { * // => { 'b': '2' } */ omitBy( - object: T, + object: T | null | undefined, predicate: ObjectIterator ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitObjectWrapperBase { /** * @see _.omitBy */ @@ -17141,7 +17141,7 @@ declare namespace _ { ): LoDashImplicitObjectWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitObjectWrapperBase { /** * @see _.omitBy */ @@ -17170,12 +17170,12 @@ declare namespace _ { * // => { 'a': 1, 'c': 3 } */ pick( - object: T, + object: T | null | undefined, ...predicate: Array> ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitObjectWrapperBase { /** * @see _.pick */ @@ -17184,7 +17184,7 @@ declare namespace _ { ): LoDashImplicitObjectWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitObjectWrapperBase { /** * @see _.pick */ @@ -17213,12 +17213,12 @@ declare namespace _ { * // => { 'a': 1, 'c': 3 } */ pickBy( - object: T, + object: T | null | undefined, predicate?: ObjectIterator ): TResult; } - interface LoDashImplicitObjectWrapper { + interface LoDashImplicitObjectWrapperBase { /** * @see _.pickBy */ @@ -17227,7 +17227,7 @@ declare namespace _ { ): LoDashImplicitObjectWrapper; } - interface LoDashExplicitObjectWrapper { + interface LoDashExplicitObjectWrapperBase { /** * @see _.pickBy */ @@ -18909,7 +18909,12 @@ declare namespace _ { * @param value Any value. * @return Returns value. */ - identity(value?: T): T; + identity(value: T): T; + + /** + * @see _.identity + */ + identity(): undefined; } interface LoDashImplicitWrapper { @@ -19969,7 +19974,7 @@ declare namespace _ { type MemoVoidDictionaryIterator = (acc: TResult, curr: T, key: string, dict: Dictionary) => void; /** Common interface between Arrays and jQuery objects */ - type List = ArrayLike + type List = ArrayLike; interface Dictionary { [index: string]: T; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 8b8a27e97a..d56d5e45d6 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -10375,109 +10375,114 @@ namespace TestMergeWith { // _.omit namespace TestOmit { + let obj: {} | null | undefined = any; let predicate: (element: any, key: string, collection: any) => boolean; { let result: TResult; - result = _.omit({}, 'a'); - result = _.omit({}, 0, 'a'); - result = _.omit({}, true, 0, 'a'); - result = _.omit({}, ['b', 1, false], true, 0, 'a'); + result = _.omit(obj, 'a'); + result = _.omit(obj, 0, 'a'); + result = _.omit(obj, true, 0, 'a'); + result = _.omit(obj, ['b', 1, false], true, 0, 'a'); } { let result: _.LoDashImplicitObjectWrapper; - result = _({}).omit('a'); - result = _({}).omit(0, 'a'); - result = _({}).omit(true, 0, 'a'); - result = _({}).omit(['b', 1, false], true, 0, 'a'); + result = _(obj).omit('a'); + result = _(obj).omit(0, 'a'); + result = _(obj).omit(true, 0, 'a'); + result = _(obj).omit(['b', 1, false], true, 0, 'a'); } { let result: _.LoDashExplicitObjectWrapper; - result = _({}).chain().omit('a'); - result = _({}).chain().omit(0, 'a'); - result = _({}).chain().omit(true, 0, 'a'); - result = _({}).chain().omit(['b', 1, false], true, 0, 'a'); + result = _(obj).chain().omit('a'); + result = _(obj).chain().omit(0, 'a'); + result = _(obj).chain().omit(true, 0, 'a'); + result = _(obj).chain().omit(['b', 1, false], true, 0, 'a'); } } // _.omitBy namespace TestOmitBy { + let obj: {} | null | undefined = any; let predicate = (element: any, key: string, collection: any) => true; { let result: TResult; - result = _.omitBy({}, predicate); + result = _.omitBy(obj, predicate); } { let result: _.LoDashImplicitObjectWrapper; - result = _({}).omitBy(predicate); + result = _(obj).omitBy(predicate); } { let result: _.LoDashExplicitObjectWrapper; - result = _({}).chain().omitBy(predicate); + result = _(obj).chain().omitBy(predicate); } } // _.pick namespace TestPick { + let obj: {} | null | undefined = any; + { let result: TResult; - result = _.pick({}, 'a'); - result = _.pick({}, 0, 'a'); - result = _.pick({}, true, 0, 'a'); - result = _.pick({}, ['b', 1, false], true, 0, 'a'); + result = _.pick(obj, 'a'); + result = _.pick(obj, 0, 'a'); + result = _.pick(obj, true, 0, 'a'); + result = _.pick(obj, ['b', 1, false], true, 0, 'a'); } { let result: _.LoDashImplicitObjectWrapper; - result = _({}).pick('a'); - result = _({}).pick(0, 'a'); - result = _({}).pick(true, 0, 'a'); - result = _({}).pick(['b', 1, false], true, 0, 'a'); + result = _(obj).pick('a'); + result = _(obj).pick(0, 'a'); + result = _(obj).pick(true, 0, 'a'); + result = _(obj).pick(['b', 1, false], true, 0, 'a'); } { let result: _.LoDashExplicitObjectWrapper; - result = _({}).chain().pick('a'); - result = _({}).chain().pick(0, 'a'); - result = _({}).chain().pick(true, 0, 'a'); - result = _({}).chain().pick(['b', 1, false], true, 0, 'a'); + result = _(obj).chain().pick('a'); + result = _(obj).chain().pick(0, 'a'); + result = _(obj).chain().pick(true, 0, 'a'); + result = _(obj).chain().pick(['b', 1, false], true, 0, 'a'); } } // _.pickBy namespace TestPickBy { + let obj: {} | null | undefined = any; let predicate = (element: any, key: string, collection: any) => true; { let result: TResult; - result = _.pickBy({}, predicate); + result = _.pickBy(obj, predicate); } { let result: _.LoDashImplicitObjectWrapper; - result = _({}).pickBy(predicate); + result = _(obj).pickBy(predicate); } { let result: _.LoDashExplicitObjectWrapper; - result = _({}).chain().pickBy(predicate); + result = _(obj).chain().pickBy(predicate); } } @@ -11948,6 +11953,12 @@ namespace TestIdentity { result = _({a: 42}).chain().identity(); } + + { + let input: {} | null | undefined = any; + _.identity(input); // $ExpectType {} | null | undefined + _.identity(); // $ExpectType undefined + } } // _.iteratee From 01764b65dafff52df5aa72519563e2349acdd300 Mon Sep 17 00:00:00 2001 From: HAMPLENI Date: Fri, 21 Jul 2017 22:00:35 -0400 Subject: [PATCH 0203/1139] Adding useNativeDriver to EventConfig (#18302) The AnimatedEvent class's constructor takes in a config parameter of type EventConfig. This config object is passed to shouldUseNativeDriver, which only returns something other than false if useNativeDriver is ever set. A case when useNativeDriver is set to true is when Animated.Event is used for an Animated.ScrollView's onScroll prop. https://facebook.github.io/react-native/blog/2017/02/14/using-native-driver-for-animated.html --- types/react-native/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index e8e9eca55c..4b9ef8c075 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -8057,7 +8057,8 @@ export namespace Animated { type Mapping = { [key: string]: Mapping } | AnimatedValue; interface EventConfig { - listener?: ValueListenerCallback + listener?: ValueListenerCallback; + useNativeDriver?: boolean; } /** From 29fc3e073559cb4a1b7a56601ca81536d00f308e Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sat, 22 Jul 2017 04:01:23 +0200 Subject: [PATCH 0204/1139] [p-queue] introduce typings (#18303) --- types/p-queue/index.d.ts | 50 ++++++++++++++++++++++++++++++++++ types/p-queue/p-queue-tests.ts | 42 ++++++++++++++++++++++++++++ types/p-queue/tsconfig.json | 22 +++++++++++++++ types/p-queue/tslint.json | 1 + 4 files changed, 115 insertions(+) create mode 100644 types/p-queue/index.d.ts create mode 100644 types/p-queue/p-queue-tests.ts create mode 100644 types/p-queue/tsconfig.json create mode 100644 types/p-queue/tslint.json diff --git a/types/p-queue/index.d.ts b/types/p-queue/index.d.ts new file mode 100644 index 0000000000..3cc6acef53 --- /dev/null +++ b/types/p-queue/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for p-queue 1.1 +// Project: https://github.com/sindresorhus/p-queue#readme +// Definitions by: BendingBender +// Evan Shortiss +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = PQueue; + +declare class PQueue { + size: number; + pending: number; + + constructor(opts?: PQueue.Options); + + add(fn: PQueue.Task, opts?: O): Promise; + + onEmpty(): Promise; + + clear(): void; +} + +declare namespace PQueue { + interface QueueAddOptions { + [key: string]: any; + } + + interface QueueClassConstructor { + new(): QueueClass; + } + + interface QueueClass { + size: number; + + enqueue(run: () => void, options?: O): void; + + dequeue(): (() => void) | undefined; + } + + interface Options { + queueClass?: QueueClassConstructor; + concurrency?: number; + } + + interface DefaultAddOptions { + priority?: number; + } + + type Task = () => Promise; +} diff --git a/types/p-queue/p-queue-tests.ts b/types/p-queue/p-queue-tests.ts new file mode 100644 index 0000000000..6a63e9e607 --- /dev/null +++ b/types/p-queue/p-queue-tests.ts @@ -0,0 +1,42 @@ +import PQueue = require('p-queue'); + +const queue = new PQueue({concurrency: 1}); + +queue.add(() => Promise.resolve('sindresorhus.com')).then((sindre) => { + const str: string = sindre; +}); + +Promise.resolve((): Promise => Promise.resolve('unicorn')) + .then(task => queue.add(task, {priority: 5})) + .then(unicorn => { + const str: string = unicorn; + }); + +queue.onEmpty().then(() => { +}); +queue.clear(); + +let num: number; +num = queue.size; +num = queue.pending; + +class QueueClass implements PQueue.QueueClass<{ any: string }> { + private queue: Array<() => void>; + + size = 0; + + constructor() { + this.queue = []; + } + + enqueue(run: () => void, options: { any: string }) { + this.queue.push(run); + } + + dequeue() { + return this.queue.shift(); + } +} + +const queue2 = new PQueue({queueClass: QueueClass}); +queue2.add(() => Promise.resolve(), {any: 'hi'}); diff --git a/types/p-queue/tsconfig.json b/types/p-queue/tsconfig.json new file mode 100644 index 0000000000..6fd210c82f --- /dev/null +++ b/types/p-queue/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "p-queue-tests.ts" + ] +} diff --git a/types/p-queue/tslint.json b/types/p-queue/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-queue/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 1de704cfe3b79b59e65c210a864318bd6d725c20 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sat, 22 Jul 2017 04:14:12 +0200 Subject: [PATCH 0205/1139] [color-string] introduce typings (#18298) --- types/color-string/color-string-tests.ts | 38 ++++++++++++++++++++++++ types/color-string/index.d.ts | 31 +++++++++++++++++++ types/color-string/tsconfig.json | 22 ++++++++++++++ types/color-string/tslint.json | 1 + 4 files changed, 92 insertions(+) create mode 100644 types/color-string/color-string-tests.ts create mode 100644 types/color-string/index.d.ts create mode 100644 types/color-string/tsconfig.json create mode 100644 types/color-string/tslint.json diff --git a/types/color-string/color-string-tests.ts b/types/color-string/color-string-tests.ts new file mode 100644 index 0000000000..3f084fbc25 --- /dev/null +++ b/types/color-string/color-string-tests.ts @@ -0,0 +1,38 @@ +import * as colorString from 'color-string'; + +let colorDescriptor: colorString.ColorDescriptor | null; +colorDescriptor = colorString.get('#FFF'); +colorDescriptor = colorString.get('#FFFA'); +colorDescriptor = colorString.get('#FFFFFFAA'); +colorDescriptor = colorString.get('hsl(360, 100%, 50%)'); +colorDescriptor = colorString.get('hwb(60, 3%, 60%)'); + +let color: colorString.Color | null; +color = colorString.get.rgb('#FFF'); +color = colorString.get.rgb('blue'); +color = colorString.get.rgb('rgba(200, 60, 60, 0.3)'); +color = colorString.get.rgb('rgb(200, 200, 200)'); + +color = colorString.get.hsl('hsl(360, 100%, 50%)'); +color = colorString.get.hsl('hsla(360, 60%, 50%, 0.4)'); +color = colorString.get.hwb('hwb(60, 3%, 60%)'); + +color = colorString.get.hwb('hwb(60, 3%, 60%, 0.6)'); + +color = colorString.get.rgb('invalid color string'); + +let stringifiedColor: string; +stringifiedColor = colorString.to.hex([255, 255, 255]); +stringifiedColor = colorString.to.hex([0, 0, 255, 0.4]); +stringifiedColor = colorString.to.hex([0, 0, 255], 0.4); +stringifiedColor = colorString.to.rgb([255, 255, 255]); +stringifiedColor = colorString.to.rgb([0, 0, 255, 0.4]); +stringifiedColor = colorString.to.rgb([0, 0, 255], 0.4); +stringifiedColor = colorString.to.rgb.percent([0, 0, 255]); +stringifiedColor = colorString.to.keyword([255, 255, 0]); +stringifiedColor = colorString.to.hsl([360, 100, 100]); +stringifiedColor = colorString.to.hwb([50, 3, 15]); + +stringifiedColor = colorString.to.rgb(0, [0, 255], 0.4); +stringifiedColor = colorString.to.rgb([0, 0], [255], 0.4); +stringifiedColor = colorString.to.rgb([0], 0, [255, 0.4]); diff --git a/types/color-string/index.d.ts b/types/color-string/index.d.ts new file mode 100644 index 0000000000..4eda883297 --- /dev/null +++ b/types/color-string/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for color-string 1.5 +// Project: https://github.com/qix-/color-string#readme +// Definitions by: BendingBender +// Dan Marshall +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Color = [number, number, number, number]; + +export interface ColorDescriptor { + model: 'rgb' | 'hsl' | 'hwb'; + value: Color; +} + +export function get(colorString: string): ColorDescriptor | null; + +export namespace get { + function hsl(colorString: string): Color | null; + function hwb(colorString: string): Color | null; + function rgb(colorString: string): Color | null; +} + +export namespace to { + function hex(...args: Array): string; + function rgb(...args: Array): string; + namespace rgb { + function percent(...args: Array): string; + } + function keyword(...args: Array): string; + function hsl(...args: Array): string; + function hwb(...args: Array): string; +} diff --git a/types/color-string/tsconfig.json b/types/color-string/tsconfig.json new file mode 100644 index 0000000000..bf5a829c6e --- /dev/null +++ b/types/color-string/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "color-string-tests.ts" + ] +} diff --git a/types/color-string/tslint.json b/types/color-string/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/color-string/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 4d9811d69d524cf902229864b986c13042fc0120 Mon Sep 17 00:00:00 2001 From: Jeffery Grajkowski Date: Fri, 21 Jul 2017 19:17:39 -0700 Subject: [PATCH 0206/1139] Update imap-simple to v3.1.0. (#18301) * Update imap-simple to v3.1.0. * Fix compilation for TS 2.0 --- types/imap-simple/imap-simple-tests.ts | 18 ++++++++++++++++++ types/imap-simple/index.d.ts | 25 ++++++++++++++++++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/types/imap-simple/imap-simple-tests.ts b/types/imap-simple/imap-simple-tests.ts index 39236023d5..9161ebb832 100644 --- a/types/imap-simple/imap-simple-tests.ts +++ b/types/imap-simple/imap-simple-tests.ts @@ -81,3 +81,21 @@ imaps.connect(config).then(function (connection) { // { filename: "pay-stub.pdf", data: Buffer() } ] }); }); + +imaps.connect({ + imap: config.imap, + onmail: function (numNewMail) { + //... + }, + onexpunge: function (seqno) { + //... + }, + onupdate: function (seqno, info) { + //... + } +}).then(function (connection) { + connection.on("error", err => { + console.error("imap socket error", err); + }) +}); + diff --git a/types/imap-simple/index.d.ts b/types/imap-simple/index.d.ts index 765c8a5f0a..9f851ae21b 100644 --- a/types/imap-simple/index.d.ts +++ b/types/imap-simple/index.d.ts @@ -1,8 +1,10 @@ -// Type definitions for imap-simple v1.6.3 +// Type definitions for imap-simple v3.1.0 // Project: https://github.com/chadxz/imap-simple // Definitions by: Jeffery Grajkowski // Definitions: https://github.com/psnider/DefinitelyTyped/imap-simple +/// + import Imap = require("imap"); export interface ImapSimpleOptions { @@ -11,6 +13,15 @@ export interface ImapSimpleOptions { /** Time in milliseconds to wait before giving up on a connection attempt. (Deprecated: please use options.imap.authTimeout instead) */ connectTimeout?: number; + + /** Server event emitted when new mail arrives in the currently open mailbox. */ + onmail?: (numNewMail: number) => void; + + /** Server event emitted when a message was expunged externally. seqno is the sequence number (instead of the unique UID) of the message that was expunged. If you are caching sequence numbers, all sequence numbers higher than this value MUST be decremented by 1 in order to stay synchronized with the server and to keep correct continuity. */ + onexpunge?: (seqno: number) => void; + + /** Server event emitted when message metadata (e.g. flags) changes externally. */ + onupdate?: (seqno: number, info: any) => void; } export interface MessageBodyPart extends Imap.ImapMessageBodyInfo { @@ -21,9 +32,10 @@ export interface MessageBodyPart extends Imap.ImapMessageBodyInfo { export interface Message { attributes: Imap.ImapMessageAttributes; parts: MessageBodyPart[]; + seqno: number; } -export class ImapSimple { +export class ImapSimple extends NodeJS.EventEmitter { constructor(imap: Imap); /** Open a mailbox, calling the provided callback with signature (err, boxName), or resolves the returned promise with boxName. */ @@ -48,6 +60,14 @@ export class ImapSimple { /** Moves the specified message(s) in the currently open mailbox to another mailbox. source corresponds to a node-imap MessageSource which specifies the messages to be moved. When completed, either calls the provided callback with signature (err), or resolves the returned promise. */ moveMessage(source: string | string[], boxName: string, callback: (err: Error) => void): void; moveMessage(source: string | string[], boxName: string): Promise; + + /** Adds the provided flag(s) to the specified message(s). uid is the uid of the message you want to add the flag to or an array of uids. flag is either a string or array of strings indicating the flags to add. */ + addFlags(source: string | string[], flag: string | string[], callback: (err: Error) => void): void; + addFlags(source: string | string[], flag: string | string[]): Promise; + + /** Removes the provided flag(s) from the specified message(s). uid is the uid of the message you want to remove the flag from or an array of uids. flag is either a string or array of strings indicating the flags to remove. */ + delFlags(source: string | string[], flag: string | string[], callback: (err: Error) => void): void; + delFlags(source: string | string[], flag: string | string[]): Promise; } export namespace errors { @@ -58,7 +78,6 @@ export namespace errors { } } - /** Main entry point. Connect to an Imap server. */ export function connect(options: ImapSimpleOptions, callback: (err: Error, connection: ImapSimple) => void): void; export function connect(options: ImapSimpleOptions): Promise; From cc903d089f900eabf428192adcb1514cf21d8a9c Mon Sep 17 00:00:00 2001 From: Mohsen Azimi Date: Fri, 21 Jul 2017 19:18:30 -0700 Subject: [PATCH 0207/1139] Some improvements to webpack configuration (#18118) * Some improvements to webpack configuration `"name"` property schema: https://github.com/webpack/webpack/blob/master/schemas/webpackOptionsSchema.json#L822-L825 * Update index.d.ts * Update index.d.ts * Update index.d.ts * Update index.d.ts --- types/webpack/index.d.ts | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index 13b2de85cd..3dd1a08583 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -4,6 +4,7 @@ // Benjamin Lim // Boris Cherny // Tommy Troy Lin +// Mohsen Azimi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -27,6 +28,12 @@ declare function webpack(options: webpack.Configuration[]): webpack.MultiCompile declare namespace webpack { interface Configuration { + /** Name of the configuration. Used when loading multiple configurations. */ + name?: string; + /** + * The base directory (absolute path!) for resolving the `entry` option. + * If `output.pathinfo` is set, the included pathinfo is shortened to this directory. + */ context?: string; entry?: string | string[] | Entry; /** Choose a style of source mapping to enhance the debugging process. These values can affect build and rebuild speed dramatically. */ @@ -52,9 +59,14 @@ declare namespace webpack { *

  • "async-node" Compile for usage in a node.js-like environment (use fs and vm to load chunks async)
  • *
  • "node-webkit" Compile for usage in webkit, uses jsonp chunk loading but also supports builtin node.js modules plus require(“nw.gui”) (experimental)
  • *
  • "atom" Compile for usage in electron (formerly known as atom-shell), supports require for modules necessary to run Electron.
  • + *
  • "electron-renderer" Compile for Electron for renderer process, providing a target using JsonpTemplatePlugin, FunctionModulePlugin + * for browser environments and NodeTargetPlugin and ExternalsPlugin for CommonJS and Electron built-in modules.
  • + *
  • "electron-main" Compile for Electron for main process.
  • + *
  • "atom" Alias for electron-main
  • + *
  • "electron" Alias for electron-main
  • *
      */ - target?: string; + target?: 'web' | 'webworker' | 'node' | 'async-node' | 'node-webkit' | 'atom' | 'electron' | 'electron-renderer' | 'electron-main' | ((compiler?: any) => void); /** Report the first error as a hard error instead of tolerating it. */ bail?: boolean; /** Capture timing information for each module. */ @@ -145,9 +157,12 @@ declare namespace webpack { *
    • "commonjs2" - Export by setting module.exports: module.exports = xxx
    • *
    • "amd" - Export to AMD (optionally named)
    • *
    • "umd" - Export to AMD, CommonJS2 or as property in root
    • + *
    • "window" - Assign to widnow
    • + *
    • "assign" - Assign to a global variable
    • + *
    • "jsonp" - Generate Webpack JSONP module
    • *
    */ - libraryTarget?: string; + libraryTarget?: 'var' | 'this' | 'commonjs' | 'commonjs2' | 'amd' | 'umd' | 'window' | 'assign' | 'jsonp'; /** If output.libraryTarget is set to umd and output.library is set, setting this to true will name the AMD module. */ umdNamedDefine?: boolean; /** Prefixes every line of the source in the bundle with this string. */ From 045b2eace84c827e09deb06abb586079ad85801c Mon Sep 17 00:00:00 2001 From: Andrew Throener Date: Fri, 21 Jul 2017 22:28:56 -0500 Subject: [PATCH 0208/1139] (paypal-rest-sdk): Initial Type commit (#18296) Update Update Update Update Update remove package.json Review 1 --- types/paypal-rest-sdk/index.d.ts | 748 +++++++++++++++++ .../paypal-rest-sdk/paypal-rest-sdk-tests.ts | 759 ++++++++++++++++++ types/paypal-rest-sdk/tsconfig.json | 22 + types/paypal-rest-sdk/tslint.json | 1 + 4 files changed, 1530 insertions(+) create mode 100644 types/paypal-rest-sdk/index.d.ts create mode 100644 types/paypal-rest-sdk/paypal-rest-sdk-tests.ts create mode 100644 types/paypal-rest-sdk/tsconfig.json create mode 100644 types/paypal-rest-sdk/tslint.json diff --git a/types/paypal-rest-sdk/index.d.ts b/types/paypal-rest-sdk/index.d.ts new file mode 100644 index 0000000000..e5609d0b70 --- /dev/null +++ b/types/paypal-rest-sdk/index.d.ts @@ -0,0 +1,748 @@ +// Type definitions for paypal-rest-sdk 1.7 +// Project: https://github.com/paypal/PayPal-node-SDK +// Definitions by: Andrew Throener +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import http = require('http'); + +export function configure(opts: ConfigureOptions): string; + +/*~ You can declare types that are available via importing the module */ + +export interface PayPalError { + readonly name: string; + readonly message: string; + readonly details: ErrorDetails[]; + readonly information_link: string; + readonly debug_id: string; +} + +export type CallbackFunction = ( err: SDKError, response: T) => any; + +export interface SDKError { + httpStatusCode: number; + message: string; + response: PayPalError; + response_stringified?: string; + stack: string; +} +export interface ErrorDetails { + readonly field: string; + readonly issue: string; +} + +export interface Address { + line1: string; + line2?: string; + city: string; + country_code: string; + postal_code: string; + state: string; + phone?: string; + readonly normalization_status?: string; + type?: string; + recipient_name?: string; +} + +export interface Phone { + country_code: string; + national_number: string; +} + +export interface ConfigureOptions { + client_id: string; + client_secret: string; + mode: string; + schema?: string; + host?: string; + port?: string; + openid_connect_schema?: string; + openid_connect_host?: string; + openid_connect_port?: string; + authorize_url?: string; + logout_url?: string; + headers?: any; +} + +export interface FraudManagementFiltersDetails { + filter_type: string; + filter_id: string; + name: string; + description: string; +} + +export interface Response { + readonly httpStatusCode: number; + readonly create_time?: string; + readonly count?: number; + readonly total_count?: number; +} + +export interface FilterOptions { + page_size: number; + start_time: string; + end_time: string; +} + +export interface UpdateRequest { + op: string; + path: string; + value: any; +} + +export interface Amount { + currency: string; + total: string; + details?: { + subtotal?: string; + shipping?: string; + tax?: string; + handling_fee?: string; + shipping_discout?: string; + insurance?: string; + gift_wrap?: string; + }; +} +export interface ErrorDetails { + readonly field: string; + readonly issue: string; +} + +export interface Currency { + currency: string; + value: string; +} + +export interface QueryParameters { + count?: number; + start_id?: string; + start_index?: number; + start_time?: string; + end_time?: string; + payee_id?: string; + sort_by?: string; + sort_order?: string; + anchor_type?: string; + page_size?: number; + transaction_id?: string; + event_type?: string; + webhook_id?: string; + page?: number; + total_count_required?: boolean; +} + +export interface Link { + href: string; + method: string; + rel: string; +} + +export interface Transaction { + reference_id?: string; + amount: Amount; + description?: string; + item_list?: { + items: Item[]; + shipping_address?: Address; + shipping_method?: string; + shipping_phone_number?: string; + }; + payee?: Payee; + note_to_payee?: string; + custom?: string; + invoice_number?: string; + purchase_order?: string; + soft_descriptor?: string; + payment_options?: { + allowed_payment_method: string; + }; + notify_url?: string; + order_url?: string; + readonly related_resources?: RelatedResources; +} + +export interface Payee { + email: string; + merchant_id: string; + payee_display_metadata?: { + email?: string; + display_phone?: Phone; + brand_name?: string; + }; +} + +export interface Payment { + readonly id?: string; + intent: string; + payer: { + payment_method: string; + }; + transactions: [ Transaction ]; + readonly state?: string; + experience_profile_id?: string; + note_to_payer?: string; + redirect_urls?: { + return_url?: string; + cancel_url?: string; + }; + readonly failure_reason?: string; + readonly create_time?: string; + readonly update_time?: string; + readonly links?: Link[]; +} + +export interface PaymentResponse extends Payment, Response {} + +export interface Resource { + readonly id: string; + amount: Amount; + readonly payment_mode?: string; + readonly state?: string; + readonly reason_code?: string; + readonly protection_eligibility?: string; + readonly protection_eligibility_type?: string; + readonly fmf_details?: FraudManagementFiltersDetails; + readonly receipt_id?: string; + readonly parent_payment?: string; + readonly processor_response?: any; + readonly create_time?: string; + readonly update_time?: string; + readonly links?: Link[]; +} + +export interface SaleResource extends Resource { + readonly purchase_unit_reference_id?: string; + readonly clearing_time?: string; + readonly payment_hold_status?: string; + readonly payment_hold_reasons?: string[]; + readonly transaction_fee?: Currency; + readonly exchange_rate?: string; + readonly billing_agreement_id?: string; +} + +export interface AuthorizationResource extends Resource { + readonly valid_until: string; + readonly update_time: string; + readonly reference_id?: string; +} + +export interface CaptureResource extends Resource { + is_final_capture?: boolean; + invoice_number?: string; + transaction_fee?: Currency; +} + +export interface RefundResource extends Resource { + reason?: string; + invoice_number?: string; + readonly sale_id?: string; + readonly capture_id?: string; + description?: string; + readonly reason_code?: string; + readonly refund_reason_code?: string; + readonly refund_funding_type?: string; +} + +export interface Item { + currency: string; + name: string; + price: string; + quantity: number; + sku?: string; + description?: string; + tax?: string; + url?: string; +} + +export interface RefundRequest { + amount?: Amount; + description?: string; + refund_source?: string; + reason?: string; + invoice_number?: string; + refund_advice?: boolean; + items?: Item[]; + // TODO: Type this https://developer.paypal.com/docs/api/payments/#definition-payer_info + payer_info?: any; + supplementary_data?: any[]; +} + +export interface RelatedResources { + sale?: SaleResource; + authorization?: AuthorizationResource; + order?: any; + capture?: CaptureResource; + refund?: RefundResource; +} + +export namespace payment { + interface ExecuteRequest { + payer_id: string; + } + interface SaleResponse extends SaleResource, Response {} + interface AuthorizationResponse extends AuthorizationResource, Response {} + interface CaptureResponse extends CaptureResource, Response {} + interface RefundResponse extends RefundResource, Response {} + interface ListResponse extends Response { + payments: Payment[]; + count: number; + next_id: string; + } + function create( + data: Payment, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function execute( + id: string, + data: ExecuteRequest, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function get( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function list( + data: QueryParameters | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function update( + id: string, + data: UpdateRequest[], + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; +} +export namespace notification { + interface NotificationEventType { + readonly description?: string; + name: string; + status?: string; + } + interface EventTypesResponse extends Response { + readonly event_types: NotificationEventType[]; + } + namespace webhook { + interface Webhook { + event_types: NotificationEventType[]; + readonly id?: string; + readonly links?: Link[]; + url: string; + } + interface WebhookListResponse extends Response { + readonly webhooks: Webhook[]; + } + function list( + data: QueryParameters | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function create( + data: Webhook, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function replace( + id: string, + data: UpdateRequest[], + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function del( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function get( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function eventTypes( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + } + namespace webhookEvent { + interface WebhookEvent { + readonly id?: string; + readonly create_time?: string; + readonly resource_type?: string; + readonly event_version?: string; + readonly event_type?: string; + readonly summary?: string; + readonly resource?: any; + } + interface WebhookEventListResponse extends Response { + events: WebhookEvent[]; + } + interface WebhookVerifyResponse { + verification_status: string; + } + function get( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function getAndVerify( + body: WebhookEvent, + cb: CallbackFunction): void; + function list( + data: QueryParameters | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function resend( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function verify( + headers: any, + body: WebhookEvent, + id: string, + cb: CallbackFunction): void; + } + namespace webhookEventType { + function list( + data: QueryParameters | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + } +} + +export namespace authorization { + interface CaptureRequest { + amount?: Amount; + is_final_capture?: boolean; + invoice_number?: string; + } + function get( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function capture( + id: string, + data: CaptureRequest | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function reauthorize( + id: string, data: Amount | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + // TODO: Not sure how to type a function named void.... + // function void(data?: any, config?: http.RequestOptions, cb?: CallbackFunction): void; +} +export namespace capture { + function get( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function refund( + id: string, + data: RefundRequest | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; +} +export namespace invoice { + interface EmailRequest { + subject?: string; + note?: string; + send_to_merchant?: boolean; + send_to_payer?: boolean; + cc_emails?: string[]; + } + interface Invoice { + allow_tip?: boolean; + billing_info?: BillingInfo; + discount?: Cost; + shipping_cost?: ShippingCost; + readonly id?: string; + invoice_date?: string; + items?: InvoiceItem[]; + merchant_info?: Merchant; + readonly metadata?: { + created_date: string; + }; + note?: string; + number?: string; + payment_term?: PaymentTerm; + reference?: string; + shipping_info?: { + address: Address; + business_name?: string; + first_name: string; + last_name: string; + }; + phone?: Phone; + readonly status?: string; + tax_calculated_after_discount?: boolean; + tax_inclusive?: boolean; + template_id?: string; + readonly total_amount?: Currency; + readonly uri?: string; + cc_info?: Participant[]; + custom?: CustomAmount; + allow_partial_payment?: boolean; + minimum_amount_due?: Currency; + terms?: string; + merchant_memo?: string; + logo_url?: string; + readonly payments?: PaymentDetail[]; + readonly refunds?: Detail[]; + readonly payment_summary?: { + paypal: Currency; + other: Currency; + }; + readonly refunded_amount?: { + paypal: Currency; + other: Currency; + }; + readonly paid_amount?: { + paypal: Currency; + other: Currency; + }; + attachments?: FileAttachment[]; + readonly links?: Link[]; + } + interface InvoiceResponse extends Invoice, Response {} + interface FileAttachment { + name: string; + url: string; + } + interface BillingInfo extends Person { + email?: string; + language?: string; + notification_channel?: string; + } + interface InvoiceItem { + name: string; + description?: string; + quantity: number; + unit_price: Currency; + tax?: Tax; + date?: string; + discount?: Cost; + unit_of_measure?: string; + } + interface CustomAmount { + label: string; + amount: Currency; + } + interface ShippingCost { + amount?: Currency; + tax?: Tax; + } + interface Tax extends Cost { + id?: string; + name?: string; + } + interface Cost { + percent?: number; + amount?: Currency; + } + interface PaymentTerm { + term_type?: string; + due_date?: string; + } + interface Person { + email?: string; + first_name?: string; + last_name?: string; + business_name?: string; + phone?: Phone; + website?: string; + address?: Address; + } + interface Merchant extends Person { + tax_id?: string; + fax?: Phone; + additional_info_label?: string; + additional_info?: string; + } + interface Participant extends Person { + email: string; + fax?: Phone; + additional_info?: string; + } + interface Detail { + type: string; + transaction_id: string; + date: string; + note?: string; + amount: Currency; + } + interface PaymentDetail extends Detail { + transaction_type: string; + method: string; + } + interface NumberResponse { + number: string; + } + interface QrResponse { + image: string; + } + interface ListResponse extends Response { + invoices: Invoice[]; + } + interface PayRequest { + date: string; + method: string; + note?: string; + amount: Currency; + } + interface RefundRequest { + date: string; + note?: string; + amount: Currency; + } + interface SearchRequest { + email?: string; + recipient_first_name?: string; + recipient_last_name?: string; + recipient_business_name?: string; + number?: string; + status?: string; + lower_total_amount?: Currency; + upper_total_amount?: Currency; + start_invoice_date?: string; + end_invoice_date?: string; + start_due_date?: string; + end_due_date?: string; + start_payment_date?: string; + end_payment_date?: string; + start_creation_date?: string; + end_creation_date?: string; + page?: number; + page_size?: number; + total_count_required?: boolean; + archived?: boolean; + } + function cancel( + id: string, + data: EmailRequest | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction , + cb?: CallbackFunction): void; + function create( + data: Invoice, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function del( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function deleteExternalPayment( + id: string, + trxid: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function deleteExternalRefund( + id: string, + trxid: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function generateNumber( + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function get( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function list( + data: QueryParameters | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function qrCode( + id: string, + height: number, + width: number, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function recordPayment( + id: string, + data: PayRequest, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function recordRefund( + id: string, + data: RefundRequest, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function remind( + id: string, + data: EmailRequest | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function search( + data: SearchRequest, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function send( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function update( + id: string, + data: Invoice, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; +} +export namespace refund { + function get( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; +} +export namespace sale { + function get( + id: string, + config: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; + function refund( + id: string, + data: RefundRequest | http.RequestOptions | CallbackFunction, + config?: http.RequestOptions | CallbackFunction, + cb?: CallbackFunction): void; +} +// TODO: Strong Typing stops here +export namespace billingAgreement { + function billBalance(id: string, data: any, config?: any, cb?: any): void; + function cancel(id: string, data: any, config?: any, cb?: any): void; + function create(data: any, config: any, cb?: any): void; + function execute(id: string, data: any, config?: any, cb?: any): void; + function get(id: string, config: any, cb?: any): void; + function reactivate(id: string, data: any, config?: any, cb?: any): void; + function searchTransactions(id: string, start_date: any, end_date?: any, config?: any, cb?: any): void; + function setBalance(id: string, data: any, config?: any, cb?: any): void; + function suspend(id: string, data: any, config?: any, cb?: any): void; + function update(id: string, data: any, config?: any, cb?: any): void; +} +export namespace billingPlan { + function activate(id: string, config: any, cb?: any): void; + function create(data: any, config: any, cb?: any): void; + function get(id: string, config: any, cb?: any): void; + function list(data: any, config?: any, cb?: any): void; + function update(id: string, data: any, config: any, cb?: any): void; +} +export namespace invoiceTemplate { + function create(data: any, config: any, cb?: any): void; + // function delete(id: string, config: any, cb?: any): void; + function get(id: string, config: any, cb?: any): void; + function list(data: any, config?: any, cb?: any): void; + function update(id: string, data: any, config: any, cb?: any): void; +} +export namespace order { + function authorize(id: string, data: any, config: any, cb?: any): void; + // function void(id: string, config: any, cb?: any): void; + function get(id: string, config: any, cb?: any): void; + function capture(id: string, data: any, config: any, cb?: any): void; +} +export namespace payout { + function create(data: any, sync_mode: any, config?: any, cb?: any): void; + function get(id: string, config: any, cb?: any): void; +} +export namespace payoutItem { + function cancel(id: string, config: any, cb?: any): void; + function get(id: string, config: any, cb?: any): void; +} +export namespace webProfile { + function create(data: any, config: any, cb?: any): void; + function del(id: string, config: any, cb?: any): void; + function get(id: string, config: any, cb?: any): void; + function list(data: any, config?: any, cb?: any): void; + function replace(id: string, data: any, config: any, cb?: any): void; + function update(id: string, data: any, config: any, cb?: any): void; +} diff --git a/types/paypal-rest-sdk/paypal-rest-sdk-tests.ts b/types/paypal-rest-sdk/paypal-rest-sdk-tests.ts new file mode 100644 index 0000000000..bb1d5539eb --- /dev/null +++ b/types/paypal-rest-sdk/paypal-rest-sdk-tests.ts @@ -0,0 +1,759 @@ +import * as paypal from "paypal-rest-sdk"; + +// Minimum Config +const minConfig: paypal.ConfigureOptions = { + client_id: 'asdf', + client_secret: 'asdf', + mode: 'sandbox', +}; + +// Max Config +const maxConfig: paypal.ConfigureOptions = { + client_id: 'asdf', + client_secret: 'asdf', + mode: 'sandbox', + schema: 'asdf', + host: 'asdf', + port: 'asdf', + openid_connect_schema: 'asdf', + openid_connect_host: 'asdf', + openid_connect_port: 'asdf', + authorize_url: 'asdf', + logout_url: 'asdf', + headers: { + asdf: 'asdf', + } +}; + +// Execute Configure +paypal.configure(maxConfig); + +// Min Payment +const minPayment: paypal.Payment = { + intent: "sale", + payer: { + payment_method: "paypal", + }, + transactions: [ + { + amount: { + total: "30.01", + currency: "USD", + details: { + subtotal: "30.00", + handling_fee: "0.01", + }, + }, + }, + ], +}; + +// Max Payment +const maxPayment: paypal.Payment = { + intent: "sale", + payer: { + payment_method: "paypal", + }, + transactions: [ + { + amount: { + total: "30.01", + currency: "USD", + details: { + subtotal: "30.00", + handling_fee: "0.01", + shipping: 'test', + tax: 'test', + shipping_discout: 'a', + insurance: 'a', + gift_wrap: 'a', + }, + }, + payee: { + email: 'a', + merchant_id: 'a', + payee_display_metadata: { + email: 'a', + display_phone: { + country_code: 'a', + national_number: 'a', + } + } + }, + description: 'asdf', + note_to_payee: 'asdf', + custom: 'asdf', + invoice_number: 'asdf', + purchase_order: 'asdf', + soft_descriptor: 'asdf', + payment_options: { + allowed_payment_method: 'asdf' + }, + item_list: { + items: [{ + sku: 'asdf', + name: 'asdf', + description: 'asdf', + quantity: 2, + price: 'adsf', + currency: 'adsf', + tax: 'asdf', + url: 'asdf' + }], + shipping_address: { + line1: 'asdf', + line2: 'asdf', + city: 'asdf', + country_code: 'asdf', + postal_code: 'asdf', + state: 'asdf', + phone: 'asdf', + type: 'adsf', + recipient_name: 'asdf', + }, + shipping_method: 'adsf', + shipping_phone_number: 'adsf', + }, + notify_url: 'asdf', + order_url: 'asdf', + }, + ], + experience_profile_id: 'test', + note_to_payer: 's', + redirect_urls: { + cancel_url: 'test', + return_url: 'test', + }, + failure_reason: 'test', +}; + +// Create Payment +paypal.payment.create(maxPayment, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.state; +}); + +let request: paypal.payment.ExecuteRequest = { + payer_id: 'test' +}; + +// Execute Payment +paypal.payment.execute('test', request, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.state; +}); + +// Get Payment +paypal.payment.get('test', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.state; +}); + +let paymentList: paypal.QueryParameters = { + page: 2 +}; + +// List Payments +paypal.payment.list(paymentList, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.payments[0].id; + test = response.total_count; +}); + +let updatePayment: paypal.UpdateRequest = { + op: 'asdf', + path: 'asdf', + value: 'asdf', +}; + +// Update Payment +paypal.payment.update('asdf', [updatePayment], (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; +}); + +// List Webhooks +let whList: paypal.QueryParameters = { + transaction_id: 'asdf' +}; +paypal.notification.webhook.list(whList, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.webhooks[0].id; +}); + +// Create Webhooks +let webhook = { name: 'test', url: 'asdf', event_types: [ { name: 'test' } ] }; +paypal.notification.webhook.create(webhook, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.event_types[0].name; +}); + +// Replace Webhook +paypal.notification.webhook.replace('asdf', [{ op: 'string', path: 'asdf', value: 'asdf' }], (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.event_types[0].name; +}); + +// Delete Webhook +paypal.notification.webhook.del('asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.event_types[0].name; +}); + +// Get Webhook +paypal.notification.webhook.get('asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.event_types[0].name; +}); + +// Webhook Event Types +paypal.notification.webhook.eventTypes('asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.event_types[0].name; +}); + +// WebhookEvent Get +paypal.notification.webhookEvent.get('asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.resource; +}); + +let webhookEvent: paypal.notification.webhookEvent.WebhookEvent = { + id: 'etst', + create_time: 'asdf', + resource_type: 'adsf', + event_version: 'asdf', + event_type: 'asdf', + summary: 'asdf', + resource: { + id: 'asdf' + } +}; + +// WebhookEvent Get and Verify +paypal.notification.webhookEvent.getAndVerify(webhookEvent, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.resource; +}); + +// WebhookEvent List +paypal.notification.webhookEvent.list({ transaction_id: 'asdf' }, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.events[0].resource; +}); + +// WebhookEvent Resend +paypal.notification.webhookEvent.resend('id', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.resource; +}); + +// WebhookEvent Resend +paypal.notification.webhookEvent.resend('id', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.resource; +}); + +// WebhookEvent Verify +paypal.notification.webhookEvent.verify({ header: 'asdf' }, webhookEvent, 'id', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.verification_status; +}); + +// WebhookEventType List +paypal.notification.webhookEventType.list((err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.event_types[0].name; +}); + +// Authorization Get +paypal.authorization.get('id', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; +}); + +let captureRequest: paypal.authorization.CaptureRequest = { + is_final_capture: true, +}; +// Authorization Capture +paypal.authorization.capture('id', captureRequest, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; +}); + +// ReAuthorization +paypal.authorization.reauthorize('id', { total: "10", currency: "USD" }, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; +}); + +// Capture Get +paypal.capture.get('id', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; +}); + +let refundRequest: paypal.RefundRequest = { + amount: { + total: "30.00", + currency: "USD" + } +}; + +// Capture Get +paypal.capture.refund('id', refundRequest, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; +}); + +// Min Invoice +let minInvoice: paypal.invoice.Invoice = {}; + +// Max Invoice +let maxInvoice: paypal.invoice.Invoice = { + allow_tip: true, + billing_info: { + email: 'asfd', + language: 'string', + notification_channel: 'string', + }, + discount: { + percent: 2, + amount: { + currency: "USD", + value: "34" + }, + }, + shipping_cost: { + amount: { + currency: "USD", + value: "20", + }, + tax: { + id: 'tst', + name: "asdf", + percent: 20, + amount: { + currency: "USD", + value: "20", + } + } + }, + invoice_date: "asdf", + items: [{ + name: "asdf", + description: "asdf", + quantity: 2, + unit_price: { + currency: "USD", + value: "20", + }, + tax: { + percent: 20, + }, + date: "asdf", + discount: { + percent: 20, + }, + unit_of_measure: 'asdf' + }], + merchant_info: { + email: "asdf", + first_name: "asdf", + last_name: "asdf", + address: { + line1: "asdf", + city: "asdf", + state: "asdf", + postal_code: "adsf", + country_code: "asdf" + }, + business_name: "asdf", + phone: { + country_code: "1", + national_number: "asdf", + }, + website: "asdf", + tax_id: "adsf", + additional_info: "asdf", + additional_info_label: "asdf", + }, + note: 'string', + number: 'string', + payment_term: { + term_type: "asdf", + due_date: "asdf", + }, + reference: 'string', + shipping_info: { + address: { + line1: "asdf", + city: "asdf", + state: "asdf", + postal_code: "adsf", + country_code: "asdf" + }, + business_name: 'asdf', + first_name: "string", + last_name: "string", + }, + phone: { + country_code: "1", + national_number: "asdf", + }, + tax_calculated_after_discount: true, + tax_inclusive: true, + template_id: "string", + cc_info: [ + { + first_name: "asdf", + email: "adsf", + } + ], + custom: { + label: "adsf", + amount: { + currency: "asdf", + value: "adsf" + }, + }, + allow_partial_payment: true, + minimum_amount_due: { + currency: "asdf", + value: "adsf" + }, + terms: "asdf", + merchant_memo: "asdf", + logo_url: "adsf", + attachments: [ + { + name: "adsf", + url: "adsf" + } + ] +}; + +// Invoice Cancel +paypal.invoice.cancel('id', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } +}); + +// Invoice Create +paypal.invoice.create(maxInvoice, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.items ? response.items[0].name : 'asdf'; +}); + +// Invoice Delete +paypal.invoice.del('adsf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.items ? response.items[0].name : 'asdf'; +}); + +// Invoice Delete External Payment +paypal.invoice.deleteExternalPayment('adsf', 'asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } +}); + +// Invoice Delete External Refund +paypal.invoice.deleteExternalRefund('adsf', 'asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } +}); + +// Invoice Delete External Refund +paypal.invoice.generateNumber((err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.number; +}); + +// Invoice Get +paypal.invoice.get('adsf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.items ? response.items[0].name : 'asdf'; +}); + +// Invoice List +paypal.invoice.list((err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.invoices.length > 0 ? response.invoices[0].id : 'asdf'; +}); + +// Invoice Qrcode +paypal.invoice.qrCode('asdf', 1, 3, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.image; +}); + +let recordPayment: paypal.invoice.PayRequest = { + date: "asdf", + method: "asdf", + note: "asdf", + amount: { + currency: "USD", + value: "10.10", + } +}; + +// Invoice Record Payment +paypal.invoice.recordPayment('asdf', recordPayment, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } +}); + +// Invoice Record Refund +paypal.invoice.recordRefund('asdf', recordPayment, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } +}); + +// Invoice Remind +paypal.invoice.remind('asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } +}); + +let invoiceSearch: paypal.invoice.SearchRequest = { + archived: true, + start_creation_date: "asdf", +}; + +// Invoice Search +paypal.invoice.search(invoiceSearch, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.invoices.length > 0 ? response.invoices[0].id : 'asdf'; +}); + +// Invoice Update +paypal.invoice.update('asdf', maxInvoice, (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.items ? response.items[0].name : 'asdf'; +}); + +// Refund Get +paypal.refund.get('asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.capture_id; +}); + +// Sale Get +paypal.sale.get('asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.create_time; +}); + +// Sale Refund +paypal.sale.refund('asdf', (err, response) => { + let test; + if (err) { + test = err.response.debug_id; + test = err.stack; + return; + } + test = response.id; + test = response.refund_reason_code; +}); diff --git a/types/paypal-rest-sdk/tsconfig.json b/types/paypal-rest-sdk/tsconfig.json new file mode 100644 index 0000000000..37d11017e6 --- /dev/null +++ b/types/paypal-rest-sdk/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "paypal-rest-sdk-tests.ts" + ] +} diff --git a/types/paypal-rest-sdk/tslint.json b/types/paypal-rest-sdk/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/paypal-rest-sdk/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c469f9c6062460eb410b3ac1216d42da851e10ee Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sat, 22 Jul 2017 11:09:18 +0200 Subject: [PATCH 0209/1139] [time-span] introduce typings (#18294) * [time-span] introduce typings * [time-span] simplify typings as suggested by review --- types/time-span/index.d.ts | 18 ++++++++++++++++++ types/time-span/time-span-tests.ts | 9 +++++++++ types/time-span/tsconfig.json | 22 ++++++++++++++++++++++ types/time-span/tslint.json | 1 + 4 files changed, 50 insertions(+) create mode 100644 types/time-span/index.d.ts create mode 100644 types/time-span/time-span-tests.ts create mode 100644 types/time-span/tsconfig.json create mode 100644 types/time-span/tslint.json diff --git a/types/time-span/index.d.ts b/types/time-span/index.d.ts new file mode 100644 index 0000000000..327c3fd189 --- /dev/null +++ b/types/time-span/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for time-span 2.0 +// Project: https://github.com/sindresorhus/time-span#readme +// Definitions by: BendingBender +// Mike Dvorscak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace timeSpan { + interface TimeSpanObject { + (): number; + rounded(): number; + sec(): number; + nano(): number; + } +} + +declare function timeSpan(): timeSpan.TimeSpanObject; + +export = timeSpan; diff --git a/types/time-span/time-span-tests.ts b/types/time-span/time-span-tests.ts new file mode 100644 index 0000000000..de5e8dfc53 --- /dev/null +++ b/types/time-span/time-span-tests.ts @@ -0,0 +1,9 @@ +import timeSpan = require('time-span'); + +const end = timeSpan(); + +let endTime: number; +endTime = end(); +endTime = end.rounded(); +endTime = end.sec(); +endTime = end.nano(); diff --git a/types/time-span/tsconfig.json b/types/time-span/tsconfig.json new file mode 100644 index 0000000000..c872de67cd --- /dev/null +++ b/types/time-span/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "time-span-tests.ts" + ] +} diff --git a/types/time-span/tslint.json b/types/time-span/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/time-span/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 42e60e528305fdf3082d04a50f9e830c1ac9d595 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sat, 22 Jul 2017 11:22:57 +0200 Subject: [PATCH 0210/1139] [sparkly] introduce typings (#18291) * [sparkly] introduce typings * [sparkly] restrict input type to allow all types from examples but not more than that --- types/sparkly/index.d.ts | 16 ++++++++++++++++ types/sparkly/sparkly-tests.ts | 7 +++++++ types/sparkly/tsconfig.json | 22 ++++++++++++++++++++++ types/sparkly/tslint.json | 1 + 4 files changed, 46 insertions(+) create mode 100644 types/sparkly/index.d.ts create mode 100644 types/sparkly/sparkly-tests.ts create mode 100644 types/sparkly/tsconfig.json create mode 100644 types/sparkly/tslint.json diff --git a/types/sparkly/index.d.ts b/types/sparkly/index.d.ts new file mode 100644 index 0000000000..3e1e5529a6 --- /dev/null +++ b/types/sparkly/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for sparkly 3.1 +// Project: https://github.com/sindresorhus/sparkly +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = sparkly; + +declare function sparkly(numbers: Array, options?: sparkly.Options): string; + +declare namespace sparkly { + interface Options { + min?: number; + max?: number; + style?: 'fire'; + } +} diff --git a/types/sparkly/sparkly-tests.ts b/types/sparkly/sparkly-tests.ts new file mode 100644 index 0000000000..cd5fa262e0 --- /dev/null +++ b/types/sparkly/sparkly-tests.ts @@ -0,0 +1,7 @@ +import sparkly = require('sparkly'); + +let str: string; +str = sparkly([0, 3, 5, 8, 4, 3, 4, 10]); +str = sparkly([0, 3, 5, '', 4, 3, 4, 10]); +str = sparkly([1, 2, 3, 4, 5], {min: 0, max: 10}); +str = sparkly([1, 2, 3, 4, 5, 6, 7, 8], {style: 'fire'}); diff --git a/types/sparkly/tsconfig.json b/types/sparkly/tsconfig.json new file mode 100644 index 0000000000..f439b0a2e7 --- /dev/null +++ b/types/sparkly/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sparkly-tests.ts" + ] +} diff --git a/types/sparkly/tslint.json b/types/sparkly/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sparkly/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 69c1ab4f365ab13ed971bbb89361f996b37aeae2 Mon Sep 17 00:00:00 2001 From: spielc Date: Sat, 22 Jul 2017 21:04:34 +0200 Subject: [PATCH 0211/1139] Add typings for Reactable 0.14. (#18270) * Add typings for Reactable 0.14. Not complete but the stuff provided by the typings have been tested/used quite extensively by myself during the development of ReactPlayer! * Add two tests (very simple one and a quite sophisticated one which contains all the components i created typings for...) --- types/reactable/index.d.ts | 60 +++++++++++++++++++++ types/reactable/reactable-tests.tsx | 82 +++++++++++++++++++++++++++++ types/reactable/tsconfig.json | 24 +++++++++ types/reactable/tslint.json | 1 + 4 files changed, 167 insertions(+) create mode 100644 types/reactable/index.d.ts create mode 100644 types/reactable/reactable-tests.tsx create mode 100644 types/reactable/tsconfig.json create mode 100644 types/reactable/tslint.json diff --git a/types/reactable/index.d.ts b/types/reactable/index.d.ts new file mode 100644 index 0000000000..4509d421c1 --- /dev/null +++ b/types/reactable/index.d.ts @@ -0,0 +1,60 @@ +// Type definitions for reactable 0.14 +// Project: https://github.com/glittershark/reactable +// Definitions by: Christoph Spielmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from 'react'; + +export interface KeyLabelObject { + key: string; + label: string; +} + +export type ColumnsType = string | KeyLabelObject; + +export type FilterMethodType = (text: string) => void; + +export interface TableComponentProperties { + data?: T[]; + className?: string; + columns?: ColumnsType[]; + id?: string; + sortable?: string[]; + filterable?: string[]; + filterBy?: string; + onFilter?: FilterMethodType; +} + +export interface ThProperties { + column: string; + className?: string; +} + +export interface TrProperties { + data?: T; + className?: string; +} + +export interface TdProperties { + column: string; + value?: any; + data?: any; +} + +export class Table extends React.Component, {}> { +} + +export class Thead extends React.Component<{}, {}> { +} + +export class Th extends React.Component { +} + +export class Tr extends React.Component, {}> { +} + +export class Td extends React.Component { +} + +export class Tfoot extends React.Component<{}, {}> { +} diff --git a/types/reactable/reactable-tests.tsx b/types/reactable/reactable-tests.tsx new file mode 100644 index 0000000000..91d80c27ef --- /dev/null +++ b/types/reactable/reactable-tests.tsx @@ -0,0 +1,82 @@ +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import * as Reactable from "reactable"; + +interface Person { + name: string; + age: number; +} + +type PersonTable = new () => Reactable.Table; +const PersonTable = Reactable.Table as PersonTable; + +type PersonTableHeader = new () => Reactable.Thead; +const PersonTableHeader = Reactable.Thead as PersonTableHeader; + +type PersonTableTh = new () => Reactable.Th; +const PersonTableTh = Reactable.Th as PersonTableTh; + +type PersonRow = new () => Reactable.Tr; +const PersonRow = Reactable.Tr as PersonRow; + +type PersonTableTd = new () => Reactable.Td; +const PersonTableTd = Reactable.Td as PersonTableTd; + +type PersonTableTfoot = new () => Reactable.Tfoot; +const PersonTableTfoot = Reactable.Tfoot as PersonTableTfoot; + +let data = [ + { + name: "Christoph Spielmann", + age: 36 + } +]; + +export class TestComponent extends React.Component<{}, {}> { + render(): JSX.Element { + return ; + } +} + +export class FullblownReactableTestComponent extends React.Component<{}, {}> { + render(): JSX.Element { + let displayedColumns = ["name"]; + // custom table Th-elements + let columns: JSX.Element[] = []; + for (let colName of displayedColumns) { + columns.push( + + {colName} + + ); + } + let rows: JSX.Element[] = []; + for (let d of data) { + let tds: JSX.Element[] = []; + displayedColumns.forEach(col => tds.push( + +

    d[col]

    +
    + )); + rows.push( + + {tds} + + ); + } + return ( + + + {columns} + + {rows} + + + footer cell1 + footer cell2 + + + + ); + } +} diff --git a/types/reactable/tsconfig.json b/types/reactable/tsconfig.json new file mode 100644 index 0000000000..c3300f0e32 --- /dev/null +++ b/types/reactable/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "reactable-tests.tsx" + ] +} diff --git a/types/reactable/tslint.json b/types/reactable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/reactable/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 4cfe41dc6b6b1502340a49f4101f37b0627db3de Mon Sep 17 00:00:00 2001 From: Nick Graham Date: Sat, 22 Jul 2017 14:16:13 -0500 Subject: [PATCH 0212/1139] [material-ui] Adds linting (#18189) * Adds props to GridTile * Adds ts line * Fixes lint array error Array type using 'T[]' is forbidden for non-simple types. Use 'Array' instead. * Fixes lint consecutive blank line error * Fixes whitespace and semicolon lint errors * Fixes lint whitespace error Don't use blank line after '{' * Fixes lint type error Use an interface instead of a type literal * Fixes lint interface error An empty interface is equivalent to `{}`. * Lint: Replaces var with let Do not use 'var' * Lint: Prefer method signature * Lint: Fixes array type Array type using 'T[]' is forbidden for non-simple types. Use 'Array' * Lint: Fixes boolean type Don't use 'Boolean' as a type. Avoid using the `Boolean` type. Did you mean `boolean`? * Lint: Ignore unneccesary exports * Lint : fix errors * Lint: adds missing semi-colons * Lint: Removes spaces * Lint: Ignore no empty interfaces (We could just delete them) * Lint: Ignore "dt-header" (could remove patch number) * Lint: Ignore ban-types so we can use Function * Remove new props that I added * Fixes var -> let over replacement --- types/material-ui/index.d.ts | 249 ++++++++++++------------ types/material-ui/material-ui-tests.tsx | 124 +++--------- types/material-ui/tslint.json | 9 + 3 files changed, 158 insertions(+), 224 deletions(-) create mode 100644 types/material-ui/tslint.json diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 154be283de..6180f193f7 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -128,7 +128,7 @@ declare namespace __MaterialUI { desktopSubheaderHeight?: number; desktopToolbarHeight?: number; } - export var Spacing: Spacing; + export let Spacing: Spacing; interface ThemePalette { primary1Color?: string; @@ -147,7 +147,7 @@ declare namespace __MaterialUI { clockCircleColor?: string; shadowColor?: string; } - export var ThemePalette: ThemePalette; + export let ThemePalette: ThemePalette; interface MuiTheme { spacing?: Spacing; fontFamily?: string; @@ -454,15 +454,15 @@ declare namespace __MaterialUI { snackbar: number; tooltip: number; } - export var zIndex: zIndex; + export let zIndex: zIndex; interface RawTheme { spacing?: Spacing; fontFamily?: string; palette?: ThemePalette; } - var lightBaseTheme: RawTheme; - var darkBaseTheme: RawTheme; + let lightBaseTheme: RawTheme; + let darkBaseTheme: RawTheme; export function muiThemeable(): < TComponent extends React.ComponentClass

    | React.StatelessComponent

    , @@ -483,7 +483,7 @@ declare namespace __MaterialUI { easeOutFunction: string; easeInOutFunction: string; } - export var Transitions: Transitions; + export let Transitions: Transitions; interface Typography { textFullBlack: string; @@ -501,7 +501,7 @@ declare namespace __MaterialUI { fontStyleButtonFontSize: number; } - export var Typography: Typography; + export let Typography: Typography; } interface AppBarProps { @@ -541,14 +541,14 @@ declare namespace __MaterialUI { } interface utils { - getWeekArray: (date: Date, firstDayOfWeek: number) => (Date | null)[][]; - getYear: (date: Date) => number; - setYear: (date: Date, year: number) => Date; - addDays: (date: Date, days: number) => Date; - addMonths: (date: Date, months: number) => Date; - addYears: (date: Date, years: number) => Date; - getFirstDayOfMonth: (date: Date) => Date; - monthDiff: (date1: Date, date2: Date) => number; + getWeekArray(date: Date, firstDayOfWeek: number): Array>; + getYear(date: Date): number; + setYear(date: Date, year: number): Date; + addDays(date: Date, days: number): Date; + addMonths(date: Date, months: number): Date; + addYears(date: Date, years: number): Date; + getFirstDayOfMonth(date: Date): Date; + monthDiff(date1: Date, date2: Date): number; } type corners = 'bottom-left' | 'bottom-right' | 'top-left' | 'top-right'; @@ -564,7 +564,7 @@ declare namespace __MaterialUI { disableFocusRipple?: boolean; errorStyle?: React.CSSProperties; errorText?: React.ReactNode; - filter?: (searchText: string, key: string, item: DataItem) => boolean; + filter?(searchText: string, key: string, item: DataItem): boolean; floatingLabelText?: React.ReactNode; fullWidth?: boolean; hintText?: React.ReactNode; @@ -576,8 +576,8 @@ declare namespace __MaterialUI { onBlur?: React.FocusEventHandler<{}>; onFocus?: React.FocusEventHandler<{}>; onKeyDown?: React.KeyboardEventHandler<{}>; - onNewRequest?: (chosenRequest: DataItem, index: number) => void; - onUpdateInput?: (searchText: string, dataSource: DataItem[]) => void; + onNewRequest?(chosenRequest: DataItem, index: number): void; + onUpdateInput?(searchText: string, dataSource: DataItem[]): void; open?: boolean; openOnFocus?: boolean; popoverProps?: Popover.PopoverProps; @@ -587,14 +587,14 @@ declare namespace __MaterialUI { textFieldStyle?: React.CSSProperties; } export class AutoComplete extends React.Component> { - static noFilter: () => boolean; - static defaultFilter: (searchText: string, key: string) => boolean; - static caseSensitiveFilter: (searchText: string, key: string) => boolean; - static caseInsensitiveFilter: (searchText: string, key: string) => boolean; + static noFilter(): boolean; + static defaultFilter(searchText: string, key: string): boolean; + static caseSensitiveFilter(searchText: string, key: string): boolean; + static caseInsensitiveFilter(searchText: string, key: string): boolean; static levenshteinDistanceFilter(distanceLessThan: number): (searchText: string, key: string) => boolean; - static fuzzyFilter: (searchText: string, key: string) => boolean; + static fuzzyFilter(searchText: string, key: string): boolean; static Item: Menus.MenuItem; static Divider: Divider; } @@ -645,7 +645,7 @@ declare namespace __MaterialUI { keyboardFocused?: boolean; onBlur?: React.FocusEventHandler<{}>; onFocus?: React.FocusEventHandler<{}>; - onKeyboardFocus?: (e: React.FocusEvent<{}>, isKeyboardFocused: boolean) => void; + onKeyboardFocus?(e: React.FocusEvent<{}>, isKeyboardFocused: boolean): void; onKeyDown?: React.KeyboardEventHandler<{}>; onKeyUp?: React.KeyboardEventHandler<{}>; onTouchTap?: TouchTapEventHandler; @@ -679,7 +679,7 @@ declare namespace __MaterialUI { labelPosition?: "before" | "after"; labelStyle?: React.CSSProperties; linkButton?: boolean; - onKeyboardFocus?: (e: React.FocusEvent<{}>, isKeyboardFocused: boolean) => void; + onKeyboardFocus?(e: React.FocusEvent<{}>, isKeyboardFocused: boolean): void; onMouseEnter?: React.MouseEventHandler<{}>; onMouseLeave?: React.MouseEventHandler<{}>; onTouchStart?: React.TouchEventHandler<{}>; @@ -753,7 +753,7 @@ declare namespace __MaterialUI { iconStyle?: React.CSSProperties; onBlur?: React.FocusEventHandler<{}>; onFocus?: React.FocusEventHandler<{}>; - onKeyboardFocus?: (e: React.FocusEvent<{}>, isKeyboardFocused: boolean) => void; + onKeyboardFocus?(e: React.FocusEvent<{}>, isKeyboardFocused: boolean): void; onMouseEnter?: React.MouseEventHandler<{}>; onMouseLeave?: React.MouseEventHandler<{}>; onMouseOut?: React.MouseEventHandler<{}>; @@ -785,7 +785,6 @@ declare namespace __MaterialUI { } namespace Card { - interface CardProps { className?: string; actAsExpander?: boolean; @@ -793,7 +792,7 @@ declare namespace __MaterialUI { expandable?: boolean; expanded?: boolean; initiallyExpanded?: boolean; - onExpandChange?: (isExpanded: boolean) => void; + onExpandChange?(isExpanded: boolean): void; showExpandableButton?: boolean; style?: React.CSSProperties; } @@ -812,7 +811,7 @@ declare namespace __MaterialUI { interface CardExpandableProps { expanded?: boolean; - onExpanding?: (isExpanded: boolean) => void; + onExpanding?(isExpanded: boolean): void; style?: React.CSSProperties; } export class CardExpandable extends React.Component { @@ -902,18 +901,18 @@ declare namespace __MaterialUI { disableYearSelection?: boolean; disabled?: boolean; firstDayOfWeek?: number; - formatDate?: (date: Date) => string; + formatDate?(date: Date): string; locale?: string; maxDate?: Date; minDate?: Date; mode?: "portrait" | "landscape"; okLabel?: React.ReactNode; - onChange?: (e: any, date: Date) => void; // e is always null - onDismiss?: () => void; + onChange?(e: any, date: Date): void; // e is always null + onDismiss?(): void; onFocus?: React.FocusEventHandler<{}>; - onShow?: () => void; + onShow?(): void; onTouchTap?: React.TouchEventHandler<{}>; - shouldDisableDate?: (day: Date) => boolean; + shouldDisableDate?(day: Date): boolean; style?: React.CSSProperties; textFieldStyle?: React.CSSProperties; value?: Date; @@ -933,8 +932,8 @@ declare namespace __MaterialUI { inputStyle?: React.CSSProperties; onBlur?: React.FocusEventHandler<{}>; onKeyDown?: React.KeyboardEventHandler<{}>; - rows?: number, - rowsMax?: number, + rows?: number; + rowsMax?: number; name?: string; type?: string; underlineDisabledStyle?: React.CSSProperties; @@ -963,16 +962,16 @@ declare namespace __MaterialUI { minDate?: Date; mode?: "portrait" | "landscape"; okLabel?: React.ReactNode; - onAccept?: (d: Date) => void; - onDismiss?: () => void; - onShow?: () => void; - shouldDisableDate?: (day: Date) => boolean; + onAccept?(d: Date): void; + onDismiss?(): void; + onShow?(): void; + shouldDisableDate?(day: Date): boolean; style?: React.CSSProperties; utils?: propTypes.utils; } export class DatePickerDialog extends React.Component { - public show(): void; - public dismiss(): void; + show(): void; + dismiss(): void; } } @@ -998,7 +997,7 @@ declare namespace __MaterialUI { contentClassName?: string; contentStyle?: React.CSSProperties; modal?: boolean; - onRequestClose?: (buttonClicked: boolean) => void; + onRequestClose?(buttonClicked: boolean): void; open: boolean; overlayClassName?: string; overlayStyle?: React.CSSProperties; @@ -1025,9 +1024,9 @@ declare namespace __MaterialUI { containerStyle?: React.CSSProperties; disableSwipeToOpen?: boolean; docked?: boolean; - onRequestChange?: (opening: boolean, reason: string) => void; + onRequestChange?(opening: boolean, reason: string): void; open?: boolean; - openSecondary?: Boolean; + openSecondary?: boolean; overlayClassName?: string; overlayStyle?: React.CSSProperties; style?: React.CSSProperties; @@ -1109,13 +1108,13 @@ declare namespace __MaterialUI { leftAvatar?: React.ReactElement; leftCheckbox?: React.ReactElement; leftIcon?: React.ReactElement; - nestedItems?: React.ReactElement[]; + nestedItems?: Array>; nestedLevel?: number; nestedListStyle?: React.CSSProperties; - onKeyboardFocus?: (e: React.FocusEvent<{}>, isKeyboardFocused: boolean) => void; + onKeyboardFocus?(e: React.FocusEvent<{}>, isKeyboardFocused: boolean): void; onMouseEnter?: React.MouseEventHandler<{}>; onMouseLeave?: React.MouseEventHandler<{}>; - onNestedListToggle?: (item: ListItem) => void; + onNestedListToggle?(item: ListItem): void; onTouchStart?: React.TouchEventHandler<{}>; onTouchTap?: TouchTapEventHandler; open?: boolean; @@ -1134,7 +1133,7 @@ declare namespace __MaterialUI { } interface SelectableProps { - onChange?: (e: TouchTapEvent, value: any) => void; + onChange?(e: TouchTapEvent, value: any): void; selectedItemStyle?: React.CSSProperties; value?: any; } @@ -1153,9 +1152,9 @@ declare namespace __MaterialUI { listStyle?: React.CSSProperties; maxHeight?: number; multiple?: boolean; - onChange?: (e: TouchTapEvent, itemValue: any | any[]) => void; + onChange?(e: TouchTapEvent, itemValue: any | any[]): void; onEscKeyDown?: React.KeyboardEventHandler<{}>; - onItemTouchTap?: (e: TouchTapEvent, item: MenuItem) => void; + onItemTouchTap?(e: TouchTapEvent, item: MenuItem): void; onKeyDown?: React.KeyboardEventHandler<{}>; selectedMenuItemStyle?: React.CSSProperties; style?: React.CSSProperties; @@ -1196,13 +1195,13 @@ declare namespace __MaterialUI { iconButtonElement: React.ReactElement; iconStyle?: React.CSSProperties; menuStyle?: React.CSSProperties; - onItemTouchTap?: (e: TouchTapEvent, item: MenuItem) => void; - onKeyboardFocus?: (e: React.FocusEvent<{}>, isKeyboardFocused: boolean) => void; + onItemTouchTap?(e: TouchTapEvent, item: MenuItem): void; + onKeyboardFocus?(e: React.FocusEvent<{}>, isKeyboardFocused: boolean): void; onMouseDown?: React.MouseEventHandler<{}>; onMouseEnter?: React.MouseEventHandler<{}>; onMouseLeave?: React.MouseEventHandler<{}>; onMouseUp?: React.MouseEventHandler<{}>; - onRequestChange?: (opening: boolean, reason: string) => void; + onRequestChange?(opening: boolean, reason: string): void; onTouchTap?: TouchTapEventHandler; open?: boolean; style?: React.CSSProperties; @@ -1216,7 +1215,7 @@ declare namespace __MaterialUI { listStyle?: React.CSSProperties; maxHeight?: number; multiple?: boolean; - onChange?: (e: TouchTapEvent, itemValue: any | any[]) => void; + onChange?(e: TouchTapEvent, itemValue: any | any[]): void; onKeyDown?: React.KeyboardEventHandler<{}>; selectedMenuItemStyle?: React.CSSProperties; value?: any | any[]; @@ -1238,8 +1237,8 @@ declare namespace __MaterialUI { listStyle?: React.CSSProperties; maxHeight?: number; menuStyle?: React.CSSProperties; - onChange?: (e: TouchTapEvent, index: number, menuItemValue: any) => void; - onClose?: (e: TouchTapEvent) => void; + onChange?(e: TouchTapEvent, index: number, menuItemValue: any): void; + onClose?(e: TouchTapEvent): void; openImmediately?: boolean; style?: React.CSSProperties; underlineStyle?: React.CSSProperties; @@ -1285,7 +1284,7 @@ declare namespace __MaterialUI { autoCloseWhenOffScreen?: boolean; canAutoPosition?: boolean; className?: string; - onRequestClose?: (reason: string) => void; + onRequestClose?(reason: string): void; open?: boolean; style?: React.CSSProperties; targetOrigin?: propTypes.origin; @@ -1367,10 +1366,10 @@ declare namespace __MaterialUI { labelStyle?: React.CSSProperties; multiple?: boolean; onBlur?: React.FocusEventHandler<{}>; - onChange?: (e: TouchTapEvent, index: number, menuItemValue: any) => void; + onChange?(e: TouchTapEvent, index: number, menuItemValue: any): void; onFocus?: React.FocusEventHandler<{}>; selectFieldRoot?: React.CSSProperties; - selectionRenderer?: (value: any) => React.ReactNode; + selectionRenderer?(value: any): React.ReactNode; style?: React.CSSProperties; underlineDisabledStyle?: React.CSSProperties; underlineFocusStyle?: React.CSSProperties; @@ -1400,12 +1399,12 @@ declare namespace __MaterialUI { min?: number; name?: string; onBlur?: React.FocusEventHandler<{}>; - onChange?: (e: React.MouseEvent<{}>, value: number) => void; + onChange?(e: React.MouseEvent<{}>, value: number): void; onDragStart?: React.MouseEventHandler<{}>; onDragStop?: React.MouseEventHandler<{}>; onFocus?: React.FocusEventHandler<{}>; required?: boolean; - sliderStyle?: React.CSSProperties, + sliderStyle?: React.CSSProperties; step?: number; style?: React.CSSProperties; value?: number; @@ -1414,7 +1413,6 @@ declare namespace __MaterialUI { } namespace Switches { - // what's not commonly overridden by Checkbox, RadioButton, or Toggle interface CommonEnhancedSwitchProps extends React.InputHTMLAttributes<{}>, React.Props { label?: React.ReactNode; @@ -1439,8 +1437,8 @@ declare namespace __MaterialUI { onMouseDown?: React.MouseEventHandler<{}>; onMouseLeave?: React.MouseEventHandler<{}>; onMouseUp?: React.MouseEventHandler<{}>; - onParentShouldUpdate: (isInputChecked: boolean) => void; - onSwitch?: (e: React.MouseEvent<{}>, isInputChecked: boolean) => void; + onParentShouldUpdate(isInputChecked: boolean): void; + onSwitch?(e: React.MouseEvent<{}>, isInputChecked: boolean): void; onTouchEnd?: React.TouchEventHandler<{}>; onTouchStart?: React.TouchEventHandler<{}>; required?: boolean; @@ -1469,7 +1467,7 @@ declare namespace __MaterialUI { iconStyle?: React.CSSProperties; labelPosition?: "left" | "right"; labelStyle?: React.CSSProperties; - onCheck?: (event: React.MouseEvent<{}>, checked: boolean) => void; + onCheck?(event: React.MouseEvent<{}>, checked: boolean): void; style?: React.CSSProperties; uncheckedIcon?: React.ReactElement<{ style?: React.CSSProperties }>; // Normally an SvgIcon valueLink?: ReactLink; @@ -1489,7 +1487,7 @@ declare namespace __MaterialUI { iconStyle?: React.CSSProperties; inputStyle?: React.CSSProperties; labelStyle?: React.CSSProperties; - onCheck?: (e: React.FormEvent<{}>, selected: string) => void; + onCheck?(e: React.FormEvent<{}>, selected: string): void; style?: React.CSSProperties; uncheckedIcon?: React.ReactElement<{ style?: React.CSSProperties }>; // Normally an SvgIcon value?: any; @@ -1505,7 +1503,7 @@ declare namespace __MaterialUI { defaultSelected?: any; labelPosition?: "left" | "right"; name: string; - onChange?: (e: React.FormEvent<{}>, selected: string) => void; + onChange?(e: React.FormEvent<{}>, selected: string): void; style?: React.CSSProperties; valueSelected?: any; } @@ -1527,7 +1525,7 @@ declare namespace __MaterialUI { label?: string; labelPosition?: "left" | "right"; labelStyle?: React.CSSProperties; - onToggle?: (e: React.MouseEvent<{}>, isInputChecked: boolean) => void; + onToggle?(e: React.MouseEvent<{}>, isInputChecked: boolean): void; rippleStyle?: React.CSSProperties; style?: React.CSSProperties; thumbStyle?: React.CSSProperties; @@ -1552,7 +1550,7 @@ declare namespace __MaterialUI { contentStyle?: React.CSSProperties; message: React.ReactNode; onActionTouchTap?: React.TouchEventHandler<{}>; - onRequestClose?: (reason: string) => void; + onRequestClose?(reason: string): void; open: boolean; style?: React.CSSProperties; } @@ -1609,10 +1607,10 @@ declare namespace __MaterialUI { message: string | JSX.Element; onActionTouchTap?: React.TouchEventHandler<{}>; /** @deprecated Use the open property to control the component instead */ - onDismiss?: () => void; // DEPRECATED - onRequestClose: (reason: string) => void; + onDismiss?(): void; // DEPRECATED + onRequestClose(reason: string): void; /** @deprecated Use the open property to control the component instead */ - onShow?: () => void; // DEPRECATED + onShow?(): void; // DEPRECATED open: boolean; /** @deprecated Use the open property to control the component instead */ openOnMount?: boolean; // DEPRECATED @@ -1646,12 +1644,12 @@ declare namespace __MaterialUI { headerStyle?: React.CSSProperties; height?: string; multiSelectable?: boolean; - onCellClick?: (row: number, column: number) => void; - onCellHover?: (row: number, column: number) => void; - onCellHoverExit?: (row: number, column: number) => void; - onRowHover?: (row: number) => void; - onRowHoverExit?: (row: number) => void; - onRowSelection?: (selectedRows: number[] | string) => void; + onCellClick?(row: number, column: number): void; + onCellHover?(row: number, column: number): void; + onCellHoverExit?(row: number, column: number): void; + onRowHover?(row: number): void; + onRowHoverExit?(row: number): void; + onRowSelection?(selectedRows: number[] | string): void; selectable?: boolean; style?: React.CSSProperties; wrapperStyle?: React.CSSProperties; @@ -1666,17 +1664,17 @@ declare namespace __MaterialUI { hoverable?: boolean; hovered?: boolean; /** @deprecated Instead, use event handler on Table */ - onCellClick?: (e: React.MouseEvent<{}>, row: number, column: number) => void; + onCellClick?(e: React.MouseEvent<{}>, row: number, column: number): void; /** @deprecated Instead, use event handler on Table */ - onCellHover?: (e: React.MouseEvent<{}>, row: number, column: number) => void; + onCellHover?(e: React.MouseEvent<{}>, row: number, column: number): void; /** @deprecated Instead, use event handler on Table */ - onCellHoverExit?: (e: React.MouseEvent<{}>, row: number, column: number) => void; + onCellHoverExit?(e: React.MouseEvent<{}>, row: number, column: number): void; /** @deprecated Instead, use event handler on Table */ - onRowClick?: (e: React.MouseEvent<{}>, row: number) => void; + onRowClick?(e: React.MouseEvent<{}>, row: number): void; /** @deprecated Instead, use event handler on Table */ - onRowHover?: (e: React.MouseEvent<{}>, row: number) => void; + onRowHover?(e: React.MouseEvent<{}>, row: number): void; /** @deprecated Instead, use event handler on Table */ - onRowHoverExit?: (e: React.MouseEvent<{}>, row: number) => void; + onRowHoverExit?(e: React.MouseEvent<{}>, row: number): void; rowNumber?: number; selectable?: boolean; selected?: boolean; @@ -1693,11 +1691,11 @@ declare namespace __MaterialUI { hoverable?: boolean; key?: string; /** @deprecated Instead, use event handler on Table */ - onClick?: (e: React.MouseEvent<{}>, column: number) => void; + onClick?(e: React.MouseEvent<{}>, column: number): void; /** @deprecated Instead, use event handler on Table */ - onHover?: (e: React.MouseEvent<{}>, column: number) => void; + onHover?(e: React.MouseEvent<{}>, column: number): void; /** @deprecated Instead, use event handler on Table */ - onHoverExit?: (e: React.MouseEvent<{}>, column: number) => void; + onHoverExit?(e: React.MouseEvent<{}>, column: number): void; style?: React.CSSProperties; // useful attributes passed to @@ -1713,7 +1711,7 @@ declare namespace __MaterialUI { displaySelectAll?: boolean; enableSelectAll?: boolean; /** @deprecated Instead, use event handler on Table */ - onSelectAll?: (checked: boolean) => void; + onSelectAll?(checked: boolean): void; /** @deprecated Instead, use event handler on Table */ selectAllSelected?: boolean; style?: React.CSSProperties; @@ -1726,7 +1724,7 @@ declare namespace __MaterialUI { className?: string; columnNumber?: number; key?: string; - onClick?: (e: React.MouseEvent<{}>, column: number) => void; + onClick?(e: React.MouseEvent<{}>, column: number): void; style?: React.CSSProperties; tooltip?: string; tooltipStyle?: React.CSSProperties; @@ -1747,17 +1745,17 @@ declare namespace __MaterialUI { /** @deprecated Instead, use property on Table */ multiSelectable?: boolean; /** @deprecated Instead, use event handler on Table */ - onCellClick?: (row: number, column: number) => void; + onCellClick?(row: number, column: number): void; /** @deprecated Instead, use event handler on Table */ - onCellHover?: (row: number, column: number) => void; + onCellHover?(row: number, column: number): void; /** @deprecated Instead, use event handler on Table */ - onCellHoverExit?: (row: number, column: number) => void; + onCellHoverExit?(row: number, column: number): void; /** @deprecated Instead, use event handler on Table */ - onRowHover?: (row: number) => void; + onRowHover?(row: number): void; /** @deprecated Instead, use event handler on Table */ - onRowHoverExit?: (row: number) => void; + onRowHoverExit?(row: number): void; /** @deprecated Instead, use event handler on Table */ - onRowSelection?: (selectedRows: number[] | string) => void; + onRowSelection?(selectedRows: number[] | string): void; preScanRows?: boolean; /** @deprecated Instead, use property on Table */ selectable?: boolean; @@ -1785,7 +1783,7 @@ declare namespace __MaterialUI { contentContainerStyle?: React.CSSProperties; initialSelectedIndex?: number; inkBarStyle?: React.CSSProperties; - onChange?: (value: any, e: React.FormEvent<{}>, tab: Tab) => void; + onChange?(value: any, e: React.FormEvent<{}>, tab: Tab): void; style?: React.CSSProperties; tabItemContainerStyle?: React.CSSProperties; tabTemplate?: React.ComponentClass; @@ -1800,7 +1798,7 @@ declare namespace __MaterialUI { className?: string; icon?: React.ReactNode; label?: React.ReactNode; - onActive?: (tab: Tab) => void; + onActive?(tab: Tab): void; style?: React.CSSProperties; value?: any; disabled?: boolean; @@ -1829,14 +1827,14 @@ declare namespace __MaterialUI { multiLine?: boolean; name?: string; onBlur?: React.FocusEventHandler<{}>; - onChange?: (e: React.FormEvent<{}>, newValue: string) => void; + onChange?(e: React.FormEvent<{}>, newValue: string): void; onFocus?: React.FocusEventHandler<{}>; onKeyDown?: React.KeyboardEventHandler<{}>; onKeyUp?: React.KeyboardEventHandler<{}>; onKeyPress?: React.KeyboardEventHandler<{}>; required?: boolean; - rows?: number, - rowsMax?: number, + rows?: number; + rowsMax?: number; style?: React.CSSProperties; textareaStyle?: React.CSSProperties; type?: string; @@ -1874,10 +1872,10 @@ declare namespace __MaterialUI { format?: "ampm" | "24hr"; minutesStep?: number; okLabel?: React.ReactNode; - onChange?: (e: any, time: Date) => void; - onDismiss?: () => void; + onChange?(e: any, time: Date): void; + onDismiss?(): void; onFocus?: React.FocusEventHandler<{}>; - onShow?: () => void; + onShow?(): void; onTouchTap?: TouchTapEventHandler; pedantic?: boolean; style?: React.CSSProperties; @@ -1902,8 +1900,8 @@ declare namespace __MaterialUI { name?: string; onBlur?: React.FocusEventHandler<{}>; onKeyDown?: React.KeyboardEventHandler<{}>; - rows?: number, - rowsMax?: number, + rows?: number; + rowsMax?: number; textareaStyle?: React.CSSProperties; type?: string; underlineDisabledStyle?: React.CSSProperties; @@ -1988,7 +1986,7 @@ declare namespace __MaterialUI { toggleClass(el: Element, className: string): void; withoutTransition(el: HTMLElement, callback: () => void): void; } - export var Dom: Dom; + export let Dom: Dom; interface Events { isKeyboard(e: Event): boolean; @@ -1996,7 +1994,7 @@ declare namespace __MaterialUI { on(el: Element, type: string, callback: EventListener): void; once(el: Element, type: string, callback: EventListener): void; } - export var Events: Events; + export let Events: Events; } } // __MaterialUI @@ -6924,7 +6922,7 @@ declare module 'material-ui/styles/MuiThemeProvider' { declare module 'material-ui/styles/spacing' { type Spacing = __MaterialUI.Styles.Spacing; - var Spacing: Spacing; + let Spacing: Spacing; export default Spacing; } @@ -7666,7 +7664,7 @@ declare namespace __MaterialUI.Styles { darkWhite: string; lightWhite: string; } - export var Colors: Colors; + export let Colors: Colors; } declare module "material-ui/svg-icons" { @@ -8594,7 +8592,6 @@ declare module "material-ui/svg-icons" { export import ToggleStarHalf = __MaterialUI.SvgIcon; // require('material-ui/svg-icons/toggle/star-half'); } - declare module 'material-ui/internal/AppCanvas' { interface AppCanvasProps extends React.Props { } class AppCanvas extends React.Component { } @@ -8609,12 +8606,12 @@ declare module 'material-ui/internal/AutoLockScrolling' { } declare module 'material-ui/internal/BeforeAfterWrapper' { interface BeforeAfterWrapperProps extends React.Props { - afterElementType?: string, - afterStyle?: React.CSSProperties, - beforeElementType?: string, - beforeStyle?: React.CSSProperties, - elementType?: string, - style?: React.CSSProperties, + afterElementType?: string; + afterStyle?: React.CSSProperties; + beforeElementType?: string; + beforeStyle?: React.CSSProperties; + elementType?: string; + style?: React.CSSProperties; } class BeforeAfterWrapper extends React.Component { } export default BeforeAfterWrapper; @@ -8638,7 +8635,7 @@ declare module 'material-ui/internal/ClearFix' { } declare module 'material-ui/internal/ClickAwayListener' { interface ClickAwayListenerProps extends React.Props { - onClickAway?: any, + onClickAway?: any; } class ClickAwayListener extends React.Component { } export default ClickAwayListener; @@ -8679,11 +8676,11 @@ declare module 'material-ui/internal/ExpandTransitionChild' { } declare module 'material-ui/internal/FocusRipple' { interface FocusRippleProps extends React.Props { - color?: string, - innerStyle?: React.CSSProperties, - opacity?: number, - show?: boolean, - style?: React.CSSProperties + color?: string; + innerStyle?: React.CSSProperties; + opacity?: number; + show?: boolean; + style?: React.CSSProperties; } class FocusRipple extends React.Component { } export default FocusRipple; @@ -8742,7 +8739,7 @@ declare module 'material-ui/internal/SlideIn' { } declare module 'material-ui/internal/SlideInChild' { interface SlideInChildProps extends React.Props { - direction?: string, + direction?: string; enterDelay?: number; getLeaveDirection: Function; style?: React.CSSProperties; @@ -8765,11 +8762,11 @@ declare module 'material-ui/internal/Tooltip' { } declare module 'material-ui/internal/TouchRipple' { interface TouchRippleProps extends React.Props { - abortOnScroll?: boolean, + abortOnScroll?: boolean; centerRipple?: boolean; color?: string; opacity?: number; - style?: React.CSSProperties + style?: React.CSSProperties; } class TouchRipple extends React.Component { } export default TouchRipple; diff --git a/types/material-ui/material-ui-tests.tsx b/types/material-ui/material-ui-tests.tsx index 506d70bce8..c927fdd2e6 100644 --- a/types/material-ui/material-ui-tests.tsx +++ b/types/material-ui/material-ui-tests.tsx @@ -1,11 +1,11 @@ import * as React from 'react'; -import {Component, PropTypes} from 'react'; +import { Component, PropTypes } from 'react'; import * as ReactDOM from 'react-dom'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; -import {muiThemeable} from 'material-ui/styles/muiThemeable'; +import { muiThemeable } from 'material-ui/styles/muiThemeable'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme'; -import {MuiTheme} from 'material-ui/styles'; +import { MuiTheme } from 'material-ui/styles'; import AppBar from 'material-ui/AppBar'; import AutoComplete from 'material-ui/AutoComplete'; import Avatar from 'material-ui/Avatar'; @@ -38,19 +38,19 @@ import SvgIcon from 'material-ui/SvgIcon'; import TextField from 'material-ui/TextField'; import TimePicker from 'material-ui/TimePicker'; import Toggle from 'material-ui/Toggle'; -import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card'; -import {GridList, GridTile} from 'material-ui/GridList'; -import {makeSelectable} from 'material-ui/List'; -import {Menu} from 'material-ui/Menu'; -import {Popover, PopoverAnimationVertical} from 'material-ui/Popover'; -import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton'; -import {Step, Stepper, StepLabel, StepContent, StepButton} from 'material-ui/Stepper'; -import {BottomNavigation, BottomNavigationItem} from 'material-ui/BottomNavigation'; +import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card'; +import { GridList, GridTile } from 'material-ui/GridList'; +import { makeSelectable } from 'material-ui/List'; +import { Menu } from 'material-ui/Menu'; +import { Popover, PopoverAnimationVertical } from 'material-ui/Popover'; +import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton'; +import { Step, Stepper, StepLabel, StepContent, StepButton } from 'material-ui/Stepper'; +import { BottomNavigation, BottomNavigationItem } from 'material-ui/BottomNavigation'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, TableFooter -} from 'material-ui/Table'; -import {Tabs, Tab} from 'material-ui/Tabs'; -import {Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle} from 'material-ui/Toolbar'; + } from 'material-ui/Table'; +import { Tabs, Tab } from 'material-ui/Tabs'; +import { Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle } from 'material-ui/Toolbar'; import ActionAndroid from 'material-ui/svg-icons/action/android'; import ActionAssignment from 'material-ui/svg-icons/action/assignment'; import ActionFavorite from 'material-ui/svg-icons/action/favorite'; @@ -93,10 +93,9 @@ import { cyan500, cyan700, grey100, grey300, grey400, grey500, pinkA200, white, darkBlack, fullBlack, blue300, indigo900, orange200, deepOrange300, pink400, purple500, fullWhite, blue500, red500, greenA200, yellow500, transparent, yellow600, indigo500, lightBlack, orange500 -} from 'material-ui/styles/colors'; -import {fade} from 'material-ui/utils/colorManipulator'; -import {default as withWidth} from 'material-ui/utils/withWidth'; - + } from 'material-ui/styles/colors'; +import { fade } from 'material-ui/utils/colorManipulator'; +import { default as withWidth } from 'material-ui/utils/withWidth'; import injectTapEventPlugin = require('react-tap-event-plugin'); @@ -304,7 +303,6 @@ const lightBaseTheme = { const lightMuiTheme = getMuiTheme(lightBaseTheme); - class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}> { static propTypes: React.ValidationMap = { muiTheme: React.PropTypes.object.isRequired, @@ -319,7 +317,10 @@ class DeepDownTheTree extends React.Component<{} & {muiTheme: MuiTheme}> { } } -type Props = { label: string, muiTheme?: MuiTheme }; +interface Props { + label: string; + muiTheme?: MuiTheme; +} const MuiThemeableFunction = muiThemeable(), Props>(props => { return ( @@ -348,7 +349,6 @@ const MuiThemeableContainer = (props: {}) => ( ); - // "http://www.material-ui.com/#/customization/inline-styles" const InlineStylesCheckbox = () => ( ( /> ); - // "http://www.material-ui.com/#/components/app-bar" const AppBarExampleIcon = () => ( ( // "http://www.material-ui.com/#/components/auto-complete" export class AutoCompleteExampleSimple extends React.Component<{}, {dataSource: string[]}> { - constructor(props) { super(props); @@ -660,7 +658,6 @@ const AvatarExampleSimple = () => ( ); - // "http://www.material-ui.com/#/components/badge" const BadgeExampleSimple = () => (

    @@ -698,7 +695,6 @@ const BadgeExampleContent = () => (
    ); - // "http://www.material-ui.com/#/components/flat-button" const FlatButtonExampleSimple = () => (
    @@ -754,7 +750,6 @@ const FlatButtonExampleIcon = () => (
    ); - // "http://www.material-ui.com/#/components/raised-button" const RaisedButtonExampleSimple = () => (
    @@ -811,7 +806,6 @@ const RaisedButtonExampleIcon = () => (
    ); - // "http://www.material-ui.com/#/components/floating-action-button" const FloatingActionButtonExampleSimple = () => (
    @@ -841,7 +835,6 @@ const FloatingActionButtonExampleSimple = () => (
    ); - // "http://www.material-ui.com/#/components/icon-button" const IconButtonExampleSimple = () => (
    @@ -950,7 +943,6 @@ const IconButtonExampleTouch = () => (
    ); - // "http://www.material-ui.com/#/components/card" const CardExampleWithAvatar = () => ( @@ -1000,7 +992,6 @@ const CardExampleWithoutAvatar = () => ( ); class CardExampleControlled extends React.Component<{}, {expanded: boolean}> { - constructor(props) { super(props); this.state = { @@ -1093,7 +1084,6 @@ class ChipExampleComplex extends React.Component { } } - // "http://www.material-ui.com/#/components/date-picker" const DatePickerExampleSimple = () => (
    @@ -1205,7 +1195,6 @@ class DatePickerExampleToggle extends React.Component<{}, DatePickerExampleToggl } class DatePickerExampleControlled extends React.Component<{}, {controlledDate?: Date}> { - constructor(props) { super(props); @@ -1270,7 +1259,6 @@ const DatePickerExampleInternational = () => (
    ); - // "http://material-ui.com/#/components/dialog" class DialogExampleSimple extends React.Component<{}, {open?: boolean}> { state = { @@ -1549,7 +1537,6 @@ class DialogExampleAlert extends React.Component<{}, {open?: boolean}> { } } - // "http://www.material-ui.com/#/components/divider" const DividerExampleForm = () => ( @@ -1587,10 +1574,8 @@ const DividerExampleMenu = () => ( ); - // "http://www.material-ui.com/#/components/drawer" class DrawerSimpleExample extends React.Component<{}, {open?: boolean}> { - constructor(props) { super(props); this.state = {open: false}; @@ -1615,7 +1600,6 @@ class DrawerSimpleExample extends React.Component<{}, {open?: boolean}> { } class DrawerUndockedExample extends React.Component<{}, {open?: boolean}> { - constructor(props) { super(props); this.state = {open: false}; @@ -1647,7 +1631,6 @@ class DrawerUndockedExample extends React.Component<{}, {open?: boolean}> { } class DrawerOpenRightExample extends React.Component<{}, {open?: boolean}> { - constructor(props) { super(props); this.state = {open: false}; @@ -1670,9 +1653,8 @@ class DrawerOpenRightExample extends React.Component<{}, {open?: boolean}> { } } - // "http://www.material-ui.com/#/components/grid-list" -const tilesData: {img: string, title: string, author: string, featured?: boolean}[] = [ +const tilesData: Array<{img: string, title: string, author: string, featured?: boolean}> = [ { img: 'images/grid-list/00-52-29-429_640.jpg', title: 'Breakfast', @@ -1763,7 +1745,6 @@ const GridListExampleComplex = () => (
    ); - // "http://www.material-ui.com/#/components/font-icon" const FontIconExampleSimple = () => (
    @@ -1796,7 +1777,6 @@ const FontIconExampleIcons = () => (
    ); - // "http://www.material-ui.com/#/components/svg-icon" const HomeIcon = (props) => ( @@ -1821,7 +1801,6 @@ const SvgIconExampleIcons = () => (
    ); - // "http://material-ui.com/#/components/lists" const ListExampleSimple = () => ( @@ -2337,7 +2316,6 @@ const ListExampleSelectable = () => ( ); - // "http://www.material-ui.com/#/components/menu" const MenuExampleSimple = () => (
    @@ -2491,7 +2469,6 @@ const MenuExampleNested = () => (
    ); - // "http://www.material-ui.com/#/components/icon-menu" const IconMenuExampleSimple = () => (
    @@ -2725,10 +2702,8 @@ const IconMenuExampleNested = () => (
    ); - // "http://www.material-ui.com/#/components/dropdown-menu" class DropDownMenuSimpleExample extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = {value: 1}; @@ -2766,7 +2741,6 @@ class DropDownMenuSimpleExample extends React.Component<{}, {value?: number}> { } class DropDownMenuOpenImmediateExample extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = {value: 2}; @@ -2787,13 +2761,12 @@ class DropDownMenuOpenImmediateExample extends React.Component<{}, {value?: numb } } -const items: React.ReactElement<__MaterialUI.Menus.MenuItemProps>[] = []; +const items: Array> = []; for (let i = 0; i < 100; i++) { items.push(); } class DropDownMenuLongMenuExample extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = {value: 10}; @@ -2811,7 +2784,6 @@ class DropDownMenuLongMenuExample extends React.Component<{}, {value?: number}> } class DropDownMenuLabeledExample extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = {value: 2}; @@ -2831,7 +2803,6 @@ class DropDownMenuLabeledExample extends React.Component<{}, {value?: number}> { } } - // "http://material-ui.com/#/components/paper" const PaperExampleSimple = () => (
    @@ -2863,10 +2834,8 @@ const PaperExampleCircle = () => (
    ); - // "http://www.material-ui.com/#/components/popover" class PopoverExampleSimple extends React.Component<{}, {open?: boolean, anchorEl?: React.ReactInstance}> { - constructor(props) { super(props); @@ -2918,7 +2887,6 @@ class PopoverExampleSimple extends React.Component<{}, {open?: boolean, anchorEl } class PopoverExampleAnimation extends React.Component<{}, {open?: boolean, anchorEl?: React.ReactInstance}> { - constructor(props) { super(props); @@ -2977,7 +2945,6 @@ interface PopoverExampleConfigurableState { } class PopoverExampleConfigurable extends React.Component<{}, PopoverExampleConfigurableState> { - constructor(props) { super(props); @@ -3127,7 +3094,6 @@ class PopoverExampleConfigurable extends React.Component<{}, PopoverExampleConfi } } - // "http://www.material-ui.com/#/components/circular-progress" const CircularProgressExampleSimple = () => (
    @@ -3177,7 +3143,6 @@ class CircularProgressExampleDeterminate extends React.Component<{}, {completed? } } - // "http://www.material-ui.com/#/components/linear-progress" const LinearProgressExampleSimple = () => ( @@ -3219,7 +3184,6 @@ class LinearProgressExampleDeterminate extends React.Component<{}, {completed?: } } - // "http://www.material-ui.com/#/components/refresh-indicator" const RefreshIndicatorExampleSimple = () => (
    @@ -3280,10 +3244,8 @@ const RefreshIndicatorExampleLoading = () => (
    ); - // "http://www.material-ui.com/#/components/select-field" class SelectFieldExampleSimple extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = {value: 1}; @@ -3336,7 +3298,6 @@ class SelectFieldExampleSimple extends React.Component<{}, {value?: number}> { } class SelectFieldLongMenuExample extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = {value: 10}; @@ -3354,7 +3315,6 @@ class SelectFieldLongMenuExample extends React.Component<{}, {value?: number}> { } class SelectFieldExampleCustomLabel extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = {value: 1}; @@ -3383,7 +3343,6 @@ const itemsPeriod = [ ]; export default class SelectFieldExampleFloatingLabel extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = {value: null}; @@ -3417,7 +3376,6 @@ export default class SelectFieldExampleFloatingLabel extends React.Component<{}, } class SelectFieldExampleError extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = {value: null}; @@ -3467,7 +3425,6 @@ const names = [ ]; class SelectFieldExampleMultiSelect extends React.Component<{}, {values?: string[]}> { - constructor(props) { super(props); this.state = {values: []}; @@ -3516,7 +3473,6 @@ const persons = [ ]; class SelectFieldExampleSelectionRenderer extends React.Component<{}, {values?: string[]}> { - constructor(props) { super(props); this.state = {values: []}; @@ -3562,7 +3518,6 @@ class SelectFieldExampleSelectionRenderer extends React.Component<{}, {values?: } } - // "http://www.material-ui.com/#/components/slider" const SliderExampleSimple = () => (
    @@ -3585,7 +3540,6 @@ const SliderExampleStep = () => ( ); class SliderExampleControlled extends React.Component<{}, {firstSlider?: number, secondSlider?: number}> { - state = { firstSlider: 0.5, secondSlider: 50, @@ -3630,7 +3584,6 @@ class SliderExampleControlled extends React.Component<{}, {firstSlider?: number, } } - // "http://www.material-ui.com/#/components/checkbox" const CheckboxExampleSimple = () => (
    @@ -3668,7 +3621,6 @@ const CheckboxExampleSimple = () => (
    ); - // "http://www.material-ui.com/#/components/radio-button" const RadioButtonExampleSimple = () => (
    @@ -3715,7 +3667,6 @@ const RadioButtonExampleSimple = () => (
    ); - // "http://www.material-ui.com/#/components/toggle" const ToggleExampleSimple = () => (
    @@ -3743,10 +3694,8 @@ const ToggleExampleSimple = () => (
    ); - // "http://material-ui.com/#/components/snackbar" class SnackbarExampleSimple extends React.Component<{}, {open?: boolean}> { - constructor(props) { super(props); this.state = { @@ -3786,7 +3735,6 @@ class SnackbarExampleSimple extends React.Component<{}, {open?: boolean}> { } class SnackbarExampleAction extends React.Component<{}, {open?: boolean, autoHideDuration?: number, message?: string}> { - constructor(props) { super(props); this.state = { @@ -3849,7 +3797,6 @@ class SnackbarExampleAction extends React.Component<{}, {open?: boolean, autoHid } class SnackbarExampleTwice extends React.Component<{}, {open?: boolean, message?: string}> { - private timer: number; constructor(props) { @@ -3902,10 +3849,8 @@ class SnackbarExampleTwice extends React.Component<{}, {open?: boolean, message? } } - // "http://www.material-ui.com/#/components/stepper" class HorizontalLinearStepper extends React.Component<{}, {stepIndex?: number, finished?: boolean}> { - state = { finished: false, stepIndex: 0, @@ -3994,7 +3939,6 @@ class HorizontalLinearStepper extends React.Component<{}, {stepIndex?: number, f } class VerticalLinearStepper extends React.Component<{}, {stepIndex?: number, finished?: boolean}> { - state = { finished: false, stepIndex: 0, @@ -4097,7 +4041,6 @@ class VerticalLinearStepper extends React.Component<{}, {stepIndex?: number, fin } class HorizontalNonLinearStepper extends React.Component<{}, {stepIndex?: number}> { - state = { stepIndex: 0, }; @@ -4175,7 +4118,6 @@ class HorizontalNonLinearStepper extends React.Component<{}, {stepIndex?: number } class VerticalNonLinear extends React.Component<{}, {stepIndex?: number}> { - state = { stepIndex: 0, }; @@ -4289,7 +4231,6 @@ const getStyles = () => { }; class GranularControlStepper extends React.Component<{}, {stepIndex?: number, visited?: number[]}> { - state = { stepIndex: null, visited: [], @@ -4392,7 +4333,6 @@ class GranularControlStepper extends React.Component<{}, {stepIndex?: number, vi } class CustomIcon extends React.Component<{}, {stepIndex?: number}> { - state = { stepIndex: 0, }; @@ -4452,7 +4392,6 @@ class CustomIcon extends React.Component<{}, {stepIndex?: number}> { } } - // "http://www.material-ui.com/#/components/subheader" // Included in ListExampleChat and ListExampleFolder @@ -4491,7 +4430,7 @@ const TableExampleSimple = () => ( ); -const tableData: {name: string, status: string, selected?: boolean}[] = [ +const tableData: Array<{name: string, status: string, selected?: boolean}> = [ { name: 'John Smith', status: 'Employed', @@ -4538,7 +4477,6 @@ interface TableExampleComplexState { } class TableExampleComplex extends React.Component<{}, TableExampleComplexState> { - constructor(props) { super(props); @@ -4734,7 +4672,6 @@ const TabsExampleSimple = () => ( ); class TabsExampleControlled extends React.Component<{}, {value?: string}> { - constructor(props) { super(props); this.state = { @@ -4804,7 +4741,6 @@ const TabsExampleIconText = () => ( ); - // "http://www.material-ui.com/#/components/text-field" const TextFieldExampleSimple = () => (
    @@ -4941,7 +4877,6 @@ const TextFieldExampleDisabled = () => ( ); class TextFieldExampleControlled extends React.Component<{}, {value?: string}> { - constructor(props) { super(props); @@ -4988,7 +4923,6 @@ const TimePickerExampleSimple = () => ( ); class TimePickerExampleComplex extends React.Component<{}, {value24?: Date, value12?: Date}> { - constructor(props) { super(props); this.state = {value24: null, value12: null}; @@ -5032,10 +4966,8 @@ const TimePickerInternational = () => (
    ); - // "http://www.material-ui.com/#/components/toolbar" class ToolbarExamplesSimple extends React.Component<{}, {value?: number}> { - constructor(props) { super(props); this.state = { @@ -5086,7 +5018,7 @@ class BottomNavigationExample extends React.Component<{}, { index?: number }> { constructor() { - super() + super(); this.state = { index: 0 }; @@ -5099,11 +5031,7 @@ class BottomNavigationExample extends React.Component<{}, { } } -interface MaterialUiTestsState { -} - -class MaterialUiTests extends React.Component<{}, MaterialUiTestsState> { - +class MaterialUiTests extends React.Component<{}, {}> { render() { return ( diff --git a/types/material-ui/tslint.json b/types/material-ui/tslint.json new file mode 100644 index 0000000000..e225711bd5 --- /dev/null +++ b/types/material-ui/tslint.json @@ -0,0 +1,9 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false, + "no-empty-interface": false, + "dt-header": false, + "ban-types": false + } +} \ No newline at end of file From 271b8ec0aa47105cff01e5e849a6f34f23e30bf3 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Sat, 22 Jul 2017 21:21:48 +0200 Subject: [PATCH 0213/1139] [normalize-url] correct typings, add tests, export namespace (#18292) --- types/normalize-url/index.d.ts | 28 +++++++++++----------- types/normalize-url/normalize-url-tests.ts | 17 +++++++++++++ types/normalize-url/tsconfig.json | 5 ++-- 3 files changed, 34 insertions(+), 16 deletions(-) create mode 100644 types/normalize-url/normalize-url-tests.ts diff --git a/types/normalize-url/index.d.ts b/types/normalize-url/index.d.ts index 94cf9ee522..ec70be130b 100644 --- a/types/normalize-url/index.d.ts +++ b/types/normalize-url/index.d.ts @@ -1,21 +1,21 @@ // Type definitions for normalize-url 1.9 // Project: https://github.com/sindresorhus/normalize-url // Definitions by: odin3 +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace NormalizeUrl { - interface NormalizeUrlArgs { - normalizeProtocol?: boolean; - normalizeHttps?: boolean; - stripFragment?: boolean; - stripWWW?: boolean; - removeQueryParameters?: string[]; - removeTrailingSlash?: boolean; - removeDirectoryIndex?: RegExp[]; - } - - // tslint:disable-next-line align - function normalizeUrl(url: string, args?: NormalizeUrlArgs): string; +declare namespace normalizeUrl { + interface Options { + normalizeProtocol?: boolean; + normalizeHttps?: boolean; + stripFragment?: boolean; + stripWWW?: boolean; + removeQueryParameters?: Array; + removeTrailingSlash?: boolean; + removeDirectoryIndex?: Array; + } } -export = NormalizeUrl.normalizeUrl; +declare function normalizeUrl(url: string, options?: normalizeUrl.Options): string; + +export = normalizeUrl; diff --git a/types/normalize-url/normalize-url-tests.ts b/types/normalize-url/normalize-url-tests.ts new file mode 100644 index 0000000000..961be30c0d --- /dev/null +++ b/types/normalize-url/normalize-url-tests.ts @@ -0,0 +1,17 @@ +import normalizeUrl = require('normalize-url'); + +let str: string; +str = normalizeUrl('sindresorhus.com'); +str = normalizeUrl('HTTP://xn--xample-hva.com:80/?b=bar&a=foo'); + +normalizeUrl('//sindresorhus.com:80/', {normalizeProtocol: false}); +normalizeUrl('https://sindresorhus.com:80/', {normalizeHttps: true}); +normalizeUrl('sindresorhus.com/about.html#contact', {stripFragment: false}); +normalizeUrl('http://www.sindresorhus.com/about.html#contact', {stripWWW: false}); +normalizeUrl('www.sindresorhus.com?foo=bar&ref=test_ref', { + removeQueryParameters: ['ref', /test/] +}); +normalizeUrl('http://sindresorhus.com/', {removeTrailingSlash: false}); +normalizeUrl('www.sindresorhus.com/foo/default.php', { + removeDirectoryIndex: [/^default\.[a-z]+$/, 'foo'] +}); diff --git a/types/normalize-url/tsconfig.json b/types/normalize-url/tsconfig.json index 27e01ecd7b..8d9596fd6f 100644 --- a/types/normalize-url/tsconfig.json +++ b/types/normalize-url/tsconfig.json @@ -16,6 +16,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts" + "index.d.ts", + "normalize-url-tests.ts" ] -} \ No newline at end of file +} From d9420c7ffc2fe9efc8c56d67114cbab5e09527b5 Mon Sep 17 00:00:00 2001 From: Mike Deverell Date: Wed, 19 Jul 2017 16:26:08 -0400 Subject: [PATCH 0214/1139] add missing textarea attributes --- types/react/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 3849e98d7f..e0a047c593 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -2815,8 +2815,10 @@ declare namespace React { } interface TextareaHTMLAttributes extends HTMLAttributes { + autoComplete?: string; autoFocus?: boolean; cols?: number; + dirName?: string; disabled?: boolean; form?: string; maxLength?: number; From 801ffc3751d64f19b33cca2f7e702ca09aef0e71 Mon Sep 17 00:00:00 2001 From: Mike Deverell Date: Wed, 19 Jul 2017 16:34:19 -0400 Subject: [PATCH 0215/1139] add myself (devrelm) to the contributors list --- types/react/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index e0a047c593..33f70c73d9 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -12,6 +12,7 @@ // Tanguy Krotoff // Dovydas Navickas // Stéphane Goetz +// Mike Deverell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From c3f41ac81b330212ab75ab8609c79a050bd6e2cd Mon Sep 17 00:00:00 2001 From: Mike Deverell Date: Thu, 20 Jul 2017 12:43:26 -0400 Subject: [PATCH 0216/1139] 'autoComplete' should be lowercase 'autocomplete' --- types/react/index.d.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 33f70c73d9..b74fe7a1a0 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -2392,7 +2392,7 @@ declare namespace React { allowTransparency?: boolean; alt?: string; async?: boolean; - autoComplete?: string; + autocomplete?: string; autoFocus?: boolean; autoPlay?: boolean; capture?: boolean; @@ -2577,7 +2577,7 @@ declare namespace React { interface FormHTMLAttributes extends HTMLAttributes { acceptCharset?: string; action?: string; - autoComplete?: string; + autocomplete?: string; encType?: string; method?: string; name?: string; @@ -2623,7 +2623,7 @@ declare namespace React { interface InputHTMLAttributes extends HTMLAttributes { accept?: string; alt?: string; - autoComplete?: string; + autocomplete?: string; autoFocus?: boolean; capture?: boolean; // https://www.w3.org/TR/html-media-capture/#the-capture-attribute checked?: boolean; @@ -2816,7 +2816,7 @@ declare namespace React { } interface TextareaHTMLAttributes extends HTMLAttributes { - autoComplete?: string; + autocomplete?: string; autoFocus?: boolean; cols?: number; dirName?: string; From 9ecdd3cbcb39b520fc9390410baff66df400de58 Mon Sep 17 00:00:00 2001 From: Michel Boudreau Date: Mon, 24 Jul 2017 11:15:25 +1000 Subject: [PATCH 0217/1139] Updating Q to have optional resolves (#18200) * Remove export as namespace This particular file was causing me issues with the new typings-2.0 since it doesn't support exporting namespaces from within modules. * Updating Q to have optional resolves, adding tslint file, fixing tests compilation * forgot to merge in latest from upstream, replicated the changes into new folder structure * adding tslint to q * latest changes to please tslint, but is currently breaking the .all tests - still need to fix * fixing the reason why the tests was failing, a problem with Typescript trying to decipher the signature of arrays within function arguments that are unionized, updating tslint to ignore those issues * whoops, messed up header which failed linting --- types/q/index.d.ts | 601 ++++++++++++++++++++++-------------------- types/q/q-tests.ts | 291 ++++++++++---------- types/q/tsconfig.json | 2 +- types/q/tslint.json | 8 + 4 files changed, 471 insertions(+), 431 deletions(-) create mode 100644 types/q/tslint.json diff --git a/types/q/index.d.ts b/types/q/index.d.ts index 56ada9590a..942d5535ec 100644 --- a/types/q/index.d.ts +++ b/types/q/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for Q 1.0 // Project: https://github.com/kriskowal/q -// Definitions by: Barrie Nemetchek , Andrew Gaspar , John Reilly +// Definitions by: Barrie Nemetchek +// Andrew Gaspar +// John Reilly +// Michel Boudreau // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -10,343 +13,371 @@ export as namespace Q; /** * If value is a Q promise, returns the promise. * If value is a promise from another library it is coerced into a Q promise (where possible). - */ -declare function Q(promise: PromiseLike): Q.Promise; -/** * If value is not a promise, returns a promise that is fulfilled with value. */ -declare function Q(value: T): Q.Promise; +declare function Q(promise: PromiseLike | T): Q.Promise; /** * Calling with nothing at all creates a void promise */ declare function Q(): Q.Promise; declare namespace Q { + export type IWhenable = PromiseLike | T; + export type IPromise = PromiseLike; - export type IWhenable = PromiseLike | T; - export type IPromise = PromiseLike; + export interface Deferred { + promise: Promise; - export interface Deferred { - promise: Promise; - resolve(value?: IWhenable): void; - reject(reason: any): void; - notify(value: any): void; - makeNodeResolver(): (reason: any, value: T) => void; - } + resolve(value?: IWhenable): void; - export interface Promise { - /** - * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. + reject(reason: any): void; - * finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished. - */ - fin(finallyCallback: () => any): Promise; - /** - * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. + notify(value: any): void; - * finally returns a promise, which will become resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise returned from callback is finished. - */ - finally(finallyCallback: () => any): Promise; + makeNodeResolver(): (reason: any, value: T) => void; + } - /** - * The then method from the Promises/A+ specification, with an additional progress handler. - */ - then(onFulfill?: (value: T) => IWhenable, onReject?: (error: any) => IWhenable, onProgress?: Function): Promise; + export interface Promise { + /** + * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources + * regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. finally returns a promise, which will become + * resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise + * returned from callback is finished. + */ + fin(finallyCallback: () => any): Promise; - /** - * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection reason. - * - * This is especially useful in conjunction with all - */ - spread(onFulfill: (...args: any[]) => IWhenable, onReject?: (reason: any) => IWhenable): Promise; + /** + * Like a finally clause, allows you to observe either the fulfillment or rejection of a promise, but to do so without modifying the final value. This is useful for collecting resources + * regardless of whether a job succeeded, like closing a database connection, shutting a server down, or deleting an unneeded key from an object. finally returns a promise, which will become + * resolved with the same fulfillment value or rejection reason as promise. However, if callback returns a promise, the resolution of the returned promise will be delayed until the promise + * returned from callback is finished. + */ + finally(finallyCallback: () => any): Promise; - fail(onRejected: (reason: any) => IWhenable): Promise; + /** + * The then method from the Promises/A+ specification, with an additional progress handler. + */ + then(onFulfill?: (value: T) => IWhenable, onReject?: (error: any) => IWhenable, onProgress?: (progress: any) => any): Promise; - /** - * A sugar method, equivalent to promise.then(undefined, onRejected). - */ - catch(onRejected: (reason: any) => IWhenable): Promise; + /** + * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's + * rejection reason. + * + * This is especially useful in conjunction with all + */ + spread(onFulfill: (...args: any[]) => IWhenable, onReject?: (reason: any) => IWhenable): Promise; - /** - * A sugar method, equivalent to promise.then(undefined, undefined, onProgress). - */ - progress(onProgress: (progress: any) => any): Promise; + fail(onRejected: (reason: any) => IWhenable): Promise; - /** - * Much like then, but with different behavior around unhandled rejection. If there is an unhandled rejection, either because promise is rejected and no onRejected callback was provided, or because onFulfilled or onRejected threw an error or returned a rejected promise, the resulting rejection reason is thrown as an exception in a future turn of the event loop. - * - * This method should be used to terminate chains of promises that will not be passed elsewhere. Since exceptions thrown in then callbacks are consumed and transformed into rejections, exceptions at the end of the chain are easy to accidentally, silently ignore. By arranging for the exception to be thrown in a future turn of the event loop, so that it won't be caught, it causes an onerror event on the browser window, or an uncaughtException event on Node.js's process object. - * - * Exceptions thrown by done will have long stack traces, if Q.longStackSupport is set to true. If Q.onerror is set, exceptions will be delivered there instead of thrown in a future turn. - * - * The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. - */ - done(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any, onProgress?: (progress: any) => any): void; + /** + * A sugar method, equivalent to promise.then(undefined, onRejected). + */ + catch(onRejected: (reason: any) => IWhenable): Promise; - /** - * If callback is a function, assumes it's a Node.js-style callback, and calls it as either callback(rejectionReason) when/if promise becomes rejected, or as callback(null, fulfillmentValue) when/if promise becomes fulfilled. If callback is not a function, simply returns promise. - */ - nodeify(callback: (reason: any, value: any) => void): Promise; + /** + * A sugar method, equivalent to promise.then(undefined, undefined, onProgress). + */ + progress(onProgress: (progress: any) => any): Promise; - /** - * Returns a promise to get the named property of an object. Essentially equivalent to - * - * promise.then(function (o) { - * return o[propertyName]; - * }); - */ - get(propertyName: String): Promise; - set(propertyName: String, value: any): Promise; - delete(propertyName: String): Promise; - /** - * Returns a promise for the result of calling the named method of an object with the given array of arguments. The object itself is this in the function, just like a synchronous method call. Essentially equivalent to - * - * promise.then(function (o) { - * return o[methodName].apply(o, args); - * }); - */ - post(methodName: String, args: any[]): Promise; - /** - * Returns a promise for the result of calling the named method of an object with the given variadic arguments. The object itself is this in the function, just like a synchronous method call. - */ - invoke(methodName: String, ...args: any[]): Promise; - fapply(args: any[]): Promise; - fcall(...args: any[]): Promise; + /** + * Much like then, but with different behavior around unhandled rejection. If there is an unhandled rejection, either because promise is rejected and no onRejected callback was provided, or + * because onFulfilled or onRejected threw an error or returned a rejected promise, the resulting rejection reason is thrown as an exception in a future turn of the event loop. + * + * This method should be used to terminate chains of promises that will not be passed elsewhere. Since exceptions thrown in then callbacks are consumed and transformed into rejections, + * exceptions at the end of the chain are easy to accidentally, silently ignore. By arranging for the exception to be thrown in a future turn of the event loop, so that it won't be caught, it + * causes an onerror event on the browser window, or an uncaughtException event on Node.js's process object. + * + * Exceptions thrown by done will have long stack traces, if Q.longStackSupport is set to true. If Q.onerror is set, exceptions will be delivered there instead of thrown in a future turn. + * + * The Golden Rule of done vs. then usage is: either return your promise to someone else, or if the chain ends with you, call done to terminate it. + */ + done(onFulfilled?: (value: T) => any, onRejected?: (reason: any) => any, onProgress?: (progress: any) => any): void; - /** - * Returns a promise for an array of the property names of an object. Essentially equivalent to - * - * promise.then(function (o) { - * return Object.keys(o); - * }); - */ - keys(): Promise; + /** + * If callback is a function, assumes it's a Node.js-style callback, and calls it as either callback(rejectionReason) when/if promise becomes rejected, or as callback(null, fulfillmentValue) + * when/if promise becomes fulfilled. If callback is not a function, simply returns promise. + */ + nodeify(callback: (reason: any, value: any) => void): Promise; - /** - * A sugar method, equivalent to promise.then(function () { return value; }). - */ - thenResolve(value: U): Promise; - /** - * A sugar method, equivalent to promise.then(function () { throw reason; }). - */ - thenReject(reason: any): Promise; + /** + * Returns a promise to get the named property of an object. Essentially equivalent to + * + * @example + * promise.then(function (o) { return o[propertyName]; }); + */ + get(propertyName: string): Promise; - /** - * Attaches a handler that will observe the value of the promise when it becomes fulfilled, returning a promise for that same value, perhaps deferred but not replaced by the promise returned by the onFulfilled handler. - */ - tap(onFulfilled: (value: T) => any): Promise; + set(propertyName: string, value: any): Promise; - timeout(ms: number, message?: string): Promise; - /** - * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. - */ - delay(ms: number): Promise; + delete(propertyName: string): Promise; - /** - * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. - */ - isFulfilled(): boolean; - /** - * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. - */ - isRejected(): boolean; - /** - * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. - */ - isPending(): boolean; + /** + * Returns a promise for the result of calling the named method of an object with the given array of arguments. The object itself is this in the function, just like a synchronous method call. + * Essentially equivalent to + * + * @example + * promise.then(function (o) { return o[methodName].apply(o, args); }); + */ + post(methodName: string, args: any[]): Promise; - valueOf(): any; + /** + * Returns a promise for the result of calling the named method of an object with the given variadic arguments. The object itself is this in the function, just like a synchronous method call. + */ + invoke(methodName: string, ...args: any[]): Promise; - /** - * Returns a "state snapshot" object, which will be in one of three forms: - * - * - { state: "pending" } - * - { state: "fulfilled", value: } - * - { state: "rejected", reason: } - */ - inspect(): PromiseState; - } + fapply(args: any[]): Promise; - export interface PromiseState { - state: "fulfilled" | "rejected" | "pending"; - value?: T; - reason?: any; - } + fcall(...args: any[]): Promise; - // If no value provided, returned promise will be of void type - export function when(): Promise; + /** + * Returns a promise for an array of the property names of an object. Essentially equivalent to + * + * @example + * promise.then(function (o) { return Object.keys(o); }); + */ + keys(): Promise; - // if no fulfill, reject, or progress provided, returned promise will be of same type - export function when(value: IWhenable): Promise; + /** + * A sugar method, equivalent to promise.then(function () { return value; }). + */ + thenResolve(value: U): Promise; - // If a non-promise value is provided, it will not reject or progress - export function when(value: IWhenable, onFulfilled: (val: T) => IWhenable, onRejected?: (reason: any) => IWhenable, onProgress?: (progress: any) => any): Promise; + /** + * A sugar method, equivalent to promise.then(function () { throw reason; }). + */ + thenReject(reason: any): Promise; - function _try(method: Function, ...args: any[]): Promise; - export { _try as try }; + /** + * Attaches a handler that will observe the value of the promise when it becomes fulfilled, returning a promise for that same value, perhaps deferred but not replaced by the promise returned + * by the onFulfilled handler. + */ + tap(onFulfilled: (value: T) => any): Promise; - export function fbind(method: (...args: any[]) => IWhenable, ...args: any[]): (...args: any[]) => Promise; + timeout(ms: number, message?: string): Promise; - export function fcall(method: (...args: any[]) => T, ...args: any[]): Promise; + /** + * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. + */ + delay(ms: number): Promise; - export function send(obj: any, functionName: string, ...args: any[]): Promise; - export function invoke(obj: any, functionName: string, ...args: any[]): Promise; - export function mcall(obj: any, functionName: string, ...args: any[]): Promise; + /** + * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. + */ + isFulfilled(): boolean; - export function denodeify(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; - export function nbind(nodeFunction: Function, thisArg: any, ...args: any[]): (...args: any[]) => Promise; - export function nfbind(nodeFunction: Function, ...args: any[]): (...args: any[]) => Promise; - export function nfcall(nodeFunction: Function, ...args: any[]): Promise; - export function nfapply(nodeFunction: Function, args: any[]): Promise; + /** + * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. + */ + isRejected(): boolean; - export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Promise; - export function npost(nodeModule: any, functionName: string, args: any[]): Promise; - export function nsend(nodeModule: any, functionName: string, ...args: any[]): Promise; - export function nmcall(nodeModule: any, functionName: string, ...args: any[]): Promise; + /** + * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. + */ + isPending(): boolean; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D, E, F]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D, E]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable<[IPromise, IPromise]>): Promise<[A, B]>; - export function all(promises: IWhenable<[A, IPromise]>): Promise<[A, B]>; - export function all(promises: IWhenable<[IPromise, B]>): Promise<[A, B]>; - export function all(promises: IWhenable<[A, B]>): Promise<[A, B]>; - /** - * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. - */ - export function all(promises: IWhenable[]>): Promise; + valueOf(): any; - /** - * Returns a promise for the first of an array of promises to become settled. - */ - export function race(promises: IWhenable[]): Promise; + /** + * Returns a "state snapshot" object, which will be in one of three forms: + * + * - { state: "pending" } + * - { state: "fulfilled", value: } + * - { state: "rejected", reason: } + */ + inspect(): PromiseState; + } - /** - * Returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected. - */ - export function allSettled(promises: IWhenable[]>): Promise[]>; + export interface PromiseState { + state: "fulfilled" | "rejected" | "pending"; + value?: T; + reason?: any; + } - export function allResolved(promises: IWhenable[]>): Promise[]>; + // If no value provided, returned promise will be of void type + export function when(): Promise; - /** - * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection reason. - * This is especially useful in conjunction with all. - */ - export function spread(promises: IWhenable[], onFulfilled: (...args: T[]) => IWhenable, onRejected?: (reason: any) => IWhenable): Promise; + // if no fulfill, reject, or progress provided, returned promise will be of same type + export function when(value: IWhenable): Promise; - /** - * Returns a promise that will have the same result as promise, except that if promise is not fulfilled or rejected before ms milliseconds, the returned promise will be rejected with an Error with the given message. If message is not supplied, the message will be "Timed out after " + ms + " ms". - */ - export function timeout(promise: Promise, ms: number, message?: string): Promise; + // If a non-promise value is provided, it will not reject or progress + export function when(value: IWhenable, onFulfilled: (val: T) => IWhenable, onRejected?: (reason: any) => IWhenable, onProgress?: (progress: any) => any): Promise; - /** - * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. - */ - export function delay(promise: Promise, ms: number): Promise; - /** - * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. - */ - export function delay(value: T, ms: number): Promise; - /** - * Returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed. - */ - export function delay(ms: number): Promise ; - /** - * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. - */ - export function isFulfilled(promise: Promise): boolean; - /** - * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. - */ - export function isRejected(promise: Promise): boolean; - /** - * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. - */ - export function isPending(promise: Promise): boolean; + export function fbind(method: (...args: any[]) => IWhenable, ...args: any[]): (...args: any[]) => Promise; - /** - * Returns a "deferred" object with a: - * promise property - * resolve(value) method - * reject(reason) method - * notify(value) method - * makeNodeResolver() method - */ - export function defer(): Deferred; + export function fcall(method: (...args: any[]) => T, ...args: any[]): Promise; - /** - * Returns a promise that is rejected with reason. - */ - export function reject(reason?: any): Promise; + // Try is an alias for fcall, but 'try' is a reserved word. This is the only way to get around this + export {fcall as try}; - export function Promise(resolver: (resolve: (val: IWhenable) => void , reject: (reason: any) => void , notify: (progress: any) => void ) => void ): Promise; + export function send(obj: any, functionName: string, ...args: any[]): Promise; - /** - * Creates a new version of func that accepts any combination of promise and non-promise values, converting them to their fulfillment values before calling the original func. The returned version also always returns a promise: if func does a return or throw, then Q.promised(func) will return fulfilled or rejected promise, respectively. - * - * This can be useful for creating functions that accept either promises or non-promise values, and for ensuring that the function always returns a promise even in the face of unintentional thrown exceptions. - */ - export function promised(callback: (...args: any[]) => T): (...args: any[]) => Promise; + export function invoke(obj: any, functionName: string, ...args: any[]): Promise; - /** - * Returns whether the given value is a Q promise. - */ - export function isPromise(object: any): boolean; - /** - * Returns whether the given value is a promise (i.e. it's an object with a then function). - */ - export function isPromiseAlike(object: any): boolean; - /** - * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. - */ - export function isPending(object: any): boolean; - /** - * If an object is not a promise, it is as "near" as possible. - * If a promise is rejected, it is as "near" as possible too. - * If it’s a fulfilled promise, the fulfillment value is nearer. - * If it’s a deferred promise and the deferred has been resolved, the - * resolution is "nearer". - */ - export function nearer(promise: Promise): T; + export function mcall(obj: any, functionName: string, ...args: any[]): Promise; - /** - * This is an experimental tool for converting a generator function into a deferred function. This has the potential of reducing nested callbacks in engines that support yield. - */ - export function async(generatorFunction: any): (...args: any[]) => Promise; - export function nextTick(callback: Function): void; + export function denodeify(nodeFunction: (...args: any[]) => any, ...args: any[]): (...args: any[]) => Promise; - /** - * A settable property that will intercept any uncaught errors that would otherwise be thrown in the next tick of the event loop, usually as a result of done. Can be useful for getting the full stack trace of an error in browsers, which is not usually possible with window.onerror. - */ - export var onerror: (reason: any) => void; - /** - * A settable property that lets you turn on long stack trace support. If turned on, "stack jumps" will be tracked across asynchronous promise operations, so that if an uncaught error is thrown by done or a rejection reason's stack property is inspected in a rejection callback, a long stack trace is produced. - */ - export var longStackSupport: boolean; + export function nbind(nodeFunction: (...args: any[]) => any, thisArg: any, ...args: any[]): (...args: any[]) => Promise; - /** - * Calling resolve with a pending promise causes promise to wait on the passed promise, becoming fulfilled with its fulfillment value or rejected with its rejection reason (or staying pending forever, if the passed promise does). - * Calling resolve with a rejected promise causes promise to be rejected with the passed promise's rejection reason. - * Calling resolve with a fulfilled promise causes promise to be fulfilled with the passed promise's fulfillment value. - * Calling resolve with a non-promise value causes promise to be fulfilled with that value. - */ - export function resolve(object: IWhenable): Promise; + export function nfbind(nodeFunction: (...args: any[]) => any, ...args: any[]): (...args: any[]) => Promise; + + export function nfcall(nodeFunction: (...args: any[]) => any, ...args: any[]): Promise; + + export function nfapply(nodeFunction: (...args: any[]) => any, args: any[]): Promise; + + export function ninvoke(nodeModule: any, functionName: string, ...args: any[]): Promise; + + export function npost(nodeModule: any, functionName: string, args: any[]): Promise; + + export function nsend(nodeModule: any, functionName: string, ...args: any[]): Promise; + + export function nmcall(nodeModule: any, functionName: string, ...args: any[]): Promise; + + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D, E, F]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D, E]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C, D]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IWhenable, IWhenable, IWhenable]>): Promise<[A, B, C]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable<[IPromise, IPromise]>): Promise<[A, B]>; + export function all(promises: IWhenable<[A, IPromise]>): Promise<[A, B]>; + export function all(promises: IWhenable<[IPromise, B]>): Promise<[A, B]>; + export function all(promises: IWhenable<[A, B]>): Promise<[A, B]>; + /** + * Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected. + */ + export function all(promises: IWhenable>>): Promise; + + /** + * Returns a promise for the first of an array of promises to become settled. + */ + export function race(promises: Array>): Promise; + + /** + * Returns a promise that is fulfilled with an array of promise state snapshots, but only after all the original promises have settled, i.e. become either fulfilled or rejected. + */ + export function allSettled(promises: IWhenable>>): Promise>>; + + export function allResolved(promises: IWhenable>>): Promise>>; + + /** + * Like then, but "spreads" the array into a variadic fulfillment handler. If any of the promises in the array are rejected, instead calls onRejected with the first rejected promise's rejection + * reason. This is especially useful in conjunction with all. + */ + export function spread(promises: Array>, onFulfilled: (...args: T[]) => IWhenable, onRejected?: (reason: any) => IWhenable): Promise; + + /** + * Returns a promise that will have the same result as promise, except that if promise is not fulfilled or rejected before ms milliseconds, the returned promise will be rejected with an Error + * with the given message. If message is not supplied, the message will be "Timed out after " + ms + " ms". + */ + export function timeout(promise: Promise, ms: number, message?: string): Promise; + + /** + * Returns a promise that will have the same result as promise, but will only be fulfilled or rejected after at least ms milliseconds have passed. + */ + export function delay(promiseOrValue: Promise | T, ms: number): Promise; + /** + * Returns a promise that will be fulfilled with undefined after at least ms milliseconds have passed. + */ + export function delay(ms: number): Promise; + + /** + * Returns whether a given promise is in the fulfilled state. When the static version is used on non-promises, the result is always true. + */ + export function isFulfilled(promise: Promise): boolean; + + /** + * Returns whether a given promise is in the rejected state. When the static version is used on non-promises, the result is always false. + */ + export function isRejected(promise: Promise): boolean; + + /** + * Returns whether a given promise is in the pending state. When the static version is used on non-promises, the result is always false. + */ + export function isPending(promiseOrObject: Promise | any): boolean; + + /** + * Returns a "deferred" object with a: + * promise property + * resolve(value) method + * reject(reason) method + * notify(value) method + * makeNodeResolver() method + */ + export function defer(): Deferred; + + /** + * Returns a promise that is rejected with reason. + */ + export function reject(reason?: any): Promise; + + export function Promise(resolver: (resolve: (val?: IWhenable) => void, reject: (reason: any) => void, notify: (progress: any) => void) => void): Promise; + + /** + * Creates a new version of func that accepts any combination of promise and non-promise values, converting them to their fulfillment values before calling the original func. The returned version + * also always returns a promise: if func does a return or throw, then Q.promised(func) will return fulfilled or rejected promise, respectively. + * + * This can be useful for creating functions that accept either promises or non-promise values, and for ensuring that the function always returns a promise even in the face of unintentional + * thrown exceptions. + */ + export function promised(callback: (...args: any[]) => T): (...args: any[]) => Promise; + + /** + * Returns whether the given value is a Q promise. + */ + export function isPromise(object: any): boolean; + + /** + * Returns whether the given value is a promise (i.e. it's an object with a then function). + */ + export function isPromiseAlike(object: any): boolean; + + /** + * If an object is not a promise, it is as "near" as possible. + * If a promise is rejected, it is as "near" as possible too. + * If it’s a fulfilled promise, the fulfillment value is nearer. + * If it’s a deferred promise and the deferred has been resolved, the + * resolution is "nearer". + */ + export function nearer(promise: Promise): T; + + /** + * This is an experimental tool for converting a generator function into a deferred function. This has the potential of reducing nested callbacks in engines that support yield. + */ + export function async(generatorFunction: any): (...args: any[]) => Promise; + + export function nextTick(callback: (...args: any[]) => any): void; + + /** + * A settable property that will intercept any uncaught errors that would otherwise be thrown in the next tick of the event loop, usually as a result of done. Can be useful for getting the full + * stack trace of an error in browsers, which is not usually possible with window.onerror. + */ + export let onerror: (reason: any) => void; + /** + * A settable property that lets you turn on long stack trace support. If turned on, "stack jumps" will be tracked across asynchronous promise operations, so that if an uncaught error is thrown + * by done or a rejection reason's stack property is inspected in a rejection callback, a long stack trace is produced. + */ + export let longStackSupport: boolean; + + /** + * Calling resolve with a pending promise causes promise to wait on the passed promise, becoming fulfilled with its fulfillment value or rejected with its rejection reason (or staying pending + * forever, if the passed promise does). Calling resolve with a rejected promise causes promise to be rejected with the passed promise's rejection reason. Calling resolve with a fulfilled promise + * causes promise to be fulfilled with the passed promise's fulfillment value. Calling resolve with a non-promise value causes promise to be fulfilled with that value. + */ + export function resolve(object?: IWhenable): Promise; /** * Resets the global "Q" variable to the value it has before Q was loaded. diff --git a/types/q/q-tests.ts b/types/q/q-tests.ts index 5acb354c80..3a5c125f25 100644 --- a/types/q/q-tests.ts +++ b/types/q/q-tests.ts @@ -1,24 +1,24 @@ +/* tslint:disable:no-namespace */ /// - import Q = require('q'); Q(8).then(x => console.log(x.toExponential())); Q().then(() => console.log("nothing")); -var delay = function (delay: number) { - var d = Q.defer(); - setTimeout(d.resolve, delay); - return d.promise; +const delay = (delay: number) => { + let d = Q.defer(); + setTimeout(d.resolve, delay); + return d.promise; }; -Q.when(delay(1000), function (val: void) { - console.log('Hello, World!'); - return; +Q.when(delay(1000), (val) => { + console.log('Hello, World!'); + return; }); // Note from Q documentation: a deferred can be resolved with a value or a promise. -var otherPromise = Q.defer().promise; +const otherPromise = Q.defer().promise; Q.defer().resolve(otherPromise); Q.timeout(Q(new Date()), 1000, "My dates never arrived. :(").then(d => d.toJSON()); @@ -28,75 +28,79 @@ Q.delay(8, 1000).then(x => x.toExponential()); Q.delay(Q("asdf"), 1000).then(x => x.length); Q.delay("asdf", 1000).then(x => x.length); -var eventualAdd = Q.promised((a?: number, b?: number) => a + b); +const eventualAdd = Q.promised((a?: number, b?: number) => a + b); eventualAdd(Q(1), Q(2)).then(x => x.toExponential()); function eventually(eventually: T) { - return Q.delay(eventually, 1000); -}; + return Q.delay(eventually, 1000); +} -var x = Q.all([1, 2, 3].map(eventually)); -Q.when(x, function (x) { - console.log(x); +const x = Q.all([1, 2, 3].map(eventually)); +Q.when(x, (x) => { + console.log(x); }); Q.all([ - eventually(10), - eventually(20) -]).spread(function (x: number, y: number) { - console.log(x, y); + eventually(10), + eventually(20) +]).spread((x: number, y: number) => { + console.log(x, y); }); Q.all([ - eventually(10), - eventually(20) -]).then(function (results) { - let [x, y] = results; - console.log(x, y); + eventually(10), + eventually(20) +]).then((results) => { + let [x, y] = results; + console.log(x, y); }); - -Q.fcall(function () { }) - .then(function () { }) - .then(function () { }) - .then(function () { }) - .then(function (value4) { - // Do something with value4 - }, function (error) { - // Handle any error from step1 through step4 - }).done(); +Q.fcall(() => { +}) + .then(() => { + }) + .then(() => { + }) + .then(() => { + }) + .then((value4) => { + // Do something with value4 + }, (error) => { + // Handle any error from step1 through step4 + }).done(); Q.allResolved([]) -.then(function (promises: Q.Promise[]) { - promises.forEach(function (promise) { - if (promise.isFulfilled()) { - var value = promise.valueOf(); - } else { - var exception = promise.valueOf().exception; - } - }) -}); + .then((promises: Array>) => { + promises.forEach((promise) => { + if (promise.isFulfilled()) { + let value = promise.valueOf(); + } else { + let exception = promise.valueOf().exception; + } + }); + }); Q(42) - .tap(() => "hello") - .tap(x => { - console.log(x); - }) - .then(x => { - console.log("42 == " + x); - }); + .tap(() => "hello") + .tap(x => { + console.log(x); + }) + .then(x => { + console.log("42 == " + x); + }); + +declare let arrayPromise: Q.IPromise; +declare let stringPromise: Q.IPromise; -declare var arrayPromise: Q.IPromise; -declare var stringPromise: Q.IPromise; declare function returnsNumPromise(text: string): Q.Promise; declare function returnsNumPromise(text: string): JQueryPromise; Q(arrayPromise) // type specification required - .then(arr => arr.join(',')) - .then(returnsNumPromise) // requires specification - .then(num => num.toFixed()); + .then(arr => arr.join(',')) + .then(returnsNumPromise) // requires specification + .then(num => num.toFixed()); -declare var jPromise: JQueryPromise; +declare let jPromise: JQueryPromise; // if jQuery promises definition supported generics, this could be more interesting example Q(jPromise).then(str => str.split(',')); @@ -105,9 +109,11 @@ jPromise.then(returnsNumPromise); // watch the typing flow through from jQueryPromise to Q.Promise Q(jPromise).then(str => str.split(',')); -declare var promiseArray: Q.IPromise[]; -var qPromiseArray = promiseArray.map(p => Q(p)); -var myNums: any[] = [2, 3, Q(4), 5, Q(6), Q(7)]; +declare let promiseArray: Array>; +const qPromiseArray = promiseArray.map(p => { + return Q(p); +}); +const myNums: any[] = [2, 3, Q(4), 5, Q(6), Q(7)]; Q.all(promiseArray).then(nums => nums.map(num => num.toPrecision(2)).join(',')); @@ -117,121 +123,116 @@ Q.fbind((dateString?: string) => new Date(dateString), "11/11/1991")().then(d => Q.when(8, num => num + "!"); Q.when(Q(8), num => num + "!").then(str => str.split(',')); -var voidPromise: Q.Promise = Q.when(); +const voidPromise: Q.Promise = Q.when(); declare function saveToDisk(): Q.Promise; -declare function saveToCloud(): Q.Promise; -Q.allSettled([saveToDisk(), saveToCloud()]).spread(function (disk: any, cloud: any) { - console.log("saved to disk:", disk.state === "fulfilled"); - console.log("saved to cloud:", cloud.state === "fulfilled"); - if (disk.state === "fulfilled") { - console.log("value was " + disk.value); - } - else if (disk.state === "rejected") { - console.log("rejected because " + disk.reason); - } +declare function saveToCloud(): Q.Promise; + +Q.allSettled([saveToDisk(), saveToCloud()]).spread((disk: any, cloud: any) => { + console.log("saved to disk:", disk.state === "fulfilled"); + console.log("saved to cloud:", cloud.state === "fulfilled"); + + if (disk.state === "fulfilled") { + console.log("value was " + disk.value); + } else if (disk.state === "rejected") { + console.log("rejected because " + disk.reason); + } }).done(); -var nodeStyle = (input: string, cb: Function) => { - cb(null, input); +const nodeStyle = (input: string, cb: (error: any, success: any) => void) => { + cb(null, input); }; -Q.nfapply(nodeStyle, ["foo"]).done((result: string) => {}); -Q.nfcall(nodeStyle, "foo").done((result: string) => {}); -Q.denodeify(nodeStyle)('foo').done((result: string) => {}); -Q.nfbind(nodeStyle)('foo').done((result: string) => {}); - +Q.nfapply(nodeStyle, ["foo"]).done((result: string) => { +}); +Q.nfcall(nodeStyle, "foo").done((result: string) => { +}); +Q.denodeify(nodeStyle)('foo').done((result: string) => { +}); +Q.nfbind(nodeStyle)('foo').done((result: string) => { +}); class Repo { - private items: any[] = [ - { name: 'Max', cute: false }, - { name: 'Annie', cute: true } - ]; + private items: any[] = [ + {name: 'Max', cute: false}, + {name: 'Annie', cute: true} + ]; - find(options: any): Q.Promise { - var result = this.items; + find(options: any): Q.Promise { + let result = this.items; - for (var key in options) { - result = result.filter(i => i[key] == options[key]); - } + for (let key in options) { + result = result.filter(i => i[key] === options[key]); + } - return Q(result); - } + return Q(result); + } } -var kitty = new Repo(); -Q.nbind(kitty.find, kitty)({ cute: true }).done((kitties: any[]) => {}); +const kitty = new Repo(); +Q.nbind(kitty.find, kitty)({cute: true}).done((kitties: any[]) => { +}); - -/* +/** * Test: Can "rethrow" rejected promises */ namespace TestCanRethrowRejectedPromises { + interface Foo { + a: number; + } - interface Foo { - a: number; - } + function nestedBar(): Q.Promise { + let deferred = Q.defer(); - function nestedBar(): Q.Promise { - var deferred = Q.defer(); + return deferred.promise; + } - return deferred.promise; - } + function bar(): Q.Promise { + return nestedBar() + .then((foo: Foo) => { + console.log("Lorem ipsum"); + }) + .fail((error) => { + console.log("Intermediate error handling"); - function bar(): Q.Promise { - return nestedBar() - .then((foo:Foo) => { - console.log("Lorem ipsum"); - }) - .fail((error) => { - console.log("Intermediate error handling"); - - /* - * Cannot do this, because: - * error TS2322: Type 'Promise' is not assignable to type 'Promise' - */ - //throw error; - - return Q.reject(error); - }) - ; - } - - bar() - .finally(() => { - console.log("Cleanup") - }) - .done() - ; + /* + * Cannot do this, because: + * error TS2322: Type 'Promise' is not assignable to type 'Promise' + */ + return Q.reject(error); + }); + } + bar() + .finally(() => { + console.log("Cleanup"); + }) + .done(); } // test Q.Promise.all -var y1 = Q().then(() => { - var s = Q("hello"); - var n = Q(1); - return <[typeof s, typeof n]>[s, n]; +const y1 = Q().then(() => { + let s = Q("hello"); + let n = Q(1); + return <[typeof s, typeof n]> [s, n]; }); -var y2 = Q().then(() => { - var s = "hello"; - var n = Q(1); - return <[typeof s, typeof n]>[s, n]; +const y2 = Q().then(() => { + let s = "hello"; + let n = Q(1); + return <[typeof s, typeof n]> [s, n]; }); -var p2: Q.Promise<[string, number]> = y1.then(val => Q.all(val)); -var p3: Q.Promise<[string, number]> = Q.all(y1); -var p5: Q.Promise<[string, number]> = y2.then(val => Q.all(val)); -var p6: Q.Promise<[string, number]> = Q.all(y2); +const p2: Q.Promise<[string, number]> = y1.then(val => Q.all(val)); +const p3: Q.Promise<[string, number]> = Q.all(y1); +const p5: Q.Promise<[string, number]> = y2.then(val => Q.all(val)); +const p6: Q.Promise<[string, number]> = Q.all(y2); - -Q.try(function () { - if (Math.random() % 2) { - throw new Error("The cloud is down!"); - } - return true; +Q.try(() => { + if (Math.random() % 2) { + throw new Error("The cloud is down!"); + } + return true; }) -.catch(function (error) { - console.error("Couldn't sync to the cloud", error); -}); + .catch((error) => console.error("Couldn't sync to the cloud", error)); diff --git a/types/q/tsconfig.json b/types/q/tsconfig.json index ec30c7c1c5..12c105d622 100644 --- a/types/q/tsconfig.json +++ b/types/q/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "q-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/q/tslint.json b/types/q/tslint.json new file mode 100644 index 0000000000..f4bf4b2db5 --- /dev/null +++ b/types/q/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "prefer-declare-function": false, + "strict-export-declare-modifiers": false, + "unified-signatures": false + } +} From 6310159eb6ce25ab5e51454cfde70bdc17774d3a Mon Sep 17 00:00:00 2001 From: paranoidjk Date: Fri, 21 Jul 2017 10:42:43 +0800 Subject: [PATCH 0218/1139] fix(ReactNative): ScrollView.props.style definition error --- types/react-native/index.d.ts | 2 +- types/react-native/test/index.tsx | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index e8e9eca55c..f2e5c8127b 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -6065,7 +6065,7 @@ export interface ScrollViewProperties extends ViewProperties, ScrollViewProperti /** * Style */ - style?: ScrollViewStyle | Array + style?: StyleProp /** * A RefreshControl component, used to provide pull-to-refresh diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 954402f23c..5cf036d433 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -244,6 +244,14 @@ export class CapsLockComponent extends React.Component { class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListViewDataSource}> { render() { + const scrollViewStyle1 = StyleSheet.create({ + scrollView: { + backgroundColor: 'red', + }, + }); + const scrollViewStyle2 = { + flex: 1 + }; return ( { @@ -251,7 +259,7 @@ class ScrollerListComponentTest extends React.Component<{}, { dataSource: ListVi throw new Error("Expected scroll to be enabled.") } - return + return }} renderRow={({ type, data }, _, row: number) => { return Filler From 64099f0b4cb876893dcd2dcffc6b523209516bae Mon Sep 17 00:00:00 2001 From: dyst5422 Date: Mon, 24 Jul 2017 08:43:11 -0700 Subject: [PATCH 0219/1139] fix(point-in-polygon): Fixed point-in-polygon type declaration (#18069) * fix(point-in-polygon): Fixed point-in-polygon type declaration The export format of point-in-polygon did not match the type declaration format. * Fixed removed definition author --- types/point-in-polygon/index.d.ts | 6 ++++-- types/point-in-polygon/point-in-polygon-tests.ts | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/types/point-in-polygon/index.d.ts b/types/point-in-polygon/index.d.ts index ceb85ecdec..1a8919b7e1 100644 --- a/types/point-in-polygon/index.d.ts +++ b/types/point-in-polygon/index.d.ts @@ -1,8 +1,10 @@ // Type definitions for point-in-polygon // Project: https://github.com/substack/point-in-polygon -// Definitions by: kogai +// Definitions by: dyst5422 +// kogai // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'point-in-polygon' { - export default function inside(point: number[], polygon: number[][]): boolean; + const inside: (point: number[], polygon: number[][]) => boolean; + export = inside; } diff --git a/types/point-in-polygon/point-in-polygon-tests.ts b/types/point-in-polygon/point-in-polygon-tests.ts index 519b0a39d4..75fdc4ea18 100644 --- a/types/point-in-polygon/point-in-polygon-tests.ts +++ b/types/point-in-polygon/point-in-polygon-tests.ts @@ -1,4 +1,4 @@ -import inside from 'point-in-polygon'; +import * as inside from 'point-in-polygon'; const polygon = [ [ 1, 1 ], [ 1, 2 ], [ 2, 2 ], [ 2, 1 ] ]; const inPolygon: boolean = inside([ 1.5, 1.5 ], polygon); From 01924ef872642806278dff62f03f5ebca37594c5 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 24 Jul 2017 17:54:38 +0200 Subject: [PATCH 0220/1139] [promise.prototype.finally] add typings for the non-shim variant (#18114) * [promise.prototype.finally] add typings for the non-shim variant of promise.prototype.finally * [promise.prototype.finally] change indentation to 4 spaces * [promise.prototype.finally] fix lint error --- types/promise.prototype.finally/index.d.ts | 8 +++++++- .../promise.prototype.finally-tests.ts | 19 ++++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/types/promise.prototype.finally/index.d.ts b/types/promise.prototype.finally/index.d.ts index 5c4581ba46..a2db2ef22a 100644 --- a/types/promise.prototype.finally/index.d.ts +++ b/types/promise.prototype.finally/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for promise.prototype.finally 2.0 // Project: https://github.com/matthew-andrews/Promise.prototype.finally // Definitions by: Slava Shpitalny +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare global { @@ -9,4 +10,9 @@ declare global { } } -export function shim(): void; +export = promiseFinally; + +declare function promiseFinally(promise: Promise, onFinally?: () => U | PromiseLike): Promise; +declare namespace promiseFinally { + function shim(): void; +} diff --git a/types/promise.prototype.finally/promise.prototype.finally-tests.ts b/types/promise.prototype.finally/promise.prototype.finally-tests.ts index 2fa7c96512..bbbb2ce390 100644 --- a/types/promise.prototype.finally/promise.prototype.finally-tests.ts +++ b/types/promise.prototype.finally/promise.prototype.finally-tests.ts @@ -3,7 +3,7 @@ import promiseFinally = require('promise.prototype.finally'); promiseFinally.shim(); let promise = new Promise((resolve, reject) => { - resolve(true); + resolve(true); }); promise.finally(() => {}); @@ -13,3 +13,20 @@ promise.catch(() => {}).finally(() => {}); let allPromise = Promise.all([promise]); allPromise.finally(() => {}); + +const resolved = Promise.resolve(42); +const rejected = Promise.reject(-1); + +let num: number; +promiseFinally(resolved, () => Promise.resolve(true)) + .then(x => num = x); + +promiseFinally(resolved, () => > Promise.resolve(true)) + .then(x => num = x); + +promiseFinally(rejected, () => false) + .catch(e => num = e); + +let bool: boolean; +promiseFinally(rejected, () => {throw false; }) + .catch(e => bool = e); From 674bf789c477acd73d25ae13cc9c3b36b5ca1162 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 24 Jul 2017 17:55:35 +0200 Subject: [PATCH 0221/1139] [cucumber] add more specific typings for TableDefinition (#18131) --- types/cucumber/cucumber-tests.ts | 23 +++++++++++---------- types/cucumber/index.d.ts | 8 ++++---- types/cucumber/v1/cucumber-tests.ts | 31 ++++++++++++++++------------- types/cucumber/v1/index.d.ts | 8 ++++---- 4 files changed, 38 insertions(+), 32 deletions(-) diff --git a/types/cucumber/cucumber-tests.ts b/types/cucumber/cucumber-tests.ts index 53ca726230..e0ecc2bed9 100644 --- a/types/cucumber/cucumber-tests.ts +++ b/types/cucumber/cucumber-tests.ts @@ -62,7 +62,7 @@ function StepSample() { }); Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function (title: string, callback: Callback) { - var pageTitle = this.browser.text('title'); + const pageTitle = this.browser.text('title'); if (title === pageTitle) { callback(); @@ -75,38 +75,41 @@ function StepSample() { // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js Given(/^a table step with Table raw$/, function (table: Table) { - var expected = [ + const expected = [ ['Cucumber', 'Cucumis sativus'], ['Burr Gherkin', 'Cucumis anguria'] ]; - - assert.deepEqual(table.raw(), expected); + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); }); Given(/^a table step with Table rows$/, function (table: Table) { - var expected = [ + const expected = [ ['Apricot', '5'], ['Brocolli', '2'], ['Cucumber', '10'] ]; - assert.deepEqual(table.rows(), expected) + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); }); Given(/^a table step with Table rowHash$/, function (table: Table) { - var expected = { + const expected = { 'Cucumber': 'Cucumis sativus', 'Burr Gherkin': 'Cucumis anguria' }; - assert.deepEqual(table.rowsHash(), expected) + const actual: { [firstCol:string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); }); Given(/^a table step$/, function (table: Table) { - var expected = [ + const expected = [ {'Vegetable': 'Apricot', 'Rating': '5'}, {'Vegetable': 'Brocolli', 'Rating': '2'}, {'Vegetable': 'Cucumber', 'Rating': '10'} ]; - assert.deepEqual(table.hashes(), expected) + const actual: { [colName:string]: string }[] = table.hashes(); + assert.deepEqual(actual, expected); }); defineParameterType({ diff --git a/types/cucumber/index.d.ts b/types/cucumber/index.d.ts index 60e3d27d5d..635a594ae5 100644 --- a/types/cucumber/index.d.ts +++ b/types/cucumber/index.d.ts @@ -13,10 +13,10 @@ declare namespace cucumber { } export interface TableDefinition { - raw: () => Array; - rows: () => Array; - rowsHash: () => {}; - hashes: () => {}; + raw: () => Array>; + rows: () => Array>; + rowsHash: () => { [firstCol:string]: string }; + hashes: () => Array<{ [colName:string]: string }>; } type StepDefinitionParam = string | number | CallbackStepDefinition | TableDefinition; diff --git a/types/cucumber/v1/cucumber-tests.ts b/types/cucumber/v1/cucumber-tests.ts index 596772274f..347bec135b 100644 --- a/types/cucumber/v1/cucumber-tests.ts +++ b/types/cucumber/v1/cucumber-tests.ts @@ -5,17 +5,17 @@ function StepSample() { type Callback = cucumber.CallbackStepDefinition; type Table = cucumber.TableDefinition; type HookScenario = cucumber.HookScenario; - var step = this; - var hook = this; + const step = this; + const hook = this; hook.Before(function (scenario: HookScenario, callback: Callback) { scenario.isFailed() && callback.pending(); }); - + hook.Before({ timeout: 1000 }, function(scenario: HookScenario, callback: Callback) { callback(); }); - + hook.After({ timeout: 1000 }, function(scenario: HookScenario, callback: Callback) { callback(); }); @@ -39,7 +39,7 @@ function StepSample() { }); step.Then(/^I should see "(.*)" as the page title$/, {timeout: 60 * 1000}, function (title: string, callback: Callback) { - var pageTitle = this.browser.text('title'); + const pageTitle = this.browser.text('title'); if (title === pageTitle) { callback(); @@ -52,38 +52,41 @@ function StepSample() { // https://github.com/cucumber/cucumber-js/blob/a5fd8251918c278ab2e389226d165cedb44df14a/lib/cucumber/ast/data_table.js step.Given(/^a table step with Table raw$/, function (table: Table) { - var expected = [ + const expected = [ ['Cucumber', 'Cucumis sativus'], ['Burr Gherkin', 'Cucumis anguria'] ]; - - assert.deepEqual(table.raw(), expected); + const actual: string[][] = table.raw(); + assert.deepEqual(actual, expected); }); step.Given(/^a table step with Table rows$/, function (table: Table) { - var expected = [ + const expected = [ ['Apricot', '5'], ['Brocolli', '2'], ['Cucumber', '10'] ]; - assert.deepEqual(table.rows(), expected) + const actual: string[][] = table.rows(); + assert.deepEqual(actual, expected); }); step.Given(/^a table step with Table rowHash$/, function (table: Table) { - var expected = { + const expected = { 'Cucumber': 'Cucumis sativus', 'Burr Gherkin': 'Cucumis anguria' }; - assert.deepEqual(table.rowsHash(), expected) + const actual: { [firstCol:string]: string } = table.rowsHash(); + assert.deepEqual(actual, expected); }); step.Given(/^a table step$/, function (table: Table) { - var expected = [ + const expected = [ {'Vegetable': 'Apricot', 'Rating': '5'}, {'Vegetable': 'Brocolli', 'Rating': '2'}, {'Vegetable': 'Cucumber', 'Rating': '10'} ]; - assert.deepEqual(table.hashes(), expected) + const actual: { [colName:string]: string }[] = table.hashes(); + assert.deepEqual(actual, expected); }); } diff --git a/types/cucumber/v1/index.d.ts b/types/cucumber/v1/index.d.ts index bdf30d740d..39a915f935 100644 --- a/types/cucumber/v1/index.d.ts +++ b/types/cucumber/v1/index.d.ts @@ -13,10 +13,10 @@ declare namespace cucumber { } export interface TableDefinition { - raw: () => Array; - rows: () => Array; - rowsHash: () => {}; - hashes: () => {}; + raw: () => Array>; + rows: () => Array>; + rowsHash: () => { [firstCol:string]: string }; + hashes: () => Array<{ [colName:string]: string }>; } type StepDefinitionParam = string | CallbackStepDefinition | TableDefinition; From e41d2c543c86cc2bd887d86cb2ea18a2d8ec8e7d Mon Sep 17 00:00:00 2001 From: Sl1MBoy Date: Mon, 24 Jul 2017 17:56:01 +0200 Subject: [PATCH 0222/1139] Added UnauthorizedError class to @types/express-jwt. (#18137) * Added UnauthorizedError class. * Updated definition to match gridstack v0.3.0 * Revert "Updated definition to match gridstack v0.3.0" This reverts commit 2e1f194e68ffd914af08e1f6265cdc7ffb9f44f4. Commited to wrong branch --- types/express-jwt/express-jwt-tests.ts | 13 ++++++++++++- types/express-jwt/index.d.ts | 10 +++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/types/express-jwt/express-jwt-tests.ts b/types/express-jwt/express-jwt-tests.ts index 190c85ce4b..798818b728 100644 --- a/types/express-jwt/express-jwt-tests.ts +++ b/types/express-jwt/express-jwt-tests.ts @@ -17,4 +17,15 @@ var jwtCheck = jwt({ secret: 'shhhhhhared-secret' }); jwtCheck.unless = unless; -app.use(jwtCheck.unless({ path: '/api/login' })); \ No newline at end of file +app.use(jwtCheck.unless({ path: '/api/login' })); + +app.use(function (err: any, req: express.Request, res: express.Response, next: express.NextFunction) { + if (err) { + if (err instanceof jwt.UnauthorizedError) { + res.status(err.status); + res.end(); + } + } else { + next(err); + } +}); \ No newline at end of file diff --git a/types/express-jwt/index.d.ts b/types/express-jwt/index.d.ts index d75dfa9adf..ec7aeb64f7 100644 --- a/types/express-jwt/index.d.ts +++ b/types/express-jwt/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for express-jwt // Project: https://www.npmjs.org/package/express-jwt -// Definitions by: Wonshik Kim , Kacper Polak +// Definitions by: Wonshik Kim , Kacper Polak , Sl1MBoy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import express = require('express'); @@ -36,6 +36,14 @@ declare namespace jwt { export interface RequestHandler extends express.RequestHandler { unless: typeof unless; } + + export class UnauthorizedError extends Error { + name: string; + message: string; + code: string; + status: number; + inner: Error + } } declare global { namespace Express { From 84384b0417e1aed709437e4dd2f92d35e25b2904 Mon Sep 17 00:00:00 2001 From: sixinli Date: Mon, 24 Jul 2017 11:58:05 -0400 Subject: [PATCH 0223/1139] add support for AMD require (#18142) --- types/keypress/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/keypress/index.d.ts b/types/keypress/index.d.ts index 122095cd09..4f639fdb69 100644 --- a/types/keypress/index.d.ts +++ b/types/keypress/index.d.ts @@ -3,6 +3,13 @@ // Definitions by: Roger Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +declare var __keypress: Keypress.Keypress; + +// Support AMD require +declare module 'keypress.js' { + export = __keypress; +} + // A keyboard input capturing utility in which any key can be a modifier key. declare namespace Keypress { From 6333711213343973fd3a9dc49a30f96f0f24f758 Mon Sep 17 00:00:00 2001 From: Dave Parslow Date: Mon, 24 Jul 2017 09:20:10 -0700 Subject: [PATCH 0224/1139] Export the configuration interface (#18162) Added class for the server instead of interface Added TS lint file and fixed errors --- types/webpack-dev-server/index.d.ts | 92 +++++++++---------- types/webpack-dev-server/tslint.json | 1 + .../webpack-dev-server-tests.ts | 24 +++-- 3 files changed, 61 insertions(+), 56 deletions(-) create mode 100644 types/webpack-dev-server/tslint.json diff --git a/types/webpack-dev-server/index.d.ts b/types/webpack-dev-server/index.d.ts index 0e84e67eab..97f190aa28 100644 --- a/types/webpack-dev-server/index.d.ts +++ b/types/webpack-dev-server/index.d.ts @@ -1,54 +1,54 @@ -// Type definitions for webpack-dev-server 2.4.5 +// Type definitions for webpack-dev-server 2.4 // Project: https://github.com/webpack/webpack-dev-server // Definitions by: maestroh +// Dave Parslow // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare module "webpack-dev-server" { - import * as webpack from 'webpack'; - import * as core from 'express-serve-static-core'; - import * as serveStatic from 'serve-static'; - import * as http from 'http'; +import * as webpack from 'webpack'; +import * as core from 'express-serve-static-core'; +import * as serveStatic from 'serve-static'; +import * as http from 'http'; - namespace WebpackDevServer { - export interface Configuration { - contentBase?: string; - hot?: boolean; - https?: boolean; - historyApiFallback?: boolean; - compress?: boolean; - proxy?: any; - staticOptions?: any; - quiet?: boolean; - noInfo?: boolean; - lazy?: boolean; - filename?: string| RegExp; - watchOptions?: webpack.WatchOptions; - publicPath: string; - headers?: any; - stats?: webpack.compiler.StatsOptions| webpack.compiler.StatsToStringOptions; - public?: string; - disableHostCheck?: boolean; +declare namespace WebpackDevServer { + interface Configuration { + contentBase?: string; + hot?: boolean; + https?: boolean; + historyApiFallback?: boolean; + compress?: boolean; + proxy?: any; + staticOptions?: any; + quiet?: boolean; + noInfo?: boolean; + lazy?: boolean; + filename?: string| RegExp; + watchOptions?: webpack.WatchOptions; + publicPath: string; + headers?: any; + stats?: webpack.compiler.StatsOptions| webpack.compiler.StatsToStringOptions; + public?: string; + disableHostCheck?: boolean; - setup?(app: core.Express): void; - } - - export interface WebpackDevServer { - new ( - webpack: webpack.compiler.Compiler, - config: Configuration - ):WebpackDevServer; - - listen(port: number, - hostname: string, - callback?: Function - ): http.Server; - - listen(port: number, - callback?: Function - ): http.Server; - } + setup?(app: core.Express): void; } - var wds: WebpackDevServer.WebpackDevServer; +} - export = wds; -} \ No newline at end of file +declare class WebpackDevServer { + constructor( + webpack: webpack.compiler.Compiler, + config: WebpackDevServer.Configuration + ); + + listen( + port: number, + hostname: string, + callback?: (...args: any[]) => any + ): http.Server; + + listen( + port: number, + callback?: (...args: any[]) => any + ): http.Server; +} + +export = WebpackDevServer; diff --git a/types/webpack-dev-server/tslint.json b/types/webpack-dev-server/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/webpack-dev-server/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/webpack-dev-server/webpack-dev-server-tests.ts b/types/webpack-dev-server/webpack-dev-server-tests.ts index f4f81542a1..312372e76f 100644 --- a/types/webpack-dev-server/webpack-dev-server-tests.ts +++ b/types/webpack-dev-server/webpack-dev-server-tests.ts @@ -1,15 +1,16 @@ import * as webpack from 'webpack'; import * as WebpackDevServer from 'webpack-dev-server'; -var compiler = webpack({}); +import * as core from 'express-serve-static-core'; +let compiler = webpack({}); // basic example -var server = new WebpackDevServer(compiler, { +let server = new WebpackDevServer(compiler, { publicPath: "/assets/" }); server.listen(8080); -// API example -server = new WebpackDevServer(compiler, { +// Configuration can be used as a type +let config: WebpackDevServer.Configuration = { // webpack-dev-server options contentBase: "/path/to/directory", // or: contentBase: "http://localhost/", @@ -41,12 +42,12 @@ server = new WebpackDevServer(compiler, { "**": "http://localhost:9090" }, - setup: function (app) { + setup: (app: core.Express) => { // Here you can access the Express app object and add your own custom middleware to it. // For example, to define custom handlers for some paths: - // app.get('/some/path', function(req, res) { - // res.json({ custom: 'response' }); - // }); + app.get('/some/path', (req, res) => { + res.json({ custom: 'response' }); + }); }, // pass [static options](http://expressjs.com/en/4x/api.html#express.static) to inner express server @@ -66,5 +67,8 @@ server = new WebpackDevServer(compiler, { publicPath: "/assets/", headers: { "X-Custom-Header": "yes" }, stats: { colors: true } -}); -server.listen(8080, "localhost", function () { }); \ No newline at end of file +}; + +// API example +server = new WebpackDevServer(compiler, config); +server.listen(8080, "localhost", () => {}); From 67a886f023b53a4f36c4cb9157adace18f609e27 Mon Sep 17 00:00:00 2001 From: Thomas Barrera Date: Mon, 24 Jul 2017 13:59:52 -0300 Subject: [PATCH 0225/1139] Adding new overload for using methods (#18175) https://github.com/wenzhixin/bootstrap-table/blob/develop/docs/_i18n/en/documentation/methods.md --- types/bootstrap-table/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/bootstrap-table/index.d.ts b/types/bootstrap-table/index.d.ts index e70ada9e38..166289f14f 100644 --- a/types/bootstrap-table/index.d.ts +++ b/types/bootstrap-table/index.d.ts @@ -7,7 +7,8 @@ /// interface JQuery { - bootstrapTable(options?: any): JQuery; + bootstrapTable(options?: any): JQuery; + bootstrapTable(method: string, parameter?: any): JQuery; } declare var bootstrapTable: JQueryStatic; From 2fa3d94c92b4b49b1f362a431a494835b01b307d Mon Sep 17 00:00:00 2001 From: Daniel Espeset Date: Mon, 24 Jul 2017 13:03:04 -0400 Subject: [PATCH 0226/1139] Expands support for Esprima comments (#18182) Adds an optional `comments` field to the `Program`, which will be present if the AST is created with Esprima using the `{ comments: true }` option. Adds an optional `innerComments` field to `BlockStatement` which will be present if the AST is created with Esprima using the `{ attachComments: true }` option, given the following code: ```.js function foo(n) { // comments in an empty block are `innerComments` } ``` Note that though these fields are not specified in the ESTree specification they extend the support already present in this set of types for `trailingComments` and `leadingComments`, which are also unspecified. --- types/estree/index.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/types/estree/index.d.ts b/types/estree/index.d.ts index 64731a6895..23c5b19f86 100644 --- a/types/estree/index.d.ts +++ b/types/estree/index.d.ts @@ -58,6 +58,7 @@ export interface Program extends BaseNode { type: "Program"; sourceType: "script" | "module"; body: Array; + comments?: Array; } interface BaseFunction extends BaseNode { @@ -89,6 +90,7 @@ export interface EmptyStatement extends BaseStatement { export interface BlockStatement extends BaseStatement { type: "BlockStatement"; body: Array; + innerComments?: Array; } export interface ExpressionStatement extends BaseStatement { From dfeadbd5acc0b8437537e309809032b74c34d118 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 24 Jul 2017 19:04:09 +0200 Subject: [PATCH 0227/1139] [cookie-parser] finish incomplete typings (#18191) * [cookie-parser] finish incomplete typings * [cookie-parser] bump compiler version as suggested by travis output * [cookie-parser] revert compiler bump * [cookie-parser] restrict compiler version in failing packages * [cookie-parser] fix indentation --- types/connect-timeout/index.d.ts | 1 + types/cookie-parser/cookie-parser-tests.ts | 29 ++++++++++++++++++++-- types/cookie-parser/index.d.ts | 24 ++++++++++++++---- types/cookie-parser/tslint.json | 1 + types/easy-session/index.d.ts | 1 + 5 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 types/cookie-parser/tslint.json diff --git a/types/connect-timeout/index.d.ts b/types/connect-timeout/index.d.ts index bfaa7c473d..0ec4963306 100644 --- a/types/connect-timeout/index.d.ts +++ b/types/connect-timeout/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/expressjs/timeout // Definitions by: Cyril Schumacher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// diff --git a/types/cookie-parser/cookie-parser-tests.ts b/types/cookie-parser/cookie-parser-tests.ts index 1f9aaa1a8b..3a9f885efd 100644 --- a/types/cookie-parser/cookie-parser-tests.ts +++ b/types/cookie-parser/cookie-parser-tests.ts @@ -1,6 +1,31 @@ - import express = require('express'); import cookieParser = require('cookie-parser'); -var app = express(); +const app = express(); app.use(cookieParser('optional secret string')); + +let obj: object; +let str: string; +let notTrue: false; +let undef: undefined; + +const res = cookieParser.JSONCookie('foo'); +if (typeof res === 'undefined') { + undef = res; +} else { + obj = res; +} + +const res2 = cookieParser.JSONCookies({foo: 'bar'}); +const jsonRes: { foo?: object } = res2; + +const res3 = cookieParser.signedCookie('', 'keyboard cat'); +cookieParser.signedCookie('', ['keyboard', 'cat']); +if (typeof res3 === 'string') { + str = res3; +} else { + notTrue = res3; +} + +const res4 = cookieParser.signedCookies({foo: 'bar'}, 'keyboard cat'); +const signedCookieRes: { foo?: string | false } = res4; diff --git a/types/cookie-parser/index.d.ts b/types/cookie-parser/index.d.ts index 96412d6ee9..b2520080b0 100644 --- a/types/cookie-parser/index.d.ts +++ b/types/cookie-parser/index.d.ts @@ -1,12 +1,26 @@ -// Type definitions for cookie-parser v1.3.4 +// Type definitions for cookie-parser 1.4 // Project: https://github.com/expressjs/cookie-parser // Definitions by: Santi Albo +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +import * as express from 'express'; +declare function cookieParser(secret?: string | string[], options?: cookieParser.CookieParseOptions): express.RequestHandler; +declare namespace cookieParser { + interface CookieParseOptions { + decode?(val: string): string; + } -import express = require('express'); -declare function e(secret?: string, options?: any): express.RequestHandler; -declare namespace e { } -export = e; + function JSONCookie(jsonCookie: string): object | undefined; + + function JSONCookies(jsonCookies: T): { [P in keyof T]: object | undefined }; + + function signedCookie(cookie: string, secret: string | string[]): string | false; + + function signedCookies(cookies: T, secret: string | string[]): { [P in keyof T]?: string | false}; +} + +export = cookieParser; diff --git a/types/cookie-parser/tslint.json b/types/cookie-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cookie-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/easy-session/index.d.ts b/types/easy-session/index.d.ts index 0d96c61783..9a449b5322 100644 --- a/types/easy-session/index.d.ts +++ b/types/easy-session/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/DeadAlready/node-easy-session // Definitions by: Karl Düüna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// From 0a1c229ee54fdf137d6bd2949d0a43d7cc88284b Mon Sep 17 00:00:00 2001 From: Vito Date: Mon, 24 Jul 2017 13:05:39 -0400 Subject: [PATCH 0228/1139] refactor react-overlays into individual modules (#18197) * refactor react-overlays into individual modules also adds correct definitions for some modules whose definitions were incorretly being imported from react-bootstrap. (react-bootstrap depends on react-overlays, not the other way around) * use exported namespace hack instead of default exports --- types/react-overlays/index.d.ts | 207 ++++-------------- types/react-overlays/lib/Affix.d.ts | 84 +++++++ types/react-overlays/lib/AutoAffix.d.ts | 19 ++ types/react-overlays/lib/Modal.d.ts | 126 +++++++++++ types/react-overlays/lib/ModalManager.d.ts | 10 + types/react-overlays/lib/Overlay.d.ts | 33 +++ types/react-overlays/lib/Portal.d.ts | 10 + types/react-overlays/lib/Position.d.ts | 34 +++ .../react-overlays/lib/RootCloseWrapper.d.ts | 18 +- types/react-overlays/lib/Transition.d.ts | 56 +++++ types/react-overlays/lib/index.d.ts | 21 ++ .../test/react-overlays-tests-individual.tsx | 49 +++++ .../{ => test}/react-overlays-tests.tsx | 12 +- types/react-overlays/tsconfig.json | 6 +- 14 files changed, 505 insertions(+), 180 deletions(-) create mode 100644 types/react-overlays/lib/Affix.d.ts create mode 100644 types/react-overlays/lib/AutoAffix.d.ts create mode 100644 types/react-overlays/lib/Modal.d.ts create mode 100644 types/react-overlays/lib/ModalManager.d.ts create mode 100644 types/react-overlays/lib/Overlay.d.ts create mode 100644 types/react-overlays/lib/Portal.d.ts create mode 100644 types/react-overlays/lib/Position.d.ts create mode 100644 types/react-overlays/lib/Transition.d.ts create mode 100644 types/react-overlays/lib/index.d.ts create mode 100644 types/react-overlays/test/react-overlays-tests-individual.tsx rename types/react-overlays/{ => test}/react-overlays-tests.tsx (82%) diff --git a/types/react-overlays/index.d.ts b/types/react-overlays/index.d.ts index 450e8e2e93..e97c7e3761 100644 --- a/types/react-overlays/index.d.ts +++ b/types/react-overlays/index.d.ts @@ -1,184 +1,53 @@ // Type definitions for React Overlays 0.6 // Project: https://github.com/react-bootstrap/react-overlays // Definitions by: Aaron Beall +// Vito Samson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as React from "react"; -export { Modal, Overlay, Portal, Position } from "react-bootstrap"; +export { + Affix, + AutoAffix, + Modal, + ModalManager, + Overlay, + Portal, + Position, + Transition, + RootCloseWrapper, +} from './lib'; -// -export interface AffixProps { - /** - * Pixels to offset from top of screen when calculating position - */ - offsetTop?: number; +// these callbacks are used in a few components +export interface TransitionCallbacks { + /** + * Callback fired before the Overlay transitions in + */ + onEnter?(node: HTMLElement): any; - /** - * When affixed, pixels to offset from top of viewport - */ - viewportOffsetTop?: number; + /** + * Callback fired as the Overlay begins to transition in + */ + onEntering?(node: HTMLElement): any; - /** - * Pixels to offset from bottom of screen when calculating position - */ - offsetBottom?: number; + /** + * Callback fired after the Overlay finishes transitioning in + */ + onEntered?(node: HTMLElement): any; - /** - * CSS class or classes to apply when at top - */ - topClassName?: string; + /** + * Callback fired right before the Overlay transitions out + */ + onExit?(node: HTMLElement): any; - /** - * Style to apply when at top - */ - topStyle?: React.CSSProperties; + /** + * Callback fired as the Overlay begins to transition out + */ + onExiting?(node: HTMLElement): any; - /** - * CSS class or classes to apply when affixed - */ - affixClassName?: string; - - /** - * Style to apply when affixed - */ - affixStyle?: React.CSSProperties; - - /** - * CSS class or classes to apply when at bottom - */ - bottomClassName?: string; - - /** - * Style to apply when at bottom - */ - bottomStyle?: React.CSSProperties; - - /** - * Callback fired when the right before the `affixStyle` and `affixStyle` props are rendered - */ - onAffix?(): void; - /** - * Callback fired after the component `affixStyle` and `affixClassName` props have been rendered. - */ - onAffixed?(): void; - - /** - * Callback fired when the right before the `topStyle` and `topClassName` props are rendered - */ - onAffixTop?(): void; - - /** - * Callback fired after the component `topStyle` and `topClassName` props have been rendered. - */ - onAffixedTop?(): void; - - /** - * Callback fired when the right before the `bottomStyle` and `bottomClassName` props are rendered - */ - onAffixBottom?(): void; - - /** - * Callback fired after the component `bottomStyle` and `bottomClassName` props have been rendered. - */ - onAffixedBottom?(): void; + /** + * Callback fired after the Overlay finishes transitioning out + */ + onExited?(node: HTMLElement): any; } -export class Affix extends React.Component { } - -// -export interface AutoAffixProps extends AffixProps { - /** - * The logical container node or component for determining offset from bottom - * of viewport, or a function that returns it - */ - container?: React.ReactInstance | (() => React.ReactInstance); - - /** - * Automatically set width when affixed - */ - autoWidth?: boolean; -} -export class AutoAffix extends React.Component { } - -// -export interface TransitionProps { - className?: string; - - /** - * Show the component; triggers the enter or exit animation - */ - in?: boolean; - - /** - * Unmount the component (remove it from the DOM) when it is not shown - */ - unmountOnExit?: boolean; - - /** - * Run the enter animation when the component mounts, if it is initially - * shown - */ - transitionAppear?: boolean; - - /** - * A Timeout for the animation, in milliseconds, to ensure that a node doesn't - * transition indefinately if the browser transitionEnd events are - * canceled or interrupted. - * - * By default this is set to a high number (5 seconds) as a failsafe. You should consider - * setting this to the duration of your animation (or a bit above it). - */ - timeout?: number; - - /** - * CSS class or classes applied when the component is exited - */ - exitedClassName?: string; - - /** - * CSS class or classes applied while the component is exiting - */ - exitingClassName?: string; - - /** - * CSS class or classes applied when the component is entered - */ - enteredClassName?: string; - - /** - * CSS class or classes applied while the component is entering - */ - enteringClassName?: string; - - /** - * Callback fired before the "entering" classes are applied - */ - onEnter?(element: Element): void; - - /** - * Callback fired after the "entering" classes are applied - */ - onEntering?(element: Element): void; - - /** - * Callback fired after the "enter" classes are applied - */ - onEntered?(element: Element): void; - - /** - * Callback fired before the "exiting" classes are applied - */ - onExit?(element: Element): void; - - /** - * Callback fired after the "exiting" classes are applied - */ - onExiting?(element: Element): void; - - /** - * Callback fired after the "exited" classes are applied - */ - onExited?(element: Element): void; -} -export class Transition extends React.Component { } diff --git a/types/react-overlays/lib/Affix.d.ts b/types/react-overlays/lib/Affix.d.ts new file mode 100644 index 0000000000..e24cb8186a --- /dev/null +++ b/types/react-overlays/lib/Affix.d.ts @@ -0,0 +1,84 @@ +import * as React from 'react'; + +declare class Affix extends React.Component { } +export = Affix; + +declare namespace Affix { + // put AffixProps inside the exported namespace so it's importable in AutoAffix + interface AffixProps { + /** + * Pixels to offset from top of screen when calculating position + */ + offsetTop?: number; + + /** + * When affixed, pixels to offset from top of viewport + */ + viewportOffsetTop?: number; + + /** + * Pixels to offset from bottom of screen when calculating position + */ + offsetBottom?: number; + + /** + * CSS class or classes to apply when at top + */ + topClassName?: string; + + /** + * Style to apply when at top + */ + topStyle?: React.CSSProperties; + + /** + * CSS class or classes to apply when affixed + */ + affixClassName?: string; + + /** + * Style to apply when affixed + */ + affixStyle?: React.CSSProperties; + + /** + * CSS class or classes to apply when at bottom + */ + bottomClassName?: string; + + /** + * Style to apply when at bottom + */ + bottomStyle?: React.CSSProperties; + + /** + * Callback fired when the right before the `affixStyle` and `affixStyle` props are rendered + */ + onAffix?(): void; + + /** + * Callback fired after the component `affixStyle` and `affixClassName` props have been rendered. + */ + onAffixed?(): void; + + /** + * Callback fired when the right before the `topStyle` and `topClassName` props are rendered + */ + onAffixTop?(): void; + + /** + * Callback fired after the component `topStyle` and `topClassName` props have been rendered. + */ + onAffixedTop?(): void; + + /** + * Callback fired when the right before the `bottomStyle` and `bottomClassName` props are rendered + */ + onAffixBottom?(): void; + + /** + * Callback fired after the component `bottomStyle` and `bottomClassName` props have been rendered. + */ + onAffixedBottom?(): void; + } +} diff --git a/types/react-overlays/lib/AutoAffix.d.ts b/types/react-overlays/lib/AutoAffix.d.ts new file mode 100644 index 0000000000..8c075c1782 --- /dev/null +++ b/types/react-overlays/lib/AutoAffix.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; +import { AffixProps } from './Affix'; + +declare class AutoAffix extends React.Component { } +declare namespace AutoAffix { } +export = AutoAffix; + +interface AutoAffixProps extends AffixProps { + /** + * The logical container node or component for determining offset from bottom + * of viewport, or a function that returns it + */ + container?: React.ReactInstance | (() => React.ReactInstance); + + /** + * Automatically set width when affixed + */ + autoWidth?: boolean; +} diff --git a/types/react-overlays/lib/Modal.d.ts b/types/react-overlays/lib/Modal.d.ts new file mode 100644 index 0000000000..c89c607e76 --- /dev/null +++ b/types/react-overlays/lib/Modal.d.ts @@ -0,0 +1,126 @@ +import * as React from 'react'; +import { TransitionCallbacks } from 'react-overlays'; +import * as ModalManager from './ModalManager'; +import { PortalProps } from './Portal'; + +declare class Modal extends React.Component { + public static Manager: ModalManager; +} +declare namespace Modal { } +export = Modal; + +interface ModalProps extends TransitionCallbacks, PortalProps { + /** + * Set the visibility of the Modal + */ + show?: boolean; + + /** + * A Node, Component instance, or function that returns either. The Modal is appended to it's container element. + * + * For the sake of assistive technologies, the container should usually be the document body, so that the rest of the + * page content can be placed behind a virtual backdrop as well as a visual one. + */ + container?: React.ReactNode | Function; + + /** + * A callback fired when the Modal is opening. + */ + onShow?: Function; + + /** + * A callback fired when either the backdrop is clicked, or the escape key is pressed. + * + * The `onHide` callback only signals intent from the Modal, + * you must actually set the `show` prop to `false` for the Modal to close. + */ + onHide?: Function; + + /** + * Include a backdrop component. + */ + backdrop?: boolean | 'static'; + + /** + * A function that returns a backdrop component. Useful for custom + * backdrop rendering. + * + * ```js + * renderBackdrop={props => } + * ``` + */ + renderBackdrop?(props: any): React.ReactNode; + + /** + * A callback fired when the escape key, if specified in `keyboard`, is pressed. + */ + onEscapeKeyUp?: Function; + + /** + * A callback fired when the backdrop, if specified, is clicked. + */ + onBackdropClick?: Function; + + /** + * A style object for the backdrop component. + */ + backdropStyle?: Object; + + /** + * A css class or classes for the backdrop component. + */ + backdropClassName?: string; + + /** + * A css class or set of classes applied to the modal container when the modal is open, + * and removed when it is closed. + */ + containerClassName?: string; + + /** + * Close the modal when escape key is pressed + */ + keyboard?: boolean; + + /** + * A `react-transition-group@2.0.0` `` component used + * to control animations for the dialog component. + */ + transition?: Element; + + /** + * A `react-transition-group@2.0.0` `` component used + * to control animations for the backdrop components. + */ + backdropTransition?: Element; + + /** + * When `true` The modal will automatically shift focus to itself when it opens, and + * replace it to the last focused element when it closes. This also + * works correctly with any Modal children that have the `autoFocus` prop. + * + * Generally this should never be set to `false` as it makes the Modal less + * accessible to assistive technologies, like screen readers. + */ + autoFocus?: boolean; + + /** + * When `true` The modal will prevent focus from leaving the Modal while open. + * + * Generally this should never be set to `false` as it makes the Modal less + * accessible to assistive technologies, like screen readers. + */ + enforceFocus?: boolean; + + /** + * When `true` The modal will restore focus to previously focused element once + * modal is hidden + */ + restoreFocus?: boolean; + + /** + * A ModalManager instance used to track and manage the state of open + * Modals. Useful when customizing how modals interact within a container + */ + manager: ModalManager; +} diff --git a/types/react-overlays/lib/ModalManager.d.ts b/types/react-overlays/lib/ModalManager.d.ts new file mode 100644 index 0000000000..f2492aee7d --- /dev/null +++ b/types/react-overlays/lib/ModalManager.d.ts @@ -0,0 +1,10 @@ +import * as Modal from './Modal'; + +declare class ModalManager { + constructor(opts?: { hideSiblingNodes?: boolean; handleContainerOverflow?: boolean }); + add(modal: Modal, container: any, className?: string): number; + remove(modal: Modal): void; + isTopModal(modal: Modal): boolean; +} +declare namespace ModalManager { } +export = ModalManager; diff --git a/types/react-overlays/lib/Overlay.d.ts b/types/react-overlays/lib/Overlay.d.ts new file mode 100644 index 0000000000..f145919eb8 --- /dev/null +++ b/types/react-overlays/lib/Overlay.d.ts @@ -0,0 +1,33 @@ +import * as React from 'react'; +import { TransitionCallbacks } from 'react-overlays'; +import { PortalProps } from './Portal'; +import { PositionProps } from './Position'; + +declare class Overlay extends React.Component { } +declare namespace Overlay { } +export = Overlay; + +interface OverlayProps extends TransitionCallbacks, PortalProps, PositionProps { + /** + * Set the visibility of the Overlay + */ + show?: boolean; + + /** + * Specify whether the overlay should trigger `onHide` when the user clicks outside the overlay + */ + rootClose?: boolean; + + /** + * A Callback fired by the Overlay when it wishes to be hidden. + * + * __required__ when `rootClose` is `true`. + */ + onHide?(props: PortalProps, ...args: any[]): any; + + /** + * A `react-transition-group@2.0.0` `` component + * used to animate the overlay as it changes visibility. + */ + transition: Element; +} diff --git a/types/react-overlays/lib/Portal.d.ts b/types/react-overlays/lib/Portal.d.ts new file mode 100644 index 0000000000..b70c273b33 --- /dev/null +++ b/types/react-overlays/lib/Portal.d.ts @@ -0,0 +1,10 @@ +import * as React from 'react'; + +declare class Portal extends React.Component { } +export = Portal; + +declare namespace Portal { + interface PortalProps { + container?: React.ReactNode | Function; + } +} diff --git a/types/react-overlays/lib/Position.d.ts b/types/react-overlays/lib/Position.d.ts new file mode 100644 index 0000000000..2bbca4364e --- /dev/null +++ b/types/react-overlays/lib/Position.d.ts @@ -0,0 +1,34 @@ +import * as React from 'react'; + +declare class Position extends React.Component { } +export = Position; + +declare namespace Position { + interface PositionProps { + /** + * A node, element, or function that returns either. The child will be + * be positioned next to the `target` specified. + */ + target?: React.ReactNode | Function; + + /** + * "offsetParent" of the component + */ + container?: React.ReactNode | Function; + + /** + * Minimum spacing in pixels between container border and component border + */ + containerPadding?: number; + + /** + * How to position the component relative to the target + */ + placement?: 'top' | 'right' | 'bottom' | 'left'; + + /** + * Whether the position should be changed on each update + */ + shouldUpdatePosition?: boolean; + } +} diff --git a/types/react-overlays/lib/RootCloseWrapper.d.ts b/types/react-overlays/lib/RootCloseWrapper.d.ts index cfe4955f29..679426b50c 100644 --- a/types/react-overlays/lib/RootCloseWrapper.d.ts +++ b/types/react-overlays/lib/RootCloseWrapper.d.ts @@ -1,8 +1,18 @@ import * as React from "react"; -// +declare class RootCloseWrapper extends React.Component { } +declare namespace RootCloseWrapper { } +export = RootCloseWrapper; + interface RootCloseWrapperProps { - onRootClose?(): void; + /** + * Callback fired after click or mousedown. Also triggers when user hits `esc`. + */ + onRootClose?(e: React.SyntheticEvent): void; + + /** + * Children to render. + */ children?: React.ReactNode; /** @@ -16,7 +26,3 @@ interface RootCloseWrapperProps { */ event?: 'click' | 'mousedown'; } - -declare class RootCloseWrapper extends React.Component { } -declare namespace RootCloseWrapper { } // module export workaround: https://github.com/Microsoft/TypeScript/issues/5073 -export = RootCloseWrapper; diff --git a/types/react-overlays/lib/Transition.d.ts b/types/react-overlays/lib/Transition.d.ts new file mode 100644 index 0000000000..7f57e7b0c8 --- /dev/null +++ b/types/react-overlays/lib/Transition.d.ts @@ -0,0 +1,56 @@ +import * as React from 'react'; +import { TransitionCallbacks } from 'react-overlays'; + +declare class Transition extends React.Component { } +declare namespace Transition { } +export = Transition; + +interface TransitionProps extends TransitionCallbacks { + className?: string; + + /** + * Show the component; triggers the enter or exit animation + */ + in?: boolean; + + /** + * Unmount the component (remove it from the DOM) when it is not shown + */ + unmountOnExit?: boolean; + + /** + * Run the enter animation when the component mounts, if it is initially + * shown + */ + transitionAppear?: boolean; + + /** + * A Timeout for the animation, in milliseconds, to ensure that a node doesn't + * transition indefinately if the browser transitionEnd events are + * canceled or interrupted. + * + * By default this is set to a high number (5 seconds) as a failsafe. You should consider + * setting this to the duration of your animation (or a bit above it). + */ + timeout?: number; + + /** + * CSS class or classes applied when the component is exited + */ + exitedClassName?: string; + + /** + * CSS class or classes applied while the component is exiting + */ + exitingClassName?: string; + + /** + * CSS class or classes applied when the component is entered + */ + enteredClassName?: string; + + /** + * CSS class or classes applied while the component is entering + */ + enteringClassName?: string; +} diff --git a/types/react-overlays/lib/index.d.ts b/types/react-overlays/lib/index.d.ts new file mode 100644 index 0000000000..bc08d18d77 --- /dev/null +++ b/types/react-overlays/lib/index.d.ts @@ -0,0 +1,21 @@ +import * as Affix from './Affix'; +import * as AutoAffix from './AutoAffix'; +import * as Modal from './Modal'; +import * as ModalManager from './ModalManager'; +import * as Overlay from './Overlay'; +import * as Portal from './Portal'; +import * as Position from './Position'; +import * as Transition from './Transition'; +import * as RootCloseWrapper from './RootCloseWrapper'; + +export { + Affix, + AutoAffix, + Modal, + ModalManager, + Overlay, + Portal, + Position, + Transition, + RootCloseWrapper, +}; diff --git a/types/react-overlays/test/react-overlays-tests-individual.tsx b/types/react-overlays/test/react-overlays-tests-individual.tsx new file mode 100644 index 0000000000..fbf2506331 --- /dev/null +++ b/types/react-overlays/test/react-overlays-tests-individual.tsx @@ -0,0 +1,49 @@ +import * as React from "react"; + +import * as Transition from 'react-overlays/lib/Transition'; +import * as Portal from 'react-overlays/lib/Portal'; +import * as Modal from 'react-overlays/lib/Modal'; +import * as Position from 'react-overlays/lib/Position'; +import * as Overlay from 'react-overlays/lib/Overlay'; +import * as Affix from 'react-overlays/lib/Affix'; +import * as AutoAffix from 'react-overlays/lib/AutoAffix'; +import * as RootCloseWrapper from 'react-overlays/lib/RootCloseWrapper'; + +function testTransition() { + return ( + +
    Test
    +
    + ); +} + +class TestAffix extends React.Component { + render(): JSX.Element { + return ( +
    + +
    Test
    +
    +
    + ); + } +} + +class TestRootCloseWrapper extends React.Component { + handleRootClose = () => { }; + render() { + return ( + +
    Test
    +
    + ); + } +} diff --git a/types/react-overlays/react-overlays-tests.tsx b/types/react-overlays/test/react-overlays-tests.tsx similarity index 82% rename from types/react-overlays/react-overlays-tests.tsx rename to types/react-overlays/test/react-overlays-tests.tsx index af9eabaea8..dde53d76bc 100644 --- a/types/react-overlays/react-overlays-tests.tsx +++ b/types/react-overlays/test/react-overlays-tests.tsx @@ -1,7 +1,15 @@ import * as React from "react"; -import {Transition, Portal, Modal, Position, Overlay, Affix, AutoAffix} from "react-overlays"; -import * as RootCloseWrapper from "react-overlays/lib/RootCloseWrapper"; +import { + Transition, + Portal, + Modal, + Position, + Overlay, + Affix, + AutoAffix, + RootCloseWrapper, +} from "react-overlays"; function testTransition() { return ( diff --git a/types/react-overlays/tsconfig.json b/types/react-overlays/tsconfig.json index 65d976b3af..bb2d5734e3 100644 --- a/types/react-overlays/tsconfig.json +++ b/types/react-overlays/tsconfig.json @@ -19,7 +19,7 @@ }, "files": [ "index.d.ts", - "lib/RootCloseWrapper.d.ts", - "react-overlays-tests.tsx" + "test/react-overlays-tests.tsx", + "test/react-overlays-tests-individual.tsx" ] -} \ No newline at end of file +} From eb11dbc3862cb22084d8e0ee8fd389b2ae70cb20 Mon Sep 17 00:00:00 2001 From: Ben Date: Mon, 24 Jul 2017 12:09:19 -0500 Subject: [PATCH 0229/1139] Adding the 'resources' property to AlexaObject (#18210) * Adding the 'resources' property to AlexaObject * Updating alexa-sdk tests * Adding myself to credits for alexa-sdk --- types/alexa-sdk/alexa-sdk-tests.ts | 1 + types/alexa-sdk/index.d.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/types/alexa-sdk/alexa-sdk-tests.ts b/types/alexa-sdk/alexa-sdk-tests.ts index 1454309b93..c384bf194d 100644 --- a/types/alexa-sdk/alexa-sdk-tests.ts +++ b/types/alexa-sdk/alexa-sdk-tests.ts @@ -2,6 +2,7 @@ import * as Alexa from "alexa-sdk"; const handler = (event: Alexa.RequestBody, context: Alexa.Context, callback: () => void) => { let alexa = Alexa.handler(event, context); + alexa.resources = {}; alexa.registerHandlers(handlers); alexa.execute(); }; diff --git a/types/alexa-sdk/index.d.ts b/types/alexa-sdk/index.d.ts index 24baccf484..d5892f6ec7 100644 --- a/types/alexa-sdk/index.d.ts +++ b/types/alexa-sdk/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Pete Beegle // Huw // pascalwhoop +// Ben // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -20,6 +21,7 @@ export interface AlexaObject extends Handler { state: any; appId: any; response: any; + resources: any; dynamoDBTableName: any; saveBeforeResponse: boolean; registerHandlers: (...handlers: Array>) => any; From 869871c06962f73b37dbfdc4e5dd1773ca316f30 Mon Sep 17 00:00:00 2001 From: lobo87 Date: Mon, 24 Jul 2017 19:10:04 +0200 Subject: [PATCH 0230/1139] googlemaps: possibility to use an array for the property country in GeocoderComponentRestrictions class (#18212) * added cordova-plugin-native-keyboard * updated to conform linting checks * onSubmit callback is now optional * added possibility to use an array for the property country in GeocoderComponentRestrictions --- types/googlemaps/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/googlemaps/index.d.ts b/types/googlemaps/index.d.ts index b36032d298..2fea0028b8 100644 --- a/types/googlemaps/index.d.ts +++ b/types/googlemaps/index.d.ts @@ -1163,7 +1163,7 @@ declare namespace google.maps { export interface GeocoderComponentRestrictions { administrativeArea?: string; - country?: string; + country?: string | string[]; locality?: string; postalCode?: string; route?: string; From 5dcf62750161fb1187a2a7d5e3a3e894afe5daf8 Mon Sep 17 00:00:00 2001 From: Albert Willemsen Date: Mon, 24 Jul 2017 19:11:00 +0200 Subject: [PATCH 0231/1139] fix for issue #18211. (#18213) --- types/handlebars/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/handlebars/index.d.ts b/types/handlebars/index.d.ts index 56c341aa47..006ef242c3 100644 --- a/types/handlebars/index.d.ts +++ b/types/handlebars/index.d.ts @@ -308,3 +308,7 @@ declare namespace hbs { declare module "handlebars" { export = Handlebars; } + +declare module "handlebars/handlebars.runtime" { + export = Handlebars; +} From 9ffab7326388383e6394e4cbdc4cff9ddee82ca4 Mon Sep 17 00:00:00 2001 From: AngryPowman Date: Tue, 25 Jul 2017 01:14:27 +0800 Subject: [PATCH 0232/1139] Add delegate for parse (#18222) * Add delegate for parse * explicit type of node param --- types/esprima/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/esprima/index.d.ts b/types/esprima/index.d.ts index f03fd096f9..2d5f933cad 100644 --- a/types/esprima/index.d.ts +++ b/types/esprima/index.d.ts @@ -13,7 +13,7 @@ declare namespace esprima { const version: string; - function parse(code: string, options?: Options): ESTree.Program; + function parse(code: string, options?: Options, delegate?: (node: ESTree.Node, meta: any) => void): ESTree.Program; function tokenize(code: string, options?: Options): Array; interface Token { @@ -101,4 +101,4 @@ declare namespace esprima { YieldExpression: 'YieldExpression' }; -} \ No newline at end of file +} From f173f58c4412084af46f5b87f690647fc670f462 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20Ga=C5=82uszka?= Date: Mon, 24 Jul 2017 19:25:22 +0200 Subject: [PATCH 0233/1139] fix(stripe-checkout): fix removed stripe package in favor of stripe-v2 (#18243) --- types/stripe-checkout/index.d.ts | 10 +++++----- types/stripe-checkout/stripe-checkout-tests.ts | 14 +++++++------- types/stripe-checkout/tslint.json | 1 + 3 files changed, 13 insertions(+), 12 deletions(-) create mode 100644 types/stripe-checkout/tslint.json diff --git a/types/stripe-checkout/index.d.ts b/types/stripe-checkout/index.d.ts index b546ef1851..601559ee82 100644 --- a/types/stripe-checkout/index.d.ts +++ b/types/stripe-checkout/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for Stripe Checkout +// Type definitions for Stripe Checkout 1.0 // Project: https://stripe.com/checkout // Definitions by: Chris Wrench // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// +/// interface StripeCheckoutStatic { configure(options: StripeCheckoutOptions): StripeCheckoutHandler; @@ -16,7 +16,7 @@ interface StripeCheckoutHandler { interface StripeCheckoutOptions { key?: string; - token?: (token: StripeTokenResponse) => void; + token?(token: stripe.StripeTokenResponse): void; image?: string; name?: string; description?: string; @@ -33,8 +33,8 @@ interface StripeCheckoutOptions { bitcoin?: boolean; alipay?: boolean | 'auto'; alipayReusable?: boolean; - opened?: () => void; - closed?: () => void; + opened?(): void; + closed?(): void; } declare var StripeCheckout: StripeCheckoutStatic; diff --git a/types/stripe-checkout/stripe-checkout-tests.ts b/types/stripe-checkout/stripe-checkout-tests.ts index f4f3d67600..6cd221debf 100644 --- a/types/stripe-checkout/stripe-checkout-tests.ts +++ b/types/stripe-checkout/stripe-checkout-tests.ts @@ -1,7 +1,7 @@ // Test the minimum amount of configuration required. -var handler = StripeCheckout.configure({ +let handler = StripeCheckout.configure({ key: "my-secret-key", - token: function(token: StripeTokenResponse) { + token: (token: stripe.StripeTokenResponse) => { console.log(token.id); } }); @@ -11,9 +11,9 @@ handler.open(); handler.close(); // Test all configuration options. -var options: StripeCheckoutOptions = { +const options: StripeCheckoutOptions = { key: "my-secret-key", - token: function(token: StripeTokenResponse) { + token: (token: stripe.StripeTokenResponse) => { console.log(token.id); }, image: "http://placehold.it/128x128", @@ -31,9 +31,9 @@ var options: StripeCheckoutOptions = { alipay: "auto", alipayReusable: false, shippingAddress: false, - opened: function() {}, - closed: function() {} -} + opened: () => {}, + closed: () => {} +}; handler = StripeCheckout.configure(options); diff --git a/types/stripe-checkout/tslint.json b/types/stripe-checkout/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/stripe-checkout/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From bfbdf31ceb43512083b46ab4ee7018d9cee36448 Mon Sep 17 00:00:00 2001 From: Alex Ruzzante Date: Mon, 24 Jul 2017 19:27:58 +0200 Subject: [PATCH 0234/1139] [Office-js] Add item.dateTimeCreated and ui.closeContainer (#18248) --- types/office-js/index.d.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 4c5f6f0ad2..3633805360 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -160,6 +160,15 @@ declare namespace Office { * @param messageObject Accepts a message from the dialog to deliver to the add-in. */ messageParent(messageObject: any): void; + /** + * Closes the UI container where the JavaScript is executing. + * The behavior of this method is specified by the following table. + * When called from Behavior + * A UI-less command button No effect. Any dialogs opened by displayDialogAsync will remain open. + * A taskpane The taskpane will close. Any dialogs opened by displayDialogAsync will also close. If the taskpane supports pinning and was pinned by the user, it will be un-pinned. + * A module extension No effect. + */ + closeContainer(): void; } export interface DialogOptions { /** @@ -1769,6 +1778,7 @@ declare namespace Office { body: Body; itemType: Office.MailboxEnums.ItemType; notificationMessages: NotificationMessages; + dateTimeCreated: Date; /** * Asynchronously loads custom properties that are specific to the item and a app for Office * @param callback The optional callback method From 2ba36f6527124f0d460221e9de1464b520025ad8 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 24 Jul 2017 19:28:19 +0200 Subject: [PATCH 0235/1139] [execa] align to v0.7, add missing interfaces (#18251) --- types/execa/execa-tests.ts | 9 +++++++++ types/execa/index.d.ts | 24 ++++++++++++++++++------ 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/types/execa/execa-tests.ts b/types/execa/execa-tests.ts index fd7428d1ae..abdbfd6dad 100644 --- a/types/execa/execa-tests.ts +++ b/types/execa/execa-tests.ts @@ -54,6 +54,15 @@ execa.shell('echo unicorns') execa('echo', ['unicorns']).stdout.pipe(process.stdout); execa('echo', ['unicorns']).stderr.pipe(process.stderr); +execa('forever', {extendEnv: false}).pid; +execa('forever', {argv0: 'hi'}).pid; +execa('forever', {localDir: '~'}).pid; +execa('forever', {reject: false}).pid; +execa('forever', {cleanup: false}).pid; +execa('forever', {stdin: 1}).pid; +execa('forever', {stdout: 'ignore'}).pid; +execa('forever', {stderr: undefined}).pid; + async () => { const { stdout } = await execa('noop', ['foo'], { stripEof: false }); assert(stdout === 'foo\n'); diff --git a/types/execa/index.d.ts b/types/execa/index.d.ts index df868e4d15..df2c0d9d83 100644 --- a/types/execa/index.d.ts +++ b/types/execa/index.d.ts @@ -1,21 +1,33 @@ -// Type definitions for execa 0.6 +// Type definitions for execa 0.7 // Project: https://github.com/sindresorhus/execa#readme // Definitions by: Douglas Duteil +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// -import { ExecOptions, SpawnOptions, SpawnSyncOptions, SpawnSyncReturns, ChildProcess } from "child_process"; +import { ChildProcess, ExecOptions, SpawnOptions, SpawnSyncOptions } from "child_process"; import { Stream } from 'stream'; +type StdIOOption = 'pipe' | 'ipc' | 'ignore' | number | Stream | undefined | null; + interface ExecaOptions { input: string | Buffer | Stream; preferLocal: boolean; stripEof: boolean; + extendEnv: boolean; + argv0: string; + localDir: string; + reject: boolean; + cleanup: boolean; + stdin: StdIOOption; + stdout: StdIOOption; + stderr: StdIOOption; } type Options = SpawnOptions & ExecaOptions & ExecOptions; +type SyncOptions = SpawnSyncOptions & ExecaOptions & ExecOptions; interface ExecaReturns { cmd: string; @@ -42,10 +54,10 @@ declare namespace execa { function stdout(file: string, args?: string[], options?: Partial): Promise; function stderr(file: string, options?: Partial): Promise; function stderr(file: string, args?: string[], options?: Partial): Promise; - function shell(command: string, options?: SpawnOptions): ExecaChildProcess; - function sync(file: string, options?: SpawnSyncOptions): ExecaReturns; - function sync(file: string, args?: string[], options?: SpawnSyncOptions): ExecaReturns; - function shellSync(command: string, options?: SpawnOptions): ExecaReturns; + function shell(command: string, options?: Partial): ExecaChildProcess; + function sync(file: string, options?: Partial): ExecaReturns; + function sync(file: string, args?: string[], options?: Partial): ExecaReturns; + function shellSync(command: string, options?: Partial): ExecaReturns; } export = execa; From 0473fda9c679c9133afa46b0199d202208baf7a2 Mon Sep 17 00:00:00 2001 From: Andy Date: Mon, 24 Jul 2017 10:29:25 -0700 Subject: [PATCH 0236/1139] graphql: Lint (#18257) --- types/graphql/error/GraphQLError.d.ts | 9 +- types/graphql/error/formatError.d.ts | 18 +- types/graphql/error/index.d.ts | 2 +- types/graphql/error/locatedError.d.ts | 2 +- types/graphql/error/syntaxError.d.ts | 2 +- types/graphql/execution/execute.d.ts | 4 +- types/graphql/execution/values.d.ts | 4 +- types/graphql/graphql-tests.ts | 144 +++++------ types/graphql/index.d.ts | 12 +- types/graphql/language/ast.d.ts | 228 +++++++++--------- types/graphql/language/kinds.d.ts | 2 +- types/graphql/language/lexer.d.ts | 4 +- types/graphql/language/location.d.ts | 1 - types/graphql/language/parser.d.ts | 6 +- types/graphql/language/visitor.d.ts | 2 +- types/graphql/tslint.json | 1 + types/graphql/type/definition.d.ts | 135 +++++------ types/graphql/type/directives.d.ts | 11 +- types/graphql/type/introspection.d.ts | 3 +- types/graphql/type/scalars.d.ts | 1 - types/graphql/type/schema.d.ts | 9 +- types/graphql/utilities/TypeInfo.d.ts | 12 +- types/graphql/utilities/assertValidName.d.ts | 2 +- types/graphql/utilities/astFromValue.d.ts | 19 +- types/graphql/utilities/buildASTSchema.d.ts | 3 +- .../graphql/utilities/buildClientSchema.d.ts | 1 - types/graphql/utilities/concatAST.d.ts | 3 +- types/graphql/utilities/extendSchema.d.ts | 1 - .../utilities/findBreakingChanges.d.ts | 20 +- .../utilities/findDeprecatedUsages.d.ts | 2 +- .../graphql/utilities/introspectionQuery.d.ts | 45 ++-- types/graphql/utilities/isValidJSValue.d.ts | 2 +- .../utilities/isValidLiteralValue.d.ts | 2 +- .../graphql/utilities/separateOperations.d.ts | 2 +- types/graphql/utilities/typeComparators.d.ts | 1 - types/graphql/utilities/typeFromAST.d.ts | 2 +- types/graphql/utilities/valueFromAST.d.ts | 1 - types/graphql/validation/validate.d.ts | 27 +-- 38 files changed, 364 insertions(+), 381 deletions(-) create mode 100644 types/graphql/tslint.json diff --git a/types/graphql/error/GraphQLError.d.ts b/types/graphql/error/GraphQLError.d.ts index 857f25b593..fbafcb1e30 100644 --- a/types/graphql/error/GraphQLError.d.ts +++ b/types/graphql/error/GraphQLError.d.ts @@ -9,7 +9,6 @@ import { Source } from '../language/source'; * GraphQL document and/or execution result that correspond to the Error. */ export class GraphQLError extends Error { - /** * A message describing the Error for debugging purposes. * @@ -40,7 +39,7 @@ export class GraphQLError extends Error { /** * An array of GraphQL AST Nodes corresponding to this error. */ - nodes?: Array | undefined; + nodes?: ASTNode[] | undefined; /** * The source GraphQL document corresponding to this error. @@ -51,7 +50,7 @@ export class GraphQLError extends Error { * An array of character offsets within the source GraphQL document * which correspond to this error. */ - positions?: Array | undefined; + positions?: number[] | undefined; /** * The original error thrown from a field resolver during execution. @@ -60,9 +59,9 @@ export class GraphQLError extends Error { constructor( message: string, - nodes?: Array, + nodes?: any[], source?: Source, - positions?: Array, + positions?: number[], path?: Array, originalError?: Error, ); diff --git a/types/graphql/error/formatError.d.ts b/types/graphql/error/formatError.d.ts index 5b974d5461..fbb31cdb23 100644 --- a/types/graphql/error/formatError.d.ts +++ b/types/graphql/error/formatError.d.ts @@ -6,13 +6,13 @@ import { GraphQLError } from './GraphQLError'; */ export function formatError(error: GraphQLError): GraphQLFormattedError; -export type GraphQLFormattedError = { - message: string, - locations?: Array, - path?: Array -}; +export interface GraphQLFormattedError { + message: string; + locations?: GraphQLErrorLocation[]; + path?: Array; +} -export type GraphQLErrorLocation = { - line: number, - column: number -}; +export interface GraphQLErrorLocation { + line: number; + column: number; +} diff --git a/types/graphql/error/index.d.ts b/types/graphql/error/index.d.ts index 50fe58c06a..cfb5b92740 100644 --- a/types/graphql/error/index.d.ts +++ b/types/graphql/error/index.d.ts @@ -1,4 +1,4 @@ export { GraphQLError } from './GraphQLError'; export { syntaxError } from './syntaxError'; export { locatedError } from './locatedError'; -export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from './formatError'; \ No newline at end of file +export { formatError, GraphQLFormattedError, GraphQLErrorLocation } from './formatError'; diff --git a/types/graphql/error/locatedError.d.ts b/types/graphql/error/locatedError.d.ts index 8aca478f03..c827f8ede8 100644 --- a/types/graphql/error/locatedError.d.ts +++ b/types/graphql/error/locatedError.d.ts @@ -7,6 +7,6 @@ import { GraphQLError } from './GraphQLError'; */ export function locatedError( originalError: Error, - nodes: Array, + nodes: T[], path: Array ): GraphQLError; diff --git a/types/graphql/error/syntaxError.d.ts b/types/graphql/error/syntaxError.d.ts index d57b292211..80c4453e03 100644 --- a/types/graphql/error/syntaxError.d.ts +++ b/types/graphql/error/syntaxError.d.ts @@ -9,4 +9,4 @@ export function syntaxError( source: Source, position: number, description: string -): GraphQLError; \ No newline at end of file +): GraphQLError; diff --git a/types/graphql/execution/execute.d.ts b/types/graphql/execution/execute.d.ts index 48ee78840a..782310b6f4 100644 --- a/types/graphql/execution/execute.d.ts +++ b/types/graphql/execution/execute.d.ts @@ -22,7 +22,7 @@ export interface ExecutionContext { rootValue: any; operation: OperationDefinitionNode; variableValues: { [key: string]: any }; - errors: Array; + errors: GraphQLError[]; } /** @@ -32,7 +32,7 @@ export interface ExecutionContext { */ export interface ExecutionResult { data?: { [key: string]: any }; - errors?: Array; + errors?: GraphQLError[]; } /** diff --git a/types/graphql/execution/values.d.ts b/types/graphql/execution/values.d.ts index e6a0be63cc..3f6e909ed7 100644 --- a/types/graphql/execution/values.d.ts +++ b/types/graphql/execution/values.d.ts @@ -10,9 +10,9 @@ import { FieldNode, DirectiveNode, VariableDefinitionNode } from '../language/as */ export function getVariableValues( schema: GraphQLSchema, - varDefNodes: Array, + varDefNodes: VariableDefinitionNode[], inputs: { [key: string]: any } -): { [key: string]: any } +): { [key: string]: any }; /** * Prepares an object map of argument values given a list of argument diff --git a/types/graphql/graphql-tests.ts b/types/graphql/graphql-tests.ts index 58725259e7..7c0210249b 100644 --- a/types/graphql/graphql-tests.ts +++ b/types/graphql/graphql-tests.ts @@ -3,180 +3,180 @@ import * as graphql from 'graphql'; /////////////////////////// // graphql // /////////////////////////// -namespace graphql_tests { +function graphql_tests() { // TODO } /////////////////////////// // graphql/language // /////////////////////////// -namespace language_ast_tests { - // TODOS +function language_ast_tests() { + // TODO } -namespace language_index_tests { - // TODOS +function language_index_tests() { + // TODO } -namespace language_kinds_tests { - // TODOS +function language_kinds_tests() { + // TODO } -namespace language_lexer_tests { - // TODOS +function language_lexer_tests() { + // TODO } -namespace language_location_tests { - // TODOS +function language_location_tests() { + // TODO } -namespace language_parser_tests { - // TODOS +function language_parser_tests() { + // TODO } -namespace language_printer_tests { - // TODOS +function language_printer_tests() { + // TODO } -namespace language_source_tests { - // TODOS +function language_source_tests() { + // TODO } -namespace language_visitor_tests { - // TODOS +function language_visitor_tests() { + // TODO } /////////////////////////// // graphql/type // /////////////////////////// -namespace type_definition_tests { +function type_definition_tests() { // TODO } -namespace type_directives_tests { +function type_directives_tests() { // TODO } -namespace type_introspection_tests { +function type_introspection_tests() { // TODO } -namespace type_scalars_tests { +function type_scalars_tests() { // TODO } -namespace type_schema_tests { +function type_schema_tests() { // TODO } /////////////////////////// // graphql/validation // /////////////////////////// -namespace validation_specifiedRules_tests { - +function validation_specifiedRules_tests() { + // TODO } -namespace validation_validate_tests { - +function validation_validate_tests() { + // TODO } /////////////////////////// // graphql/execution // /////////////////////////// -namespace execution_execute_tests { +function execution_execute_tests() { // TODOS } -namespace execution_values_tests { +function execution_values_tests() { // TODOS } /////////////////////////// // graphql/error // /////////////////////////// -namespace error_GraphQLError { - +function error_GraphQLError() { + // TODOS } -namespace error_formatError { - +function error_formatError() { + // TODOS } -namespace error_locatedError { - +function error_locatedError() { + // TODOS } -namespace error_syntaxError { - +function error_syntaxError() { + // TODOS } /////////////////////////// // graphql/utilities // /////////////////////////// -namespace utilities_TypeInfo_tests { - //TODOS +function utilities_TypeInfo_tests() { + // TODOS } -namespace utilities_assertValidName_tests { - //TODOS +function utilities_assertValidName_tests() { + // TODOS } -namespace utilities_astFromValue_tests { - //TODOS +function utilities_astFromValue_tests() { + // TODOS } -namespace utilities_buildASTSchema_tests { - //TODOS +function utilities_buildASTSchema_tests() { + // TODOS } -namespace utilities_buildClientSchema_tests { - //TODOS +function utilities_buildClientSchema_tests() { + // TODOS } -namespace utilities_concatAST_tests { - //TODOS +function utilities_concatAST_tests() { + // TODOS } -namespace utilities_extendSchema_tests { - //TODOS +function utilities_extendSchema_tests() { + // TODOS } -namespace utilities_getOperationAST_tests { - //TODOS +function utilities_getOperationAST_tests() { + // TODOS } -namespace utilities_index_tests { - //TODOS +function utilities_index_tests() { + // TODOS } -namespace utilities_introspectionQuery_tests { - //TODOS +function utilities_introspectionQuery_tests() { + // TODOS } -namespace utilities_isValidJSValue_tests { - //TODOS +function utilities_isValidJSValue_tests() { + // TODOS } -namespace utilities_isValidLiteralValue_tests { - //TODOS +function utilities_isValidLiteralValue_tests() { + // TODOS } -namespace utilities_schemaPrinter_tests { - //TODOS +function utilities_schemaPrinter_tests() { + // TODOS } -namespace utilities_separateOperations_tests { - //TODOS +function utilities_separateOperations_tests() { + // TODOS } -namespace utilities_typeComparators_tests { - //TODOS +function utilities_typeComparators_tests() { + // TODOS } -namespace utilities_typeFromAST_tests { - //TODOS +function utilities_typeFromAST_tests() { + // TODOS } -namespace utilities_valueFromAST_tests { - //TODOS +function utilities_valueFromAST_tests() { + // TODOS } diff --git a/types/graphql/index.d.ts b/types/graphql/index.d.ts index fbd724ff4a..d4cf14b42f 100644 --- a/types/graphql/index.d.ts +++ b/types/graphql/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for graphql 0.10 // Project: https://www.npmjs.com/package/graphql -// Definitions by: TonyYang , Caleb Meredith , Dominic Watson , Firede , Kepennar +// Definitions by: TonyYang +// Caleb Meredith +// Dominic Watson +// Firede +// Kepennar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -9,12 +13,9 @@ export { graphql } from './graphql'; -/// - // Create and operate on GraphQL type definitions and schema. export * from './type'; - // Parse and operate on GraphQL language source files. export * from './language'; @@ -28,7 +29,6 @@ export { ExecutionResult, } from './execution'; - // Validate GraphQL queries. export { validate, @@ -36,7 +36,6 @@ export { specifiedRules, } from './validation'; - // Create and format GraphQL errors. export { GraphQLError, @@ -45,7 +44,6 @@ export { GraphQLErrorLocation, } from './error'; - // Utilities for operating on GraphQL type schema and parsed sources. export { // The GraphQL query recommended for a full schema introspection. diff --git a/types/graphql/language/ast.d.ts b/types/graphql/language/ast.d.ts index d0f25b65d0..f4bc343ed2 100644 --- a/types/graphql/language/ast.d.ts +++ b/types/graphql/language/ast.d.ts @@ -4,8 +4,7 @@ import { Source } from './source'; * Contains a range of UTF-8 character offsets and token references that * identify the region of the source from which the AST derived. */ -export type Location = { - +export interface Location { /** * The character offset at which this Node begins. */ @@ -30,37 +29,37 @@ export type Location = { * The Source document the AST represents. */ source: Source; -}; +} /** * Represents a range of characters represented by a lexical token * within a Source. */ -export type Token = { - +export interface Token { /** * The kind of Token. */ - kind: '' - | '' - | '!' - | '$' - | '(' - | ')' - | '...' - | ':' - | '=' - | '@' - | '[' - | ']' - | '{' - | '|' - | '}' - | 'Name' - | 'Int' - | 'Float' - | 'String' - | 'Comment'; + kind: + | '' + | '' + | '!' + | '$' + | '(' + | ')' + | '...' + | ':' + | '=' + | '@' + | '[' + | ']' + | '{' + | '|' + | '}' + | 'Name' + | 'Int' + | 'Float' + | 'String' + | 'Comment'; /** * The character offset at which this Node begins. @@ -94,12 +93,13 @@ export type Token = { */ prev?: Token; next?: Token; -}; +} /** * The list of all possible AST node types. */ -export type ASTNode = NameNode +export type ASTNode = + | NameNode | DocumentNode | OperationDefinitionNode | VariableDefinitionNode @@ -139,7 +139,7 @@ export type ASTNode = NameNode // Name -export type NameNode = { +export interface NameNode { kind: 'Name'; loc?: Location; value: string; @@ -147,30 +147,31 @@ export type NameNode = { // Document -export type DocumentNode = { +export interface DocumentNode { kind: 'Document'; loc?: Location; - definitions: Array; + definitions: DefinitionNode[]; } -export type DefinitionNode = OperationDefinitionNode +export type DefinitionNode = + | OperationDefinitionNode | FragmentDefinitionNode - | TypeSystemDefinitionNode // experimental non-spec addition. + | TypeSystemDefinitionNode; // experimental non-spec addition. -export type OperationDefinitionNode = { +export interface OperationDefinitionNode { kind: 'OperationDefinition'; loc?: Location; operation: OperationTypeNode; name?: NameNode; - variableDefinitions?: Array; - directives?: Array; + variableDefinitions?: VariableDefinitionNode[]; + directives?: DirectiveNode[]; selectionSet: SelectionSetNode; } // Note: subscription is an experimental non-spec addition. export type OperationTypeNode = 'query' | 'mutation' | 'subscription'; -export type VariableDefinitionNode = { +export interface VariableDefinitionNode { kind: 'VariableDefinition'; loc?: Location; variable: VariableNode; @@ -178,70 +179,70 @@ export type VariableDefinitionNode = { defaultValue?: ValueNode; } -export type VariableNode = { +export interface VariableNode { kind: 'Variable'; loc?: Location; name: NameNode; } -export type SelectionSetNode = { +export interface SelectionSetNode { kind: 'SelectionSet'; loc?: Location; - selections: Array; + selections: SelectionNode[]; } -export type SelectionNode = FieldNode +export type SelectionNode = + | FieldNode | FragmentSpreadNode - | InlineFragmentNode + | InlineFragmentNode; -export type FieldNode = { +export interface FieldNode { kind: 'Field'; loc?: Location; alias?: NameNode; name: NameNode; - arguments?: Array; - directives?: Array; + arguments?: ArgumentNode[]; + directives?: DirectiveNode[]; selectionSet?: SelectionSetNode; } -export type ArgumentNode = { +export interface ArgumentNode { kind: 'Argument'; loc?: Location; name: NameNode; value: ValueNode; } - // Fragments -export type FragmentSpreadNode = { +export interface FragmentSpreadNode { kind: 'FragmentSpread'; loc?: Location; name: NameNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InlineFragmentNode = { +export interface InlineFragmentNode { kind: 'InlineFragment'; loc?: Location; typeCondition?: NamedTypeNode; - directives?: Array; + directives?: DirectiveNode[]; selectionSet: SelectionSetNode; } -export type FragmentDefinitionNode = { +export interface FragmentDefinitionNode { kind: 'FragmentDefinition'; loc?: Location; name: NameNode; typeCondition: NamedTypeNode; - directives?: Array; + directives?: DirectiveNode[]; selectionSet: SelectionSetNode; } - // Values -export type ValueNode = VariableNode +export type ValueNode = + | VariableNode | IntValueNode | FloatValueNode | StringValueNode @@ -249,92 +250,91 @@ export type ValueNode = VariableNode | NullValueNode | EnumValueNode | ListValueNode - | ObjectValueNode + | ObjectValueNode; -export type IntValueNode = { +export interface IntValueNode { kind: 'IntValue'; loc?: Location; value: string; } -export type FloatValueNode = { +export interface FloatValueNode { kind: 'FloatValue'; loc?: Location; value: string; } -export type StringValueNode = { +export interface StringValueNode { kind: 'StringValue'; loc?: Location; value: string; } -export type BooleanValueNode = { +export interface BooleanValueNode { kind: 'BooleanValue'; loc?: Location; value: boolean; } -export type NullValueNode = { +export interface NullValueNode { kind: 'NullValue'; loc?: Location; } -export type EnumValueNode = { +export interface EnumValueNode { kind: 'EnumValue'; loc?: Location; value: string; } -export type ListValueNode = { +export interface ListValueNode { kind: 'ListValue'; loc?: Location; - values: Array; + values: ValueNode[]; } -export type ObjectValueNode = { +export interface ObjectValueNode { kind: 'ObjectValue'; loc?: Location; - fields: Array; + fields: ObjectFieldNode[]; } -export type ObjectFieldNode = { +export interface ObjectFieldNode { kind: 'ObjectField'; loc?: Location; name: NameNode; value: ValueNode; } - // Directives -export type DirectiveNode = { +export interface DirectiveNode { kind: 'Directive'; loc?: Location; name: NameNode; - arguments?: Array; + arguments?: ArgumentNode[]; } - // Type Reference -export type TypeNode = NamedTypeNode +export type TypeNode = + | NamedTypeNode | ListTypeNode - | NonNullTypeNode + | NonNullTypeNode; -export type NamedTypeNode = { +export interface NamedTypeNode { kind: 'NamedType'; loc?: Location; name: NameNode; -}; +} -export type ListTypeNode = { +export interface ListTypeNode { kind: 'ListType'; loc?: Location; type: TypeNode; } -export type NonNullTypeNode = { +export interface NonNullTypeNode { kind: 'NonNullType'; loc?: Location; type: NamedTypeNode | ListTypeNode; @@ -342,115 +342,117 @@ export type NonNullTypeNode = { // Type System Definition -export type TypeSystemDefinitionNode = SchemaDefinitionNode +export type TypeSystemDefinitionNode = + | SchemaDefinitionNode | TypeDefinitionNode | TypeExtensionDefinitionNode - | DirectiveDefinitionNode + | DirectiveDefinitionNode; -export type SchemaDefinitionNode = { +export interface SchemaDefinitionNode { kind: 'SchemaDefinition'; loc?: Location; - directives: Array; - operationTypes: Array; + directives: DirectiveNode[]; + operationTypes: OperationTypeDefinitionNode[]; } -export type OperationTypeDefinitionNode = { +export interface OperationTypeDefinitionNode { kind: 'OperationTypeDefinition'; loc?: Location; operation: OperationTypeNode; type: NamedTypeNode; } -export type TypeDefinitionNode = ScalarTypeDefinitionNode +export type TypeDefinitionNode = + | ScalarTypeDefinitionNode | ObjectTypeDefinitionNode | InterfaceTypeDefinitionNode | UnionTypeDefinitionNode | EnumTypeDefinitionNode - | InputObjectTypeDefinitionNode + | InputObjectTypeDefinitionNode; -export type ScalarTypeDefinitionNode = { +export interface ScalarTypeDefinitionNode { kind: 'ScalarTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type ObjectTypeDefinitionNode = { +export interface ObjectTypeDefinitionNode { kind: 'ObjectTypeDefinition'; loc?: Location; name: NameNode; - interfaces?: Array; - directives?: Array; - fields: Array; + interfaces?: NamedTypeNode[]; + directives?: DirectiveNode[]; + fields: FieldDefinitionNode[]; } -export type FieldDefinitionNode = { +export interface FieldDefinitionNode { kind: 'FieldDefinition'; loc?: Location; name: NameNode; - arguments: Array; + arguments: InputValueDefinitionNode[]; type: TypeNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InputValueDefinitionNode = { +export interface InputValueDefinitionNode { kind: 'InputValueDefinition'; loc?: Location; name: NameNode; type: TypeNode; defaultValue?: ValueNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InterfaceTypeDefinitionNode = { +export interface InterfaceTypeDefinitionNode { kind: 'InterfaceTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - fields: Array; + directives?: DirectiveNode[]; + fields: FieldDefinitionNode[]; } -export type UnionTypeDefinitionNode = { +export interface UnionTypeDefinitionNode { kind: 'UnionTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - types: Array; + directives?: DirectiveNode[]; + types: NamedTypeNode[]; } -export type EnumTypeDefinitionNode = { +export interface EnumTypeDefinitionNode { kind: 'EnumTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - values: Array; + directives?: DirectiveNode[]; + values: EnumValueDefinitionNode[]; } -export type EnumValueDefinitionNode = { +export interface EnumValueDefinitionNode { kind: 'EnumValueDefinition'; loc?: Location; name: NameNode; - directives?: Array; + directives?: DirectiveNode[]; } -export type InputObjectTypeDefinitionNode = { +export interface InputObjectTypeDefinitionNode { kind: 'InputObjectTypeDefinition'; loc?: Location; name: NameNode; - directives?: Array; - fields: Array; + directives?: DirectiveNode[]; + fields: InputValueDefinitionNode[]; } -export type TypeExtensionDefinitionNode = { +export interface TypeExtensionDefinitionNode { kind: 'TypeExtensionDefinition'; loc?: Location; definition: ObjectTypeDefinitionNode; } -export type DirectiveDefinitionNode = { +export interface DirectiveDefinitionNode { kind: 'DirectiveDefinition'; loc?: Location; name: NameNode; - arguments?: Array; - locations: Array; + arguments?: InputValueDefinitionNode[]; + locations: NameNode[]; } diff --git a/types/graphql/language/kinds.d.ts b/types/graphql/language/kinds.d.ts index 3b595beb65..626d350818 100644 --- a/types/graphql/language/kinds.d.ts +++ b/types/graphql/language/kinds.d.ts @@ -63,4 +63,4 @@ export const TYPE_EXTENSION_DEFINITION: 'TypeExtensionDefinition'; // Directive Definitions -export const DIRECTIVE_DEFINITION: 'DirectiveDefinition'; \ No newline at end of file +export const DIRECTIVE_DEFINITION: 'DirectiveDefinition'; diff --git a/types/graphql/language/lexer.d.ts b/types/graphql/language/lexer.d.ts index 5175b5b1e6..4a55f03dc2 100644 --- a/types/graphql/language/lexer.d.ts +++ b/types/graphql/language/lexer.d.ts @@ -18,7 +18,7 @@ export function createLexer( /** * The return type of createLexer. */ -export type Lexer = { +export interface Lexer { source: Source; options: TOptions; @@ -46,7 +46,7 @@ export type Lexer = { * Advances the token stream to the next non-ignored token. */ advance(): Token; -}; +} /** * An exported enum describing the different kinds of tokens that the diff --git a/types/graphql/language/location.d.ts b/types/graphql/language/location.d.ts index 8c638a3a96..4d7a13e314 100644 --- a/types/graphql/language/location.d.ts +++ b/types/graphql/language/location.d.ts @@ -1,6 +1,5 @@ import { Source } from "./source"; - export interface SourceLocation { line: number; column: number; diff --git a/types/graphql/language/parser.d.ts b/types/graphql/language/parser.d.ts index 1458d6736d..5aa195ddd4 100644 --- a/types/graphql/language/parser.d.ts +++ b/types/graphql/language/parser.d.ts @@ -5,14 +5,14 @@ import { Lexer } from "./lexer"; /** * Configuration options to control parser behavior */ -export type ParseOptions = { +export interface ParseOptions { /** * By default, the parser creates AST nodes that know the location * in the source that they correspond to. This configuration flag * disables that behavior for performance or testing. */ - noLocation?: boolean -}; + noLocation?: boolean; +} /** * Given a GraphQL source, parses it into a Document. diff --git a/types/graphql/language/visitor.d.ts b/types/graphql/language/visitor.d.ts index d4c528501e..024b292ed6 100644 --- a/types/graphql/language/visitor.d.ts +++ b/types/graphql/language/visitor.d.ts @@ -38,7 +38,7 @@ export const QueryDocumentKeys: { EnumValueDefinition: string[]; InputObjectTypeDefinition: string[]; TypeExtensionDefinition: string[]; -} +}; export const BREAK: any; diff --git a/types/graphql/tslint.json b/types/graphql/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/graphql/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/graphql/type/definition.d.ts b/types/graphql/type/definition.d.ts index eb64172f40..5b0a2e9181 100644 --- a/types/graphql/type/definition.d.ts +++ b/types/graphql/type/definition.d.ts @@ -10,14 +10,14 @@ import { GraphQLSchema } from './schema'; * These are all of the possible kinds of types. */ export type GraphQLType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList | - GraphQLNonNull; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull; export function isType(type: any): type is GraphQLType; @@ -27,16 +27,15 @@ export function assertType(type: any): GraphQLType; * These types may be used as input types for arguments and directives. */ export type GraphQLInputType = - GraphQLScalarType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList | - GraphQLNonNull< - GraphQLScalarType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList - >; + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList>; export function isInputType(type: GraphQLType): type is GraphQLInputType; @@ -46,20 +45,19 @@ export function assertInputType(type: GraphQLType): GraphQLInputType; * These types may be used as output types as the result of fields. */ export type GraphQLOutputType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLList | - GraphQLNonNull< - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLList - >; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList + | GraphQLNonNull< + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLList>; export function isOutputType(type: GraphQLType): type is GraphQLOutputType; @@ -69,8 +67,8 @@ export function assertOutputType(type: GraphQLType): GraphQLOutputType; * These types may describe types which may be leaf values. */ export type GraphQLLeafType = - GraphQLScalarType | - GraphQLEnumType; + | GraphQLScalarType + | GraphQLEnumType; export function isLeafType(type: GraphQLType): type is GraphQLLeafType; @@ -80,9 +78,9 @@ export function assertLeafType(type: GraphQLType): GraphQLLeafType; * These types may describe the parent context of a selection set. */ export type GraphQLCompositeType = - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType; + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType; export function isCompositeType(type: GraphQLType): type is GraphQLCompositeType; @@ -92,8 +90,8 @@ export function assertCompositeType(type: GraphQLType): GraphQLCompositeType; * These types may describe the parent context of a selection set. */ export type GraphQLAbstractType = - GraphQLInterfaceType | - GraphQLUnionType; + | GraphQLInterfaceType + | GraphQLUnionType; export function isAbstractType(type: GraphQLType): type is GraphQLAbstractType; @@ -103,13 +101,13 @@ export function assertAbstractType(type: GraphQLType): GraphQLAbstractType; * These types can all accept null as a value. */ export type GraphQLNullableType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType | - GraphQLList; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType + | GraphQLList; export function getNullableType( type: T @@ -119,12 +117,12 @@ export function getNullableType( * These named types do not include modifiers like List or NonNull. */ export type GraphQLNamedType = - GraphQLScalarType | - GraphQLObjectType | - GraphQLInterfaceType | - GraphQLUnionType | - GraphQLEnumType | - GraphQLInputObjectType; + | GraphQLScalarType + | GraphQLObjectType + | GraphQLInterfaceType + | GraphQLUnionType + | GraphQLEnumType + | GraphQLInputObjectType; export function isNamedType(type: GraphQLType): boolean; @@ -175,9 +173,9 @@ export class GraphQLScalarType { export interface GraphQLScalarTypeConfig { name: string; description?: string; - serialize: (value: any) => TExternal | null | undefined; - parseValue?: (value: any) => TInternal | null | undefined; - parseLiteral?: (valueNode: ValueNode) => TInternal | null | undefined; + serialize(value: any): TExternal | null | undefined; + parseValue?(value: any): TInternal | null | undefined; + parseLiteral?(valueNode: ValueNode): TInternal | null | undefined; } /** @@ -224,17 +222,16 @@ export class GraphQLObjectType { constructor(config: GraphQLObjectTypeConfig); getFields(): GraphQLFieldMap; - getInterfaces(): Array; + getInterfaces(): GraphQLInterfaceType[]; toString(): string; } - export interface GraphQLObjectTypeConfig { name: string; - interfaces?: Thunk>; + interfaces?: Thunk; fields: Thunk>; isTypeOf?: GraphQLIsTypeOfFn; - description?: string + description?: string; } export type GraphQLTypeResolver = ( @@ -258,7 +255,7 @@ export type GraphQLFieldResolver = ( export interface GraphQLResolveInfo { fieldName: string; - fieldNodes: Array; + fieldNodes: FieldNode[]; returnType: GraphQLOutputType; parentType: GraphQLCompositeType; path: ResponsePath; @@ -297,7 +294,7 @@ export interface GraphQLField { name: string; description: string; type: GraphQLOutputType; - args: Array; + args: GraphQLArgument[]; resolve?: GraphQLFieldResolver; isDeprecated?: boolean; deprecationReason?: string; @@ -345,15 +342,15 @@ export class GraphQLInterfaceType { } export interface GraphQLInterfaceTypeConfig { - name: string, - fields: Thunk>, + name: string; + fields: Thunk>; /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing * Object type. */ - resolveType?: GraphQLTypeResolver, - description?: string + resolveType?: GraphQLTypeResolver; + description?: string; } /** @@ -386,14 +383,14 @@ export class GraphQLUnionType { constructor(config: GraphQLUnionTypeConfig); - getTypes(): Array; + getTypes(): GraphQLObjectType[]; toString(): string; } export interface GraphQLUnionTypeConfig { - name: string, - types: Thunk>, + name: string; + types: Thunk; /** * Optionally provide a custom type resolver function. If one is not provided, * the default implementation will call `isTypeOf` on each implementing @@ -429,7 +426,7 @@ export class GraphQLEnumType { description: string; constructor(config: GraphQLEnumTypeConfig); - getValues(): Array; + getValues(): GraphQLEnumValue[]; getValue(name: string): GraphQLEnumValue; serialize(value: any): string; parseValue(value: any): any; diff --git a/types/graphql/type/directives.d.ts b/types/graphql/type/directives.d.ts index 5e470ddfca..aed6234ef5 100644 --- a/types/graphql/type/directives.d.ts +++ b/types/graphql/type/directives.d.ts @@ -3,7 +3,6 @@ import { GraphQLArgument } from './definition'; - export const DirectiveLocation: { // Operations QUERY: 'QUERY', @@ -27,7 +26,7 @@ export const DirectiveLocation: { INPUT_FIELD_DEFINITION: 'INPUT_FIELD_DEFINITION', }; -export type DirectiveLocationEnum = any //$Keys +export type DirectiveLocationEnum = keyof typeof DirectiveLocation; /** * Directives are used by the GraphQL runtime as a way of modifying execution @@ -36,8 +35,8 @@ export type DirectiveLocationEnum = any //$Keys export class GraphQLDirective { name: string; description: string; - locations: Array; - args: Array; + locations: DirectiveLocationEnum[]; + args: GraphQLArgument[]; constructor(config: GraphQLDirectiveConfig); } @@ -45,7 +44,7 @@ export class GraphQLDirective { export interface GraphQLDirectiveConfig { name: string; description?: string; - locations: Array; + locations: DirectiveLocationEnum[]; args?: GraphQLFieldConfigArgumentMap; } @@ -72,4 +71,4 @@ export const GraphQLDeprecatedDirective: GraphQLDirective; /** * The full list of specified directives. */ -export const specifiedDirectives: Array; +export const specifiedDirectives: GraphQLDirective[]; diff --git a/types/graphql/type/introspection.d.ts b/types/graphql/type/introspection.d.ts index 0227328b1d..989e34a882 100644 --- a/types/graphql/type/introspection.d.ts +++ b/types/graphql/type/introspection.d.ts @@ -10,7 +10,6 @@ import { } from './definition'; import { GraphQLField } from './definition'; - export const __Schema: GraphQLObjectType; export const __Directive: GraphQLObjectType; export const __DirectiveLocation: GraphQLEnumType; @@ -28,7 +27,7 @@ export const TypeKind: { INPUT_OBJECT: 'INPUT_OBJECT', LIST: 'LIST', NON_NULL: 'NON_NULL', -} +}; export const __TypeKind: GraphQLEnumType; diff --git a/types/graphql/type/scalars.d.ts b/types/graphql/type/scalars.d.ts index 6c01256643..31a33aafad 100644 --- a/types/graphql/type/scalars.d.ts +++ b/types/graphql/type/scalars.d.ts @@ -1,6 +1,5 @@ import { GraphQLScalarType } from './definition'; - export const GraphQLInt: GraphQLScalarType; export const GraphQLFloat: GraphQLScalarType; export const GraphQLString: GraphQLScalarType; diff --git a/types/graphql/type/schema.d.ts b/types/graphql/type/schema.d.ts index 01bd3b1ca5..2d0c5c7f3d 100644 --- a/types/graphql/type/schema.d.ts +++ b/types/graphql/type/schema.d.ts @@ -10,7 +10,6 @@ import { GraphQLDirective, } from './directives'; - /** * Schema Definition * @@ -53,14 +52,14 @@ export class GraphQLSchema { getSubscriptionType(): GraphQLObjectType|null|undefined; getTypeMap(): { [typeName: string]: GraphQLNamedType }; getType(name: string): GraphQLType; - getPossibleTypes(abstractType: GraphQLAbstractType): Array; + getPossibleTypes(abstractType: GraphQLAbstractType): GraphQLObjectType[]; isPossibleType( abstractType: GraphQLAbstractType, possibleType: GraphQLObjectType ): boolean; - getDirectives(): Array; + getDirectives(): GraphQLDirective[]; getDirective(name: string): GraphQLDirective; } @@ -68,6 +67,6 @@ export interface GraphQLSchemaConfig { query: GraphQLObjectType; mutation?: GraphQLObjectType; subscription?: GraphQLObjectType; - types?: Array; - directives?: Array; + types?: GraphQLNamedType[]; + directives?: GraphQLDirective[]; } diff --git a/types/graphql/utilities/TypeInfo.d.ts b/types/graphql/utilities/TypeInfo.d.ts index b4fa855569..98a53d37ef 100644 --- a/types/graphql/utilities/TypeInfo.d.ts +++ b/types/graphql/utilities/TypeInfo.d.ts @@ -36,10 +36,8 @@ export class TypeInfo { leave(node: ASTNode): any; } -export interface getFieldDef { - ( - schema: GraphQLSchema, - parentType: GraphQLType, - fieldNode: FieldNode - ): GraphQLField -} +export type getFieldDef = ( + schema: GraphQLSchema, + parentType: GraphQLType, + fieldNode: FieldNode, +) => GraphQLField; diff --git a/types/graphql/utilities/assertValidName.d.ts b/types/graphql/utilities/assertValidName.d.ts index 6104a26063..5ca2310a26 100644 --- a/types/graphql/utilities/assertValidName.d.ts +++ b/types/graphql/utilities/assertValidName.d.ts @@ -1,2 +1,2 @@ // Helper to assert that provided names are valid. -export function assertValidName(name: string): void; \ No newline at end of file +export function assertValidName(name: string): void; diff --git a/types/graphql/utilities/astFromValue.d.ts b/types/graphql/utilities/astFromValue.d.ts index 3d8ecdd0ec..44745c5e6c 100644 --- a/types/graphql/utilities/astFromValue.d.ts +++ b/types/graphql/utilities/astFromValue.d.ts @@ -1,12 +1,15 @@ import { ValueNode, - //IntValueNode, - //FloatValueNode, - //StringValueNode, - //BooleanValueNode, - //EnumValueNode, - //ListValueNode, - //ObjectValueNode, + /* + TODO: + IntValueNode, + FloatValueNode, + StringValueNode, + BooleanValueNode, + EnumValueNode, + ListValueNode, + ObjectValueNode, + */ } from '../language/ast'; import { GraphQLInputType } from '../type/definition'; @@ -30,4 +33,4 @@ import { GraphQLInputType } from '../type/definition'; export function astFromValue( value: any, type: GraphQLInputType -): ValueNode // Warning: there is a code in bottom: throw new TypeError +): ValueNode; // Warning: there is a code in bottom: throw new TypeError diff --git a/types/graphql/utilities/buildASTSchema.d.ts b/types/graphql/utilities/buildASTSchema.d.ts index 94f4e2a47a..b20c8fc856 100644 --- a/types/graphql/utilities/buildASTSchema.d.ts +++ b/types/graphql/utilities/buildASTSchema.d.ts @@ -2,7 +2,6 @@ import { DocumentNode, Location } from '../language/ast'; import { Source } from '../language/source'; import { GraphQLSchema } from '../type/schema'; - /** * This takes the ast of a schema document produced by the parse function in * src/language/parser.js. @@ -24,5 +23,5 @@ export function getDescription(node: { loc?: Location }): string; /** * A helper function to build a GraphQLSchema directly from a source * document. -*/ + */ export function buildSchema(source: string | Source): GraphQLSchema; diff --git a/types/graphql/utilities/buildClientSchema.d.ts b/types/graphql/utilities/buildClientSchema.d.ts index 391e651f52..166ec43cf7 100644 --- a/types/graphql/utilities/buildClientSchema.d.ts +++ b/types/graphql/utilities/buildClientSchema.d.ts @@ -1,7 +1,6 @@ import { IntrospectionQuery } from './introspectionQuery'; import { GraphQLSchema } from '../type/schema'; - /** * Build a GraphQLSchema for use by client tools. * diff --git a/types/graphql/utilities/concatAST.d.ts b/types/graphql/utilities/concatAST.d.ts index 1f6fcb985f..405ac69936 100644 --- a/types/graphql/utilities/concatAST.d.ts +++ b/types/graphql/utilities/concatAST.d.ts @@ -1,9 +1,8 @@ import { DocumentNode } from '../language/ast'; - /** * Provided a collection of ASTs, presumably each from different files, * concatenate the ASTs together into batched AST, useful for validating many * GraphQL source files which together represent one conceptual application. */ -export function concatAST(asts: Array): DocumentNode; +export function concatAST(asts: DocumentNode[]): DocumentNode; diff --git a/types/graphql/utilities/extendSchema.d.ts b/types/graphql/utilities/extendSchema.d.ts index 60b91e70b2..f7d00b2fee 100644 --- a/types/graphql/utilities/extendSchema.d.ts +++ b/types/graphql/utilities/extendSchema.d.ts @@ -1,7 +1,6 @@ import { DocumentNode } from '../language/ast'; import { GraphQLSchema } from '../type/schema'; - /** * Produces a new schema given an existing schema and a document which may * contain GraphQL type extensions and definitions. The original schema will diff --git a/types/graphql/utilities/findBreakingChanges.d.ts b/types/graphql/utilities/findBreakingChanges.d.ts index 94a74ced90..78d5a5a95b 100644 --- a/types/graphql/utilities/findBreakingChanges.d.ts +++ b/types/graphql/utilities/findBreakingChanges.d.ts @@ -10,7 +10,6 @@ import { } from '../type/definition'; import { GraphQLSchema } from '../type/schema'; - export const BreakingChangeType: { FIELD_CHANGED_KIND: 'FIELD_CHANGED_KIND', FIELD_REMOVED: 'FIELD_REMOVED', @@ -20,17 +19,18 @@ export const BreakingChangeType: { VALUE_REMOVED_FROM_ENUM: 'VALUE_REMOVED_FROM_ENUM', }; -export type BreakingChangeKey = 'FIELD_CHANGED_KIND' +export type BreakingChangeKey = + | 'FIELD_CHANGED_KIND' | 'FIELD_REMOVED' | 'TYPE_CHANGED_KIND' | 'TYPE_REMOVED' | 'TYPE_REMOVED_FROM_UNION' | 'VALUE_REMOVED_FROM_ENUM'; -export type BreakingChange = { +export interface BreakingChange { type: BreakingChangeKey; description: string; -}; +} /** * Given two schemas, returns an Array containing descriptions of all the types @@ -39,7 +39,7 @@ export type BreakingChange = { export function findBreakingChanges( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -48,7 +48,7 @@ export function findBreakingChanges( export function findRemovedTypes( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -57,7 +57,7 @@ export function findRemovedTypes( export function findTypesThatChangedKind( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -67,7 +67,7 @@ export function findTypesThatChangedKind( export function findFieldsThatChangedType( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array; +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -76,7 +76,7 @@ export function findFieldsThatChangedType( export function findTypesRemovedFromUnions( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array; +): BreakingChange[]; /** * Given two schemas, returns an Array containing descriptions of any breaking @@ -85,4 +85,4 @@ export function findTypesRemovedFromUnions( export function findValuesRemovedFromEnums( oldSchema: GraphQLSchema, newSchema: GraphQLSchema -): Array; +): BreakingChange[]; diff --git a/types/graphql/utilities/findDeprecatedUsages.d.ts b/types/graphql/utilities/findDeprecatedUsages.d.ts index 58e9ae1685..8f6ff48239 100644 --- a/types/graphql/utilities/findDeprecatedUsages.d.ts +++ b/types/graphql/utilities/findDeprecatedUsages.d.ts @@ -10,4 +10,4 @@ import { GraphQLError } from '../error/GraphQLError'; export function findDeprecatedUsages( schema: GraphQLSchema, ast: DocumentNode -): Array +): GraphQLError[]; diff --git a/types/graphql/utilities/introspectionQuery.d.ts b/types/graphql/utilities/introspectionQuery.d.ts index cb9f0267b6..a89c5c1fec 100644 --- a/types/graphql/utilities/introspectionQuery.d.ts +++ b/types/graphql/utilities/introspectionQuery.d.ts @@ -95,26 +95,25 @@ fragment TypeRef on __Type { */ export const introspectionQuery: string; - export interface IntrospectionQuery { - __schema: IntrospectionSchema + __schema: IntrospectionSchema; } export interface IntrospectionSchema { queryType: IntrospectionNamedTypeRef; mutationType?: IntrospectionNamedTypeRef; subscriptionType?: IntrospectionNamedTypeRef; - types: Array; - directives: Array; + types: IntrospectionType[]; + directives: IntrospectionDirective[]; } export type IntrospectionType = - IntrospectionScalarType | - IntrospectionObjectType | - IntrospectionInterfaceType | - IntrospectionUnionType | - IntrospectionEnumType | - IntrospectionInputObjectType; + | IntrospectionScalarType + | IntrospectionObjectType + | IntrospectionInterfaceType + | IntrospectionUnionType + | IntrospectionEnumType + | IntrospectionInputObjectType; export interface IntrospectionScalarType { kind: 'SCALAR'; @@ -126,43 +125,43 @@ export interface IntrospectionObjectType { kind: 'OBJECT'; name: string; description?: string; - fields: Array; - interfaces: Array; + fields: IntrospectionField[]; + interfaces: IntrospectionNamedTypeRef[]; } export interface IntrospectionInterfaceType { kind: 'INTERFACE'; name: string; description?: string; - fields: Array; - possibleTypes: Array; + fields: IntrospectionField[]; + possibleTypes: IntrospectionNamedTypeRef[]; } export interface IntrospectionUnionType { kind: 'UNION'; name: string; description?: string; - possibleTypes: Array; + possibleTypes: IntrospectionNamedTypeRef[]; } export interface IntrospectionEnumType { kind: 'ENUM'; name: string; description?: string; - enumValues: Array; + enumValues: IntrospectionEnumValue[]; } export interface IntrospectionInputObjectType { kind: 'INPUT_OBJECT'; name: string; description?: string; - inputFields: Array; + inputFields: IntrospectionInputValue[]; } export type IntrospectionTypeRef = - IntrospectionNamedTypeRef | - IntrospectionListTypeRef | - IntrospectionNonNullTypeRef + | IntrospectionNamedTypeRef + | IntrospectionListTypeRef + | IntrospectionNonNullTypeRef; export interface IntrospectionNamedTypeRef { kind: string; @@ -182,7 +181,7 @@ export interface IntrospectionNonNullTypeRef { export interface IntrospectionField { name: string; description?: string; - args: Array; + args: IntrospectionInputValue[]; type: IntrospectionTypeRef; isDeprecated: boolean; deprecationReason?: string; @@ -205,6 +204,6 @@ export interface IntrospectionEnumValue { export interface IntrospectionDirective { name: string; description?: string; - locations: Array; - args: Array; + locations: DirectiveLocationEnum[]; + args: IntrospectionInputValue[]; } diff --git a/types/graphql/utilities/isValidJSValue.d.ts b/types/graphql/utilities/isValidJSValue.d.ts index a06706ec2c..cd11014579 100644 --- a/types/graphql/utilities/isValidJSValue.d.ts +++ b/types/graphql/utilities/isValidJSValue.d.ts @@ -8,4 +8,4 @@ import { GraphQLInputType } from '../type/definition'; export function isValidJSValue( value: any, type: GraphQLInputType -): Array +): string[]; diff --git a/types/graphql/utilities/isValidLiteralValue.d.ts b/types/graphql/utilities/isValidLiteralValue.d.ts index 71f7471a70..697c8eb97e 100644 --- a/types/graphql/utilities/isValidLiteralValue.d.ts +++ b/types/graphql/utilities/isValidLiteralValue.d.ts @@ -11,4 +11,4 @@ import { GraphQLInputType } from '../type/definition'; export function isValidLiteralValue( type: GraphQLInputType, valueNode: ValueNode -): Array +): string[]; diff --git a/types/graphql/utilities/separateOperations.d.ts b/types/graphql/utilities/separateOperations.d.ts index b5d9e7439a..4b4106df53 100644 --- a/types/graphql/utilities/separateOperations.d.ts +++ b/types/graphql/utilities/separateOperations.d.ts @@ -5,4 +5,4 @@ import { export function separateOperations( documentAST: DocumentNode -): { [operationName: string]: DocumentNode } +): { [operationName: string]: DocumentNode }; diff --git a/types/graphql/utilities/typeComparators.d.ts b/types/graphql/utilities/typeComparators.d.ts index f9442914d3..16e6acd680 100644 --- a/types/graphql/utilities/typeComparators.d.ts +++ b/types/graphql/utilities/typeComparators.d.ts @@ -7,7 +7,6 @@ import { GraphQLSchema } from '../type/schema'; - /** * Provided two types, return true if the types are equal (invariant). */ diff --git a/types/graphql/utilities/typeFromAST.d.ts b/types/graphql/utilities/typeFromAST.d.ts index ce1c8b061f..c3cacf90df 100644 --- a/types/graphql/utilities/typeFromAST.d.ts +++ b/types/graphql/utilities/typeFromAST.d.ts @@ -5,4 +5,4 @@ import { GraphQLSchema } from '../type/schema'; export function typeFromAST( schema: GraphQLSchema, typeNode: TypeNode -): GraphQLType +): GraphQLType; diff --git a/types/graphql/utilities/valueFromAST.d.ts b/types/graphql/utilities/valueFromAST.d.ts index a292e079ab..24dd435448 100644 --- a/types/graphql/utilities/valueFromAST.d.ts +++ b/types/graphql/utilities/valueFromAST.d.ts @@ -6,7 +6,6 @@ import { ObjectValueNode } from '../language/ast'; - export function valueFromAST( valueNode: ValueNode, type: GraphQLInputType, diff --git a/types/graphql/validation/validate.d.ts b/types/graphql/validation/validate.d.ts index 9f4a9afdad..a4b628777e 100644 --- a/types/graphql/validation/validate.d.ts +++ b/types/graphql/validation/validate.d.ts @@ -19,9 +19,6 @@ import { GraphQLDirective } from '../type/directives'; import { TypeInfo } from '../utilities/TypeInfo'; import { specifiedRules } from './specifiedRules'; - -//type ValidationRule = (context: ValidationContext) => any; - /** * Implements the "Validation" section of the spec. * @@ -38,8 +35,8 @@ import { specifiedRules } from './specifiedRules'; export function validate( schema: GraphQLSchema, ast: DocumentNode, - rules?: Array -): Array; + rules?: any[] +): GraphQLError[]; /** * This uses a specialized visitor which runs multiple visitors in parallel, @@ -51,13 +48,13 @@ export function visitUsingRules( schema: GraphQLSchema, typeInfo: TypeInfo, documentAST: DocumentNode, - rules: Array -): Array; + rules: any[] +): GraphQLError[]; export type NodeWithSelectionSet = OperationDefinitionNode | FragmentDefinitionNode; export interface VariableUsage { - node: VariableNode, - type: GraphQLInputType + node: VariableNode; + type: GraphQLInputType; } /** @@ -69,7 +66,7 @@ export class ValidationContext { constructor(schema: GraphQLSchema, ast: DocumentNode, typeInfo: TypeInfo); reportError(error: GraphQLError): void; - getErrors(): Array; + getErrors(): GraphQLError[]; getSchema(): GraphQLSchema; @@ -77,17 +74,17 @@ export class ValidationContext { getFragment(name: string): FragmentDefinitionNode; - getFragmentSpreads(node: SelectionSetNode): Array; + getFragmentSpreads(node: SelectionSetNode): FragmentSpreadNode[]; getRecursivelyReferencedFragments( operation: OperationDefinitionNode - ): Array; + ): FragmentDefinitionNode[]; - getVariableUsages(node: NodeWithSelectionSet): Array; + getVariableUsages(node: NodeWithSelectionSet): VariableUsage[]; getRecursiveVariableUsages( operation: OperationDefinitionNode - ): Array; + ): VariableUsage[]; getType(): GraphQLOutputType; @@ -100,4 +97,4 @@ export class ValidationContext { getDirective(): GraphQLDirective; getArgument(): GraphQLArgument; -} \ No newline at end of file +} From 0429e70ac56fa01e0b14370baa0eb0032d2b439c Mon Sep 17 00:00:00 2001 From: Drew Hays Date: Mon, 24 Jul 2017 10:32:29 -0700 Subject: [PATCH 0237/1139] Fix a few next.js type issues (#18262) - Some of the `render` parameters should've been made optional. - The export style of the `'next'` module wasn't correct. - Added some missing static methods to `Head` - Some readonly properties of `Router` can be `undefined`. Note that this also means that `'next'` technically needs to be imported like `import next = require('next');` --- types/next/index.d.ts | 21 +++++++++++++-------- types/next/next-tests.ts | 6 ++++-- types/next/test/next-head-tests.tsx | 10 ++++++++++ types/next/test/next-router-tests.tsx | 7 +++++-- 4 files changed, 32 insertions(+), 12 deletions(-) diff --git a/types/next/index.d.ts b/types/next/index.d.ts index ab6e3df6f5..ca873fe5f2 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -43,11 +43,11 @@ declare module 'next' { start(): Promise; run(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: UrlLike): Promise; - render(req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query: {[key: string]: any}, parsedUrl: UrlLike): Promise; - renderError(err: any, req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query: {[key: string]: any}): Promise; + render(req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query?: {[key: string]: any}, parsedUrl?: UrlLike): Promise; + renderError(err: any, req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query?: {[key: string]: any}): Promise; render404(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: UrlLike): Promise; - renderToHTML(req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query: {[key: string]: any}): Promise; - renderErrorToHTML(err: any, req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query: {[key: string]: any}): Promise; + renderToHTML(req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query?: {[key: string]: any}): Promise; + renderErrorToHTML(err: any, req: http.IncomingMessage, res: http.ServerResponse, pathname: string, query?: {[key: string]: any}): Promise; serveStatic(req: http.IncomingMessage, res: http.ServerResponse, path: string): Promise; isServeableUrl(path: string): boolean; @@ -59,7 +59,8 @@ declare module 'next' { send404(res: http.ServerResponse): void; } - export default function(options?: ServerOptions): Server; + function next(options?: ServerOptions): Server; + export = next; } declare module 'next/error' { @@ -71,7 +72,11 @@ declare module 'next/head' { import * as React from 'react'; function defaultHead(): JSX.Element[]; - export default class extends React.Component<{}, {}> {} + export default class extends React.Component<{}, {}> { + static canUseDOM: boolean; + static peek(): Array>; + static rewind(): Array>; + } } declare module 'next/document' { @@ -147,8 +152,8 @@ declare module 'next/router' { readonly components: { [key: string]: { Component: React.ComponentType, err: any } }; readonly pathname: string; readonly route: string; - readonly asPath: string; - readonly query: { [key: string]: any }; + readonly asPath?: string; + readonly query?: { [key: string]: any }; // router methods reload(route: string): Promise; diff --git a/types/next/next-tests.ts b/types/next/next-tests.ts index bfa93bfff8..23157c1ba2 100644 --- a/types/next/next-tests.ts +++ b/types/next/next-tests.ts @@ -1,4 +1,4 @@ -import createServer from 'next'; +import createServer = require('next'); import * as http from 'http'; import * as url from 'url'; @@ -12,7 +12,7 @@ const server = createServer({ anotherProperty: { key: true } - } + }, }); const voidFunc = () => {}; @@ -31,8 +31,10 @@ function handle(req: http.IncomingMessage, res: http.ServerResponse) { handler(req, res, parsedUrl).then(voidFunc); server.run(req, res, parsedUrl).then(voidFunc); + server.render(req, res, '/path/to/resource').then(voidFunc); server.render(req, res, '/path/to/resource', {}, parsedUrl).then(voidFunc); server.render(req, res, '/path/to/resource', { key: 'value' }, parsedUrl).then(voidFunc); + server.renderError(new Error(), req, res, '/path/to/resource').then(voidFunc); server.renderError(new Error(), req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); server.renderError('this can be an error, too!', req, res, '/path/to/resource', { key: 'value' }).then(voidFunc); server.render404(req, res, parsedUrl).then(voidFunc); diff --git a/types/next/test/next-head-tests.tsx b/types/next/test/next-head-tests.tsx index eaf6754b49..c81333700c 100644 --- a/types/next/test/next-head-tests.tsx +++ b/types/next/test/next-head-tests.tsx @@ -7,3 +7,13 @@ const jsx = ( {elements} ); + +if (!Head.canUseDOM) { + Head.rewind().map( + x => [x.key, x.props, x.type] + ); +} + +Head.peek().map( + x => [x.key, x.props, x.type] +); diff --git a/types/next/test/next-router-tests.tsx b/types/next/test/next-router-tests.tsx index 38d091dcc2..37e739d98a 100644 --- a/types/next/test/next-router-tests.tsx +++ b/types/next/test/next-router-tests.tsx @@ -20,9 +20,12 @@ function split(routeLike: string) { }); } +if (Router.asPath) { + split(Router.asPath); + split(Router.asPath); +} + split(Router.pathname); -split(Router.asPath); -split(Router.asPath); const query = `?${qs.stringify(Router.query)}`; From 5bee3a49cb07ef70651a2d330fa01053bd79573a Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 24 Jul 2017 19:33:31 +0200 Subject: [PATCH 0238/1139] [file-type] add typings for browser version (#18264) * [file-type] add typings for browser version * [file-type] fix url to definitelyTyped repo in header --- types/file-type/file-type-tests.ts | 7 +++---- types/file-type/index.d.ts | 9 +++++---- types/file-type/tslint.json | 1 + 3 files changed, 9 insertions(+), 8 deletions(-) create mode 100644 types/file-type/tslint.json diff --git a/types/file-type/file-type-tests.ts b/types/file-type/file-type-tests.ts index 1ce0bf6bdf..ecfd658a1a 100644 --- a/types/file-type/file-type-tests.ts +++ b/types/file-type/file-type-tests.ts @@ -1,5 +1,4 @@ -"use strict"; +import fileType = require("file-type"); -import fileType = require("file-type") - -fileType(new Buffer([0xFF, 0xD8, 0xFF])) +fileType(new Buffer([0xFF, 0xD8, 0xFF])); +fileType(new Uint8Array([0xFF, 0xD8, 0xFF])); diff --git a/types/file-type/index.d.ts b/types/file-type/index.d.ts index 3a88fe0a94..95217430eb 100644 --- a/types/file-type/index.d.ts +++ b/types/file-type/index.d.ts @@ -1,16 +1,17 @@ -// Type definitions for file-type +// Type definitions for file-type 5.2 // Project: https://github.com/sindresorhus/file-type // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk -// Definitions: https://github.com/DefinitelyType/DefinitelyTyped +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// export = FileType; -declare function FileType(buf: Buffer): FileType.FileTypeResult; +declare function FileType(buf: Buffer | Uint8Array): FileType.FileTypeResult; declare namespace FileType { - export interface FileTypeResult { + interface FileTypeResult { ext: string; mime: string; } diff --git a/types/file-type/tslint.json b/types/file-type/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/file-type/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 910023509a2a0d5e7c62531248bd5fdbffc8d77c Mon Sep 17 00:00:00 2001 From: Nick Graham Date: Mon, 24 Jul 2017 12:33:52 -0500 Subject: [PATCH 0239/1139] [material-ui] Adds missing subtitleStyleProps to GridTile (#18271) * Adds props to GridTile * Removes the children prop that I added --- types/material-ui/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 6180f193f7..632ab397b7 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -1055,6 +1055,7 @@ declare namespace __MaterialUI { rows?: number; style?: React.CSSProperties; subtitle?: React.ReactNode; + subtitleStyle?: React.CSSProperties; title?: React.ReactNode; titleBackground?: string; titlePosition?: "top" | "bottom"; From dfda34b1c242a8f6ef65de26fbb584fb943dedf4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?william=20chang=28=E5=BC=B5=E4=BB=B2=E5=A8=81=29?= Date: Tue, 25 Jul 2017 01:37:46 +0800 Subject: [PATCH 0240/1139] [node] net.Server, http.Server, http.ServerRequest, http.ServerResponse, http.ClientRequest, http.IncomingMessage, http.ClientResponse fix from interface to class and add constructors. (#18281) * [node] net.Server, http.Server, http.ServerRequest, http.ServerResponse, http.ClientRequest, http.IncomingMessage, http.ClientResponse, http.Server fix from interface to class and add constructors. * add http constructor tests * fix lint * add author * fix: remove rejectUnauthorized, createConnection callback make more detailed, http.Server requestListener more detailed, add export OutgoingMessage, ServerResponse and ClientRequest extends OutgoingMessage. combine the constructors in ClientRequest * add more http tests * remove trailing space * remove deprecated apis, private props not documented, seperate httpHeaders to incoming and outgoing, fix rejectUnauthorized prop misplaced, use () => void for callback * typo * settimeout return this --- types/node/index.d.ts | 149 ++++++++++++++++++++++----------------- types/node/node-tests.ts | 83 ++++++++++++++++++++++ 2 files changed, 167 insertions(+), 65 deletions(-) diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 518b1d5d00..017124eb7e 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -10,6 +10,7 @@ // Chigozirim C. // Flarna // Mariusz Wiktorczyk +// wwwy3y3 // Daniel Imms // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -773,24 +774,40 @@ declare module "http" { import * as stream from "stream"; import { URL } from "url"; - export interface RequestOptions { + // incoming headers will never contain number + export interface IncomingHttpHeaders { + [header: string]: string | string[]; + } + + // outgoing headers allows nubmers (as they are converted internally to strings) + export interface OutgoingHttpHeaders { + [header: string]: number | string | string[]; + } + + export interface ClientRequestArgs { protocol?: string; host?: string; hostname?: string; family?: number; port?: number | string; + defaultPort?: number | string; localAddress?: string; socketPath?: string; method?: string; path?: string; - headers?: { [key: string]: any }; + headers?: OutgoingHttpHeaders; auth?: string; agent?: Agent | boolean; + _defaultAgent?: Agent, timeout?: number; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L278 + createConnection?: (options: ClientRequestArgs, oncreate: (err: Error, socket: net.Socket) => void) => net.Socket; } - export interface Server extends net.Server { - setTimeout(msecs: number, callback: Function): void; + export class Server extends net.Server { + constructor(requestListener?: (req: IncomingMessage, res: ServerResponse) => void); + + setTimeout(msecs: number, callback: () => void): this; maxHeadersCount: number; timeout: number; listening: boolean; @@ -798,86 +815,78 @@ declare module "http" { /** * @deprecated Use IncomingMessage */ - export interface ServerRequest extends IncomingMessage { + export class ServerRequest extends IncomingMessage { connection: net.Socket; } - export interface ServerResponseHeaders { - [key: string]: number | string | string[]; + // https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js + export class OutgoingMessage extends stream.Writable { + upgrading: boolean; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + finished: boolean; + headersSent: boolean; + connection: net.Socket; + + constructor(); + + setTimeout(msecs: number, callback?: () => void): this; + destroy(error: Error): void; + setHeader(name: string, value: number | string | string[]): void; + getHeader(name: string): number | string | string[] | undefined; + getHeaders(): OutgoingHttpHeaders; + getHeaderNames(): string[]; + hasHeader(name: string): boolean; + removeHeader(name: string): void; + addTrailers(headers: OutgoingHttpHeaders | [string, string][]): void; + flushHeaders(): void; } - export interface ServerResponse extends stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - - addTrailers(headers: ServerResponseHeaders): void; - finished: boolean; - getHeader(name: string): number | string | string[] | undefined; - getHeaderNames(): string[] - getHeaders(): any - hasHeader(name: string): boolean - headersSent: boolean; - removeHeader(name: string): void; - sendDate: boolean; - setHeader(name: string, value: string | string[]): void; - setTimeout(msecs: number, callback: Function): ServerResponse; + // https://github.com/nodejs/node/blob/master/lib/_http_server.js#L108-L256 + export class ServerResponse extends OutgoingMessage { statusCode: number; statusMessage: string; - write(chunk: any, encoding?: string): any; - writeContinue(): void; - writeHead(statusCode: number, reasonPhrase?: string, headers?: ServerResponseHeaders): void; - writeHead(statusCode: number, headers?: ServerResponseHeaders): void; - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; + constructor(req: IncomingMessage); + + assignSocket(socket: net.Socket): void; + detachSocket(socket: net.Socket): void; + // https://github.com/nodejs/node/blob/master/test/parallel/test-http-write-callbacks.js#L53 + // no args in writeContinue callback + writeContinue(callback?: () => void): void; + writeHead(statusCode: number, reasonPhrase?: string, headers?: OutgoingHttpHeaders): void; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): void; } - export interface ClientRequest extends stream.Writable { - // Extended base methods - write(buffer: Buffer): boolean; - write(buffer: Buffer, cb?: Function): boolean; - write(str: string, cb?: Function): boolean; - write(str: string, encoding?: string, cb?: Function): boolean; - write(str: string, encoding?: string, fd?: string): boolean; - write(chunk: any, encoding?: string): void; + // https://github.com/nodejs/node/blob/master/lib/_http_client.js#L77 + export class ClientRequest extends OutgoingMessage { + connection: net.Socket; + socket: net.Socket; + aborted: number; + + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + abort(): void; - setTimeout(timeout: number, callback?: Function): void; + onSocket(socket: net.Socket): void; + setTimeout(timeout: number, callback?: () => void): this; setNoDelay(noDelay?: boolean): void; setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; - - setHeader(name: string, value: string | string[]): void; - getHeader(name: string): string; - removeHeader(name: string): void; - addTrailers(headers: any): void; - - // Extended base methods - end(): void; - end(buffer: Buffer, cb?: Function): void; - end(str: string, cb?: Function): void; - end(str: string, encoding?: string, cb?: Function): void; - end(data?: any, encoding?: string): void; } - export interface IncomingMessageHeaders { - [key: string]: string | string[] | undefined; - } - export interface IncomingMessage extends stream.Readable { + + export class IncomingMessage extends stream.Readable { + constructor(socket: net.Socket); + httpVersion: string; httpVersionMajor: number; httpVersionMinor: number; connection: net.Socket; - headers: IncomingMessageHeaders; + headers: IncomingHttpHeaders; rawHeaders: string[]; trailers: { [key: string]: string }; rawTrailers: string[]; - setTimeout(msecs: number, callback: Function): NodeJS.Timer; + setTimeout(msecs: number, callback: () => void): this; /** * Only valid for request obtained from http.Server. */ @@ -897,10 +906,11 @@ declare module "http" { socket: net.Socket; destroy(error?: Error): void; } + /** * @deprecated Use IncomingMessage */ - export interface ClientResponse extends IncomingMessage { } + export class ClientResponse extends IncomingMessage { } export interface AgentOptions { /** @@ -944,8 +954,13 @@ declare module "http" { [errorCode: number]: string; [errorCode: string]: string; }; + export function createServer(requestListener?: (request: IncomingMessage, response: ServerResponse) => void): Server; export function createClient(port?: number, host?: string): any; + + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + export interface RequestOptions extends ClientRequestArgs {} export function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; export function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; export var globalAgent: Agent; @@ -2438,7 +2453,11 @@ declare module "net" { exclusive?: boolean; } - export interface Server extends events.EventEmitter { + // https://github.com/nodejs/node/blob/master/lib/net.js + export class Server extends events.EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: { allowHalfOpen?: boolean, pauseOnConnect?: boolean }, connectionListener?: (socket: Socket) => void); + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; listen(port?: number, hostname?: string, listeningListener?: Function): Server; listen(port?: number, backlog?: number, listeningListener?: Function): Server; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 10ce35e723..4c2f5de484 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -1062,6 +1062,89 @@ namespace tls_tests { //////////////////////////////////////////////////// namespace http_tests { + // http Server + { + var server: http.Server = new http.Server(); + } + + // http IncomingMessage + // http ServerResponse + { + // incoming + var incoming: http.IncomingMessage = new http.IncomingMessage(new net.Socket()); + + incoming.setEncoding('utf8'); + + // stream + incoming.pause(); + incoming.resume(); + + // response + var res: http.ServerResponse = new http.ServerResponse(incoming); + + // test headers + res.setHeader('Content-Type', 'text/plain'); + var bool: boolean = res.hasHeader('Content-Type'); + var headers: string[] = res.getHeaderNames(); + + // trailers + res.addTrailers([ + ['x-fOo', 'xOxOxOx'], + ['x-foO', 'OxOxOxO'], + ['X-fOo', 'xOxOxOx'], + ['X-foO', 'OxOxOxO'] + ]); + res.addTrailers({'x-foo': 'bar'}); + + // writeHead + res.writeHead(200, 'OK\r\nContent-Type: text/html\r\n'); + res.writeHead(200, { 'Transfer-Encoding': 'chunked' }); + res.writeHead(200); + + // write string + res.write('Part of my res.'); + // write buffer + const chunk = Buffer.alloc(16390, 'Й'); + req.write(chunk); + res.write(chunk, 'hex'); + + // end + res.end("end msg"); + // without msg + res.end(); + + // flush + res.flushHeaders(); + } + + // http ClientRequest + { + var req: http.ClientRequest = new http.ClientRequest("https://www.google.com"); + var req: http.ClientRequest = new http.ClientRequest(new url.URL("https://www.google.com")); + var req: http.ClientRequest = new http.ClientRequest({ path: 'http://0.0.0.0' }); + + // header + req.setHeader('Content-Type', 'text/plain'); + var bool: boolean = req.hasHeader('Content-Type'); + var headers: string[] = req.getHeaderNames(); + req.removeHeader('Date'); + + // write + const chunk = Buffer.alloc(16390, 'Й'); + req.write(chunk); + req.write('a'); + req.end(); + + // abort + req.abort(); + + // connection + req.connection.on('pause', () => {}); + + // event + req.on('data', () => {}); + } + { // Status codes var codeMessage = http.STATUS_CODES['400']; From 8cd84431d4fcbf32a8b22d3f209568ba2278fc8b Mon Sep 17 00:00:00 2001 From: Clark Stevenson Date: Mon, 24 Jul 2017 19:39:29 +0200 Subject: [PATCH 0241/1139] Minor Updates Pixi.js (#18295) - Fixes a few minor bugs on the latest release. --- types/pixi.js/index.d.ts | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index f7410baaa6..3f7f65390d 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -1139,7 +1139,7 @@ declare namespace PIXI { class WebGLManager { constructor(renderer: WebGLRenderer); - renderer: SystemRenderer; + renderer: WebGLRenderer; onContextChange(): void; destroy(): void; } @@ -2000,7 +2000,8 @@ declare namespace PIXI { type InteractionMouseEvents = "rightdown" | "mousedown" | "rightup" | "mouseup" | "rightclick" | "click" | "rightupoutside" | "mouseupoutside" | "mousemove" | "mouseover" | "mouseout" | "mouseover"; - type InteractionEventTypes = InteractionPointerEvents | InteractionTouchEvents | InteractionMouseEvents; + type InteractionPixiEvents = "added" | "removed"; + type InteractionEventTypes = InteractionPointerEvents | InteractionTouchEvents | InteractionMouseEvents | InteractionPixiEvents; interface InteractionManagerOptions { autoPreventDefault?: boolean; interactionFrequency?: number; @@ -2080,7 +2081,7 @@ declare namespace PIXI { // pixi loader extends // https://github.com/englercj/resource-loader/ - // 2.0.6 + // 2.0.9 class MiniSignalBinding { //tslint:disable-next-line:ban-types forbidden-types @@ -2121,9 +2122,11 @@ declare namespace PIXI { crossOrigin?: boolean | string; loadType?: number; xhrType?: string; - metaData?: any; - loadElement?: HTMLImageElement | HTMLAudioElement | HTMLVideoElement; - skipSource?: boolean; + metaData?: { + loadElement?: HTMLImageElement | HTMLAudioElement | HTMLVideoElement; + skipSource?: boolean; + mimeType?: string | string[]; + }; } interface ResourceDictionary { [index: string]: PIXI.loaders.Resource; @@ -2617,7 +2620,7 @@ declare namespace PIXI { drawType: number; data: ArrayBuffer | ArrayBufferView | any; - upload(data: ArrayBuffer | ArrayBufferView | any, offset?: number, dontBind?: boolean): void; + upload(data?: ArrayBuffer | ArrayBufferView | any, offset?: number, dontBind?: boolean): void; bind(): void; static createVertexBuffer(gl: WebGLRenderingContext, data: ArrayBuffer | ArrayBufferView | any, drawType: number): GLBuffer; @@ -2713,7 +2716,7 @@ declare namespace PIXI { class VertexArrayObject { static FORCE_NATIVE: boolean; - constructor(gl: WebGLRenderingContext, state: WebGLState); + constructor(gl: WebGLRenderingContext, state?: WebGLState); protected nativeVaoExtension: any; protected nativeState: AttribState; @@ -2808,7 +2811,7 @@ declare namespace PIXI { class EventEmitter { static prefixed: string | boolean; static EventEmitter: { - new (): EventEmitter; + new(): EventEmitter; prefixed: string | boolean; }; /** From 6b00563c2d7ab801c2a9fa6476a95e0714391934 Mon Sep 17 00:00:00 2001 From: Jerod King Date: Mon, 24 Jul 2017 10:40:48 -0700 Subject: [PATCH 0242/1139] Fixing findCreateFind to return [Model, created] (#18305) http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-findCreateFind --- types/sequelize/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 921515276b..e767118394 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -3915,7 +3915,7 @@ declare namespace sequelize { * A more performant findOrCreate that will not work under a transaction (at least not in postgres) * Will execute a find call, if empty then attempt to create, if unique constraint then attempt to find again */ - findCreateFind(options: FindCreateFindOptions): Promise; + findCreateFind(options: FindCreateFindOptions): Promise<[TInstance, boolean]>; /** * Insert or update a single row. An update will be executed if a row which matches the supplied values on From 56d1e73dc8639d13be829cdd2b5d12e51fb19554 Mon Sep 17 00:00:00 2001 From: Dimitri Benin Date: Mon, 24 Jul 2017 19:56:31 +0200 Subject: [PATCH 0243/1139] [cookie] add linting and fix found issues (#18310) --- types/cookie/cookie-tests.ts | 10 ++++------ types/cookie/index.d.ts | 12 +++++++----- types/cookie/tslint.json | 1 + 3 files changed, 12 insertions(+), 11 deletions(-) create mode 100644 types/cookie/tslint.json diff --git a/types/cookie/cookie-tests.ts b/types/cookie/cookie-tests.ts index dd5be0f850..08e4d43519 100644 --- a/types/cookie/cookie-tests.ts +++ b/types/cookie/cookie-tests.ts @@ -1,23 +1,21 @@ - - import cookie = require('cookie'); function test_serialize(): void { - var retVal: string; + let retVal: string; retVal = cookie.serialize('foo', 'bar'); retVal = cookie.serialize('foo', 'bar', { httpOnly: true }); } function test_parse(): void { - var retVal: { [key: string]: string }; + let retVal: { [key: string]: string }; retVal = cookie.parse('foo=bar; bar=baz;'); retVal = cookie.parse('foo=bar; bar=baz', { decode: x => x }); } function test_options(): void { - var serializeOptions: cookie.CookieSerializeOptions = { + const serializeOptions: cookie.CookieSerializeOptions = { encode: (x: string) => x, path: '/', expires: new Date(), @@ -27,7 +25,7 @@ function test_options(): void { httpOnly: false }; - var parseOptios: cookie.CookieParseOptions = { + const parseOptios: cookie.CookieParseOptions = { decode: (x: string) => x }; } diff --git a/types/cookie/index.d.ts b/types/cookie/index.d.ts index 507eaee01d..bb7fc2cb54 100644 --- a/types/cookie/index.d.ts +++ b/types/cookie/index.d.ts @@ -1,15 +1,16 @@ -// Type definitions for cookie v0.3.0 +// Type definitions for cookie 0.3 // Project: https://github.com/jshttp/cookie // Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -interface CookieSerializeOptions { +export interface CookieSerializeOptions { /** * Specifies the value for the Domain Set-Cookie attribute. By default, no * domain is set, and most clients will consider the cookie to apply to only * the current domain. */ domain?: string; + /** * Specifies a function that will be used to encode a cookie's value. Since * value of a cookie has a limited character set (and must be a simple @@ -20,7 +21,8 @@ interface CookieSerializeOptions { * encode a JavaScript string into UTF-8 byte sequences and then URL-encode * any that fall outside of the cookie range. */ - encode?: (val: string) => string; + encode?(val: string): string; + /** * Specifies the `Date` object to be the value for the `Expires` * `Set-Cookie` attribute. By default, no expiration is set, and most @@ -83,7 +85,7 @@ interface CookieSerializeOptions { secure?: boolean; } -interface CookieParseOptions { +export interface CookieParseOptions { /** * Specifies a function that will be used to decode a cookie's value. Since * the value of a cookie has a limited character set (and must be a simple @@ -96,7 +98,7 @@ interface CookieParseOptions { * *Note* if an error is thrown from this function, the original, non-decoded * cookie value will be returned as the cookie's value. */ - decode?: (val: string) => string; + decode?(val: string): string; } /** diff --git a/types/cookie/tslint.json b/types/cookie/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cookie/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 17610c15f1bab70722b3a433b635801adf9157b7 Mon Sep 17 00:00:00 2001 From: Boriss Nazarovs Date: Mon, 24 Jul 2017 20:57:43 +0300 Subject: [PATCH 0244/1139] Update typings for riot v3.6 (#18311) --- types/riot/index.d.ts | 1083 ++++++++++++++++++++++++-------------- types/riot/riot-tests.ts | 145 ++--- types/riot/tsconfig.json | 6 +- types/riot/tslint.json | 3 + 4 files changed, 752 insertions(+), 485 deletions(-) create mode 100644 types/riot/tslint.json diff --git a/types/riot/index.d.ts b/types/riot/index.d.ts index 3c76a0b1d0..079132db72 100644 --- a/types/riot/index.d.ts +++ b/types/riot/index.d.ts @@ -1,426 +1,727 @@ -// Type definitions for riot v2.6.0 +// Type definitions for riot 3.6 // Project: https://github.com/riot/riot // Definitions by: Boriss Nazarovs // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare namespace riot { +/** + * Current version number as a string + */ +export const version: string; + +/** + * Riot settings + */ +export interface Settings { /** - * Current version number as string + * Setting used to customize the start and end tokens of the expression + * @default { } */ - const version: string; + brackets: string; + /** + * If set to false, riot will not create lighter tag instances for anonymous tags + * @default true + */ + skipAnonymousTags: boolean; + /** + * If set to false, DOM event handlers will not trigger update events + * @default true + */ + autoUpdate: boolean; + /** + * `riot.renderAsync` timeout in ms + * @default 1000 + */ + asyncRenderTimeout: number; +} + +export const settings: Settings; + +export interface TemplateError extends Error { + riotData: { + _riot_id: number; + tagName: string; + }; +} + +/** + * Riot template engine + */ +export interface Tmpl { + (expression: string, data?: any): any; + + version: string; /** - * Riot settings + * Utility hook function to catch all the errors swallowed by the riot template engine */ - interface Settings { - /** - * Setting used to customize the start and end tokens of the expression - */ - brackets: string; - } + errorHandler(error: TemplateError): void; +} - const settings: Settings; +/** + * Object that is used to inject and manage the css of every tag instance + */ +export interface StyleManager { + styleNode: HTMLStyleElement; - interface TemplateError extends Error { - riotData: { - tagName: string; - } - } + /** + * Save a tag style to be later injected into DOM + * @param {string} css - css string + * @param {string} name - if it's passed the css will be mapped to a tagname + */ + add(css: string, name?: string): void; - interface Util { - tmpl: { - errorHandler(error: TemplateError): void; - } - } + /** + * Inject all previously saved tag styles into DOM + */ + inject(): void; +} - const util: Util; +export interface DOMUtil { + /** + * Select multiple nodes in the DOM + * @param selector - DOM selector + * @param ctx - DOM node where the targets of our search will is located + * @returns DOM nodes found + */ + $$(selector: string, ctx?: Element): Element[]; + + /** + * Select a single node in the DOM + * @param selector - unique dom selector + * @param ctx - DOM node where the target of search will is located + * @returns DOM node found + */ + $(selector: string, ctx?: Element): Element | null; + + /** + * Create a document fragment + * @returns Document fragment + */ + createFrag(): DocumentFragment; + + /** + * Create a document text node + * @returns Text node + */ + createDOMPlaceholder(): Text; + + /** + * Check if a DOM node is an svg element + * @param element - node to check + * @returns { boolean } True if element is an svg element + */ + isSvg(element: Element): element is SVGElement; + + /** + * Create a generic DOM node + * @param name - name of the DOM node + * @returns Created element + */ + mkEl(name: string): Element; + + /** + * Set the inner html of any DOM node SVGs included + * @param container - DOM node where html should be injected + * @param html - html to inject + */ + setInnerHTML(container: Element, html: string): void; + + /** + * Toggle the visibility of a DOM node + * @param element - DOM node to update visibility for + * @param show - If true element is shown + */ + toggleVisibility(element: Element, show?: boolean): void; + + /** + * Remove any DOM attribute from a node + * @param element - DOM node to update + * @param name - name of the attribute + */ + remAttr(element: Element, name: string): void; + + /** + * Get the value of any DOM attribute on a node + * @param element - DOM node + * @param name - name of the attribute + * @returns Attribute value + */ + getAttr(element: Element, name: string): string | null; + + /** + * Set any DOM attribute + * @param element - DOM node we want to update + * @param name - name of the property we want to set + * @param value - value of the property we want to set + */ + setAttr(element: Element, name: string, value: string): void; + + /** + * Convert a style object to a string + * @param style - style object to parse + * @returns Resulting css string + */ + styleObjectToString(style: any): string; + + /** + * Insert tag safely + * @param root - children container + * @param curr - node to insert + * @param next - node that should precede inserted node + */ + safeInsert(root: Node, curr: Node, next: Node): void; + + /** + * Run callback function for each attribute in html string + * @param html - html string we want to parse + * @param fn - callback function to apply on found attributes + */ + walkAttrs(html: string, fn: (attrName: string, attrValue: string) => void): void; + + /** + * Walk down recursively through all child nodes starting with provided dom node + * @param node - starting node where we will start the recursion + * @param fn - callback to transform the child node just found + * @param context - fn can optionally return an object, which is passed to children + */ + walkNodes(node: Node, fn: (node: Node, context: any) => any, context: any): void; +} + +export interface CheckUtil { + /** + * Check if provided value is name of boolean attribute + * @param value - name to check + * @returns True if value is name of boolean attribute + */ + isBoolAttr(value: string): boolean; + + /** + * Check if provided value is a function + * @param value - reference to check + * @returns True if provided value is a function + */ + isFunction(value: any): boolean; + + /** + * Check if provided value is an object (null excluded) + * @param value - reference to check + * @returns True if provided value is an object + */ + isObject(value: any): boolean; + + /** + * Check if provided value is undefined + * @param value - reference to check + * @returns True if provided value is undefined + */ + isUndefined(value: any): boolean; + + /** + * Check if provided value is a string + * @param value - reference to check + * @returns True if provided value is a string + */ + isString(value: any): value is string; + + /** + * Check if provided value is empty. Different from falsy, because 0 or false are not considered to be blank + * @param value - value to check + * @returns True if provided value is undefined, null or empty string + */ + isBlank(value: any): boolean; + + /** + * Check if provided value is an array + * @param value - reference to check + * @returns True if provided value is an array + */ + isArray(value: any): boolean; + + /** + * Check whether object's property could be overridden + * @param obj - source object + * @param key - object property + * @returns True if value for specified key can be overridden + */ + isWritable(obj: any, key: string): boolean; + + /** + * Check if provided string is a reserved name for Riot tag instances + * @param value - name to check + * @returns True if provided string is a reserved name + */ + isReservedName(value: string): boolean; +} + +export interface MiscUtil { + /** + * Specialized function for looping over array-like collections + * @param list - collection of items + * @param fn - callback applied to each item + */ + each(list: any, fn: (item: any, index: number) => void): void; + + /** + * Check whether an array contains an item + * @param arr - target array + * @param item - item to test + * @returns True if array contains item + */ + contains(arr: any[], item: any): boolean; + + /** + * Convert a string containing dashes to camel case + * @param str - input string + * @returns my-string -> myString + */ + toCamel(str: string): string; + + /** + * Check if string starts with specified value + * @param str - source string + * @param value - test string + * @returns True if string starts with provided value + */ + startsWith(str: string, value: string): boolean; + + /** + * Helper function to set an immutable property + * @param el - object where the new property will be set + * @param key - object key where the new property will be stored + * @param value - value of the new property + * @param options - set the property overriding the default options + * @returns The initial object + */ + defineProperty(el: any, key: string, value: any, options: any): any; + + /** + * Extend any object with other properties + * @param args - objects to merge + * @returns The resulting extended object + */ + extend(...args: any[]): any; +} + +export interface TagsUtil { + /** + * Detect the tag implementation by a DOM node + * @param element - DOM node we need to parse to get its tag implementation + * @returns Object containing the implementation of a custom tag (template and boot function) + */ + getTag(element: Element): any; + + /** + * Inherit properties from a target tag instance + * @param target - tag where we will inherit properties + * @param propsInSyncWithParent - array of properties to sync with the target + */ + inheritFrom(this: TagInstance, target: TagInstance, propsInSyncWithParent: string[]): void; + + /** + * Move the position of a custom tag in its parent tag + * @param tagName - key where the tag was stored + * @param newPos - index where the new tag will be stored + */ + moveChildTag(this: TagInstance, tagName: string, newPos: number): void; + + /** + * Create a new child tag including it correctly into its parent + * @param child - child tag implementation + * @param opts - tag options containing the DOM node where the tag will be mounted + * @param innerHTML - inner html of the child node + * @param parent - instance of the parent tag including the child custom tag + * @returns Instance of the new child tag just created + */ + initChildTag(child: any, opts: any, innerHTML: string, parent: TagInstance): TagInstance; + + /** + * Loop backward all the parents tree to detect the first custom parent tag + * @param tag - a tag instance + * @returns Instance of the first custom parent tag found + */ + getImmediateCustomParentTag(tag: TagInstance): TagInstance; + + /** + * Trigger the unmount method on all the expressions + * @param expressions - DOM expressions + */ + unmountAll(expressions: any[]): void; + + /** + * Get the tag name of any DOM node + * @param dom - DOM node we want to parse + * @param skipDataIs - hack to ignore the data-is attribute when attaching to parent + * @returns Name to identify this dom node in riot + */ + getTagName(dom: Element, skipDataIs: boolean): string; + + /** + * With this function we avoid that the internal Tag methods get overridden + * @param data - options we want to use to extend the tag instance + * @returns Clean object without containing the riot internal reserved words + */ + cleanUpData(data: any): any; + + /** + * Set the property of an object for a given key. If something already + * exists there, then it becomes an array containing both the old and new value. + * @param obj - object on which to set the property + * @param key - property name + * @param value - the value of the property to be set + * @param ensureArray - ensure that the property remains an array + * @param index - add the new item in a certain array position + */ + arrayishAdd(obj: any, key: string, value: any, ensureArray?: boolean, index?: number): void; + + /** + * Removes an item from an object at a given key. If the key points to an array, + * then the item is just removed from the array. + * @param obj - object on which to remove the property + * @param key - property name + * @param value - the value of the property to be removed + * @param ensureArray - ensure that the property remains an array + */ + arrayishRemove(obj: any, key: string, value: any, ensureArray?: boolean): void; + + /** + * Mount a tag creating new Tag instance + * @param root - dom node where the tag will be mounted + * @param tagName - name of the riot tag we want to mount + * @param opts - options to pass to the Tag instance + * @param ctx - optional context that will be used to extend an existing class ( used in riot.Tag ) + * @returns Created tag instance + */ + mountTo(root: Element, tagName: string, opts?: TagOpts, ctx?: any): TagInstance; + + /** + * Makes a tag virtual and replaces a reference in the dom + * @param tag - tag to make virtual + * @param ref - dom reference location + */ + makeReplaceVirtual(tag: TagInstance, ref: Node): void; + + /** + * Adds the elements for a virtual tag + * @param src - the node that will do the inserting or appending + * @param target - only if inserting, insert before this tag's first child + */ + makeVirtual(this: TagInstance, src: Node, target?: TagInstance): void; + + /** + * Move virtual tag and all child nodes + * @param src - the node that will do the inserting + * @param target - insert before this tag's first child + */ + moveVirtual(this: TagInstance, src: Node, target: TagInstance): void; + + /** + * Get selectors for tags + * @param tags - tag names to select + * @returns Selector + */ + selectTags(tags: string[]): string; +} + +export interface Util { + /** + * Reference to the internal riot template engine + */ + tmpl: Tmpl; /** * Internal riot tags cache */ - const vdom: Tag[]; - - interface Observable { - /** - * Register callback for specified events. - * Callback is executed each time event is triggered - * @param events Space separated list of events or wildcard '*' that matches all events - * @param callback Callback function - */ - on?(events: string, callback: Function): Observable; - - /** - * Register callback for specified events. - * Callback is executed at most once. - * @param events Space separated list of events. - * @param callback Callback function - */ - one?(events: string, callback: Function): Observable; - - /** - * Remove all registered callbacks for specified events - * @param events Space separated list of events or wildcard '*' that matches all events - */ - off?(events: string): Observable; - - /** - * Remove specified callback for specified events - * @param events Space separated list of events or wildcard '*' that matches all events - * @param callback Callback function to remove - */ - off?(events: string, callback: Function): Observable; - - /** - * Execute all callback functions registered for specified list of events - * @param events Space separated list of events - * @param args Arguments provided to callbacks - */ - trigger?(events: string, ...args: any[]): Observable; - } + vdom: TagInstance[]; /** - * Riot Router + * Object used to append and create custom tags css */ - interface Route { - /** - * Register callback that is executed when the URL changes - * @param callback Callback function - */ - (callback: (...args: any[]) => void): void; - - /** - * Register callback that is executed when the URL changes and new URL matches specified filter - * @param filter URL filter - * @param callback Callback function - */ - (filter: string, callback: (...any: string[]) => void): void; - - /** - * Change the browser URL and notify all the listeners registered with `Route(callback)` - * @param to New URL - * @param title Document title for new URL - * @param shouldReplace Should new url replace the current history - */ - (to: string, title?: string, shouldReplace?: boolean): void; - - /** - * Return a new routing context - */ - create(): Route; - - /** - * Start listening for url changes - * @param autoExec Should router exec routing on the current url - */ - start(autoExec?: boolean): void; - - /** - * Stop all the routings. - * Removes the listeners and clears the callbacks. - */ - stop(): void; - - /** - * Study the current browser path “in place” and emit routing without waiting for it to change. - */ - exec(): void; - - /** - * @deprecated - */ - exec(callback: Function): void; - - /** - * Extract query from the url - */ - query(): { [key: string]: string }; - - /** - * Change the base path - * @param base Base path - */ - base(base: string): void; - - /** - * Change the default parsers to the custom ones. - * @param parser Replacement parser for default parser - * @param secondParser Replacement parser for handling url filters - */ - parser(parser: (path: string) => any[], secondParser?: (path: string, filter: string) => any[]): void; - } + styleManager: StyleManager; /** - * Adds Observer support for the given object or - * if the argument is empty a new observable instance is created and returned. - * @param el Object to become observable + * Series of utility functions to query and update DOM nodes */ - function observable(el?: any): Observable; - - const route: Route; + dom: DOMUtil; /** - * Mount custom tags with specified tag name. Returns an array of mounted tag instances. - * @param selector Tag selector. - * It can be tag name, css selector or special '*' selector that matches all tags on the page. - * @param opts Optional object passed for the tags to consume. + * Series of helper functions needed for type checking */ - function mount(selector: string, opts?: any): Tag[]; + check: CheckUtil; /** - * Mount a custom tag on DOM nodes matching provided selector. Returns an array of mounted tag instances. - * @param selector CSS selector - * @param tagName Custom tag name - * @param opts Optional object passed for the tag to consume. + * Generic helper functions */ - function mount(selector: string, tagName: string, opts?: any): Tag[]; + misc: MiscUtil; /** - * Mount a custom tag on a given DOM node. Returns an array of mounted tag instances. - * @param domNode DOM node - * @param tagName Tag name - * @param opts Optional object passed for the tag to consume. + * Methods for managing all the riot tags instances */ - function mount(domNode: Node, tagName: string, opts?: any): Tag[]; - - /** - * Render a tag to html. This method is only available on server-side. - * @param tagName Custom tag name - * @param opts Optional object passed for the tag to consume. - */ - function render(tagName: string, opts?: any): string; - - /** - * Update all the mounted tags and their expressions on the page. - * Returns an array of tag instances that are mounted on the page. - */ - function update(): Tag[]; - - /** - * Register a global mixin and automatically add it to all tag instances. - * @param mixinObject Mixin object - */ - function mixin(mixinObject: TagMixin): void; - - /** - * Register a shared mixin, globally available to be used in any tag using `TagInstance.mixin(mixinName)` - * @param mixinName Name of the mixin - * @param mixinObject Mixin object - * @param isGlobal Is global mixin? - */ - function mixin(mixinName: string, mixinObject: TagMixin, isGlobal?: boolean): void; - - /** - * Create a new custom tag “manually” without the compiler. Returns name of the tag. - * @param tagName The tag name - * @param html The layout with expressions - * @param css The style of the tag - * @param attrs String of attributes for the tag - * @param constructor The initialization function being called before - * the tag expressions are calculated and before the tag is mounted - */ - function tag(tagName: string, html: string, css?: string, attrs?: string, constructor?: (opts: any) => void): string; - - - interface TagImplementation { - /** - * Tag template - */ - tmpl: string; - /** - * The callback function called on the mount event - * @param opts Tag options object - */ - fn?(opts: any): void; - /** - * Root tag html attributes as object (key => value) - */ - attrs?: { - [key: string]: any; - } - } - - interface TagConfiguration { - /** - * DOM node where you will mount the tag template - */ - root: Node; - /** - * Tag options - */ - opts?: any; - /** - * Is it used in as loop tag - */ - isLoop?: boolean; - /** - * Is already registered using `riot.tag` - */ - hasImpl?: boolean; - /** - * Loop item in the loop assigned to this instance - */ - item?: any; - } - - interface TagInterface extends Observable { - /** - * options object - */ - opts?: any; - /** - * the parent tag if any - */ - parent?: Tag; - /** - * root DOM node - */ - root?: Node; - /** - * nested custom tags - */ - tags?: { - [key: string]: Tag | Tag[]; - }; - - /** - * Updates all the expressions on the current tag instance as well as on all the children. - * @param data Context data - */ - update?(data?: any): void; - - /** - * Extend tag with functionality available on shared mixin registered with `riot.mixin(mixinName, mixinObject)` - * @param mixinName Name of shared mixin - */ - mixin?(mixinName: string): void; - - /** - * Extend tag functionality with functionality available on provided mixin object. - * @param mixinObject Mixin object - */ - mixin?(mixinObject: TagMixin): void; - - /** - * Mount the tag - */ - mount?(): void; - - /** - * Detach the tag and its children from the page. - * @param keepTheParent If `true` unmounting tag doesn't remove the parent tag - */ - unmount?(keepTheParent?: boolean): void; - } - - - class Tag implements TagInterface { - /** - * Tag constructor - * @param impl Tag implementation - * @param conf Tag configuration - * @param innerHTML HTML that can be used replacing a nested `yield` tag in its template - */ - constructor(impl: TagImplementation, conf: TagConfiguration, innerHTML?: string); - - /** - * options object - */ - opts: any; - /** - * the parent tag if any - */ - parent: Tag; - /** - * root DOM node - */ - root: Node; - /** - * nested custom tags - */ - tags: { - [key: string]: Tag | Tag[]; - }; - - /** - * Updates all the expressions on the current tag instance as well as on all the children. - * @param data Context data - */ - update(data?: any): void; - - /** - * Extend tag with functionality available on shared mixin registered with `riot.mixin(mixinName, mixinObject)` - * @param mixinName Name of shared mixin - */ - mixin(mixinName: string): void; - - /** - * Extend tag functionality with functionality available on provided mixin object. - * @param mixinObject Mixin object - */ - mixin(mixinObject: TagMixin): void; - - /** - * Mount the tag - */ - mount(): void; - - /** - * Detach the tag and its children from the page. - * @param keepTheParent If `true` unmounting tag doesn't remove the parent tag - */ - unmount(keepTheParent?: boolean): void; - - // Observable methods - on(events: string, callback: Function): this; - one(events: string, callback: Function): this; - off(events: string): this; - off(events: string, callback: Function): this; - trigger(events: string, ...args: any[]): this; - } - - /** - * Mixin object for extending tag functionality. - * When it gets mixed in it has access to all tag properties. - * It should not override any built in tag properties - */ - interface TagMixin extends TagInterface { - /** - * Special method which can initialize - * the mixin when it's loaded to the tag and is not - * accessible from the tag its mixed in - */ - init?(): void; - } - - /** - * Compile all tags defined with '); dompurify.addHook('beforeSanitizeElements', (el, data, config) => { - return el; + return el; }); //examples from the DOMPurify README let dirty = '

    Totally safe

    Totally not safe

    '; // allow only -dompurify.sanitize(dirty, {ALLOWED_TAGS: ['b']}); +dompurify.sanitize(dirty, { ALLOWED_TAGS: ['b'] }); // allow only and with style attributes (for whatever reason) -dompurify.sanitize(dirty, {ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style']}); +dompurify.sanitize(dirty, { ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style'] }); // leave all as it is but forbid