diff --git a/notNeededPackages.json b/notNeededPackages.json index d6e99fbf9b..50d71d2165 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -138,6 +138,12 @@ "sourceRepoURL": "https://github.com/loopline-systems/electron-builder", "asOfVersion": "2.8.0" }, + { + "libraryName": "eventemitter2", + "typingsPackageName": "eventemitter2", + "sourceRepoURL": "https://github.com/asyncly/EventEmitter2", + "asOfVersion": "4.1.0" + }, { "libraryName": "EventEmitter3", "typingsPackageName": "eventemitter3", @@ -420,6 +426,12 @@ "sourceRepoURL": "https://github.com/angular/protractor", "asOfVersion": "4.0.0" }, + { + "libraryName": "qiniu", + "typingsPackageName": "qiniu", + "sourceRepoURL": "https://github.com/qiniu/nodejs-sdk", + "asOfVersion": "7.0.1" + }, { "libraryName": "Raven JS", "typingsPackageName": "raven-js", diff --git a/package.json b/package.json index 8e734f2b89..c2fef9b679 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "scripts": { "compile-scripts": "tsc -p scripts", "not-needed": "node scripts/not-needed.js", - "test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 4", + "test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed --nProcesses 8", "lint": "dtslint types" }, "devDependencies": { diff --git a/types/activex-adodb/activex-adodb-tests.ts b/types/activex-adodb/activex-adodb-tests.ts new file mode 100644 index 0000000000..cadb01c15e --- /dev/null +++ b/types/activex-adodb/activex-adodb-tests.ts @@ -0,0 +1,30 @@ +let obj0 = new ActiveXObject('ADODB.Command'); + +let obj1 = new ActiveXObject('ADODB.Connection'); + +let obj2 = new ActiveXObject('ADODB.Parameter'); + +let obj3 = new ActiveXObject('ADODB.Record'); + +let obj4 = new ActiveXObject('ADODB.Recordset'); + +let obj5 = new ActiveXObject('ADODB.Stream'); + +// open connection to an Excel file +let pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx'; +let conn = new ActiveXObject('ADODB.Connection'); +conn.Provider = 'Microsoft.ACE.OLEDB.12.0'; +conn.ConnectionString = + 'Data Source="' + pathToExcelFile + '";' + + 'Extended Properties="Excel 12.0;HDR=Yes"'; +conn.Open(); + +// create a Command to access the data +let cmd = new ActiveXObject('ADODB.Command'); +cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]'; +// get a Recordset +let rs = cmd.Execute(); +// build a string from the Recordset +let s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)'); +rs.Close(); +WScript.Echo(s); diff --git a/types/activex-data-objects/index.d.ts b/types/activex-adodb/index.d.ts similarity index 54% rename from types/activex-data-objects/index.d.ts rename to types/activex-adodb/index.d.ts index d3ccf7a6c7..ec5d67167a 100644 --- a/types/activex-data-objects/index.d.ts +++ b/types/activex-adodb/index.d.ts @@ -1,11 +1,9 @@ -// Type definitions for Microsoft ActiveX Data Objects -// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms675532(v=vs.85).aspx +// Type definitions for Microsoft ActiveX Data Objects 6.1 +// Project: https://msdn.microsoft.com/en-us/library/jj249010.aspx // Definitions by: Zev Spitz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace ADODB { - - //Enums const enum ADCPROP_ASYNCTHREADPRIORITY_ENUM { adPriorityAboveNormal = 4, adPriorityBelowNormal = 2, @@ -595,240 +593,415 @@ declare namespace ADODB { adXactSyncPhaseOne = 1048576 } - //Interfaces interface Command { ActiveConnection: Connection; - Cancel: () => void; - CommandStream: any /*VT_UNKNOWN*/; + Cancel(): void; + CommandStream: any; CommandText: string; CommandTimeout: number; CommandType: CommandTypeEnum; - CreateParameter: (Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any) => Parameter; + + /** + * @param string [Name=''] + * @param ADODB.DataTypeEnum [Type=0] + * @param ADODB.ParameterDirectionEnum [Direction=1] + * @param number [Size=0] + */ + CreateParameter(Name?: string, Type?: DataTypeEnum, Direction?: ParameterDirectionEnum, Size?: number, Value?: any): Parameter; Dialect: string; - Execute: (RecordsAffected?: any, Parameters?: any, Options?: number) => Recordset; + + /** @param number [Options=-1] */ + Execute(RecordsAffected?: any, Parameters?: any, Options?: number): Recordset; Name: string; NamedParameters: boolean; - Parameters: Parameters; + readonly Parameters: Parameters; Prepared: boolean; - Properties: Properties; - State: number; + readonly Properties: Properties; + readonly State: number; } interface Connection { Attributes: number; - BeginTrans: () => number; - Cancel: () => void; - Close: () => void; + BeginTrans(): number; + Cancel(): void; + Close(): void; CommandTimeout: number; - CommitTrans: () => void; + CommitTrans(): void; ConnectionString: string; ConnectionTimeout: number; CursorLocation: CursorLocationEnum; DefaultDatabase: string; - Errors: Errors; - Execute: (CommandText: string, RecordsAffected: any, Options?: number) => Recordset; + readonly Errors: Errors; + + /** @param number [Options=-1] */ + Execute(CommandText: string, RecordsAffected: any, Options?: number): Recordset; IsolationLevel: IsolationLevelEnum; Mode: ConnectModeEnum; - Open: (ConnectionString?: string, UserID?: string, Password?: string, Options?: number) => void; - OpenSchema: (Schema: SchemaEnum, Restrictions?: any, SchemaID?: any) => Recordset; - Properties: Properties; + + /** + * @param string [ConnectionString=''] + * @param string [UserID=''] + * @param string [Password=''] + * @param number [Options=-1] + */ + Open(ConnectionString?: string, UserID?: string, Password?: string, Options?: number): void; + OpenSchema(Schema: SchemaEnum, Restrictions?: any, SchemaID?: any): Recordset; + readonly Properties: Properties; Provider: string; - RollbackTrans: () => void; - State: number; - Version: string; + RollbackTrans(): void; + readonly State: number; + readonly Version: string; } interface Error { - Description: string; - HelpContext: number; - HelpFile: string; - NativeError: number; - Number: number; - Source: string; - SQLState: string; + readonly Description: string; + readonly HelpContext: number; + readonly HelpFile: string; + readonly NativeError: number; + readonly Number: number; + readonly Source: string; + readonly SQLState: string; } interface Errors { - Clear: () => void; - Count: number; - Item: (Index: any) => Error; - Refresh: () => void; + Clear(): void; + readonly Count: number; + Item(Index: any): Error; + Refresh(): void; } interface Field { - ActualSize: number; - AppendChunk: (Data: any) => void; + readonly ActualSize: number; + AppendChunk(Data: any): void; Attributes: number; - DataFormat: any /*VT_UNKNOWN*/; + DataFormat: any; DefinedSize: number; - GetChunk: (Length: number) => any; - Name: string; + GetChunk(Length: number): any; + readonly Name: string; NumericScale: number; - OriginalValue: any; + readonly OriginalValue: any; Precision: number; - Properties: Properties; - Status: number; + readonly Properties: Properties; + readonly Status: number; Type: DataTypeEnum; - UnderlyingValue: any; + readonly UnderlyingValue: any; Value: any; } interface Fields { - _Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum) => void; - Append: (Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any) => void; - CancelUpdate: () => void; - Count: number; - Delete: (Index: any) => void; - Item: (Index: any) => Field; - Refresh: () => void; - Resync: (ResyncValues?: ResyncEnum) => void; - Update: () => void; + /** + * @param number [DefinedSize=0] + * @param ADODB.FieldAttributeEnum [Attrib=-1] + */ + _Append(Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum): void; + + /** + * @param number [DefinedSize=0] + * @param ADODB.FieldAttributeEnum [Attrib=-1] + */ + Append(Name: string, Type: DataTypeEnum, DefinedSize?: number, Attrib?: FieldAttributeEnum, FieldValue?: any): void; + CancelUpdate(): void; + readonly Count: number; + Delete(Index: any): void; + Item(Index: any): Field; + Refresh(): void; + + /** @param ADODB.ResyncEnum [ResyncValues=2] */ + Resync(ResyncValues?: ResyncEnum): void; + Update(): void; } interface Parameter { - AppendChunk: (Val: any) => void; + AppendChunk(Val: any): void; Attributes: number; Direction: ParameterDirectionEnum; Name: string; NumericScale: number; Precision: number; - Properties: Properties; + readonly Properties: Properties; Size: number; Type: DataTypeEnum; Value: any; } interface Parameters { - Append: (Object: any /*VT_DISPATCH*/) => void; - Count: number; - Delete: (Index: any) => void; - Item: (Index: any) => Parameter; - Refresh: () => void; + Append(Object: any): void; + readonly Count: number; + Delete(Index: any): void; + Item(Index: any): Parameter; + Refresh(): void; } interface Properties { - Count: number; - Item: (Index: any) => Property; - Refresh: () => void; + readonly Count: number; + Item(Index: any): Property; + Refresh(): void; } interface Property { Attributes: number; - Name: string; - Type: DataTypeEnum; + readonly Name: string; + readonly Type: DataTypeEnum; Value: any; } interface Record { ActiveConnection: any; - Cancel: () => void; - Close: () => void; - CopyRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean) => string; - DeleteRecord: (Source?: string, Async?: boolean) => void; - Fields: Fields; - GetChildren: () => Recordset; + Cancel(): void; + Close(): void; + + /** + * @param string [Source=''] + * @param string [Destination=''] + * @param string [UserName=''] + * @param string [Password=''] + * @param ADODB.CopyRecordOptionsEnum [Options=-1] + * @param boolean [Async=false] + */ + CopyRecord(Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: CopyRecordOptionsEnum, Async?: boolean): string; + + /** + * @param string [Source=''] + * @param boolean [Async=false] + */ + DeleteRecord(Source?: string, Async?: boolean): void; + readonly Fields: Fields; + GetChildren(): Recordset; Mode: ConnectModeEnum; - MoveRecord: (Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean) => string; - Open: (Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string) => void; - ParentURL: string; - Properties: Properties; - RecordType: RecordTypeEnum; + + /** + * @param string [Source=''] + * @param string [Destination=''] + * @param string [UserName=''] + * @param string [Password=''] + * @param ADODB.MoveRecordOptionsEnum [Options=-1] + * @param boolean [Async=false] + */ + MoveRecord(Source?: string, Destination?: string, UserName?: string, Password?: string, Options?: MoveRecordOptionsEnum, Async?: boolean): string; + + /** + * @param ADODB.ConnectModeEnum [Mode=0] + * @param ADODB.RecordCreateOptionsEnum [CreateOptions=-1] + * @param ADODB.RecordOpenOptionsEnum [Options=-1] + * @param string [UserName=''] + * @param string [Password=''] + */ + Open(Source: any, ActiveConnection: any, Mode?: ConnectModeEnum, CreateOptions?: RecordCreateOptionsEnum, Options?: RecordOpenOptionsEnum, UserName?: string, Password?: string): void; + readonly ParentURL: string; + readonly Properties: Properties; + readonly RecordType: RecordTypeEnum; Source: any; - State: ObjectStateEnum; + readonly State: ObjectStateEnum; } interface Recordset { - _xClone: () => Recordset; - _xResync: (AffectRecords?: AffectEnum) => void; - _xSave: (FileName?: string, PersistFormat?: PersistFormatEnum) => void; + _xClone(): Recordset; + + /** @param ADODB.AffectEnum [AffectRecords=3] */ + _xResync(AffectRecords?: AffectEnum): void; + + /** + * @param string [FileName=''] + * @param ADODB.PersistFormatEnum [PersistFormat=0] + */ + _xSave(FileName?: string, PersistFormat?: PersistFormatEnum): void; AbsolutePage: PositionEnum; AbsolutePosition: PositionEnum; - ActiveCommand: any /*VT_DISPATCH*/; - ActiveConnection: any /*VT_DISPATCH*/; - AddNew: (FieldList?: any, Values?: any) => void; - BOF: boolean; + readonly ActiveCommand: any; + ActiveConnection: any; + AddNew(FieldList?: any, Values?: any): void; + readonly BOF: boolean; Bookmark: any; CacheSize: number; - Cancel: () => void; - CancelBatch: (AffectRecords?: AffectEnum) => void; - CancelUpdate: () => void; - Clone: (LockType?: LockTypeEnum) => Recordset; - Close: () => void; - Collect: (Index: any) => any; //Also has setter with parameters - CompareBookmarks: (Bookmark1: any, Bookmark2: any) => CompareEnum; + Cancel(): void; + + /** @param ADODB.AffectEnum [AffectRecords=3] */ + CancelBatch(AffectRecords?: AffectEnum): void; + CancelUpdate(): void; + + /** @param ADODB.LockTypeEnum [LockType=-1] */ + Clone(LockType?: LockTypeEnum): Recordset; + Close(): void; + Collect(Index: any): any; + CompareBookmarks(Bookmark1: any, Bookmark2: any): CompareEnum; CursorLocation: CursorLocationEnum; CursorType: CursorTypeEnum; DataMember: string; - DataSource: any /*VT_UNKNOWN*/; - Delete: (AffectRecords?: AffectEnum) => void; - EditMode: EditModeEnum; - EOF: boolean; - Fields: Fields; + DataSource: any; + + /** @param ADODB.AffectEnum [AffectRecords=1] */ + Delete(AffectRecords?: AffectEnum): void; + readonly EditMode: EditModeEnum; + readonly EOF: boolean; + readonly Fields: Fields; Filter: any; - Find: (Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any) => void; - GetRows: (Rows?: number, Start?: any, Fields?: any) => any; - GetString: (StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string) => string; + + /** + * @param number [SkipRecords=0] + * @param ADODB.SearchDirectionEnum [SearchDirection=1] + */ + Find(Criteria: string, SkipRecords?: number, SearchDirection?: SearchDirectionEnum, Start?: any): void; + + /** @param number [Rows=-1] */ + GetRows(Rows?: number, Start?: any, Fields?: any): any; + + /** + * @param ADODB.StringFormatEnum [StringFormat=2] + * @param number [NumRows=-1] + * @param string [ColumnDelimeter=''] + * @param string [RowDelimeter=''] + * @param string [NullExpr=''] + */ + GetString(StringFormat?: StringFormatEnum, NumRows?: number, ColumnDelimeter?: string, RowDelimeter?: string, NullExpr?: string): string; Index: string; LockType: LockTypeEnum; MarshalOptions: MarshalOptionsEnum; MaxRecords: number; - Move: (NumRecords: number, Start?: any) => void; - MoveFirst: () => void; - MoveLast: () => void; - MoveNext: () => void; - MovePrevious: () => void; - NextRecordset: (RecordsAffected?: any) => Recordset; - Open: (Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number) => void; - PageCount: number; + Move(NumRecords: number, Start?: any): void; + MoveFirst(): void; + MoveLast(): void; + MoveNext(): void; + MovePrevious(): void; + NextRecordset(RecordsAffected?: any): Recordset; + + /** + * @param ADODB.CursorTypeEnum [CursorType=-1] + * @param ADODB.LockTypeEnum [LockType=-1] + * @param number [Options=-1] + */ + Open(Source: any, ActiveConnection: any, CursorType?: CursorTypeEnum, LockType?: LockTypeEnum, Options?: number): void; + readonly PageCount: number; PageSize: number; - Properties: Properties; - RecordCount: number; - Requery: (Options?: number) => void; - Resync: (AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum) => void; - Save: (Destination: any, PersistFormat?: PersistFormatEnum) => void; - Seek: (KeyValues: any, SeekOption?: SeekEnum) => void; + readonly Properties: Properties; + readonly RecordCount: number; + + /** @param number [Options=-1] */ + Requery(Options?: number): void; + + /** + * @param ADODB.AffectEnum [AffectRecords=3] + * @param ADODB.ResyncEnum [ResyncValues=2] + */ + Resync(AffectRecords?: AffectEnum, ResyncValues?: ResyncEnum): void; + + /** @param ADODB.PersistFormatEnum [PersistFormat=0] */ + Save(Destination: any, PersistFormat?: PersistFormatEnum): void; + + /** @param ADODB.SeekEnum [SeekOption=1] */ + Seek(KeyValues: any, SeekOption?: SeekEnum): void; Sort: string; - Source: any /*VT_DISPATCH*/; - State: number; - Status: number; + Source: any; + readonly State: number; + readonly Status: number; StayInSync: boolean; - Supports: (CursorOptions: CursorOptionEnum) => boolean; - Update: (Fields?: any, Values?: any) => void; - UpdateBatch: (AffectRecords?: AffectEnum) => void; + Supports(CursorOptions: CursorOptionEnum): boolean; + Update(Fields?: any, Values?: any): void; + + /** @param ADODB.AffectEnum [AffectRecords=3] */ + UpdateBatch(AffectRecords?: AffectEnum): void; } interface Stream { - Cancel: () => void; + Cancel(): void; Charset: string; - Close: () => void; - CopyTo: (DestStream: Stream, CharNumber?: number) => void; - EOS: boolean; - Flush: () => void; - LineSeparator: LineSeparatorEnum; - LoadFromFile: (FileName: string) => void; - Mode: ConnectModeEnum; - Open: (Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string) => void; - Position: number; - Read: (NumBytes?: number) => any; - ReadText: (NumChars?: number) => string; - SaveToFile: (FileName: string, Options?: SaveOptionsEnum) => void; - SetEOS: () => void; - Size: number; - SkipLine: () => void; - State: ObjectStateEnum; - Type: StreamTypeEnum; - Write: (Buffer: any) => void; - WriteText: (Data: string, Options?: StreamWriteEnum) => void; - } + Close(): void; + /** @param number [CharNumber=-1] */ + CopyTo(DestStream: Stream, CharNumber?: number): void; + readonly EOS: boolean; + Flush(): void; + LineSeparator: LineSeparatorEnum; + LoadFromFile(FileName: string): void; + Mode: ConnectModeEnum; + + /** + * @param ADODB.ConnectModeEnum [Mode=0] + * @param ADODB.StreamOpenOptionsEnum [Options=-1] + * @param string [UserName=''] + * @param string [Password=''] + */ + Open(Source: any, Mode?: ConnectModeEnum, Options?: StreamOpenOptionsEnum, UserName?: string, Password?: string): void; + Position: number; + + /** @param number [NumBytes=-1] */ + Read(NumBytes?: number): any; + + /** @param number [NumChars=-1] */ + ReadText(NumChars?: number): string; + + /** @param ADODB.SaveOptionsEnum [Options=1] */ + SaveToFile(FileName: string, Options?: SaveOptionsEnum): void; + SetEOS(): void; + readonly Size: number; + SkipLine(): void; + readonly State: ObjectStateEnum; + Type: StreamTypeEnum; + Write(Buffer: any): void; + + /** @param ADODB.StreamWriteEnum [Options=0] */ + WriteText(Data: string, Options?: StreamWriteEnum): void; + } } interface ActiveXObject { - new (progID: 'ADODB.Connection'): ADODB.Connection; - new (progID: 'ADODB.Record'): ADODB.Record; - new (progID: 'ADODB.Stream'): ADODB.Stream; - new (progID: 'ADODB.Command'): ADODB.Command; - new (progID: 'ADODB.Recordset'): ADODB.Recordset; - new (progID: 'ADODB.Parameter'): ADODB.Parameter; + on(obj: ADODB.Connection, event: 'BeginTransComplete', argNames: ['TransactionLevel', 'pError', 'adStatus', 'pConnection'], handler: ( + this: ADODB.Connection, parameter: { + TransactionLevel: number, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void; + on(obj: ADODB.Connection, event: 'Disconnect', argNames: ['adStatus', 'pConnection'], handler: ( + this: ADODB.Connection, parameter: { + adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void; + on(obj: ADODB.Connection, event: 'ExecuteComplete', argNames: ['RecordsAffected', 'pError', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'], handler: ( + this: ADODB.Connection, parameter: { + RecordsAffected: number, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pCommand: ADODB.Command, pRecordset: ADODB.Recordset, pConnection: ADODB.Connection}) => void): void; + on(obj: ADODB.Connection, event: 'InfoMessage' | 'CommitTransComplete' | 'RollbackTransComplete' | 'ConnectComplete', argNames: ['pError', 'adStatus', 'pConnection'], handler: ( + this: ADODB.Connection, parameter: { + pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void; + on(obj: ADODB.Connection, event: 'WillConnect', argNames: ['ConnectionString', 'UserID', 'Password', 'Options', 'adStatus', 'pConnection'], handler: ( + this: ADODB.Connection, parameter: { + ConnectionString: string, UserID: string, Password: string, Options: number, adStatus: ADODB.EventStatusEnum, pConnection: ADODB.Connection}) => void): void; + on(obj: ADODB.Connection, event: 'WillExecute', argNames: ['Source', 'CursorType', 'LockType', 'Options', 'adStatus', 'pCommand', 'pRecordset', 'pConnection'], handler: ( + this: ADODB.Connection, parameter: { + Source: string, CursorType: ADODB.CursorTypeEnum, LockType: ADODB.LockTypeEnum, Options: number, adStatus: ADODB.EventStatusEnum, pCommand: ADODB.Command, + pRecordset: ADODB.Recordset, pConnection: ADODB.Connection}) => void): void; + on(obj: ADODB.Recordset, event: 'EndOfRecordset', argNames: ['fMoreData', 'adStatus', 'pRecordset'], handler: ( + this: ADODB.Recordset, parameter: { + fMoreData: boolean, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void; + on(obj: ADODB.Recordset, event: 'FetchComplete', argNames: ['pError', 'adStatus', 'pRecordset'], handler: ( + this: ADODB.Recordset, parameter: { + pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void; + on(obj: ADODB.Recordset, event: 'FetchProgress', argNames: ['Progress', 'MaxProgress', 'adStatus', 'pRecordset'], handler: ( + this: ADODB.Recordset, parameter: { + Progress: number, MaxProgress: number, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void; + on(obj: ADODB.Recordset, event: 'FieldChangeComplete', argNames: ['cFields', 'Fields', 'pError', 'adStatus', 'pRecordset'], handler: ( + this: ADODB.Recordset, parameter: { + cFields: number, Fields: any, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void; + on(obj: ADODB.Recordset, event: 'RecordChangeComplete', argNames: ['adReason', 'cRecords', 'pError', 'adStatus', 'pRecordset'], handler: ( + this: ADODB.Recordset, parameter: { + adReason: ADODB.EventReasonEnum, cRecords: number, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void; + on(obj: ADODB.Recordset, event: 'RecordsetChangeComplete' | 'MoveComplete', argNames: ['adReason', 'pError', 'adStatus', 'pRecordset'], handler: ( + this: ADODB.Recordset, parameter: { + adReason: ADODB.EventReasonEnum, pError: ADODB.Error, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void; + on(obj: ADODB.Recordset, event: 'WillChangeField', argNames: ['cFields', 'Fields', 'adStatus', 'pRecordset'], handler: ( + this: ADODB.Recordset, parameter: { + cFields: number, Fields: any, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void; + on(obj: ADODB.Recordset, event: 'WillChangeRecord', argNames: ['adReason', 'cRecords', 'adStatus', 'pRecordset'], handler: ( + this: ADODB.Recordset, parameter: { + adReason: ADODB.EventReasonEnum, cRecords: number, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void; + on(obj: ADODB.Recordset, event: 'WillChangeRecordset' | 'WillMove', argNames: ['adReason', 'adStatus', 'pRecordset'], handler: ( + this: ADODB.Recordset, parameter: { + adReason: ADODB.EventReasonEnum, adStatus: ADODB.EventStatusEnum, pRecordset: ADODB.Recordset}) => void): void; + set(obj: ADODB.Recordset, propertyName: 'Collect', parameterTypes: [any], newValue: any): void; + new(progid: 'ADODB.Command'): ADODB.Command; + new(progid: 'ADODB.Connection'): ADODB.Connection; + new(progid: 'ADODB.Parameter'): ADODB.Parameter; + new(progid: 'ADODB.Record'): ADODB.Record; + new(progid: 'ADODB.Recordset'): ADODB.Recordset; + new(progid: 'ADODB.Stream'): ADODB.Stream; } +interface EnumeratorConstructor { + new(col: ADODB.Errors): ADODB.Error; + new(col: ADODB.Fields): ADODB.Field; + new(col: ADODB.Parameters): ADODB.Parameter; + new(col: ADODB.Properties): ADODB.Property; +} diff --git a/types/activex-adodb/package.json b/types/activex-adodb/package.json new file mode 100644 index 0000000000..d798f99261 --- /dev/null +++ b/types/activex-adodb/package.json @@ -0,0 +1 @@ +{ "dependencies": { "activex-helpers": "*"}} \ No newline at end of file diff --git a/types/activex-adodb/tsconfig.json b/types/activex-adodb/tsconfig.json new file mode 100644 index 0000000000..484faf1ed0 --- /dev/null +++ b/types/activex-adodb/tsconfig.json @@ -0,0 +1,22 @@ + +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es5", "scripthost"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strict": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "activex-adodb-tests.ts" + ] +} \ No newline at end of file diff --git a/types/activex-adodb/tslint.json b/types/activex-adodb/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/activex-adodb/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/activex-data-objects/activex-data-objects-tests.ts b/types/activex-data-objects/activex-data-objects-tests.ts deleted file mode 100644 index 6298298a48..0000000000 --- a/types/activex-data-objects/activex-data-objects-tests.ts +++ /dev/null @@ -1,18 +0,0 @@ -//open connection to an Excel file -var pathToExcelFile = 'C:\\path\\to\\excel\\file.xlsx'; -var conn = new ActiveXObject('ADODB.Connection'); -conn.Provider = 'Microsoft.ACE.OLEDB.12.0'; -conn.ConnectionString = - 'Data Source="' + pathToExcelFile + '";' + - 'Extended Properties="Excel 12.0;HDR=Yes"'; -conn.Open(); - -//create a Command to access the data -var cmd = new ActiveXObject('ADODB.Command'); -cmd.CommandText = 'SELECT DISTINCT LastName, CityName FROM [Sheet1$]'; -//get a Recordset -var rs = cmd.Execute(); -//build a string from the Recordset -var s = rs.GetString(ADODB.StringFormatEnum.adClipString, -1, '\t', '\n', '(NULL)'); -rs.Close(); -WScript.Echo(s); \ No newline at end of file diff --git a/types/activex-scripting-runtime/index.d.ts b/types/activex-scripting-runtime/index.d.ts deleted file mode 100644 index 54065e1bd7..0000000000 --- a/types/activex-scripting-runtime/index.d.ts +++ /dev/null @@ -1,205 +0,0 @@ -// Type definitions for Microsoft Scripting Runtime -// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx -// Definitions by: Zev Spitz -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Scripting { - - //Enums - const enum CompareMethod { - BinaryCompare = 0, - DatabaseCompare = 2, - TextCompare = 1 - } - - const enum DriveTypeConst { - CDRom = 4, - Fixed = 2, - RamDisk = 5, - Remote = 3, - Removable = 1, - UnknownType = 0 - } - - const enum FileAttribute { - Alias = 1024, - Archive = 32, - Compressed = 2048, - Directory = 16, - Hidden = 2, - Normal = 0, - ReadOnly = 1, - System = 4, - Volume = 8 - } - - const enum IOMode { - ForAppending = 8, - ForReading = 1, - ForWriting = 2 - } - - const enum SpecialFolderConst { - SystemFolder = 1, - TemporaryFolder = 2, - WindowsFolder = 0 - } - - const enum StandardStreamTypes { - StdErr = 2, - StdIn = 0, - StdOut = 1 - } - - const enum Tristate { - TristateFalse = 0, - TristateMixed = -2, - TristateTrue = -1, - TristateUseDefault = -2 - } - - //Interfaces - interface Dictionary { - Add: (Key: any, Item: any) => void; - CompareMode: CompareMethod; - Count: number; - Exists: (Key: any) => boolean; - HashVal: (Key: any) => any; - Item: (Key: any) => any; //Also has setter with parameters - Items: () => any; - Key: (Key: any) => any; - Keys: () => any; - Remove: (Key: any) => void; - RemoveAll: () => void; - } - - interface Drive { - AvailableSpace: any; - DriveLetter: string; - DriveType: DriveTypeConst; - FileSystem: string; - FreeSpace: any; - IsReady: boolean; - Path: string; - RootFolder: Folder; - SerialNumber: number; - ShareName: string; - TotalSize: any; - VolumeName: string; - } - - interface Drives { - Count: number; - Item: (Key: any) => Drive; - } - - interface Encoder { - EncodeScriptFile: (szExt: string, bstrStreamIn: string, cFlags: number, bstrDefaultLang: string) => string; - } - - interface File { - Attributes: FileAttribute; - Copy: (Destination: string, OverWriteFiles?: boolean) => void; - DateCreated: VarDate; - DateLastAccessed: VarDate; - DateLastModified: VarDate; - Delete: (Force?: boolean) => void; - Drive: Drive; - Move: (Destination: string) => void; - Name: string; - OpenAsTextStream: (IOMode?: IOMode, Format?: Tristate) => TextStream; - ParentFolder: Folder; - Path: string; - ShortName: string; - ShortPath: string; - Size: any; - Type: string; - } - - interface Files { - Count: number; - Item: (Key: any) => File; - } - - interface FileSystemObject { - BuildPath: (Path: string, Name: string) => string; - CopyFile: (Source: string, Destination: string, OverWriteFiles?: boolean) => void; - CopyFolder: (Source: string, Destination: string, OverWriteFiles?: boolean) => void; - CreateFolder: (Path: string) => Folder; - CreateTextFile: (FileName: string, Overwrite?: boolean, Unicode?: boolean) => TextStream; - DeleteFile: (FileSpec: string, Force?: boolean) => void; - DeleteFolder: (FolderSpec: string, Force?: boolean) => void; - DriveExists: (DriveSpec: string) => boolean; - Drives: Drives; - FileExists: (FileSpec: string) => boolean; - FolderExists: (FolderSpec: string) => boolean; - GetAbsolutePathName: (Path: string) => string; - GetBaseName: (Path: string) => string; - GetDrive: (DriveSpec: string) => Drive; - GetDriveName: (Path: string) => string; - GetExtensionName: (Path: string) => string; - GetFile: (FilePath: string) => File; - GetFileName: (Path: string) => string; - GetFileVersion: (FileName: string) => string; - GetFolder: (FolderPath: string) => Folder; - GetParentFolderName: (Path: string) => string; - GetSpecialFolder: (SpecialFolder: SpecialFolderConst) => Folder; - GetStandardStream: (StandardStreamType: StandardStreamTypes, Unicode?: boolean) => TextStream; - GetTempName: () => string; - MoveFile: (Source: string, Destination: string) => void; - MoveFolder: (Source: string, Destination: string) => void; - OpenTextFile: (FileName: string, IOMode?: IOMode, Create?: boolean, Format?: Tristate) => TextStream; - } - - interface Folder { - Attributes: FileAttribute; - Copy: (Destination: string, OverWriteFiles?: boolean) => void; - CreateTextFile: (FileName: string, Overwrite?: boolean, Unicode?: boolean) => TextStream; - DateCreated: VarDate; - DateLastAccessed: VarDate; - DateLastModified: VarDate; - Delete: (Force?: boolean) => void; - Drive: Drive; - Files: Files; - IsRootFolder: boolean; - Move: (Destination: string) => void; - Name: string; - ParentFolder: Folder; - Path: string; - ShortName: string; - ShortPath: string; - Size: any; - SubFolders: Folders; - Type: string; - } - - interface Folders { - Add: (Name: string) => Folder; - Count: number; - Item: (Key: any) => Folder; - } - - interface TextStream { - AtEndOfLine: boolean; - AtEndOfStream: boolean; - Close: () => void; - Column: number; - Line: number; - Read: (Characters: number) => string; - ReadAll: () => string; - ReadLine: () => string; - Skip: (Characters: number) => void; - SkipLine: () => void; - Write: (Text: string) => void; - WriteBlankLines: (Lines: number) => void; - WriteLine: (Text?: string) => void; - } - -} - -interface ActiveXObject { - new (progID: 'Scripting.Dictionary'): Scripting.Dictionary; - new (progID: 'Scripting.FileSystemObject'): Scripting.FileSystemObject; - new (progID: 'Scripting.Encoder'): Scripting.Encoder; -} - diff --git a/types/activex-scripting-runtime/activex-scripting-runtime-tests.ts b/types/activex-scripting/activex-scripting-tests.ts similarity index 62% rename from types/activex-scripting-runtime/activex-scripting-runtime-tests.ts rename to types/activex-scripting/activex-scripting-tests.ts index 1510b98e1b..cc14a421ff 100644 --- a/types/activex-scripting-runtime/activex-scripting-runtime-tests.ts +++ b/types/activex-scripting/activex-scripting-tests.ts @@ -1,8 +1,7 @@ -//source -- https://msdn.microsoft.com/en-us/library/ebkhfaaz.aspx +// source -- https://msdn.microsoft.com/en-us/library/ebkhfaaz.aspx - -//Generates a string describing the drive type of a given Drive object. -var showDriveType = (drive: Scripting.Drive) => { +// Generates a string describing the drive type of a given Drive object. +let showDriveType = (drive: Scripting.Drive) => { switch (drive.DriveType) { case Scripting.DriveTypeConst.Removable: return 'Removeable'; @@ -19,14 +18,13 @@ var showDriveType = (drive: Scripting.Drive) => { } }; - -//Generates a string describing the attributes of a file or folder. -var showFileAttributes = (file: Scripting.File) => { - var attr = file.Attributes; +// Generates a string describing the attributes of a file or folder. +let showFileAttributes = (file: Scripting.File) => { + let attr = file.Attributes; if (attr === 0) { return 'Normal'; } - var attributeStrings: string[] = []; + let attributeStrings: string[] = []; if (attr & Scripting.FileAttribute.Directory) { attributeStrings.push('Directory'); } if (attr & Scripting.FileAttribute.ReadOnly) { attributeStrings.push('Read-only'); } if (attr & Scripting.FileAttribute.Hidden) { attributeStrings.push('Hidden'); } @@ -38,24 +36,22 @@ var showFileAttributes = (file: Scripting.File) => { return attributeStrings.join(','); }; - -//source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx -var showFreeSpace = (drvPath: string) => { - var fso = new ActiveXObject('Scripting.FileSystemObject'); - var d = fso.GetDrive(fso.GetDriveName(drvPath)); - var s = 'Drive ' + drvPath + ' - '; +// source --https://msdn.microsoft.com/en-us/library/ts2t8ybh(v=vs.84).aspx +let showFreeSpace = (drvPath: string) => { + let fso = new ActiveXObject('Scripting.FileSystemObject'); + let d = fso.GetDrive(fso.GetDriveName(drvPath)); + let s = 'Drive ' + drvPath + ' - '; s += d.VolumeName + '
'; s += 'Free Space: ' + d.FreeSpace / 1024 + ' Kbytes'; return (s); }; +// source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx +let getALine = (filespec: string) => { + let fso = new ActiveXObject('Scripting.FileSystemObject'); + let file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false); -//source -- https://msdn.microsoft.com/en-us/library/kaf6yaft(v=vs.84).aspx -var getALine = (filespec: string) => { - var fso = new ActiveXObject('Scripting.FileSystemObject'); - var file = fso.OpenTextFile(filespec, Scripting.IOMode.ForReading, false); - - var s = ''; + let s = ''; while (!file.AtEndOfLine) { s += file.Read(1); } diff --git a/types/activex-scripting/index.d.ts b/types/activex-scripting/index.d.ts new file mode 100644 index 0000000000..c4a64c54af --- /dev/null +++ b/types/activex-scripting/index.d.ts @@ -0,0 +1,465 @@ +// Type definitions for Microsoft Scripting Runtime 1.0 +// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx +// Definitions by: Zev Spitz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace Scripting { + const enum CompareMethod { + BinaryCompare = 0, + DatabaseCompare = 2, + TextCompare = 1 + } + + const enum DriveTypeConst { + CDRom = 4, + Fixed = 2, + RamDisk = 5, + Remote = 3, + Removable = 1, + UnknownType = 0 + } + + const enum FileAttribute { + Alias = 1024, + Archive = 32, + Compressed = 2048, + Directory = 16, + Hidden = 2, + Normal = 0, + ReadOnly = 1, + System = 4, + Volume = 8 + } + + const enum IOMode { + ForAppending = 8, + ForReading = 1, + ForWriting = 2 + } + + const enum SpecialFolderConst { + SystemFolder = 1, + TemporaryFolder = 2, + WindowsFolder = 0 + } + + const enum StandardStreamTypes { + StdErr = 2, + StdIn = 0, + StdOut = 1 + } + + const enum Tristate { + TristateFalse = 0, + TristateMixed = -2, + TristateTrue = -1, + TristateUseDefault = -2 + } + + /** Scripting.Dictionary */ + interface Dictionary { + /** Add a new key and item to the dictionary. */ + Add(Key: any, Item: any): void; + + /** Set or get the string comparison method. */ + CompareMode: CompareMethod; + + /** Get the number of items in the dictionary. */ + readonly Count: number; + + /** Determine if a given key is in the dictionary. */ + Exists(Key: any): boolean; + HashVal(Key: any): any; + + /** Set or get the item for a given key */ + Item(Key: any): any; + + /** Get an array containing all items in the dictionary. */ + Items(): any; + + /** Change a key to a different key. */ + Key(Key: any): any; + + /** Get an array containing all keys in the dictionary. */ + Keys(): any; + + /** Remove a given key from the dictionary. */ + Remove(Key: any): void; + + /** Remove all information from the dictionary. */ + RemoveAll(): void; + } + + /** Drive Object */ + interface Drive { + /** Get available space */ + readonly AvailableSpace: any; + + /** Drive letter */ + readonly DriveLetter: string; + + /** Drive type */ + readonly DriveType: DriveTypeConst; + + /** Filesystem type */ + readonly FileSystem: string; + + /** Get drive free space */ + readonly FreeSpace: any; + + /** Check if disk is available */ + readonly IsReady: boolean; + + /** Path */ + readonly Path: string; + + /** Root folder */ + readonly RootFolder: Folder; + + /** Serial number */ + readonly SerialNumber: number; + + /** Share name */ + readonly ShareName: string; + + /** Get total drive size */ + readonly TotalSize: any; + + /** Name of volume */ + VolumeName: string; + } + + /** Collection of drives associated with drive letters */ + interface Drives { + /** Number of drives */ + readonly Count: number; + + /** Get drive */ + Item(Key: any): Drive; + } + + /** Script Encoder Object */ + interface Encoder { + /** Call the Encoder determined by szExt, passing bstrStreamIn and optional arguments */ + EncodeScriptFile(szExt: string, bstrStreamIn: string, cFlags: number, bstrDefaultLang: string): string; + } + + /** File object */ + interface File { + /** File attributes */ + Attributes: FileAttribute; + + /** + * Copy this file + * @param boolean [OverWriteFiles=true] + */ + Copy(Destination: string, OverWriteFiles?: boolean): void; + + /** Date file was created */ + readonly DateCreated: VarDate; + + /** Date file was last accessed */ + readonly DateLastAccessed: VarDate; + + /** Date file was last modified */ + readonly DateLastModified: VarDate; + + /** + * Delete this file + * @param boolean [Force=false] + */ + Delete(Force?: boolean): void; + + /** Get drive that contains file */ + readonly Drive: Drive; + + /** Move this file */ + Move(Destination: string): void; + + /** Get name of file */ + Name: string; + + /** + * Open a file as a TextStream + * @param Scripting.IOMode [IOMode=1] + * @param Scripting.Tristate [Format=0] + */ + OpenAsTextStream(IOMode?: IOMode, Format?: Tristate): TextStream; + + /** Get folder that contains file */ + readonly ParentFolder: Folder; + + /** Path to the file */ + readonly Path: string; + + /** Short name */ + readonly ShortName: string; + + /** Short path */ + readonly ShortPath: string; + + /** File size */ + readonly Size: any; + + /** Type description */ + readonly Type: string; + } + + /** Collection of files in a folder */ + interface Files { + /** Number of folders */ + readonly Count: number; + + /** Get file */ + Item(Key: any): File; + } + + /** FileSystem Object */ + interface FileSystemObject { + /** Generate a path from an existing path and a name */ + BuildPath(Path: string, Name: string): string; + + /** + * Copy a file + * @param boolean [OverWriteFiles=true] + */ + CopyFile(Source: string, Destination: string, OverWriteFiles?: boolean): void; + + /** + * Copy a folder + * @param boolean [OverWriteFiles=true] + */ + CopyFolder(Source: string, Destination: string, OverWriteFiles?: boolean): void; + + /** Create a folder */ + CreateFolder(Path: string): Folder; + + /** + * Create a file as a TextStream + * @param boolean [Overwrite=true] + * @param boolean [Unicode=false] + */ + CreateTextFile(FileName: string, Overwrite?: boolean, Unicode?: boolean): TextStream; + + /** + * Delete a file + * @param boolean [Force=false] + */ + DeleteFile(FileSpec: string, Force?: boolean): void; + + /** + * Delete a folder + * @param boolean [Force=false] + */ + DeleteFolder(FolderSpec: string, Force?: boolean): void; + + /** Check if a drive or a share exists */ + DriveExists(DriveSpec: string): boolean; + + /** Get drives collection */ + readonly Drives: Drives; + + /** Check if a file exists */ + FileExists(FileSpec: string): boolean; + + /** Check if a path exists */ + FolderExists(FolderSpec: string): boolean; + + /** Return the canonical representation of the path */ + GetAbsolutePathName(Path: string): string; + + /** Return base name from a path */ + GetBaseName(Path: string): string; + + /** Get drive or UNC share */ + GetDrive(DriveSpec: string): Drive; + + /** Return drive from a path */ + GetDriveName(Path: string): string; + + /** Return extension from path */ + GetExtensionName(Path: string): string; + + /** Get file */ + GetFile(FilePath: string): File; + + /** Return the file name from a path */ + GetFileName(Path: string): string; + + /** Retrieve the file version of the specified file into a string */ + GetFileVersion(FileName: string): string; + + /** Get folder */ + GetFolder(FolderPath: string): Folder; + + /** Return path to the parent folder */ + GetParentFolderName(Path: string): string; + + /** Get location of various system folders */ + GetSpecialFolder(SpecialFolder: SpecialFolderConst): Folder; + + /** + * Retrieve the standard input, output or error stream + * @param boolean [Unicode=false] + */ + GetStandardStream(StandardStreamType: StandardStreamTypes, Unicode?: boolean): TextStream; + + /** Generate name that can be used to name a temporary file */ + GetTempName(): string; + + /** Move a file */ + MoveFile(Source: string, Destination: string): void; + + /** Move a folder */ + MoveFolder(Source: string, Destination: string): void; + + /** + * Open a file as a TextStream + * @param Scripting.IOMode [IOMode=1] + * @param boolean [Create=false] + * @param Scripting.Tristate [Format=0] + */ + OpenTextFile(FileName: string, IOMode?: IOMode, Create?: boolean, Format?: Tristate): TextStream; + } + + /** Folder object */ + interface Folder { + /** Folder attributes */ + Attributes: FileAttribute; + + /** + * Copy this folder + * @param boolean [OverWriteFiles=true] + */ + Copy(Destination: string, OverWriteFiles?: boolean): void; + + /** + * Create a file as a TextStream + * @param boolean [Overwrite=true] + * @param boolean [Unicode=false] + */ + CreateTextFile(FileName: string, Overwrite?: boolean, Unicode?: boolean): TextStream; + + /** Date folder was created */ + readonly DateCreated: VarDate; + + /** Date folder was last accessed */ + readonly DateLastAccessed: VarDate; + + /** Date folder was last modified */ + readonly DateLastModified: VarDate; + + /** + * Delete this folder + * @param boolean [Force=false] + */ + Delete(Force?: boolean): void; + + /** Get drive that contains folder */ + readonly Drive: Drive; + + /** Get files collection */ + readonly Files: Files; + + /** True if folder is root */ + readonly IsRootFolder: boolean; + + /** Move this folder */ + Move(Destination: string): void; + + /** Get name of folder */ + Name: string; + + /** Get parent folder */ + readonly ParentFolder: Folder; + + /** Path to folder */ + readonly Path: string; + + /** Short name */ + readonly ShortName: string; + + /** Short path */ + readonly ShortPath: string; + + /** Sum of files and subfolders */ + readonly Size: any; + + /** Get folders collection */ + readonly SubFolders: Folders; + + /** Type description */ + readonly Type: string; + } + + /** Collection of subfolders in a folder */ + interface Folders { + /** Create a new folder */ + Add(Name: string): Folder; + + /** Number of folders */ + readonly Count: number; + + /** Get folder */ + Item(Key: any): Folder; + } + + /** TextStream object */ + interface TextStream { + /** Is the current position at the end of a line? */ + readonly AtEndOfLine: boolean; + + /** Is the current position at the end of the stream? */ + readonly AtEndOfStream: boolean; + + /** Close a text stream */ + Close(): void; + + /** Current column number */ + readonly Column: number; + + /** Current line number */ + readonly Line: number; + + /** Read a specific number of characters into a string */ + Read(Characters: number): string; + + /** Read the entire stream into a string */ + ReadAll(): string; + + /** Read an entire line into a string */ + ReadLine(): string; + + /** Skip a specific number of characters */ + Skip(Characters: number): void; + + /** Skip a line */ + SkipLine(): void; + + /** Write a string to the stream */ + Write(Text: string): void; + + /** Write a number of blank lines to the stream */ + WriteBlankLines(Lines: number): void; + + /** + * Write a string and an end of line to the stream + * @param string [Text=''] + */ + WriteLine(Text?: string): void; + } +} + +interface ActiveXObject { + set(obj: Scripting.Dictionary, propertyName: 'Item', parameterTypes: [any], newValue: any): void; + new(progid: 'Scripting.Dictionary'): Scripting.Dictionary; + new(progid: 'Scripting.Encoder'): Scripting.Encoder; + new(progid: 'Scripting.FileSystemObject'): Scripting.FileSystemObject; +} + +interface EnumeratorConstructor { + new(col: Scripting.Dictionary): any; + new(col: Scripting.Drives): Scripting.Drive; + new(col: Scripting.Files): Scripting.File; + new(col: Scripting.Folders): Scripting.Folder; +} diff --git a/types/activex-scripting/package.json b/types/activex-scripting/package.json new file mode 100644 index 0000000000..d798f99261 --- /dev/null +++ b/types/activex-scripting/package.json @@ -0,0 +1 @@ +{ "dependencies": { "activex-helpers": "*"}} \ No newline at end of file diff --git a/types/activex-scripting/tsconfig.json b/types/activex-scripting/tsconfig.json new file mode 100644 index 0000000000..190e7bdcd6 --- /dev/null +++ b/types/activex-scripting/tsconfig.json @@ -0,0 +1,22 @@ + +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es5", "scripthost"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strict": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "activex-scripting-tests.ts" + ] +} \ No newline at end of file diff --git a/types/activex-scripting/tslint.json b/types/activex-scripting/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/activex-scripting/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/activex-windows-image-acquisition/activex-windows-image-acquisition-tests.ts b/types/activex-wia/activex-wia-tests.ts similarity index 50% rename from types/activex-windows-image-acquisition/activex-windows-image-acquisition-tests.ts rename to types/activex-wia/activex-wia-tests.ts index 549bb4433f..8384291f5d 100644 --- a/types/activex-windows-image-acquisition/activex-windows-image-acquisition-tests.ts +++ b/types/activex-wia/activex-wia-tests.ts @@ -1,31 +1,43 @@ -//source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx +// source -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms630826(v=vs.85).aspx +// Convert a file +let commonDialog = new ActiveXObject('WIA.CommonDialog'); +let img = commonDialog.ShowAcquireImage(); -//Convert a file -var commonDialog = new ActiveXObject('WIA.CommonDialog'); -var img = commonDialog.ShowAcquireImage(); -if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) { - var ip = new ActiveXObject('WIA.ImageProcess'); +// when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these: +let jpegFormatID = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}'; +if (img.FormatID !== jpegFormatID) { + let ip = new ActiveXObject('WIA.ImageProcess'); + ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID); + ip.Filters.Item(1).Properties.Item('FormatID').Value = jpegFormatID; + img = ip.Apply(img); +} +// with this: +/*if (img.FormatID !== WIA.FormatID.wiaFormatJPEG) { + let ip = new ActiveXObject('WIA.ImageProcess'); ip.Filters.Add(ip.FilterInfos.Item('Convert').FilterID); ip.Filters.Item(1).Properties.Item('FormatID').Value = WIA.FormatID.wiaFormatJPEG; img = ip.Apply(img); -} +}*/ - -//Take a picture -var dev = commonDialog.ShowSelectDevice(); +// Take a picture +let dev = commonDialog.ShowSelectDevice(); if (dev.Type === WIA.WiaDeviceType.CameraDeviceType) { - var itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); + // when DefinitelyTyped supports Typescript 2.4 -- end of July 2017, replace these: + let commandID = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'; + let itm = dev.ExecuteCommand(commandID); + + // with this: + // let itm = dev.ExecuteCommand(WIA.CommandID.wiaCommandTakePicture); } - -//Display detailed property information +// Display detailed property information dev = commonDialog.ShowSelectDevice(); -var e = new Enumerator(dev.Properties); //no foreach over ActiveX collections +let e = new Enumerator(dev.Properties); // no foreach over ActiveX collections e.moveFirst(); while (!e.atEnd()) { - var p = e.item(); - var s = p.Name + ' (' + p.PropertyID + ') = '; + let p = e.item(); + let s = p.Name + ' (' + p.PropertyID + ') = '; if (p.IsVector) { s += '[vector of data]'; } else { @@ -48,8 +60,8 @@ while (!e.atEnd()) { } else { s += ' [valid values include: '; } - var count = p.SubTypeValues.Count; - for (var i = 1; i <= count; i++) { + let count = p.SubTypeValues.Count; + for (let i = 1; i <= count; i++) { s += p.SubTypeValues.Item(i); if (i < count) { s += ', '; @@ -63,9 +75,5 @@ while (!e.atEnd()) { } } - if (WScript) { - WScript.Echo(s); - } else if (window) { - window.alert(s); - } -} \ No newline at end of file + WScript.Echo(s); +} diff --git a/types/activex-wia/index.d.ts b/types/activex-wia/index.d.ts new file mode 100644 index 0000000000..7d7cbae727 --- /dev/null +++ b/types/activex-wia/index.d.ts @@ -0,0 +1,759 @@ +// Type definitions for Windows Image Acquisition 2.0 +// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630368(v=vs.85).aspx +// Definitions by: Zev Spitz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Typescript Version: 2.4 + +declare namespace WIA { + /** String versions of globally unique identifiers (GUIDs) that identify common Device and Item commands. */ + // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) + /*const enum CommandID { + wiaCommandChangeDocument = '{04E725B0-ACAE-11D2-A093-00C04F72DC3C}', + wiaCommandDeleteAllItems = '{E208C170-ACAD-11D2-A093-00C04F72DC3C}', + wiaCommandSynchronize = '{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}', + wiaCommandTakePicture = '{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}', + wiaCommandUnloadDocument = '{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}' + }*/ + + /** String versions of globally unique identifiers (GUIDs) that identify DeviceManager events. */ + // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) + /*const enum EventID { + wiaEventDeviceConnected = '{A28BBADE-64B6-11D2-A231-00C04FA31809}', + wiaEventDeviceDisconnected = '{143E4E83-6497-11D2-A231-00C04FA31809}', + wiaEventItemCreated = '{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}', + wiaEventItemDeleted = '{1D22A559-E14F-11D2-B326-00C04F68CE61}', + wiaEventScanEmailImage = '{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}', + wiaEventScanFaxImage = '{C00EB793-8C6E-11D2-977A-0000F87A926F}', + wiaEventScanFilmImage = '{9B2B662C-6185-438C-B68B-E39EE25E71CB}', + wiaEventScanImage = '{A6C5A715-8C6E-11D2-977A-0000F87A926F}', + wiaEventScanImage2 = '{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}', + wiaEventScanImage3 = '{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}', + wiaEventScanImage4 = '{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}', + wiaEventScanOCRImage = '{9D095B89-37D6-4877-AFED-62A297DC6DBE}', + wiaEventScanPrintImage = '{B441F425-8C6E-11D2-977A-0000F87A926F}' + }*/ + + /** String versions of globally unique identifiers (GUIDs) that indicate the file format of an image. */ + // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) + /*const enum FormatID { + wiaFormatBMP = '{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}', + wiaFormatGIF = '{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}', + wiaFormatJPEG = '{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}', + wiaFormatPNG = '{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}', + wiaFormatTIFF = '{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}' + }*/ + + /** Miscellaneous string constants */ + // uncomment when DefinitelyTyped supports Typescript 2.4 (end of July 2017) + /*const enum Miscellaneous { + wiaAnyDeviceID = '*', + wiaIDUnknown = '{00000000-0000-0000-0000-000000000000}' + }*/ + + /** + * The WiaDeviceType enumeration specifies the type of device attached to a user's computer. Use the Type property on the DeviceInfo object or the Device + * object to obtain these values from the device. + */ + const enum WiaDeviceType { + CameraDeviceType = 2, + ScannerDeviceType = 1, + UnspecifiedDeviceType = 0, + VideoDeviceType = 3 + } + + /** + * A DeviceEvent's type is composed of bits from the WiaEventFlags enumeration. You can test a DeviceEvent's type by using the AND operation with DeviceEv + * ent.Type and a member from the WiaEventFlags enumeration. + */ + const enum WiaEventFlag { + ActionEvent = 2, + NotificationEvent = 1 + } + + /** The WiaImageBias enumeration helps specify what type of data the image is intended to represent. */ + const enum WiaImageBias { + MaximizeQuality = 131072, + MinimizeSize = 65536 + } + + /** The WiaImageIntent enumeration helps specify what type of data the image is intended to represent. */ + const enum WiaImageIntent { + ColorIntent = 1, + GrayscaleIntent = 2, + TextIntent = 4, + UnspecifiedIntent = 0 + } + + /** + * The WiaImagePropertyType enumeration specifies the type of the value of an image property. Image properties can be found in the Properties collection o + * f an ImageFile object. + */ + const enum WiaImagePropertyType { + ByteImagePropertyType = 1001, + LongImagePropertyType = 1004, + RationalImagePropertyType = 1006, + StringImagePropertyType = 1002, + UndefinedImagePropertyType = 1000, + UnsignedIntegerImagePropertyType = 1003, + UnsignedLongImagePropertyType = 1005, + UnsignedRationalImagePropertyType = 1007, + VectorOfBytesImagePropertyType = 1101, + VectorOfLongsImagePropertyType = 1103, + VectorOfRationalsImagePropertyType = 1105, + VectorOfUndefinedImagePropertyType = 1100, + VectorOfUnsignedIntegersImagePropertyType = 1102, + VectorOfUnsignedLongsImagePropertyType = 1104, + VectorOfUnsignedRationalsImagePropertyType = 1106 + } + + /** + * An Item's type is composed of bits from the WiaItemFlags enumeration. You can test an Item's type by using the AND operation with Item.Properties("Item + * Flags") and a member from the WiaItemFlags enumeration. + */ + const enum WiaItemFlag { + AnalyzeItemFlag = 16, + AudioItemFlag = 32, + BurstItemFlag = 2048, + DeletedItemFlag = 128, + DeviceItemFlag = 64, + DisconnectedItemFlag = 256, + FileItemFlag = 2, + FolderItemFlag = 4, + FreeItemFlag = 0, + GeneratedItemFlag = 16384, + HasAttachmentsItemFlag = 32768, + HPanoramaItemFlag = 512, + ImageItemFlag = 1, + RemovedItemFlag = -2147483648, + RootItemFlag = 8, + StorageItemFlag = 4096, + TransferItemFlag = 8192, + VideoItemFlag = 65536, + VPanoramaItemFlag = 1024 + } + + /** + * The WiaPropertyType enumeration specifies the type of the value of an item property. Item properties can be found in the Properties collection of a Dev + * ice or Item object. + */ + const enum WiaPropertyType { + BooleanPropertyType = 1, + BytePropertyType = 2, + ClassIDPropertyType = 15, + CurrencyPropertyType = 12, + DatePropertyType = 13, + DoublePropertyType = 11, + ErrorCodePropertyType = 7, + FileTimePropertyType = 14, + HandlePropertyType = 18, + IntegerPropertyType = 3, + LargeIntegerPropertyType = 8, + LongPropertyType = 5, + ObjectPropertyType = 17, + SinglePropertyType = 10, + StringPropertyType = 16, + UnsignedIntegerPropertyType = 4, + UnsignedLargeIntegerPropertyType = 9, + UnsignedLongPropertyType = 6, + UnsupportedPropertyType = 0, + VariantPropertyType = 19, + VectorOfBooleansPropertyType = 101, + VectorOfBytesPropertyType = 102, + VectorOfClassIDsPropertyType = 115, + VectorOfCurrenciesPropertyType = 112, + VectorOfDatesPropertyType = 113, + VectorOfDoublesPropertyType = 111, + VectorOfErrorCodesPropertyType = 107, + VectorOfFileTimesPropertyType = 114, + VectorOfIntegersPropertyType = 103, + VectorOfLargeIntegersPropertyType = 108, + VectorOfLongsPropertyType = 105, + VectorOfSinglesPropertyType = 110, + VectorOfStringsPropertyType = 116, + VectorOfUnsignedIntegersPropertyType = 104, + VectorOfUnsignedLargeIntegersPropertyType = 109, + VectorOfUnsignedLongsPropertyType = 106, + VectorOfVariantsPropertyType = 119 + } + + /** + * The WiaSubType enumeration specifies more detail about the property value. Use the SubType property on the Property object to obtain these values for t + * he property. + */ + const enum WiaSubType { + FlagSubType = 3, + ListSubType = 2, + RangeSubType = 1, + UnspecifiedSubType = 0 + } + + /** + * The CommonDialog control is an invisible-at-runtime control that contains all the methods that display a User Interface. A CommonDialog control can be + * created using "WIA.CommonDialog" in a call to CreateObject or by dropping a CommonDialog on a form. + */ + interface CommonDialog { + /** + * Displays one or more dialog boxes that enable the user to acquire an image from a hardware device for image acquisition and returns an ImageFile object + * on success, otherwise Nothing + * @param WIA.WiaDeviceType [DeviceType=0] + * @param WIA.WiaImageIntent [Intent=0] + * @param WIA.WiaImageBias [Bias=131072] + * @param string [FormatID='{00000000-0000-0000-0000-000000000000}'] + * @param boolean [AlwaysSelectDevice=false] + * @param boolean [UseCommonUI=true] + * @param boolean [CancelError=false] + */ + ShowAcquireImage( + DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean): ImageFile; + + /** Launches the Windows Scanner and Camera Wizard and returns Nothing. Future versions may return a collection of ImageFile objects. */ + ShowAcquisitionWizard(Device: Device): any; + + /** + * Displays the properties dialog box for the specified Device + * @param boolean [CancelError=false] + */ + ShowDeviceProperties(Device: Device, CancelError?: boolean): void; + + /** + * Displays the properties dialog box for the specified Item + * @param boolean [CancelError=false] + */ + ShowItemProperties(Item: Item, CancelError?: boolean): void; + + /** Launches the Photo Printing Wizard with the absolute path of a specific file or Vector of absolute paths to files */ + ShowPhotoPrintingWizard(Files: any): void; + + /** + * Displays a dialog box that enables the user to select a hardware device for image acquisition. Returns the selected Device object on success, otherwise + * Nothing + * @param WIA.WiaDeviceType [DeviceType=0] + * @param boolean [AlwaysSelectDevice=false] + * @param boolean [CancelError=false] + */ + ShowSelectDevice(DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean): Device; + + /** + * Displays a dialog box that enables the user to select an item for transfer from a hardware device for image acquisition. Returns the selection as an It + * ems collection on success, otherwise Nothing + * @param WIA.WiaImageIntent [Intent=0] + * @param WIA.WiaImageBias [Bias=131072] + * @param boolean [SingleSelect=true] + * @param boolean [UseCommonUI=true] + * @param boolean [CancelError=false] + */ + ShowSelectItems(Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean): Items; + + /** + * Displays a progress dialog box while transferring the specified Item to the local machine. See Item.Transfer for additional information. + * @param string [FormatID='{00000000-0000-0000-0000-000000000000}'] + * @param boolean [CancelError=false] + */ + ShowTransfer(Item: Item, FormatID?: string, CancelError?: boolean): any; + } + + /** The Device object represents an active connection to an imaging device. */ + interface Device { + /** A collection of all commands for this imaging device */ + readonly Commands: DeviceCommands; + + /** Returns the DeviceID for this Device */ + readonly DeviceID: string; + + /** A collection of all events for this imaging device */ + readonly Events: DeviceEvents; + + /** + * Issues the command specified by CommandID to the imaging device. CommandIDs are device dependent. Valid CommandIDs for this Device are contained in the + * Commands collection. + */ + ExecuteCommand(CommandID: string): Item; + + /** Returns the Item object specified by ItemID if it exists */ + GetItem(ItemID: string): Item; + + /** A collection of all items for this imaging device */ + readonly Items: Items; + + /** A collection of all properties for this imaging device */ + readonly Properties: Properties; + + /** Returns the Type of Device */ + readonly Type: WiaDeviceType; + + /** Returns the underlying IWiaItem interface for this Device object */ + readonly WiaItem: any; + } + + /** The DeviceCommand object describes a CommandID that can be used when calling ExecuteCommand on a Device or Item object. */ + interface DeviceCommand { + /** Returns the commandID for this Command */ + readonly CommandID: string; + + /** Returns the command Description */ + readonly Description: string; + + /** Returns the command Name */ + readonly Name: string; + } + + /** + * The DeviceCommands object is a collection of all the supported DeviceCommands for an imaging device. See the Commands property of a Device or Item obje + * ct for more details on determining the collection of supported device commands. + */ + interface DeviceCommands { + /** Returns the number of members in the collection */ + readonly Count: number; + + /** Returns the specified item in the collection by position */ + Item(Index: number): DeviceCommand; + } + + /** The DeviceEvent object describes an EventID that can be used when calling RegisterEvent or RegisterPersistentEvent on a DeviceManager object. */ + interface DeviceEvent { + /** Returns the event Description */ + readonly Description: string; + + /** Returns the EventID for this Event */ + readonly EventID: string; + + /** Returns the event Name */ + readonly Name: string; + + /** Returns the Type of this Event */ + readonly Type: WiaEventFlag; + } + + /** + * The DeviceEvents object is a collection of all the supported DeviceEvent for an imaging device. See the Events property of a Device object for more det + * ails on determining the collection of supported device events. + */ + interface DeviceEvents { + /** Returns the number of members in the collection */ + readonly Count: number; + + /** Returns the specified item in the collection by position */ + Item(Index: number): DeviceEvent; + } + + /** + * The DeviceInfo object is a container that describes the unchanging (static) properties of an imaging device that is currently connected to the computer + * . + */ + interface DeviceInfo { + /** Establish a connection with this device and return a Device object */ + Connect(): Device; + + /** Returns the DeviceID for this Device */ + readonly DeviceID: string; + + /** A collection of all properties for this imaging device that are applicable when the device is not connected */ + readonly Properties: Properties; + + /** Returns the Type of Device */ + readonly Type: WiaDeviceType; + } + + /** + * The DeviceInfos object is a collection of all the imaging devices currently connected to the computer. See the DeviceInfos property on the DeviceManage + * r object for detail on accessing the DeviceInfos object. + */ + interface DeviceInfos { + /** Returns the number of members in the collection */ + readonly Count: number; + + /** Returns the specified item in the collection either by position or Device ID */ + Item(Index: any): DeviceInfo; + } + + /** + * The DeviceManager control is an invisible-at-runtime control that manages the imaging devices connected to the computer. A DeviceManager control can be + * created using "WIA.DeviceManager" in a call to CreateObject or by dropping a DeviceManager on a form. + */ + interface DeviceManager { + /** A collection of all imaging devices connected to this computer */ + readonly DeviceInfos: DeviceInfos; + + /** + * Registers the specified EventID for the specified DeviceID. If DeviceID is "*" then OnEvent will be called whenever the event specified occurs for any + * device. Otherwise, OnEvent will only be called if the event specified occurs on the device specified. + * @param string [DeviceID='*'] + */ + RegisterEvent(EventID: string, DeviceID?: string): void; + + /** + * Registers the specified Command to launch when the specified EventID for the specified DeviceID occurs. Command can be either a ClassID or the full pat + * h name and the appropriate command-line arguments needed to invoke the application. + * @param string [DeviceID='*'] + */ + RegisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void; + + /** + * Unregisters the specified EventID for the specified DeviceID. UnregisterEvent should only be called for EventID and DeviceID for which you called Regis + * terEvent. + * @param string [DeviceID='*'] + */ + UnregisterEvent(EventID: string, DeviceID?: string): void; + + /** + * Unregisters the specified Command for the specified EventID for the specified DeviceID. UnregisterPersistentEvent should only be called for the Command + * , Name, Description, Icon, EventID and DeviceID for which you called RegisterPersistentEvent. + * @param string [DeviceID='*'] + */ + UnregisterPersistentEvent(Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string): void; + } + + /** + * The Filter object represents a unit of modification on an ImageFile. To use a Filter, add it to the Filters collection, then set the filter's propertie + * s and finally use the Apply method of the ImageProcess object to filter an ImageFile. + */ + interface Filter { + /** Returns a Description of what the filter does */ + readonly Description: string; + + /** Returns the FilterID for this Filter */ + readonly FilterID: string; + + /** Returns the Filter Name */ + readonly Name: string; + + /** A collection of all properties for this filter */ + readonly Properties: Properties; + } + + /** + * The FilterInfo object is a container that describes a Filter object without requiring a Filter to be Added to the process chain. See the FilterInfos pr + * operty on the ImageProcess object for details on accessing FilterInfo objects. + */ + interface FilterInfo { + /** Returns a technical Description of what the filter does and how to use it in a filter chain */ + readonly Description: string; + + /** Returns the FilterID for this filter */ + readonly FilterID: string; + + /** Returns the FilterInfo Name */ + readonly Name: string; + } + + /** + * The FilterInfos object is a collection of all the available FilterInfo objects. See the FilterInfos property on the ImageProcess object for detail on a + * ccessing the FilterInfos object. + */ + interface FilterInfos { + /** Returns the number of members in the collection */ + readonly Count: number; + + /** Returns the specified item in the collection either by position or name */ + Item(Index: any): FilterInfo; + } + + /** The Filters object is a collection of the Filters that will be applied to an ImageFile when you call the Apply method on the ImageProcess object. */ + interface Filters { + /** + * Appends/Inserts a new Filter of the specified FilterID into a Filter collection + * @param number [Index=0] + */ + Add(FilterID: string, Index?: number): void; + + /** Returns the number of members in the collection */ + readonly Count: number; + + /** Returns the specified item in the collection by position or FilterID */ + Item(Index: number): Filter; + + /** Removes the designated filter */ + Remove(Index: number): void; + } + + /** + * The Formats object is a collection of supported FormatIDs that you can use when calling Transfer on an Item object or ShowTransfer on a CommonDialog ob + * ject for this Item. + */ + interface Formats { + /** Returns the number of members in the collection */ + readonly Count: number; + + /** Returns the specified item in the collection by position */ + Item(Index: number): string; + } + + /** + * The ImageFile object is a container for images transferred to your computer when you call Transfer or ShowTransfer. It also supports image files throug + * h LoadFile. An ImageFile object can be created using "WIA.ImageFile" in a call to CreateObject. + */ + interface ImageFile { + /** Returns/Sets the current frame in the image */ + ActiveFrame: number; + + /** Returns the raw image bits as a Vector of Long values */ + readonly ARGBData: Vector; + + /** Returns the raw image file as a Vector of Bytes */ + readonly FileData: Vector; + + /** Returns the file extension for this image file type */ + readonly FileExtension: string; + + /** Returns the FormatID for this file type */ + readonly FormatID: string; + + /** Returns the number of frames in the image */ + readonly FrameCount: number; + + /** Returns the Height of the image in pixels */ + readonly Height: number; + + /** Returns the Horizontal pixels per inch of the image */ + readonly HorizontalResolution: number; + + /** Indicates if the pixel format has an alpha component */ + readonly IsAlphaPixelFormat: boolean; + + /** Indicates whether the image is animated */ + readonly IsAnimated: boolean; + + /** Indicates if the pixel format is extended (16 bits/channel) */ + readonly IsExtendedPixelFormat: boolean; + + /** Indicates if the pixel data is an index into a palette or the actual color data */ + readonly IsIndexedPixelFormat: boolean; + + /** Loads the ImageFile object with the specified File */ + LoadFile(Filename: string): void; + + /** Returns the depth of the pixels of the image in bits per pixel */ + readonly PixelDepth: number; + + /** A collection of all properties for this image */ + readonly Properties: Properties; + + /** Save the ImageFile object to the specified File */ + SaveFile(Filename: string): void; + + /** Returns the Vertical pixels per inch of the image */ + readonly VerticalResolution: number; + + /** Returns the Width of the image in pixels */ + readonly Width: number; + } + + /** The ImageProcess object manages the filter chain. An ImageProcess object can be created using "WIA.ImageProcess" in a call to CreateObject. */ + interface ImageProcess { + /** Takes the specified ImageFile and returns the new ImageFile with all the filters applied on success */ + Apply(Source: ImageFile): ImageFile; + + /** A collection of all available filters */ + readonly FilterInfos: FilterInfos; + + /** A collection of the filters to be applied in this process */ + readonly Filters: Filters; + } + + /** + * The Item object is a container for an item on an imaging device object. See the Items property on the Device or Item object for details on accessing It + * em objects. + */ + interface Item { + /** A collection of all commands for this item */ + readonly Commands: DeviceCommands; + + /** Issues the command specified by CommandID. CommandIDs are device dependent. Valid CommandIDs for this Item are contained in the Commands collection. */ + ExecuteCommand(CommandID: string): Item; + + /** A collection of all supported format types for this item */ + readonly Formats: Formats; + + /** Returns the ItemID for this Item */ + readonly ItemID: string; + + /** A collection of all child items for this item */ + readonly Items: Items; + + /** A collection of all properties for this item */ + readonly Properties: Properties; + + /** + * Returns an ImageFile object, in this version, in the format specified in FormatID if supported, otherwise using the preferred format for this imaging d + * evice. Future versions may return a collection of ImageFile objects. + * @param string [FormatID='{00000000-0000-0000-0000-000000000000}'] + */ + Transfer(FormatID?: string): any; + + /** Returns the underlying IWiaItem interface for this Item object */ + readonly WiaItem: any; + } + + /** The Items object contains a collection of Item objects. See the Items property on the Device or Item object for details on accessing the Items object. */ + interface Items { + /** Adds a new Item with the specified Name and Flags. The Flags value is created by using the OR operation with members of the WiaItemFlags enumeration. */ + Add(Name: string, Flags: number): void; + + /** Returns the number of members in the collection */ + readonly Count: number; + + /** Returns the specified item in the collection by position */ + Item(Index: number): Item; + + /** Removes the designated Item */ + Remove(Index: number): void; + } + + /** + * The Properties object is a collection of all the Property objects associated with a given Device, DeviceInfo, Filter, ImageFile or Item object. See the + * Properties property on any of these objects for detail on accessing the Properties object. + */ + interface Properties { + /** Returns the number of members in the collection */ + readonly Count: number; + + /** Indicates whether the specified Property exists in the collection */ + Exists(Index: any): boolean; + + /** Returns the specified item in the collection either by position or name. */ + Item(Index: any): Property; + } + + /** + * The Property object is a container for a property associated with a Device, DeviceInfo, Filter, ImageFile or Item object. See the Properties property o + * n any of these objects for details on accessing Property objects. + */ + interface Property { + /** Indicates whether the Property Value is read only */ + readonly IsReadOnly: boolean; + + /** Indicates whether the Property Value is a vector */ + readonly IsVector: boolean; + + /** Returns the Property Name */ + readonly Name: string; + + /** Returns the PropertyID of this Property */ + readonly PropertyID: number; + + /** Returns the SubType of the Property, if any */ + readonly SubType: WiaSubType; + + /** Returns the default Property Value if the SubType is not UnspecifiedSubType */ + readonly SubTypeDefault: any; + + /** Returns the maximum valid Property Value if the SubType is RangeSubType */ + readonly SubTypeMax: number; + + /** Returns the minimum valid Property Value if the SubType is RangeSubType */ + readonly SubTypeMin: number; + + /** Returns the step increment of Property Values if the SubType is RangeSubType */ + readonly SubTypeStep: number; + + /** Returns a Vector of valid Property Values if the SubType is ListSubType or valid flag Values that can be ored together if the SubType is FlagSubType */ + readonly SubTypeValues: Vector; + + /** Returns either a WiaPropertyType or a WiaImagePropertyType */ + readonly Type: number; + + /** Returns/Sets the Property Value */ + Value: any; + } + + /** + * The Rational object is a container for the rational values found in Exif tags. It is a supported element type of the Vector object and may be created u + * sing "WIA.Rational" in a call to CreateObject. + */ + interface Rational { + /** Returns/Sets the Rational Value Denominator */ + Denominator: number; + + /** Returns/Sets the Rational Value Numerator */ + Numerator: number; + + /** Returns the Rational Value as a Double */ + readonly Value: number; + } + + /** + * The Vector object is a collection of values of the same type. It is used throughout the library in many different ways. The Vector object may be create + * d using "WIA.Vector" in a call to CreateObject. + */ + interface Vector { + /** + * If Index is not zero, Inserts a new element into the Vector collection before the specified Index. If Index is zero, Appends a new element to the Vecto + * r collection. + * @param number [Index=0] + */ + Add(Value: any, Index?: number): void; + + /** Returns/Sets the Vector of Bytes as an array of bytes */ + BinaryData: any; + + /** Removes all elements. */ + Clear(): void; + + /** Returns the number of members in the vector */ + readonly Count: number; + + /** Returns/Sets the Vector of Integers from a Date */ + Date: VarDate; + + /** + * Used to get the Thumbnail property of an ImageFile which is an image file, The thumbnail property of an Item which is RGB data, or creating an ImageFil + * e from raw ARGB data. Returns an ImageFile object on success. See the Picture method for more details. + * @param number [Width=0] + * @param number [Height=0] + */ + ImageFile(Width?: number, Height?: number): ImageFile; + + /** Returns/Sets the specified item in the vector by position */ + Item(Index: number): any; + + /** + * If the Vector of Bytes contains an image file, then Width and Height are ignored. Otherwise a Vector of Bytes must be RGB data and a Vector of Longs mu + * st be ARGB data. Returns a Picture object on success. See the ImageFile method for more details. + * @param number [Width=0] + * @param number [Height=0] + */ + Picture(Width?: number, Height?: number): any; + + /** Removes the designated element and returns it if successful */ + Remove(Index: number): any; + + /** + * Stores the string Value into the Vector of Bytes including the NULL terminator. Value may be truncated unless Resizable is True. The string will be sto + * red as an ANSI string unless Unicode is True, in which case it will be stored as a Unicode string. + * @param boolean [Resizable=true] + * @param boolean [Unicode=true] + */ + SetFromString(Value: string, Resizable?: boolean, Unicode?: boolean): void; + + /** + * Returns a Vector of Bytes as a String + * @param boolean [Unicode=true] + */ + String(Unicode?: boolean): string; + } +} + +interface ActiveXObject { + on(obj: WIA.DeviceManager, event: 'OnEvent', argNames: ['EventID', 'DeviceID', 'ItemID'], handler: ( + this: WIA.DeviceManager, parameter: { + EventID: string, DeviceID: string, ItemID: string}) => void): void; + set(obj: WIA.Vector, propertyName: 'Item', parameterTypes: [number], newValue: any): void; + new(progid: 'WIA.CommonDialog'): WIA.CommonDialog; + new(progid: 'WIA.DeviceManager'): WIA.DeviceManager; + new(progid: 'WIA.ImageFile'): WIA.ImageFile; + new(progid: 'WIA.ImageProcess'): WIA.ImageProcess; + new(progid: 'WIA.Rational'): WIA.Rational; + new(progid: 'WIA.Vector'): WIA.Vector; +} + +interface EnumeratorConstructor { + new(col: WIA.DeviceCommands): WIA.DeviceCommand; + new(col: WIA.DeviceEvents): WIA.DeviceEvent; + new(col: WIA.DeviceInfos): WIA.DeviceInfo; + new(col: WIA.FilterInfos): WIA.FilterInfo; + new(col: WIA.Filters): WIA.Filter; + new(col: WIA.Formats): string; + new(col: WIA.Items): WIA.Item; + new(col: WIA.Properties): WIA.Property; + new(col: WIA.Vector): any; +} diff --git a/types/activex-wia/package.json b/types/activex-wia/package.json new file mode 100644 index 0000000000..d798f99261 --- /dev/null +++ b/types/activex-wia/package.json @@ -0,0 +1 @@ +{ "dependencies": { "activex-helpers": "*"}} \ No newline at end of file diff --git a/types/activex-wia/tsconfig.json b/types/activex-wia/tsconfig.json new file mode 100644 index 0000000000..b06917d12c --- /dev/null +++ b/types/activex-wia/tsconfig.json @@ -0,0 +1,22 @@ + +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es5", "scripthost"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strict": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "activex-wia-tests.ts" + ] +} \ No newline at end of file diff --git a/types/activex-wia/tslint.json b/types/activex-wia/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/activex-wia/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/activex-windows-image-acquisition/index.d.ts b/types/activex-windows-image-acquisition/index.d.ts deleted file mode 100644 index af32d8a865..0000000000 --- a/types/activex-windows-image-acquisition/index.d.ts +++ /dev/null @@ -1,379 +0,0 @@ -// Type definitions for Microsoft Windows Image Acquisition Library v2.0 -// Project: https://msdn.microsoft.com/en-us/library/windows/desktop/ms630827(v=vs.85).aspx -// Definitions by: Zev Spitz -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace WIA { - - //Enums - type CommandID = - "'{04E725B0-ACAE-11D2-A093-00C04F72DC3C}'" //wiaCommandChangeDocument - | "'{E208C170-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandDeleteAllItems - | "'{9B26B7B2-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandSynchronize - | "'{AF933CAC-ACAD-11D2-A093-00C04F72DC3C}'" //wiaCommandTakePicture - | "'{1F3B3D8E-ACAE-11D2-A093-00C04F72DC3C}'"; //wiaCommandUnloadDocument - const CommandID: { - wiaCommandChangeDocument: CommandID, - wiaCommandDeleteAllItems: CommandID, - wiaCommandSynchronize: CommandID, - wiaCommandTakePicture: CommandID, - wiaCommandUnloadDocument: CommandID - }; - - type EventID = - "'{A28BBADE-64B6-11D2-A231-00C04FA31809}'" //wiaEventDeviceConnected - | "'{143E4E83-6497-11D2-A231-00C04FA31809}'" //wiaEventDeviceDisconnected - | "'{4C8F4EF5-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemCreated - | "'{1D22A559-E14F-11D2-B326-00C04F68CE61}'" //wiaEventItemDeleted - | "'{C686DCEE-54F2-419E-9A27-2FC7F2E98F9E}'" //wiaEventScanEmailImage - | "'{C00EB793-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanFaxImage - | "'{9B2B662C-6185-438C-B68B-E39EE25E71CB}'" //wiaEventScanFilmImage - | "'{A6C5A715-8C6E-11D2-977A-0000F87A926F}'" //wiaEventScanImage - | "'{FC4767C1-C8B3-48A2-9CFA-2E90CB3D3590}'" //wiaEventScanImage2 - | "'{154E27BE-B617-4653-ACC5-0FD7BD4C65CE}'" //wiaEventScanImage3 - | "'{A65B704A-7F3C-4447-A75D-8A26DFCA1FDF}'" //wiaEventScanImage4 - | "'{9D095B89-37D6-4877-AFED-62A297DC6DBE}'" //wiaEventScanOCRImage - | "'{B441F425-8C6E-11D2-977A-0000F87A926F}'"; //wiaEventScanPrintImage - const EventID: { - wiaEventDeviceConnected: EventID, - wiaEventDeviceDisconnected: EventID, - wiaEventItemCreated: EventID, - wiaEventItemDeleted: EventID, - wiaEventScanEmailImage: EventID, - wiaEventScanFaxImage: EventID, - wiaEventScanFilmImage: EventID, - wiaEventScanImage: EventID, - wiaEventScanImage2: EventID, - wiaEventScanImage3: EventID, - wiaEventScanImage4: EventID, - wiaEventScanOCRImage: EventID, - wiaEventScanPrintImage: EventID - }; - - type FormatID = - "'{B96B3CAB-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatBMP - | "'{B96B3CB0-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatGIF - | "'{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatJPEG - | "'{B96B3CAF-0728-11D3-9D7B-0000F81EF32E}'" //wiaFormatPNG - | "'{B96B3CB1-0728-11D3-9D7B-0000F81EF32E}'"; //wiaFormatTIFF - const FormatID: { - wiaFormatBMP: FormatID, - wiaFormatGIF: FormatID, - wiaFormatJPEG: FormatID, - wiaFormatPNG: FormatID, - wiaFormatTIFF: FormatID - }; - - type Miscellaneous = - "'*'" //wiaAnyDeviceID - | "'{00000000-0000-0000-0000-000000000000}'"; //wiaIDUnknown - const Miscellaneous: { - wiaAnyDeviceID: Miscellaneous, - wiaIDUnknown: Miscellaneous - }; - - const enum WiaDeviceType { - CameraDeviceType = 2, - ScannerDeviceType = 1, - UnspecifiedDeviceType = 0, - VideoDeviceType = 3 - } - - const enum WiaEventFlag { - ActionEvent = 2, - NotificationEvent = 1 - } - - const enum WiaImageBias { - MaximizeQuality = 131072, - MinimizeSize = 65536 - } - - const enum WiaImageIntent { - ColorIntent = 1, - GrayscaleIntent = 2, - TextIntent = 4, - UnspecifiedIntent = 0 - } - - const enum WiaImagePropertyType { - ByteImagePropertyType = 1001, - LongImagePropertyType = 1004, - RationalImagePropertyType = 1006, - StringImagePropertyType = 1002, - UndefinedImagePropertyType = 1000, - UnsignedIntegerImagePropertyType = 1003, - UnsignedLongImagePropertyType = 1005, - UnsignedRationalImagePropertyType = 1007, - VectorOfBytesImagePropertyType = 1101, - VectorOfLongsImagePropertyType = 1103, - VectorOfRationalsImagePropertyType = 1105, - VectorOfUndefinedImagePropertyType = 1100, - VectorOfUnsignedIntegersImagePropertyType = 1102, - VectorOfUnsignedLongsImagePropertyType = 1104, - VectorOfUnsignedRationalsImagePropertyType = 1106 - } - - const enum WiaItemFlag { - AnalyzeItemFlag = 16, - AudioItemFlag = 32, - BurstItemFlag = 2048, - DeletedItemFlag = 128, - DeviceItemFlag = 64, - DisconnectedItemFlag = 256, - FileItemFlag = 2, - FolderItemFlag = 4, - FreeItemFlag = 0, - GeneratedItemFlag = 16384, - HasAttachmentsItemFlag = 32768, - HPanoramaItemFlag = 512, - ImageItemFlag = 1, - RemovedItemFlag = -2147483648, - RootItemFlag = 8, - StorageItemFlag = 4096, - TransferItemFlag = 8192, - VideoItemFlag = 65536, - VPanoramaItemFlag = 1024 - } - - const enum WiaPropertyType { - BooleanPropertyType = 1, - BytePropertyType = 2, - ClassIDPropertyType = 15, - CurrencyPropertyType = 12, - DatePropertyType = 13, - DoublePropertyType = 11, - ErrorCodePropertyType = 7, - FileTimePropertyType = 14, - HandlePropertyType = 18, - IntegerPropertyType = 3, - LargeIntegerPropertyType = 8, - LongPropertyType = 5, - ObjectPropertyType = 17, - SinglePropertyType = 10, - StringPropertyType = 16, - UnsignedIntegerPropertyType = 4, - UnsignedLargeIntegerPropertyType = 9, - UnsignedLongPropertyType = 6, - UnsupportedPropertyType = 0, - VariantPropertyType = 19, - VectorOfBooleansPropertyType = 101, - VectorOfBytesPropertyType = 102, - VectorOfClassIDsPropertyType = 115, - VectorOfCurrenciesPropertyType = 112, - VectorOfDatesPropertyType = 113, - VectorOfDoublesPropertyType = 111, - VectorOfErrorCodesPropertyType = 107, - VectorOfFileTimesPropertyType = 114, - VectorOfIntegersPropertyType = 103, - VectorOfLargeIntegersPropertyType = 108, - VectorOfLongsPropertyType = 105, - VectorOfSinglesPropertyType = 110, - VectorOfStringsPropertyType = 116, - VectorOfUnsignedIntegersPropertyType = 104, - VectorOfUnsignedLargeIntegersPropertyType = 109, - VectorOfUnsignedLongsPropertyType = 106, - VectorOfVariantsPropertyType = 119 - } - - const enum WiaSubType { - FlagSubType = 3, - ListSubType = 2, - RangeSubType = 1, - UnspecifiedSubType = 0 - } - - //Interfaces - interface CommonDialog { - ShowAcquireImage: (DeviceType?: WiaDeviceType, Intent?: WiaImageIntent, Bias?: WiaImageBias, FormatID?: string, AlwaysSelectDevice?: boolean, UseCommonUI?: boolean, CancelError?: boolean) => ImageFile; - ShowAcquisitionWizard: (Device: Device) => any; - ShowDeviceProperties: (Device: Device, CancelError?: boolean) => void; - ShowItemProperties: (Item: Item, CancelError?: boolean) => void; - ShowPhotoPrintingWizard: (Files: any) => void; - ShowSelectDevice: (DeviceType?: WiaDeviceType, AlwaysSelectDevice?: boolean, CancelError?: boolean) => Device; - ShowSelectItems: (Device: Device, Intent?: WiaImageIntent, Bias?: WiaImageBias, SingleSelect?: boolean, UseCommonUI?: boolean, CancelError?: boolean) => Items; - ShowTransfer: (Item: Item, FormatID?: string, CancelError?: boolean) => any; - } - - interface Device { - Commands: DeviceCommands; - DeviceID: string; - Events: DeviceEvents; - ExecuteCommand: (CommandID: string) => Item; - GetItem: (ItemID: string) => Item; - Items: Items; - Properties: Properties; - Type: WiaDeviceType; - WiaItem: any /*VT_UNKNOWN*/; - } - - interface DeviceCommand { - CommandID: string; - Description: string; - Name: string; - } - - interface DeviceCommands { - Count: number; - Item: (Index: number) => DeviceCommand; - } - - interface DeviceEvent { - Description: string; - EventID: string; - Name: string; - Type: WiaEventFlag; - } - - interface DeviceEvents { - Count: number; - Item: (Index: number) => DeviceEvent; - } - - interface DeviceInfo { - Connect: () => Device; - DeviceID: string; - Properties: Properties; - Type: WiaDeviceType; - } - - interface DeviceInfos { - Count: number; - Item: (Index: any) => DeviceInfo; - } - - interface DeviceManager { - DeviceInfos: DeviceInfos; - RegisterEvent: (EventID: string, DeviceID?: string) => void; - RegisterPersistentEvent: (Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string) => void; - UnregisterEvent: (EventID: string, DeviceID?: string) => void; - UnregisterPersistentEvent: (Command: string, Name: string, Description: string, Icon: string, EventID: string, DeviceID?: string) => void; - } - - interface Filter { - Description: string; - FilterID: string; - Name: string; - Properties: Properties; - } - - interface FilterInfo { - Description: string; - FilterID: string; - Name: string; - } - - interface FilterInfos { - Count: number; - Item: (Index: any) => FilterInfo; - } - - interface Filters { - Add: (FilterID: string, Index?: number) => void; - Count: number; - Item: (Index: number) => Filter; - Remove: (Index: number) => void; - } - - interface Formats { - Count: number; - Item: (Index: number) => string; - } - - interface ImageFile { - ActiveFrame: number; - ARGBData: Vector; - FileData: Vector; - FileExtension: string; - FormatID: string; - FrameCount: number; - Height: number; - HorizontalResolution: number; - IsAlphaPixelFormat: boolean; - IsAnimated: boolean; - IsExtendedPixelFormat: boolean; - IsIndexedPixelFormat: boolean; - LoadFile: (Filename: string) => void; - PixelDepth: number; - Properties: Properties; - SaveFile: (Filename: string) => void; - VerticalResolution: number; - Width: number; - } - - interface ImageProcess { - Apply: (Source: ImageFile) => ImageFile; - FilterInfos: FilterInfos; - Filters: Filters; - } - - interface Item { - Commands: DeviceCommands; - ExecuteCommand: (CommandID: string) => Item; - Formats: Formats; - ItemID: string; - Items: Items; - Properties: Properties; - Transfer: (FormatID?: string) => any; - WiaItem: any /*VT_UNKNOWN*/; - } - - interface Items { - Add: (Name: string, Flags: number) => void; - Count: number; - Item: (Index: number) => Item; - Remove: (Index: number) => void; - } - - interface Properties { - Count: number; - Exists: (Index: any) => boolean; - Item: (Index: any) => Property; - } - - interface Property { - IsReadOnly: boolean; - IsVector: boolean; - Name: string; - PropertyID: number; - SubType: WiaSubType; - SubTypeDefault: any; - SubTypeMax: number; - SubTypeMin: number; - SubTypeStep: number; - SubTypeValues: Vector; - Type: number; - Value: any; - } - - interface Rational { - Denominator: number; - Numerator: number; - Value: number; - } - - interface Vector { - Add: (Value: any, Index?: number) => void; - BinaryData: any; - Clear: () => void; - Count: number; - Date: VarDate; - ImageFile: (Width?: number, Height?: number) => ImageFile; - Item: (Index: number) => any; //Also has setter with parameters - Picture: (Width?: number, Height?: number) => any; - Remove: (Index: number) => any; - SetFromString: (Value: string, Resizable?: boolean, Unicode?: boolean) => void; - String: (Unicode?: boolean) => string; - } - -} - -interface ActiveXObject { - new (progID: 'WIA.Rational'): WIA.Rational; - new (progID: 'WIA.Vector'): WIA.Vector; - new (progID: 'WIA.ImageFile'): WIA.ImageFile; - new (progID: 'WIA.ImageProcess'): WIA.ImageProcess; - new (progID: 'WIA.CommonDialog'): WIA.CommonDialog; - new (progID: 'WIA.DeviceManager'): WIA.DeviceManager; -} - diff --git a/types/activex-windows-image-acquisition/tsconfig.json b/types/activex-windows-image-acquisition/tsconfig.json deleted file mode 100644 index 486d95921c..0000000000 --- a/types/activex-windows-image-acquisition/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom", - "scripthost" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": false, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "activex-windows-image-acquisition-tests.ts" - ] -} \ No newline at end of file diff --git a/types/archiver/index.d.ts b/types/archiver/index.d.ts index 2e4b1063ff..1ceffb18f9 100644 --- a/types/archiver/index.d.ts +++ b/types/archiver/index.d.ts @@ -15,9 +15,7 @@ /// -import * as fs from 'fs'; import * as stream from 'stream'; -import * as express from 'express'; import * as glob from 'glob'; declare function archiver(format: archiver.Format, options?: archiver.ArchiverOptions): archiver.Archiver; @@ -46,7 +44,7 @@ declare namespace archiver { glob(pattern: string, options?: glob.IOptions, data?: EntryData): this; finalize(): this; - pipe(stream: fs.WriteStream | express.Response): void; + pipe(stream: stream.Writable): void; setFormat(format: string): this; setModule(module: Function): this; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index b84e92e223..08a866e9b1 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -7,7 +7,8 @@ const management = new auth0.ManagementClient({ const auth = new auth0.AuthenticationClient({ domain: '{YOUR_ACCOUNT}.auth0.com', - clientId: '{OPTIONAL_CLIENT_ID}' + clientId: '{OPTIONAL_CLIENT_ID}', + clientSecret: '{OPTIONAL_CLIENT_SECRET}' }); // Using a callback. diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index 3025b8d380..07a316268a 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for auth0 3.0 +// Type definitions for auth0 2.3 // Project: https://github.com/auth0/node-auth0 // Definitions by: Wilson Hobbs , Seth Westphal , Amiram Korach // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -83,6 +83,7 @@ export interface Identity { export interface AuthenticationClientOptions { clientId?: string; + clientSecret?: string; domain: string; } @@ -131,6 +132,16 @@ export interface ResetPasswordEmailOptions { connection: string; } +export interface ClientCredentialsGrantOptions { + audience: string; +} + +export interface PasswordGrantOptions { + username: string; + password: string; + realm?: string; +} + export interface ObjectWithId { id: string; } @@ -187,7 +198,8 @@ export interface UnlinkAccountsResponse { export interface LinkAccountsData { user_id: string; - connection_id: string; + connection_id?: string; + provider?: string; } export interface Token { @@ -254,8 +266,11 @@ export class AuthenticationClient { getProfile(accessToken: string): Promise; getProfile(accessToken: string, cb: (err: Error, message: string) => void): void; - getCredentialsGrant(scope: string): Promise; - getCredentialsGrant(scope: string, cb: (err: Error, message: string) => void): void; + clientCredentialsGrant(options: ClientCredentialsGrantOptions): Promise; + clientCredentialsGrant(options: ClientCredentialsGrantOptions, cb: (err: Error, response: any) => void): void; + + passwordGrant(options: PasswordGrantOptions): Promise; + passwordGrant(options: PasswordGrantOptions, cb: (err: Error, response: any) => void): void; } diff --git a/types/chartjs/chartjs-tests.ts b/types/chartjs/chartjs-tests.ts index d6b47d45bf..ef50da1b40 100644 --- a/types/chartjs/chartjs-tests.ts +++ b/types/chartjs/chartjs-tests.ts @@ -51,12 +51,14 @@ var lineData: LinearChartData = { datasets: [ { label: 'Accepted', + type: 'bar', fillColor: 'rgba(220,220,220,0.2)', strokeColor: 'rgba(220,220,220,1)', pointColor: 'rgba(220,220,220,1)', pointStrokeColor: '#fff', pointHighlightFill: '#fff', pointHighlightStroke: 'rgba(220,220,220,1)', + borderColor: "#9b0391", data: [65, 59, 80, 81, 56, 55, 40] }, { @@ -67,7 +69,8 @@ var lineData: LinearChartData = { pointStrokeColor: '#fff', pointHighlightFill: '#fff', pointHighlightStroke: 'rgba(151,187,205,1)', - data: [28, 48, 40, 19, 86, 27, 90] + data: [28, 48, 40, 19, 86, 27, 90], + yAxisID: 'quarantined' } ] }; @@ -85,6 +88,21 @@ var myLineChart = new Chart(ctx).Line(lineData, { datasetStroke: true, datasetStrokeWidth: 2, datasetFill: true, + scales: { + xAxes: [{ + stacked: true, + }], + yAxes: [{ + position: "left", + "id": "users" + }, { + position: "right", + "id": "ratio", + ticks: { + min: -13 + } + }] + }, legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
  • <%}%>
" }); @@ -129,6 +147,10 @@ var myBarChart = new Chart(ctx).Bar(barData, { barStrokeWidth: 2, barValueSpacing: 5, barDatasetSpacing: 1, + legend: { + display: true, + position: 'bottom' + }, legendTemplate: "
    -legend\"><% for (var i=0; i
  • \"><%if(datasets[i].label){%><%=datasets[i].label%><%}%>
  • <%}%>
" }); @@ -369,4 +391,3 @@ var my2ndRadarChart = new Chart(ctx).Radar(radarData, partialOpts); var my2ndPolarAreaChart = new Chart(ctx).PolarArea(polarAreaData, partialOpts); var my2ndPieChart = new Chart(ctx).Pie(pieData, partialOpts); var my2ndDoughnutChart = new Chart(ctx).Doughnut(pieData, partialOpts); - diff --git a/types/chartjs/index.d.ts b/types/chartjs/index.d.ts index fca81b6d22..a9075e02a2 100644 --- a/types/chartjs/index.d.ts +++ b/types/chartjs/index.d.ts @@ -1,13 +1,18 @@ // Type definitions for Chart.js // Project: https://github.com/nnnick/Chart.js // Definitions by: Steve Fenton +// Alessio Fanelli // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface ChartDataSet { label: string; fillColor: string; strokeColor: string; + type?: string; + yAxisID?: string; + xAxisID?: string; + borderColor?: string; /* Line, Radar */ pointColor?: string; pointStrokeColor?: string; @@ -17,6 +22,8 @@ interface ChartDataSet { /* Bar */ highlightFill?: string; highlightStroke?: string; + backgroundColorHover?: string; + data: number[]; } @@ -80,8 +87,44 @@ interface ChartOptions extends ChartSettings { scaleGridLineColor?: string; scaleGridLineWidth?: number; scaleShowHorizontalLines?: boolean; - scaleShowVerticalLines?: boolean; + scaleShowVerticalLines?: boolean; legendTemplate?: string; + tooltips?: ChartTooltips; + legend?: ChartLegend; + scales?: ChartScales; + title?: ChartTitle; +} + +interface ChartTooltips { + mode?: string; + intersect?: boolean; +} + +interface ChartLegend { + display?: boolean; + position?: string; +} + +interface ChartScales { + xAxes?: Array; + yAxes?: Array; +} + +interface ChartScalesOptions { + stacked?: boolean; + position?: string; + id?: string; + ticks?: ScaleTicksOptions; +} + +interface ScaleTicksOptions { + min?: number; + max?: number; +} + +interface ChartTitle { + display?: boolean; + text?: string; } interface PointsAtEvent { @@ -137,7 +180,7 @@ interface BarChartOptions extends ChartOptions { barShowStroke?: boolean; barStrokeWidth?: number; barValueSpacing?: number; - barDatasetSpacing?: number; + barDatasetSpacing?: number; } interface RadarChartOptions extends ChartSettings { diff --git a/types/cheerio/cheerio-tests.ts b/types/cheerio/cheerio-tests.ts index 1c0848eef7..4a15f029f0 100644 --- a/types/cheerio/cheerio-tests.ts +++ b/types/cheerio/cheerio-tests.ts @@ -306,3 +306,5 @@ $.parseHTML(html, null, true); * Not in doc */ $el.toArray(); + +cheerio.html($el); diff --git a/types/cheerio/index.d.ts b/types/cheerio/index.d.ts index 4096a0f9c2..f525a46ee6 100644 --- a/types/cheerio/index.d.ts +++ b/types/cheerio/index.d.ts @@ -263,7 +263,7 @@ interface CheerioElement { nodeValue: string; } -interface CheerioAPI extends CheerioSelector { +interface CheerioAPI extends CheerioSelector, CheerioStatic { load(html: string, options?: CheerioOptionsInterface): CheerioStatic; load(element: CheerioElement, options?: CheerioOptionsInterface): CheerioStatic; } diff --git a/types/cote/cote-tests.ts b/types/cote/cote-tests.ts index 3236fe83b7..8fd52a73a4 100644 --- a/types/cote/cote-tests.ts +++ b/types/cote/cote-tests.ts @@ -26,6 +26,27 @@ class Readme { .then(() => process.exit()); } + requesterCallback() { + const randomRequester = new cote.Requester({ + name: 'Random Requester', + namespace: 'rnd', + key: 'a certain key', + requests: ['randomRequest'] + }); + + const req = { + type: 'randomRequest', + payload: { + val: Math.floor(Math.random() * 10) + } + }; + + randomRequester.send(req, res => { + console.log(res); + process.exit(); + }); + } + responder() { const randomResponder = new cote.Responder({ name: 'Random Responder', @@ -34,19 +55,49 @@ class Readme { respondsTo: ['randomRequest'] }); - randomResponder.on('randomRequest', (req: cote.Action<{ val: number }>) => { + interface RandomRequest { + type: 'randomRequest'; + payload: { val: number }; + } + + randomResponder.on('randomRequest', (req: RandomRequest) => { const answer = Math.floor(Math.random() * 10); console.log('request', req.payload.val, 'answering with', answer); return Promise.resolve(answer); }); } + responderCallback() { + const randomResponder = new cote.Responder({ + name: 'Random Responder', + namespace: 'rnd', + key: 'a certain key', + respondsTo: ['randomRequest'] + }); + + interface RandomRequest { + type: 'randomRequest'; + payload: { val: number }; + } + + randomResponder.on('randomRequest', (req: RandomRequest, callback: (answer: number) => void) => { + const answer = Math.floor(Math.random() * 10); + console.log('request', req.payload.val, 'answering with', answer); + callback(answer); + }); + } + mongooseResponder() { const UserModel = require('UserModel'); // a promise-based model API const userResponder = new cote.Responder({ name: 'User Responder' }); - userResponder.on('find', (req: cote.Action<{ username: string }>) => UserModel.findOne(req.payload)); + interface Find { + type: 'find'; + payload: { username: string }; + } + + userResponder.on('find', (req: Find) => UserModel.findOne(req.payload)); } mongooseRequester() { @@ -67,16 +118,16 @@ class Readme { }); setInterval(() => { - const action = { + const event = { type: 'randomUpdate', payload: { val: Math.floor(Math.random() * 1000) } }; - console.log('emitting', action); + console.log('emitting', event); - randomPublisher.publish('randomUpdate', action); + randomPublisher.publish('randomUpdate', event); }, 3000); } @@ -141,7 +192,7 @@ class Readme { key: 'conversion backend' }); - responder.on('convert', (req) => { + responder.on('convert', (req: any) => { return conversionRequester.send(req); // proxy the request }); } @@ -157,11 +208,16 @@ class Readme { eur_usd: 1.10 }; - responder.on('convert', (req: cote.Action<{ - amount: number, - from: string, - to: string - }>) => { + interface Convert { + type: 'convert'; + payload: { + amount: number, + from: string, + to: string + }; + } + + responder.on('convert', (req: Convert) => { const { payload } = req; return Promise.resolve(payload.amount * rates[`${payload.from}_${payload.to}`]); }); @@ -183,3 +239,213 @@ class Readme { const req = new cote.Requester({ name: 'req' }, { broadcast: '255.255.255.255' }); } } + +/** + * Fixes for initial errors and shortcomings. + * @see https://github.com/makepost/DefinitelyTyped/projects/1 + */ +class InitialObservations { + event() { + const event: cote.Event = { type: 'someEvent' }; + } + + eventEmitter() { + const quitter = new cote.Requester({ name: 'Quitter' }); + quitter.onAny(() => process.exit); + + const indecisive = new cote.Responder({ name: 'Indecisive' }); + const callback = (x: T) => Promise.resolve(x); + indecisive.on('choice', callback); + indecisive.off('choice', callback); + + const techno = new cote.Publisher({ name: 'Techno' }); + techno.removeAllListeners(); + + const village = new cote.Subscriber({ name: 'Village' }); + const doHelp = () => { }; + village.many('wolf', 2, doHelp); + village.emit('wolf'); + village.emit('wolf'); + const emptyArray = village.listenersAny(); + village.emit('wolf'); // no reaction + + const eternity = new cote.Sockend(null as any, { name: 'Eternity' }); + const handler = () => { + if (Math.random() === Number.MIN_VALUE) { + console.log('It happened.'); + eternity.offAny(handler); + } + }; + eternity.addListener('request', handler); + + const monitor = new cote.Monitor({ + name: 'Monitor', + port: 8025 + }); + monitor.setMaxListeners(1); + monitor.once('foobar', () => { + monitor.removeAllListeners(); + monitor.once('foobar', () => { + console.log('Not a warning.'); + }); + }); + } + + advertisement() { + // Incorrect: + // const requester = new cote.Requester({ + // name: 'Requester', + // respondsTo: ['foo'] + // }) + + // Incorrect: + // const responder = new cote.Responder({ + // name: 'Responder', + // subscribesTo: ['bar'] + // }) + + // Incorrect: + // const publisher = new cote.Publisher({ + // name: 'Publisher', + // requests: ['baz'] + // }) + + // Incorrect: + // const subscriber = new cote.Subscriber({ + // name: 'Subscriber', + // broadcasts: ['qux'] + // }) + } + + discovery() { + new cote.Responder({ name: 'LocalUnlessForwarded' }, { address: '127.0.0.1' }); + + new cote.Publisher({ name: 'PassionateGreeter' }, { helloInterval: 100 }); + + new cote.Requester({ name: 'Optimist' }, { + checkInterval: 1e5, + nodeTimeout: 1e6 + }); + + new cote.Subscriber({ name: 'Hachiko' }, { masterTimeout: 9 * 365 * 24 * 60 * 60 * 1000 }); + + new cote.Monitor({ name: 'HelloService', port: 2345 }, { + monitor: false, + statusLogsEnabled: false + }); + + new cote.Monitor({ name: 'OfflineLogger', port: 2346 }, { + disableScreen: true, + helloLogsEnabled: false, + log: true + }); + + new cote.Responder({ name: 'HearsNoneAbove' }, { ignoreProcess: true }); + + new cote.Requester({ name: 'OwnStatusReporter' }, { statusInterval: 100 }); + } + + callbackApi() { + // Added to Readme above, near respective Promise examples. + } + + timeBalancedRequester() { + const randomRequester = new cote.TimeBalancedRequester({ + name: 'Random Requester', + namespace: 'rnd', + key: 'a certain key', + requests: ['randomRequest'] + }); + + const req = { + type: 'randomRequest', + payload: { + val: Math.floor(Math.random() * 10) + } + }; + + randomRequester.send(req) + .then(console.log) + .catch(console.log) + .then(() => process.exit()); + } + + pendingBalancedRequester() { + const randomRequester = new cote.PendingBalancedRequester({ + name: 'Random Requester', + namespace: 'rnd', + key: 'a certain key', + requests: ['randomRequest'] + }); + + const req = { + type: 'randomRequest', + payload: { + val: Math.floor(Math.random() * 10) + } + }; + + randomRequester.send(req) + .then(console.log) + .catch(console.log) + .then(() => process.exit()); + } + + lifecycle() { + const key = Math.random().toString(); + + const requester = new cote.Requester({ + name: `${key} requester`, + key + }); + + const responder = new cote.Responder({ + name: `${key} responder`, + key + }); + + responder.on('cote:added', ({ advertisement, type }) => { + console.log({ + advertisement: { + broadcasts: advertisement.broadcasts, + key: advertisement.key, + name: advertisement.name, + namespace: advertisement.namespace, + requests: advertisement.requests, + respondsTo: advertisement.respondsTo, + subscribesTo: advertisement.subscribesTo + }, + type + }); + + requester.close(); + }); + + responder.on('cote:removed', ({ advertisement, type }) => { + console.assert(advertisement.name === `${key} requester`); + + console.log({ + advertisement: { + broadcasts: advertisement.broadcasts, + key: advertisement.key, + name: advertisement.name, + namespace: advertisement.namespace, + requests: advertisement.requests, + respondsTo: advertisement.respondsTo, + subscribesTo: advertisement.subscribesTo + }, + type + }); + + responder.close(); + }); + } + + monitorAdvertisement() { + const name = 'Service'; + const port = undefined; + + new cote.Monitor({ name, port }); + new cote.Monitor({ name }); + } +} diff --git a/types/cote/index.d.ts b/types/cote/index.d.ts index 6a59b37392..f6c60c54a2 100644 --- a/types/cote/index.d.ts +++ b/types/cote/index.d.ts @@ -3,11 +3,12 @@ // Definitions by: makepost // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +import { EventEmitter2 } from "eventemitter2"; import * as SocketIO from "socket.io"; import { Stream } from "stream"; import { Server } from "http"; -export class Requester { +export abstract class Component extends EventEmitter2 { constructor( /** * Configuration which controls the data being advertised for auto-discovery. @@ -20,21 +21,59 @@ export class Requester { discoveryOptions?: DiscoveryOptions ); + /** + * Closes socket and stops discovery. + */ + close(): void; +} + +export class Requester extends Component { + constructor( + /** + * Configuration which controls the data being advertised for auto-discovery. + */ + advertisement: RequesterAdvertisement, + + /** + * Controls the network-layer configuration and environments for components. + */ + discoveryOptions?: DiscoveryOptions + ); + /** * Queues a request until a Responder is available, and once so, delivers * the request. Requests are dispatched to Responders in a round-robin way. * - * @param action Request. + * @param event Request. */ - send(action: Action): Promise; + send(event: T): Promise; + + /** + * Queues a request until a Responder is available, and once so, delivers + * the request. Requests are dispatched to Responders in a round-robin way. + * + * @param event Request. + * @param callback Function to execute after getting a result. + */ + send(event: T, callback: (result: any) => void): void; } -export class Responder { +/** + * Configuration which controls the data being advertised for auto-discovery. + */ +export interface RequesterAdvertisement extends Advertisement { + /** + * Request types that a Requester can send. + */ + requests?: string[]; +} + +export class Responder extends Component { constructor( /** * Configuration which controls the data being advertised for auto-discovery. */ - advertisement: Advertisement, + advertisement: ResponderAdvertisement, /** * Controls the network-layer configuration and environments for components. @@ -42,24 +81,47 @@ export class Responder { discoveryOptions?: DiscoveryOptions ); + /** + * Listens to internal `cote:added` and `cote:removed` events. + * + * @param listener Callback. + */ + on( + type: 'cote:added' | 'cote:removed', + listener: (event: Status) => void + ): this; + /** * Responds to certain requests from a Requester. * * @param type Type. May be wildcarded or namespaced like in EventEmitter2. * @param listener Callback. Should return a result. */ - on( - type: string, - listener: (action: Action) => Promise - ): void; + on( + type: string | string[], + listener: ( + ((event: T, callback: (result: any) => void) => void) | + ((event: T) => Promise) + ) + ): this; } -export class Publisher { +/** + * Configuration which controls the data being advertised for auto-discovery. + */ +export interface ResponderAdvertisement extends Advertisement { + /** + * Request types that a Responder can listen to. + */ + respondsTo?: string[]; +} + +export class Publisher extends Component { constructor( /** * Configuration which controls the data being advertised for auto-discovery. */ - advertisement: Advertisement, + advertisement: PublisherAdvertisement, /** * Controls the network-layer configuration and environments for components. @@ -72,20 +134,30 @@ export class Publisher { * there are no Subscribers listening, the event is lost. * * @param type EventEmitter-compatible type. - * @param action Request. + * @param event Request. */ - publish( + publish( type: string, - action: Action + event: T ): void; } -export class Subscriber { +/** + * Configuration which controls the data being advertised for auto-discovery. + */ +export interface PublisherAdvertisement extends Advertisement { + /** + * Event types that a Publisher can publish. + */ + broadcasts?: string[]; +} + +export class Subscriber extends Component { constructor( /** * Configuration which controls the data being advertised for auto-discovery. */ - advertisement: Advertisement, + advertisement: SubscriberAdvertisement, /** * Controls the network-layer configuration and environments for components. @@ -99,13 +171,23 @@ export class Subscriber { * @param type Type. May be wildcarded or namespaced like in EventEmitter2. * @param listener Callback. Returns nothing. */ - on( - type: string, - listener: (action: Action) => void - ): void; + on( + type: string | string[], + listener: (event: T) => void + ): this; } -export class Sockend { +/** + * Configuration which controls the data being advertised for auto-discovery. + */ +export interface SubscriberAdvertisement extends Advertisement { + /** + * Event types that a Subscriber can listen to. + */ + subscribesTo?: string[]; +} + +export class Sockend extends Component { /** * Exposes APIs directly to front-end. Make sure to use namespaces. */ @@ -115,7 +197,7 @@ export class Sockend { /** * Configuration which controls the data being advertised for auto-discovery. */ - advertisement: Advertisement, + advertisement: SockendAdvertisement, /** * Controls the network-layer configuration and environments for components. @@ -124,12 +206,17 @@ export class Sockend { ); } -export class Monitor { +/** + * Configuration which controls the data being advertised for auto-discovery. + */ +export interface SockendAdvertisement extends ResponderAdvertisement, PublisherAdvertisement { } + +export class Monitor extends Component { constructor( /** * Configuration which controls the data being advertised for auto-discovery. */ - advertisement: Advertisement, + advertisement: MonitorAdvertisement, /** * Controls the network-layer configuration and environments for components. @@ -140,6 +227,16 @@ export class Monitor { ) } +/** + * Configuration which controls the data being advertised for auto-discovery. + */ +export interface MonitorAdvertisement extends Advertisement { + /** + * Port for Monitor to listen on. By default will start searching from 8000. + */ + port?: number | string; +} + /** * Displays the cote ecosystem running in your environment in a nice graph. * @@ -151,16 +248,58 @@ export function MonitoringTool(port: number): { }; /** - * Flux standard action. - * @see https://github.com/acdlite/flux-standard-action + * Takes average response times of each connected socket and balances requests + * among them accordingly. */ -export interface Action { - type: string; - payload: T; - error?: boolean; - meta?: {}; +export class TimeBalancedRequester extends Requester { + /** + * How long to wait for response before neglecting its calculation time, + * in milliseconds. + */ + CALCULATION_TIMEOUT: number; + + /** + * How many requests to make before exploring a random server for response + * time improvement. + */ + MAX_REQUESTS: number; + + /** + * How often to check whether a response arrived. Readonly because used in + * constructor right after being set. + */ + readonly SAMPLE_INTERVAL: number; } +/** + * Keeps track of open, pending requests for each known Responder. Each new + * request goes to the Responder with the minimum open requests. + */ +export class PendingBalancedRequester extends Requester { } + +/** + * Event is nothing but object with `type`. + */ +export interface Event { + type: string; +} + +/** + * Internal `cote:added` and `cote:removed` events. + */ +export interface Status extends Event { + advertisement: StatusAdvertisement; +} + +/** + * Advertisement in internal `cote:added` and `cote:removed` events. + */ +export interface StatusAdvertisement extends + RequesterAdvertisement, + ResponderAdvertisement, + PublisherAdvertisement, + SubscriberAdvertisement { } + /** * Configuration which controls the data being advertised for auto-discovery. */ @@ -180,32 +319,81 @@ export interface Advertisement { * to communicate. Think of it as `${environment}_${key}`. */ key?: string; - - /** - * Request types that a Requester can send. - */ - requests?: string[]; - - /** - * Response types that a Responder can listen to. - */ - respondsTo?: string[]; - - /** - * Event types that a Publisher can publish. - */ - broadcasts?: string[]; - - /** - * Event types that a Subscriber can listen to. - */ - subscribesTo?: string[]; } /** * Controls the network-layer configuration and environments for components. */ export interface DiscoveryOptions { + /** + * Multicast address if using multicast. + */ multicast?: string; + + /** + * Broadcast address if using broadcast. + */ broadcast?: string; + + /** + * Address to bind to. + */ + address?: string; + + /** + * How often to broadcast a hello packet in milliseconds. + */ + helloInterval?: number; + + /** + * How often to to check for missing nodes in milliseconds. + */ + checkInterval?: number; + + /** + * Consider a node dead if not seen in this many milliseconds. + */ + nodeTimeout?: number; + + /** + * Consider a master node dead if not seen in this many milliseconds. + */ + masterTimeout?: number; + + /** + * Skips key equality checks when logging. + */ + monitor?: boolean; + + /** + * If false, disables `helloLogsEnabled` and `statusLogsEnabled` no matter + * what value they have, and also own hello log. + */ + log?: boolean; + + /** + * Notifies when another service goes online. + */ + helloLogsEnabled?: boolean; + + /** + * Notifies when another service goes online or offline. If false, disables + * `helloLogsEnabled` as well. + */ + statusLogsEnabled?: boolean; + + /** + * Ignores messages from other services within the same process. + */ + ignoreProcess?: boolean; + + /** + * Prevents Monitor from drawing. + */ + disableScreen?: boolean; + + /** + * Milliseconds between emissions of own status for monitoring. + */ + statusInterval?: number; } diff --git a/types/cote/package.json b/types/cote/package.json new file mode 100644 index 0000000000..ce4365fc69 --- /dev/null +++ b/types/cote/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "eventemitter2": "^4.1.0" + } +} diff --git a/types/dedent/dedent-tests.ts b/types/dedent/dedent-tests.ts new file mode 100644 index 0000000000..30c3546066 --- /dev/null +++ b/types/dedent/dedent-tests.ts @@ -0,0 +1,11 @@ +import * as dedent from 'dedent'; + +const lines: string = dedent` + first + second + third +`; + +const text: string = dedent(` + A test argument. + `); diff --git a/types/dedent/index.d.ts b/types/dedent/index.d.ts new file mode 100644 index 0000000000..1029974a22 --- /dev/null +++ b/types/dedent/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for dedent 0.7 +// Project: https://github.com/dmnd/dedent +// Definitions by: Douglas Duteil +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = dedent; + +declare function dedent(literals: string): string; +declare function dedent(literals: TemplateStringsArray, ...placeholders: any[]): string; +declare namespace dedent {} diff --git a/types/qiniu/tsconfig.json b/types/dedent/tsconfig.json similarity index 94% rename from types/qiniu/tsconfig.json rename to types/dedent/tsconfig.json index d862b59b98..29eb7040b0 100644 --- a/types/qiniu/tsconfig.json +++ b/types/dedent/tsconfig.json @@ -17,6 +17,6 @@ }, "files": [ "index.d.ts", - "qiniu-tests.ts" + "dedent-tests.ts" ] } diff --git a/types/qiniu/tslint.json b/types/dedent/tslint.json similarity index 100% rename from types/qiniu/tslint.json rename to types/dedent/tslint.json diff --git a/types/draggabilly/draggabilly-tests.ts b/types/draggabilly/draggabilly-tests.ts new file mode 100644 index 0000000000..6ab38e6c13 --- /dev/null +++ b/types/draggabilly/draggabilly-tests.ts @@ -0,0 +1,46 @@ +import Draggabilly from 'draggabilly'; + +const elem = document.querySelector('.draggable') as Element; + +const draggieA = new Draggabilly('.test'); +const draggieB = new Draggabilly(elem); + +const draggie = new Draggabilly(elem, { + axis: 'x', + containment: true, + grid: [20, 20], + handle: '.handle' +}); + +const draggiePosX: number = draggie.position.x; +const draggiePosY: number = draggie.position.y; + +draggie.on( 'dragMove', (event, pointer, moveVector) => { + const pointerPageX: number = pointer.pageX; + const pointePageY: number = pointer.pageY; + + const moveVectorX: number = moveVector.x; + const moveVectorY: number = moveVector.y; +}); + +draggie.on( 'dragStart', (event, pointer) => {}); + +draggie.on( 'dragEnd', (event, pointer) => {}); + +draggie.on( 'pointerDown', (event, pointer) => {}); + +draggie.on( 'pointerMove', (event, pointer, moveVector) => {}); + +draggie.on( 'pointerUp', (event, pointer) => {}); + +draggie.on( 'staticClick', (event, pointer) => {}); + +draggie.off('dragMove', (event, pointer, moveVector) => {}); + +draggie.once('dragMove', (event, pointer, moveVector) => {}); + +draggie.enable(); + +draggie.disable(); + +draggie.destroy(); diff --git a/types/draggabilly/index.d.ts b/types/draggabilly/index.d.ts new file mode 100644 index 0000000000..6307c424ab --- /dev/null +++ b/types/draggabilly/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for draggabilly 2.1 +// Project: http://draggabilly.desandro.com/ +// Definitions by: Jason Wu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export interface Position { + x: number; + y: number; +} + +export interface DraggabillyOptions { + axis?: 'x' | 'y'; + containment?: Element | string | boolean; + grid?: [number, number]; + handle?: string; +} + +export type DraggabillyClickEventName = 'dragStart' | 'dragEnd' | 'pointerDown' | 'pointerUp' | 'staticClick'; + +export type DraggabillyMoveEventName = 'dragMove' | 'pointerMove'; + +export default class Draggabilly { + position: Position; + + constructor(element: Element | string, options?: DraggabillyOptions); + + on(eventName: DraggabillyClickEventName, listener: (event: Event, pointer: MouseEvent | Touch) => void): Draggabilly; + + on(eventName: DraggabillyMoveEventName, listener: (event: Event, pointer: MouseEvent | Touch, moveVector: Position) => void): Draggabilly; + + off(eventName: DraggabillyClickEventName, listener: (event: Event, pointer: MouseEvent | Touch) => void): Draggabilly; + + off(eventName: DraggabillyMoveEventName, listener: (event: Event, pointer: MouseEvent | Touch, moveVector: Position) => void): Draggabilly; + + once(eventName: DraggabillyClickEventName, listener: (event: Event, pointer: MouseEvent | Touch) => void): Draggabilly; + + once(eventName: DraggabillyMoveEventName, listener: (event: Event, pointer: MouseEvent | Touch, moveVector: Position) => void): Draggabilly; + + enable(): void; + + disable(): void; + + destroy(): void; +} diff --git a/types/activex-data-objects/tsconfig.json b/types/draggabilly/tsconfig.json similarity index 76% rename from types/activex-data-objects/tsconfig.json rename to types/draggabilly/tsconfig.json index aa81742f09..32cc6ee235 100644 --- a/types/activex-data-objects/tsconfig.json +++ b/types/draggabilly/tsconfig.json @@ -3,12 +3,11 @@ "module": "commonjs", "lib": [ "es6", - "dom", - "scripthost" + "dom" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,6 +18,6 @@ }, "files": [ "index.d.ts", - "activex-data-objects-tests.ts" + "draggabilly-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/draggabilly/tslint.json b/types/draggabilly/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/draggabilly/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/electron-packager/electron-packager-tests.ts b/types/electron-packager/electron-packager-tests.ts index bf6122bb2f..482c49bbff 100644 --- a/types/electron-packager/electron-packager-tests.ts +++ b/types/electron-packager/electron-packager-tests.ts @@ -1,11 +1,8 @@ - - import * as packager from "electron-packager"; function callback(err: Error, appPath: string) { - const - msg = err.message, - index = appPath.indexOf("test"); + const msg = err.message; + const index = appPath.indexOf("test"); } packager({ @@ -13,29 +10,27 @@ packager({ name: "myapplication", platform: "win32", arch: "all", - version: "0.34.0" + electronVersion: "0.34.0" }, callback); packager({ dir: ".", name: "myapplication", - version: "0.34.0", + electronVersion: "0.34.0", all: true }, callback); -const pkger = require("electron-packager"); - -pkger({ +packager({ dir: ".", name: "myapplication", platform: "win32", arch: "all", - version: "0.34.0" + electronVersion: "0.34.0" }, callback); -pkger({ +packager({ dir: ".", name: "myapplication", - version: "0.34.0", + electronVersion: "0.34.0", all: true }, callback); diff --git a/types/electron-packager/index.d.ts b/types/electron-packager/index.d.ts index e5fe985761..99b232388b 100644 --- a/types/electron-packager/index.d.ts +++ b/types/electron-packager/index.d.ts @@ -1,115 +1,204 @@ -// Type definitions for electron-packager v5.1.0 -// Project: https://github.com/maxogden/electron-packager +// Type definitions for electron-packager 8.7 +// Project: https://github.com/electron-userland/electron-packager // Definitions by: Maxime LUCE +// Juan Jimenez-Anca // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -declare namespace ElectronPackager { +export = electronPackager; + +/** + * This will: + * - Find or download the correct release of Electron + * - Use that version of electron to create a app in /-- + * + * You should be able to launch the app on the platform you built for. If not, check your settings and try again. + * + * @param opts - Options to configure packaging. + * @param callback - Callback which is called when packaging is done or an error occured. + */ +declare function electronPackager(opts: electronPackager.Options, callback: electronPackager.finalCallback): void; + +declare namespace electronPackager { + /** + * Callback which is called when electron-packager is done. + * + * @param err - Contains errors if any. + * @param appPaths - Path(s) to the newly created application(s). + */ + type finalCallback = (err: Error, appPaths: string|string[]) => void; + + type ignoreFunction = (path: string) => boolean; + type onCompleteFn = (buildPath: string, electronVersion: string, platform: string, arch: string, callbackFn: () => void) => void; + type arch = "ia32" | "x64" | "armv7l" | "all"; + type packageManager = "npm" | "cnpm" | "yarn"; + type platform = "linux" | "win32" | "darwin" | "mas" | "all"; + + interface AsarOptions { + ordering?: string; + unpack?: string; + unpackDir?: string; + } + + interface ElectronDownloadOptions { + cache?: string; + mirror?: string; + quiet?: boolean; + strictSSL?: boolean; + } + + interface ElectronOsXSignOptions { + identity?: string; + entitlements?: string; + "entitlements-inherit"?: string; + } + + /** + * Object (also known as a "hash") of application metadata to embed into the executable + */ + interface Win32Metadata { + CompanyName?: string; + FileDescription?: string; + OriginalFilename?: string; + ProductName?: string; + InternalName?: string; + "requested-execution-level": any; + "application-manifest": any; + } + /** Electron-packager Options. */ - export interface Options { + interface Options { /** The source directory. */ dir: string; - /** The application name. */ - name: string; /** - * Allowed values: linux, win32, darwin, all. Not required if `all` is used. - * Arbitrary combinations of individual platforms are also supported via a comma-delimited string or array of strings. + * Optional list of methods to call on completion of each process */ - platform?: string | string[]; - /** Allowed values: ia32, x64, all Not required if `all` is used. */ - arch?: string; - /** Electron version (without the "v"). See https://github.com/atom/electron/releases. */ - version: string; - + afterCopy?: onCompleteFn[]; + afterExtract?: onCompleteFn[]; + afterPrune?: onCompleteFn[]; /** Shortcut for `--arch=all --platform=all`. */ all?: boolean; + /** + * The human-readable copyright line for the app. Maps to the LegalCopyright metadata property on Windows, and NSHumanReadableCopyright on OS X. + */ + appCopyright?: string; + /** + * The release version of the application. By default the version property in the package.json is used but it can be overridden with this argument. + * If neither are provided, the version of Electron will be used. Maps to the ProductVersion metadata property on Windows, and CFBundleShortVersionString on OS X. + */ + appVersion?: string; + /** + * The target system architecture(s) to build for. Not required if the all option is set. + * If arch is set to all, all supported architectures for the target platforms specified by platform will be built. + * Arbitrary combinations of individual architectures are also supported via a comma-delimited string or array of strings. + * The non-all values correspond to the architecture names used by Electron releases. This value is not restricted to the official set if download.mirror is set. + */ + arch?: arch; + /** + * Whether to package the application's source code into an archive, using Electron's archive format + */ + asar?: boolean | AsarOptions; + /** + * The build version of the application. Defaults to the value of appVersion. + * Maps to the FileVersion metadata property on Windows, and CFBundleVersion on OS X. + */ + buildVersion?: string; + /** + * Whether symlinks should be dereferenced during the copying of the application source. + */ + derefSymlinks?: boolean; + /** + * If present, passes custom options to electron-download + */ + download?: ElectronDownloadOptions; + /** + * The Electron version with which the app is built (without the leading 'v') - for example, 1.4.13 + */ + electronVersion?: string; + /** + * One or more files to be copied directly into the app's Contents/Resources directory for OS X target platforms, and the resources directory for other target platforms. + */ + extraResource?: string | string[]; + /** + * The local path to the icon file, if the target platform supports setting embedding an icon. + */ + icon?: string; + /** + * One or more additional regular expression patterns which specify which files to ignore when copying files to create the app bundle(s). + * The regular expressions are matched against the absolute path of a given file/directory to be copied. + */ + ignore?: RegExp | RegExp[] | ignoreFunction; + /** + * The application name. If omitted, it will use the productName or name value from the nearest package.json + */ + name?: string; /** The output directory. */ out?: string; /** - * Currently you must look for conversion tools in order to supply an icon in the format required by the platform: - * - OS X: `.icns` - * - Windows: `.ico` - * - * For Linux builds, this option is not required, as the dock/window list icon is set via the icon option in the BrowserWindow contructor. - * Setting the icon in the file manager is not currently supported. - * - * If the file extension is omitted, it is auto-completed to the correct extension based on the platform, - * including when `--platform=all` is in effect. + * Whether to replace an already existing output directory for a given platform (true) or skip recreating it (false). */ - icon?: string; - - /** The bundle identifier to use in the app plist. */ - "app-bundle-id"?: string; - /** The release version to set for the app. */ - "app-version"?: string; - /** The build version to set for the app (OS X only). */ - "build-version"?: string; - /** The bundle identifier to use in the app helper plist. */ - "helper-bundle-id"?: string; - /** Object hash of application metadata to embed into the executable (Windows only). */ - "version-string"?: VersionString; - - /** The directory of cached electron downloads. Defaults to "$HOME/.electron". */ - cache?: string; - /** Do not copy files into App whose filenames regex .match this string. */ - ignore?: RegExp; - /** Runs `npm prune --production` on the app. */ - prune?: boolean; - /** If output directory for a platform already exists, replaces it rather than skipping it. */ overwrite?: boolean; - /** Packages the source code within your app into an archive. */ - asar?: boolean; - /** Unpacks the files to app.asar.unpacked directory whose filenames regex .match this string. */ - "asar-unpack"?: string; - /** Should contain the identity to be used when running `codesign` (OS X only). */ - sign?: string; - } - - /** Object hash of application metadata to embed into the executable (Windows only). */ - export interface VersionString { - CompanyName?: string; - LegalCopyright?: string; - FileDescription?: string; - OriginalFilename?: string; - FileVersion?: string; - ProductVersion?: string; - ProductName?: string; - InternalName?: string; - } - - /** Electron-packager done callback. */ - export interface Callback { /** - * Callback which is called when electron-packager is done. - * - * @param err - Contains errors if any. - * @param appPath - Path(s) to the newly created application(s). + * The package manager used to prune devDependencies modules from the outputted Electron app */ - (err: Error, appPath: string|string[]): void - } - - /** Electron-packager function */ - export interface Packager { + packageManager?: packageManager; /** - * This will: - * - Find or download the correct release of Electron - * - Use that version of electron to create a app in /-- - * - * You should be able to launch the app on the platform you built for. If not, check your settings and try again. - * - * @param opts - Options to configure packaging. - * @param callback - Callback which is called when packaging is done or an error occured. + * The target platform(s) to build for. Not required if the all option is set. */ - (opts: Options, callback: Callback): void; + platform?: platform; + /** + * Runs the package manager command to remove all of the packages specified in the devDependencies section of package.json from the outputted Electron app. + */ + prune?: boolean; + /** + * If true, disables printing informational and warning messages to the console when packaging the application. This does not disable errors. + */ + quiet?: boolean; + /** + * The base directory to use as a temp directory. Set to false to disable use of a temporary directory. + */ + tmpdir?: string | false; + + /** + * OS X/Mac App Store targets only + */ + + /** + * The bundle identifier to use in the application's plist. + */ + appBundleId?: string; + /** + * The application category type, as shown in the Finder via View → Arrange by Application Category when viewing the Applications directory. + */ + appCategoryType?: string; + /** + * When the value is a String, the filename of a plist file. Its contents are added to the app's plist. + * When the value is an Object, an already-parsed plist data structure that is merged into the app's plist. + */ + extendInfo?: string | {[property: string]: any}; + /** + * The bundle identifier to use in the application helper's plist. + */ + helperBundleId?: string; + /** + * If present, signs OS X target apps when the host platform is OS X and XCode is installed. + */ + osxSign?: boolean | ElectronOsXSignOptions; + /** + * The URL protocol scheme(s) to associate the app with + */ + protocol?: string; + /** + * The descriptive name(s) of the URL protocol scheme(s) specified via the protocol option. + * Maps to the CFBundleURLName metadata property. + */ + protocolName?: string[]; + + /** + * Windows targets only + */ + + win32metadata?: Win32Metadata; } } - -declare module "electron-packager" { - const packager: ElectronPackager.Packager; - export = packager; -} - -interface NodeRequireFunction { - (id: "electron-packager"): ElectronPackager.Packager; -} diff --git a/types/electron-packager/tslint.json b/types/electron-packager/tslint.json new file mode 100644 index 0000000000..5d0b359e47 --- /dev/null +++ b/types/electron-packager/tslint.json @@ -0,0 +1,5 @@ +{ "extends": "dtslint/dt.json", + "rules": { + "no-conditional-assignment": false + } +} diff --git a/types/email-templates/index.d.ts b/types/email-templates/index.d.ts index a836fdfadc..5fdd7054f3 100644 --- a/types/email-templates/index.d.ts +++ b/types/email-templates/index.d.ts @@ -64,6 +64,6 @@ declare module "email-templates" { * @param {EmailTemplateCallback|Object} locals The variables or callback function. * @param {EmailTemplateCallback} callback The callback function. */ - render(locals: EmailTemplateCallback|Object, callback?: EmailTemplateCallback): void; + render(locals: EmailTemplateCallback|Object, callback?: EmailTemplateCallback): void | Promise; } } diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index 07a8a0d54f..41f8fe6d45 100644 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -2449,6 +2449,7 @@ declare namespace Ember { function observersFor(obj: any, path: string): any[]; function onLoad(name: string, callback: Function): void; const onError: Error; + function onerror(error: any): void; function overrideChains(obj: any, keyName: string, m: any): boolean; // ReSharper disable once DuplicatingLocalDeclaration const platform: { @@ -2480,6 +2481,7 @@ declare namespace Ember { throttle(target: any, method: Function | string, ...args: any[]): void; queues: any[]; }; + function runInDebug(fn: Function): void; function runLoadHooks(name: string, object: any): void; function sendEvent(obj: any, eventName: string, params?: any[], actions?: any[]): boolean; function set(obj: any, keyName: string, value: any): any; diff --git a/types/eventemitter2/eventemitter2-tests.ts b/types/eventemitter2/eventemitter2-tests.ts deleted file mode 100644 index 8a7849abfa..0000000000 --- a/types/eventemitter2/eventemitter2-tests.ts +++ /dev/null @@ -1,101 +0,0 @@ -// Example for CommonJS/AMD -/* -import eventemitter2 = require("eventemitter2"); -var EventEmitter2 = eventemitter2.EventEmitter2; - -class Child extends eventemitter2.EventEmitter2 { -} -*/ - -// This class definition doesn't work in CommonJS/AMD. -class Child extends EventEmitter2 { -} - -var server = new EventEmitter2(); - -function testConfiguration() { - var foo = new EventEmitter2({ - wildcard: true, - delimiter: '::', - newListener: false, - maxListeners: 20, - verboseMemoryLeak: true - }); - var bar = new EventEmitter2({}); - var bazz = new EventEmitter2(); -} - -function testAddListener() { - server.addListener('data', function (value1: any, value2: any, value3: any) { - console.log('The event was raised!'); - }); - - server.addListener('data', function (value: any) { - console.log('The event was raised!'); - }); -} - -function testOn() { - server.on('data', function (value1: any, value2: any, value3: any) { - console.log('The event was raised!'); - }); - - server.on('data', function (value: any) { - console.log('The event was raised!'); - }); -} - -function testOnAny() { - server.onAny(function (value: any) { - console.log('All events trigger this.'); - }); -} - -function testOffAny() { - server.offAny(function (value: any) { - console.log('The event was raised!'); - }); -} - -function testOnce() { - server.once('get', function (value: any) { - console.log('Ah, we have our first value!'); - }); -} - -function testMany() { - server.many('get', 4, function (value: any) { - console.log('This event will be listened to exactly four times.'); - }); -} - -function testRemoveListener() { - var callback = function (value: any) { - console.log('someone connected!'); - }; - server.on('get', callback); - server.removeListener('get', callback); -} - -function testRemoveAllListeners() { - server.removeAllListeners(["test::event", "another::test::event"]); - server.removeAllListeners("test"); - server.removeAllListeners(); -} - -function testSetMaxListeners() { - server.setMaxListeners(40); -} - -function testListeners() { - console.log(server.listeners('get')); -} - -function testListenersAny() { - console.log(server.listenersAny()[0]); -} - -function testEmit() { - server.emit('foo.bazz'); - server.emit(['foo', 'bar']); -} diff --git a/types/eventemitter2/index.d.ts b/types/eventemitter2/index.d.ts deleted file mode 100644 index 33ffe20b09..0000000000 --- a/types/eventemitter2/index.d.ts +++ /dev/null @@ -1,258 +0,0 @@ -// Type definitions for EventEmitter2 v2.2.0 -// Project: https://github.com/asyncly/EventEmitter2 -// Definitions by: ryiwamoto -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -interface EventEmitter2Configuration { - /** - * use wildcards - */ - wildcard?: boolean; - - /** - * the delimiter used to segment namespaces, defaults to `.`. - */ - delimiter?: string; - - /** - * if you want to emit the newListener event set to true. - */ - newListener?: boolean; - - /** - * max listeners that can be assigned to an event, default 10. - */ - maxListeners?: number; - - /** - * show event name in memory leak message when more than maximum amount of listeners is assigned, default false - */ - verboseMemoryLeak?: boolean; -} - -declare class EventEmitter2 { - /** - * @param conf - */ - constructor(conf?: EventEmitter2Configuration); - - /** - * Adds a listener to the end of the listeners array for the specified event. - * @param event - * @param listener - */ - addListener(event: string, listener: Function): EventEmitter2; - - /** - * Adds a listener to the end of the listeners array for the specified event. - * @param event - * @param listener - */ - on(event: string | string[], listener: Function): EventEmitter2; - - /** - * Adds a listener that will be fired when any event is emitted. - * @param listener - */ - onAny(listener: Function): EventEmitter2; - - /** - * Removes the listener that will be fired when any event is emitted. - * @param listener - */ - offAny(listener?: Function): EventEmitter2; - - /** - * Adds a one time listener for the event. - * The listener is invoked only the first time the event is fired, after which it is removed. - * @param event - * @param listener - */ - once(event: string, listener: Function): EventEmitter2; - - /** - * Adds a listener that will execute n times for the event before being removed. - * The listener is invoked only the first n times the event is fired, after which it is removed. - * @param event - * @param timesToListen - * @param listener - */ - many(event: string, timesToListen: number, listener: Function): EventEmitter2; - - /** - * Remove a listener from the listener array for the specified event. - * Caution: changes array indices in the listener array behind the listener. - * @param event - * @param listener - */ - removeListener(event: string, listener: Function): EventEmitter2; - - /** - * Remove a listener from the listener array for the specified event. - * Caution: changes array indices in the listener array behind the listener. - * @param event - * @param listener - */ - off(event: string, listener: Function): EventEmitter2; - - /** - * Removes all listeners, or those of the specified event. - * @param event - */ - removeAllListeners(event?: string): EventEmitter2; - - /** - * Removes all listeners, or those of the specified event. - * @param events - */ - removeAllListeners(events: string[]): EventEmitter2; - - /** - * By default EventEmitters will print a warning if more than 10 listeners are added to it. - * This is a useful default which helps finding memory leaks. - * Obviously not all Emitters should be limited to 10. This function allows that to be increased. - * Set to zero for unlimited. - * @param n - */ - setMaxListeners(n: number): void; - - /** - * Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners. - * @param event - */ - listeners(event: string): Function[]; - - /** - * Returns an array of listeners that are listening for any event that is specified. - * This array can be manipulated, e.g. to remove listeners. - */ - listenersAny(): Function[]; - - /** - * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. - * @param event - * @param args - */ - emit(event: string | string[], ...args: any[]): boolean; - - /** - * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. - * @param event - */ - emit(event: string[]): boolean; -} - -declare module "eventemitter2" { - export class EventEmitter2 { - /** - * @param conf - */ - constructor(conf?: EventEmitter2Configuration); - - /** - * Adds a listener to the end of the listeners array for the specified event. - * @param event - * @param listener - */ - addListener(event: string, listener: Function): EventEmitter2; - - /** - * Adds a listener to the end of the listeners array for the specified event. - * @param event - * @param listener - */ - on(event: string | string[], listener: Function): EventEmitter2; - - /** - * Adds a listener that will be fired when any event is emitted. - * @param listener - */ - onAny(listener: Function): EventEmitter2; - - /** - * Removes the listener that will be fired when any event is emitted. - * @param listener - */ - offAny(listener: Function): EventEmitter2; - - /** - * Adds a one time listener for the event. - * The listener is invoked only the first time the event is fired, after which it is removed. - * @param event - * @param listener - */ - once(event: string, listener: Function): EventEmitter2; - - /** - * Adds a listener that will execute n times for the event before being removed. - * The listener is invoked only the first n times the event is fired, after which it is removed. - * @param event - * @param timesToListen - * @param listener - */ - many(event: string, timesToListen: number, listener: Function): EventEmitter2; - - /** - * Remove a listener from the listener array for the specified event. - * Caution: changes array indices in the listener array behind the listener. - * @param event - * @param listener - */ - removeListener(event: string, listener: Function): EventEmitter2; - - /** - * Remove a listener from the listener array for the specified event. - * Caution: changes array indices in the listener array behind the listener. - * @param event - * @param listener - */ - off(event: string, listener: Function): EventEmitter2; - - /** - * Removes all listeners, or those of the specified event. - * @param event - */ - removeAllListeners(event?: string): EventEmitter2; - - /** - * Removes all listeners, or those of the specified event. - * @param events - */ - removeAllListeners(events: string[]): EventEmitter2; - - /** - * By default EventEmitters will print a warning if more than 10 listeners are added to it. - * This is a useful default which helps finding memory leaks. - * Obviously not all Emitters should be limited to 10. This function allows that to be increased. - * Set to zero for unlimited. - * @param n - */ - setMaxListeners(n: number): void; - - /** - * Returns an array of listeners for the specified event. This array can be manipulated, e.g. to remove listeners. - * @param event - */ - listeners(event: string): Function[]; - - /** - * Returns an array of listeners that are listening for any event that is specified. - * This array can be manipulated, e.g. to remove listeners. - */ - listenersAny(): Function[]; - - /** - * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. - * @param event - * @param args - */ - emit(event: string | string[], ...args: any[]): boolean; - - /** - * Execute each of the listeners that may be listening for the specified event name in order with the list of arguments. - * @param event - */ - emit(event: string[]): boolean; - } -} - diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index bd8647aa77..5e4491c9a1 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -239,9 +239,9 @@ interface Request extends http.IncomingMessage, Express.Request { * // => "json" */ accepts(): string[]; - accepts(type: string): string | boolean; - accepts(type: string[]): string | boolean; - accepts(...type: string[]): string | boolean; + accepts(type: string): string | false; + accepts(type: string[]): string | false; + accepts(...type: string[]): string | false; /** * Returns the first accepted charset of the specified character sets, @@ -252,9 +252,9 @@ interface Request extends http.IncomingMessage, Express.Request { * @param charset */ acceptsCharsets(): string[]; - acceptsCharsets(charset: string): string | boolean; - acceptsCharsets(charset: string[]): string | boolean; - acceptsCharsets(...charset: string[]): string | boolean; + acceptsCharsets(charset: string): string | false; + acceptsCharsets(charset: string[]): string | false; + acceptsCharsets(...charset: string[]): string | false; /** * Returns the first accepted encoding of the specified encodings, @@ -265,9 +265,9 @@ interface Request extends http.IncomingMessage, Express.Request { * @param encoding */ acceptsEncodings(): string[]; - acceptsEncodings(encoding: string): string | boolean; - acceptsEncodings(encoding: string[]): string | boolean; - acceptsEncodings(...encoding: string[]): string | boolean; + acceptsEncodings(encoding: string): string | false; + acceptsEncodings(encoding: string[]): string | false; + acceptsEncodings(...encoding: string[]): string | false; /** * Returns the first accepted language of the specified languages, @@ -279,9 +279,9 @@ interface Request extends http.IncomingMessage, Express.Request { * @param lang */ acceptsLanguages(): string[]; - acceptsLanguages(lang: string): string | boolean; - acceptsLanguages(lang: string[]): string | boolean; - acceptsLanguages(...lang: string[]): string | boolean; + acceptsLanguages(lang: string): string | false; + acceptsLanguages(lang: string[]): string | false; + acceptsLanguages(...lang: string[]): string | false; /** * Parse Range header field, diff --git a/types/express/express-tests.ts b/types/express/express-tests.ts index 3270a3f391..2891a37d96 100644 --- a/types/express/express-tests.ts +++ b/types/express/express-tests.ts @@ -51,22 +51,22 @@ namespace express_tests { router.route('/users') .get((req, res, next) => { let types: string[] = req.accepts(); - let type: string | boolean = req.accepts('json'); + let type: string | false = req.accepts('json'); type = req.accepts(['json', 'text']); type = req.accepts('json', 'text'); let charsets: string[] = req.acceptsCharsets(); - let charset: string | boolean = req.acceptsCharsets('utf-8'); + let charset: string | false = req.acceptsCharsets('utf-8'); charset = req.acceptsCharsets(['utf-8', 'utf-16']); charset = req.acceptsCharsets('utf-8', 'utf-16'); let encodings: string[] = req.acceptsEncodings(); - let encoding: string | boolean = req.acceptsEncodings('gzip'); + let encoding: string | false = req.acceptsEncodings('gzip'); encoding = req.acceptsEncodings(['gzip', 'deflate']); encoding = req.acceptsEncodings('gzip', 'deflate'); let languages: string[] = req.acceptsLanguages(); - let language: string | boolean = req.acceptsLanguages('en'); + let language: string | false = req.acceptsLanguages('en'); language = req.acceptsLanguages(['en', 'ja']); language = req.acceptsLanguages('en', 'ja'); diff --git a/types/flatpickr/index.d.ts b/types/flatpickr/index.d.ts index 535ec0145e..fce4214c90 100644 --- a/types/flatpickr/index.d.ts +++ b/types/flatpickr/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/chmln/flatpickr // Definitions by: James Birtles // Rowell Heria +// Michael Wagner // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function flatpickr(element: string | Element | HTMLElement, options?: Flatpickr.Options): Flatpickr; @@ -21,6 +22,11 @@ declare class Flatpickr { set(option: string, value: any): void; setDate(date: Flatpickr.DateString | Flatpickr.DateString[], triggerChange?: boolean, dateFormat?: string): void; toggle(): void; + + static localize(locale: string | Flatpickr.Locale): void; + static l10ns: { + default: Flatpickr.Locale; + }; } declare namespace Flatpickr { @@ -63,6 +69,30 @@ declare namespace Flatpickr { utc?: boolean; weekNumbers?: boolean; wrap?: boolean; + locale?: string | Locale; + } + + interface Locale { + weekdays?: { + shorthand?: string[]; + longhand?: string[]; + }; + + months?: { + shorthand?: string[]; + longhand?: string[]; + }; + + firstDayOfWeek?: number; + weekAbbreviation?: string; + rangeSeparator?: string; + am?: string; + pm?: string; + + ordinal?: ((nth: number) => string) | string; + + scrollTitle?: string; + toggleTitle?: string; } type DateString = Date | string; diff --git a/types/flux-standard-action/flux-standard-action-tests.ts b/types/flux-standard-action/flux-standard-action-tests.ts index 5934e56fb8..1a98c6663c 100644 --- a/types/flux-standard-action/flux-standard-action-tests.ts +++ b/types/flux-standard-action/flux-standard-action-tests.ts @@ -23,3 +23,17 @@ var result1: boolean = isError(sample1); var result2: boolean = isFSA(sample1); var result3: boolean = isError(sample2); var result4: boolean = isFSA(sample2); + +declare function alert (message: string): void + +function unwrapAction(action: { type: string }) { + if (isFSA(action)) { + if (isError(action)) { + alert(action.payload!.message) + } + return action.payload + } +} + +var result5: TextPayload = unwrapAction(sample1) +var result6: Error = unwrapAction(sample2) diff --git a/types/flux-standard-action/index.d.ts b/types/flux-standard-action/index.d.ts index d5393e0ace..388132bea6 100644 --- a/types/flux-standard-action/index.d.ts +++ b/types/flux-standard-action/index.d.ts @@ -5,7 +5,7 @@ export interface ErrorAction extends Action { - error: boolean; + error: true; } export interface Action { @@ -14,16 +14,16 @@ export interface Action { error?: boolean; } -// Usage: var action: Action & AnyMeta; +/** Usage: `var action: Action & AnyMeta;` */ export interface AnyMeta { meta: any } -// Usage: var action: Action & TypedMeta; +/** Usage: `var action: Action & TypedMeta;` */ export interface TypedMeta { meta: T } -export declare function isFSA(action: any): boolean; +export declare function isFSA(action: any): action is Action; -export declare function isError(action: any): boolean; +export declare function isError(action: any): action is ErrorAction; diff --git a/types/gapi.auth2/index.d.ts b/types/gapi.auth2/index.d.ts index 04dfe32c2d..6e9e5c4199 100644 --- a/types/gapi.auth2/index.d.ts +++ b/types/gapi.auth2/index.d.ts @@ -47,7 +47,7 @@ declare namespace gapi.auth2 { /** * Get permission from the user to access the specified scopes offline. */ - grantOfflineAccess(options: { + grantOfflineAccess(options?: { scope?: string; prompt?: "select_account" | "consent"; app_package_name?: string; diff --git a/types/hls.js/hls.js-tests.ts b/types/hls.js/hls.js-tests.ts index a8f7291044..9af972ebcc 100644 --- a/types/hls.js/hls.js-tests.ts +++ b/types/hls.js/hls.js-tests.ts @@ -1,8 +1,29 @@ import * as Hls from 'hls.js'; +function process(playlist: string) { + return playlist; +} + +class pLoader extends Hls.DefaultConfig.loader { + constructor(config: Hls.LoaderConfig) { + super(config); + const load = this.load.bind(this); + this.load = (context: Hls.LoaderContext, cfg: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks) => { + if (context.type === 'manifest') { + const onSuccess = callbacks.onSuccess; + callbacks.onSuccess = (response: Hls.LoaderResponse, stats: Hls.LoaderStats, context: Hls.LoaderContext) => { + response.data = process(response.data as string); + onSuccess(response, stats, context); + }; + } + load(context, config, callbacks); + }; + } +} + if (Hls.isSupported()) { const video = document.getElementById('video'); - const hls = new Hls(); + const hls = new Hls({ pLoader }); const version: string = Hls.version; hls.loadSource('http://www.streambox.fr/playlists/test_001/stream.m3u8'); hls.attachMedia(video); diff --git a/types/hls.js/index.d.ts b/types/hls.js/index.d.ts index 1911413c4f..66ad839da1 100644 --- a/types/hls.js/index.d.ts +++ b/types/hls.js/index.d.ts @@ -4,6 +4,22 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 +declare class Loader { + constructor(config: Hls.LoaderConfig) + /** + * Start retrieving content located at given URL (HTTP GET). + */ + load(context: Hls.LoaderContext, config: Hls.LoaderConfig, callbacks: Hls.LoaderCallbacks): void; + /** + * Abort any loading in progress. + */ + abort(): void; + /** + * Destroy loading context. + */ + destroy(): void; +} + declare namespace Hls { /** * Hls events @@ -385,6 +401,410 @@ declare namespace Hls { const version: string; interface Config { + /** + * (default: true) + * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event + * if set to false, an explicit API call (hls.startLoad(startPosition=-1)) will be needed to start quality level/fragment loading. + */ + autoStartLoad: boolean; + /** + * (default -1) + * if set to -1, playback will start from initialTime=0 for VoD and according to liveSyncDuration/liveSyncDurationCount config params for Live + * otherwise, playback will start from predefined value. (unless stated otherwise in autoStartLoad=false mode : in that case startPosition can be overrided using hls.startLoad(startPosition)). + */ + startPosition: number; + /** + * (default: false) + * if set to true, the adaptive algorithm with limit levels usable in auto-quality by the HTML video element dimensions (width and height) + * if set to false, levels will not be limited. All available levels could be used in auto-quality mode taking only bandwidth into consideration. + */ + capLevelToPlayerSize: boolean; + /** + * (default: false) + * setting config.debug = true; will turn on debug logs on JS console. + * a logger object could also be provided for custom logging: config.debug = customLogger; + */ + debug: boolean; + /** + * (default: undefined) + * if audio codec is not signaled in variant manifest, or if only a stream manifest is provided, hls.js tries to guess audio codec by parsing audio sampling rate in ADTS header. + * If sampling rate is less or equal than 22050 Hz, then hls.js assumes it is HE-AAC, otherwise it assumes it is AAC-LC. + * This could result in bad guess, leading to audio decode error, ending up in media error. + * It is possible to hint default audiocodec to hls.js by configuring this value as below: + * mp4a.40.2 (AAC-LC) or + * mp4a.40.5 (HE-AAC) or + * undefined (guess based on sampling rate) + */ + defaultAudioCodec: string; + /** + * (default: 1) + * number of segments needed to start a playback of Live stream. + */ + initialLiveManifestSize: number; + /** + * (default: 30 seconds) + * Maximum buffer length in seconds. If buffer length is/become less than this value, a new fragment will be loaded. + * This is the guaranteed buffer length hls.js will try to reach, regardless of maxBufferSize. + */ + maxBufferLength: number; + /** + * (default 600s) + * Maximum buffer length in seconds. Hls.js will never exceed this value, even if maxBufferSize is not reached yet. + * hls.js tries to buffer up to a maximum number of bytes (60 MB by default) rather than to buffer up to a maximum nb of seconds. + * This is to mimic the browser behaviour (the buffer eviction algorithm is starting after the browser detects that video buffer size reaches a limit in bytes) + * maxBufferLength is the minimum guaranteed buffer length that hls.js will try to achieve, even if that value exceeds the amount of bytes 60 MB of memory. + * maxMaxBufferLength acts as a capping value, as if bitrate is really low, you could need more than one hour of buffer to fill 60 MB. + */ + maxMaxBufferLength: number; + /** + * (default: 60 MB) + * 'Minimum' maximum buffer size in bytes. If buffer size upfront is bigger than this value, no fragment will be loaded + */ + maxBufferSize: number; + /** + * (default: 0.5 seconds) + * 'Maximum' inter-fragment buffer hole tolerance that hls.js can cope with when searching for the next fragment to load. When switching between quality level, + * fragments might not be perfectly aligned. + * This could result in small overlapping or hole in media buffer. This tolerance factor helps cope with this. + */ + maxBufferHole: number; + /** + * (default: 4s) + * + * ABR algorithm will always try to choose a quality level that should avoid rebuffering. In case no quality level with this criteria can + * be found (lets say for example that buffer length is 1s, but fetching a fragment at lowest quality is predicted to take around 2s ... + * ie we can forecast around 1s of rebuffering ...) then ABR algorithm will try to find a level that should guarantee less than + * maxStarvationDelay of buffering. + */ + maxStarvationDelay: number; + /** + * (default: 2s) + * In case playback is stalled, and a buffered range is available upfront, less than maxSeekHole seconds from current media position, + * hls.js will jump over this buffer hole to reach the beginning of this following buffered range. + * maxSeekHole allows to configure this jumpable threshold. + */ + maxSeekHole: number; + /** + * (default: 0.5s) + * media element is expected to play and if currentTime has not moved for more than lowBufferWatchdogPeriod and if there are less than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback + */ + lowBufferWatchdogPeriod: number; + /** + * (default: 3s) + * if media element is expected to play and if currentTime has not moved for more than highBufferWatchdogPeriod and if there are more than maxBufferHole seconds buffered upfront, + * hls.js will try to nudge playhead to recover playback + */ + highBufferWatchdogPeriod: number; + /** + * (default: 0.1s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset + */ + nudgeOffset: number; + /** + * (default: 3s) + * In case playback continues to stall after first playhead nudging, currentTime will be nudged evenmore following nudgeOffset to try to restore playback. + * media.currentTime += (nb nudge retry -1)*nudgeOffset + */ + nudgeMaxRetry: number; + /** + * (default 0.2s) + * This tolerance factor is used during fragment lookup. + * Instead of checking whether buffered.end is located within [start, end] range, frag lookup will be done by checking within [start-maxFragLookUpTolerance, end-maxFragLookUpTolerance] range. + * This tolerance factor is used to cope with situations like: + * buffered.end = 9.991 + * frag[0] : [0,10] + * frag[1] : [10,20] + * buffered.end is within frag[0] range, but as we are close to frag[1], frag[1] should be choosen instead + * If maxFragLookUpTolerance = 0.2, this lookup will be adjusted to + * frag[0] : [-0.2,9.8] + * frag[1] : [9.8,19.8] + * This time, buffered.end is within frag[1] range, and frag[1] will be the next fragment to be loaded, as expected + */ + maxLoadingDelay: number; + /** + * (default 4s) + * + * max video loading delay used in automatic start level selection : in that mode ABR controller will ensure that video loading time (ie + * the time to fetch the first fragment at lowest quality level + the time to fetch the fragment at the appropriate quality level is less + * than maxLoadingDelay ) + */ + maxFragLookUpTolerance: number; + /** + * (default: 3) + * edge of live delay, expressed in multiple of EXT-X-TARGETDURATION. if set to 3, playback will start from fragment N-3, N being the last fragment of the live playlist. + * Decreasing this value is likely to cause playback stalls. + */ + liveSyncDurationCount: number; + /** + * (default: undefined) + * Alternative parameter to liveSyncDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveSyncDuration will take precedence over the default liveSyncDurationCount. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too low (inferior to ~3 segment durations) is likely to cause playback stalls. + */ + liveSyncDuration: number; + /** + * (default: Infinity) + * maximum delay allowed from edge of live, expressed in multiple of EXT-X-TARGETDURATION. + * If set to 10, the player will seek back to liveSyncDurationCount whenever the next fragment to be loaded is older than N-10, N being the last fragment of the live playlist. + * If set, this value must be stricly superior to liveSyncDurationCount a value too close from liveSyncDurationCount is likely to cause playback stalls. + */ + liveMaxLatencyDurationCount: number; + /** + * (default: undefined) + * Alternative parameter to liveMaxLatencyDurationCount, expressed in seconds vs number of segments. + * If defined in the configuration object, liveMaxLatencyDuration will take precedence over the default liveMaxLatencyDurationCount. + * If set, this value must be stricly superior to liveSyncDuration which must be defined as well. + * You can't define this parameter and either liveSyncDurationCount or liveMaxLatencyDurationCount in your configuration object at the same time. + * A value too close from liveSyncDuration is likely to cause playback stalls. + */ + liveMaxLatencyDuration: number; + /** + * (default: true) + * Enable WebWorker (if available on browser) for TS demuxing/MP4 remuxing, to improve performance and avoid lag/frame drops. + */ + enableWorker: boolean; + /** + * (default: true) + * Enable to use JavaScript version AES decryption for fallback of WebCrypto API. + */ + enableSoftwareAES: boolean; + /** + * (default: undefined) + * When set, use this level as the default hls.startLevel. Keep in mind that the startLevel set with the API takes precedence over + * config.startLevel configuration parameter. + */ + startLevel: number; + /** + * (default: 10000ms for level and manifest) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + manifestLoadingTimeOut: number; + /** + * (default: 3) + * Max number of load retries. + */ + manifestLoadingMaxRetry: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + manifestLoadingRetryDelay: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + manifestLoadingMaxRetryTimeout: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + levelLoadingTimeOut: number; + /** + * (default: 3) + * Max number of load retries. + */ + levelLoadingMaxRetry: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + levelLoadingRetryDelay: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + levelLoadingMaxRetryTimeout: number; + /** + * (default: 60000ms for fragment) + * URL Loader timeout. A timeout callback will be triggered if loading duration exceeds this timeout. no further action will be done : the load operation will not be cancelled/aborted. + * It is up to the application to catch this event and treat it as needed. + */ + fragLoadingTimeOut: number; + /** + * (default: 3) + * Max number of load retries. + */ + fragLoadingMaxRetry: number; + /** + * (default: 1000 ms) + * Initial delay between XMLHttpRequest error and first load retry (in ms). + * Any I/O error will trigger retries every 500ms,1s,2s,4s,8s, ... capped to fragLoadingMaxRetryTimeout / manifestLoadingMaxRetryTimeout / levelLoadingMaxRetryTimeout value (exponential backoff). + * Prefetch start fragment although media not attached. + */ + fragLoadingRetryDelay: number; + /** + * (default: 64000 ms) + * Maximum frag/manifest/key retry timeout (in milliseconds) in case I/O errors are met. + */ + fragLoadingMaxRetryDelay: number; + /** + * (default: false) + * Start prefetching start fragment although media not attached yet. Max number of append retries. + */ + startFragPrefech: boolean; + /** + * (default: 3) + * Max number of sourceBuffer.appendBuffer() retry upon error. Such error could happen in loop with UHD streams, when internal buffer is full. (Quota Exceeding Error will be triggered). + * In that case we need to wait for the browser to evict some data before being able to append buffer correctly. + */ + appendErrorMaxRetry: number; + /** + * (default: standard XMLHttpRequest-based URL loader) + * Override standard URL loader by a custom one. Could be useful for P2P or stubbing (testing). + * Use this, if you want to overwrite both the fragment and the playlist loader. + * Note: If fLoader or pLoader are used, they overwrite loader! + */ + loader: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the fragment loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + fLoader?: typeof Loader; + /** + * (default: undefined) + * This enables the manipulation of the playlist loader. + * Note: This will overwrite the default loader, as well as your own loader function. + */ + pLoader?: typeof Loader; + /** + * (default: undefined) + * XMLHttpRequest customization callback for default XHR based loader. + * Parameter should be a function with two arguments (xhr: XMLHttpRequest, url: string). + * If xhrSetup is specified, default loader will invoke it before calling xhr.send(). This allows user to easily modify/setup XHR. + */ + xhrSetup?(xhr: XMLHttpRequest, url: string): void; + /** + * (default: undefined) + * Fetch customization callback for Fetch based loader. + * Parameter should be a function with two arguments (context and Request Init Params). + * If fetchSetup is specified and Fetch loader is used, fetchSetup will be triggered to instantiate Request Object. This allows user to easily tweak Fetch loader. + */ + fetchSetup?(context: any, initParams: any): Request; + /** + * (default: internal ABR controller) + * Customized Adaptive Bitrate Streaming Controller. + * Parameter should be a class providing 2 getters, 2 setters and a destroy() method: + * get/set nextAutoLevel: return next auto-quality level/force next auto-quality level that should be returned (currently used for emergency switch down) + * get/set autoLevelCapping: capping/max level value that could be used by ABR Controller + * destroy(): should clean-up all used resources + */ + abrController: AbrController; + /** + * (default: internal track timeline controller) + * Customized text track syncronization controller. + * Parameter should be a class with a destroy() method: + * destroy() : should clean-up all used resources + */ + timelineController: TimelineController; + /** + * (default: true) + * whether or not to enable CEA-708 captions + */ + enableCEA708Captions: boolean; + /** + * (default: English) + * Label for the text track generated for CEA-708 captions track 1. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack1Label: string; + /** + * (default: en) + * RFC 3066 language code for the text track generated for CEA-708 captions track 1. + */ + captionsTextTrack1LanguagedCode: string; + /** + * (default: Spanish) + * Label for the text track generated for CEA-708 captions track 2. This is how it will appear in the browser's native menu for subtitles and captions. + */ + captionsTextTrack2Label: string; + /** + * (default: es) + * RFC 3066 language code for the text track generated for CEA-708 captions track 2. + */ + captionsTextTrack2LanguageCode: string; + /** + * (default: false) + * If a segment's video track is shorter than its audio track by > min(maxSeekHole, maxBufferHole), extend the final video frame's duration to match the audio track's duration. + * This helps playback continue in certain cases that might otherwise get stuck. + */ + stretchShortVideoTrack: boolean; + /** + * (default: true) + * Whether or not to force having a key frame in the first AVC sample after a discontinuity. + * If set to true, after a discontinuity, the AVC samples without any key frame will be dropped until finding one that contains a key frame. + * If set to false, all AVC samples will be kept, which can help avoid holes in the stream. Setting this parameter to false can also generate decoding weirdness when switching level or seeking. + */ + forceKeyFrameOnDiscontinuity: boolean; + /** + * (default: 5.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaFastLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + abrEwmaFastLive: number; + /** + * (default: 9.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for Live streams. + * Half of the estimate is based on the last abrEwmaSlowLive seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastLive + */ + arbEwmaSlowLive: number; + /** + * (default: 4.0) + * Fast bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaFastVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than 0 + */ + arbEwmaFastVod: number; + /** + * (default: 15.0) + * Slow bitrate Exponential moving average half-life, used to compute average bitrate for VoD streams. + * Half of the estimate is based on the last abrEwmaSlowVoD seconds of sample history. Each of the sample is weighted by the fragment loading duration. + * parameter should be a float greater than abrEwmaFastVoD + */ + arbEwmaSlowVod: number; + /** + * (default: 500000) + * Default bandwidth estimate in bits/second prior to collecting fragment bandwidth samples. + * parameter should be a float + */ + arbEwmaDefaultEstimate: number; + /** + * (default: 0.8) + * Scale factor to be applied against measured bandwidth average, to determine whether we can stay on current or lower quality level. + * If abrBandWidthFactor * bandwidth average < level.bitrate then ABR can switch to that level providing that it is equal or less than current level. + */ + arbBandWidthFactor: number; + /** + * (default: 0.7) + * Scale factor to be applied against measured bandwidth average, to determine whether we can switch up to a higher quality level. + * If abrBandWidthUpFactor * bandwidth average < level.bitrate then ABR can switch up to that quality level. + */ + arbBandWidthUpFactor: number; + /** + * (default: false) + * max bitrate used in ABR by avg measured bitrate i.e. if bitrate signaled in variant manifest for a given level is 2Mb/s but average bitrate measured on this level is 2.5Mb/s, + * then if config value is set to true, ABR will use 2.5 Mb/s for this quality level. + */ + abrMaxWithRealBitrate: boolean; + /** + * (default: 0) + * Return the capping/min bandwidth value that could be used by automatic level selection algorithm. + * Useful when browser or tab of the browser is not in the focus and bandwidth drops + */ + minAutoBitrate: number; + } + + interface OptionalConfig { /** * (default: true) * if set to true, start level playlist and first fragments will be loaded automatically, after triggering of Hls.Events.MANIFEST_PARSED event @@ -647,19 +1067,19 @@ declare namespace Hls { * Use this, if you want to overwrite both the fragment and the playlist loader. * Note: If fLoader or pLoader are used, they overwrite loader! */ - loader?: any; + loader?: typeof Loader; /** * (default: undefined) * This enables the manipulation of the fragment loader. * Note: This will overwrite the default loader, as well as your own loader function. */ - fLoader?: any; + fLoader?: typeof Loader; /** * (default: undefined) * This enables the manipulation of the playlist loader. * Note: This will overwrite the default loader, as well as your own loader function. */ - pLoader?: any; + pLoader?: typeof Loader; /** * (default: undefined) * XMLHttpRequest customization callback for default XHR based loader. @@ -1121,18 +1541,6 @@ declare namespace Hls { length?: number; } - interface Loader { - load(context: LoaderContext, config: LoaderConfig, callbacks: LoaderCallbacks): void; - /** - * Abort any loading in progress. - */ - abort(): void; - /** - * Destroy loading context. - */ - destroy(): void; - } - interface LoaderContext { /** * target URL @@ -1200,7 +1608,7 @@ declare class Hls { /** * Constructor. Can be provided an HlsConfig object as default properties and or overrides */ - constructor(config?: Hls.Config) + constructor(config?: Hls.OptionalConfig) /** * return array of available quality levels */ diff --git a/types/i18next/i18next-tests.ts b/types/i18next/i18next-tests.ts index a96901cbb7..cdf30bb9c1 100644 --- a/types/i18next/i18next-tests.ts +++ b/types/i18next/i18next-tests.ts @@ -6,13 +6,14 @@ i18n.init({ en: { translation: { helloWorld: 'Hello, world!', - helloWorldInterpolated: 'Hello, {{name}}!' + helloWorldInterpolated: 'Hello, {{name}}!', + uppercaseFormatted: '{{text^uppercase}} just uppercased', } }, ru: { translation: { helloWorld: 'Привет, мир!', - helloWorldInterpolated: 'Привет, {{name}}!' + helloWorldInterpolated: 'Привет, {{name}}!', } } }, @@ -31,23 +32,29 @@ i18n.init({ contextSeparator: '_', saveMissing: true, saveMissingTo: 'all', - missingKeyHandler: (lng:string, ns:string, key:string, fallbackValue:string) => { + missingKeyHandler: (lng: string, ns: string, key: string, fallbackValue: string) => { console.log('Lng: ' + lng + ', ns: ' + ns + ', key' + key + ', fallbackValue: ' + fallbackValue); }, - parseMissingKeyHandler: (key:string) => { + parseMissingKeyHandler: (key: string) => { console.log(key); }, appendNamespaceToMissingKey: true, returnNull: false, returnEmptyString: false, returnObjects: false, - returnedObjectHandler: (key:string, value:string, options:any) => { + returnedObjectHandler: (key: string, value: string, options: any) => { }, joinArrays: '\n', - overloadTranslationOptionHandler: (args:any[]) => { + overloadTranslationOptionHandler: (args: any[]) => { return {} }, - interpolation: {}, + interpolation: { + format: function(value, format, lng) { + if (format === 'uppercase') return value.toUpperCase(); + return value; + }, + formatSeparator: '^', + }, detection: null, backend: null, cache: null, @@ -77,6 +84,10 @@ i18n.t('helloWorldInterpolated', { name: "world" }); +i18n.t('uppercaseFormatted', { + text: 'can you hear me', +}); + i18n.t('helloSingleFallbackLng', { fallbackLng: 'en' }); diff --git a/types/i18next/index.d.ts b/types/i18next/index.d.ts index 1cacdeb7c3..8ea39a6352 100644 --- a/types/i18next/index.d.ts +++ b/types/i18next/index.d.ts @@ -1,11 +1,10 @@ -// Type definitions for i18next v2.3.5 +// Type definitions for i18next v8.4.2 // Project: http://i18next.com // Definitions by: Michael Ledin , Budi Irawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Sources: https://github.com/i18next/i18next/ - declare namespace i18n { interface ResourceStore { [language: string]: ResourceStoreLanguage; @@ -25,7 +24,12 @@ declare namespace i18n { type FallbackLng = string | string[] | FallbackLngObjList; + type FormatFunction = (value: any, format: string, lng: string) => string; + interface InterpolationOptions { + format?: FormatFunction; + formatSeparator?: string; + escape?: (str: string) => string; escapeValue?: boolean; prefix?: string; suffix?: string; @@ -99,40 +103,28 @@ declare namespace i18n { } type TranslationFunction = (key: string, options?: TranslationOptions) => string; + type LoadCallback = (error: any, t: TranslationFunction) => void; interface I18n { - //constructor(options?: Options, callback?: (err: any, t: TranslationFunction) => void); - - init(options?: Options&ReactOptions, callback?: (err: any, t: TranslationFunction) => void): I18n; - - loadResources(callback?: (err: any) => void): void; - - language: string; - - languages: string[]; - + // api + init(options?: Options & ReactOptions, callback?: LoadCallback): I18n; use(module: any): I18n; - - changeLanguage(lng: string, callback?: (err: any, t: TranslationFunction) => void): void; - - getFixedT(lng?: string, ns?: string | string[]): TranslationFunction; - - t(key: string, options?: TranslationOptions): string | any | Array; - + t(key: string, options?: TranslationOptions): string | any | any[]; exists(key: string, options?: TranslationOptions): boolean; - + getFixedT(lng?: string, ns?: string | string[]): TranslationFunction; + changeLanguage(lng: string, callback?: LoadCallback): void; + language: string; + languages: string[]; + loadNamespaces(ns: string[], callback?: LoadCallback): void; + loadLanguages(lngs: string[], callback?: LoadCallback): void; + reloadResources(lng?: string[], ns?: string[]): void; setDefaultNamespace(ns: string): void; - - loadNamespaces(ns: string[], callback?: () => void): void; - - loadLanguages(lngs: string[], callback?: () => void): void; - dir(lng?: string): string; - - createInstance(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n; - - cloneInstance(options?: Options, callback?: (err: any, t: TranslationFunction) => void): I18n; - + format: FormatFunction; // introduced in v8.4.0; + // instance creation + createInstance(options?: Options, callback?: LoadCallback): I18n; + cloneInstance(options?: Options, callback?: LoadCallback): I18n; + // events on(event: string, listener: () => void): void; on(initialized: 'initialized', listener: (options: i18n.Options) => void): void; on(loaded: 'loaded', listener: (loaded: any) => void): void; @@ -141,8 +133,20 @@ declare namespace i18n { on(added: 'added', listener: (lng: string, ns: string) => void): void; on(removed: 'removed', listener: (lng: string, ns: string) => void): void; on(languageChanged: 'languageChanged', listener: (lng: string) => void): void; - off(event: string, listener: () => void): void; + // resource handling + getResource(lng: string, ns: string, key: string, options?: { + keySeparator?: string, + }): ResourceStore; + addResource(lng: string, ns: string, key: string, value: string, options?: { + keySeparator?: string, + silent?: boolean, + }): void; + addResources(lng: string, ns: string, resources: ResourceStore): void; + addResourceBundle(lng: string, ns: string, resources: ResourceStore, deep: boolean, overwrite: boolean): void; + hasResourceBundle(lng: string, ns: string): boolean; + getResourceBundle(lng: string, ns: string): ResourceStore; + removeResourceBundle(lng: string, ns: string): void; options: Options; } diff --git a/types/is-alphanumerical/index.d.ts b/types/is-alphanumerical/index.d.ts new file mode 100644 index 0000000000..940a005b08 --- /dev/null +++ b/types/is-alphanumerical/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for is-alphanumerical 1.0 +// Project: https://github.com/wooorm/is-alphanumerical/ +// Definitions by: Vu Tran +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function isAlphanumerical(val: string | boolean | number): boolean; +export = isAlphanumerical; diff --git a/types/is-alphanumerical/is-alphanumerical-tests.ts b/types/is-alphanumerical/is-alphanumerical-tests.ts new file mode 100644 index 0000000000..3d6602c6df --- /dev/null +++ b/types/is-alphanumerical/is-alphanumerical-tests.ts @@ -0,0 +1,7 @@ +import isAlphanumerical = require('is-alphanumerical'); + +isAlphanumerical('a'); +isAlphanumerical('z'); +isAlphanumerical('0'); +isAlphanumerical('9'); +isAlphanumerical('💩'); diff --git a/types/is-alphanumerical/tsconfig.json b/types/is-alphanumerical/tsconfig.json new file mode 100644 index 0000000000..481957289e --- /dev/null +++ b/types/is-alphanumerical/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-alphanumerical-tests.ts" + ] +} diff --git a/types/is-alphanumerical/tslint.json b/types/is-alphanumerical/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/is-alphanumerical/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index ac047d0167..b71bfbbed3 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -38,7 +38,7 @@ declare const $: JQueryStatic; // Used by JQuery.Event type _Event = Event; -interface JQuery { +interface JQuery extends Iterable { /** * A string containing the jQuery version number. * @@ -1368,7 +1368,7 @@ interface JQuery { * @see {@link https://api.jquery.com/offset/} * @since 1.2 */ - offset(): JQuery.Coordinates; + offset(): JQuery.Coordinates | undefined; /** * Get the closest ancestor element that is positioned. * @@ -1793,6 +1793,7 @@ interface JQuery { * @param handler A function to execute after the DOM is ready. * @see {@link https://api.jquery.com/ready/} * @since 1.0 + * @deprecated 3.0 */ ready(handler: ($: JQueryStatic) => void): this; /** @@ -2329,7 +2330,7 @@ interface JQuery { * @see {@link https://api.jquery.com/val/} * @since 1.0 */ - val(): string | number | string[] | null | undefined; + val(): string | number | string[] | undefined; /** * Set the CSS width of each element in the set of matched elements. * @@ -2389,12 +2390,22 @@ interface JQuery { * @since 1.4 */ wrapInner(wrappingElement: JQuery.Selector | JQuery.htmlString | Element | JQuery | ((this: TElement, index: number) => string | JQuery | Element)): this; + + [n: number]: TElement; } -interface JQuery extends ArrayLike, Iterable { } - interface JQueryStatic { - Event: JQuery.Event; + /** + * A factory function that returns a chainable utility object with methods to register multiple + * callbacks into callback queues, invoke callback queues, and relay the success or failure state of + * any synchronous or asynchronous function. + * + * @param beforeStart A function that is called just before the constructor returns. + * @see {@link https://api.jquery.com/jQuery.Deferred/} + * @since 1.5 + */ + Deferred: JQuery.DeferredStatic; + Event: JQuery.EventStatic; /** * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize * CSS property naming, or create custom properties. @@ -2499,20 +2510,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.Callbacks/} * @since 1.7 */ - Callbacks(flags?: string): JQuery.Callbacks; - /** - * A factory function that returns a chainable utility object with methods to register multiple - * callbacks into callback queues, invoke callback queues, and relay the success or failure state of - * any synchronous or asynchronous function. - * - * @param beforeStart A function that is called just before the constructor returns. - * @see {@link https://api.jquery.com/jQuery.Deferred/} - * @since 1.5 - */ - Deferred(beforeStart?: (this: JQuery.Deferred, - deferred: JQuery.Deferred) => void): JQuery.Deferred; + Callbacks(flags?: string): JQuery.Callbacks; /** * Perform an asynchronous HTTP (Ajax) request. * @@ -2908,6 +2906,7 @@ interface JQueryStatic { * @param hold Indicates whether the ready hold is being requested or released * @see {@link https://api.jquery.com/jQuery.holdReady/} * @since 1.6 + * @deprecated 3.2 */ holdReady(hold: boolean): void; /** @@ -2934,6 +2933,7 @@ interface JQueryStatic { * @param obj Object to test whether or not it is an array. * @see {@link https://api.jquery.com/jQuery.isArray/} * @since 1.3 + * @deprecated 3.2 */ isArray(obj: any): obj is any[]; /** @@ -2943,7 +2943,7 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.isEmptyObject/} * @since 1.4 */ - isEmptyObject(obj: any): boolean; + isEmptyObject(obj: any): obj is {}; /** * Determine if the argument passed is a JavaScript function object. * @@ -3265,9 +3265,52 @@ interface JQueryStatic { * @since 1.12-2.2 */ uniqueSort(array: T[]): T[]; - when(jqxhr1: JQuery.jqXHR, jqxhr2: JQuery.jqXHR, jqxhr3: JQuery.jqXHR): JQuery.Promise<[T | U | V, string, JQuery.jqXHR]>; - when(jqxhr1: JQuery.jqXHR, jqxhr2: JQuery.jqXHR): JQuery.Promise<[T | U, string, JQuery.jqXHR]>; - when(jqxhr1: JQuery.jqXHR): JQuery.Promise>; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when + (deferredT: JQuery.Promise | JQuery.Thenable | TR1, + deferredU: JQuery.Promise | JQuery.Thenable | UR1, + deferredV: JQuery.Promise | JQuery.Thenable | VR1): JQuery.Promise3; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when + (deferredT: JQuery.Promise | JQuery.Thenable | TR1, + deferredU: JQuery.Promise | JQuery.Thenable | UR1): JQuery.Promise2; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when + (deferredT: JQuery.Promise3 | + JQuery.Promise2): JQuery.Promise3; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when(deferred: JQuery.Promise | JQuery.Thenable | TR1): JQuery.Promise; /** * Provides a way to execute callback functions based on zero or more Thenable objects, usually * Deferred objects that represent asynchronous events. @@ -3276,7 +3319,16 @@ interface JQueryStatic { * @see {@link https://api.jquery.com/jQuery.when/} * @since 1.5 */ - when(...deferreds: any[]): JQuery.Promise; + when(...deferreds: Array | JQuery.Thenable | TR1>): JQuery.Promise; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually + * Deferred objects that represent asynchronous events. + * + * @param deferreds Zero or more Thenable objects. + * @see {@link https://api.jquery.com/jQuery.when/} + * @since 1.5 + */ + when(...deferreds: any[]): JQuery.Promise; } declare namespace JQuery { @@ -3482,7 +3534,7 @@ declare namespace JQuery { * XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from * within the beforeSend function. */ - headers?: PlainObject; + headers?: PlainObject; /** * Allow the request to be successful only if the response has changed since the last request. This is * done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery @@ -3578,6 +3630,7 @@ declare namespace JQuery { * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. */ username?: string; + // ActiveXObject requires "lib": ["scripthost"] which consumers would also require /** * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), * the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or @@ -3591,12 +3644,14 @@ declare namespace JQuery { * requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ * should you require the use of it. */ - xhrFields?: PlainObject; + xhrFields?: XHRFields; } - // Status codes not listed require type annotations when defining the callback type StatusCodeCallbacks = { + // region Success Status Codes + // jQuery treats 2xx and 304 status codes as a success + 200?: SuccessCallback; 201?: SuccessCallback; 202?: SuccessCallback; @@ -3699,7 +3754,10 @@ declare namespace JQuery { 299?: SuccessCallback; 304?: SuccessCallback; - // Standard 3xx, 4xx, and 5xx status codes that are considered an error + // endregion + + // region Error Status Codes + 300?: ErrorCallback; 301?: ErrorCallback; 302?: ErrorCallback; @@ -3708,6 +3766,97 @@ declare namespace JQuery { 306?: ErrorCallback; 307?: ErrorCallback; 308?: ErrorCallback; + 309?: ErrorCallback; + 310?: ErrorCallback; + 311?: ErrorCallback; + 312?: ErrorCallback; + 313?: ErrorCallback; + 314?: ErrorCallback; + 315?: ErrorCallback; + 316?: ErrorCallback; + 317?: ErrorCallback; + 318?: ErrorCallback; + 319?: ErrorCallback; + 320?: ErrorCallback; + 321?: ErrorCallback; + 322?: ErrorCallback; + 323?: ErrorCallback; + 324?: ErrorCallback; + 325?: ErrorCallback; + 326?: ErrorCallback; + 327?: ErrorCallback; + 328?: ErrorCallback; + 329?: ErrorCallback; + 330?: ErrorCallback; + 331?: ErrorCallback; + 332?: ErrorCallback; + 333?: ErrorCallback; + 334?: ErrorCallback; + 335?: ErrorCallback; + 336?: ErrorCallback; + 337?: ErrorCallback; + 338?: ErrorCallback; + 339?: ErrorCallback; + 340?: ErrorCallback; + 341?: ErrorCallback; + 342?: ErrorCallback; + 343?: ErrorCallback; + 344?: ErrorCallback; + 345?: ErrorCallback; + 346?: ErrorCallback; + 347?: ErrorCallback; + 348?: ErrorCallback; + 349?: ErrorCallback; + 350?: ErrorCallback; + 351?: ErrorCallback; + 352?: ErrorCallback; + 353?: ErrorCallback; + 354?: ErrorCallback; + 355?: ErrorCallback; + 356?: ErrorCallback; + 357?: ErrorCallback; + 358?: ErrorCallback; + 359?: ErrorCallback; + 360?: ErrorCallback; + 361?: ErrorCallback; + 362?: ErrorCallback; + 363?: ErrorCallback; + 364?: ErrorCallback; + 365?: ErrorCallback; + 366?: ErrorCallback; + 367?: ErrorCallback; + 368?: ErrorCallback; + 369?: ErrorCallback; + 370?: ErrorCallback; + 371?: ErrorCallback; + 372?: ErrorCallback; + 373?: ErrorCallback; + 374?: ErrorCallback; + 375?: ErrorCallback; + 376?: ErrorCallback; + 377?: ErrorCallback; + 378?: ErrorCallback; + 379?: ErrorCallback; + 380?: ErrorCallback; + 381?: ErrorCallback; + 382?: ErrorCallback; + 383?: ErrorCallback; + 384?: ErrorCallback; + 385?: ErrorCallback; + 386?: ErrorCallback; + 387?: ErrorCallback; + 388?: ErrorCallback; + 389?: ErrorCallback; + 390?: ErrorCallback; + 391?: ErrorCallback; + 392?: ErrorCallback; + 393?: ErrorCallback; + 394?: ErrorCallback; + 395?: ErrorCallback; + 396?: ErrorCallback; + 397?: ErrorCallback; + 398?: ErrorCallback; + 399?: ErrorCallback; 400?: ErrorCallback; 401?: ErrorCallback; 402?: ErrorCallback; @@ -3727,15 +3876,87 @@ declare namespace JQuery { 416?: ErrorCallback; 417?: ErrorCallback; 418?: ErrorCallback; + 419?: ErrorCallback; + 420?: ErrorCallback; 421?: ErrorCallback; 422?: ErrorCallback; 423?: ErrorCallback; 424?: ErrorCallback; + 425?: ErrorCallback; 426?: ErrorCallback; + 427?: ErrorCallback; 428?: ErrorCallback; 429?: ErrorCallback; + 430?: ErrorCallback; 431?: ErrorCallback; + 432?: ErrorCallback; + 433?: ErrorCallback; + 434?: ErrorCallback; + 435?: ErrorCallback; + 436?: ErrorCallback; + 437?: ErrorCallback; + 438?: ErrorCallback; + 439?: ErrorCallback; + 440?: ErrorCallback; + 441?: ErrorCallback; + 442?: ErrorCallback; + 443?: ErrorCallback; + 444?: ErrorCallback; + 445?: ErrorCallback; + 446?: ErrorCallback; + 447?: ErrorCallback; + 448?: ErrorCallback; + 449?: ErrorCallback; + 450?: ErrorCallback; 451?: ErrorCallback; + 452?: ErrorCallback; + 453?: ErrorCallback; + 454?: ErrorCallback; + 455?: ErrorCallback; + 456?: ErrorCallback; + 457?: ErrorCallback; + 458?: ErrorCallback; + 459?: ErrorCallback; + 460?: ErrorCallback; + 461?: ErrorCallback; + 462?: ErrorCallback; + 463?: ErrorCallback; + 464?: ErrorCallback; + 465?: ErrorCallback; + 466?: ErrorCallback; + 467?: ErrorCallback; + 468?: ErrorCallback; + 469?: ErrorCallback; + 470?: ErrorCallback; + 471?: ErrorCallback; + 472?: ErrorCallback; + 473?: ErrorCallback; + 474?: ErrorCallback; + 475?: ErrorCallback; + 476?: ErrorCallback; + 477?: ErrorCallback; + 478?: ErrorCallback; + 479?: ErrorCallback; + 480?: ErrorCallback; + 481?: ErrorCallback; + 482?: ErrorCallback; + 483?: ErrorCallback; + 484?: ErrorCallback; + 485?: ErrorCallback; + 486?: ErrorCallback; + 487?: ErrorCallback; + 488?: ErrorCallback; + 489?: ErrorCallback; + 490?: ErrorCallback; + 491?: ErrorCallback; + 492?: ErrorCallback; + 493?: ErrorCallback; + 494?: ErrorCallback; + 495?: ErrorCallback; + 496?: ErrorCallback; + 497?: ErrorCallback; + 498?: ErrorCallback; + 499?: ErrorCallback; 500?: ErrorCallback; 501?: ErrorCallback; 502?: ErrorCallback; @@ -3745,9 +3966,106 @@ declare namespace JQuery { 506?: ErrorCallback; 507?: ErrorCallback; 508?: ErrorCallback; + 509?: ErrorCallback; 510?: ErrorCallback; 511?: ErrorCallback; - } & { [index: number]: SuccessCallback | ErrorCallback; }; + 512?: ErrorCallback; + 513?: ErrorCallback; + 514?: ErrorCallback; + 515?: ErrorCallback; + 516?: ErrorCallback; + 517?: ErrorCallback; + 518?: ErrorCallback; + 519?: ErrorCallback; + 520?: ErrorCallback; + 521?: ErrorCallback; + 522?: ErrorCallback; + 523?: ErrorCallback; + 524?: ErrorCallback; + 525?: ErrorCallback; + 526?: ErrorCallback; + 527?: ErrorCallback; + 528?: ErrorCallback; + 529?: ErrorCallback; + 530?: ErrorCallback; + 531?: ErrorCallback; + 532?: ErrorCallback; + 533?: ErrorCallback; + 534?: ErrorCallback; + 535?: ErrorCallback; + 536?: ErrorCallback; + 537?: ErrorCallback; + 538?: ErrorCallback; + 539?: ErrorCallback; + 540?: ErrorCallback; + 541?: ErrorCallback; + 542?: ErrorCallback; + 543?: ErrorCallback; + 544?: ErrorCallback; + 545?: ErrorCallback; + 546?: ErrorCallback; + 547?: ErrorCallback; + 548?: ErrorCallback; + 549?: ErrorCallback; + 550?: ErrorCallback; + 551?: ErrorCallback; + 552?: ErrorCallback; + 553?: ErrorCallback; + 554?: ErrorCallback; + 555?: ErrorCallback; + 556?: ErrorCallback; + 557?: ErrorCallback; + 558?: ErrorCallback; + 559?: ErrorCallback; + 560?: ErrorCallback; + 561?: ErrorCallback; + 562?: ErrorCallback; + 563?: ErrorCallback; + 564?: ErrorCallback; + 565?: ErrorCallback; + 566?: ErrorCallback; + 567?: ErrorCallback; + 568?: ErrorCallback; + 569?: ErrorCallback; + 570?: ErrorCallback; + 571?: ErrorCallback; + 572?: ErrorCallback; + 573?: ErrorCallback; + 574?: ErrorCallback; + 575?: ErrorCallback; + 576?: ErrorCallback; + 577?: ErrorCallback; + 578?: ErrorCallback; + 579?: ErrorCallback; + 580?: ErrorCallback; + 581?: ErrorCallback; + 582?: ErrorCallback; + 583?: ErrorCallback; + 584?: ErrorCallback; + 585?: ErrorCallback; + 586?: ErrorCallback; + 587?: ErrorCallback; + 588?: ErrorCallback; + 589?: ErrorCallback; + 590?: ErrorCallback; + 591?: ErrorCallback; + 592?: ErrorCallback; + 593?: ErrorCallback; + 594?: ErrorCallback; + 595?: ErrorCallback; + 596?: ErrorCallback; + 597?: ErrorCallback; + 598?: ErrorCallback; + 599?: ErrorCallback; + + // endregion + } & { + // Status codes not listed require type annotations when defining the callback + [index: number]: SuccessCallback | ErrorCallback; + }; + + // Writable properties on XMLHttpRequest + interface XHRFields extends Partial> { } } interface Transport { @@ -3764,95 +4082,14 @@ declare namespace JQuery { /** * @see {@link http://api.jquery.com/jquery.ajax/#jqXHR} */ - interface jqXHR extends Pick { - responseJSON: any; - statusCode(map: Ajax.StatusCodeCallbacks): void; + interface jqXHR extends Promise3, never, + Ajax.SuccessTextStatus, Ajax.ErrorTextStatus, never, + jqXHR, string, never>, + Pick, + Partial> { + responseJSON?: any; - /** - * Add handlers to be called when the Deferred object is either resolved or rejected. - * - * @param alwaysCallback A function, or array of functions, that is called when the Deferred is resolved or rejected. - * @param alwaysCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - * @see {@link https://api.jquery.com/deferred.always/} - * @since 1.6 - */ - always(alwaysCallback: TypeOrArray>, - ...alwaysCallbacks: Array>>): this; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failFilter A function that is called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.catch/} - * @since 3.0 - */ - catch(failFilter: (jqXHR: this, textStatus: Ajax.ErrorTextStatus, errorThrown: string) => never): Deferred; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failFilter A function that is called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.catch/} - * @since 3.0 - */ - catch(failFilter: (jqXHR: this, textStatus: Ajax.ErrorTextStatus, errorThrown: string) => UResolve | Thenable): Deferred; - /** - * Add handlers to be called when the Deferred object is resolved. - * - * @param doneCallback A function, or array of functions, that are called when the Deferred is resolved. - * @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - * @see {@link https://api.jquery.com/deferred.done/} - * @since 1.5 - */ - done(doneCallback: TypeOrArray>, - ...doneCallbacks: Array>>): this; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failCallback A function, or array of functions, that are called when the Deferred is rejected. - * @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.fail/} - * @since 1.5 - */ - fail(failCallback: TypeOrArray>, - ...failCallbacks: Array>>): this; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.pipe/} - * @since 1.6 - * @since 1.7 - * @deprecated 1.8 - */ - pipe(doneFilter: ((data: TResolve, textStatus: Ajax.SuccessTextStatus, jqXHR: this) => UResolve | Thenable) | null, - failFilter?: ((jqXHR: this, textStatus: Ajax.ErrorTextStatus, errorThrown: string) => UReject | Thenable) | null): Deferred; - /** - * Add handlers to be called when the Deferred object generates progress notifications. - * - * @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications. - * @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates - * progress notifications. - * @see {@link https://api.jquery.com/deferred.progress/} - * @since 1.7 - */ - progress(progressCallback: TypeOrArray, - ...progressCallbacks: Array>): this; - /** - * Return a Deferred's Promise object. - * - * @param target Object onto which the promise methods have to be attached - * @see {@link https://api.jquery.com/deferred.promise/} - * @since 1.5 - */ - promise(target: TTarget): JQuery.Promise & TTarget; - /** - * Return a Deferred's Promise object. - * - * @see {@link https://api.jquery.com/deferred.promise/} - * @since 1.5 - */ - promise(): JQuery.Promise; /** * Determine the current state of a Deferred object. * @@ -3860,50 +4097,40 @@ declare namespace JQuery { * @since 1.7 */ state(): 'pending' | 'resolved' | 'rejected'; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.then/} - * @since 1.8 - */ - then(doneFilter: ((data: TResolve, textStatus: Ajax.SuccessTextStatus, jqXHR: this) => UResolve | Thenable) | null, - failFilter?: ((jqXHR: this, textStatus: Ajax.ErrorTextStatus, errorThrown: string) => UReject | Thenable) | null): Deferred; + statusCode(map: Ajax.StatusCodeCallbacks): void; } namespace jqXHR { - interface DoneCallback { - (data: TResolve, textStatus: Ajax.SuccessTextStatus, jqXHR: jqXHR): void; - } + /** + * @deprecated + */ + interface DoneCallback> extends Deferred.Callback3 { } - interface FailCallback { - (jqXHR: TResolve, textStatus: Ajax.ErrorTextStatus, errorThrown: string): void; - } + /** + * @deprecated + */ + interface FailCallback extends Deferred.Callback3 { } - interface AlwaysCallback { - (data_jqXHR: TResolve | jqXHR, textStatus: Ajax.TextStatus, jqXHR_errorThrown: jqXHR | string): void; - } - - interface ProgressCallback { - (...values: any[]): void; - } + /** + * @deprecated + */ + interface AlwaysCallback> extends Deferred.Callback3 { } } // endregion // region Callbacks - interface Callbacks { + interface Callbacks { /** * Add a callback or a collection of callbacks to a callback list. * + * @param callback A function, or array of functions, that are to be added to the callback list. * @param callbacks A function, or array of functions, that are to be added to the callback list. * @see {@link https://api.jquery.com/callbacks.add/} * @since 1.7 */ - add(callbacks: TypeOrArray): this; + add(callback: TypeOrArray, ...callbacks: Array>): this; /** * Disable a callback list from doing anything more. * @@ -3941,7 +4168,7 @@ declare namespace JQuery { * @see {@link https://api.jquery.com/callbacks.fireWith/} * @since 1.7 */ - fireWith(context?: object, args?: TypeOrArray): this; + fireWith(context: object, args?: ArrayLike): this; /** * Determine if the callbacks have already been called at least once. * @@ -3957,7 +4184,7 @@ declare namespace JQuery { * @see {@link https://api.jquery.com/callbacks.has/} * @since 1.7 */ - has(callback?: Function): boolean; + has(callback?: T): boolean; /** * Lock a callback list in its current state. * @@ -3979,7 +4206,7 @@ declare namespace JQuery { * @see {@link https://api.jquery.com/callbacks.remove/} * @since 1.7 */ - remove(callbacks: TypeOrArray): this; + remove(...callbacks: T[]): this; } // endregion @@ -4000,7 +4227,28 @@ declare namespace JQuery { */ interface Thenable extends PromiseLike { } - interface Deferred { + // Type parameter guide + // -------------------- + // Each type parameter represents a parameter in one of the three possible callbacks. + // + // The first letter indicates which position the parameter is in. + // + // T = A = 1st position + // U = B = 2nd position + // V = C = 3rd position + // + // The second letter indicates which whether it is a [R]esolve, Re[J]ect, or [N]otify value. + // + // The third letter indicates whether the value is returned in the [D]one filter, [F]ail filter, or [P]rogress filter. + /** + * This object provides a subset of the methods of the Deferred object (then, done, fail, always, + * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. + * + * @see {@link http://api.jquery.com/Types/#Promise} + */ + interface Promise3 { /** * Add handlers to be called when the Deferred object is either resolved or rejected. * @@ -4009,16 +4257,8 @@ declare namespace JQuery { * @see {@link https://api.jquery.com/deferred.always/} * @since 1.6 */ - always(alwaysCallback: TypeOrArray>, - ...alwaysCallbacks: Array>>): this; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failFilter A function that is called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.catch/} - * @since 3.0 - */ - catch(failFilter: (...reasons: TReject[]) => UResolve | Thenable): Deferred; + always(alwaysCallback: TypeOrArray>, + ...alwaysCallbacks: Array>>): this; /** * Add handlers to be called when the Deferred object is resolved. * @@ -4027,8 +4267,8 @@ declare namespace JQuery { * @see {@link https://api.jquery.com/deferred.done/} * @since 1.5 */ - done(doneCallback: TypeOrArray>, - ...doneCallbacks: Array>>): this; + done(doneCallback: TypeOrArray>, + ...doneCallbacks: Array>>): this; /** * Add handlers to be called when the Deferred object is rejected. * @@ -4037,41 +4277,8 @@ declare namespace JQuery { * @see {@link https://api.jquery.com/deferred.fail/} * @since 1.5 */ - fail(failCallback: TypeOrArray>, - ...failCallbacks: Array>>): this; - /** - * Call the progressCallbacks on a Deferred object with the given args. - * - * @param args Optional arguments that are passed to the progressCallbacks. - * @see {@link https://api.jquery.com/deferred.notify/} - * @since 1.7 - */ - notify(...args: TNotify[]): this; - /** - * Call the progressCallbacks on a Deferred object with the given context and args. - * - * @param context Context passed to the progressCallbacks as the this object. - * @param args An optional array of arguments that are passed to the progressCallbacks. - * @see {@link https://api.jquery.com/deferred.notifyWith/} - * @since 1.7 - */ - notifyWith(context: object, ...args: TNotify[]): this; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.pipe/} - * @since 1.6 - * @since 1.7 - * @deprecated 1.8 - */ - pipe(doneFilter: ((...values: TResolve[]) => UResolve | Thenable) | null, - failFilter?: ((...reasons: TReject[]) => UReject | Thenable) | null, - progressFilter?: ((...values: TNotify[]) => TNotify | Thenable) | null): Deferred; + fail(failCallback: TypeOrArray>, + ...failCallbacks: Array>>): this; /** * Add handlers to be called when the Deferred object generates progress notifications. * @@ -4081,8 +4288,8 @@ declare namespace JQuery { * @see {@link https://api.jquery.com/deferred.progress/} * @since 1.7 */ - progress(progressCallback: TypeOrArray>, - ...progressCallbacks: Array>>): this; + progress(progressCallback: TypeOrArray>, + ...progressCallbacks: Array>>): this; /** * Return a Deferred's Promise object. * @@ -4090,48 +4297,14 @@ declare namespace JQuery { * @see {@link https://api.jquery.com/deferred.promise/} * @since 1.5 */ - promise(target: TTarget): JQuery.Promise & TTarget; + promise(target: TTarget): this & TTarget; /** * Return a Deferred's Promise object. * * @see {@link https://api.jquery.com/deferred.promise/} * @since 1.5 */ - promise(): JQuery.Promise; - /** - * Reject a Deferred object and call any failCallbacks with the given args. - * - * @param args Optional arguments that are passed to the failCallbacks. - * @see {@link https://api.jquery.com/deferred.reject/} - * @since 1.5 - */ - reject(...args: TReject[]): this; - /** - * Reject a Deferred object and call any failCallbacks with the given context and args. - * - * @param context Context passed to the failCallbacks as the this object. - * @param args An optional array of arguments that are passed to the failCallbacks. - * @see {@link https://api.jquery.com/deferred.rejectWith/} - * @since 1.5 - */ - rejectWith(context: object, ...args: TReject[]): this; - /** - * Resolve a Deferred object and call any doneCallbacks with the given args. - * - * @param args Optional arguments that are passed to the doneCallbacks. - * @see {@link https://api.jquery.com/deferred.resolve/} - * @since 1.5 - */ - resolve(...args: TResolve[]): this; - /** - * Resolve a Deferred object and call any doneCallbacks with the given context and args. - * - * @param context Context passed to the doneCallbacks as the this object. - * @param args An optional array of arguments that are passed to the doneCallbacks. - * @see {@link https://api.jquery.com/deferred.resolveWith/} - * @since 1.5 - */ - resolveWith(context: object, ...args: TResolve[]): this; + promise(): this; /** * Determine the current state of a Deferred object. * @@ -4139,56 +4312,7 @@ declare namespace JQuery { * @since 1.7 */ state(): 'pending' | 'resolved' | 'rejected'; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see {@link https://api.jquery.com/deferred.then/} - * @since 1.8 - */ - then(doneFilter: ((...values: TResolve[]) => UResolve | Thenable) | null, - failFilter?: ((...reasons: TReject[]) => UReject | Thenable) | null, - progressFilter?: ((...values: TNotify[]) => TNotify | Thenable) | null): Deferred; - } - namespace Deferred { - interface DoneCallback { - (...values: TResolve[]): void; - } - - interface FailCallback { - (...reasons: TReject[]): void; - } - - interface AlwaysCallback { - (...values_reasons: Array): void; - } - - interface ProgressCallback { - (...values: TNotify[]): void; - } - } - - /** - * This object provides a subset of the methods of the Deferred object (then, done, fail, always, - * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. - * - * @see {@link http://api.jquery.com/Types/#Promise} - */ - interface Promise extends Pick, - 'always' | 'done' | 'fail' | 'progress' | 'promise' | 'state'> { - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failFilter A function that is called when the Deferred is rejected. - * @see {@link https://api.jquery.com/deferred.catch/} - * @since 3.0 - */ - catch(failFilter: (...reasons: TReject[]) => UReject | Thenable): Promise; /** * Utility method to filter and/or chain Deferreds. * @@ -4200,11 +4324,169 @@ declare namespace JQuery { * @since 1.7 * @deprecated 1.8 */ - pipe(doneFilter: ((...values: TResolve[]) => UResolve | Thenable) | null, - failFilter?: ((...reasons: TReject[]) => UReject | Thenable) | null, - progressFilter?: ((...values: TNotify[]) => TNotify | Thenable) | null): Promise; + pipe + (doneFilter: (t: TR, u: UR, v: VR) => Promise3 | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | AJF, + progressFilter: (t: TN, u: UN, v: VN) => Promise3 | Thenable | ANP): Promise3; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | AJF, + progressFilter: (t: TN, u: UN, v: VN) => Promise3 | Thenable | ANP): Promise3; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: (t: TR, u: UR, v: VR) => Promise3 | Thenable | ARD, + failFilter: null, + progressFilter: (t: TN, u: UN, v: VN) => Promise3 | Thenable | ANP): Promise3; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: (t: TR, u: UR, v: VR) => Promise3 | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | AJF, + progressFilter?: null): Promise3; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: (t: TR, u: UR, v: VR) => Promise3 | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | AJF, + progressFilter?: null): Promise3; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | AJF, + progressFilter?: null): Promise3; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: (t: TR, u: UR, v: VR) => Promise3 | Thenable | ARD, + failFilter?: null, + progressFilter?: null): Promise3; + /** * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. * @@ -4214,11 +4496,551 @@ declare namespace JQuery { * @see {@link https://api.jquery.com/deferred.then/} * @since 1.8 */ - then(doneFilter: ((...values: TResolve[]) => UResolve | Thenable) | null, - failFilter?: ((...reasons: TReject[]) => UReject | Thenable) | null, - progressFilter?: ((...values: TNotify[]) => TNotify | Thenable) | null): Promise; + then + (doneFilter: (t: TR, u: UR, v: VR) => Promise3 | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | ARF, + progressFilter: (t: TN, u: UN, v: VN) => Promise3 | Thenable | ANP): Promise3; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | ARF, + progressFilter: (t: TN, u: UN, v: VN) => Promise3 | Thenable | ANP): Promise3; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: (t: TR, u: UR, v: VR) => Promise3 | Thenable | ARD, + failFilter: null, + progressFilter: (t: TN, u: UN, v: VN) => Promise3 | Thenable | ANP): Promise3; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: null, + failFilter: null, + progressFilter: (t: TN, u: UN, v: VN) => Promise3 | Thenable | ANP): Promise3; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: (t: TR, u: UR, v: VR) => Promise3 | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | ARF, + progressFilter?: null): Promise3; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | ARF, + progressFilter?: null): Promise3; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: (t: TR, u: UR, v: VR) => Promise3 | Thenable | ARD, + failFilter?: null, + progressFilter?: null): Promise3; + + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failFilter A function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.catch/} + * @since 3.0 + */ + catch + (failFilter: (t: TJ, u: UJ, v: VJ) => Promise3 | Thenable | ARF): Promise3; + } + + /** + * This object provides a subset of the methods of the Deferred object (then, done, fail, always, + * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. + * + * @see {@link http://api.jquery.com/Types/#Promise} + */ + interface Promise2 extends Promise3 { } + + /** + * This object provides a subset of the methods of the Deferred object (then, done, fail, always, + * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. + * + * @see {@link http://api.jquery.com/Types/#Promise} + */ + interface Promise { + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * + * @param alwaysCallback A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + * @see {@link https://api.jquery.com/deferred.always/} + * @since 1.6 + */ + always(alwaysCallback: TypeOrArray>, + ...alwaysCallbacks: Array>>): this; + /** + * Add handlers to be called when the Deferred object is resolved. + * + * @param doneCallback A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + * @see {@link https://api.jquery.com/deferred.done/} + * @since 1.5 + */ + done(doneCallback: TypeOrArray>, + ...doneCallbacks: Array>>): this; + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failCallback A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.fail/} + * @since 1.5 + */ + fail(failCallback: TypeOrArray>, + ...failCallbacks: Array>>): this; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * + * @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications. + * @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates + * progress notifications. + * @see {@link https://api.jquery.com/deferred.progress/} + * @since 1.7 + */ + progress(progressCallback: TypeOrArray>, + ...progressCallbacks: Array>>): this; + /** + * Return a Deferred's Promise object. + * + * @param target Object onto which the promise methods have to be attached + * @see {@link https://api.jquery.com/deferred.promise/} + * @since 1.5 + */ + promise(target: TTarget): JQuery.Promise & TTarget; + /** + * Return a Deferred's Promise object. + * + * @see {@link https://api.jquery.com/deferred.promise/} + * @since 1.5 + */ + promise(): JQuery.Promise; + /** + * Determine the current state of a Deferred object. + * + * @see {@link https://api.jquery.com/deferred.state/} + * @since 1.7 + */ + state(): 'pending' | 'resolved' | 'rejected'; + + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: (...t: TR[]) => Promise | Thenable | ARD, + failFilter: (...t: TJ[]) => Promise | Thenable | AJF, + progressFilter: (...t: TN[]) => Promise | Thenable | ANP): Promise; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: null, + failFilter: (...t: TJ[]) => Promise | Thenable | AJF, + progressFilter: (...t: TN[]) => Promise | Thenable | ANP): Promise; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: (...t: TR[]) => Promise | Thenable | ARD, + failFilter: null, + progressFilter: (...t: TN[]) => Promise | Thenable | ANP): Promise; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: null, + failFilter: (...t: TR[]) => Promise | Thenable | AJF, + progressFilter: (...t: TN[]) => Promise | Thenable | ANP): Promise; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: (...t: TR[]) => Promise | Thenable | ARD, + failFilter: (...t: TJ[]) => Promise | Thenable | AJF, + progressFilter?: null): Promise; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: null, + failFilter: (...t: TJ[]) => Promise | Thenable | AJF, + progressFilter?: null): Promise; + /** + * Utility method to filter and/or chain Deferreds. + * + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @see {@link https://api.jquery.com/deferred.pipe/} + * @since 1.6 + * @since 1.7 + * @deprecated 1.8 + */ + pipe + (doneFilter: (...t: TR[]) => Promise | Thenable | ARD, + failFilter?: null, + progressFilter?: null): Promise; + + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: (...t: TR[]) => Promise | Thenable | ARD, + failFilter: (...t: TJ[]) => Promise | Thenable | ARF, + progressFilter: (...t: TN[]) => Promise | Thenable | ANP): Promise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: null, + failFilter: (...t: TJ[]) => Promise | Thenable | ARF, + progressFilter: (...t: TN[]) => Promise | Thenable | ANP): Promise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: (...t: TR[]) => Promise | Thenable | ARD, + failFilter: null, + progressFilter: (...t: TN[]) => Promise | Thenable | ANP): Promise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: null, + failFilter: null, + progressFilter: (...t: TN[]) => Promise | Thenable | ANP): Promise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: (...t: TR[]) => Promise | Thenable | ARD, + failFilter: (...t: TJ[]) => Promise | Thenable | ARF, + progressFilter?: null): Promise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: null, + failFilter: (...t: TJ[]) => Promise | Thenable | ARF, + progressFilter?: null): Promise; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * + * @param doneFilter A function that is called when the Deferred is resolved. + * @see {@link https://api.jquery.com/deferred.then/} + * @since 1.8 + */ + then + (doneFilter: (...t: TR[]) => Promise | Thenable | ARD, + failFilter?: null, + progressFilter?: null): Promise; + + /** + * Add handlers to be called when the Deferred object is rejected. + * + * @param failFilter A function that is called when the Deferred is rejected. + * @see {@link https://api.jquery.com/deferred.catch/} + * @since 3.0 + */ + catch + (failFilter: (...t: TJ[]) => Promise | Thenable | ARF): Promise; + } + + interface DeferredStatic { + // https://jquery.com/upgrade-guide/3.0/#callback-exit + exceptionHook: any; + (beforeStart?: (this: JQuery.Deferred, deferred: JQuery.Deferred) => void): JQuery.Deferred; + } + + interface Deferred extends JQuery.Promise { + /** + * Call the progressCallbacks on a Deferred object with the given args. + * + * @param args Optional arguments that are passed to the progressCallbacks. + * @see {@link https://api.jquery.com/deferred.notify/} + * @since 1.7 + */ + notify(...args: TN[]): this; + /** + * Call the progressCallbacks on a Deferred object with the given context and args. + * + * @param context Context passed to the progressCallbacks as the this object. + * @param args An optional array of arguments that are passed to the progressCallbacks. + * @see {@link https://api.jquery.com/deferred.notifyWith/} + * @since 1.7 + */ + notifyWith(context: object, args?: ArrayLike): this; + /** + * Reject a Deferred object and call any failCallbacks with the given args. + * + * @param args Optional arguments that are passed to the failCallbacks. + * @see {@link https://api.jquery.com/deferred.reject/} + * @since 1.5 + */ + reject(...args: TJ[]): this; + /** + * Reject a Deferred object and call any failCallbacks with the given context and args. + * + * @param context Context passed to the failCallbacks as the this object. + * @param args An optional array of arguments that are passed to the failCallbacks. + * @see {@link https://api.jquery.com/deferred.rejectWith/} + * @since 1.5 + */ + rejectWith(context: object, args?: ArrayLike): this; + /** + * Resolve a Deferred object and call any doneCallbacks with the given args. + * + * @param args Optional arguments that are passed to the doneCallbacks. + * @see {@link https://api.jquery.com/deferred.resolve/} + * @since 1.5 + */ + resolve(...args: TR[]): this; + /** + * Resolve a Deferred object and call any doneCallbacks with the given context and args. + * + * @param context Context passed to the doneCallbacks as the this object. + * @param args An optional array of arguments that are passed to the doneCallbacks. + * @see {@link https://api.jquery.com/deferred.resolveWith/} + * @since 1.5 + */ + resolveWith(context: object, args?: ArrayLike): this; + } + + namespace Deferred { + interface Callback3 { + (t: T, u: U, v: V): void; + } + + interface Callback { + (...args: T[]): void; + } + + /** + * @deprecated + */ + interface DoneCallback extends Callback { } + + /** + * @deprecated + */ + interface FailCallback extends Callback { } + + /** + * @deprecated + */ + interface AlwaysCallback extends Callback { } + + /** + * @deprecated + */ + interface ProgressCallback extends Callback { } } // endregion @@ -4305,10 +5127,11 @@ declare namespace JQuery { complete?(this: TElement): void; } + // This should be a class but doesn't work correctly under the JQuery namespace. Tween should be an inner class of jQuery. // Undocumented // https://github.com/jquery/api.jquery.com/issues/391 // https://github.com/jquery/api.jquery.com/issues/61 - class Tween { + interface Tween { easing: string; elem: TElement; end: number; @@ -4328,29 +5151,12 @@ declare namespace JQuery { // region Events + // region Event + // This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery. - interface Event { - /** - * The current DOM element within the event bubbling phase. - * - * @see {@link https://api.jquery.com/event.currentTarget/} - * @since 1.3 - */ - currentTarget: TTarget; - /** - * An optional object of data passed to an event method when the current executing handler is bound. - * - * @see {@link https://api.jquery.com/event.data/} - * @since 1.1 - */ - data: TData; - /** - * The element where the currently-called jQuery event handler was attached. - * - * @see {@link https://api.jquery.com/event.delegateTarget/} - * @since 1.7 - */ - delegateTarget: TTarget; + + // Instance members + interface Event { /** * Indicates whether the META key was pressed when the event fired. * @@ -4379,13 +5185,6 @@ declare namespace JQuery { * @since 1.0.4 */ pageY: number; - /** - * The other DOM element involved in the event, if any. - * - * @see {@link https://api.jquery.com/event.relatedTarget/} - * @since 1.1.4 - */ - relatedTarget: TTarget | null; /** * The last value returned by an event handler that was triggered by this event, unless the value was undefined. * @@ -4393,13 +5192,6 @@ declare namespace JQuery { * @since 1.3 */ result: any; - /** - * The DOM element that initiated the event. - * - * @see {@link https://api.jquery.com/event.target/} - * @since 1.0 - */ - target: TTarget; /** * The difference in milliseconds between the time the browser created the event and January 1, 1970. * @@ -4471,18 +5263,64 @@ declare namespace JQuery { stopPropagation(): void; } - interface Event extends Partial extends Partial> { - originalTarget?: TTarget; + /** + * The current DOM element within the event bubbling phase. + * + * @see {@link https://api.jquery.com/event.currentTarget/} + * @since 1.3 + */ + currentTarget: TTarget; + /** + * An optional object of data passed to an event method when the current executing handler is bound. + * + * @see {@link https://api.jquery.com/event.data/} + * @since 1.1 + */ + data: TData; + /** + * The element where the currently-called jQuery event handler was attached. + * + * @see {@link https://api.jquery.com/event.delegateTarget/} + * @since 1.7 + */ + delegateTarget: TTarget; originalEvent: _Event; - new(event: string, properties?: T): JQuery.Event & T; - new(properties: T): JQuery.Event & T; - (event: string, properties?: T): JQuery.Event & T; - (properties: T): JQuery.Event & T; + /** + * The other DOM element involved in the event, if any. + * + * @see {@link https://api.jquery.com/event.relatedTarget/} + * @since 1.1.4 + */ + relatedTarget: TTarget | null; + /** + * The DOM element that initiated the event. + * + * @see {@link https://api.jquery.com/event.target/} + * @since 1.0 + */ + target: TTarget; } + // Static members + interface EventStatic { + (event: string, properties?: T): JQuery.Event & T; + (properties: T): JQuery.Event & T; + new (event: string, properties?: T): JQuery.Event & T; + new (properties: T): JQuery.Event & T; + } + + interface EventLike { + type: string; + } + + // endregion + // Extra parameters can be passed from trigger() interface EventHandler { (this: TContext, eventObject: JQuery.Event, ...args: any[]): void | false | any; @@ -4633,7 +5471,7 @@ declare namespace JQuery { // region Legacy types -interface JQueryCallback extends JQuery.Callbacks { } +interface JQueryCallback extends JQuery.Callbacks { } interface JQueryDeferred extends JQuery.Deferred { } interface JQueryEventConstructor extends JQuery.Event { } interface JQueryDeferred extends JQuery.Deferred { } diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 438f36c79b..35b91fe1d3 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -1,3 +1,5 @@ +// tslint:disable:interface-name + function JQuery() { function type_assertion() { const $el = $(document.createElement('canvas')); @@ -11,7 +13,10 @@ function JQuery() { } function arrayLike() { - $('div')[0] === new HTMLElement(); + // $ExpectType HTMLElement + $('div')[0]; + + $('div')[0] = new HTMLElement(); } function ajax() { @@ -601,7 +606,7 @@ function JQuery() { }; }); - // $ExpectType Coordinates + // $ExpectType Coordinates | undefined $('p').offset(); } @@ -1186,9 +1191,6 @@ function JQuery() { this; }); - // $ExpectType JQuery - $('p').toggle('linear'); - // $ExpectType JQuery $('p').toggle(true); @@ -3025,7 +3027,7 @@ function JQuery() { return 'myVal'; }); - // $ExpectType string | number | string[] | null | undefined + // $ExpectType string | number | string[] | undefined $('p').val(); } } @@ -3479,10 +3481,10 @@ function JQueryStatic() { } function call_signature() { - // #ExpectType JQuery + // $ExpectType JQuery $('

', new Document()); - // #ExpectType JQuery + // $ExpectType JQuery $('

', { class: 'my-div', on: { @@ -3492,57 +3494,154 @@ function JQueryStatic() { } }); - // #ExpectType JQuery + // $ExpectType JQuery $('span', new HTMLElement()); - // #ExpectType JQuery + // $ExpectType JQuery $('span', new Document()); - // #ExpectType JQuery + // $ExpectType JQuery $('span', $('p')); - // #ExpectType JQuery + // $ExpectType JQuery $('span'); - // #ExpectType JQuery + // $ExpectType JQuery $('

'); - // #ExpectType JQuery + // $ExpectType JQuery $(new HTMLElement()); - // #ExpectType JQuery + // $ExpectType JQuery $([new HTMLElement()]); - // #ExpectType JQuery + // $ExpectType JQuery $({ foo: 'bar', hello: 'world' }); - // #ExpectType JQuery + // $ExpectType JQuery $($('p')); - // #ExpectType JQuery + // $ExpectType JQuery $(function($) { - // #ExpectType Document + // $ExpectType Document this; - // #ExpectType JQueryStatic + // $ExpectType JQueryStatic $; }); - // #ExpectType JQuery + // $ExpectType JQuery $(); } + function Event() { + // $ExpectType EventStatic + $.Event; + } + + function cssHooks() { + // $ExpectType PlainObject> + $.cssHooks; + } + + function cssNumber() { + // $ExpectType PlainObject + $.cssNumber; + } + + function fn() { + // $ExpectType JQuery + $.fn; + } + + function fx() { + function interval() { + // $ExpectType number + $.fx.interval; + } + + function off() { + // $ExpectType boolean + $.fx.off; + } + + function step() { + // $ExpectType PlainObject> + $.fx.step; + } + } + + function ready() { + // $ExpectType Thenable> + $.ready; + } + + function support() { + // $ExpectType PlainObject + $.support; + } + + function valHooks() { + // $ExpectType PlainObject> + $.valHooks; + } + function Callbacks() { - // #ExpectType Callbacks + // $ExpectType Callbacks $.Callbacks('once'); - // #ExpectType Callbacks + // $ExpectType Callbacks $.Callbacks(); } - function Event() { - function constructor() { - const e = $.Event('click'); - e.stopPropagation(); + function Deferred() { + function call_signature() { + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); + + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); + + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); + + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); + } + + function exceptionHook() { + $.Deferred.exceptionHook = undefined; } } @@ -3999,8 +4098,12 @@ function JQueryStatic() { } function isEmptyObject() { - // $ExpectType boolean - $.isEmptyObject({}); + function type_guard(obj: object) { + if ($.isEmptyObject(obj)) { + // $ExpectType {} + obj; + } + } } function isFunction() { @@ -4342,24 +4445,346 @@ function JQueryStatic() { } function when() { - const t = $.ajax() as JQuery.jqXHR; - const u = $.ajax() as JQuery.jqXHR; - const v = $.ajax() as JQuery.jqXHR; + interface I1 { kind: 'I1'; } + interface I2 { kind: 'I2'; } + interface I3 { kind: 'I3'; } + interface I4 { kind: 'I4'; } + interface I5 { kind: 'I5'; } + interface I6 { kind: 'I6'; } + interface I7 { kind: 'I7'; } + interface I8 { kind: 'I8'; } + interface I9 { kind: 'I9'; } - // $ExpectType Promise<[string | number | boolean, string, jqXHR], any, any> - $.when(t, u, v); + function Promise3() { + const t = $.ajax() as JQuery.jqXHR; + const u = $.ajax() as JQuery.jqXHR; + const v = $.ajax() as JQuery.jqXHR; - // $ExpectType Promise<[string | number, string, jqXHR], any, any> - $.when(t, u); + // // 3 parameters + // { + // const w = $.when(t, u, v); + // + // w.then((a, b, c) => { + // a[0]; // $ExpectType string + // a[1]; // $ExpectType SuccessTextStatus + // a[2]; // $ExpectType jqXHR + // b[0]; // $ExpectType number + // b[1]; // $ExpectType SuccessTextStatus + // b[2]; // $ExpectType jqXHR + // c[0]; // $ExpectType boolean + // c[1]; // $ExpectType SuccessTextStatus + // c[2]; // $ExpectType jqXHR + // }, (a, b, c) => { + // a[0]; // $ExpectType jqXHR + // a[1]; // $ExpectType ErrorTextStatus + // a[2]; // $ExpectType string + // b[0]; // $ExpectType jqXHR + // b[1]; // $ExpectType ErrorTextStatus + // b[2]; // $ExpectType string + // c[0]; // $ExpectType jqXHR + // c[1]; // $ExpectType ErrorTextStatus + // c[2]; // $ExpectType string + // }, (a, b, c) => { + // a; // $ExpectType never + // b; // $ExpectType never + // c; // $ExpectType never + // }); + // } + // + // // 2 parameters + // { + // const w = $.when(t, u); + // + // w.then((a, b) => { + // a[0]; // $ExpectType string + // a[1]; // $ExpectType SuccessTextStatus + // a[2]; // $ExpectType jqXHR + // b[0]; // $ExpectType number + // b[1]; // $ExpectType SuccessTextStatus + // b[2]; // $ExpectType jqXHR + // }, (a, b) => { + // a[0]; // $ExpectType jqXHR + // a[1]; // $ExpectType ErrorTextStatus + // a[2]; // $ExpectType string + // b[0]; // $ExpectType jqXHR + // b[1]; // $ExpectType ErrorTextStatus + // b[2]; // $ExpectType string + // }, (a, b) => { + // a; // $ExpectType never + // b; // $ExpectType never + // }); + // } - // $ExpectType Promise, any, any> - $.when(t); + // 1 parameter + { + const w = $.when(t); - // $ExpectType Promise - $.when($.Deferred()); + w.then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType SuccessTextStatus + c; // $ExpectType jqXHR + }, (a, b, c) => { + a; // $ExpectType jqXHR + b; // $ExpectType ErrorTextStatus + c; // $ExpectType string + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + } - // $ExpectType Promise - $.when(); + function Promise2() { + const t: JQuery.Promise2 = {} as any; + const u: JQuery.Promise2 = {} as any; + const v: JQuery.Promise2 = {} as any; + + // // 3 parameters + // { + // const w = $.when(t, u, v); + // + // w.then((a, b, c) => { + // a[0]; // $ExpectType string + // a[1]; // $ExpectType boolean + // b[0]; // $ExpectType string + // b[1]; // $ExpectType boolean + // c[0]; // $ExpectType string + // c[1]; // $ExpectType boolean + // }, (a, b, c) => { + // a[0]; // $ExpectType Error + // a[1]; // $ExpectType any + // b[0]; // $ExpectType Error + // b[1]; // $ExpectType any + // c[0]; // $ExpectType Error + // c[1]; // $ExpectType any + // }, (a, b, c) => { + // a; // $ExpectType never + // b; // $ExpectType never + // c; // $ExpectType never + // }); + // } + // + // // 2 parameters + // { + // const w = $.when(t, u); + // + // w.then((a, b) => { + // a[0]; // $ExpectType string + // a[1]; // $ExpectType boolean + // b[0]; // $ExpectType string + // b[1]; // $ExpectType boolean + // }, (a, b) => { + // a[0]; // $ExpectType Error + // a[1]; // $ExpectType any + // b[0]; // $ExpectType Error + // b[1]; // $ExpectType any + // }, (a, b) => { + // a; // $ExpectType never + // b; // $ExpectType never + // }); + // } + + // 1 parameter + { + const w = $.when(t); + + w.then((a, b) => { + a; // $ExpectType string + b; // $ExpectType boolean + }, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType any + }, (a, b) => { + a; // $ExpectType never + b; // $ExpectType never + }); + } + } + + function Promise() { + const p1: JQuery.Promise = {} as any; + const p2: JQuery.Promise = {} as any; + const p3: JQuery.Promise = {} as any; + + // 3 parameters + { + const w = $.when(p1, p2, p3); + + w.then((a, b, c) => { + a; // $ExpectType I1 + b; // $ExpectType I2 + c; // $ExpectType I3 + }, (a, b, c) => { + a; // $ExpectType I2 + b; // $ExpectType I3 + c; // $ExpectType I4 + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + + // 2 parameters + { + const w = $.when(p1, p2); + + w.then((a, b) => { + a; // $ExpectType I1 + b; // $ExpectType I2 + }, (a, b) => { + a; // $ExpectType I2 + b; // $ExpectType I3 + }, (a, b) => { + a; // $ExpectType never + b; // $ExpectType never + }); + } + + // 1 parameter + { + const w = $.when(p1); + + w.then(a => { + a; // $ExpectType I1 + }, a => { + a; // $ExpectType I2 + }, a => { + a; // $ExpectType never + }); + } + } + + function Thenable() { + const t1: JQuery.Thenable = {} as any; + const t2: JQuery.Thenable = {} as any; + const t3: JQuery.Thenable = {} as any; + + // 3 parameters + { + const w = $.when(t1, t2, t3); + + w.then((a, b, c) => { + a; // $ExpectType I1 + b; // $ExpectType I2 + c; // $ExpectType I3 + }, (a, b, c) => { + a; // $ExpectType any + b; // $ExpectType any + c; // $ExpectType any + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + + // 2 parameters + { + const w = $.when(t1, t2); + + w.then((a, b) => { + a; // $ExpectType I1 + b; // $ExpectType I2 + }, (a, b) => { + a; // $ExpectType any + b; // $ExpectType any + }, (a, b) => { + a; // $ExpectType never + b; // $ExpectType never + }); + } + + // 1 parameter + { + const w = $.when(t1); + + w.then(a => { + a; // $ExpectType I1 + }, a => { + a; // $ExpectType any + }, a => { + a; // $ExpectType never + }); + } + } + + function value() { + const w = $.when('myVal1'); + + w.then(a => { + a; // $ExpectType string + }); + } + + function Zero() { + const w = $.when(); + + w.then(a => { + a; // $ExpectType never + }, a => { + a; // $ExpectType never + }, a => { + a; // $ExpectType never + }); + } + + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/2725 + function issue_2725() { + function first() { + return $.when('1'); + } + + $.when().then(() => { + return first(); + }).then((value) => { + value; // $ExpectType string + }); + } + + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/10159 + function issue_10159() { + interface One { result: number; } + interface Two { Result: number; } + interface Three { TheResult: number; } + + class AsyncRunner { + Run(): void { + const task1 = this.runTask1(); + const task2 = this.runTask2(); + const task3 = this.runTask3(); + + $.when(task1, task2, task3) + .then((r1, r2, r3) => { + r1; // $ExpectType One + r2; // $ExpectType Two + r3; // $ExpectType Three + }); + } + + runTask1() { + let dfd = $.Deferred(); + console.log('Task 1'); + setTimeout(() => { dfd.resolve({ result: 1 }); }, Math.floor(400 + Math.random() * 2000)); + return dfd.promise(); + } + + runTask2() { + let dfd = $.Deferred(); + console.log('Task 2'); + setTimeout(() => { dfd.resolve({ Result: 2 }); }, Math.floor(400 + Math.random() * 2000)); + return dfd.promise(); + } + + runTask3() { + let dfd = $.Deferred(); + console.log('Task 3'); + setTimeout(() => { dfd.resolve({ TheResult: 3 }); }, Math.floor(400 + Math.random() * 2000)); + return dfd.promise(); + } + } + } } } @@ -4529,6 +4954,86 @@ function AjaxSettings() { }); } +function Callbacks() { + function add() { + const callbacks = $.Callbacks(); + + // $ExpectType Callbacks + callbacks.add(() => { }, [() => { }], () => { }); + + // $ExpectType Callbacks + callbacks.add(() => { }, [() => { }]); + + // $ExpectType Callbacks + callbacks.add(() => { }, () => { }); + + // $ExpectType Callbacks + callbacks.add(() => { }); + + // $ExpectType Callbacks + callbacks.add([() => { }]); + } + + function disable() { + // $ExpectType Callbacks + $.Callbacks().disable(); + } + + function disabled() { + // $ExpectType boolean + $.Callbacks().disabled(); + } + + function empty() { + // $ExpectType Callbacks + $.Callbacks().empty(); + } + + function fire() { + // $ExpectType Callbacks + $.Callbacks().fire(1); + + // $ExpectType Callbacks + $.Callbacks().fire(); + } + + function fireWith() { + // $ExpectType Callbacks + $.Callbacks().fireWith(window, [1]); + + // $ExpectType Callbacks + $.Callbacks().fireWith(window); + } + + function fired() { + // $ExpectType boolean + $.Callbacks().fired(); + } + + function has() { + // $ExpectType boolean + $.Callbacks().has(() => { }); + + // $ExpectType boolean + $.Callbacks().has(); + } + + function lock() { + // $ExpectType Callbacks + $.Callbacks().lock(); + } + + function locked() { + // $ExpectType boolean + $.Callbacks().locked(); + } + + function remove() { + // $ExpectType Callbacks + $.Callbacks().remove(() => { }, () => { }); + } +} + function EffectsOptions() { $('p').show({ always(animation, jumpToEnd) { @@ -4593,51 +5098,272 @@ function EffectsOptions() { }); } -function JQuery_Event() { - function mixin() { - const e = $.Event('keydown', { - mySpecialKeyCode: JQuery.Key.CapsLock, - }); +function _Event() { + function call_signature() { + // $ExpectType Event & Coordinates + $.Event('keydown', $('p').offset()); - e.mySpecialKeyCode === JQuery.Key.NumLock; + // $ExpectType Event & { type: string; } + $.Event({ + type: 'keydown' + }); + } + + function constructor() { + // $ExpectType Event & Coordinates + new $.Event('keydown', $('p').offset()); + + // $ExpectType Event & { type: string; } + new $.Event({ + type: 'keydown' + }); } } function jqXHR() { - function catch_returnType() { - // $ExpectType Deferred - $.ajax('/echo').catch(() => { }); - } - - function catch_throw_returnType() { - // $ExpectType Deferred - $.ajax('/echo').catch((reason) => { - throw new Error(); - }); - } - - function then_returnType() { - // $ExpectType Deferred - $.ajax('/echo').then(() => { }); - } - - function throw_from_catch() { - $.ajax('/echo').catch(() => { - throw new Error('Thrown from [jQuery] 1st catch block'); - }).then((value) => { - // $ExpectType never - value; - }).catch((reason) => { + function always() { + // $ExpectType jqXHR + $.ajax('/echo/json').always((data_jqXHR, textStatus, jqXHR_errorThrown) => { // $ExpectType any - reason; - }).then((value) => { - // $ExpectType void - value; + data_jqXHR; + // $ExpectType TextStatus + textStatus; + // $ExpectType string | jqXHR + jqXHR_errorThrown; + }, [(data_jqXHR, textStatus, jqXHR_errorThrown) => { + // $ExpectType any + data_jqXHR; + // $ExpectType TextStatus + textStatus; + // $ExpectType string | jqXHR + jqXHR_errorThrown; + }], (data_jqXHR, textStatus, jqXHR_errorThrown) => { + // $ExpectType any + data_jqXHR; + // $ExpectType TextStatus + textStatus; + // $ExpectType string | jqXHR + jqXHR_errorThrown; }); + + // $ExpectType jqXHR + $.ajax('/echo/json').always((data_jqXHR, textStatus, jqXHR_errorThrown) => { + // $ExpectType any + data_jqXHR; + // $ExpectType TextStatus + textStatus; + // $ExpectType string | jqXHR + jqXHR_errorThrown; + }, [(data_jqXHR, textStatus, jqXHR_errorThrown) => { + // $ExpectType any + data_jqXHR; + // $ExpectType TextStatus + textStatus; + // $ExpectType string | jqXHR + jqXHR_errorThrown; + }]); + + // $ExpectType jqXHR + $.ajax('/echo/json').always([(data_jqXHR, textStatus, jqXHR_errorThrown) => { + // $ExpectType any + data_jqXHR; + // $ExpectType TextStatus + textStatus; + // $ExpectType string | jqXHR + jqXHR_errorThrown; + }], (data_jqXHR, textStatus, jqXHR_errorThrown) => { + // $ExpectType any + data_jqXHR; + // $ExpectType TextStatus + textStatus; + // $ExpectType string | jqXHR + jqXHR_errorThrown; + }); + + // $ExpectType jqXHR + $.ajax('/echo/json').always((data_jqXHR, textStatus, jqXHR_errorThrown) => { + // $ExpectType any + data_jqXHR; + // $ExpectType TextStatus + textStatus; + // $ExpectType string | jqXHR + jqXHR_errorThrown; + }); + + // $ExpectType jqXHR + $.ajax('/echo/json').always([(data_jqXHR, textStatus, jqXHR_errorThrown) => { + // $ExpectType any + data_jqXHR; + // $ExpectType TextStatus + textStatus; + // $ExpectType string | jqXHR + jqXHR_errorThrown; + }]); + } + + function done() { + // $ExpectType jqXHR + $.ajax('/echo/json').done((data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, [(data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }], (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType jqXHR + $.ajax('/echo/json').done((data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }, [(data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }]); + + // $ExpectType jqXHR + $.ajax('/echo/json').done([(data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }], (data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType jqXHR + $.ajax('/echo/json').done((data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }); + + // $ExpectType jqXHR + $.ajax('/echo/json').done([(data, textStatus, jqXHR) => { + // $ExpectType any + data; + // $ExpectType SuccessTextStatus + textStatus; + // $ExpectType jqXHR + jqXHR; + }]); } function fail() { - $.ajax('/echo').fail((jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + $.ajax('/echo/json').fail((jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }, [(jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }], (jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }); + + // $ExpectType jqXHR + $.ajax('/echo/json').fail((jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }, [(jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }]); + + // $ExpectType jqXHR + $.ajax('/echo/json').fail([(jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }], (jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }); + + // $ExpectType jqXHR + $.ajax('/echo/json').fail((jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }); + + // $ExpectType jqXHR + $.ajax('/echo/json').fail([(jqXHR, textStatus, errorThrown) => { + // $ExpectType jqXHR + jqXHR; + // $ExpectType ErrorTextStatus + textStatus; + // $ExpectType string + errorThrown; + }]); + } + + function _catch() { + // $ExpectType Promise3 + $.ajax('/echo').catch((jqXHR, textStatus, errorThrown) => { // $ExpectType jqXHR jqXHR; // $ExpectType ErrorTextStatus @@ -4647,3 +5373,625 @@ function jqXHR() { }); } } + +function Promise3() { + interface I1 { kind: 'I1'; } + interface I2 { kind: 'I2'; } + interface I3 { kind: 'I3'; } + interface I4 { kind: 'I4'; } + interface I5 { kind: 'I5'; } + interface I6 { kind: 'I6'; } + interface I7 { kind: 'I7'; } + interface I8 { kind: 'I8'; } + interface I9 { kind: 'I9'; } + + const p: JQuery.Promise3 = {} as any; + const p1: JQuery.Promise3 = {} as any; + const p2: JQuery.Promise3 = {} as any; + const p3: JQuery.Promise3 = {} as any; + + const t1: JQuery.Thenable = {} as any; + const t2: JQuery.Thenable = {} as any; + const t3: JQuery.Thenable = {} as any; + + function then() { + p.then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType JQuery + c; // $ExpectType any + }, (a, b, c) => { + a; // $ExpectType Error + b; // $ExpectType string + c; // $ExpectType Function + }, (a, b, c) => { + a; // $ExpectType number + b; // $ExpectType boolean + c; // $ExpectType never + }); + + p.then(null, (a, b, c) => { + a; // $ExpectType Error + b; // $ExpectType string + c; // $ExpectType Function + }, (a, b, c) => { + a; // $ExpectType number + b; // $ExpectType boolean + c; // $ExpectType never + }); + + p.then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType JQuery + c; // $ExpectType any + }, null, (a, b, c) => { + a; // $ExpectType number + b; // $ExpectType boolean + c; // $ExpectType never + }); + + p.then(null, null, (a, b, c) => { + a; // $ExpectType number + b; // $ExpectType boolean + c; // $ExpectType never + }); + + p.then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType JQuery + c; // $ExpectType any + }, (a, b, c) => { + a; // $ExpectType Error + b; // $ExpectType string + c; // $ExpectType Function + }, null); + + p.then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType JQuery + c; // $ExpectType any + }, (a, b, c) => { + a; // $ExpectType Error + b; // $ExpectType string + c; // $ExpectType Function + }); + + p.then(null, (a, b, c) => { + a; // $ExpectType Error + b; // $ExpectType string + c; // $ExpectType Function + }, null); + + p.then(null, (a, b, c) => { + a; // $ExpectType Error + b; // $ExpectType string + c; // $ExpectType Function + }); + + p.then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType JQuery + c; // $ExpectType any + }, null, null); + + p.then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType JQuery + c; // $ExpectType any + }, null); + + p.then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType JQuery + c; // $ExpectType any + }); + + function doneFilter() { + p.then(() => { + return 1; + }).then((a) => { + a; // $ExpectType number + }); + + p.then(() => { + return $.ready; + }).then((a) => { + a; // $ExpectType JQueryStatic + }); + + p.then(() => { + return p; + }).then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType JQuery + c; // $ExpectType any + }, (a, b, c) => { + a; // $ExpectType Error + b; // $ExpectType string + c; // $ExpectType Function + }, (a, b, c) => { + a; // $ExpectType number + b; // $ExpectType boolean + c; // $ExpectType never + }); + } + + function failFilter() { + p.then(null, () => { + return 1; + }).then((a) => { + a; // $ExpectType number + }); + + p.then(null, () => { + return $.ready; + }).then((a) => { + a; // $ExpectType JQueryStatic + }); + + p.then(null, () => { + return p; + }).then((a, b, c) => { + a; // $ExpectType string + b; // $ExpectType JQuery + c; // $ExpectType any + }, (a, b, c) => { + a; // $ExpectType Error + b; // $ExpectType string + c; // $ExpectType Function + }, (a, b, c) => { + a; // $ExpectType number + b; // $ExpectType boolean + c; // $ExpectType never + }); + } + + function doneFilter_failFilter() { + // (value, value) + { + const q = p.then(() => { + return 1; + }, () => { + return 1; + }); + + q.then((a) => { + a; // $ExpectType number + }, (a) => { + a; // $ExpectType never + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + + // (Thenable, Thenable) + { + const q = p.then(() => { + return t1; + }, () => { + return t2; + }); + + q.then((a) => { + a; // $ExpectType I1 | I2 + }, (a) => { + a; // $ExpectType never + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + + // (Promise3, Promise3) + { + const q = p.then(() => { + return p1; + }, () => { + return p2; + }); + + q.then((a, b, c) => { + a; // $ExpectType I1 | I2 + b; // $ExpectType I4 | I5 + c; // $ExpectType I7 | I8 + }, (a, b, c) => { + a; // $ExpectType I2 | I3 + b; // $ExpectType I5 | I6 + c; // $ExpectType I8 | I9 + }, (a, b, c) => { + a; // $ExpectType I3 | I4 + b; // $ExpectType I6 | I7 + c; // $ExpectType I1 | I9 + }); + } + + // (value, Thenable) + { + const q = p.then(() => { + return 1; + }, () => { + return t1; + }); + + q.then((a) => { + a; // $ExpectType number | I1 + }, (a) => { + a; // never + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + + // (Thenable, value) + { + const q = p.then(() => { + return t1; + }, () => { + return 1; + }); + + q.then((a) => { + a; // $ExpectType number | I1 + }, (a) => { + a; // never + }, (a, b, c) => { + a; // $ExpectType never + b; // $ExpectType never + c; // $ExpectType never + }); + } + + // (value, Promise3) + { + const q = p.then(() => { + return 1; + }, () => { + return p1; + }); + + q.then((a, b, c) => { + a; // $ExpectType number | I1 + b; // $ExpectType I4 + c; // $ExpectType I7 + }, (a, b, c) => { + a; // $ExpectType I2 + b; // $ExpectType I5 + c; // $ExpectType I8 + }, (a, b, c) => { + a; // $ExpectType I3 + b; // $ExpectType I6 + c; // $ExpectType I9 + }); + } + + // (Promise3, value) + { + const q = p.then(() => { + return p1; + }, () => { + return 1; + }); + + q.then((a, b, c) => { + a; // $ExpectType number | I1 + b; // $ExpectType I4 + c; // $ExpectType I7 + }, (a, b, c) => { + a; // $ExpectType I2 + b; // $ExpectType I5 + c; // $ExpectType I8 + }, (a, b, c) => { + a; // $ExpectType I3 + b; // $ExpectType I6 + c; // $ExpectType I9 + }); + } + + // (Thenable, Promise3) + { + const q = p.then(() => { + return t1; + }, () => { + return p2; + }); + + q.then((a, b, c) => { + a; // $ExpectType I1 | I2 + b; // $ExpectType I5 + c; // $ExpectType I8 + }, (a, b, c) => { + a; // $ExpectType I3 + b; // $ExpectType I6 + c; // $ExpectType I9 + }, (a, b, c) => { + a; // $ExpectType I4 + b; // $ExpectType I7 + c; // $ExpectType I1 + }); + } + + // (Promise3, Thenable) + { + const q = p.then(() => { + return p1; + }, () => { + return t2; + }); + + q.then((a, b, c) => { + a; // $ExpectType I1 | I2 + b; // $ExpectType I4 + c; // $ExpectType I7 + }, (a, b, c) => { + a; // $ExpectType I2 + b; // $ExpectType I5 + c; // $ExpectType I8 + }, (a, b, c) => { + a; // $ExpectType I3 + b; // $ExpectType I6 + c; // $ExpectType I9 + }); + } + } + } + + function _catch() { + // $ExpectType Promise3 + $.ajax('/echo/json').catch(() => { + return 1; + }); + + // $ExpectType Promise3 + $.ajax('/echo/json').catch(() => { + return t1; + }); + + // $ExpectType Promise3, never, SuccessTextStatus, ErrorTextStatus, never, jqXHR, string, never> + $.ajax('/echo/json').catch(() => { + return $.ajax('/echo/json'); + }); + } +} + +function Promise2(p: JQuery.Promise2) { + function then() { + p.then((a, b) => { + a; // $ExpectType string + b; // $ExpectType JQuery + }, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType string + }, (a, b) => { + a; // $ExpectType number + b; // $ExpectType boolean + }); + + p.then(null, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType string + }, (a, b) => { + a; // $ExpectType number + b; // $ExpectType boolean + }); + + p.then((a, b) => { + a; // $ExpectType string + b; // $ExpectType JQuery + }, null, (a, b) => { + a; // $ExpectType number + b; // $ExpectType boolean + }); + + p.then(null, null, (a, b) => { + a; // $ExpectType number + b; // $ExpectType boolean + }); + + p.then((a, b) => { + a; // $ExpectType string + b; // $ExpectType JQuery + }, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType string + }, null); + + p.then((a, b) => { + a; // $ExpectType string + b; // $ExpectType JQuery + }, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType string + }); + + p.then(null, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType string + }, null); + + p.then(null, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType string + }); + + p.then((a, b) => { + a; // $ExpectType string + b; // $ExpectType JQuery + }, null, null); + + p.then((a, b) => { + a; // $ExpectType string + b; // $ExpectType JQuery + }, null); + + p.then((a, b) => { + a; // $ExpectType string + b; // $ExpectType JQuery + }); + + function doneFilter() { + p.then(() => { + return 1; + }).then((a) => { + a; // $ExpectType number + }); + + p.then(() => { + return $.ready; + }).then((a) => { + a; // $ExpectType JQueryStatic + }); + + p.then(() => { + return p; + }).then((a, b) => { + a; // $ExpectType string + b; // $ExpectType JQuery + }, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType string + }, (a, b) => { + a; // $ExpectType number + b; // $ExpectType boolean + }); + } + + function failFilter() { + p.then(null, () => { + return 1; + }).then((a) => { + a; // $ExpectType number + }); + + p.then(null, () => { + return $.ready; + }).then((a) => { + a; // $ExpectType JQueryStatic + }); + + p.then(null, () => { + return p; + }).then((a, b) => { + a; // $ExpectType string + b; // $ExpectType JQuery + }, (a, b) => { + a; // $ExpectType Error + b; // $ExpectType string + }, (a, b) => { + a; // $ExpectType number + b; // $ExpectType boolean + }); + } + } +} + +function _Promise(p: JQuery.Promise) { + function then() { + p.then((a) => { + a; // $ExpectType string + }, (a) => { + a; // $ExpectType Error + }, (a) => { + a; // $ExpectType number + }); + + p.then(null, (a) => { + a; // $ExpectType Error + }, (a) => { + a; // $ExpectType number + }); + + p.then((a) => { + a; // $ExpectType string + }, null, (a) => { + a; // $ExpectType number + }); + + p.then(null, null, (a) => { + a; // $ExpectType number + }); + + p.then((a) => { + a; // $ExpectType string + }, (a) => { + a; // $ExpectType Error + }, null); + + p.then((a) => { + a; // $ExpectType string + }, (a) => { + a; // $ExpectType Error + }); + + p.then(null, (a) => { + a; // $ExpectType Error + }, null); + + p.then(null, (a) => { + a; // $ExpectType Error + }); + + p.then((a) => { + a; // $ExpectType string + }, null, null); + + p.then((a) => { + a; // $ExpectType string + }, null); + + p.then((a) => { + a; // $ExpectType string + }); + + function doneFilter() { + p.then(() => { + return 1; + }).then((a) => { + a; // $ExpectType number + }); + + p.then(() => { + return $.ready; + }).then((a) => { + a; // $ExpectType JQueryStatic + }); + + p.then(() => { + return p; + }).then((a) => { + a; // $ExpectType string + }, (a) => { + a; // $ExpectType Error + }, (a) => { + a; // $ExpectType number + }); + } + + function failFilter() { + p.then(null, () => { + return 1; + }).then((a) => { + a; // $ExpectType number + }); + + p.then(null, () => { + return $.ready; + }).then((a) => { + a; // $ExpectType JQueryStatic + }); + + p.then(null, () => { + return p; + }).then((a) => { + a; // $ExpectType string + }, (a) => { + a; // $ExpectType Error + }, (a) => { + a; // $ExpectType number + }); + } + } +} diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 404aba2013..0c871de0a7 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -1202,14 +1202,13 @@ function examples() { // Attach a done, fail, and progress handler for the asyncEvent $.when(asyncEvent()).then( function(status) { - status === 3; alert(status + ', things are going well'); }, function(status) { alert(status + ', you fail this time'); }, function(status) { - // $('body').append(status); + $('body').append(status); }, ); } @@ -1233,9 +1232,7 @@ function examples() { // Use the object as a Promise _obj.done(function(name) { _obj.hello(name); // Will alert "Hello John" - }); - /// TODO: This doesn't work even though .done() returns this - // .hello('Karl'); // Will alert "Hello Karl" + }).hello('Karl'); // Will alert "Hello Karl" } function deferred_then_0() { @@ -1392,7 +1389,7 @@ function examples() { function each_2() { $('button').click(function() { $('div').each(function(index, element) { - // element == this + // element == this; $(element).css('backgroundColor', 'yellow'); if ($(this).is('#stop')) { $('span').text('Stopped at div index #' + index); @@ -3757,13 +3754,13 @@ function examples() { function offset_0() { var p = $('p:last'); - var offset = p.offset(); + var offset = p.offset()!; p.html('left: ' + offset.left + ', top: ' + offset.top); } function offset_1() { $('*', document.body).click(function(event) { - var offset = $(this).offset(); + var offset = $(this).offset()!; event.stopPropagation(); $('#result').text(this.tagName + ' coords ( ' + offset.left + ', ' + offset.top + ' )'); diff --git a/types/jquery/tslint.json b/types/jquery/tslint.json index 401b7a77e9..ca514c4aba 100644 --- a/types/jquery/tslint.json +++ b/types/jquery/tslint.json @@ -2,8 +2,9 @@ "extends": "dtslint/dt.json", "rules": { "ban-types": false, - "no-misused-new": false, + "callable-types": false, "no-empty-interface": false, - "callable-types": false + "no-misused-new": false, + "space-before-function-paren": false } } diff --git a/types/jsdom/index.d.ts b/types/jsdom/index.d.ts index ca17ea4bbf..ca2a1aad41 100644 --- a/types/jsdom/index.d.ts +++ b/types/jsdom/index.d.ts @@ -12,17 +12,17 @@ import * as tough from 'tough-cookie'; import { Script } from 'vm'; export class JSDOM { - static fromURL(url: string | Buffer | jsdom.BinaryData, options?: jsdom.FromUrlOptions | object): Promise; + static fromURL(url: string, options?: FromUrlOptions): Promise; - static fromFile(url: string | Buffer | jsdom.BinaryData, options?: jsdom.Options | object): Promise; + static fromFile(url: string, options?: FromFileOptions): Promise; static fragment(html: string): DocumentFragment; - constructor(html?: string | Buffer | jsdom.BinaryData, options?: jsdom.Options | object); + constructor(html?: string | Buffer | BinaryData, options?: ConstructorOptions); - readonly window: jsdom.Window; - readonly virtualConsole: jsdom.VirtualConsole; - readonly cookieJar: jsdom.CookieJar; + readonly window: DOMWindow; + readonly virtualConsole: VirtualConsole; + readonly cookieJar: CookieJar; /** * The serialize() method will return the HTML serialization of the document, including the doctype. @@ -42,97 +42,87 @@ export class JSDOM { */ runVMScript(script: Script): void; - reconfigure(settings: jsdom.ReconfigureSettings | object): void; + reconfigure(settings: ReconfigureSettings): void; } -// Alias DOM Window so we can extend from it and still name the type Window -// tslint:disable-next-line strict-export-declare-modifiers -type DOMWindow = Window; - -export namespace jsdom { - interface FromUrlOptions extends Pick { } - - namespace FromUrlOptions { - interface _Impl { - /** - * referrer just affects the value read from document.referrer. - * It defaults to no referrer (which reflects as the empty string). - */ - referrer: string; - /** - * userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources. - * It defaults to `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`. - */ - userAgent: string; - /** - * includeNodeLocations preserves the location info produced by the HTML parser, - * allowing you to retrieve it with the nodeLocation() method (described below). - * It defaults to false to give the best performance, - * and cannot be used with an XML content type since our XML parser does not support location info. - */ - includeNodeLocations: boolean; - runScripts: 'dangerously' | 'outside-only'; - resources: 'usable'; - virtualConsole: VirtualConsole; - cookieJar: CookieJar; - beforeParse(window: jsdom.Window): void; - } - } - - interface Options extends Pick { } - - namespace Options { - interface _Impl extends FromUrlOptions._Impl { - /** - * url sets the value returned by window.location, document.URL, and document.documentURI, - * and affects things like resolution of relative URLs within the document - * and the same-origin restrictions and referrer used while fetching subresources. - * It defaults to "about:blank". - */ - url: string; - /** - * contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML. - * Values that are not "text/html" or an XML mime type will throw. It defaults to "text/html". - */ - contentType: string; - } - } - - interface Window extends DOMWindow { - ran: number; - - eval(script: string): void; - } - - type BinaryData = ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; - - class VirtualConsole extends EventEmitter { - on(method: K, callback: Console[K]): this; - on(event: 'jsdomError', callback: (e: Error) => void): this; - - sendTo(console: Console, options?: VirtualConsole.SendToOptions | object): this; - } - - namespace VirtualConsole { - interface SendToOptions extends Pick { } - - namespace SendToOptions { - interface _Impl { - omitJSDOMErrors: boolean; - } - } - } - - class CookieJar extends tough.CookieJar { } - - const toughCookie: typeof tough; - - interface ReconfigureSettings extends Pick { } - - namespace ReconfigureSettings { - interface _Impl { - windowTop: DOMWindow; - url: string; - } - } +export interface Options { + /** + * referrer just affects the value read from document.referrer. + * It defaults to no referrer (which reflects as the empty string). + */ + referrer?: string; + /** + * userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources. + * It defaults to `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`. + */ + userAgent?: string; + /** + * includeNodeLocations preserves the location info produced by the HTML parser, + * allowing you to retrieve it with the nodeLocation() method (described below). + * It defaults to false to give the best performance, + * and cannot be used with an XML content type since our XML parser does not support location info. + */ + includeNodeLocations?: boolean; + runScripts?: 'dangerously' | 'outside-only'; + resources?: 'usable'; + virtualConsole?: VirtualConsole; + cookieJar?: CookieJar; + beforeParse?(window: DOMWindow): void; +} + +export type FromUrlOptions = Options; + +export type FromFileOptions = Options & { + /** + * url sets the value returned by window.location, document.URL, and document.documentURI, + * and affects things like resolution of relative URLs within the document + * and the same-origin restrictions and referrer used while fetching subresources. + * It will default to a file URL corresponding to the given filename, instead of to "about:blank". + */ + url?: string; + /** + * contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML. + * Values that are not "text/html" or an XML mime type will throw. It will default to "application/xhtml+xml" if + * the given filename ends in .xhtml or .xml; otherwise it will continue to default to "text/html". + */ + contentType?: string; +}; + +export type ConstructorOptions = Options & { + /** + * url sets the value returned by window.location, document.URL, and document.documentURI, + * and affects things like resolution of relative URLs within the document + * and the same-origin restrictions and referrer used while fetching subresources. + * It defaults to "about:blank". + */ + url?: string; + /** + * contentType affects the value read from document.contentType, and how the document is parsed: as HTML or as XML. + * Values that are not "text/html" or an XML mime type will throw. It defaults to "text/html". + */ + contentType?: string; +}; + +export interface DOMWindow extends Window { eval(script: string): void; } + +export type BinaryData = ArrayBuffer | DataView | Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; + +export class VirtualConsole extends EventEmitter { + on(method: K, callback: Console[K]): this; + on(event: 'jsdomError', callback: (e: Error) => void): this; + + sendTo(console: Console, options?: VirtualConsoleSendToOptions): this; +} + +export interface VirtualConsoleSendToOptions { + omitJSDOMErrors: boolean; +} + +export class CookieJar extends tough.CookieJar { } + +export const toughCookie: typeof tough; + +export interface ReconfigureSettings { + windowTop?: DOMWindow; + url?: string; } diff --git a/types/jsdom/jsdom-tests.ts b/types/jsdom/jsdom-tests.ts index 4c80bd2571..c672580a63 100644 --- a/types/jsdom/jsdom-tests.ts +++ b/types/jsdom/jsdom-tests.ts @@ -1,5 +1,5 @@ -import { jsdom, JSDOM } from 'jsdom'; -import { CookieJar, MemoryCookieStore } from 'tough-cookie'; +import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow } from 'jsdom'; +import { CookieJar as ToughCookieJar, MemoryCookieStore } from 'tough-cookie'; import { Script } from 'vm'; function test_basic_usage() { @@ -37,7 +37,7 @@ function test_executing_scripts3() { } function test_virtualConsole() { - const virtualConsole = new jsdom.VirtualConsole(); + const virtualConsole = new VirtualConsole(); const dom = new JSDOM(``, { virtualConsole }); virtualConsole.on('error', () => { }); @@ -54,9 +54,9 @@ function test_virtualConsole() { function test_cookieJar() { const store = {} as MemoryCookieStore; - const options = {} as CookieJar.Options; + const options = {} as ToughCookieJar.Options; - const cookieJar = new jsdom.CookieJar(store, options); + const cookieJar = new CookieJar(store, options); const dom = new JSDOM(``, { cookieJar }); } @@ -111,11 +111,11 @@ function test_runVMScript() { dom.runVMScript(s); dom.runVMScript(s); - dom.window.ran === 3; + ( dom.window).ran === 3; } function test_reconfigure() { - const myFakeTopForTesting = {} as Window; + const myFakeTopForTesting = {} as DOMWindow; const dom = new JSDOM(); @@ -129,7 +129,7 @@ function test_reconfigure() { } function test_fromURL() { - const options = {} as jsdom.FromUrlOptions; + const options = {} as FromUrlOptions; JSDOM.fromURL('https://example.com/', options).then(dom => { console.log(dom.serialize()); @@ -137,7 +137,7 @@ function test_fromURL() { } function test_fromFile() { - const options = {} as jsdom.Options; + const options = {} as FromFileOptions; JSDOM.fromFile('stuff.html', options).then(dom => { console.log(dom.serialize()); diff --git a/types/jsonp/index.d.ts b/types/jsonp/index.d.ts new file mode 100644 index 0000000000..3f1df60c87 --- /dev/null +++ b/types/jsonp/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for jsonp 0.2 +// Project: https://github.com/LearnBoost/jsonp +// Definitions by: Savva Surenkov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = jsonp; + +declare function jsonp(url: string, options?: Options, cb?: RequestCallback): CancelFn; +declare function jsonp(url: string, callback?: RequestCallback): CancelFn; + +type CancelFn = () => void; +type RequestCallback = (error: Error | null, data: any) => void; + +interface Options { + param?: string; + prefix?: string; + name?: string; + timeout?: number; +} diff --git a/types/jsonp/jsonp-tests.ts b/types/jsonp/jsonp-tests.ts new file mode 100644 index 0000000000..703e104912 --- /dev/null +++ b/types/jsonp/jsonp-tests.ts @@ -0,0 +1,28 @@ +import jsonp = require('jsonp'); + +/** + * Dummy response callback. + */ +const print = (err: Error | null, data: any) => + console.log(err !== null ? err.message : data); + +/** + * Tests jsonp request with default parameters. + */ +const cancel1 = jsonp('https://jsonplaceholder.typicode.com/posts/1', print); +cancel1(); + +/** + * Tests parametrized jsonp request. + */ +const cancel2 = jsonp( + 'https://jsonplaceholder.typicode.com/posts/1', + { + param: 'cb', + timeout: 40000, + prefix: '_jsonp', + name: 'func', + }, + print, +); +cancel2(); diff --git a/types/jsonp/tsconfig.json b/types/jsonp/tsconfig.json new file mode 100644 index 0000000000..4ba94d9d89 --- /dev/null +++ b/types/jsonp/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "jsonp-tests.ts" + ] +} diff --git a/types/jsonp/tslint.json b/types/jsonp/tslint.json new file mode 100644 index 0000000000..a62d0d4e68 --- /dev/null +++ b/types/jsonp/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false + } +} diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts index a7c08661d2..4df241d8d4 100644 --- a/types/knex/index.d.ts +++ b/types/knex/index.d.ts @@ -401,14 +401,14 @@ declare namespace Knex { comment(val: string): TableBuilder; specificType(columnName: string, type: string): ColumnBuilder; primary(columnNames: string[]): TableBuilder; - index(columnNames: string[], indexName?: string, indexType?: string): TableBuilder; - unique(columnNames: string[], indexName?: string): TableBuilder; + index(columnNames: (string | Raw)[], indexName?: string, indexType?: string): TableBuilder; + unique(columnNames: (string | Raw)[], indexName?: string): TableBuilder; foreign(column: string): ForeignConstraintBuilder; foreign(columns: string[]): MultikeyForeignConstraintBuilder; dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; - dropUnique(columnNames: string[], indexName?: string): TableBuilder; + dropUnique(columnNames: (string | Raw)[], indexName?: string): TableBuilder; dropPrimary(constraintName?: string): TableBuilder; - dropIndex(columnNames: string[], indexName?: string): TableBuilder; + dropIndex(columnNames: (string | Raw)[], indexName?: string): TableBuilder; } interface CreateTableBuilder extends TableBuilder { diff --git a/types/leaflet-draw/index.d.ts b/types/leaflet-draw/index.d.ts index 22d0d45169..cf535930a6 100644 --- a/types/leaflet-draw/index.d.ts +++ b/types/leaflet-draw/index.d.ts @@ -40,35 +40,35 @@ declare namespace L { * * Default value: {} */ - polyline?: DrawOptions.PolylineOptions; + polyline?: DrawOptions.PolylineOptions | false; /** * Polygon draw handler options. Set to false to disable handler. * * Default value: {} */ - polygon?: DrawOptions.PolygonOptions; + polygon?: DrawOptions.PolygonOptions | false; /** * Rectangle draw handler options. Set to false to disable handler. * * Default value: {} */ - rectangle?: DrawOptions.RectangleOptions; + rectangle?: DrawOptions.RectangleOptions | false; /** * Circle draw handler options. Set to false to disable handler. * * Default value: {} */ - circle?: DrawOptions.CircleOptions; + circle?: DrawOptions.CircleOptions | false; /** * Marker draw handler options. Set to false to disable handler. * * Default value: {} */ - marker?: DrawOptions.MarkerOptions; + marker?: DrawOptions.MarkerOptions | false; } interface EditOptions { @@ -85,14 +85,14 @@ declare namespace L { * * Default value: null */ - edit?: DrawOptions.EditHandlerOptions; + edit?: DrawOptions.EditHandlerOptions | false; /** * Delete handler options. Set to false to disable handler. * * Default value: null */ - remove?: DrawOptions.DeleteHandlerOptions; + remove?: DrawOptions.DeleteHandlerOptions | false; } interface Draw extends Control { diff --git a/types/leaflet-draw/leaflet-draw-tests.ts b/types/leaflet-draw/leaflet-draw-tests.ts index 21c08e21e9..db6548d844 100644 --- a/types/leaflet-draw/leaflet-draw-tests.ts +++ b/types/leaflet-draw/leaflet-draw-tests.ts @@ -45,3 +45,27 @@ map.on(L.Draw.Event.CREATED, (e: L.DrawEvents.Created) => { let examplePolygon: L.LatLngLiteral[] = [{lng: 0, lat: 0}, {lng: 10, lat: 0}, {lng: 10, lat: 10}, {lng: 0, lat: 10}, {lng: 0, lat: 0}]; let examplePolygonArea: number = L.GeometryUtil.geodesicArea(examplePolygon); L.GeometryUtil.readableArea(examplePolygonArea, true); + +function testBooleanControlOptions() { + const drawControl = new L.Control.Draw({ + position: 'topleft' , + draw: { + polygon: { + allowIntersection: false, + drawError: { + color: '#b00b00', + timeout: 1000 + }, + shapeOptions: { + color: '#bada55' + }, + showArea: true + }, + polyline: {}, + circle: false + }, + edit: { + featureGroup: drawnItems + } + }); +} diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index 80adf4bc3f..951bc4b22d 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -399,7 +399,7 @@ declare namespace L { class Layer extends Evented { constructor(options?: LayerOptions); - addTo(map: Map): this; + addTo(map: Map|LayerGroup): this; remove(): this; removeFrom(map: Map): this; getPane(name?: string): HTMLElement | undefined; diff --git a/types/license-checker/index.d.ts b/types/license-checker/index.d.ts new file mode 100644 index 0000000000..ec4ec39658 --- /dev/null +++ b/types/license-checker/index.d.ts @@ -0,0 +1,87 @@ +// Type definitions for license-checker 11.0 +// Project: https://github.com/davglass/license-checker +// Definitions by: Rogier Schouten +// Definitions: https://github.com/borisyankov/DefinitelyTyped + +/** + * Options struct for the init() function + */ +export interface InitOpts { + /** + * Path to start checking dependencies from + */ + start: string; + /** + * only show production dependencies + */ + production?: boolean; + /** + * only show development dependencies + */ + development?: boolean; + /** + * report guessed licenses as unknown licenses + */ + unknown?: boolean; + /** + * only list packages with unknown or guessed licenses + */ + onlyunknown?: boolean; + /** + * to add a custom Format file in JSON + */ + customPath?: string; + /** + * exclude modules which licenses are in the comma-separated list from the output + */ + exclude?: string[]; + /** + * Use chalk to colorize the licenses member of each returned module info. Unknown licenses become red. + */ + color?: boolean; + /** + * output the location of the license files as relative paths + */ + relativeLicensePath?: boolean; +} + +/** + * Information about one dependency + */ +export interface ModuleInfo { + /** + * licenses, either one string or an array of multiple licenses + */ + licenses: string | string[]; + /** + * Repository URL + */ + repository: string; + /** + * Publisher name + */ + publisher?: string; + /** + * Publisher e-mail + */ + email?: string; + /** + * Publisher URL + */ + url?: string; + /** + * Path to license file, if available + */ + licenseFile?: string; +} + +export interface ModuleInfos { + [packageName: string]: ModuleInfo; +} + +/** + * Run the license check + * @param opts specifies the path to the module to check dependencies of + * @param callback + */ +export function init(opts: InitOpts, callback: (err: Error, ret: ModuleInfos) => void): void; diff --git a/types/license-checker/license-checker-tests.ts b/types/license-checker/license-checker-tests.ts new file mode 100644 index 0000000000..0caf98a373 --- /dev/null +++ b/types/license-checker/license-checker-tests.ts @@ -0,0 +1,13 @@ +// From README.md: + +import * as checker from 'license-checker'; + +checker.init({ + start: '/path/to/start/looking' +}, (err: Error, json: checker.ModuleInfos): void => { + if (err) { + // Handle error + } else { + // The sorted json data + } +}); diff --git a/types/license-checker/tsconfig.json b/types/license-checker/tsconfig.json new file mode 100644 index 0000000000..4560756381 --- /dev/null +++ b/types/license-checker/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", + "license-checker-tests.ts" + ] +} diff --git a/types/license-checker/tslint.json b/types/license-checker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/license-checker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index ae7f70fdb0..172000d6b8 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Lo-Dash 4.14 // Project: http://lodash.com/ -// Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk , Eric L Anderson +// Definitions by: Brian Zengel , Ilya Mochalov , Stepan Mikhaylyuk , Eric L Anderson , AJ Richardson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -485,7 +485,7 @@ declare namespace _ { * @param array The array to compact. * @return (Array) Returns the new array of filtered values. */ - compact(array?: List | null | undefined): T[]; + compact(array?: List | null | undefined): T[]; } interface LoDashImplicitArrayWrapperBase { @@ -9604,7 +9604,6 @@ declare namespace _ { some( predicate?: ListIterator|DictionaryIterator|NumericDictionaryIterator|ObjectIterator ): boolean; - /** * @see _.some */ @@ -12011,7 +12010,12 @@ declare namespace _ { * * @return Returns true if value is correctly classified, else false. */ - isArray(value?: any): value is T[]; + isArray(value?: any): value is any[]; + + /** + * DEPRECATED + */ + isArray(value?: any): value is any[]; } interface LoDashImplicitWrapperBase { @@ -12080,7 +12084,22 @@ declare namespace _ { * _.isArrayLike(_.noop); * // => false */ - isArrayLike(value?: any): value is T[]; + isArrayLike(value: T & string & number): boolean; // should only match if T = any + + /** + * @see _.isArrayLike + */ + isArrayLike(value?: Function): value is never; + + /** + * @see _.isArrayLike + */ + isArrayLike(value: T | Function): value is T & { length: number }; + + /** + * DEPRECATED + */ + isArrayLike(value?: any): value is any[]; } interface LoDashImplicitWrapperBase { @@ -12123,7 +12142,22 @@ declare namespace _ { * _.isArrayLikeObject(_.noop); * // => false */ - isArrayLikeObject(value?: any): value is T[]; + isArrayLikeObject(value: T & string & number): boolean; // should only match if T = any + + /** + * @see _.isArrayLike + */ + isArrayLikeObject(value?: Function | string | boolean | number): value is never; + + /** + * @see _.isArrayLike + */ + isArrayLikeObject(value: T | Function | string | boolean | number): value is T & { length: number }; + + /** + * DEPRECATED + */ + isArrayLikeObject(value?: any): value is any[]; } interface LoDashImplicitWrapperBase { @@ -13283,6 +13317,48 @@ declare namespace _ { toPlainObject(): LoDashImplicitObjectWrapper; } + //_.toFinite + interface LoDashStatic { + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + toFinite(value: any): number; + } + + interface LoDashImplicitWrapperBase { + /** + * @see _.toFinite + */ + toFinite(): LoDashImplicitWrapper; + } + + interface LoDashExplicitWrapperBase { + /** + * @see _.toFinite + */ + toFinite(): LoDashExplicitWrapper; + } + //_.toInteger interface LoDashStatic { /** diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 1f7eabd3cb..4721e9381d 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -207,6 +207,8 @@ namespace TestChunk { namespace TestCompact { let array: TResult[] | null | undefined = [] as any; let list: _.List | null | undefined = [] as any; + let array2: Array | null | undefined = any; + let list2: _.List | null | undefined = any; { let result: TResult[]; @@ -214,6 +216,8 @@ namespace TestCompact { result = _.compact(); result = _.compact(array); result = _.compact(list); + result = _.compact(array2); + result = _.compact(list2); } { @@ -6899,18 +6903,13 @@ namespace TestisArguments { // _.isArray namespace TestIsArray { { - let value: number|string[]|boolean[] = []; + let value: number|string[]|boolean[] = any; - if (_.isArray(value)) { - let result: string[] = value; + if (_.isArray(value)) { + value; // $ExpectType boolean[] | string[] } else { - if (_.isArray(value)) { - let result: boolean[] = value; - } - else { - let result: number = value; - } + value; // $ExpectType number } } @@ -6935,13 +6934,13 @@ namespace TestIsArray { // _.isArrayBuffer namespace TestIsArrayBuffer { { - let value: ArrayBuffer|number = 0; + let value: ArrayBuffer|number = any; if (_.isArrayBuffer(value)) { - let result: ArrayBuffer = value; + value; // $ExpectType ArrayBuffer } else { - let result: number = value; + value; // $ExpectType number } } @@ -6966,18 +6965,59 @@ namespace TestIsArrayBuffer { // _.isArrayLike namespace TestIsArrayLike { { - let value: number|string[]|boolean[] = []; + let value: string | string[] | { [index: number]: boolean, length: number } | [number, boolean] + | number | Function | { length: string } | { a: string } + = any; - if (_.isArrayLike(value)) { - let result: string[] = value; + if (_.isArrayLike(value)) { + let result: string | string[] | { [index: number]: boolean, length: number } | [number, boolean] = value; } else { - if (_.isArrayLike(value)) { - let result: boolean[] = value; - } - else { - let result: number = value; - } + let result: number | Function | { length: string } | { a: string; } = value; + } + } + + { + let value: boolean[] = any; + + if (_.isArrayLike(value)) { + let result: boolean[] = value; + } + else { + value; // $ExpectType never + } + } + + { + let value: Function = any; + + if (_.isArrayLike(value)) { + value; // $ExpectType never + } + else { + value; // $ExpectType Function + } + } + + { + let value: { a: string } = any; + + if (_.isArrayLike(value)) { + let result: { a: string, length: number } = value; + } + else { + value; // $ExpectType { a: string; } + } + } + + { + let value: any = any; + + if (_.isArrayLike(value)) { + value; // $ExpectType any + } + else { + value; // $ExpectType any } } @@ -7002,18 +7042,59 @@ namespace TestIsArrayLike { // _.isArrayLikeObject namespace TestIsArrayLikeObject { { - let value: number|string[]|boolean[] = []; + let value: string[] | { [index: number]: boolean, length: number } | [number, boolean] + | number | string | Function | { length: string } | { a: string } + = any; - if (_.isArrayLikeObject(value)) { - let result: string[] = value; + if (_.isArrayLikeObject(value)) { + let result: string[] | { [index: number]: boolean, length: number } | [number, boolean] = value; } else { - if (_.isArrayLikeObject(value)) { - let result: boolean[] = value; - } - else { - let result: number = value; - } + let result: string | number | Function | { length: string; } | { a: string; } = value; + } + } + + { + let value: boolean[] = any; + + if (_.isArrayLikeObject(value)) { + let result: boolean[] = value; + } + else { + value; // $ExpectType never + } + } + + { + let value: string | Function = any; + + if (_.isArrayLikeObject(value)) { + value; // $ExpectType never + } + else { + value; // $ExpectType string | Function + } + } + + { + let value: { a: string } = any; + + if (_.isArrayLikeObject(value)) { + let result: { a: string, length: number } = value; + } + else { + value; // $ExpectType { a: string; } + } + } + + { + let value: any = any; + + if (_.isArrayLikeObject(value)) { + value; // $ExpectType any + } + else { + value; // $ExpectType any } } @@ -7933,13 +8014,36 @@ namespace TestToPlainObject { } } +// _.toFinite +namespace TestToFinite { + { + let result: number; + result = _.toFinite(true); + result = _.toFinite(1); + result = _.toFinite('3.2'); + result = _.toFinite([]); + result = _.toFinite({}); + } + + { + let result: _.LoDashImplicitWrapper; + + result = _(true).toFinite(); + result = _(1).toFinite(); + result = _('3.2').toFinite(); + result = _([1]).toFinite(); + result = _([]).toFinite(); + result = _({}).toFinite(); + } +} + // _.toInteger namespace TestToInteger { { let result: number; result = _.toInteger(true); result = _.toInteger(1); - result = _.toInteger('a'); + result = _.toInteger('3.2'); result = _.toInteger([]); result = _.toInteger({}); } diff --git a/types/lodash/toFinite/index.d.ts b/types/lodash/toFinite/index.d.ts new file mode 100644 index 0000000000..f0317af649 --- /dev/null +++ b/types/lodash/toFinite/index.d.ts @@ -0,0 +1,2 @@ +import { toFinite } from "../index"; +export = toFinite; diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index 55cecd6166..e1f7296a79 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -248,6 +248,7 @@ "thru/index.d.ts", "times/index.d.ts", "toArray/index.d.ts", + "toFinite/index.d.ts", "toInteger/index.d.ts", "toLength/index.d.ts", "toLower/index.d.ts", diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 680362fe82..5e08da57b6 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.39.0 +// Type definitions for Mapbox GL JS v0.39.1 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -706,7 +706,7 @@ declare namespace mapboxgl { angleWidth(p: Point): number; angleWithSep(x: number, y: number): number; - + convert(a: Array | Point): Point; } @@ -1045,7 +1045,7 @@ declare namespace mapboxgl { export interface CirclePaint { "circle-radius"?: number | StyleFunction; "circle-radius-transition"?: Transition; - "circle-color"?: string; + "circle-color"?: string | StyleFunction; "circle-blur"?: number | StyleFunction; "circle-opacity"?: number | StyleFunction; "circle-translate"?: number[]; diff --git a/types/massive/index.d.ts b/types/massive/index.d.ts index ccf6469d91..b7132ab910 100644 --- a/types/massive/index.d.ts +++ b/types/massive/index.d.ts @@ -50,9 +50,11 @@ declare namespace massive { count(criteria: object): Promise; where(query: string, params: any[] | object): Promise; search(criteria: SearchCriteria, queryOptions?: QueryOptions): Promise; - save(data: object | object[]): Promise | Promise; - insert(data: object | object[]): Promise | Promise; - update(dataOrCriteria: object | object[], changesMap?: object): Promise | Promise; + save(data: object): Promise; + insert(data: object): Promise; + insert(data: object[]): Promise; + update(dataOrCriteria: object, changesMap?: object): Promise; + update(dataOrCriteria: object[], changesMap?: object): Promise; destroy(criteria: object): Promise; } diff --git a/types/material-ui/index.d.ts b/types/material-ui/index.d.ts index 16c6b5dce7..386a83c93d 100644 --- a/types/material-ui/index.d.ts +++ b/types/material-ui/index.d.ts @@ -8,6 +8,7 @@ // Aurelién Allienne // Matthias Schlesinger // Jonathon Kelly +// Artyom Stukans // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -1057,6 +1058,7 @@ declare namespace __MaterialUI { title?: React.ReactNode; titleBackground?: string; titlePosition?: "top" | "bottom"; + titleStyle?: React.CSSProperties; onTouchTap?: TouchTapEventHandler; } export class GridTile extends React.Component { diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 18e627ebfc..311e696c8a 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for MongoDB v2.2 // Project: https://github.com/mongodb/node-mongodb-native/tree/2.2 // Definitions by: Federico Caselli +// Alan Marcell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -585,10 +586,10 @@ export interface Collection { rename(newName: string, callback: MongoCallback>): void; rename(newName: string, options?: { dropTarget?: boolean }): Promise>; rename(newName: string, options: { dropTarget?: boolean }, callback: MongoCallback>): void; - //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#replaceOne - replaceOne(filter: Object, doc: Object, callback: MongoCallback): void; - replaceOne(filter: Object, doc: Object, options?: ReplaceOneOptions): Promise; - replaceOne(filter: Object, doc: Object, options: ReplaceOneOptions, callback: MongoCallback): void; + //http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#replaceOne + replaceOne(filter: Object, doc: Object, callback: MongoCallback }>): void; + replaceOne(filter: Object, doc: Object, options?: ReplaceOneOptions): Promise }>; + replaceOne(filter: Object, doc: Object, options: ReplaceOneOptions, callback: MongoCallback }>): void; //http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html#save /** @deprecated Use insertOne, insertMany, updateOne or updateMany */ save(doc: Object, callback: MongoCallback): void; diff --git a/types/mongoose-simple-random/index.d.ts b/types/mongoose-simple-random/index.d.ts index cf41c64241..16b1c21483 100644 --- a/types/mongoose-simple-random/index.d.ts +++ b/types/mongoose-simple-random/index.d.ts @@ -2,9 +2,17 @@ // Project: https://github.com/larryprice/mongoose-simple-random // Definitions by: My Self // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// -// tslint:disable-next-line no-single-declare-module +declare module 'mongoose-simple-random' { + import mongoose = require('mongoose'); + // Dummy function allows to avoid hard to kill or fix tslint warning + // (exporting pluginFunc will make this a non-importable module) + function pluginFunc(schema: mongoose.Schema): void; + // Let allows typescript to still use ES2015 style imports + let plugin: typeof pluginFunc; + export = plugin; +} + declare module "mongoose" { interface Model extends NodeJS.EventEmitter, ModelProperties { findRandom(conditions: Object, projection?: Object | null, options?: Object | null, callback?: (err: any, res: T[]) => void) diff --git a/types/mongoose-simple-random/mongoose-simple-random-tests.ts b/types/mongoose-simple-random/mongoose-simple-random-tests.ts index 2aa9e18296..f5b26dbebb 100644 --- a/types/mongoose-simple-random/mongoose-simple-random-tests.ts +++ b/types/mongoose-simple-random/mongoose-simple-random-tests.ts @@ -1,4 +1,5 @@ import * as mongoose from 'mongoose'; +import * as mongoose_simple_random from "mongoose-simple-random"; // test compatibility with other libraries - from @types/mongoose import * as _ from 'lodash'; @@ -13,3 +14,5 @@ mongoose.Model.findRandom({ }, {}, { limit: 1 }, (error, data) => { if (error) { console.error("Error!"); } else { console.log("Success!"); } }); + +mongoose.plugin(mongoose_simple_random); diff --git a/types/noble/index.d.ts b/types/noble/index.d.ts index 4f2b5f0b7c..d62b0609a8 100644 --- a/types/noble/index.d.ts +++ b/types/noble/index.d.ts @@ -4,6 +4,7 @@ // Hans Bakker // Shantanu Bhadoria // Luke Libraro +// Dan Chao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -88,6 +89,8 @@ export declare class Characteristic extends events.EventEmitter { notify(notify: boolean, callback?: (error: string) => void): void; discoverDescriptors(callback?: (error: string, descriptors: Descriptor[]) => void): void; toString(): string; + subscribe(callback?: (error: string) => void): void; + unsubscribe(callback?: (error: string) => void): void; on(event: string, listener: Function): this; on(event: string, option: boolean, listener: Function): this; diff --git a/types/noble/noble-tests.ts b/types/noble/noble-tests.ts index baa65c5662..c790f2deb0 100644 --- a/types/noble/noble-tests.ts +++ b/types/noble/noble-tests.ts @@ -87,6 +87,10 @@ characteristic.on("write", true, (error: string): void => {}); characteristic.on("broadcast", (state: string): void => {}); characteristic.on("notify", (state: string): void => {}); characteristic.on("descriptorsDiscover", (descriptors: noble.Descriptor[]): void => {}); +characteristic.subscribe(); +characteristic.subscribe((error: string) => {}); +characteristic.unsubscribe(); +characteristic.unsubscribe((error: string) => {}); var descriptor: noble.Descriptor = new noble.Descriptor(); descriptor.uuid = ""; diff --git a/types/node/index.d.ts b/types/node/index.d.ts index bcb4db0bef..4fbcfd8279 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -8,6 +8,7 @@ // Wilco Bakker // Nicolas Voigt // Chigozirim C. +// Flarna // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -1730,7 +1731,7 @@ declare module "readline" { export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): ReadLine; export function createInterface(options: ReadLineOptions): ReadLine; - export function cursorTo(stream: NodeJS.WritableStream, x: number, y: number): void; + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; export function clearLine(stream: NodeJS.WritableStream, dir: number): void; export function clearScreenDown(stream: NodeJS.WritableStream): void; @@ -4518,3 +4519,68 @@ declare module "_debugger" { new (): ClientInstance } } + + +/** + * Async Hooks module: https://nodejs.org/api/async_hooks.html + */ +declare module "async_hooks" { + /** + * Returns the asyncId of the current execution context. + */ + export function currentId(): number; + + /** + * Returns the ID of the resource responsible for calling the callback that is currently being executed. + */ + export function triggerId(): number; + + export interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId a unique ID for the async resource + * @param type the type of the async resource + * @param triggerId the unique ID of the async resource in whose execution context this async resource was created + * @param resource reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerId: number, resource: Object): void; + + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + + /** + * Called immediately after the callback specified in before is completed. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + + export interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + + /** + * Registers functions to be called for different lifetime events of each async operation. + * @param options the callbacks to register + * @return an AsyncHooks instance used for disabling and enabling hooks + */ + export function createHook(options: HookCallbacks): AsyncHook; +} diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index a31f3e8899..fef0cd9862 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -26,6 +26,7 @@ import * as timers from "timers"; import * as repl from "repl"; import * as v8 from "v8"; import * as dns from "dns"; +import * as async_hooks from "async_hooks"; // Specifically test buffer module regression. import {Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer} from "buffer"; @@ -1409,6 +1410,7 @@ namespace readline_tests { let x: number; let y: number; + readline.cursorTo(stream, x); readline.cursorTo(stream, x, y); } @@ -2504,3 +2506,19 @@ client.connect(8888, 'localhost'); client.listbreakpoints((err, body, packet) => { }); + +//////////////////////////////////////////////////// +/// AsyncHooks tests : https://nodejs.org/api/async_hooks.html +//////////////////////////////////////////////////// +namespace async_hooks_tests { + const hooks: async_hooks.HookCallbacks = { + init: (asyncId: number, type: string, triggerId: number, resource: object) => void {}, + before: (asyncId: number) => void {}, + after: (asyncId: number) => void {}, + destroy: (asyncId: number) => void {} + }; + + const asyncHook = async_hooks.createHook(hooks); + + asyncHook.enable().disable().enable(); +} diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index 197707058b..918603be84 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -3514,6 +3514,12 @@ declare module 'paper' { * @param highlight [optional] - */ constructor(color: Gradient, origin: Point, destination: Point, highlight?: Point); + + /** + * Creates a RGB Color object. + * @param hex - the RGB color in hex, i.e. #000000 + */ + constructor(hex: string); /** * The type of the color as a string. diff --git a/types/passport-jwt/index.d.ts b/types/passport-jwt/index.d.ts index bbf96be851..066921efe6 100644 --- a/types/passport-jwt/index.d.ts +++ b/types/passport-jwt/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for passport-jwt 2.0 // Project: https://github.com/themikenicholson/passport-jwt // Definitions by: TANAKA Koichi +// Alex Young // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import {Strategy as PassportStrategy} from 'passport-strategy'; @@ -12,7 +13,7 @@ export declare class Strategy extends PassportStrategy { } export interface StrategyOptions { - secretOrKey: string; + secretOrKey: string | Buffer; jwtFromRequest: JwtFromRequestFunction; issuer?: string; audience?: string; diff --git a/types/passport-jwt/passport-jwt-tests.ts b/types/passport-jwt/passport-jwt-tests.ts index 07b8deb1f4..1dd2baeb1e 100644 --- a/types/passport-jwt/passport-jwt-tests.ts +++ b/types/passport-jwt/passport-jwt-tests.ts @@ -33,5 +33,6 @@ opts.jwtFromRequest = ExtractJwt.fromUrlQueryParameter('param_name'); opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('param_name'); opts.jwtFromRequest = ExtractJwt.fromExtractors([ExtractJwt.fromHeader('x-api-key'), ExtractJwt.fromBodyField('field_name'), ExtractJwt.fromUrlQueryParameter('param_name')]); opts.jwtFromRequest = (req: Request) => { return req.query.token; }; +opts.secretOrKey = new Buffer('secret'); declare function findUser(condition: {id: string}, callback: (error: any, user :any) => void): void; diff --git a/types/passport-local-mongoose/index.d.ts b/types/passport-local-mongoose/index.d.ts index 8a2d036c9f..2e3377a9b8 100644 --- a/types/passport-local-mongoose/index.d.ts +++ b/types/passport-local-mongoose/index.d.ts @@ -19,8 +19,8 @@ declare module 'mongoose' { // statics interface PassportLocalModel extends Model { authenticate(): (username: string, password: string, cb: (err: any, res: T, error: any) => void) => void; - serializeUser(): (user: PassportLocalModel, cb: (err: any) => void) => void; - deserializeUser(): (username: string, cb: (err: any) => void) => void; + serializeUser(): (user: PassportLocalModel, cb: (err: any, id?: any) => void) => void; + deserializeUser(): (username: string, cb: (err: any, user?: any) => void) => void; register(user: T, password: string, cb: (err: any, account: any) => void): void; findByUsername(username: string, selectHashSaltFields: boolean, cb: (err: any, account: any) => void): any; createStrategy(): passportLocal.Strategy; diff --git a/types/pg/index.d.ts b/types/pg/index.d.ts index 2b442b1227..6718fb3f12 100644 --- a/types/pg/index.d.ts +++ b/types/pg/index.d.ts @@ -71,7 +71,7 @@ export declare class Pool extends events.EventEmitter { connect(): Promise; connect(callback: (err: Error, client: Client, done: () => void) => void): void; - end(): Promise; + end(callback?: () => void): Promise; query(queryStream: QueryConfig & stream.Readable): stream.Readable; query(queryTextOrConfig: string | QueryConfig): Promise; diff --git a/types/pg/pg-tests.ts b/types/pg/pg-tests.ts index 73c18ac1b7..4b4cfba7ec 100644 --- a/types/pg/pg-tests.ts +++ b/types/pg/pg-tests.ts @@ -74,3 +74,8 @@ pool.connect((err, client, done) => { pool.on('error', (err, client) => { console.error('idle client error', err.message, err.stack) }) + +pool.end(); +pool.end(() => { + console.log("pool is closed"); +}); diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index bcf403d475..f7410baaa6 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -199,25 +199,6 @@ declare namespace PIXI { // display - interface ApplicationOptions extends RendererOptions { - view?: HTMLCanvasElement; - transparent?: boolean; - autoResize?: boolean; - antialias?: boolean; - resolution?: number; - clearBeforeRender?: boolean; - backgroundColor?: number; - roundPixels?: boolean; - context?: WebGLRenderingContext; - preserveDrawingBuffer?: boolean; - legacy?: boolean; - width?: number; - height?: number; - forceCanvas?: boolean; - sharedTicker?: boolean; - sharedLoader?: boolean; - } - class Application { constructor(options?: ApplicationOptions) constructor(width?: number, height?: number, options?: ApplicationOptions, noWebGL?: boolean, sharedTicker?: boolean, sharedLoader?: boolean); @@ -725,18 +706,91 @@ declare namespace PIXI { } // renderers interface RendererOptions { - view?: HTMLCanvasElement; - transparent?: boolean; - autoResize?: boolean; - antialias?: boolean; - resolution?: number; - clearBeforeRender?: boolean; - backgroundColor?: number; - roundPixels?: boolean; - context?: WebGLRenderingContext; + /** + * the width of the renderers view [default=800] + */ width?: number; + + /** + * the height of the renderers view [default=600] + */ height?: number; + + /** + * the canvas to use as a view, optional + */ + view?: HTMLCanvasElement; + + /** + * If the render view is transparent, [default=false] + */ + transparent?: boolean; + + /** + * sets antialias (only applicable in chrome at the moment) [default=false] + */ + antialias?: boolean; + + /** + * enables drawing buffer preservation, enable this if you need to call toDataUrl on the webgl context [default=false] + */ + preserveDrawingBuffer?: boolean; + + /** + * The resolution / device pixel ratio of the renderer, retina would be 2 [default=1] + */ + resolution?: number; + + /** + * prevents selection of WebGL renderer, even if such is present [default=false] + */ forceCanvas?: boolean; + + /** + * The background color of the rendered area (shown if not transparent) [default=0x000000] + */ + backgroundColor?: number; + + /** + * This sets if the renderer will clear the canvas or not before the new render pass. [default=true] + */ + clearBeforeRender?: boolean; + + /** + * If true Pixi will Math.floor() x/ y values when rendering, stopping pixel interpolation. [default=false] + */ + roundPixels?: boolean; + + /** + * forces FXAA antialiasing to be used over native FXAA is faster, but may not always look as great ** webgl only** [default=false] + */ + forceFXAA?: boolean; + + /** + * `true` to ensure compatibility with older / less advanced devices. If you experience unexplained flickering try setting this to true. **webgl only** [default=false] + */ + legacy?: boolean; + + /** + * Depricated + */ + context?: WebGLRenderingContext; + + /** + * Depricated + */ + autoResize?: boolean; + } + interface ApplicationOptions extends RendererOptions { + /** + * `true` to use PIXI.ticker.shared, `false` to create new ticker. [default=false] + */ + sharedTicker?: boolean; + + /** + * `true` to use PIXI.loaders.shared, `false` to create new Loader. + */ + sharedLoader?: boolean; } class SystemRenderer extends utils.EventEmitter { constructor(system: string, options?: RendererOptions); @@ -825,20 +879,7 @@ declare namespace PIXI { resize(width: number, height: number): void; destroy(): void; } - interface WebGLRendererOptions { - view?: HTMLCanvasElement; - transparent?: boolean; - autoResize?: boolean; - antialias?: boolean; - forceFXAA?: boolean; - resolution?: number; - clearBeforeRender?: boolean; - backgroundColor?: number; - preserveDrawingBuffer?: boolean; - roundPixels?: boolean; - legacy?: boolean; - width?: number; - height?: number; + interface WebGLRendererOptions extends RendererOptions { } class WebGLRenderer extends SystemRenderer { // plugintarget mixin start @@ -2512,12 +2553,18 @@ declare namespace PIXI { protected maxItemsPerFrame: number; protected itemsLeft: number; + + beginFrame(): void; + allowedToUpload(): boolean; } class TimeLimiter { constructor(maxMilliseconds: number); protected maxMilliseconds: number; protected frameStart: number; + + beginFrame(): void; + allowedToUpload(): boolean; } } @@ -2713,6 +2760,11 @@ declare namespace PIXI { function isWebGLSupported(): boolean; function sign(n: number): number; function removeItems(arr: T[], startIdx: number, removeCount: number): void; + function correctBlendMode(blendMode: number, premultiplied: boolean): number; + function premultiplyTint(tint: number, alpha: number): number; + function premultiplyRgba(rgb: Float32Array | number[], alpha: number, out?: Float32Array, premultiply?: boolean): Float32Array; + function premultiplyTintToRgba(tint: number, alpha: number, out?: Float32Array, premultiply?: boolean): Float32Array; + const premultiplyBlendMode: number[][]; const TextureCache: any; const BaseTextureCache: any; diff --git a/types/promise.prototype.finally/index.d.ts b/types/promise.prototype.finally/index.d.ts index 9df993ce93..5c4581ba46 100644 --- a/types/promise.prototype.finally/index.d.ts +++ b/types/promise.prototype.finally/index.d.ts @@ -1,11 +1,11 @@ -// Type definitions for promise.prototype.finally v2.0.1 +// Type definitions for promise.prototype.finally 2.0 // Project: https://github.com/matthew-andrews/Promise.prototype.finally // Definitions by: Slava Shpitalny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare global { interface Promise { - finally(onFinally?: () => U | Promise): Promise; + finally(onFinally?: () => U | PromiseLike): Promise; } } diff --git a/types/promise.prototype.finally/promise.prototype.finally-tests.ts b/types/promise.prototype.finally/promise.prototype.finally-tests.ts index b7f5848606..2fa7c96512 100644 --- a/types/promise.prototype.finally/promise.prototype.finally-tests.ts +++ b/types/promise.prototype.finally/promise.prototype.finally-tests.ts @@ -2,13 +2,14 @@ import promiseFinally = require('promise.prototype.finally'); promiseFinally.shim(); -var promise = new Promise((resolve, reject) => { +let promise = new Promise((resolve, reject) => { resolve(true); }); promise.finally(() => {}); +promise.finally(() => > Promise.resolve()); promise.then(() => {}, () => {}).finally(() => {}); promise.catch(() => {}).finally(() => {}); -var allPromise = Promise.all([promise]); +let allPromise = Promise.all([promise]); allPromise.finally(() => {}); diff --git a/types/promise.prototype.finally/tslint.json b/types/promise.prototype.finally/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/promise.prototype.finally/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/q/index.d.ts b/types/q/index.d.ts index 2a04f56847..56ada9590a 100644 --- a/types/q/index.d.ts +++ b/types/q/index.d.ts @@ -11,7 +11,7 @@ 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: Q.IPromise): Q.Promise; +declare function Q(promise: PromiseLike): Q.Promise; /** * If value is not a promise, returns a promise that is fulfilled with value. */ @@ -22,10 +22,9 @@ declare function Q(value: T): Q.Promise; declare function Q(): Q.Promise; declare namespace Q { - export type IWhenable = IPromise | T; - export interface IPromise { - then(onFulfill?: (value: T) => IWhenable, onReject?: (error: any) => IWhenable): IPromise; - } + + export type IWhenable = PromiseLike | T; + export type IPromise = PromiseLike; export interface Deferred { promise: Promise; @@ -224,7 +223,10 @@ declare namespace Q { /** * 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]>): Promise<[A, B]>; + 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. */ diff --git a/types/qiniu/index.d.ts b/types/qiniu/index.d.ts deleted file mode 100644 index 03eedd4914..0000000000 --- a/types/qiniu/index.d.ts +++ /dev/null @@ -1,262 +0,0 @@ -// Type definitions for qiniu 6.1 -// Project: https://github.com/qiniu/nodejs-sdk -// Definitions by: xialeistudio -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace qiniu { - type onret = (e?: any, result?: any, res?: any) => void; - class conf { - static ACCESS_KEY: string; - static SECRET_KEY: string; - static USER_AGENT: string; - static UP_HOST: string; - static RS_HOST: string; - static RSF_HOST: string; - static API_HOST: string; - static RPC_TIMEOUT: number; - static UC_HOST: string; - static UP_HTTPS_HOST: string; - static SCHEME: string; - static AUTOZONE: boolean; - static BUCKET: string | null; - static EXPIRE: number; - } - namespace auth { - class Mac { - accessKey: string; - secretKey: string; - - constructor(accessKey: string, secretKey: string); - } - } - namespace io { - const UNDEFINED_KEY: string; - class PutExtra { - params: any; - mimeType?: string; - crc32?: string; - checkCrc?: number; - - constructor(params?: any, mimeType?: string, crc32?: string, checkCrc?: number); - } - class PutRet { - hash?: string; - key?: string; - - constructor(hash?: string, key?: string); - } - - function putReadable(uptoken: string, key?: string, rs?: any, extra?: any, onret?: onret): any; - - function put(uptoken: string, key?: string, body?: any, extra?: any, onret?: onret): any; - - function putWithoutKey(uptoken: string, body?: any, extra?: any, onret?: onret): any; - - function putFile(uptoken: string, key?: string, localFile?: string, extra?: any, onret?: onret): any; - - function putFileWithoutKey(uptoken: string, localFile?: string, extra?: any, onret?: onret): any; - } - namespace util { - function urlsafeBase64Encode(jsonFlags: any): string; - - function base64ToUrlSafe(v: string): string; - - function hmacSha1(encodedFlags: any, secretKey: string): string; - - function generateAccessToken(uri: string, body?: any): string; - - function isQiniuCallback(path: string, body: any, callbackAuth: any): boolean; - } - namespace zone { - function up_host(uptoken: string, conf: conf): void; - } - namespace rsf { - function listPrefix(bucket: string, prefix?: string, marker?: any, limit?: any, delimiter?: any, onret?: onret): void; - } - namespace rpc { - function postMultipart(uri: string, form: any, onret?: onret): any; - - function postWithForm(uri: string, form: any, token?: string, onret?: onret): any; - - function postWithoutForm(uri: string, token?: string, onret?: onret): any; - } - namespace fop { - class ImageView { - mode: number; - width: number; - height: number; - quality: number; - format: any; - - constructor(mode?: number, width?: number, height?: number, quality?: number, format?: any); - - makeRequest(url: string): string; - } - - class ImageInfo { - makeRequest(url: string): string; - } - class Exif { - makeRequest(url: string): string; - } - - function pfop(bucket: string, key: string, fops: any, opts?: any, onret?: onret): void; - } - namespace rs { - import Mac = qiniu.auth.Mac; - class Client { - client?: Client; - - constructor(client?: Client); - - stat(bucket: string, key: string, onret?: onret): void; - - remove(bucket: string, key: string, onret?: onret): void; - - move(bucketSrc: string, keySrc: string, bucketDest: string, keyDest: string, onret?: onret): void; - - forceMove(bucketSrc: string, keySrc: string, bucketDest: string, keyDest: string, force: boolean, onret?: onret): void; - - copy(bucketSrc: string, keySrc: string, bucketDest: string, keyDest: string, onret?: onret): void; - - forceCopy(bucketSrc: string, keySrc: string, bucketDest: string, keyDest: string, force: boolean, onret?: onret): void; - - fetch(url: string, bucket: string, key: string, onret?: onret): void; - - batchStat(entries: any[], onret?: onret): void; - - batchDelete(entries: any[], onret?: onret): void; - - batchMove(entries: any[], onret?: onret): void; - - forceBatchMove(entries: any[], force: boolean, onret?: onret): void; - - batchCopy(entries: any[], onret?: onret): void; - - forceBatchCopy(entries: any[], force: boolean, onret?: onret): void; - } - class Entry { - hash?: string; - fsize?: number; - putTime?: number; - mimeType?: string; - endUser?: any; - - constructor(hash?: string, fsize?: number, putTime?: number, mimeType?: string, endUser?: any); - } - class EntryPath { - bucket?: string; - key?: string; - - constructor(bucket?: string, key?: string); - - encode(): string; - - toStr(op: string): string; - } - class EntryPathPair { - src?: string; - dest?: string; - - constructor(src?: string, desc?: string); - - toStr(op: string, force?: boolean): string; - } - class BatchItemRet { - error?: any; - code?: number; - - constructor(error?: any, code?: number); - } - class BatchStatItemRet { - data: any; - error: any; - code: number; - - constructor(data: any, error: any, code: number); - } - class PutPolicy { - scope?: string; - callbackUrl?: string; - callbackBody?: any; - returnUrl?: string; - returnBody?: any; - endUser?: any; - expires: number; - persistentOps?: any; - persistentNotifyUrl?: string; - - constructor(score?: string, - callbackUrl?: string, - callbackBody?: any, - returnUrl?: string, - returnBody?: any, - endUser?: any, - expires?: number, - persistentOps?: any, - persistentNotifyUrl?: string); - - token(mac?: Mac): string; - - getFlags(): any; - } - interface putPolicyObj { - scope?: string; - expires?: number; - insertOnly?: boolean; - saveKey?: string; - endUser?: any; - returnUrl?: string; - returnBody?: any; - callbackUrl?: string; - callbackHost?: string; - callbackBody?: any; - callbackBodyType?: string; - callbackFetchKey?: string; - persistentOps?: any; - persistentNotifyUrl?: string; - persistentPipeline?: string; - fsizeLimit?: number; - fsizeMin?: any; - detectMime?: any; - mimeLimit?: any; - deleteAfterDays?: number; - } - class PutPolicy2 { - scope?: string; - expires: number; - insertOnly?: boolean; - saveKey?: string; - endUser?: any; - returnUrl?: string; - returnBody?: any; - callbackUrl?: string; - callbackHost?: string; - callbackBody?: any; - callbackBodyType?: string; - callbackFetchKey?: string; - persistentOps?: any; - persistentNotifyUrl?: string; - persistentPipeline?: string; - fsizeLimit?: number; - fsizeMin?: any; - detectMime?: any; - mimeLimit?: any; - deleteAfterDays?: number; - - constructor(putPolicyObj: putPolicyObj); - - token(mac?: Mac): string; - - getFlags(): any; - } - class GetPolicy { - expires: number; - - constructor(expires?: number); - - makeRequest(baseUrl: string, mac?: Mac): string; - } - function makeBaseUrl(domain: string, key: string, query?: string): string; - } -} diff --git a/types/qiniu/qiniu-tests.ts b/types/qiniu/qiniu-tests.ts deleted file mode 100644 index ea4c3fe202..0000000000 --- a/types/qiniu/qiniu-tests.ts +++ /dev/null @@ -1,156 +0,0 @@ -// test for qiniu.conf -function testConf() { - qiniu.conf.ACCESS_KEY = 'Access_Key'; - qiniu.conf.SECRET_KEY = 'Secret_Key'; -} - -// test for qiniu.auth -function testAuth() { - // test for auth.Mac - const mac = new qiniu.auth.Mac(qiniu.conf.ACCESS_KEY, qiniu.conf.SECRET_KEY); -} - -// test for qiniu.io -function testIo() { - // test for PutExtra - const putExtra = new qiniu.io.PutExtra(); - // test for PutRet - const putRet = new qiniu.io.PutRet(); - // test for putReadable - qiniu.io.putReadable('xxx', undefined, undefined, undefined, (e?: any, result?: any, res?: any) => { - }); - // test for put - qiniu.io.put('xxx', undefined, 'test-data', undefined, (e?: any, result?: any, res?: any) => { - }); - // test for putWithoutKey - qiniu.io.putWithoutKey('xxx', 'test-data', undefined, (e?: any, result?: any, res?: any) => { - }); - // test for putFile - qiniu.io.putFile('xxx', undefined, 'tslint.json', undefined, (e?: any, result?: any, res?: any) => { - }); - // test for putFileWithoutKey - qiniu.io.putFileWithoutKey('xxx', 'tslint.json', undefined, (e?: any, result?: any, res?: any) => { - }); -} - -// test for qiniu.util -function testUtil() { - // test for urlsafeBase64Encode - qiniu.util.urlsafeBase64Encode(null); - // test for base64ToUrlSafe - qiniu.util.base64ToUrlSafe('https://example.com'); - // test for hmacSha1 - qiniu.util.hmacSha1(null, 'test'); - // test for generateAccessToken - qiniu.util.generateAccessToken('https://example.com'); - // test for isQiniuCallback - qiniu.util.isQiniuCallback('/key', 'test-data', 'test-auth'); -} - -// test for qiniu.zone -function testZone() { - qiniu.zone.up_host('test', {ACCESS_KEY: 'xx', SECRET_KEY: 'ss'}); -} - -// test for qiniu.rsf -function testRsf() { - qiniu.rsf.listPrefix('test'); -} - -// test for qiniu.rpc -function testRpc() { - // test for postMultipart - qiniu.rpc.postMultipart('https://up.qbox.me', 'test'); - // test for postWithForm - qiniu.rpc.postWithForm('https://up.qbox.me', 'test'); - // test for postWithoutForm - qiniu.rpc.postWithoutForm('https://up.qbox.me'); -} - -// test for qiniu.fop -function testFop() { - // test for ImageView - const imageView = new qiniu.fop.ImageView(1, 1, 1, 1); - imageView.makeRequest('https://up.qbox.me'); - // test for ImageInfo - const imageInfo = new qiniu.fop.ImageInfo(); - imageInfo.makeRequest('https://up.qbox.me'); - // test for Exif - const exif = new qiniu.fop.Exif(); - exif.makeRequest('https://up.qbox.me'); - // test for fop - qiniu.fop.pfop('test', 'test', 'test'); -} - -// test for qiniu.rs -function testRs() { - // test for Client - const client = new qiniu.rs.Client(); - // test for Client.stat - client.stat('test', 'test', (e?: any, result?: any, res?: any) => { - }); - // test for Client.remove - client.remove('test', 'test', (e?: any, result?: any, res?: any) => { - }); - // test for Client.move - client.move('test-src', 'test-src', 'test-dest', 'test-dest', (e?: any, result?: any, res?: any) => { - }); - // test for Client.forceMove - client.forceMove('test-src', 'test-src', 'test-dest', 'test-dest', true, (e?: any, result?: any, res?: any) => { - }); - // test for Client.copy - client.copy('test-src', 'test-src', 'test-dest', 'test-dest', (e?: any, result?: any, res?: any) => { - }); - // test for Client.forceCopy - client.forceCopy('test-src', 'test-src', 'test-dest', 'test-dest', true, (e?: any, result?: any, res?: any) => { - }); - // test for Client.fetch - client.fetch('https://up.qbox.me', 'test', 'test', (e?: any, result?: any, res?: any) => { - }); - // test for Client.batchStat - client.batchStat(['data'], (e?: any, result?: any, res?: any) => { - }); - // test for Client.batchDelete - client.batchDelete(['data'], (e?: any, result?: any, res?: any) => { - }); - // test for Client.batchMove - client.batchMove(['data'], (e?: any, result?: any, res?: any) => { - }); - // test for Client.forceBatchMove - client.forceBatchMove(['data'], true, (e?: any, result?: any, res?: any) => { - }); - // test for Client.batchCopy - client.batchCopy(['data'], (e?: any, result?: any, res?: any) => { - }); - // test for Client.forceBatchMove - client.forceBatchCopy(['data'], true, (e?: any, result?: any, res?: any) => { - }); - // test for Entry - const entry = new qiniu.rs.Entry('xx', 1, 1); - // test for EntryPath - const entryPath = new qiniu.rs.EntryPath('test', 'test'); - entryPath.encode(); - entryPath.toStr('x'); - // test for EntryPathPair - const entryPathPair = new qiniu.rs.EntryPathPair('xxx', 'xxx'); - entryPathPair.toStr('x', false); - // test for BatchItemRet - const batchItemRet = new qiniu.rs.BatchItemRet('xx', 0); - // test for BatchStatItemRet - const batchStatItemRet = new qiniu.rs.BatchStatItemRet('xx', 'xxx', 0); - // test for PutPolicy - const putPolicy = new qiniu.rs.PutPolicy(); - putPolicy.token(); - putPolicy.getFlags(); - // test for PutPolicy2 - const putPolicy2 = new qiniu.rs.PutPolicy2({ - scope: 'xxx' - }); - putPolicy2.token(); - putPolicy2.getFlags(); - // test for GetPolicy - const getPolicy = new qiniu.rs.GetPolicy(10); - getPolicy.makeRequest('https://up.qbox.me'); - // test for makeBaseUrl - qiniu.rs.makeBaseUrl('up.qbox.me', 'test'); -} diff --git a/types/qs/index.d.ts b/types/qs/index.d.ts index 400cc7a1e4..2ecbed14be 100644 --- a/types/qs/index.d.ts +++ b/types/qs/index.d.ts @@ -1,7 +1,10 @@ -// Type definitions for qs 6.2.0 -// Project: https://github.com/hapijs/qs -// Definitions by: Roman Korneev , Leon Yu , -// Belinda Teh +// Type definitions for qs 6.5.0 +// Project: https://github.com/ljharb/qs +// Definitions by: Roman Korneev +// Leon Yu +// Belinda Teh +// Melvin Lee +// Arturs Vonda // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = QueryString; @@ -18,6 +21,10 @@ declare namespace QueryString { arrayFormat?: 'indices' | 'brackets' | 'repeat'; indices?: boolean; sort?: (a: any, b: any) => number; + serializeDate?: (d: Date) => string; + format?: 'RFC1738' | 'RFC3986'; + encodeValuesOnly?: boolean; + addQueryPrefix?: boolean; } interface IParseOptions { @@ -31,6 +38,7 @@ declare namespace QueryString { allowPrototypes?: boolean; parameterLimit?: number; strictNullHandling?: boolean; + ignoreQueryPrefix?: boolean; } function stringify(obj: any, options?: IStringifyOptions): string; diff --git a/types/qs/qs-tests.ts b/types/qs/qs-tests.ts index f3e5ca3230..49fe89a4aa 100644 --- a/types/qs/qs-tests.ts +++ b/types/qs/qs-tests.ts @@ -233,6 +233,11 @@ qs.parse('a=b&c=d', { delimiter: '&' }); assert.deepEqual(parsedStrictNull, { a: null, b: '' }); } +() => { + var parsedQueryPrefix = qs.parse('?a&b=', { ignoreQueryPrefix: true }); + assert.deepEqual(parsedQueryPrefix, { a: '', b: '' }); +} + () => { var nullsSkipped = qs.stringify({ a: 'b', c: null }, { skipNulls: true }); assert.equal(nullsSkipped, 'a=b'); @@ -254,3 +259,31 @@ qs.parse('a=b&c=d', { delimiter: '&' }); var sorted = qs.stringify({ a: 1, c: 3, b: 2 }, { sort: (a, b) => a.localeCompare(b) }) assert.equal(sorted, 'a=1&b=2&c=3') } + +() => { + var date = new Date(7); + assert.equal( + qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime().toString(); } }), + 'a=7' + ); +} + +() => { + assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); +} + +() => { + assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); +} + +() => { + var encodedValues = qs.stringify( + { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, + { encodeValuesOnly: true } + ); + assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); +} + +() => { + assert.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); +} diff --git a/types/qs/tsconfig.json b/types/qs/tsconfig.json index 13f816338d..624bdc72f2 100644 --- a/types/qs/tsconfig.json +++ b/types/qs/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "qs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/quill/index.d.ts b/types/quill/index.d.ts index 73a877815f..91124814f5 100644 --- a/types/quill/index.d.ts +++ b/types/quill/index.d.ts @@ -41,7 +41,8 @@ declare namespace Quill { placeholder?: string, readOnly?: boolean, theme?: string, - formats?: string[] + formats?: string[], + bounds?: HTMLElement | string } export interface BoundsStatic { diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index ba6908d57c..e30c95f8be 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -55,15 +55,15 @@ declare namespace R { push(x: string): void; } - interface Nested { - [index: string]: Nested | ((value: any) => U); - } - interface Lens { (obj: T): U; set(str: string, obj: T): U; } + type Evolver = + | ((x: T) => T) + | { [K in keyof T]?: Evolver }; + // @see https://gist.github.com/donnut/fd56232da58d25ceecf1, comment by @albrow interface CurriedTypeGuard2 { (t1: T1): (t2: T2) => t2 is R; @@ -567,8 +567,9 @@ declare namespace R { /** * Creates a new object by evolving a shallow copy of object, according to the transformation functions. */ - evolve(transformations: Nested, obj: V): Nested; - evolve(transformations: Nested): (obj: V) => Nested; + evolve(transformations: Evolver, obj: V): V; + evolve(transformations: Evolver): (obj: W) => W; + /* * A function that always returns false. Any passed in parameters are ignored. */ @@ -627,6 +628,12 @@ declare namespace R { forEach(fn: (x: T) => void, list: T[]): T[]; forEach(fn: (x: T) => void): (list: T[]) => T[]; + /** + * Iterate over an input object, calling a provided function fn for each key and value in the object. + */ + forEachObjIndexed(fn: (value: T[keyof T], key: keyof T, obj: T) => void, obj: T): T; + forEachObjIndexed(fn: (value: T[keyof T], key: keyof T, obj: T) => void): (obj: T) => T; + /** * Creates a new object out of a list key-value pairs. */ @@ -812,7 +819,7 @@ declare namespace R { /** * Checks if the input value is null or undefined. */ - isNil(value: any): boolean; + isNil(value: any): value is null | undefined; /** * Returns a string made by inserting the `separator` between each @@ -1501,6 +1508,12 @@ declare namespace R { splitWhen(pred: (val: T) => boolean, list: U[]): U[][]; splitWhen(pred: (val: T) => boolean): (list: U[]) => U[][]; + /** + * Checks if a list starts with the provided values + */ + startsWith(a: any, list: any): boolean; + startsWith(a: any): (list: any) => boolean; + /** * Subtracts two numbers. Equivalent to `a - b` but curried. */ diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 70298f53e6..18a5ed4e7d 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -744,13 +744,13 @@ interface Obj { R.map(double, [1, 2, 3]); // => [2, 4, 6] // functor - const stringFunctor = { - map: (fn: (c: number) => number) => { + const numberFunctor = { + map: (fn: (c: number) => U) => { let chars = "Ifmmp!Xpsme".split(""); - return chars.map((char) => String.fromCharCode(fn(char.charCodeAt(0)))).join("") as any; + return chars.map(char => fn(char.charCodeAt(0))); } }; - R.map((x: number) => x - 1, stringFunctor); // => "Hello World" + R.map((x: number) => x - 1, numberFunctor); // => "Hello World" }; () => { @@ -2199,10 +2199,3 @@ class Why { R.intersperse(0, [1, 2]); // => [1, 0, 2] R.intersperse(0, [1]); // => [1] }; - -{ - const functor = { - map: (fn: (x: string) => string) => functor - }; - R.map(x => x.trim(), functor); -} diff --git a/types/rc-slider/index.d.ts b/types/rc-slider/index.d.ts index 34cfc22056..c30f6a649c 100644 --- a/types/rc-slider/index.d.ts +++ b/types/rc-slider/index.d.ts @@ -1,154 +1,165 @@ -// Type definitions for rc-slider 6.1 +// Type definitions for rc-slider 8.1 // Project: https://github.com/react-component/slider -// Definitions by: Marcinkus Mantas +// Definitions by: Marcinkus Mantas , Alexander Mattoni // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as React from 'react'; +import * as React from "react"; -declare namespace RcSliderClass { - interface Marks { - [number: number]: JSX.Element | string | { style: any, label: string | JSX.Element }; - } - - interface CommonApiProps { - /** - * Additional CSS class for the root DOM node - * @default '' - */ - className?: string; - /** - * The minimum value of the slider - * @default 0 - */ - min?: number; - /** - * The maximum value of the slider - * @default 100 - */ - max?: number; - /** - * Marks on the slider. The key determines the position, and the value determines what will show. - * If you want to set the style of a specific mark point, the value should be an object which contains style and label properties. - * @default '{}' | {number: { style, label }} - */ - marks?: Marks; - /** - * Value to be added or subtracted on each step the slider makes. Must be greater than zero, and max - min should be evenly divisible by the step value. - * @default 1 - */ - step?: number; - /** - * If vertical is true, the slider will be vertical. - * @default false - */ - vertical?: boolean; - /** - * A handle generator which could be used to customized handle. - */ - handle?(props: any): React.ReactNode; - /** - * If the value is true, it means a continuous value interval, otherwise, it is a independent value. - * @default true - */ - included?: boolean; - /** - * If true, handles can't be moved. - * @default false - */ - disabled?: boolean; - /** - * When the step value is greater than 1, you can set the dots to true if you want to render the slider with dots. - * @default false - */ - dots?: boolean; - /** - * onBeforeChange will be triggered when ontouchstart or onmousedown is triggered. - */ - onBeforeChange?(value: any): any | undefined; - /** - * onChange will be triggered while the value of Slider changing. - */ - onChange?(value: any): any | undefined; - /** - * onAfterChange will be triggered when ontouchend or onmouseup is triggered. - */ - onAfterChange?(value: any): any | undefined; - - /** - * @deprecated in version ^6.0.0. Use rc-tooltip - * Tooltip transition class name - */ - tipTransitionName?: string; - - /** - * @deprecated in version ^6.0.0. Use rc-tooltip - * Tooltip formatter - */ - tipFormatter?: ((value: any) => any | undefined) | null; - } - - interface SliderProps extends CommonApiProps { - /** - * Set initial value of slider. - * @default 0 - */ - defaultValue?: number; - /** - * Set current value of slider. - */ - value?: number; - } - - interface RangeProps extends CommonApiProps { - /** - * Set initial positions of handles. - * @default [0,0] - */ - defaultValue?: number[]; - /** - * Set current positions of handles. - */ - value?: number[]; - /** - * Determine how many ranges to render, and multiple handles will be rendered (number + 1). - * @default 1 - */ - count?: number; - /** - * allowCross could be set as true to allow those handles to cross. - * @default true - */ - allowCross?: boolean; - /** - * pushable could be set as true to allow pushing of surrounding handles when moving an handle. When set to a number, the number will be the minimum ensured distance between handles. - * @default true - */ - pushable?: boolean; - } - - interface HandleProps extends CommonApiProps { - /** - * Class name - */ - className: string; - /** - * Styling if true, then bottom: {offset} else left: {offset} - * @default False - */ - vertical: boolean; - /** - * Styling option offset - */ - offset: number; - } +export interface Marks { + [number: number]: + | JSX.Element + | string + | { style: any; label: string | JSX.Element }; } -declare class RcSliderClass extends React.Component { } +export interface CommonApiProps { + /** + * Additional CSS class for the root DOM node + * @default '' + */ + className?: string; + /** + * The minimum value of the slider + * @default 0 + */ + min?: number; + /** + * The maximum value of the slider + * @default 100 + */ + max?: number; + /** + * Marks on the slider. The key determines the position, and the value determines what will show. + * If you want to set the style of a specific mark point, the value should be an object which contains style and label properties. + * @default '{}' | {number: { style, label }} + */ + marks?: Marks; + /** + * Value to be added or subtracted on each step the slider makes. Must be greater than zero, and max - min should be evenly divisible by the step value. + * @default 1 + */ + step?: number; + /** + * If vertical is true, the slider will be vertical. + * @default false + */ + vertical?: boolean; + /** + * A handle generator which could be used to customized handle. + */ + handle?(props: any): React.ReactNode; + /** + * If the value is true, it means a continuous value interval, otherwise, it is a independent value. + * @default true + */ + included?: boolean; + /** + * If true, handles can't be moved. + * @default false + */ + disabled?: boolean; + /** + * When the step value is greater than 1, you can set the dots to true if you want to render the slider with dots. + * @default false + */ + dots?: boolean; + /** + * onBeforeChange will be triggered when ontouchstart or onmousedown is triggered. + */ + onBeforeChange?(value: any): any | undefined; + /** + * onChange will be triggered while the value of Slider changing. + */ + onChange?(value: any): any | undefined; + /** + * onAfterChange will be triggered when ontouchend or onmouseup is triggered. + */ + onAfterChange?(value: any): any | undefined; -declare namespace RcSliderClass { - class Range extends React.Component { } - class Handle extends React.Component { } + /** + * @deprecated in version ^6.0.0. Use rc-tooltip + * Tooltip transition class name + */ + tipTransitionName?: string; + + /** + * @deprecated in version ^6.0.0. Use rc-tooltip + * Tooltip formatter + */ + tipFormatter?: ((value: any) => any | undefined) | null; + + /** + * The style used for handle. (both for slider(Object) and range(Array of Object), the array will be used for mutli handle follow element order) + */ + handleStyle?: React.CSSProperties[] | React.CSSProperties; + + /** + * The style used for track. (both for slider(Object) and range(Array of Object), the array will be used for mutli track follow element order) + */ + trackStyle?: React.CSSProperties[] | React.CSSProperties; + + /** + * The style used for the track base color. + */ + railStyle?: React.CSSProperties; } -export = RcSliderClass; +export interface SliderProps extends CommonApiProps { + /** + * Set initial value of slider. + * @default 0 + */ + defaultValue?: number; + /** + * Set current value of slider. + */ + value?: number; +} + +export interface RangeProps extends CommonApiProps { + /** + * Set initial positions of handles. + * @default [0,0] + */ + defaultValue?: number[]; + /** + * Set current positions of handles. + */ + value?: number[]; + /** + * Determine how many ranges to render, and multiple handles will be rendered (number + 1). + * @default 1 + */ + count?: number; + /** + * allowCross could be set as true to allow those handles to cross. + * @default true + */ + allowCross?: boolean; + /** + * pushable could be set as true to allow pushing of surrounding handles when moving an handle. When set to a number, the number will be the minimum ensured distance between handles. + * @default true + */ + pushable?: boolean; +} + +export interface HandleProps extends CommonApiProps { + /** + * Class name + */ + className: string; + /** + * Styling if true, then bottom: {offset} else left: {offset} + * @default False + */ + vertical: boolean; + /** + * Styling option offset + */ + offset: number; +} + +export default class Slider extends React.Component { } +export class Range extends React.Component { } +export class Handle extends React.Component { } diff --git a/types/rc-slider/rc-slider-tests.tsx b/types/rc-slider/rc-slider-tests.tsx index 55c0674741..7e2e14e317 100644 --- a/types/rc-slider/rc-slider-tests.tsx +++ b/types/rc-slider/rc-slider-tests.tsx @@ -1,7 +1,6 @@ import * as React from 'react'; import * as ReactDOM from 'react-dom'; -import * as Slider from 'rc-slider'; -import { Range, Handle } from 'rc-slider'; +import Slider, { Range, Handle } from 'rc-slider'; ReactDOM.render( , diff --git a/types/react-app/index.d.ts b/types/react-app/index.d.ts new file mode 100644 index 0000000000..bd68aed103 --- /dev/null +++ b/types/react-app/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for react-app 1.0 +// Project: https://github.com/kriasoft/react-app#readme +// Definitions by: Prakarsh Pandey +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// Typescript Version: 2.3 + +import * as React from 'react'; + +export interface LinkProps { + to: string; + onClick?(): void; + className?: string; +} + +export interface LayoutProps { + className: string; +} + +export interface RouteProps { // takes the form of universal-router routes + path: string; + children: ChildProps[]; +} + +export interface ChildProps { + path: string; + action(params: any): any; +} + +export interface CreateAppObject { + routes: RouteProps; + context: {}; + container: Element | null; +} + +// exporting the createApp function +export function createApp(createAppObject: CreateAppObject): JSX.Element; + +export class Link extends React.Component {} +export class Layout extends React.Component {} +export class Header extends React.Component {} +export class Navigation extends React.Component {} diff --git a/types/react-app/react-app-tests.tsx b/types/react-app/react-app-tests.tsx new file mode 100644 index 0000000000..3c33f36944 --- /dev/null +++ b/types/react-app/react-app-tests.tsx @@ -0,0 +1,38 @@ +import * as React from 'react'; +import { Navigation, Link, Layout, Header, createApp } from 'react-app'; + +const store = {}; +const routes = { + path: '/', + children: [ + { + path: '/', + action() { + return { + title: 'Foo Page', + component:

Foo!

+ }; + } + }, + { + path: '/bar', + action() { + return { + title: 'Bar Page', + component:

Bar!

+ }; + } + } + ] +}; + +; +; +
; +; + +createApp({ + routes, + context: { store }, + container: document.body +}); diff --git a/types/react-app/tsconfig.json b/types/react-app/tsconfig.json new file mode 100644 index 0000000000..b1cf94dbd6 --- /dev/null +++ b/types/react-app/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-app-tests.tsx" + ] +} diff --git a/types/react-app/tslint.json b/types/react-app/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-app/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-hot-loader/index.d.ts b/types/react-hot-loader/index.d.ts index 214bd23f73..de8f5ee42d 100644 --- a/types/react-hot-loader/index.d.ts +++ b/types/react-hot-loader/index.d.ts @@ -15,4 +15,4 @@ export interface AppContainerProps { errorReporter?: React.ComponentClass | React.StatelessComponent } -export class AppContainer extends React.Component {} +export class AppContainer extends React.Component {} diff --git a/types/react-native-elements/README.md b/types/react-native-elements/README.md new file mode 100644 index 0000000000..0ed43c6eb3 --- /dev/null +++ b/types/react-native-elements/README.md @@ -0,0 +1,27 @@ +# [React Native Elements](https://github.com/react-native-training/react-native-elements) + +### Component Checklist +List will update as typings are added + +- [x] Buttons +- [ ] Badge +- [ ] Social Icons / Social Icon Buttons +- [ ] Icons +- [ ] Side Menu +- [ ] Form Elements +- [ ] Search Bar +- [ ] ButtonGroup +- [ ] Checkboxes +- [ ] List Element +- [ ] Badge +- [ ] Tab Bar Component +- [x] HTML style headings +- [ ] Card component +- [ ] Pricing Component +- [ ] Grid Component +- [ ] Slider Component +- [ ] Tile Component +- [ ] Avatar Component +- [ ] Rating Component +- [ ] SwipeDeck Component +- [ ] Header Component diff --git a/types/react-native-elements/index.d.ts b/types/react-native-elements/index.d.ts new file mode 100644 index 0000000000..5a39c78481 --- /dev/null +++ b/types/react-native-elements/index.d.ts @@ -0,0 +1,205 @@ +// Type definitions for react-native-elements 0.13 +// Project: https://github.com/react-native-training/react-native-elements#readme +// Definitions by: Kyle Roach +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from 'react'; +import { ViewStyle, TextStyle } from 'react-native'; + +export interface TextProps { + /** + * font size 40 + */ + h1?: boolean; + + /** + * font size 34 + */ + h2?: boolean; + + /** + * font size 28 + */ + h3?: boolean; + + /** + * font size 22 + */ + h4?: boolean; + + /** + * font family name + */ + fontFamily?: string; + + /** + * Additional styling for Text + */ + style?: TextStyle; +} + +/** + * HTML Style Headings + * + * @desc https://react-native-training.github.io/react-native-elements/API/HTML_style_headings/ + */ +export class Text extends React.Component {} + +export interface ButtonIcon { + name?: string; + color?: string; + size?: number; + type?: 'material' | 'material-community' | 'simple-line-icon' | 'zocial' | 'font-awesome' | 'octicon' | 'ionicon' | 'foundation' | 'evilicon' | 'entypo'; + buttonStyle?: TextStyle; +} + +export interface ButtonProperties { + /** + * Specify other component such as TouchableOpacity or other + * + * @default TouchableHighlight (iOS), TouchableNativeFeedback (android) + */ + Component?: JSX.Element; + + /** + * Additional styling for button component + * + * @default null + */ + buttonStyle?: ViewStyle; + + /** + * Button title + */ + title: string; + + /** + * Makes button large + * + * @default false + */ + large?: boolean; + + /** + * Specify different font family + * + * @default System font (iOS), Sans Serif (android) + */ + fontFamily?: string; + + /** + * Specify font weight for title + * + * @default null + */ + fontWeight?: string; + + /** + * Moves icon to right of title + * + * @default false + */ + iconRight?: boolean; + + /** + * onPress method + */ + onPress(): void; + + /** + * onLongPress method + */ + onLongPress?(): void; + + /** + * Icon configuration + */ + icon?: ButtonIcon; + + /** + * Specify other icon component instead of default. The component will have all values from the icon prop + * + * @default MaterialIcon + * @see https://github.com/oblador/react-native-vector-icons#icon-component + */ + iconComponent?: JSX.Element; + + /** + * Background color of button + * + * @default #397af8 + */ + backgroundColor?: string; + + /** + * Adds border radius to button + * (Note: if you set this, don't forget to also set borderRadius to containerViewStyle prop, otherwise unexpected behaviour might occur) + * + * @default 0 + */ + borderRadius?: number; + + /** + * Font color + * + * @default #fff + */ + color?: string; + + /** + * Text styling + * + * @default null + */ + textStyle?: TextStyle; + + /** + * Font size + * + * @default 18 + */ + fontSize?: number; + + /** + * Underlay color for button press + * + * @default transparent + */ + underlayColor?: string; + + /** + * Flag to add raised button styling + * + * @default false + */ + raised?: boolean; + + /** + * Indicates button is disabled + * + * @default false + */ + disabled?: boolean; + + /** + * Disabled button styling + * + * @default null + */ + disabledStyle?: ViewStyle; + + /** + * Styling for Component container + * + * @default null + */ + containerViewStyle?: ViewStyle; +} + +/** + * Button component + * + * @desc https://react-native-training.github.io/react-native-elements/API/buttons/ + */ +export class Button extends React.Component {} diff --git a/types/react-native-elements/react-native-elements-tests.tsx b/types/react-native-elements/react-native-elements-tests.tsx new file mode 100644 index 0000000000..836b04b431 --- /dev/null +++ b/types/react-native-elements/react-native-elements-tests.tsx @@ -0,0 +1,57 @@ +import * as React from 'react'; +import { View, StyleSheet } from 'react-native'; +import { Button, Text } from 'react-native-elements'; + +class TextTest extends React.Component { + render() { + return ( + + Heading 1 + Heading 2 + Heading 3 + Heading 4 + + ); + } +} + +class ButtonTest extends React.Component { + handleButtonPress() { + console.log('I got pressed'); + } + + render() { + return ( + + + + + + ; + } +} diff --git a/types/react-swipe/tsconfig.json b/types/react-swipe/tsconfig.json new file mode 100644 index 0000000000..304ae7e451 --- /dev/null +++ b/types/react-swipe/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [ + ], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-swipe-tests.tsx" + ] +} diff --git a/types/react-swipe/tslint.json b/types/react-swipe/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-swipe/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-swipeable-views/index.d.ts b/types/react-swipeable-views/index.d.ts index 068a4e8ee6..fd4b322fd5 100644 --- a/types/react-swipeable-views/index.d.ts +++ b/types/react-swipeable-views/index.d.ts @@ -1,36 +1,56 @@ -// Type definitions for react-swipeable-views +// Type definitions for react-swipeable-views 0.12 // Project: https://github.com/oliviertassinari/react-swipeable-views // Definitions by: Michael Ledin +// Deividas Bakanas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as React from 'react'; -export as namespace ReactSwipeableViews; +export type OnChangeIndexCallback = (index: number, indexLatest: number) => void; -declare namespace ReactSwipeableViews { - export interface SwipeableViewsProps extends React.Props { - containerStyle?: React.CSSProperties; - disabled?: boolean; - index?: number; - onChangeIndex?: (indexNew:number, indexLatest:number) => void; - onSwitching?: (index:number) => void; - resistance?: boolean; - slideStyle?: React.CSSProperties; - style?: React.CSSProperties; - threshold?: number; - } +export type OnTransitionEndCallback = () => void; - interface SwipeableViewsState { - indexCurrent?: number; - indexLatest?: number; - isDragging?: boolean; - isFirstRender?: boolean; - heightLatest?: number; - } +export type OnSwitchingCallback = (index: number, type: OnSwitchingCallbackTypeDescriptor) => void; - export class SwipeableViews extends React.Component { - } +export type OnSwitchingCallbackTypeDescriptor = "move" | "end"; + +export type AxisType = "x" | "x-reverse" | "y" | "y-reverse"; + +export interface SpringConfig { + duration: string; + easeFunction: string; + delay: string; } -export default ReactSwipeableViews.SwipeableViews; +export interface SwipeableViewsProps extends React.HTMLProps { + animateHeight?: boolean; + animateTransitions?: boolean; + axis?: AxisType; + containerStyle?: React.CSSProperties; + disabled?: boolean; + enableMouseEvents?: boolean; + hysteresis?: number; + ignoreNativeScroll?: boolean; + index?: number; + onChangeIndex?: OnChangeIndexCallback; + onSwitching?: OnSwitchingCallback; + onTransitionEnd?: OnTransitionEndCallback; + resistance?: boolean; + style?: React.CSSProperties; + slideStyle?: React.CSSProperties; + springConfig?: SpringConfig; + slideClassName?: string; + threshold?: number; +} + +export interface SwipeableViewsState { + indexCurrent?: number; + indexLatest?: number; + isDragging?: boolean; + isFirstRender?: boolean; + heightLatest?: number; + displaySameSlide?: boolean; +} + +export default class SwipeableViews extends React.Component { } diff --git a/types/react-swipeable-views/react-swipeable-views-tests.ts b/types/react-swipeable-views/react-swipeable-views-tests.ts index c608f065f4..b723f58575 100644 --- a/types/react-swipeable-views/react-swipeable-views-tests.ts +++ b/types/react-swipeable-views/react-swipeable-views-tests.ts @@ -1,29 +1,50 @@ import * as React from 'react'; -import SwipeableViews from 'react-swipeable-views'; +import SwipeableViews, +{ + OnChangeIndexCallback, + OnSwitchingCallback, + OnSwitchingCallbackTypeDescriptor, + OnTransitionEndCallback, + SpringConfig +} from 'react-swipeable-views'; -const onChangeIndex = (indexNew:number, indexLatest:number) => { +const onChangeIndex: OnChangeIndexCallback = (indexNew: number, indexLatest: number) => { console.log('New index: ' + indexNew + ', latest index' + indexLatest); }; -const onSwitching = (index:number) => { - console.log('Switching to ' + index); +const onSwitching: OnSwitchingCallback = (index: number, type: OnSwitchingCallbackTypeDescriptor) => { + console.log(`Switching to ${index} with transition type "${type}"`); }; -const style:React.CSSProperties = { +const onTransitionEnd: OnTransitionEndCallback = () => { + console.log("Transition end."); +}; + +const style: React.CSSProperties = { height: 300 }; +const springConfig: SpringConfig = { + duration: "0.5s", + easeFunction: "cubic-bezier(0.1, 0.35, 0.2, 1)", + delay: "0.5s", +}; + React.createElement(SwipeableViews, { containerStyle: style, disabled: false, index: 0, - onChangeIndex: onChangeIndex, - onSwitching: onSwitching, + onChangeIndex, + onSwitching, resistance: false, slideStyle: style, - style: style, - threshold: 100 + style, + threshold: 100, + className: "swipable-view", + title: "Carousel", + onTransitionEnd, + axis: "x-reverse", + springConfig }); - React.createElement(SwipeableViews, {}); diff --git a/types/react-swipeable-views/tslint.json b/types/react-swipeable-views/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-swipeable-views/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-tag-input/index.d.ts b/types/react-tag-input/index.d.ts new file mode 100644 index 0000000000..626b44acac --- /dev/null +++ b/types/react-tag-input/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for React-Tags (react-tag-input) 4.7 +// Project: https://github.com/prakhar1989/react-tags +// Definitions by: Ogglas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from "react"; + +export interface ReactTagsProps { + tags?: Array<{id: number, text: string }>; + suggestions?: string[]; + handleDelete: ((i: number) => void); + handleAddition: ((tag: string) => void); + handleDrag?: ((tag: { id: number; text: string; }, currPos: number, newPos: number) => void); + placeholder?: string; +} + +export class WithContext extends React.Component { } + +export default WithContext; diff --git a/types/react-tag-input/react-tag-input-tests.tsx b/types/react-tag-input/react-tag-input-tests.tsx new file mode 100644 index 0000000000..a78bced3b9 --- /dev/null +++ b/types/react-tag-input/react-tag-input-tests.tsx @@ -0,0 +1,16 @@ +import * as React from "react"; +import * as ReactDOM from "react-dom"; +import { WithContext as ReactTags } from "react-tag-input"; + +let tags = Array({ id: 0, text: "test" }, { id: 1, text: "testing" }); + +let suggestions = Array("test1", "test2"); + +ReactDOM.render( + console.log("Delete: " + i)} + handleAddition={(tag: string) => console.log("Add: " + tag)} + handleDrag={(tag: { id: number; text: string; }, currPos: number, newPos: number) => console.log("Drag: " + tag.text)} />, + document.getElementById("app") +); diff --git a/types/eventemitter2/tsconfig.json b/types/react-tag-input/tsconfig.json similarity index 88% rename from types/eventemitter2/tsconfig.json rename to types/react-tag-input/tsconfig.json index 5df8f04c40..78318da79d 100644 --- a/types/eventemitter2/tsconfig.json +++ b/types/react-tag-input/tsconfig.json @@ -9,6 +9,7 @@ "noImplicitThis": true, "strictNullChecks": false, "baseUrl": "../", + "jsx": "react", "typeRoots": [ "../" ], @@ -18,6 +19,6 @@ }, "files": [ "index.d.ts", - "eventemitter2-tests.ts" + "react-tag-input-tests.tsx" ] } \ No newline at end of file diff --git a/types/react-tag-input/tslint.json b/types/react-tag-input/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-tag-input/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-tooltip/index.d.ts b/types/react-tooltip/index.d.ts new file mode 100644 index 0000000000..c4c380f533 --- /dev/null +++ b/types/react-tooltip/index.d.ts @@ -0,0 +1,55 @@ +// Type definitions for react-tooltip 3.3 +// Project: https://github.com/wwayne/react-tooltip +// Definitions by: Deividas Bakanas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as React from "react"; + +declare class ReactTooltip extends React.Component { } + +declare namespace ReactTooltip { + interface Offset { + top?: number; + right?: number; + left?: number; + bottom?: number; + } + + type ElementEvents = keyof HTMLElementEventMap; + type WindowEvents = keyof WindowEventMap; + + type GetContentCallback = () => React.ReactNode; + type GetContent = GetContentCallback | [GetContentCallback, number]; + + interface Props { + id?: string; + place?: "top" | "right" | "bottom" | "left"; + type?: "success" | "warning" | "error" | "info" | "light"; + effect?: "float" | "solid"; + event?: ElementEvents; + eventOff?: ElementEvents; + globalEventOff?: WindowEvents; + isCapture?: boolean; + offset?: Offset; + multiline?: boolean; + className?: string; + html?: boolean; + delayHide?: number; + delayShow?: number; + insecure?: boolean; + border?: boolean; + getContent?: GetContent; + afterShow?(): void; + afterHide?(): void; + disable?: boolean; + scrollHide?: boolean; + resizeHide?: boolean; + wrapper?: "div" | "span"; + role?: string; + class?: string; + watchWindow?: boolean; + } +} + +export = ReactTooltip; diff --git a/types/react-tooltip/react-tooltip-tests.tsx b/types/react-tooltip/react-tooltip-tests.tsx new file mode 100644 index 0000000000..7fa5332f27 --- /dev/null +++ b/types/react-tooltip/react-tooltip-tests.tsx @@ -0,0 +1,79 @@ +import * as React from "react"; +import * as ReactTooltip from "react-tooltip"; + +export class ReactTooltipTest extends React.PureComponent { + render() { + const getContent: ReactTooltip.GetContent = [() => Math.floor(Math.random() * 100), 30]; + + return
+ d(`・∀・)b + + Show happy face + + + இдஇ + { console.log("afterHide"); }}> + Show sad face + + + σ`∀´)σ + (〃∀〃) + { console.log("afterShow"); }}> +

This is a global react component tooltip

+

You can put every thing here

+
    +
  • Word
  • +
  • Chart
  • +
  • Else
  • +
+
+ + ( •̀д•́) + + + ( •̀д•́) + + + (・ω´・ )́) + + + =( •̀д•́) + + + =( •̀д•́) + new Date().toISOString(), 1000]} /> + + d(`・∀・)b + + + Show happy face + +
+ + Show happy face + +
+
; + } +} diff --git a/types/activex-scripting-runtime/tsconfig.json b/types/react-tooltip/tsconfig.json similarity index 77% rename from types/activex-scripting-runtime/tsconfig.json rename to types/react-tooltip/tsconfig.json index f5e74f9dd6..d52b7c28ab 100644 --- a/types/activex-scripting-runtime/tsconfig.json +++ b/types/react-tooltip/tsconfig.json @@ -4,11 +4,12 @@ "lib": [ "es6", "dom", - "scripthost" + "dom.iterable" ], + "jsx": "react", "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,6 +20,6 @@ }, "files": [ "index.d.ts", - "activex-scripting-runtime-tests.ts" + "react-tooltip-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/react-tooltip/tslint.json b/types/react-tooltip/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-tooltip/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react/index.d.ts b/types/react/index.d.ts index 577959ae7b..6ce2919510 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -144,6 +144,10 @@ declare namespace React { type: keyof ReactSVG, props?: ClassAttributes & P, ...children: ReactNode[]): ReactSVGElement; + function createElement

, T extends Element>( + type: string, + props?: ClassAttributes & P, + ...children: ReactNode[]): DOMElement; function createElement

( type: SFC

, props?: Attributes & P, diff --git a/types/react/test/index.ts b/types/react/test/index.ts index 27acc07d34..66b8c24bac 100644 --- a/types/react/test/index.ts +++ b/types/react/test/index.ts @@ -190,8 +190,12 @@ var classicElement: React.ClassicElement = React.createElement(ClassicComponent, props); var domElement: React.ReactHTMLElement = React.createElement("div"); -var htmlElement = React.createElement("input", { type: "text" }); -var svgElement = React.createElement("svg", { accentHeight: 12 }); +var literalHtmlElement = React.createElement("input", { type: "text" }); +var literalSvgElement = React.createElement("svg", { accentHeight: 12 }); + +declare let cardhtml: React.HTMLProps; +declare let accessKey: string; +var nonLiteralElement = React.createElement(accessKey, cardhtml); // React.cloneElement var clonedElement: React.CElement = diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index 22b23ee23f..acf1dcc857 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for redux-form 6.6 // Project: https://github.com/erikras/redux-form -// Definitions by: Carson Full , Daniel Lytkin , Karol Janyst +// Definitions by: Carson Full , Daniel Lytkin , Karol Janyst , Luka Zakrajsek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -41,5 +41,6 @@ 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/lib/Field.d.ts b/types/redux-form/lib/Field.d.ts index d2439d87a6..ecef15b4c7 100644 --- a/types/redux-form/lib/Field.d.ts +++ b/types/redux-form/lib/Field.d.ts @@ -278,7 +278,7 @@ interface WrappedFieldMetaProps { * The error for this field if its value is not passing validation. Both * synchronous, asynchronous, and submit validation errors will be reported here. */ - error?: string; + error?: any; /** * The name of the form. Could be useful if you want to manually dispatch actions. @@ -329,5 +329,5 @@ interface WrappedFieldMetaProps { /** * The warning for this field if its value is not passing warning validation. */ - warning?: string; + warning?: any; } diff --git a/types/redux-form/lib/actionTypes.d.ts b/types/redux-form/lib/actionTypes.d.ts new file mode 100644 index 0000000000..ce1ba5d208 --- /dev/null +++ b/types/redux-form/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/lib/actions.d.ts b/types/redux-form/lib/actions.d.ts index c96d5ffbb7..b126549f68 100644 --- a/types/redux-form/lib/actions.d.ts +++ b/types/redux-form/lib/actions.d.ts @@ -1,81 +1,87 @@ 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): Action; +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): Action; +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): Action; +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): Action; +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): Action; +export function arrayRemove(form: string, field: string, index: number): FormAction; /** * Removes all items from a field array */ -export function arrayRemoveAll(form: string, field: string): Action; +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): Action; +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): Action; +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): Action; +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): Action; +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): Action; +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): Action; +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): Action; +export function change(form: string, field: string, value: any): FormAction; /** * Destroys the form, removing all it's state */ -export function destroy(...form: string[]): Action; +export function destroy(...form: string[]): FormAction; /** * Marks the given field as active and visited */ -export function focus(form: string, field: string): Action; +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. @@ -88,67 +94,67 @@ interface InitializeOptions { keepSubmitSucceeded: boolean; } -export function initialize(form: string, data: any, keepDirty?: boolean | InitializeOptions, options?: InitializeOptions): Action; +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): Action; +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): Action; +export function reset(form: string): FormAction; /** * Flips the asyncValidating flag true */ -export function startAsyncValidation(form: string): Action; +export function startAsyncValidation(form: string): FormAction; /** * Flips the asyncValidating flag false and populates asyncError for each field. */ -export function stopAsyncValidation(form: string, errors?: any): Action; +export function stopAsyncValidation(form: string, errors?: any): FormAction; -export function setSubmitFailed(form: string, ...fields: string[]): Action; +export function setSubmitFailed(form: string, ...fields: string[]): FormAction; -export function setSubmitSucceeded(form: string, ...fields: string[]): Action; +export function setSubmitSucceeded(form: string, ...fields: string[]): FormAction; /** * Flips the submitting flag true. */ -export function startSubmit(form: string): Action; +export function startSubmit(form: string): FormAction; /** * Flips the submitting flag false and populates submitError for each field. */ -export function stopSubmit(form: string, errors?: any): Action; +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): Action; +export function stopAsyncValidation(form: string, errors?: any): FormAction; /** * Triggers a submission of the specified form. */ -export function submit(form: string): Action; +export function submit(form: string): FormAction; /** * Marks all the fields passed in as touched. */ -export function touch(form: string, ...fields: string[]): Action; +export function touch(form: string, ...fields: string[]): FormAction; /** * Unregisters a field with the form. */ -export function unregisterField(form: string, name: string): Action; +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[]): Action; +export function untouch(form: string, ...fields: string[]): FormAction; -export function updateSyncErrors(from: string, syncErrors: FormErrors, error: any): Action; +export function updateSyncErrors(from: string, syncErrors: FormErrors, error: any): FormAction; -export function updateSyncWarnings(form: string, syncWarnings: FormWarnings, warning: any): Action; +export function updateSyncWarnings(form: string, syncWarnings: FormWarnings, warning: any): FormAction; diff --git a/types/redux-form/lib/reducer.d.ts b/types/redux-form/lib/reducer.d.ts index 9b7f3ed520..f1dc6315bf 100644 --- a/types/redux-form/lib/reducer.d.ts +++ b/types/redux-form/lib/reducer.d.ts @@ -1,9 +1,7 @@ import { Action, Reducer } from "redux"; import { FieldType } from "../index"; -export function reducer(state: FormStateMap, action: Action): FormStateMap & FormReducer; - -export interface FormReducer { +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 @@ -11,9 +9,11 @@ export interface FormReducer { * passed to each reducer will only be the slice that pertains to that * form. */ - plugin(reducers: FormReducerMapObject): Reducer; + plugin(reducers: FormReducerMapObject): Reducer; } +export const reducer: FormReducer; + export interface FormReducerMapObject { [formName: string]: Reducer; } diff --git a/types/redux-form/lib/reduxForm.d.ts b/types/redux-form/lib/reduxForm.d.ts index 61fb88ac23..f1eac8d928 100644 --- a/types/redux-form/lib/reduxForm.d.ts +++ b/types/redux-form/lib/reduxForm.d.ts @@ -339,18 +339,19 @@ export interface FormComponent extends Compone /** * These are the props that will be passed to your form component. - * Your form component's props can extend this interface. + * Your form component's props can extend this interface if you want + * to use strict checks. */ -export interface FormProps { +export interface StrictFormProps { /** * true if any of the fields have been marked as touched, false otherwise. */ - anyTouched?: boolean; + anyTouched: boolean; /** * A set of pre-bound action creators for you to operate on array fields in your form. */ - array?: { + array: { /** * Inserts a value into the given array field in your form. */ @@ -407,7 +408,7 @@ export interface FormProps { * A function that may be called to initiate asynchronous validation if * asynchronous validation is enabled. */ - asyncValidate?: () => void; + asyncValidate: () => void; /** * This value will be either: @@ -415,54 +416,54 @@ export interface FormProps { * - 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; + 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; + autofill(field: string, value: FieldValue): void; /** * Marks a field as blurred in the Redux store. */ - blur?(field: string, value: FieldValue): void; + blur(field: string, value: FieldValue): void; /** * Changes the value of a field in the Redux store. */ - change?(field: string, value: FieldValue): void; + change(field: string, value: FieldValue): void; /** * Clear async error of a field in the Redux store. */ - clearAsyncError?(field: string): 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; + destroy(): void; /** * true if the form data has changed from its initialized values. Opposite * of pristine. */ - dirty?: boolean; + 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; + 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; + form: string; /** * A function meant to be passed to

or to @@ -484,79 +485,87 @@ export interface FormProps { * may pass that as if it were the error for a field called _error, and * it will be given as the error prop. */ - handleSubmit?(event: SyntheticEvent): void; // same as ReactEventHandler + handleSubmit(event: SyntheticEvent): void; // same as ReactEventHandler - handleSubmit?(submit: SubmitHandler): ReactEventHandler; + handleSubmit(submit: SubmitHandler): ReactEventHandler; /** * Initializes the form data to the given values. All dirty and pristine * state will be determined by comparing the current data with these * initialized values. */ - initialize?(data: FormData): void; + initialize(data: FormData): void; /** * The same initialValues object passed to reduxForm to initialize the form data. */ - initialValues?: Partial; + initialValues: Partial; /** * true if the form has validation errors. Opposite of valid. */ - invalid?: boolean; + invalid: boolean; /** * true if the form data is the same as its initialized values. Opposite * of dirty. */ - pristine?: boolean; + pristine: boolean; /** * Resets all the values in the form to the initialized state, making it * pristine again. */ - reset?(): void; + reset(): void; /** * Whether or not your form is currently submitting. This prop will only * work if you have passed an onSubmit function that returns a promise. It * will be true until the promise is resolved or rejected. */ - submitting?: boolean; + submitting: boolean; /** * Starts as false. If onSubmit is called, and fails to submit for any * reason, submitFailed will be set to true. A subsequent successful * submit will set it back to false. */ - submitFailed?: boolean; + submitFailed: boolean; /** * Starts as false. If onSubmit is called, and succeed to submit, * submitSucceeded will be set to true. A subsequent unsuccessful * submit will set it back to false. */ - submitSucceeded?: boolean; + submitSucceeded: boolean; /** * Marks the given fields as "touched" to show errors. */ - touch?(...field: string[]): void; + touch(...field: string[]): void; /** * Clears the "touched" flag for the given fields */ - untouch?(...field: string[]): void; + untouch(...field: string[]): void; /** * true if the form passes validation (has no validation errors). Opposite * of invalid. */ - valid?: boolean; + valid: boolean; /** * A generic warning for the entire form given by the `_warning` key in the result from the * synchronous warning function. */ - warning?: string; + warning: string; +} + +/** + * These are the props that will be passed to your form component. + * Your form component's props can extend this interface. + */ +export interface FormProps extends Partial> { + } diff --git a/types/redux-form/redux-form-tests.tsx b/types/redux-form/redux-form-tests.tsx index 7d3dbdd483..086e03f319 100644 --- a/types/redux-form/redux-form-tests.tsx +++ b/types/redux-form/redux-form-tests.tsx @@ -1,6 +1,7 @@ import * as React from 'react'; import { Component } from 'react'; -import { Field, GenericField, reduxForm, WrappedFieldProps, BaseFieldProps, FormProps } from "redux-form"; +import { Action } from 'redux'; +import { Field, GenericField, reduxForm, WrappedFieldProps, BaseFieldProps, FormProps, FormAction, actionTypes, reducer } from "redux-form"; interface CustomComponentProps { customProp: string; @@ -141,3 +142,23 @@ 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/selectize/index.d.ts b/types/selectize/index.d.ts index a9b7d77e7e..f6c2498d70 100644 --- a/types/selectize/index.d.ts +++ b/types/selectize/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Selectize 0.12.13 +// Type definitions for Selectize 0.12.14 // Project: https://github.com/brianreavis/selectize.js // Definitions by: Adi Dahiya , Natalie Bausch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -149,11 +149,11 @@ declare namespace Selectize { selectOnTab?: boolean; /** - * An array of plugins to use + * Plugins to use * * Default: null */ - plugins?: string[]; + plugins?: string[] | IPluginOption[] | { [name: string]: any }; // Data / Searching // ------------------------------------------------------------------------------------------------------------ @@ -369,6 +369,15 @@ declare namespace Selectize { // see https://github.com/brianreavis/selectize.js/blob/master/docs/api.md interface IApi { + /** + * An array of selected values. + */ + items: T[]; + + /** + * An object containing the entire pool of options. The object is keyed by each object's value. + */ + options: { [value: string]: U }; // Dropdown Options // ------------------------------------------------------------------------------------------------------------ @@ -398,7 +407,7 @@ declare namespace Selectize { /** * Retrieves the jQuery element for the option identified by the given value. */ - getOption(value: T): any; + getOption(value: T): JQuery; /** * Retrieves the jQuery element for the previous or next option, relative to the currently highlighted option. @@ -543,8 +552,8 @@ declare namespace Selectize { /** * Resets the selected items to the given value(s). */ - setValue(value: T): void; - setValue(value: T[]): void; + setValue(value: T, silent?: boolean): void; + setValue(value: T[], silent?: boolean): void; /** * Moves the caret to the specified position ("index" being the index in the list of selected items). @@ -603,6 +612,12 @@ declare namespace Selectize { */ items: ISearchResult[]; } + + // see https://github.com/selectize/selectize.js/blob/master/docs/plugins.md + interface IPluginOption { + name: string; + options: any; + } } interface JQuery { diff --git a/types/selectize/selectize-tests.ts b/types/selectize/selectize-tests.ts index 6e66ba0992..a51b121d89 100644 --- a/types/selectize/selectize-tests.ts +++ b/types/selectize/selectize-tests.ts @@ -417,3 +417,41 @@ $("#select-car").selectize({ plugins: ['optgroup_columns'], openOnFocus: false }); + +// Plugins example +// -------------------------------------------------------------------------------------------------------------------- +$('.input-tags').selectize({ + plugins: ['remove_button'], + persist: false, + create: true, + render: { + item: function(data, escape) { + return '
"' + escape(data.text) + '"
'; + } + }, + onDelete: function(values) { + return confirm(values.length > 1 ? 'Are you sure you want to remove these ' + values.length + ' items?' : 'Are you sure you want to remove "' + values[0] + '"?'); + } +}); + +$('#input-tags6').selectize({ + plugins: ['restore_on_backspace'], + persist: false, + create: true +}); + +$('.input-sortable').selectize({ + plugins: ['drag_drop'], + persist: false, + create: true +}); + +$('.demo-code-language').selectize({ + sortField: 'text', + hideSelected: false, + plugins: { + 'dropdown_header': { + title: 'Language' + } + } +}); diff --git a/types/send/index.d.ts b/types/send/index.d.ts index 4b738fa011..6c38861c4f 100644 --- a/types/send/index.d.ts +++ b/types/send/index.d.ts @@ -197,7 +197,7 @@ declare namespace send { /** * Pipe to `res`. */ - pipe(res: stream.Writable): stream.Writable; + pipe(res: T): T; /** * Transfer `path`. diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index 86ecb00809..cb117779cd 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -259,7 +259,7 @@ declare namespace sequelize { /** * An optional where clause to limit the associated models. */ - where?: WhereOptions; + where?: AnyWhereOptions; /** * Apply a scope on the related model, or remove its default scope by passing false. @@ -346,7 +346,7 @@ declare namespace sequelize { */ ( newAssociations?: Array, - options?: HasManySetAssociationsMixinOptions | FindOptions | InstanceUpdateOptions + options?: HasManySetAssociationsMixinOptions | AnyFindOptions | InstanceUpdateOptions ): Promise; } @@ -672,7 +672,7 @@ declare namespace sequelize { /** * An optional where clause to limit the associated models. */ - where?: WhereOptions; + where?: AnyWhereOptions; /** * Apply a scope on the related model, or remove its default scope by passing false. @@ -722,7 +722,7 @@ declare namespace sequelize { /** * An optional where clause to limit the associated models. */ - where?: WhereOptions; + where?: AnyWhereOptions; /** * Apply a scope on the related model, or remove its default scope by passing false. @@ -809,7 +809,7 @@ declare namespace sequelize { */ ( newAssociations?: Array, - options?: BelongsToManySetAssociationsMixinOptions | FindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes } + options?: BelongsToManySetAssociationsMixinOptions | AnyFindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes } ): Promise; } @@ -858,7 +858,7 @@ declare namespace sequelize { */ ( newAssociations?: Array, - options?: BelongsToManyAddAssociationsMixinOptions | FindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes } + options?: BelongsToManyAddAssociationsMixinOptions | AnyFindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes } ): Promise; } @@ -907,7 +907,7 @@ declare namespace sequelize { */ ( newAssociation?: TInstance | TInstancePrimaryKey, - options?: BelongsToManyAddAssociationMixinOptions | FindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes } + options?: BelongsToManyAddAssociationMixinOptions | AnyFindOptions | BulkCreateOptions | InstanceUpdateOptions | InstanceDestroyOptions | { through: TJoinTableAttributes } ): Promise; } @@ -1135,7 +1135,7 @@ declare namespace sequelize { /** * An optional where clause to limit the associated models. */ - where?: WhereOptions; + where?: AnyWhereOptions; /** * Apply a scope on the related model, or remove its default scope by passing false. @@ -1353,6 +1353,11 @@ declare namespace sequelize { */ otherKey?: string | AssociationForeignKeyOptions; + /** + * Should the join model have timestamps + */ + timestamps?: boolean; + } /** @@ -2613,7 +2618,7 @@ declare namespace sequelize { /** * A hash of attributes to describe your search. See above for examples. */ - where?: WhereOptions | Array; + where?: AnyWhereOptions | Array; } @@ -2663,7 +2668,7 @@ declare namespace sequelize { /** * A hash of attributes to describe your search. See above for examples. */ - where?: WhereOptions | Array; + where?: AnyWhereOptions | Array; } @@ -2824,7 +2829,7 @@ declare namespace sequelize { * return a new instance. With this method, all references to the Instance are updated with the new data * and no new objects are created. */ - reload(options?: FindOptions): Promise; + reload(options?: AnyFindOptions): Promise; /** * Validate the attribute of this instance according to validation rules set in the model definition. @@ -3031,8 +3036,8 @@ declare namespace sequelize { * Where Complex nested query */ interface WhereNested { - $and: Array; - $or: Array; + $and: Array; + $or: Array; } /** @@ -3054,10 +3059,10 @@ declare namespace sequelize { /** * Logic of where statement */ - interface WhereLogic { + type WhereLogic = Partial<{ $ne: string | number | WhereLogic; $in: Array | literal; - $not: boolean | string | number | WhereOptions; + $not: boolean | string | number | AnyWhereOptions; $notIn: Array | literal; $gte: number | string | Date; $gt: number | string | Date; @@ -3078,7 +3083,7 @@ declare namespace sequelize { "@>": any; $contained: any; "<@": any; - } + }>; /** * A hash of attributes to describe your search. See above for examples. @@ -3086,8 +3091,15 @@ declare namespace sequelize { * We did put Object in the end, because there where query might be a JSON Blob. It cripples a bit the * typesafety, but there is no way to pass the tests if we just remove it. */ - interface WhereOptions { - [field: string]: string | number | WhereLogic | WhereOptions | col | and | or | WhereGeometryOptions | Array | Object | null; + type WhereOptions = { + [P in keyof T]?: string | number | WhereLogic | WhereOptions | col | and | or | WhereGeometryOptions | Array | null; + }; + + /** + * A hash of attributes to describe your search, accepting any field names. See `WhereOptions` for details. + */ + interface AnyWhereOptions { + [field: string]: WhereOptions[] | Object; } /** @@ -3098,7 +3110,7 @@ declare namespace sequelize { /** * Filter on the join model for belongsToMany relations */ - where?: WhereOptions; + where?: AnyWhereOptions; /** * A list of attributes to select from the join model for belongsToMany relations @@ -3141,7 +3153,7 @@ declare namespace sequelize { * Where clauses to apply to the child models. Note that this converts the eager load to an inner join, * unless you explicitly set `required: false` */ - where?: WhereOptions; + where?: AnyWhereOptions; /** * A list of attributes to select from the child model @@ -3183,12 +3195,12 @@ declare namespace sequelize { * * A hash of options to describe the scope of the search */ - interface FindOptions extends LoggingOptions, SearchPathOptions { + interface FindOptions extends LoggingOptions, SearchPathOptions { /** * A hash of attributes to describe your search. See above for examples. */ - where?: WhereOptions | fn | Array; + where?: WhereOptions | fn | Array; /** * A list of the attributes that you want to select. To rename an attribute, you can pass an array, with @@ -3245,7 +3257,7 @@ declare namespace sequelize { /** * having ?!? */ - having?: WhereOptions; + having?: AnyWhereOptions; /** * Group by. It is not mentioned in sequelize's JSDoc, but mentioned in docs. @@ -3265,6 +3277,8 @@ declare namespace sequelize { subQuery?: boolean; } + type AnyFindOptions = FindOptions; + /** * Options for Model.count method */ @@ -3273,7 +3287,7 @@ declare namespace sequelize { /** * A hash of search attributes. */ - where?: WhereOptions | string[]; + where?: AnyWhereOptions | string[]; /** * Include options. See `find` for details @@ -3335,7 +3349,7 @@ declare namespace sequelize { /** * Options for Model.findOrInitialize method */ - interface FindOrInitializeOptions extends FindOptions { + interface FindOrInitializeOptions extends AnyFindOptions { /** * Default values to use if building a new instance @@ -3347,7 +3361,7 @@ declare namespace sequelize { /** * Options for Model.findOrInitialize method */ - interface FindCreateFindOptions extends FindOptions { + interface FindCreateFindOptions extends FindOptions { /** * Default values to use if building a new instance @@ -3423,7 +3437,7 @@ declare namespace sequelize { /** * Filter the destroy */ - where?: WhereOptions; + where?: AnyWhereOptions; /** * Run before / after bulk destroy hooks? @@ -3462,7 +3476,7 @@ declare namespace sequelize { /** * Filter the restore */ - where?: WhereOptions; + where?: AnyWhereOptions; /** * Run before / after bulk restore hooks? @@ -3495,7 +3509,7 @@ declare namespace sequelize { /** * Options to describe the scope of the search. */ - where: WhereOptions; + where: AnyWhereOptions; /** * Run before / after bulk update hooks? @@ -3543,7 +3557,7 @@ declare namespace sequelize { /** * A hash of search attributes. */ - where?: WhereOptions; + where?: AnyWhereOptions; /** * The type of the result. If `field` is a field in this Model, the default will be the type of that field, @@ -3634,7 +3648,7 @@ declare namespace sequelize { * @param {Object} [options] * @param {Boolean} [options.override=false] */ - addScope(name: string, scope: FindOptions | Function, options?: AddScopeOptions): void; + addScope(name: string, scope: AnyFindOptions | Function, options?: AddScopeOptions): void; /** * Add a new scope to the model. This is especially useful for adding scopes with includes, when the model you want to include is not available at the time this model is defined. @@ -3646,7 +3660,7 @@ declare namespace sequelize { * @param {Object} [options] * @param {Boolean} [options.override=false] */ - addScope(name: string, scope: FindOptions | Function, options?: AddScopeOptions): void; + addScope(name: string, scope: AnyFindOptions | Function, options?: AddScopeOptions): void; /** * Apply a scope created in `define` to the model. First let's look at how to create scopes: @@ -3695,7 +3709,7 @@ declare namespace sequelize { * @return Model A reference to the model, with the scope(s) applied. Calling scope again on the returned * model will clear the previous scope. */ - scope(options?: string | ScopeOptions | WhereOptions | Array): this; + scope(options?: string | ScopeOptions | AnyWhereOptions | Array): this; /** * Search for multiple instances. @@ -3759,22 +3773,22 @@ declare namespace sequelize { * * @see {Sequelize#query} */ - findAll(options?: FindOptions): Promise; - all(optionz?: FindOptions): Promise; + findAll(options?: FindOptions): Promise; + all(optionz?: FindOptions): Promise; /** * Search for a single instance by its primary key. This applies LIMIT 1, so the listener will * always be called with a single instance. */ - findById(identifier?: number | string, options?: FindOptions): Promise; - findByPrimary(identifier?: number | string, options?: FindOptions): Promise; + findById(identifier?: number | string, options?: FindOptions): Promise; + findByPrimary(identifier?: number | string, options?: FindOptions): Promise; /** * Search for a single instance. This applies LIMIT 1, so the listener will always be called with a single * instance. */ - findOne(options?: FindOptions): Promise; - find(options?: FindOptions): Promise; + findOne(options?: FindOptions): Promise; + find(options?: FindOptions): Promise; /** * Run an aggregation method on the specified field @@ -3829,8 +3843,8 @@ declare namespace sequelize { * without * profiles will be counted */ - findAndCount(options?: FindOptions): Promise<{ rows: TInstance[], count: number }>; - findAndCountAll(options?: FindOptions): Promise<{ rows: TInstance[], count: number }>; + findAndCount(options?: FindOptions): Promise<{ rows: TInstance[], count: number }>; + findAndCountAll(options?: FindOptions): Promise<{ rows: TInstance[], count: number }>; /** * Find the maximum value of field @@ -3886,7 +3900,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; /** * Insert or update a single row. An update will be executed if a row which matches the supplied values on @@ -3994,7 +4008,7 @@ declare namespace sequelize { interface AddCheckConstraintOptions { type: 'check'; name?: string; - where?: WhereOptions; + where?: AnyWhereOptions; } interface AddPrimaryKeyConstraintOptions { @@ -4850,7 +4864,7 @@ declare namespace sequelize { /** * Condition for partioal index */ - where?: WhereOptions; + where?: AnyWhereOptions; } @@ -4901,7 +4915,7 @@ declare namespace sequelize { /** * Name of the scope and it's query */ - [scopeName: string]: FindOptions | Function; + [scopeName: string]: AnyFindOptions | Function; } @@ -4916,7 +4930,7 @@ declare namespace sequelize { * Define the default search scope to use for this model. Scopes have the same form as the options passed to * find / findAll. */ - defaultScope?: FindOptions; + defaultScope?: AnyFindOptions; /** * More scopes, defined in the same way as defaultScope above. See `Model.scope` for more information about diff --git a/types/sequelize/sequelize-tests.ts b/types/sequelize/sequelize-tests.ts index d786dfc4a2..fcb273f5e2 100644 --- a/types/sequelize/sequelize-tests.ts +++ b/types/sequelize/sequelize-tests.ts @@ -1318,7 +1318,7 @@ s.define( 'ProductWithSettersAndGetters1', { get : function() { return 'answer = ' + this.getDataValue( 'price' ); }, - set : function( v ) { + set : function( v: number ) { return this.setDataValue( 'price', v + 42 ); } } @@ -1437,6 +1437,37 @@ s.define( 'ScopeMe', { } } ); +// Generic find options +interface ChairAttributes { + id: number; + color: string; + legs: number; +} +interface ChairInstance extends Sequelize.Instance {} + +const Chair = s.define('chair', {}); + +Chair.findAll({ + where: { + color: 'blue', + legs: { $in: [3, 4] }, + }, +}); + +// If you want to use a property that isn't explicitly on the model's Attributes +// use the find-function's generic type parameter. +Chair.findAll<{ customProperty: number }>({ + where: { + customProperty: 123, + } +}); +Chair.findAll({ + where: { + customProperty1: 123, + customProperty2: 456, + } +}); + s.define( 'ScopeMe', { username : Sequelize.STRING, email : Sequelize.STRING, diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index e9b0018ed7..df3a7e709f 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -7,8 +7,9 @@ /// -import * as stream from 'stream'; +import * as fs from 'fs'; import * as https from 'https'; +import * as stream from 'stream'; type CallbackHandler = (err: any, res: request.Response) => void; @@ -96,7 +97,7 @@ declare namespace request { interface Request extends Promise /* extends NodeJS.WritableStream */ { abort(): void; accept(type: string): this; - attach(field: string, file: string | Blob, filename?: string): this; + attach(field: string, file: Blob | Buffer | fs.ReadStream | string, filename?: string): this; auth(user: string, name: string): this; buffer(val?: boolean): this; clearTimeout(): this; diff --git a/types/swiper/index.d.ts b/types/swiper/index.d.ts index e16c7d5cc5..57edc39a61 100644 --- a/types/swiper/index.d.ts +++ b/types/swiper/index.d.ts @@ -193,6 +193,10 @@ interface SwiperOptions { onLazyImageLoad?(swiper: Swiper, slide: any, image: any): void; onLazyImageReady?(swiper: Swiper, slide: any, image: any): void; onPaginationRendered?(swiper: Swiper, paginationContainer: any): void; + onScroll?(swiper: Swiper, event: Event): void; + onBeforeResize?(swiper: Swiper): void; + onAfterResize?(swiper: Swiper): void; + onKeyPress?(swiper: Swiper, kc: any): void; // Namespace slideClass?: string; @@ -237,6 +241,8 @@ declare class Swiper { height: number; params: any; positions: any; + wrapper: any; + virtualSize: number; // Feature detection support: { diff --git a/types/tinymce/index.d.ts b/types/tinymce/index.d.ts index 59156c6c13..11196fd6e4 100644 --- a/types/tinymce/index.d.ts +++ b/types/tinymce/index.d.ts @@ -282,6 +282,14 @@ export interface Settings { autosave_restore_when_empty?: boolean; autosave_retention?: string; + + imagetools_cors_hosts?: string[]; + + imagetools_proxy?: string; + + imagetools_toolbar?: string; + + imagetools_api_key?: string; } export namespace settings { diff --git a/types/tinymce/tinymce-tests.ts b/types/tinymce/tinymce-tests.ts index 921edffaea..2b32824349 100644 --- a/types/tinymce/tinymce-tests.ts +++ b/types/tinymce/tinymce-tests.ts @@ -8,7 +8,7 @@ tinymce.init({ 'advlist autolink lists link image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table contextmenu paste code', - 'autosave' + 'autosave imagetools' ], autosave_ask_before_unload: false, autosave_interval: "20s", @@ -16,7 +16,9 @@ tinymce.init({ autosave_restore_when_empty: false, autosave_retention: "30m", toolbar: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image', - content_css: '//www.tinymce.com/css/codepen.min.css' + content_css: '//www.tinymce.com/css/codepen.min.css', + imagetools_cors_hosts: ['mydomain.com', 'otherdomain.com'], + imagetools_proxy: "proxy.php" }); const t = new tinymce.util.Color('#FFFFFF'); diff --git a/types/wellknown/index.d.ts b/types/wellknown/index.d.ts new file mode 100644 index 0000000000..0b100e5c33 --- /dev/null +++ b/types/wellknown/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for wellknown 0.5 +// Project: https://github.com/mapbox/wellknown#readme +// Definitions by: Yair Tawil +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function parse(input: string): {}; +export function stringify(gj: {}): string; diff --git a/types/wellknown/tsconfig.json b/types/wellknown/tsconfig.json new file mode 100644 index 0000000000..66be74a40f --- /dev/null +++ b/types/wellknown/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", + "wellknown-tests.ts" + ] +} diff --git a/types/wellknown/tslint.json b/types/wellknown/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/wellknown/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/wellknown/wellknown-tests.ts b/types/wellknown/wellknown-tests.ts new file mode 100644 index 0000000000..0f1bcd656e --- /dev/null +++ b/types/wellknown/wellknown-tests.ts @@ -0,0 +1,7 @@ +import * as wellknown from 'wellknown'; +wellknown.parse("POINT(1 2)"); +const geoJson: {} = { + coordinates: [1, 2], + type: "Point" +}; +wellknown.stringify(geoJson); diff --git a/types/ws/index.d.ts b/types/ws/index.d.ts index 49ae4cfb3e..fc072727e8 100644 --- a/types/ws/index.d.ts +++ b/types/ws/index.d.ts @@ -155,7 +155,7 @@ declare namespace WebSocket { export class Server extends events.EventEmitter { options: IServerOptions; path: string; - clients: WebSocket[]; + clients: Set; constructor(options?: IServerOptions, callback?: Function); diff --git a/types/ws/ws-tests.ts b/types/ws/ws-tests.ts index 4da29311ee..90b0e6080f 100644 --- a/types/ws/ws-tests.ts +++ b/types/ws/ws-tests.ts @@ -34,9 +34,8 @@ import * as https from 'https'; { var wss = new WebSocket.Server({port: 8082}); - const broadcast = function(data: any) { - for(var i in wss.clients) - wss.clients[i].send(data); + const broadcast = (data: any) => { + wss.clients.forEach((ws) => ws.send(data)); }; } diff --git a/types/yargs/index.d.ts b/types/yargs/index.d.ts index 9c581611db..faf26b3fa8 100644 --- a/types/yargs/index.d.ts +++ b/types/yargs/index.d.ts @@ -1,13 +1,21 @@ -// Type definitions for yargs 6.6.0 +// Type definitions for yargs 8.0 // Project: https://github.com/chevex/yargs -// Definitions by: Martin Poelstra , Mizunashi Mana , Jeffery Grajkowski , Jeff Kenney +// Definitions by: Martin Poelstra +// Mizunashi Mana +// Jeffery Grajkowski +// Jeff Kenney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +// unified-signatures: Because there is useful information in the argument names of the overloaded signatures +// prefer-method-signature: Because it makes more sense for optional functions provided in options objects +/* tslint:disable:unified-signatures prefer-method-signature */ declare namespace yargs { interface Argv { - argv: any; - (...args: any[]): any; - parse(...args: any[]): any; + argv: Arguments; + (args?: string[], cwd?: string): Arguments; + parse(args: string | string[], context?: object, parseCallback?: ParseCallback): Arguments; reset(): Argv; @@ -18,9 +26,9 @@ declare namespace yargs { terminalWidth(): number; - alias(shortName: string, longName: string): Argv; - alias(aliases: { [shortName: string]: string }): Argv; - alias(aliases: { [shortName: string]: string[] }): Argv; + alias(shortName: string, longName: string | string[]): Argv; + alias(shortNames: string[], longName: string): Argv; + alias(aliases: { [shortName: string]: string | string[] }): Argv; array(key: string): Argv; array(keys: string[]): Argv; @@ -68,7 +76,7 @@ declare namespace yargs { requiresArg(key: string): Argv; requiresArg(keys: string[]): Argv; - describe(key: string, description: string): Argv; + describe(key: string | string[], description: string): Argv; describe(descriptions: { [key: string]: string }): Argv; option(key: string, options: Options): Argv; @@ -82,8 +90,8 @@ declare namespace yargs { command(command: string, description: string): Argv; command(command: string, description: string, builder: (args: Argv) => Argv): Argv; command(command: string, description: string, builder: { [optionName: string]: Options }): Argv; - command(command: string, description: string, builder: { [optionName: string]: Options }, handler: (args: any) => void): Argv; - command(command: string, description: string, builder: (args: Argv) => Argv, handler: (args: any) => void): Argv; + command(command: string, description: string, builder: { [optionName: string]: Options }, handler: (args: Arguments) => void): Argv; + command(command: string, description: string, builder: (args: Argv) => Argv, handler: (args: Arguments) => void): Argv; command(command: string, description: string, module: CommandModule): Argv; command(module: CommandModule): Argv; @@ -97,7 +105,7 @@ declare namespace yargs { example(command: string, description: string): Argv; - check(func: (argv: any, aliases: { [alias: string]: string }) => any): Argv; + check(func: (argv: Arguments, aliases: { [alias: string]: string }) => any): Argv; boolean(key: string): Argv; boolean(keys: string[]): Argv; @@ -108,15 +116,15 @@ declare namespace yargs { number(key: string): Argv; number(keys: string[]): Argv; - choices(choices: Object): Argv; - choices(key: string, values: any[]): Argv; + choices(choices: { [argName: string]: Choices }): Argv; + choices(key: string, values: Choices): Argv; config(): Argv; - config(explicitConfigurationObject: Object): Argv; - config(key: string, description?: string, parseFn?: (configPath: string) => Object): Argv; - config(keys: string[], description?: string, parseFn?: (configPath: string) => Object): Argv; - config(key: string, parseFn: (configPath: string) => Object): Argv; - config(keys: string[], parseFn: (configPath: string) => Object): Argv; + config(explicitConfigurationObject: object): Argv; + config(key: string, description?: string, parseFn?: (configPath: string) => object): Argv; + config(keys: string[], description?: string, parseFn?: (configPath: string) => object): Argv; + config(key: string, parseFn: (configPath: string) => object): Argv; + config(keys: string[], parseFn: (configPath: string) => object): Argv; conflicts(key: string, value: string): Argv; conflicts(conflicts: { [key: string]: string }): Argv; @@ -180,9 +188,19 @@ declare namespace yargs { skipValidation(key: string): Argv; skipValidation(keys: string[]): Argv; - updateLocale(obj: Object): Argv; + updateLocale(obj: { [key: string]: string }): Argv; - updateStrings(obj: {[key: string]: string}): Argv; + updateStrings(obj: { [key: string]: string }): Argv; + } + + interface Arguments { + /** Non-option arguments */ + _: string[]; + /** The script name or node command */ + $0: string; + + /** All remaining options */ + [ argName: string ]: any; } interface RequireDirectoryOptions { @@ -197,10 +215,11 @@ declare namespace yargs { alias?: string | string[]; array?: boolean; boolean?: boolean; - choices?: string[]; + choices?: Choices; coerce?: (arg: any) => any; config?: boolean; - configParser?: (configPath: string) => Object; + configParser?: (configPath: string) => object; + conflicts?: string | object; count?: boolean; default?: any; defaultDescription?: string; @@ -212,6 +231,7 @@ declare namespace yargs { description?: string; global?: boolean; group?: string; + implies?: string | object; nargs?: number; normalize?: boolean; number?: boolean; @@ -231,9 +251,12 @@ declare namespace yargs { handler: (args: any) => void; } - type CommandBuilder = {[key: string]: Options} | ((args: Argv) => Argv); + type ParseCallback = (err: Error | undefined, argv: Arguments, output: string) => void; + type CommandBuilder = { [key: string]: Options } | ((args: Argv) => Argv); type SyncCompletionFunction = (current: string, argv: any) => string[]; type AsyncCompletionFunction = (current: string, argv: any, done: (completion: string[]) => void) => void; + type Choice = string | true | undefined; + type Choices = Choice[]; } declare var yargs: yargs.Argv; diff --git a/types/yargs/tslint.json b/types/yargs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/yargs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/yargs/yargs-tests.ts b/types/yargs/yargs-tests.ts index f68c1113e9..2c0756d427 100644 --- a/types/yargs/yargs-tests.ts +++ b/types/yargs/yargs-tests.ts @@ -12,31 +12,30 @@ const stringVal = 'string'; // With yargs, the options be just a hash! function xup() { - var argv = yargs.argv; + let argv = yargs.argv; if (argv.rif - 5 * argv.xup > 7.138) { console.log('Plunder more riffiwobbles!'); - } - else { + } else { console.log('Drop the xupptumblers!'); } } // And non-hyphenated options too! Just use argv._! function nonopt() { - var argv = yargs.argv; + let argv = yargs.argv; console.log('(%d,%d)', argv.x, argv.y); console.log(argv._); } // Yargs even counts your booleans! function count() { - var argv = yargs + let argv = yargs .count('verbose') .alias('v', 'verbose') .argv; - var VERBOSE_LEVEL: number = argv.verbose; + let VERBOSE_LEVEL: number = argv.verbose; function WARN() { VERBOSE_LEVEL >= 0 && console.log.apply(console, arguments); } function INFO() { VERBOSE_LEVEL >= 1 && console.log.apply(console, arguments); } @@ -45,7 +44,7 @@ function count() { // Tell users how to use yer options and make demands. function divide() { - var argv = yargs + let argv = yargs .usage('Usage: $0 -x [num] -y [num]') .demand(['x', 'y']) .argv; @@ -55,7 +54,7 @@ function divide() { // After yer demands have been met, demand more! Ask for non-hypenated arguments! function demand_count() { - var argv = yargs + let argv = yargs .demand(2) .demand(2, false) .demand(2, 2) @@ -66,63 +65,69 @@ function demand_count() { // EVEN MORE SHIVER ME TIMBERS! function default_singles() { - var argv = yargs + let argv = yargs .default('x', 10) .default('y', 10) .argv - ; + ; console.log(argv.x + argv.y); } function default_hash() { - var argv = yargs + let argv = yargs .default({ x: 10, y: 10 }) .argv - ; + ; console.log(argv.x + argv.y); } // And if you really want to get all descriptive about it... function boolean_single() { - var argv = yargs + let argv = yargs .boolean('v') .argv - ; + ; console.dir(argv.v); console.dir(argv._); } function boolean_double() { - var argv = yargs + let argv = yargs .boolean(['x', 'y', 'z']) .argv - ; + ; console.dir([argv.x, argv.y, argv.z]); console.dir(argv._); } // Yargs is here to help you... function line_count() { - var argv = yargs + let argv = yargs .usage('Count the lines in a file.\nUsage: $0') .example('$0 -f', 'count the lines in the given file') .demand('f') .alias('f', 'file') .describe('f', 'Load a file') .argv - ; + ; } // Below are tests for individual methods. // Not all methods are covered yet, and neither are all possible invocations of methods. +function Argv$argv() { + let argv = yargs.argv; + console.log("command name: " + argv.$0); + console.log("command: " + argv._[1]); +} + function Argv_parsing() { - var argv1 = yargs.argv; - var argv2 = yargs(['-x', '1', '-y', '2']).argv; - var argv3 = yargs.parse(['-x', '1', '-y', '2']); + let argv1 = yargs.argv; + let argv2 = yargs(['-x', '1', '-y', '2']).argv; + let argv3 = yargs.parse(['-x', '1', '-y', '2']); console.log(argv1.x, argv2.x, argv3.x); } function Argv$options() { - var argv1 = yargs + let argv1 = yargs .options('f', { alias: 'file', default: '/etc/passwd', @@ -131,61 +136,69 @@ function Argv$options() { normalize: true, global: false, array: true, - nargs: 3 + nargs: 3, + implies: 'other-arg', + conflicts: 'conflicting-arg', }) .argv - ; + ; - var argv2 = yargs + let argv2 = yargs .alias('f', 'file') .default('f', '/etc/passwd') .argv - ; + ; } function Argv$global() { - var argv = yargs + let argv = yargs .global('foo') - .global(['bar', 'baz', 'fizz', 'buzz']) + .global(['bar', 'baz', 'fizz', 'buzz']); } function Argv$group() { - var argv = yargs + let argv = yargs .group('foo', 'foogroup') - .group(['bing', 'bang', 'buzz'], 'onomatopoeia') + .group(['bing', 'bang', 'buzz'], 'onomatopoeia'); } function Argv$env() { - var argv = yargs + let argv = yargs .env('YARGS_PREFIX_') .env() .env(true); } function Argv$array() { - var argv = yargs + let argv = yargs .array('foo') - .array(['bar', 'baz']) + .array(['bar', 'baz']); } function Argv$nargs() { - var argv = yargs + let argv = yargs .nargs('foo', 12) - .nargs({ 'bing': 3, 'bang': 2, 'buzz': 4 }) + .nargs({ bing: 3, bang: 2, buzz: 4 }); } function Argv$choices() { // example from documentation - var argv = yargs - .alias('i', 'ingredient') - .describe('i', 'choose your sandwich ingredients') - .choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles']) - .help('help') - .argv + let argv = yargs + .alias('i', 'ingredient') + .describe('i', 'choose your sandwich ingredients') + .choices('i', ['peanut-butter', 'jelly', 'banana', 'pickles']) + .help('help') + .argv; + + yargs + .choices('i', [undefined, true, 'asdf', 'test']) + .choices({ + test: [undefined, true, 'test-value'] + }); } function command() { - var argv = yargs + let argv = yargs .usage('npm ') .command('install', 'tis a mighty fine package to install') .command('publish', 'shiver me timbers, should you be sharing all that', yargs => @@ -193,7 +206,7 @@ function command() { alias: 'force', description: 'yar, it usually be a bad idea' }) - .help('help') + .help('help') ) .command("build", "arghh, build it mate", { tag: { @@ -203,7 +216,7 @@ function command() { }, publish: { default: false, - description:"Should i publish?" + description: "Should i publish?" } }) .command({ @@ -227,35 +240,35 @@ function command() { .argv; yargs - .command('get', 'make a get HTTP request', function (yargs) { + .command('get', 'make a get HTTP request', (yargs) => { return yargs.option('url', { alias: 'u', default: 'http://yargs.js.org/' - }) + }); }) .help() - .argv + .argv; yargs .command( - 'get', - 'make a get HTTP request', - function (yargs) { - return yargs.option('u', { - alias: 'url', - describe: 'the URL to make an HTTP request to' - }) - }, - function (argv: { url: string }) { - console.dir(argv.url) - } + 'get', + 'make a get HTTP request', + (yargs) => { + return yargs.option('u', { + alias: 'url', + describe: 'the URL to make an HTTP request to' + }); + }, + (argv) => { + console.dir(argv.url); + } ) .help() - .argv + .argv; } function completion_sync() { - var argv = yargs + let argv = yargs .completion('completion', (current, argv) => { // 'current' is the current command being completed. // 'argv' is the parsed arguments so far. @@ -269,9 +282,9 @@ function completion_sync() { } function completion_async() { - var argv = yargs + let argv = yargs .completion('completion', (current: string, argv: any, done: (completion: string[]) => void) => { - setTimeout(function () { + setTimeout(() => { done([ 'apple', 'banana' @@ -282,14 +295,14 @@ function completion_async() { } function Argv$help() { - var argv = yargs + let argv = yargs .usage("$0 -operand1 number -operand2 number -operation [add|subtract]") .help() .argv; } function Argv$showHelpOnFail() { - var argv = yargs + let argv = yargs .usage('Count the lines in a file.\nUsage: $0') .demand('f') .alias('f', 'file') @@ -299,72 +312,72 @@ function Argv$showHelpOnFail() { } function Argv$showHelp() { - var yargs1 = yargs + let yargs1 = yargs .usage("$0 -operand1 number -operand2 number -operation [add|subtract]"); yargs1.showHelp(); } function Argv$version() { - var argv1 = yargs + let argv1 = yargs .version(); - var argv2 = yargs + let argv2 = yargs .version('1.0.0'); - var argv3 = yargs + let argv3 = yargs .version('1.0.0', '--version'); - var argv4 = yargs + let argv4 = yargs .version('1.0.0', '--version', 'description'); - var argv5 = yargs - .version(function () { return '1.0.0'; }, '--version', 'description'); + let argv5 = yargs + .version(() => '1.0.0', '--version', 'description'); } function Argv$wrap() { - var argv1 = yargs + let argv1 = yargs .wrap(null); - var argv2 = yargs + let argv2 = yargs .wrap(yargs.terminalWidth()); } function Argv$locale() { - var argv = yargs + let argv = yargs .usage('./$0 - follow ye instructions true') .option('option', { - alias: 'o', - describe: "'tis a mighty fine option", - demand: true + alias: 'o', + describe: "'tis a mighty fine option", + demand: true }) .command('run', "Arrr, ya best be knowin' what yer doin'") .example('$0 run foo', "shiver me timbers, here's an example for ye") .help('help') .wrap(70) .locale('pirate') - .argv + .argv; } function Argv$epilogue() { - var argv = yargs + let argv = yargs .epilogue('for more information, find our manual at http://example.com'); } function Argv$reset() { - var ya = yargs + let ya = yargs .usage('$0 command') .command('hello', 'hello command') .command('world', 'world command') - .demand(1, 'must provide a valid command'), - argv = yargs.argv, - command = argv._[0]; + .demand(1, 'must provide a valid command'); + let argv = yargs.argv; + let command = argv._[0]; if (command === 'hello') { ya.reset() .usage('$0 hello') .help('h') .example('$0 hello', 'print the hello message!') - .argv + .argv; console.log('hello!'); } else if (command === 'world') { @@ -372,7 +385,7 @@ function Argv$reset() { .usage('$0 world') .help('h') .example('$0 world', 'print the world message!') - .argv + .argv; console.log('world!'); } else { @@ -382,15 +395,14 @@ function Argv$reset() { // http://yargs.js.org/docs/#methods-commanddirdirectory-opts function Argv$commandDir() { - var ya = yargs + let ya = yargs .commandDir('.') - .argv + .argv; } - // http://yargs.js.org/docs/#methods-commanddirdirectory-opts function Argv$commandDirWithOptions() { - var ya = yargs + let ya = yargs .commandDir('.', { recurse: false, extensions: ['js'], @@ -398,166 +410,166 @@ function Argv$commandDirWithOptions() { include: /.*\.js$/, exclude: /.*\.spec.js$/, }) - .argv + .argv; } function Argv$normalize() { - var ya = yargs + let ya = yargs .normalize('path') .normalize(['user', 'group']) - .argv + .argv; } // From http://yargs.js.org/docs/#methods-coercekey-fn function Argv$coerce() { - var ya = yargs - .coerce('file', function (arg: string) { + let ya = yargs + .coerce('file', (arg: string) => { return fs.readFileSync(arg, 'utf8'); }) - .argv + .argv; } function Argv$coerces() { - var ya = yargs + let ya = yargs .coerce({ date: Date.parse, json: JSON.parse }) - .argv + .argv; } function Argv$coerceWithKeys() { - var ya = yargs + let ya = yargs .coerce(['src', 'dest'], path.resolve) - .argv + .argv; } // From http://yargs.js.org/docs/#methods-failfn function Argv$fail() { - var ya = yargs - .fail(function (msg, err) { - if (err) throw err // preserve stack - console.error('You broke it!') - console.error(msg) - process.exit(1) + let ya = yargs + .fail((msg, err) => { + if (err) throw err; // preserve stack + console.error('You broke it!'); + console.error(msg); + process.exit(1); }) - .argv + .argv; } function Argv$implies() { - var ya = yargs + let ya = yargs .implies('foo', 'snuh') .implies({ x: 'y' }) - .argv + .argv; } function Argv$count() { - var ya = yargs + let ya = yargs .count('size') .count(['w', 'h']) - .argv + .argv; } function Argv$number() { - var ya = yargs + let ya = yargs .number('n') .number(['width', 'height']) - .argv + .argv; } function Argv$updateStrings() { - var ya = yargs + let ya = yargs .command('run', 'the run command') .help('help') .updateStrings({ 'Commands:': 'My Commands -->\n' }) .wrap(null) - .argv + .argv; } function Argv$default() { - var ya = yargs + let ya = yargs .default('random', function randomValue() { return Math.random() * 256; }) - .argv + .argv; } function Argv$configObject() { - var ya = yargs - .config({foo: 1, bar: 2}) - .argv + let ya = yargs + .config({ foo: 1, bar: 2 }) + .argv; } function Argv$configParseFunction() { - var ya = yargs - .config('settings', function (configPath) { - return JSON.parse(fs.readFileSync(configPath, 'utf-8')) + let ya = yargs + .config('settings', (configPath) => { + return JSON.parse(fs.readFileSync(configPath, 'utf-8')); }) - .config('settings', 'description', function (configPath) { - return JSON.parse(fs.readFileSync(configPath, 'utf-8')) + .config('settings', 'description', (configPath) => { + return JSON.parse(fs.readFileSync(configPath, 'utf-8')); }) - .argv + .argv; } function Argv$helpDescriptionExplicit() { - var ya = yargs + let ya = yargs .help('help', 'description', true) - .argv + .argv; } function Argv$showHelpConsoleLevel() { - yargs.showHelp("log"); //prints to stdout using console.log() + yargs.showHelp("log"); // prints to stdout using console.log() } function Argv$getCompletion() { - var ya = yargs + let ya = yargs .option('foobar', {}) .option('foobaz', {}) .completion() - .getCompletion(['./test.js', '--foo'], function (completions) { - console.log(completions) + .getCompletion(['./test.js', '--foo'], (completions) => { + console.log(completions); }) - .argv + .argv; } function Argv$pkgConf() { - var ya = yargs + let ya = yargs .pkgConf(['key1', 'key2'], 'configFile.json') - .argv + .argv; } function Argv$recommendCommands() { - var ya = yargs + let ya = yargs .recommendCommands() - .argv + .argv; } function Argv$showCompletionScript() { - var ya = yargs + let ya = yargs .showCompletionScript() - .argv + .argv; } function Argv$skipValidation() { - var ya = yargs + let ya = yargs .skipValidation('arg1') .skipValidation(['arg2', 'arg3']) - .argv + .argv; } function Argv$commandObject() { - var ya = yargs + let ya = yargs .command("commandname", "description", { - "arg": { + arg: ({ alias: "string", array: true, boolean: true, - choices: ["a", "b", "c"], + choices: [undefined, false, "a", "b", "c"], coerce: f => JSON.stringify(f), config: true, - configParser: t => t, + configParser: t => JSON.parse(fs.readFileSync(t, "utf8")), count: true, default: "myvalue", defaultDescription: "description", @@ -575,12 +587,12 @@ function Argv$commandObject() { skipValidation: false, string: true, type: "string" - } - }) + } as yargs.Options) + }); } function Argv$demandCommand() { - var ya = yargs + let ya = yargs .demandCommand(1) .demandCommand(1, 'at least 1 command required') .demandCommand(1, 2) @@ -590,7 +602,7 @@ function Argv$demandCommand() { } function Argv$demandOption() { - var ya = yargs + let ya = yargs .demandOption('a') .demandOption('a', 'a is required') .demandOption('a', true) @@ -601,7 +613,7 @@ function Argv$demandOption() { } function Argv$conflicts() { - var ya = yargs + let ya = yargs .conflicts('a', 'b') .conflicts({ a: 'b'