Merge pull request #2 from DefinitelyTyped/master

merge
This commit is contained in:
Amiram Korach
2017-07-17 15:11:26 +03:00
committed by GitHub
4192 changed files with 195099 additions and 266467 deletions
+2 -2
View File
@@ -1,4 +1,4 @@
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.png?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
# DefinitelyTyped [![Build Status](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped.svg?branch=master)](https://travis-ci.org/DefinitelyTyped/DefinitelyTyped)
[![Join the chat at https://gitter.im/borisyankov/DefinitelyTyped](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/borisyankov/DefinitelyTyped?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
@@ -96,7 +96,7 @@ First, [fork](https://guides.github.com/activities/forking/) this repository, in
// Steve <https://github.com/steve>
// John <https://github.com/john>
```
* `npm install -g typescript@2.0` and run `tsc`.
* If there is a `tslint.json`, run `npm run lint package-name`. Otherwise, run `tsc` in the package directory.
When you make a PR to edit an existing package, `dt-bot` should @-mention previous authors.
If it doesn't, you can do so yourself in the comment associated with the PR.
+12
View File
@@ -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",
+4 -1
View File
@@ -17,11 +17,14 @@
"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 1",
"test": "node node_modules/types-publisher/bin/tester/test.js --run-from-definitely-typed",
"lint": "dtslint types"
},
"devDependencies": {
"dtslint": "Microsoft/dtslint#production",
"types-publisher": "Microsoft/types-publisher#production"
},
"dependencies": {
"jslint": "^0.10.3"
}
}
+3
View File
@@ -3,6 +3,9 @@
// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00
// Stringified usage:
accounting.formatMoney('$4394958309392.9401'); // $4,394,958,309,392.94
// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
+6 -5
View File
@@ -1,6 +1,7 @@
// Type definitions for accounting.js 0.3
// Project: http://josscrowcroft.github.io/accounting.js/
// Type definitions for accounting.js 0.4
// Project: http://openexchangerates.github.io/accounting.js/
// Definitions by: Sergey Gerasimov <https://github.com/gerich-home/>
// Christopher Eck <https://github.com/chrisleck/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace accounting {
@@ -30,9 +31,9 @@ declare namespace accounting {
}
interface Static {
// format any number into currency
formatMoney(number: number, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
formatMoney(number: number, options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string;
// format any number or stringified number into currency
formatMoney(number: number | string, symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string;
formatMoney(number: number | string, options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string;
formatMoney(numbers: number[], symbol?: string, precision?: number, thousand?: string, decimal?: string, format?: string): string[];
formatMoney(numbers: number[], options: CurrencySettings<string> | CurrencySettings<CurrencyFormat>): string[];
+17 -1
View File
@@ -474,7 +474,9 @@ declare namespace AceAjax {
removeFold(arg: any): void;
expandFold(arg: any): void;
foldAll(startRow?: number, endRow?: number, depth?: number): void
unfold(arg1: any, arg2: boolean): void;
screenToDocumentColumn(row: number, column: number): void;
@@ -1039,6 +1041,12 @@ declare namespace AceAjax {
addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any): void;
addEventListener(ev: string, callback: Function): void;
off(ev: string, callback: Function): void;
removeListener(ev: string, callback: Function): void;
removeEventListener(ev: string, callback: Function): void;
inMultiSelectMode: boolean;
selectMoreLines(n: number): void;
@@ -2164,8 +2172,16 @@ declare namespace AceAjax {
**/
export interface Selection {
on(ev: string, callback: Function): void;
addEventListener(ev: string, callback: Function): void;
off(ev: string, callback: Function): void;
removeListener(ev: string, callback: Function): void;
removeEventListener(ev: string, callback: Function): void;
moveCursorWordLeft(): void;
moveCursorWordRight(): void;
@@ -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);
@@ -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 <https://github.com/zspitz>
// 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;
}
+1
View File
@@ -0,0 +1 @@
{ "dependencies": { "activex-helpers": "*"}}
+22
View File
@@ -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"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -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);
-205
View File
@@ -1,205 +0,0 @@
// Type definitions for Microsoft Scripting Runtime
// Project: https://msdn.microsoft.com/en-us/library/bstcxhf7.aspx
// Definitions by: Zev Spitz <https://github.com/zspitz>
// 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;
}
@@ -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 + '<br>';
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);
}
+465
View File
@@ -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 <https://github.com/zspitz>
// 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;
}
+1
View File
@@ -0,0 +1 @@
{ "dependencies": { "activex-helpers": "*"}}
+22
View File
@@ -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"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
@@ -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<WIA.Property>(dev.Properties); //no foreach over ActiveX collections
let e = new Enumerator<WIA.Property>(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);
}
}
WScript.Echo(s);
}
+759
View File
@@ -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 <https://github.com/zspitz>
// 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;
}
+1
View File
@@ -0,0 +1 @@
{ "dependencies": { "activex-helpers": "*"}}
+22
View File
@@ -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"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
-379
View File
@@ -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 <https://github.com/zspitz>
// 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;
}
+2 -2
View File
@@ -1,12 +1,12 @@
import * as Alexa from "alexa-sdk";
const handler = (event: Alexa.RequestBody, context: Alexa.Context, callback: () => void) => {
const handler = (event: Alexa.RequestBody<Alexa.Request>, context: Alexa.Context, callback: () => void) => {
let alexa = Alexa.handler(event, context);
alexa.registerHandlers(handlers);
alexa.execute();
};
let handlers: Alexa.Handlers = {
let handlers: Alexa.Handlers<Alexa.Request> = {
'LaunchRequest': function() {
this.emit('SayHello');
},
+28 -27
View File
@@ -6,14 +6,14 @@
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export function handler(event: RequestBody, context: Context, callback?: (err: any, response: any) => void ): AlexaObject;
export function handler<T>(event: RequestBody<T>, context: Context, callback?: (err: any, response: any) => void ): AlexaObject<T>;
export function CreateStateHandler(state: string, obj: any): any;
export let StateString: string;
export type ConfirmationStatuses = "NONE" | "DENIED" | "CONFIRMED";
export type DialogStates = "STARTED" | "IN_PROGRESS" | "COMPLETED";
export interface AlexaObject extends Handler {
export interface AlexaObject<T> extends Handler<T> {
_event: any;
_context: any;
_callback: any;
@@ -22,26 +22,26 @@ export interface AlexaObject extends Handler {
response: any;
dynamoDBTableName: any;
saveBeforeResponse: boolean;
registerHandlers: (...handlers: Handlers[]) => any;
registerHandlers: (...handlers: Array<Handlers<T>>) => any;
execute: () => void;
}
export interface Handlers {
[intent: string]: (this: Handler) => void;
export interface Handlers<T> {
[intent: string]: (this: Handler<T>) => void;
}
export interface Handler {
export interface Handler<T> {
on: any;
emit(event: string, ...args: any[]): boolean;
emitWithState: any;
state: any;
handler: any;
event: RequestBody;
event: RequestBody<T>;
attributes: any;
context: any;
name: any;
isOverriden: any;
t: (token: string) => void;
t: (token: string, ...args: any[]) => void;
}
export interface Context {
@@ -55,10 +55,10 @@ export interface Context {
awsRequestId: string;
}
export interface RequestBody {
export interface RequestBody<T> {
version: string;
session: Session;
request: LaunchRequest | IntentRequest | SessionEndedRequest;
request: T;
}
export interface Session {
@@ -75,36 +75,37 @@ export interface SessionApplication {
export interface SessionUser {
userId: string;
accessToken: string;
accessToken?: string;
}
export interface LaunchRequest extends Request { }
export interface IntentRequest extends Request {
dialogState: DialogStates;
intent: Intent;
}
export interface SlotValue {
confirmationStatus: ConfirmationStatuses;
name: string;
value?: any;
}
export interface Intent {
confirmationStatus: ConfirmationStatuses;
name: string;
slots: Record<string, SlotValue>;
dialogState?: DialogStates;
intent?: Intent;
}
export interface SessionEndedRequest extends Request {
reason: string;
reason?: string;
}
export interface Request {
type: "LaunchRequest" | "IntentRequest" | "SessionEndedRequest";
requestId: string;
timeStamp: string;
timestamp: string;
locale?: string;
}
export interface SlotValue {
confirmationStatus?: ConfirmationStatuses;
name: string;
value?: any;
}
export interface Intent {
confirmationStatus?: ConfirmationStatuses;
name: string;
slots: Record<string, SlotValue>;
}
export interface ResponseBody {
+2 -1
View File
@@ -4,6 +4,7 @@
"object-literal-key-quote": false,
"no-empty-interface": false,
"prefer-method-signature": false,
"object-literal-key-quotes": false
"object-literal-key-quotes": false,
"no-any": false
}
}
+3 -3
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/goatslacker/alt
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// TypeScript Version: 2.3
///<reference types="react"/>
@@ -141,7 +141,7 @@ declare module "alt/utils/chromeDebug" {
declare module "alt/AltContainer" {
import React = require("react");
import * as React from "react";
interface ContainerProps {
store?:AltJS.AltStore<any>;
@@ -152,7 +152,7 @@ declare module "alt/AltContainer" {
flux?:AltJS.Alt;
transform?:(store:AltJS.AltStore<any>, actions:any) => any;
shouldComponentUpdate?:(props:any) => boolean;
component?:React.Component<any, any>;
component?:React.Component<any>;
}
type AltContainer = React.ReactElement<ContainerProps>;
+1 -3
View File
@@ -2,9 +2,7 @@
// Project: http://angularjs.org
// Definitions by: Michel Salib <https://github.com/michelsalib>, Adi Dahiya <https://github.com/adidahiya>, Raphael Schweizer <https://github.com/rasch>, Cody Schaaf <https://github.com/codyschaaf>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="jquery" />
// TypeScript Version: 2.1
declare var _: string;
export = _;
+1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/McNull/angular-block-ui
// Definitions by: Lasse Nørregaard <https://github.com/lassebn>, Stephan Classen <https://github.com/sclassen>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as angular from "angular";
+1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/ManifestWebDesign/angular-gridster
// Definitions by: Joao Monteiro <https://github.com/jpmnteiro>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as angular from "angular";
@@ -64,6 +64,7 @@ app.config(function (localStorageServiceProvider: ng.local.storage.ILocalStorage
localStorageServiceProvider
.setPrefix('myApp')
.setStorageType('sessionStorage')
.setDefaultToCookie(false)
.setNotify(true, true);
});
+9 -3
View File
@@ -1,6 +1,6 @@
// Type definitions for angular-local-storage v0.1.6
// Type definitions for angular-local-storage v0.6.0
// Project: https://github.com/grevory/angular-local-storage
// Definitions by: Ken Fukuyama <https://github.com/kenfdev>
// Definitions by: Ken Fukuyama <https://github.com/kenfdev>, Davide Donadello <https://github.com/dona278>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -27,12 +27,18 @@ declare module 'angular' {
* @param storageType localstorage or sessionStorage. default: localStorage
*/
setStorageType(storageType: string): ILocalStorageServiceProvider;
/**
* If localStorage is not supported, the library will default to cookies instead. This behavior can be disabled
* @param shouldDefault default: true
*/
setDefaultToCookie(shouldDefault: boolean): ILocalStorageServiceProvider;
/**
* Setter for cookie config
* @param exp number of days before cookies expire (0 = does not expire). default: 30
* @param path the web path the cookie represents. default: '/'
* @param secure to store cookies as secure. default: false
*/
setStorageCookie(exp: number, path: string): ILocalStorageServiceProvider;
setStorageCookie(exp: number, path: string, secure: boolean): ILocalStorageServiceProvider;
/**
* Set the cookie domain, since this runs inside a the config() block, only providers and constants can be injected. As a result, $location service can't be used here, use a hardcoded string or window.location.
* No default value
+1
View File
@@ -2,6 +2,7 @@
// Project: https://github.com/oauthjs/angular-oauth2
// Definitions by: Antério Vieira <https://github.com/anteriovieira>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as angular from 'angular';
@@ -0,0 +1,11 @@
import * as angular from "angular";
import "angular-pdfjs-viewer";
angular.module('app').config((pdfjsViewerConfigProvider: angular.pdfjsViewer.ConfigProvider) => {
pdfjsViewerConfigProvider.setWorkerSrc("/assets/pdf.js-viewer/pdf.worker.js");
pdfjsViewerConfigProvider.setCmapDir("/assets/pdf.js-viewer/cmaps");
pdfjsViewerConfigProvider.setImageDir("/assets/pdf.js-viewer/images");
pdfjsViewerConfigProvider.disableWorker();
pdfjsViewerConfigProvider.setVerbosity("infos"); // "errors", "warnings" or "infos"
});
+19
View File
@@ -0,0 +1,19 @@
// Type definitions for angular-pdfjs-viewer 1.0
// Project: https://github.com/legalthings/angular-pdfjs-viewer
// Definitions by: Bastien Moulia <https://github.com/bastienmoulia>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as angular from 'angular';
declare module 'angular' {
namespace pdfjsViewer {
interface ConfigProvider extends angular.IServiceProvider {
setWorkerSrc(src: string): void;
setCmapDir(dir: string): void;
setImageDir(dir: string): void;
disableWorker(): void;
setVerbosity(verbosity: "errors" | "warnings" | "infos"): void;
}
}
}
+22
View File
@@ -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",
"angular-pdfjs-viewer-tests.ts"
]
}
@@ -1,15 +1,75 @@
// Examples of working with resource, previously from the angular.d.ts. readme
// Working with $resource
// We have the option to define arguments for a custom resource
interface IArticleParameters {
id: number;
}
interface IArticleResource extends ng.resource.IResource<IArticleResource> {
title: string;
text: string;
date: Date;
author: number;
// Although all actions defined on IArticleResourceClass are avaiable with
// the '$' prefix, we have the choice to expose only what we will use
$publish(): IArticleResource;
$unpublish(): IArticleResource;
}
// Let's define a custom resource
interface IArticleResourceClass extends ng.resource.IResourceClass<IArticleResource> {
// Overload get to accept our custom parameters
get(): IArticleResource;
get(params: IArticleParameters, onSuccess: Function): IArticleResource;
// Add our custom resource actions
publish(params?: IArticleParameters): IArticleResource;
unpublish(params: IArticleParameters): IArticleResource;
}
function MainController($resource: ng.resource.IResourceService): void {
// IntelliSense will provide IActionDescriptor interface and will validate
// your assignment against it
let publishDescriptor: ng.resource.IActionDescriptor = {
method: 'GET',
isArray: false
};
// A call to the $resource service returns a IResourceClass. Since
// our own IArticleResourceClass defines 2 more actions, we cast the return
// value to make the compiler aware of that
let articleResource: IArticleResourceClass = $resource<IArticleResource, IArticleResourceClass>('/articles/:id', null, {
publish : publishDescriptor,
unpublish : {
method: 'POST'
}
});
// Now we can do this
articleResource.unpublish({ id: 1 });
// IResourceClass.get() will be automatically available here
let article: IArticleResource = articleResource.get({id: 1}, function success(): void {
// Again, default + custom action here...
article.title = 'New Title';
article.$save();
article.$publish();
});
}
import IHttpPromiseCallbackArg = angular.IHttpPromiseCallbackArg;
interface IMyData {}
interface IMyHttpPromiseCallbackArg extends IHttpPromiseCallbackArg<IMyData> {}
interface IMyResource extends angular.resource.IResource<IMyResource> { }
interface IMyResourceClass extends angular.resource.IResourceClass<IMyResource> { }
interface IMyResource extends angular.resource.IResource<IMyResource> {}
interface IMyResourceClass extends angular.resource.IResourceClass<IMyResource> {}
///////////////////////////////////////
// IActionDescriptor
///////////////////////////////////////
var actionDescriptor: angular.resource.IActionDescriptor;
let actionDescriptor: angular.resource.IActionDescriptor;
angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactoryService) {
actionDescriptor.method = 'method action';
@@ -27,19 +87,18 @@ angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactorySe
actionDescriptor.withCredentials = true;
actionDescriptor.responseType = 'response type';
actionDescriptor.interceptor = {
response: function<IMyData> () { return <IMyHttpPromiseCallbackArg>{}; },
responseError: function () {}
response() { return {} as IMyHttpPromiseCallbackArg; },
responseError() {}
};
actionDescriptor.cancellable = true;
});
///////////////////////////////////////
// IResourceClass
///////////////////////////////////////
var resourceClass: IMyResourceClass;
var resource: IMyResource;
var resourceArray: angular.resource.IResourceArray<IMyResource>;
let resourceClass: IMyResourceClass;
let resource: IMyResource;
let resourceArray: angular.resource.IResourceArray<IMyResource>;
resource = resourceClass.delete();
resource = resourceClass.delete({ key: 'value' });
@@ -94,9 +153,9 @@ resource = resourceClass.save({ key: 'value' }, { key: 'value' }, function () {
// IResource
///////////////////////////////////////
var promise : angular.IPromise<IMyResource>;
var arrayPromise : angular.IPromise<IMyResource[]>;
var json: IMyResource;
let promise: angular.IPromise<IMyResource>;
let arrayPromise: angular.IPromise<IMyResource[]>;
let json: IMyResource;
promise = resource.$delete();
promise = resource.$delete({ key: 'value' });
@@ -140,7 +199,7 @@ json = resource.toJSON();
///////////////////////////////////////
// IResourceService
///////////////////////////////////////
var resourceService: angular.resource.IResourceService;
let resourceService: angular.resource.IResourceService;
resourceClass = resourceService<IMyResource, IMyResourceClass>('test');
resourceClass = resourceService<IMyResource>('test');
resourceClass = resourceService('test');
@@ -148,22 +207,20 @@ resourceClass = resourceService('test');
///////////////////////////////////////
// IModule
///////////////////////////////////////
var mod: ng.IModule;
var resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction<IMyResource>;
var resourceService: angular.resource.IResourceService;
let mod: ng.IModule;
let resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction<IMyResource>;
resourceClass = resourceServiceFactoryFunction<IMyResourceClass>(resourceService);
resourceServiceFactoryFunction = function (resourceService: angular.resource.IResourceService) { return <any>resourceClass; };
resourceServiceFactoryFunction = function (resourceService: angular.resource.IResourceService) { return resourceClass as any; };
mod = mod.factory('factory name', resourceServiceFactoryFunction);
///////////////////////////////////////
// IResource
///////////////////////////////////////
///////////////////////////////////////
// IResourceServiceProvider
///////////////////////////////////////
var resourceServiceProvider: angular.resource.IResourceServiceProvider;
let resourceServiceProvider: angular.resource.IResourceServiceProvider;
resourceServiceProvider.defaults.stripTrailingSlashes = false;
+17 -21
View File
@@ -37,23 +37,21 @@ declare module 'angular' {
// that deeply.
///////////////////////////////////////////////////////////////////////////
interface IResourceService {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: IActionHash, options?: IResourceOptions): IResourceClass<IResource<any>>;
<T, U>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: IActionHash, options?: IResourceOptions): U;
<T>(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
actions?: IActionHash, options?: IResourceOptions): IResourceClass<T>;
/**
* A factory which creates a resource object that lets you interact with RESTful server-side data sources.
* @param url A parameterized URL template with parameters prefixed by : as in /user/:username
* @param paramDefaults Default values for url parameters.
* @param actions example: {update: { method: 'PUT' }, delete: deleteDescriptor } where deleteDescriptor: IActionDescriptor
* @param options Hash with custom settings that should extend the default $resourceProvider behavior
*/
(url: string, paramDefaults?: any, actions?: IActionHash, options?: IResourceOptions): IResourceClass<IResource<any>>;
<T>(url: string, paramDefaults?: any, actions?: IActionHash, options?: IResourceOptions): IResourceClass<T>;
<T, U>(url: string, paramDefaults?: any, actions?: IActionHash, options?: IResourceOptions): U;
}
// Hash of action descriptors allows custom action names
interface IActionHash {
[action: string]: IActionDescriptor
[action: string]: IActionDescriptor;
}
// Just a reference to facilitate describing new actions
@@ -71,7 +69,7 @@ declare module 'angular' {
* would be used for multiple requests. If you are looking for a way to cancel requests, you should
* use the cancellable option.
*/
timeout?: number
timeout?: number;
cancellable?: boolean;
withCredentials?: boolean;
responseType?: string;
@@ -116,7 +114,7 @@ declare module 'angular' {
// Also, static calls always return the IResource (or IResourceArray) retrieved
// https://github.com/angular/angular.js/blob/v1.2.0/src/ngResource/resource.js#L538-L549
interface IResourceClass<T> {
new(dataOrParams? : any) : T & IResource<T>;
new(dataOrParams?: any): T & IResource<T>;
get: IResourceMethod<T>;
query: IResourceArrayMethod<T>;
@@ -153,7 +151,7 @@ declare module 'angular' {
$cancelRequest(): void;
/** the promise of the original server interaction that created this instance. **/
/** The promise of the original server interaction that created this instance. */
$promise: angular.IPromise<T>;
$resolved: boolean;
toJSON(): T;
@@ -165,7 +163,7 @@ declare module 'angular' {
interface IResourceArray<T> extends Array<T & IResource<T>> {
$cancelRequest(): void;
/** the promise of the original server interaction that created this collection. **/
/** The promise of the original server interaction that created this collection. */
$promise: angular.IPromise<IResourceArray<T>>;
$resolved: boolean;
}
@@ -178,10 +176,8 @@ declare module 'angular' {
// IResourceServiceProvider used to configure global settings
interface IResourceServiceProvider extends angular.IServiceProvider {
defaults: IResourceOptions;
}
}
/** extensions to base ng based on using angular-resource */
@@ -199,8 +195,8 @@ declare module 'angular' {
declare global {
interface Array<T> {
/** the promise of the original server interaction that created this collection. **/
$promise: angular.IPromise<Array<T>>;
/** The promise of the original server interaction that created this collection. */
$promise: angular.IPromise<T[]>;
$resolved: boolean;
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"extends": "dtslint/dt.json",
"rules": {
// TODO: Fix up types to remove these
"interface-name": false,
"only-arrow-functions": false,
"no-empty-interface": false,
"ban-types": false,
"space-before-function-paren": false,
"unified-signatures": false
}
}
+11 -140
View File
@@ -2,27 +2,23 @@
## Referencing AngularJS definition files in your code
To do that, simply add `` at the top of your code.
That will make available to your code all interfaces AngularJS' main module **ng** implements, as well as the **AUTO** module.
Read the [TypeScript handbook](https://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html) for details on consuming these type definitions.
If you are including other AngularJS' modules in your code, like **ngResource**, just like you needed to include the additional module implementation file in your code, _angular-resource.js_, you will also need to reference the definitions file related to that module. Your code would then have the following definitions files reference:
Having these modules in separated files is actually good because they sometimes either augment or modify some of **ng**'s interfaces, and thus those differences should only be available to you when you really need them. Also, it forces you to explicit what you're going to be using.
Having these modules in separated packages is actually good because they sometimes either augment or modify some of **ng**'s interfaces, and thus those differences should only be available to you when you really need them. Also, it forces you to explicit what you're going to be using.
The following extra definition files are available for referencing:
* angular-resource.d.ts (for the **ngResource** module)
* angular-route.d.ts (for the **ngRoute** module)
* angular-cookies.d.ts (for the **ngCookies** module)
* angular-sanitize.d.ts (for the **ngSanitize** module)
* angular-animate.d.ts (for the **ngAnimate** module)
* angular-mocks.d.ts (for the **ngMock** and **ngMockE2E** modules)
(postfix with version number for specific verion, eg. angular-resource-1.0.d.ts)
* angular-resource/index.d.ts (for the **ngResource** module)
* angular-route/index.d.ts (for the **ngRoute** module)
* angular-cookies/index.d.ts (for the **ngCookies** module)
* angular-sanitize/index.d.ts (for the **ngSanitize** module)
* angular-animate/index.d.ts (for the **ngAnimate** module)
* angular-mocks/index.d.ts (for the **ngMock** and **ngMockE2E** modules)
## The Angular Static
@@ -31,7 +27,7 @@ The definitions declare the AngularJS static variable `angular` as ambient. That
## Definitions modularized
To avoid cluttering the list of suggestions as you type in your IDE, all interfaces reside in their respective module namespace:
To avoid cluttering the list of suggestions as you type in your IDE, all interfaces reside in their respective module namespace after you include their respective definitions:
* `ng` for AngularJS' **ng** module
* `ng.auto` for **AUTO**
@@ -105,128 +101,3 @@ function Controller($scope: ICustomScope) {
## Examples
### Working with $resource
```ts
// We have the option to define arguments for a custom resource
interface IArticleParameters {
id: number;
}
interface IArticleResource extends ng.resource.IResource<IArticleResource> {
title: string;
text: string;
date: Date;
author: number;
// Although all actions defined on IArticleResourceClass are avaiable with
// the '$' prefix, we have the choice to expose only what we will use
$publish(): IArticleResource;
$unpublish(): IArticleResource;
}
// Let's define a custom resource
interface IArticleResourceClass extends ng.resource.IResourceClass<IArticleResource> {
// Overload get to accept our custom parameters
get(): ng.resource.IResource;
get(params: IArticleParameters, onSuccess: Function): IArticleResource;
// Add our custom resource actions
publish(): IArticleResource;
publish(params: IArticleParameters): IArticleResource;
unpublish(params: IArticleParameters): IArticleResource;
}
function MainController($resource: ng.resource.IResourceService) {
// IntelliSense will provide IActionDescriptor interface and will validate
// your assignment against it
var publishDescriptor: ng.resource.IActionDescriptor;
publishDescriptor = {
method: 'GET',
isArray: false
};
// I could still create a descriptor without the interface...
var unpublishDescriptor = {
method: 'POST'
}
// A call to the $resource service returns a IResourceClass. Since
// our own IArticleResourceClass defines 2 more actions, we cast the return
// value to make the compiler aware of that
var articleResource = $resource<IArticleResource, IArticleResourceClass>('/articles/:id', null, {
publish : publishDescriptor,
unpublish : unpublishDescriptor
});
// Now we can do this
articleResource.unpublish({ id: 1 });
// IResourceClass.get() will be automatically available here
var article: IArticleResource = articleResource.get({id: 1}, function success() {
// Again, default + custom action here...
article.title = 'New Title';
article.$save();
article.$publish();
});
}
```
### Working with $resource in angular-1.0 definitions
```ts
// Let's define a custom resource
interface IArticleResourceClass extends ng.resource.IResourceClass {
publish: ng.resource.IActionCall;
unpublish: ng.resource.IActionCall;
}
interface IArticleResource extends ng.resource.IResource {
title: string;
text: string;
date: Date;
author: number;
$publish: ng.resource.IActionCall;
$unpublish: ng.resource.IActionCall;
}
function MainController($resource: ng.resource.IResourceService) {
// IntelliSense will provide IActionDescriptor interface and will validate
// your assignment against it
var publishDescriptor: ng.resource.IActionDescriptor;
publishDescriptor = {
method: 'GET',
isArray: false
};
// I could still create a descriptor without the interface...
var unpublishDescriptor = {
method: 'POST'
}
// A call to the $resource service returns a IResourceClass. Since
// our own IArticleResourceClass defines 2 more actions, we cast the return
// value to make the compiler aware of that
var articles = <IArticleResourceClass> $resource('/articles/:id', null, {
publish : publishDescriptor,
unpublish : unpublishDescriptor
});
// Now we can do this
articles.unpublish({ id: 1 });
// IResourceClass.get() will be automatically available here
var article = <IArticleResource> articles.get({id: 1});
// Again, default + custom action here...
article.title = 'New Title';
article.$save();
article.$publish();
}
```
+23 -10
View File
@@ -178,7 +178,7 @@ mod.controller({
mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => {
return (scope, el, attrs) => {
let foo = 'none';
el.click(e => {
el.on('click', e => {
foo = e.type;
$rootScope.$apply();
});
@@ -188,8 +188,9 @@ mod.directive('myDirectiveA', ($rootScope: ng.IRootScopeService) => {
mod.directive('myDirectiveB', ['$rootScope', ($rootScope: ng.IRootScopeService) => {
return {
link(scope, el, attrs) {
el.click(e => {
el.hide();
el.on('click', e => {
// Doesn't exist on jqLite
// el.hide();
});
}
};
@@ -337,6 +338,16 @@ namespace TestQ {
let result: angular.IPromise<{a: number; b: string; }>;
result = $q.all<{a: number; b: string; }>({a: promiseAny, b: promiseAny});
}
{
let result = $q.all({ num: $q.when(2), str: $q.when('test') });
// TS should infer that num is a number and str is a string
result.then(r => (r.num * 2) + r.str.indexOf('s'));
}
{
let result = $q.all({ num: $q.when(2), str: 'test' });
// TS should infer that num is a number and str is a string
result.then(r => (r.num * 2) + r.str.indexOf('s'));
}
// $q.defer
{
@@ -616,11 +627,13 @@ function test_angular_forEach() {
}
// angular.element() tests
let element = angular.element('div.myApp');
let element = angular.element('<div></div>');
let scope: ng.IScope = element.scope();
let isolateScope: ng.IScope = element.isolateScope();
isolateScope = element.find('div.foo').isolateScope();
isolateScope = element.find('div').isolateScope();
isolateScope = element.children().isolateScope();
let element2 = angular.element(element);
let elementArray = angular.element(document.querySelectorAll('div'));
// $timeout signature tests
namespace TestTimeout {
@@ -1007,13 +1020,13 @@ angular.module('multiSlotTranscludeExample', [])
},
link(scope, element, attrs, ctrl, transclude) {
// without scope
transclude().appendTo(element);
transclude(clone => clone.appendTo(element));
element.append(transclude());
transclude(clone => element.append(clone));
// with scope
transclude(scope, clone => clone.appendTo(element));
transclude(scope, clone => clone.appendTo(element), element, 'button');
transclude(scope, null, element, 'list').addClass('drop-down-list').appendTo(element);
transclude(scope, clone => element.append(clone));
transclude(scope, clone => element.append(clone), element, 'button');
element.append(transclude(scope, null, element, 'list').addClass('drop-down-list'));
}
};
});
+12 -23
View File
@@ -1,10 +1,13 @@
// Type definitions for Angular JS 1.6
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Georgii Dolzhykov <http://github.com/thorn0>, Caleb St-Denis <https://github.com/calebstdenis>
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Georgii Dolzhykov <http://github.com/thorn0>
// Caleb St-Denis <https://github.com/calebstdenis>
// Leonard Thieu <https://github.com/leonard-thieu>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
/// <reference types="jquery" />
/// <reference path="jqlite.d.ts" />
declare var angular: angular.IAngularStatic;
@@ -1029,8 +1032,7 @@ declare namespace angular {
*
* @param promises A hash of promises.
*/
all(promises: { [id: string]: IPromise<any>; }): IPromise<{ [id: string]: any; }>;
all<T extends {}>(promises: { [id: string]: IPromise<any>; }): IPromise<T>;
all<T>(promises: { [K in keyof T]: (IPromise<T[K]> | T[K]); }): IPromise<T>;
/**
* Creates a Deferred object which represents a task which will finish in the future.
*/
@@ -1472,6 +1474,12 @@ declare namespace angular {
* See [XMLHttpRequest.responseType]https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype
*/
responseType?: string;
/**
* Name of the parameter added (by AngularJS) to the request to specify the name (in the server response) of the JSON-P callback to invoke.
* If unspecified, $http.defaults.jsonpCallbackParam will be used by default. This property is only applicable to JSON-P requests.
*/
jsonpCallbackParam?: string;
}
/**
@@ -2117,22 +2125,3 @@ declare namespace angular {
(obj: Object): string;
}
}
declare global {
interface JQuery {
// TODO: events, how to define?
// $destroy
find(element: any): JQuery;
find(obj: JQuery): JQuery;
controller(name?: string): any;
injector(): ng.auto.IInjectorService;
/** It's declared generic for custom scope interfaces */
scope<T extends ng.IScope>(): T;
isolateScope<T extends ng.IScope>(): T;
inheritedData(key: string, value: any): JQuery;
inheritedData(obj: { [key: string]: any; }): JQuery;
inheritedData(key?: string): any;
}
}
+808
View File
@@ -0,0 +1,808 @@
// Project: http://jquery.com/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Christian Hoffmeister <https://github.com/choffmeister>
// Steve Fenton <https://github.com/Steve-Fenton>
// Diullei Gomes <https://github.com/Diullei>
// Tass Iliopoulos <https://github.com/tasoili>
// Jason Swearingen <https://github.com/jasons-novaleaf>
// Sean Hill <https://github.com/seanski>
// Guus Goossens <https://github.com/Guuz>
// Kelly Summerlin <https://github.com/ksummerlin>
// Basarat Ali Syed <https://github.com/basarat>
// Nicholas Wolverson <https://github.com/nwolverson>
// Derek Cicerone <https://github.com/derekcicerone>
// Andrew Gaspar <https://github.com/AndrewGaspar>
// Seikichi Kondo <https://github.com/seikichi>
// Benjamin Jackman <https://github.com/benjaminjackman>
// Poul Sorensen <https://github.com/s093294>
// Josh Strobl <https://github.com/JoshStrobl>
// John Reilly <https://github.com/johnnyreilly/>
// Dick van den Brink <https://github.com/DickvdBrink>
// Thomas Schulz <https://github.com/King2500>
// Leonard Thieu <https://github.com/leonard-thieu>
// Andre Wiggins <https://github.com/andrewiggins>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// Definitions copied from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/0480c5ec87fab41aa23047a02b27f0ea71aaf975/types/jquery/v2/index.d.ts
interface JQuery {
/**
* Adds the specified class(es) to each of the set of matched elements.
*
* @param className One or more space-separated classes to be added to the class attribute of each matched element.
* @see {@link https://api.jquery.com/addClass/#addClass-className}
*/
addClass(className: string): JQuery;
/**
* Insert content, specified by the parameter, after each element in the set of matched elements.
*
* @param content1 HTML string, DOM element, DocumentFragment, array of elements, or jQuery object to insert after each element in the set of matched elements.
* @param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert after each element in the set of matched elements.
* @see {@link https://api.jquery.com/after/#after-content-content}
*/
after(content1: JQuery | any[] | Element | DocumentFragment | Text | string, ...content2: any[]): JQuery;
/**
* Insert content, specified by the parameter, after each element in the set of matched elements.
*
* @param func A function that returns an HTML string, DOM element(s), or jQuery object to insert after each element in the set of matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.
* @see {@link https://api.jquery.com/after/#after-function}
*/
after(func: (index: number, html: string) => string | Element | JQuery): JQuery;
/**
* Insert content, specified by the parameter, to the end of each element in the set of matched elements.
*
* @param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the end of each element in the set of matched elements.
* @param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.
* @see {@link https://api.jquery.com/append/#append-content-content}
*/
append(content1: JQuery | any[] | Element | DocumentFragment | Text | string, ...content2: any[]): JQuery;
/**
* Insert content, specified by the parameter, to the end of each element in the set of matched elements.
*
* @param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.
* @see {@link https://api.jquery.com/append/#append-function}
*/
append(func: (index: number, html: string) => string | Element | JQuery): JQuery;
/**
* Get the value of an attribute for the first element in the set of matched elements.
*
* @param attributeName The name of the attribute to get.
* @see {@link https://api.jquery.com/attr/#attr-attributeName}
*/
attr(attributeName: string): string;
/**
* Set one or more attributes for the set of matched elements.
*
* @param attributeName The name of the attribute to set.
* @param value A value to set for the attribute. If this is `null`, the attribute will be deleted.
* @see {@link https://api.jquery.com/attr/#attr-attributeName-value}
*/
attr(attributeName: string, value: string | number | null): JQuery;
/**
* Set one or more attributes for the set of matched elements.
*
* @param attributes An object of attribute-value pairs to set.
* @see {@link https://api.jquery.com/attr/#attr-attributes}
*/
attr(attributes: Object): JQuery;
/**
* Attach a handler to an event for the elements.
*
* @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names.
* @param handler A function to execute each time the event is triggered.
* @see {@link https://api.jquery.com/bind/#bind-eventType-eventData-handler}
*/
bind(eventType: string, handler: (eventObject: JQueryEventObject) => any): JQuery;
/**
* Attach a handler to an event for the elements.
*
* @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names.
* @param preventBubble Setting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.
* @see {@link https://api.jquery.com/bind/#bind-eventType-eventData-preventBubble}
*/
bind(eventType: string, preventBubble: boolean): JQuery;
/**
* Attach a handler to an event for the elements.
*
* @param events An object containing one or more DOM event types and functions to execute for them.
* @see {@link https://api.jquery.com/bind/#bind-events}
*/
bind(events: any): JQuery;
/**
* Get the children of each element in the set of matched elements, optionally filtered by a selector.
*
* @see {@link https://api.jquery.com/children/}
*/
children(): JQuery;
/**
* Create a deep copy of the set of matched elements.
*
* @param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false.
* @param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should be copied. By default its value matches the first argument's value (which defaults to false).
* @see {@link https://api.jquery.com/clone/}
*/
clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): JQuery;
/**
* Get the children of each element in the set of matched elements, including text and comment nodes.
* @see {@link https://api.jquery.com/contents/}
*/
contents(): JQuery;
/**
* Get the value of style properties for the first element in the set of matched elements.
*
* @param propertyName A CSS property.
* @see {@link https://api.jquery.com/css/#css-propertyName}
*/
css(propertyName: string): string;
/**
* Get the value of style properties for the first element in the set of matched elements.
* Results in an object of property-value pairs.
*
* @param propertyNames An array of one or more CSS properties.
* @see {@link https://api.jquery.com/css/#css-propertyNames}
*/
css(propertyNames: string[]): any;
/**
* Set one or more CSS properties for the set of matched elements.
*
* @param propertyName A CSS property name.
* @param value A value to set for the property.
* @see {@link https://api.jquery.com/css/#css-propertyName-value}
*/
css(propertyName: string, value: string | number): JQuery;
/**
* Set one or more CSS properties for the set of matched elements.
*
* @param propertyName A CSS property name.
* @param value A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
* @see {@link https://api.jquery.com/css/#css-propertyName-function}
*/
css(propertyName: string, value: (index: number, value: string) => string | number): JQuery;
/**
* Set one or more CSS properties for the set of matched elements.
*
* @param properties An object of property-value pairs to set.
* @see {@link https://api.jquery.com/css/#css-properties}
*/
css(properties: JQLiteCssProperties): JQuery;
/**
* Store arbitrary data associated with the matched elements.
*
* @param key A string naming the piece of data to set.
* @param value The new data value; it can be any JavaScript type including Array or Object.
* @see {@link https://api.jquery.com/data/#data-key-value}
*/
data(key: string, value: any): JQuery;
/**
* Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
*
* @param key Name of the data stored.
* @see {@link https://api.jquery.com/data/#data-key}
*/
data(key: string): any;
/**
* Store arbitrary data associated with the matched elements.
*
* @param obj An object of key-value pairs of data to update.
* @see {@link https://api.jquery.com/data/#data-obj}
*/
data(obj: { [key: string]: any; }): JQuery;
/**
* Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
* @see {@link https://api.jquery.com/data/#data}
*/
data(): any;
/**
* Remove the set of matched elements from the DOM.
*
* @param selector A selector expression that filters the set of matched elements to be removed.
* @see {@link https://api.jquery.com/detach/}
*/
detach(selector?: string): JQuery;
/**
* Remove all child nodes of the set of matched elements from the DOM.
* @see {@link https://api.jquery.com/empty/}
*/
empty(): JQuery;
/**
* Reduce the set of matched elements to the one at the specified index.
*
* @param index An integer indicating the 0-based position of the element. OR An integer indicating the position of the element, counting backwards from the last element in the set.
* @see {@link https://api.jquery.com/eq/}
*/
eq(index: number): JQuery;
/**
* Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
*
* @param selector A string containing a selector expression to match elements against.
* @see {@link https://api.jquery.com/find/#find-selector}
*/
find(selector: string): JQuery;
find(element: any): JQuery;
find(obj: JQuery): JQuery;
/**
* Determine whether any of the matched elements are assigned the given class.
*
* @param className The class name to search for.
* @see {@link https://api.jquery.com/hasClass/}
*/
hasClass(className: string): boolean;
/**
* Get the HTML contents of the first element in the set of matched elements.
* @see {@link https://api.jquery.com/html/#html}
*/
html(): string;
/**
* Set the HTML contents of each element in the set of matched elements.
*
* @param htmlString A string of HTML to set as the content of each matched element.
* @see {@link https://api.jquery.com/html/#html-htmlString}
*/
html(htmlString: string): JQuery;
/**
* Set the HTML contents of each element in the set of matched elements.
*
* @param func A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.
* @see {@link https://api.jquery.com/html/#html-function}
*/
html(func: (index: number, oldhtml: string) => string): JQuery;
/**
* Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
*
* @see {@link https://api.jquery.com/next/}
*/
next(): JQuery;
/**
* Attach an event handler function for one or more events to the selected elements.
*
* @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
* @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. Rest parameter args is for optional parameters passed to jQuery.trigger(). Note that the actual parameters on the event handler function must be marked as optional (? syntax).
* @see {@link https://api.jquery.com/on/#on-events-selector-data-handler}
*/
on(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;
/**
* Attach an event handler function for one or more events to the selected elements.
*
* @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
* @param data Data to be passed to the handler in event.data when an event is triggered.
* @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.
* @see {@link https://api.jquery.com/on/#on-events-selector-data-handler}
*/
on(events: string, data: any, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;
/**
* Attach an event handler function for one or more events to the selected elements.
*
* @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
* @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
* @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.
* @see {@link https://api.jquery.com/on/#on-events-selector-data-handler}
*/
on(events: string, selector: string, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery;
/**
* Attach an event handler function for one or more events to the selected elements.
*
* @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
* @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
* @param data Data to be passed to the handler in event.data when an event is triggered.
* @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.
* @see {@link https://api.jquery.com/on/#on-events-selector-data-handler}
*/
on(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject, ...eventData: any[]) => any): JQuery;
/**
* Attach an event handler function for one or more events to the selected elements.
*
* @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).
* @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.
* @param data Data to be passed to the handler in event.data when an event occurs.
* @see {@link https://api.jquery.com/on/#on-events-selector-data}
*/
on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, selector?: string, data?: any): JQuery;
/**
* Attach an event handler function for one or more events to the selected elements.
*
* @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).
* @param data Data to be passed to the handler in event.data when an event occurs.
* @see {@link https://api.jquery.com/on/#on-events-selector-data}
*/
on(events: { [key: string]: (eventObject: JQueryEventObject, ...args: any[]) => any; }, data?: any): JQuery;
/**
* Remove an event handler.
* @see {@link https://api.jquery.com/off/#off}
*/
off(): JQuery;
/**
* Remove an event handler.
*
* @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".
* @param selector A selector which should match the one originally passed to .on() when attaching event handlers.
* @param handler A handler function previously attached for the event(s), or the special value false.
* @see {@link https://api.jquery.com/off/#off-events-selector-handler}
*/
off(events: string, selector?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery;
/**
* Remove an event handler.
*
* @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".
* @param handler A handler function previously attached for the event(s), or the special value false. Takes handler with extra args that can be attached with on().
* @see {@link https://api.jquery.com/off/#off-events-selector-handler}
*/
off(events: string, handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;
/**
* Remove an event handler.
*
* @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".
* @param handler A handler function previously attached for the event(s), or the special value false.
* @see {@link https://api.jquery.com/off/#off-events-selector-handler}
*/
off(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery;
/**
* Remove an event handler.
*
* @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s).
* @param selector A selector which should match the one originally passed to .on() when attaching event handlers.
* @see {@link https://api.jquery.com/off/#off-events-selector}
*/
off(events: { [key: string]: any; }, selector?: string): JQuery;
/**
* Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
*
* @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.
* @param handler A function to execute at the time the event is triggered.
* @see {@link https://api.jquery.com/one/#one-events-data-handler}
*/
one(events: string, handler: (eventObject: JQueryEventObject) => any): JQuery;
/**
* Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
*
* @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names.
* @param data An object containing data that will be passed to the event handler.
* @param handler A function to execute at the time the event is triggered.
* @see {@link https://api.jquery.com/one/#one-events-data-handler}
*/
one(events: string, data: Object, handler: (eventObject: JQueryEventObject) => any): JQuery;
/**
* Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
*
* @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
* @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
* @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.
* @see {@link https://api.jquery.com/one/#one-events-selector-data-handler}
*/
one(events: string, selector: string, handler: (eventObject: JQueryEventObject) => any): JQuery;
/**
* Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
*
* @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".
* @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
* @param data Data to be passed to the handler in event.data when an event is triggered.
* @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false.
* @see {@link https://api.jquery.com/one/#one-events-selector-data-handler}
*/
one(events: string, selector: string, data: any, handler: (eventObject: JQueryEventObject) => any): JQuery;
/**
* Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
*
* @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).
* @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element.
* @param data Data to be passed to the handler in event.data when an event occurs.
* @see {@link https://api.jquery.com/one/#one-events-selector-data}
*/
one(events: { [key: string]: any; }, selector?: string, data?: any): JQuery;
/**
* Attach a handler to an event for the elements. The handler is executed at most once per element per event type.
*
* @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s).
* @param data Data to be passed to the handler in event.data when an event occurs.
* @see {@link https://api.jquery.com/one/#one-events-selector-data}
*/
one(events: { [key: string]: any; }, data?: any): JQuery;
/**
* Get the parent of each element in the current set of matched elements, optionally filtered by a selector.
*
* @see {@link https://api.jquery.com/parent/}
*/
parent(): JQuery;
/**
* Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
*
* @param content1 DOM element, DocumentFragment, array of elements, HTML string, or jQuery object to insert at the beginning of each element in the set of matched elements.
* @param content2 One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the beginning of each element in the set of matched elements.
* @see {@link https://api.jquery.com/prepend/#prepend-content-content}
*/
prepend(content1: JQuery | any[] | Element | DocumentFragment | Text | string, ...content2: any[]): JQuery;
/**
* Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.
*
* @param func A function that returns an HTML string, DOM element(s), or jQuery object to insert at the beginning of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.
* @see {@link https://api.jquery.com/prepend/#prepend-function}
*/
prepend(func: (index: number, html: string) => string | Element | JQuery): JQuery;
/**
* Get the value of a property for the first element in the set of matched elements.
*
* @param propertyName The name of the property to get.
* @see {@link https://api.jquery.com/prop/#prop-propertyName}
*/
prop(propertyName: string): any;
/**
* Set one or more properties for the set of matched elements.
*
* @param propertyName The name of the property to set.
* @param value A value to set for the property.
* @see {@link https://api.jquery.com/prop/#prop-propertyName-value}
*/
prop(propertyName: string, value: string | number | boolean): JQuery;
/**
* Set one or more properties for the set of matched elements.
*
* @param properties An object of property-value pairs to set.
* @see {@link https://api.jquery.com/prop/#prop-properties}
*/
prop(properties: Object): JQuery;
/**
* Set one or more properties for the set of matched elements.
*
* @param propertyName The name of the property to set.
* @param func A function returning the value to set. Receives the index position of the element in the set and the old property value as arguments. Within the function, the keyword this refers to the current element.
* @see {@link https://api.jquery.com/prop/#prop-propertyName-function}
*/
prop(propertyName: string, func: (index: number, oldPropertyValue: any) => any): JQuery;
/**
* Specify a function to execute when the DOM is fully loaded.
*
* @param handler A function to execute after the DOM is ready.
* @see {@link https://api.jquery.com/ready/}
*/
ready(handler: (jQueryAlias?: JQueryStatic) => any): JQuery;
/**
* Remove the set of matched elements from the DOM.
*
* @param selector A selector expression that filters the set of matched elements to be removed.
* @see {@link https://api.jquery.com/remove/}
*/
remove(selector?: string): JQuery;
/**
* Remove an attribute from each element in the set of matched elements.
*
* @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes.
* @see {@link https://api.jquery.com/removeAttr/}
*/
removeAttr(attributeName: string): JQuery;
/**
* Remove a single class, multiple classes, or all classes from each element in the set of matched elements.
*
* @param className One or more space-separated classes to be removed from the class attribute of each matched element.
* @see {@link https://api.jquery.com/removeClass/#removeClass-className}
*/
removeClass(className?: string): JQuery;
/**
* Remove a previously-stored piece of data.
*
* @param name A string naming the piece of data to delete or space-separated string naming the pieces of data to delete.
* @see {@link https://api.jquery.com/removeData/#removeData-name}
*/
removeData(name: string): JQuery;
/**
* Remove a previously-stored piece of data.
*
* @param list An array of strings naming the pieces of data to delete.
* @see {@link https://api.jquery.com/removeData/#removeData-list}
*/
removeData(list: string[]): JQuery;
/**
* Remove all previously-stored piece of data.
* @see {@link https://api.jquery.com/removeData/}
*/
removeData(): JQuery;
/**
* Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
*
* @param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object.
* @see {@link https://api.jquery.com/replaceWith/#replaceWith-newContent}
*/
replaceWith(newContent: JQuery | any[] | Element | Text | string): JQuery;
/**
* Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed.
*
* @param func A function that returns content with which to replace the set of matched elements.
* @see {@link https://api.jquery.com/replaceWith/#replaceWith-function}
*/
replaceWith(func: () => Element | JQuery): JQuery;
/**
* Get the combined text contents of each element in the set of matched elements, including their descendants.
* @see {@link https://api.jquery.com/text/#text}
*/
text(): string;
/**
* Set the content of each element in the set of matched elements to the specified text.
*
* @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will be converted to a String representation.
* @see {@link https://api.jquery.com/text/#text-text}
*/
text(text: string | number | boolean): JQuery;
/**
* Set the content of each element in the set of matched elements to the specified text.
*
* @param func A function returning the text content to set. Receives the index position of the element in the set and the old text value as arguments.
* @see {@link https://api.jquery.com/text/#text-function}
*/
text(func: (index: number, text: string) => string): JQuery;
/**
* Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
*
* @param className One or more class names (separated by spaces) to be toggled for each element in the matched set.
* @param swtch A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed.
* @see {@link https://api.jquery.com/toggleClass/#toggleClass-className}
*/
toggleClass(className: string, swtch?: boolean): JQuery;
/**
* Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the switch argument.
*
* @param swtch A boolean value to determine whether the class should be added or removed.
* @see {@link https://api.jquery.com/toggleClass/#toggleClass-state}
*/
toggleClass(swtch?: boolean): JQuery;
/**
* Execute all handlers attached to an element for an event.
*
* @param eventType A string containing a JavaScript event type, such as click or submit.
* @param extraParameters An array of additional parameters to pass along to the event handler.
* @see {@link https://api.jquery.com/triggerHandler/#triggerHandler-eventType-extraParameters}
*/
triggerHandler(eventType: string, ...extraParameters: any[]): Object;
/**
* Execute all handlers attached to an element for an event.
*
* @param event A jQuery.Event object.
* @param extraParameters An array of additional parameters to pass along to the event handler.
* @see {@link https://api.jquery.com/triggerHandler/#triggerHandler-event-extraParameters}
*/
triggerHandler(event: JQueryEventObject, ...extraParameters: any[]): Object;
/**
* Remove a previously-attached event handler from the elements.
*
* @param eventType A string containing a JavaScript event type, such as click or submit.
* @param handler The function that is to be no longer executed.
* @see {@link https://api.jquery.com/unbind/#unbind-eventType-handler}
*/
unbind(eventType?: string, handler?: (eventObject: JQueryEventObject) => any): JQuery;
/**
* Remove a previously-attached event handler from the elements.
*
* @param eventType A string containing a JavaScript event type, such as click or submit.
* @param fls Unbinds the corresponding 'return false' function that was bound using .bind( eventType, false ).
* @see {@link https://api.jquery.com/unbind/#unbind-eventType-false}
*/
unbind(eventType: string, fls: boolean): JQuery;
/**
* Remove a previously-attached event handler from the elements.
*
* @param evt A JavaScript event object as passed to an event handler.
* @see {@link https://api.jquery.com/unbind/#unbind-event}
*/
unbind(evt: any): JQuery;
/**
* Get the current value of the first element in the set of matched elements.
* @see {@link https://api.jquery.com/val/#val}
*/
val(): any;
/**
* Set the value of each element in the set of matched elements.
*
* @param value A string of text, an array of strings or number corresponding to the value of each matched element to set as selected/checked.
* @see {@link https://api.jquery.com/val/#val-value}
*/
val(value: string | string[] | number): JQuery;
/**
* Set the value of each element in the set of matched elements.
*
* @param func A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.
* @see {@link https://api.jquery.com/val/#val-function}
*/
val(func: (index: number, value: string) => string): JQuery;
/**
* Wrap an HTML structure around each element in the set of matched elements.
*
* @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements.
* @see {@link https://api.jquery.com/wrap/#wrap-wrappingElement}
*/
wrap(wrappingElement: JQuery | Element | string): JQuery;
/**
* Wrap an HTML structure around each element in the set of matched elements.
*
* @param func A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.
* @see {@link https://api.jquery.com/wrap/#wrap-function}
*/
wrap(func: (index: number) => string | JQuery): JQuery;
// Undocumented
length: number;
// TODO: events, how to define?
// $destroy
controller(name?: string): any;
injector(): ng.auto.IInjectorService;
/** It's declared generic for custom scope interfaces */
scope<T extends ng.IScope>(): T;
isolateScope<T extends ng.IScope>(): T;
inheritedData(key: string, value: any): JQuery;
inheritedData(obj: { [key: string]: any; }): JQuery;
inheritedData(key?: string): any;
}
interface JQueryStatic {
(element: string | Element | Document | JQuery | ArrayLike<Element>): JQuery;
}
/**
* Interface of the JQuery extension of the W3C event object
* @see {@link https://api.jquery.com/category/events/event-object/}
*/
interface BaseJQueryEventObject extends Event {
/**
* The current DOM element within the event bubbling phase.
* @see {@link https://api.jquery.com/event.currentTarget/}
*/
currentTarget: Element;
/**
* 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/}
*/
data: any;
/**
* The element where the currently-called jQuery event handler was attached.
* @see {@link https://api.jquery.com/event.delegateTarget/}
*/
delegateTarget: Element;
/**
* Returns whether event.preventDefault() was ever called on this event object.
* @see {@link https://api.jquery.com/event.isDefaultPrevented/}
*/
isDefaultPrevented(): boolean;
/**
* Returns whether event.stopImmediatePropagation() was ever called on this event object.
* @see {@link https://api.jquery.com/event.isImmediatePropagationStopped/}
*/
isImmediatePropagationStopped(): boolean;
/**
* Returns whether event.stopPropagation() was ever called on this event object.
* @see {@link https://api.jquery.com/event.isPropagationStopped/}
*/
isPropagationStopped(): boolean;
/**
* The namespace specified when the event was triggered.
* @see {@link https://api.jquery.com/event.namespace/}
*/
namespace: string;
/**
* The browser's original Event object.
* @see {@link https://api.jquery.com/category/events/event-object/}
*/
originalEvent: Event;
/**
* If this method is called, the default action of the event will not be triggered.
* @see {@link https://api.jquery.com/event.preventDefault/}
*/
preventDefault(): any;
/**
* The other DOM element involved in the event, if any.
* @see {@link https://api.jquery.com/event.relatedTarget/}
*/
relatedTarget: Element;
/**
* The last value returned by an event handler that was triggered by this event, unless the value was undefined.
* @see {@link https://api.jquery.com/event.result/}
*/
result: any;
/**
* Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree.
* @see {@link https://api.jquery.com/event.stopImmediatePropagation/}
*/
stopImmediatePropagation(): void;
/**
* Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
* @see {@link https://api.jquery.com/event.stopPropagation/}
*/
stopPropagation(): void;
/**
* The DOM element that initiated the event.
* @see {@link https://api.jquery.com/event.target/}
*/
target: Element;
/**
* The mouse position relative to the left edge of the document.
* @see {@link https://api.jquery.com/event.pageX/}
*/
pageX: number;
/**
* The mouse position relative to the top edge of the document.
* @see {@link https://api.jquery.com/event.pageY/}
*/
pageY: number;
/**
* For key or mouse events, this property indicates the specific key or button that was pressed.
* @see {@link https://api.jquery.com/event.which/}
*/
which: number;
/**
* Indicates whether the META key was pressed when the event fired.
* @see {@link https://api.jquery.com/event.metaKey/}
*/
metaKey: boolean;
}
interface JQueryInputEventObject extends BaseJQueryEventObject {
altKey: boolean;
ctrlKey: boolean;
metaKey: boolean;
shiftKey: boolean;
}
interface JQueryMouseEventObject extends JQueryInputEventObject {
button: number;
clientX: number;
clientY: number;
offsetX: number;
offsetY: number;
pageX: number;
pageY: number;
screenX: number;
screenY: number;
}
interface JQueryKeyEventObject extends JQueryInputEventObject {
char: any;
charCode: number;
key: any;
keyCode: number;
}
interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject {
}
/**
* The interface used to specify the properties parameter in css()
*/
// tslint:disable-next-line:class-name
interface cssPropertySetter {
(index: number, value?: string): string | number;
}
interface JQLiteCssProperties {
[propertyName: string]: string | number | cssPropertySetter;
}
+643
View File
@@ -0,0 +1,643 @@
import $ = require('jquery');
import * as angular from 'angular';
function JQuery() {
function addClass() {
// $ExpectType JQuery<HTMLElement>
$('p').addClass('className');
// $ExpectType JQuery<HTMLElement>
$('p').addClass(function(index, currentClassName) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType string
currentClassName;
return 'className';
});
}
function attr() {
// $ExpectType JQuery<HTMLElement>
$('#greatphoto').attr('alt', 'Beijing Brush Seller');
// $ExpectType JQuery<HTMLElement>
$('#greatphoto').attr('width', 200);
// $ExpectType JQuery<HTMLElement>
$('#greatphoto').attr('title', null);
// $ExpectType JQuery<HTMLElement>
$('#greatphoto').attr('alt', function(index, attr) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType string
attr;
return 'Beijing Brush Seller';
});
// $ExpectType JQuery<HTMLElement>
$('#greatphoto').attr('width', function(index, attr) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType string
attr;
return 200;
});
// $ExpectType JQuery<HTMLElement>
$('#greatphoto').attr('title', function(index, attr) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType string
attr;
});
// $ExpectType JQuery<HTMLElement>
$('#greatphoto').attr('title', function(index, attr) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType string
attr;
return undefined;
});
// $ExpectType JQuery<HTMLElement>
$('img').attr({
src: '/resources/hat.gif',
title: 'jQuery',
alt: 'jQuery Logo'
});
// @types/angular's definition wins here
// // $ExpectType string | undefined
// $('img').attr('src');
}
function bind() {
interface I1 { kind: 'I1'; }
// $ExpectType JQuery<HTMLElement>
$('p').bind('myEvent', 'myData', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('p').bind('myEvent', 'myData', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('p').bind('myEvent', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('p').bind('myEvent', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('p').bind('myEvent', false);
// $ExpectType JQuery<HTMLElement>
$('p').bind({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
}
});
// $ExpectType JQuery<HTMLElement>
$('p').bind('myEvent', null);
// $ExpectType JQuery<HTMLElement>
$('p').bind('myEvent', undefined);
}
function children() {
// $ExpectType JQuery<HTMLElement>
$('p').children('span');
// $ExpectType JQuery<HTMLElement>
$('p').children();
}
function off() {
function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event<HTMLElement>) { }
function defaultContext_customData(this: HTMLElement, event: JQuery.Event<HTMLElement, string>) { }
function customContext_defaultData(this: I1, event: JQuery.Event<HTMLElement>) { }
function customContext_customData(this: I1, event: JQuery.Event<HTMLElement, string>) { }
interface I1 { kind: 'I1'; }
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', 'td', defaultContext_defaultData);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', 'td', defaultContext_customData);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', 'td', customContext_defaultData);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', 'td', customContext_customData);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', 'td', false);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', 'td');
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', defaultContext_defaultData);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', defaultContext_customData);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', customContext_defaultData);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', customContext_customData);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent', false);
// $ExpectType JQuery<HTMLElement>
$('table').off('myEvent');
// $ExpectType JQuery<HTMLElement>
$('table').off({
myEvent1: false,
defaultContext_defaultData,
defaultContext_customData,
customContext_defaultData,
customContext_customData
}, 'td');
// $ExpectType JQuery<HTMLElement>
$('table').off({
myEvent1: false,
defaultContext_defaultData,
defaultContext_customData,
customContext_defaultData,
customContext_customData
});
// $ExpectType JQuery<HTMLElement>
$('table').off($.Event('myEvent'));
// $ExpectType JQuery<HTMLElement>
$('table').off();
}
function on() {
interface I1 { kind: 'I1'; }
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', 'td', 'myData', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', 'td', 'myData', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', null, 'myData', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', null, 'myData', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', 'td', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', 'td', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', 'td', false);
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', 3, function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, number>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', 3, function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, number>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').on('myEvent', false);
// $ExpectType JQuery<HTMLElement>
$('table').on({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, string>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, string>
event;
}
}, 'td', 'myData');
// $ExpectType JQuery<HTMLElement>
$('table').on({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, string>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, string>
event;
}
}, null, 'myData');
// $ExpectType JQuery<HTMLElement>
$('table').on({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
}
}, 'td');
// $ExpectType JQuery<HTMLElement>
$('table').on({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, number>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, number>
event;
}
}, 3);
// $ExpectType JQuery<HTMLElement>
$('table').on({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
}
});
}
function one() {
interface I1 { kind: 'I1'; }
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', 'td', 'myData', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', 'td', 'myData', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', null, 'myData', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', null, 'myData', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, string>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', 'td', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', 'td', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', 'td', false);
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', 3, function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, number>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', 3, function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, number>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', function(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', function(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
});
// $ExpectType JQuery<HTMLElement>
$('table').one('myEvent', false);
// $ExpectType JQuery<HTMLElement>
$('table').one({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, string>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, string>
event;
}
}, 'td', 'myData');
// $ExpectType JQuery<HTMLElement>
$('table').one({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, string>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, string>
event;
}
}, null, 'myData');
// $ExpectType JQuery<HTMLElement>
$('table').one({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
}
}, 'td');
// $ExpectType JQuery<HTMLElement>
$('table').one({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, number>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, number>
event;
}
}, 3);
// $ExpectType JQuery<HTMLElement>
$('table').one({
myEvent1: false,
myEvent2(event) {
// $ExpectType HTMLElement
this;
// $ExpectType Event<HTMLElement, null>
event;
},
myEvent3(this: I1, event) {
// $ExpectType I1
this;
// $ExpectType Event<HTMLElement, null>
event;
}
});
}
function removeClass() {
// $ExpectType JQuery<HTMLElement>
$('p').removeClass('className');
// $ExpectType JQuery<HTMLElement>
$('p').removeClass(function(index, currentClassName) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType string
currentClassName;
return 'className';
});
// $ExpectType JQuery<HTMLElement>
$('p').removeClass();
}
function toggleClass() {
// $ExpectType JQuery<HTMLElement>
$('p').toggleClass('className', true);
// $ExpectType JQuery<HTMLElement>
$('p').toggleClass(function(index, className, state) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType string
className;
// $ExpectType true
state;
return 'className';
}, true);
// $ExpectType JQuery<HTMLElement>
$('p').toggleClass('className');
// $ExpectType JQuery<HTMLElement>
$('p').toggleClass(function(index, className, state) {
// $ExpectType HTMLElement
this;
// $ExpectType number
index;
// $ExpectType string
className;
// $ExpectType boolean
state;
return 'className';
});
// $ExpectType JQuery<HTMLElement>
$('p').toggleClass(false);
// $ExpectType JQuery<HTMLElement>
$('p').toggleClass();
}
}
+7 -4
View File
@@ -1,13 +1,16 @@
{
"files": [
"index.d.ts",
"angular-tests.ts"
"jqlite.d.ts",
"angular-tests.ts",
"test/jquery3-merging-tests.ts"
],
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
"es5",
"dom",
"es2015.iterable"
],
"noImplicitAny": false,
"noImplicitThis": false,
@@ -20,4 +23,4 @@
"noEmit": true,
"forceConsistentCasingInFileNames": true
}
}
}
+1 -1
View File
@@ -39,7 +39,7 @@ const withFont = StyleSheet.create({
});
class App extends React.Component<{}, {}> {
class App extends React.Component {
render() {
return <div>
<span className={css(styles.red)}>
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/Khan/aphrodite
// Definitions by: Alexey Svetliakov <https://github.com/asvetliakov>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
// TypeScript Version: 2.3
import * as React from "react";
+3334 -1558
View File
File diff suppressed because it is too large Load Diff
+103 -29
View File
@@ -1,4 +1,4 @@
// Type definitions for ArcGIS API for JavaScript 3.20
// Type definitions for ArcGIS API for JavaScript 3.21
// Project: https://developers.arcgis.com/javascript/3/
// Definitions by: Esri <https://github.com/Esri>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -18,6 +18,7 @@ declare module "esri" {
import BasemapLayer = require("esri/dijit/BasemapLayer");
import Symbol = require("esri/symbols/Symbol");
import BookmarkItem = require("esri/dijit/BookmarkItem");
import TimeInfo = require("esri/layers/TimeInfo");
import Color = require("esri/Color");
import LocationProviderBase = require("esri/tasks/locationproviders/LocationProviderBase");
import PictureMarkerSymbol = require("esri/symbols/PictureMarkerSymbol");
@@ -213,6 +214,8 @@ declare module "esri" {
isReference?: boolean;
/** Initial opacity or transparency of the basemap layer. */
opacity?: number;
/** A url to a JSON file containing the stylesheet information to render the VectorTileLayer. */
styleUrl?: string;
/** Specify subDomains where tiles are served to speed up tile retrieval (using subDomains gets around the browser limit of the max number of concurrent requests to a domain). */
subDomains?: string[];
/** The URL template used to retrieve the tiles. */
@@ -221,7 +224,7 @@ declare module "esri" {
tileInfo?: TileInfo;
/** Define additional tile server domains for the layer. */
tileServer?: string[];
/** The type of layer, valid values are "BingMapsAerial", "BingMapsHybrid", "BingMapsRoad", "OpenStreetMap", or "WebTiledLayer". */
/** The type of layer. */
type?: string;
/** URL to the ArcGIS Server REST resource that represents a map or image service. */
url?: string;
@@ -293,6 +296,8 @@ declare module "esri" {
outFields?: string[];
/** Refresh interval of the layer in minutes. */
refreshInterval?: number;
/** Time information for the layer, such as start time field, end time field, track id field, layers time extent and the draw time interval. */
timeInfo?: TimeInfo;
/** Visibility of the layer. */
visible?: boolean;
}
@@ -474,17 +479,17 @@ declare module "esri" {
/** The selected color. */
color: Color;
/** The row size of the palette. */
colorsPerRow: number;
colorsPerRow?: number;
/** The set of available color options. */
palette: Color[];
palette?: Color[];
/** Array of recent colors to show in the recent colors row. */
recentColors: Color[];
recentColors?: Color[];
/** Toggles color selection being required. */
required: boolean;
required?: boolean;
/** Toggles the recent color row. */
showRecentColors: boolean;
showRecentColors?: boolean;
/** Toggles the transparency slider. */
showTransparencySlider: boolean;
showTransparencySlider?: boolean;
}
export interface ConnectOriginsToDestinationsOptions {
/** The URL to the GPServer used to execute an analysis job. */
@@ -879,6 +884,8 @@ declare module "esri" {
showSelectFolder?: boolean;
}
export interface FeatureLayerOptions {
/** Indicates whether attribute features containing m-values can be edited. */
allowUpdateWithoutMValues?: boolean;
/** Enable or disable the auto generalization of features from a non-editable layer in on-demand mode. */
autoGeneralize?: boolean;
/** Class attribute to set for the layer's node. */
@@ -1401,6 +1408,22 @@ declare module "esri" {
force3DTransforms?: boolean;
/** By default the map creates and uses an out-of-the-box esri/dijit/Popup. */
infoWindow?: InfoWindowBase;
/** Indicates whether to enable double-click on a map to recenter and zoom in a level by using SHIFT + Click. */
isClickRecenter?: boolean;
/** Indicates whether double-clicking on map zooms in on extent. */
isDoubleClickZoom?: boolean;
/** Indicates whether to enable navigation of the map using a keyboard's arrow keys. */
isKeyboardNavigation?: boolean;
/** Indicates whether all map navigation is enabled. */
isMapNavigation?: boolean;
/** Indicates whether panning is enabled within the map. */
isPan?: boolean;
/** Indicates whether pinch zoom navigation is enabled on touch-enabled devices. */
isPinchZoom?: boolean;
/** Indicates whether to enable a mouse drag to zoom into to a specific region on the map. */
isRubberBandZoom?: boolean;
/** (Added at version 3.21). */
isScrollWheel?: boolean;
/** If provided, the map is initialized with the specified levels of detail. */
lods?: LOD[];
/** Display the esri logo on the map. */
@@ -1547,8 +1570,6 @@ declare module "esri" {
popupWindowFeatures?: string;
/** The ArcGIS for Portal URL. */
portalUrl?: string;
/** Indicates whether to display social logins such as Google/Facebook. */
showSocialLogins?: boolean;
}
export interface ObliqueViewerOptions {
/** Azimuth angle value for which to display oblique images. */
@@ -1765,6 +1786,8 @@ declare module "esri" {
export interface PrintOptions {
/** Set to true if the print service is an asynchronous geoprocessing service. */
async?: boolean;
/** Additional parameters for the print service. */
extraParameters?: any;
/** The map to print. */
map?: Map;
/** An optional array of user-defined templates. */
@@ -1891,8 +1914,6 @@ declare module "esri" {
expanded?: boolean;
/** This the specified graphicsLayer to use for the highlightGraphic and labelGraphic instead of map.graphics. */
graphicsLayer?: Layer;
/** The symbol used for highlightGraphic. */
highlightSymbol?: Symbol;
/** A customized infoTemplate for the selected feature. */
infoTemplate?: InfoTemplate;
/** The text symbol for the label graphic. */
@@ -2528,7 +2549,7 @@ declare module "esri/IdentityManagerBase" {
findCredential(url: string, userId?: string): Credential;
/**
* Returns the OAuth configuration for the passed in Portal server URL.
* @param url The URL to the Portal.
* @param url The ArcGIS for Portal URL, for example "https://www.arcgis.com" for ArcGIS Online and "https://www.example.com/portal" for your in-house portal.
*/
findOAuthInfo(url: string): OAuthInfo;
/**
@@ -2553,7 +2574,7 @@ declare module "esri/IdentityManagerBase" {
* Call this method (during your application initialization) with JSON previously obtained from toJson method to re-hydrate the state of identity manager.
* @param json The JSON obtained from the toJson method.
*/
initialize(json: Object): any;
initialize(json: Object): void;
/** Returns true if the identity manager is busy accepting user input, i.e., the user has invoked signIn and is waiting for a response. */
isBusy(): boolean;
/**
@@ -2576,7 +2597,7 @@ declare module "esri/IdentityManagerBase" {
registerServers(serverInfos: ServerInfo[]): void;
/**
* Registers the given OAuth2 access token with the identity manager.
* @param properties See the object specifications table below for the structure of the properties object.
* @param properties See the object specifications table below for the structure of the properties object.
*/
registerToken(properties: any): void;
/**
@@ -2889,8 +2910,6 @@ declare module "esri/arcgis/OAuthInfo" {
popupWindowFeatures: string;
/** The ArcGIS for Portal URL. */
portalUrl: string;
/** Indicates whether to display social logins like Google/Facebook. */
showSocialLogins: boolean;
/**
* Creates a new OAuthInfo given the specified parameters.
* @param params Various options to configure the OAuthInfo object.
@@ -2947,6 +2966,8 @@ declare module "esri/arcgis/Portal" {
defaultBasemap: any;
/** The default extent for the map the portal displays in the map viewer. */
defaultExtent: any;
/** The default vector basemap to use for the portal. */
defaultVectorBasemap: any;
/** A description of the organization / portal. */
description: string;
/** The featured groups for the portal. */
@@ -2957,6 +2978,8 @@ declare module "esri/arcgis/Portal" {
featuredItemsGroupQuery: string;
/** The query that identifies the group containing features items for the gallery. */
galleryTemplatesGroupQuery: string;
/** Helper services provided by the portal. */
helperServices: any;
/** The group that contains featured content to be displayed on the home page. */
homePageFeaturedContent: string;
/** The number of featured items that can be displayed on the home page. */
@@ -2991,7 +3014,7 @@ declare module "esri/arcgis/Portal" {
portalProperties: any;
/** The URL to the thumbnail of the portal. */
portalThumbnail: string;
/** URL to the portal. */
/** The REST URL for the portal, for example "https://www.arcgis.com/sharing/rest/" for ArcGIS Online and "https://www.example.com/arcgis/sharing/rest/" for your in-house portal. */
portalUrl: string;
/** The region for the organization. */
region: string;
@@ -3013,7 +3036,7 @@ declare module "esri/arcgis/Portal" {
thumbnailUrl: string;
/** Sets the units of measure for the organization's users. */
units: string;
/** The portal url. */
/** The ArcGIS for Portal URL, for example "https://www.arcgis.com" for ArcGIS Online and "https://www.example.com/arcgis" for your in-house portal. */
url: string;
/** The prefix selected by the organization's administrator to be used with the customBaseURL. */
urlKey: string;
@@ -3021,9 +3044,13 @@ declare module "esri/arcgis/Portal" {
user: PortalUser;
/** If true, only simple where clauses that are complaint with SQL92 can be used when querying layers and tables. */
useStandardizedQuery: boolean;
/** Whether an organization has opted in to use the vector tile basemaps. */
useVectorBasemaps: boolean;
/** The query that defines the vector tiles basemaps that should be displayed in the Basemap Gallery when useVectorBasemaps is true. */
vectorBasemapGalleryGroupQuery: string;
/**
* Creates a new Portal object.
* @param url URL to the ArcGIS.com site or in-house portal.
* @param url The ArcGIS for Portal URL, for example "https://www.arcgis.com" for ArcGIS Online and "https://www.example.com/arcgis" for your in-house portal.
*/
constructor(url: string);
/** Returns a PortalUser object that describes the user currently signed in to the portal. */
@@ -3111,6 +3138,11 @@ declare module "esri/arcgis/Portal" {
url: string;
/** Get the current members for the group. */
getMembers(): any;
/**
* Get the URL to the thumbnail image for the portal group.
* @param width The desired image width.
*/
getThumbnailUrl(width?: number): string;
/**
* Execute a query against the group to return a deferred that when resolved returns PortalQueryResult that contain a results array of PortalItem objects that match the input query.
* @param queryParams The input query parameters.
@@ -3196,6 +3228,11 @@ declare module "esri/arcgis/Portal" {
getComments(): any;
/** Returns the rating (if any) given to the item. */
getRating(): any;
/**
* Get the URL to the thumbnail image for the portal item.
* @param width The desired image width.
*/
getThumbnailUrl(width?: number): string;
/**
* Updates an item comment.
* @param comment A PortalComment that contains the comment updates.
@@ -3274,6 +3311,11 @@ declare module "esri/arcgis/Portal" {
getNotifications(): any;
/** Access the tag objects that have been created by the portal user. */
getTags(): any;
/**
* Get the URL to the thumbnail image for the portal user.
* @param width The desired image width.
*/
getThumbnailUrl(width?: number): string;
}
}
@@ -3440,7 +3482,7 @@ declare module "esri/dijit/BasemapGallery" {
import esri = require("esri");
import Basemap = require("esri/dijit/Basemap");
/** The BasemapGallery dijit displays a collection basemaps from ArcGIS.com or a user-defined set of map or image services. */
/** The BasemapGallery dijit displays a collection of basemaps from ArcGIS.com or a user-defined set of map or image services. */
class BasemapGallery {
/** List of basemaps displayed in the BasemapGallery. */
basemaps: Basemap[];
@@ -3508,6 +3550,8 @@ declare module "esri/dijit/BasemapLayer" {
fullExtent: Extent;
/** The initial extent of the layer. */
initialExtent: Extent;
/** A url to a JSON file containing the stylesheet information to render the VectorTileLayer. */
styleUrl: string;
/** The subDomains where tiles are served to speed up tile retrieval (using subDomains gets around the browser limit of the max number of concurrent requests to a domain). */
subDomains: string[];
/** The tile info for the layer including lods, rows, cols, origin and spatial reference. */
@@ -5288,6 +5332,8 @@ declare module "esri/dijit/PopupTemplate" {
/** The PopupTemplate class extends esri/InfoTemplate and provides support for defining a layout. */
class PopupTemplate extends InfoTemplate {
/** An array of objects that reference Arcade expressions. */
expressionInfos: any[];
/** The popup definition defined as a JavaScript object. */
info: any;
/**
@@ -5640,6 +5686,9 @@ declare module "esri/dijit/SymbolStyler" {
startup(): void;
/** Saves the recent fill and outline colors. */
storeColors(): void;
/** Fired every time an edit is committed. */
on(type: "style-update", listener: (event: { target: SymbolStyler }) => void): esri.Handle;
on(type: string, listener: (event: any) => void): esri.Handle;
}
export = SymbolStyler;
}
@@ -5865,7 +5914,7 @@ declare module "esri/dijit/analysis/AnalysisBase" {
checkJobStatus(jobId: string): void;
/**
* Starts an analysis tool.
* @param params See the object specifications table below for the structure of the params object.
* @param params See the object specifications table below for the structure of the params object.
*/
execute(params: string): void;
/**
@@ -8633,6 +8682,8 @@ declare module "esri/graphic" {
getShape(): any;
/** Returns one or more dojox/gfx/shape.Shape used to draw the graphic. */
getShapes(): any[];
/** In contrast to the getLayer method, getSouceLayer does not change when a graphic is added to another layer. */
getSourceLayer(): Layer;
/** Returns the title string based on attributes and infoTemplate values. */
getTitle(): string;
/** Hides the graphic. */
@@ -9471,6 +9522,8 @@ declare module "esri/layers/FeatureLayer" {
advancedQueryCapabilities: any;
/** Returns true if the geometry of the features in the layer can be edited, false otherwise. */
allowGeometryUpdates: boolean;
/** Indicates whether attribute features containing m-values can be edited. */
allowUpdateWithoutMValues: boolean;
/** The URL, when available, where the layer's attribution data is stored. */
attributionDataUrl: string;
/** Information about the capabilities enabled for this layer. */
@@ -10279,6 +10332,8 @@ declare module "esri/layers/KMLLayer" {
getFeature(featureInfo: any): any;
/** Get an array of map layers that were created to draw placemarks, ground and screen overlays. */
getLayers(): Layer[];
/** Refreshes the features in the KML Layer. */
refresh(): void;
/**
* Set the visibility for the specified folder.
* @param folder A KML folder.
@@ -11034,6 +11089,8 @@ declare module "esri/layers/VectorTileLayer" {
fullExtent: Extent;
/** The initial extent of the layer. */
initialExtent: Extent;
/** Name of the vector tile layer. */
name: string;
/** The spatial reference of the layer. */
spatialReference: SpatialReference;
/** Contains information about the tiling scheme for the layer. */
@@ -11055,6 +11112,10 @@ declare module "esri/layers/VectorTileLayer" {
setStyle(styleUrl: string | any): void;
/** Fires when the style is changed on the layer. */
on(type: "style-change", listener: (event: { style: any; target: VectorTileLayer }) => void): esri.Handle;
/** Fires when the layer has finished updating its content. */
on(type: "update-end", listener: (event: { target: VectorTileLayer }) => void): esri.Handle;
/** Fires when the layer begins to update its content. */
on(type: "update-start", listener: (event: { target: VectorTileLayer }) => void): esri.Handle;
on(type: string, listener: (event: any) => void): esri.Handle;
}
export = VectorTileLayer;
@@ -11773,12 +11834,18 @@ declare module "esri/map" {
isDoubleClickZoom: boolean;
/** When true, keyboard navigation is enabled. */
isKeyboardNavigation: boolean;
/** Indicates whether all map navigation is enabled. */
isMapNavigation: boolean;
/** When true, map panning is enabled using the mouse. */
isPan: boolean;
/** When true, pan arrows are displayed around the edge of the map. */
isPanArrows: boolean;
/** Indicates whether pinch zoom navigation is enabled on touch-enabled devices. */
isPinchZoom: boolean;
/** When true, rubberband zoom is enabled. */
isRubberBandZoom: boolean;
/** It indicates whether map navigation based on mouse scroll wheel is enabled. */
isScrollWheel: boolean;
/** When true, the mouse scroll wheel zoom is enabled. */
isScrollWheelZoom: boolean;
/** When true, shift double click zoom is enabled. */
@@ -11853,8 +11920,11 @@ declare module "esri/map" {
disableMapNavigation(): void;
/** Disallows panning a map using the mouse. */
disablePan(): void;
disablePinchZoom(): void;
/** Disallows zooming in or out on a map using a bounding box. */
disableRubberBandZoom(): void;
/** Disables navigation of the map based on mouse scroll wheel. */
disableScrollWheel(): void;
/** Disallows zooming in or out on a map using the mouse scroll wheel. */
disableScrollWheelZoom(): void;
/** Disallows shift double clicking on a map to zoom in a level and center the map. */
@@ -11871,8 +11941,12 @@ declare module "esri/map" {
enableMapNavigation(): void;
/** Permits users to pan a map using the mouse. */
enablePan(): void;
/** Enables the user to work with pinch zoom navigation for touch-enabled devices. */
enablePinchZoom(): void;
/** Permits users to zoom in or out on a map using a bounding box. */
enableRubberBandZoom(): void;
/** Enables the user to navigate the map based on mouse scroll wheel. */
enableScrollWheel(): void;
/** Permits users to zoom in or out on a map using the mouse scroll wheel. */
enableScrollWheelZoom(): void;
/** Permits users to shift double click on a map to zoom in a level and center the map. */
@@ -12947,7 +13021,7 @@ declare module "esri/renderers/HeatmapRenderer" {
import esri = require("esri");
import Renderer = require("esri/renderers/Renderer");
/** The HeatmapRenderer renders point data into a raster visualization that emphasizes areas of higher density or weighted values. */
/** The HeatmapRenderer renders feature layer point data into a raster visualization that emphasizes areas of higher density or weighted values. */
class HeatmapRenderer extends Renderer {
/** The radius (in pixels) of the circle over which the majority of each points value is spread out over. */
blurRadius: number;
@@ -13052,7 +13126,7 @@ declare module "esri/renderers/Renderer" {
* Returns the visual variable of the specified type.
* @param type The type of visual variable desired.
*/
getVisualVariablesForType(type: string): any;
getVisualVariablesForType(type: string): any[];
/** Indicates if the renderer has defined visualVariables. */
hasVisualVariables(): boolean;
/**
@@ -14873,7 +14947,7 @@ declare module "esri/tasks/GeometryService" {
distance(params: DistanceParameters, callback?: Function, errback?: Function): any;
/**
* Converts an array of well-known strings into xy-coordinates based on the conversion type and spatial reference supplied by the user.
* @param params See the object specifications table below for the structure of the params object.
* @param params See the object specifications table below for the structure of the params object.
* @param callback The function to call when the method has completed.
* @param errback An error object is returned if an error occurs during task execution.
*/
@@ -14945,7 +15019,7 @@ declare module "esri/tasks/GeometryService" {
simplify(geometries: Geometry[], callback?: Function, errback?: Function): any;
/**
* Converts an array of xy-coordinates into well-known strings based on the conversion type and spatial reference supplied by the user.
* @param params See the object specifications table below for the structure of the params object.
* @param params See the object specifications table below for the structure of the params object.
* @param callback The function to call when the method has completed.
* @param errback An error object is returned if an error occurs during task execution.
*/
@@ -15890,7 +15964,7 @@ declare module "esri/tasks/RouteParameters" {
startTimeIsUTC: boolean;
/** The set of stops loaded as network locations during analysis. */
stops: any;
/** If true , the TimeWindowStart and TimeWindowEnd attributes of a stop are in UTC time (milliseconds). */
/** If true, the TimeWindowStart and TimeWindowEnd attributes of a stop are in UTC time (milliseconds). */
timeWindowsAreUTC: boolean;
/** Travel modes define how a pedestrian, car, truck or other medium of transportation moves through the street network. */
travelMode: any;
@@ -17172,7 +17246,7 @@ declare module "esri/tasks/locator" {
*/
constructor(url: string);
/**
* Find address candidates for the input addresses.
* Find address candidates for multiple input addresses.
* @param params The input addresses in the format supported by the geocoding service.
* @param callback The function to call when the method has completed.
* @param errback The function to call if an error occurs on the server during task execution.
@@ -17180,7 +17254,7 @@ declare module "esri/tasks/locator" {
addressesToLocations(params: any, callback: Function, errback: Function): any;
/**
* Sends a request to the ArcGIS REST geocode resource to find candidates for a single address specified in the address parameter.
* @param params Specify the address and optionally specify the outFields and searchExtent.
* @param params Specify at least the address and optionally other properties.
* @param callback The function to call when the method has completed.
* @param errback An error object is returned if an error occurs on the Server during task execution.
*/
-4
View File
@@ -15,9 +15,7 @@
/// <reference types="node" />
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,8 +44,6 @@ declare namespace archiver {
glob(pattern: string, options?: glob.IOptions, data?: EntryData): this;
finalize(): this;
pipe(stream: fs.WriteStream | express.Response): void;
setFormat(format: string): this;
setModule(module: Function): this;
+14
View File
@@ -0,0 +1,14 @@
import arrify = require("arrify");
arrify(null);
arrify<number>(null);
arrify(undefined);
arrify<number>(undefined);
arrify(1);
arrify([2, 3]);
function test(val?: string | string[]) {
arrify(val);
}
+18
View File
@@ -0,0 +1,18 @@
// Type definitions for arrify 1.0.1
// Project: https://github.com/sindresorhus/arrify
// Definitions by: AnJun Wang <https://github.com/wanganjun>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* @example
* arrify(undefined) // returns []
* @example
* arrify(null) // returns []
* @example
* arrify(1) // returns [1]
* @example
* arrify([2, 3]) // returns [2, 3]
* @param val
*/
declare function arrify<T>(val: undefined | null | T | T[]): T[];
export = arrify;
+22
View File
@@ -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",
"arrify-tests.ts"
]
}
@@ -0,0 +1,15 @@
import { AskmethatRating, AskmethatRatingSteps } from "askmethat-rating";
let options = {
backgroundColor: "#e5e500",
hoverColor: "#ffff66",
fontClass: "fa fa-star",
minRating: 1,
maxRating: 5,
readonly: false,
step: AskmethatRatingSteps["OnePerOneStep"],
inputName: "AskmethatRating"
};
let div = document.createElement("div");
let amcRating = new AskmethatRating(div, 2 , options);
+131
View File
@@ -0,0 +1,131 @@
// Type definitions for askmethat-rating 0.3
// Project: https://alexteixeira.github.io/Askmethat-Rating/
// Definitions by: Alexandre Teixeira <https://github.com/AlexTeixeira/>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
export enum AskmethatRatingSteps {
/**
* Step 0.1 per 0.1
*/
DecimalStep = 0,
/**
* Step 0.5 per 0.5
*/
HalfStep = 1,
/**
* Step 1 per 1
*/
OnePerOneStep = 2,
}
export interface AskmethatRatingOptions {
hoverColor?: string;
/**
* Color when the rating is not hovered
*/
backgroundColor?: string;
/**
* Mininmum rating that the user can set
*/
minRating?: number;
/**
* Maximum rating that the plugin display
*/
maxRating?: number;
/**
* Class to display as rating (FontAwesome or Rating for exemple)
*/
fontClass: string;
/**
* Set the rating to readonly
*/
readonly: boolean;
/**
* The stepping for the rating
*/
step: AskmethatRatingSteps;
/**
* Input name (Default is AskmethatRating)
*/
inputName: string;
}
export class AskmethatRating {
private parentElement;
private pValue;
private styleSheet;
private changeEvent;
private ratingClick;
private mouseMove;
/**
* @function get the current value for the rating
*/
/**
* @function set a new value for the rating
*
* @param _value this is the new value you want to set to the rating
* @returns the current number
*/
value: number;
/**
* Default option base on @type IAskmethatRatingOptions
*/
private _defaultOptions;
/**
* @function get the default option for the rating
*
* @return options based on @type AskmethatRatingOptions
*/
readonly defaultOptions: any;
/**
* constructor with div element, default rating value & default options
*
* @param element This is the html container for the rating elements
* @param defaultValue Default value set when the plugin render the rating
* @param options Default option base on AskmethatRatingOptions type
*/
constructor(element: HTMLDivElement, defaultValue?: number, options?: any);
/**
* render a new rating, by default value is the minRating
*
* @param value this is the default value set when the plugin is rendered, by default IAskmethatRatingOptions.minRating
*/
render(value?: number): void;
/**
* @function when a rating is clicked
* @param {type} event : Event {event object}
*/
private onRatingClick(event?);
/**
* @function Calculate the value according to the step provided in options
* @param {Number} value:number the current value
* @return {Number} the new value according to step
*/
protected getValueAccordingToStep(value: number): number;
/**
* @function mouse event enter in rating
* @param {type} event?: Event {event}
*/
private onMouseMove(event?);
/**
* @function mouse out event in rating
* @param {type} event?: Event {event}
*/
private onMouseLeave(event?);
/**
* @function set or unset the active class and color
* @param {HTMLSpanElement} current : current span element
* @param {number} current : value needed for the if
*/
protected setOrUnsetActive(value: number): void;
/**
* Check if disabled attribute is added or removed from the input
* Update readonly status if needed for the rating
*/
private mutationEvent();
/**
* @function static method to retrieve with identifier the value
* @param {string} identifier: string container identifier
* @return {number} current rating
*/
static value(identifier: string): number;
}
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6",
"dom"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"askmethat-rating-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/thejameskyle/assert-equal-jsx
// Definitions by: Josh Toft <https://github.com/seryl>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 2.3
import * as React from 'react';
@@ -0,0 +1,11 @@
import {nextTick} from 'async.nexttick';
function calledOnNextTick(a: string): number {
return parseInt(a, 10);
}
const aString = 'Hi!';
nextTick(() => {
calledOnNextTick(aString);
});
+6
View File
@@ -0,0 +1,6 @@
// Type definitions for async.nexttick 0.5
// Project: https://www.npmjs.com/package/async.nexttick
// Definitions by: Damien "pyrho" Rajon <https://github.com/pyrho>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export function nextTick(callback: () => void, ...args: any[]): void;
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"async.nexttick-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+26
View File
@@ -0,0 +1,26 @@
import * as audiosprite from 'audiosprite';
const files = ['file1.mp3', 'file2.mp3'];
const opts = {output: 'result'};
audiosprite(files, opts, (err, obj) => {
if (err) {
return err;
}
return JSON.stringify(obj, null, 2);
});
audiosprite(files, {
path: "aaa",
format: "howler",
export: "ogg,mp3",
minlength: 9999,
vbr: 9,
'vbr:vorbis': 10,
logger: {
debug(a) {
}
}
}, (err, obj) => {
});
+55
View File
@@ -0,0 +1,55 @@
// Type definitions for audiosprite 0.6
// Project: https://github.com/tonistiigi/audiosprite
// Definitions by: Gyusun Yeom <https://github.com/Perlmint>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace audiosprite;
export = audiosprite;
declare function audiosprite(files: string[], callback: (error: Error, obj: audiosprite.Result) => void): void;
declare function audiosprite(files: string[], option: audiosprite.Option, callback: (error: Error, obj: audiosprite.Result) => void): void;
declare namespace audiosprite {
type ExportType = "jukebox" | "howler" | "createjs" | null;
type LogLevel = "debug" | "info" | "notice" | "warning" | "error";
type VBR = -1 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type VBR_Vorbis = VBR | 10;
type Channels = 1 | 2;
interface Option {
output?: string;
path?: string;
export?: string;
format?: ExportType;
log?: LogLevel;
autoplay?: string | null;
loop?: string[];
silence?: number;
gap?: number;
minlength?: number;
bitrate?: number;
vbr?: VBR;
'vbr:vorbis'?: VBR_Vorbis;
samplerate?: number;
channels?: Channels;
rawparts?: string;
logger?: Logger;
}
interface Logger {
debug?(...log: any[]): void;
info?(...log: any[]): void;
log?(...log: any[]): void;
}
interface Result {
resources: string[];
spritemap: {
[key: string]: {
start: number;
end: number;
loop: boolean;
}
};
autoplay?: string;
}
}
+22
View File
@@ -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",
"audiosprite-tests.ts"
]
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+38 -1
View File
@@ -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.
@@ -28,6 +29,42 @@ management
// Handle the error.
});
// Using a callback.
management.getUser({id: 'user_id'},(err: Error, user: auth0.User) => {
if (err) {
// Handle error.
}
console.log(user);
});
// Using a Promise.
management
.getUser({id: 'user_id'})
.then((user) => {
console.log(user);
})
.catch((err) => {
// Handle the error.
});
// Using a callback.
management.deleteUser({id: 'user_id'},(err: Error) => {
if (err) {
// Handle error.
}
console.log('deleted');
});
// Using a Promise.
management
.deleteUser({id: 'user_id'})
.then(() => {
console.log('deleted');
})
.catch((err) => {
// Handle the error.
});
management
.createUser({
connection: 'My-Connection',
+85 -30
View File
@@ -1,6 +1,6 @@
// Type definitions for auth0 2.4
// Type definitions for auth0 2.3
// Project: https://github.com/auth0/node-auth0
// Definitions by: Wilson Hobbs <https://github.com/wbhob>, Seth Westphal <https://github.com/westy92>
// Definitions by: Wilson Hobbs <https://github.com/wbhob>, Seth Westphal <https://github.com/westy92>, Amiram Korach <https://github.com/amiram>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -15,16 +15,29 @@ export interface UserMetadata { }
export interface AppMetadata { }
export interface UserData {
connection: string;
email?: string;
username?: string;
email_verified?: boolean;
verify_email?: boolean;
password?: string;
phone_number?: string;
phone_verified?: boolean,
user_metadata?: UserMetadata;
email_verified?: boolean;
app_metadata?: AppMetadata;
}
export interface CreateUserData extends UserData {
connection: string;
}
export interface UpdateUserData extends UserData {
connection?: string;
blocked?: boolean;
verify_phone_number?: boolean,
verify_password?: boolean,
client_id?: string
}
export interface GetUsersData {
per_page?: number;
page?: number;
@@ -68,12 +81,9 @@ export interface Identity {
isSocial: boolean;
}
export interface UpdateUserParameters {
id: string;
}
export interface AuthenticationClientOptions {
clientId?: string;
clientSecret?: string;
domain: string;
}
@@ -122,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;
}
@@ -135,20 +155,51 @@ export interface ClientParams {
client_id: string;
}
export type DeleteDeleteMultifactorParamsProvider = 'duo' | 'google-authenticator';
export interface DeleteMultifactorParams {
id: string;
provider: string;
provider: DeleteDeleteMultifactorParamsProvider;
}
export interface LinkAccountsParams {
export type UnlinkAccountsParamsProvider = 'ad' | 'adfs' | 'amazon' | 'dropbox' | 'bitbucket' | 'aol' | 'auth0-adldap' |
'auth0-oidc' | 'auth0' | 'baidu' | 'bitly' | 'box' | 'custom' | 'dwolla' | 'email' | 'evernote-sandbox' | 'evernote' |
'exact' | 'facebook' | 'fitbit' | 'flickr' | 'github' | 'google-apps' | 'google-oauth2' | 'guardian' | 'instagram' |
'ip' | 'linkedin' | 'miicard' | 'oauth1' | 'oauth2' | 'office365' | 'paypal' | 'paypal-sandbox' | 'pingfederate' |
'planningcenter' | 'renren' | 'salesforce-community' | 'salesforce-sandbox' | 'salesforce' | 'samlp' | 'sharepoint' |
'shopify' | 'sms' | 'soundcloud' | 'thecity-sandbox' | 'thecity' | 'thirtysevensignals' | 'twitter' | 'untappd' |
'vkontakte' | 'waad' | 'weibo' | 'windowslive' | 'wordpress' | 'yahoo' | 'yammer' | 'yandex';
export interface UnlinkAccountsParams {
id: string;
provider: string;
provider: UnlinkAccountsParamsProvider;
user_id: string;
}
export interface UnlinkAccountsResponseProfile {
email?: string;
email_verified?: boolean;
name?: string;
username?: string;
given_name?: string;
phone_number?: string;
phone_verified?: boolean;
family_name?: string;
}
export interface UnlinkAccountsResponse {
connection: string;
user_id: string;
provider: string;
isSocial?: boolean;
access_token?: string;
profileData?: UnlinkAccountsResponseProfile
}
export interface LinkAccountsData {
user_id: string;
connection_id: string;
connection_id?: string;
provider?: string;
}
export interface Token {
@@ -215,8 +266,11 @@ export class AuthenticationClient {
getProfile(accessToken: string): Promise<any>;
getProfile(accessToken: string, cb: (err: Error, message: string) => void): void;
getCredentialsGrant(scope: string): Promise<any>;
getCredentialsGrant(scope: string, cb: (err: Error, message: string) => void): void;
clientCredentialsGrant(options: ClientCredentialsGrantOptions): Promise<any>;
clientCredentialsGrant(options: ClientCredentialsGrantOptions, cb: (err: Error, response: any) => void): void;
passwordGrant(options: PasswordGrantOptions): Promise<any>;
passwordGrant(options: PasswordGrantOptions, cb: (err: Error, response: any) => void): void;
}
@@ -308,32 +362,33 @@ export class ManagementClient {
getUsers(params?: GetUsersData): Promise<User[]>;
getUsers(params?: GetUsersData, cb?: (err: Error, users: User[]) => void): void;
getUser(params?: ObjectWithId): Promise<User[]>;
getUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void;
getUser(params: ObjectWithId): Promise<User>;
getUser(params: ObjectWithId, cb?: (err: Error, user: User) => void): void;
createUser(data: UserData): Promise<User>;
createUser(data: UserData, cb: (err: Error, data: User) => void): void;
createUser(data: CreateUserData): Promise<User>;
createUser(data: CreateUserData, cb: (err: Error, data: User) => void): void;
updateUser(params: UpdateUserParameters, data: User): Promise<User>;
updateUser(params: UpdateUserParameters, data: User, cb: (err: Error, data: User) => void): void;
updateUser(params: ObjectWithId, data: UpdateUserData): Promise<User>;
updateUser(params: ObjectWithId, data: UpdateUserData, cb: (err: Error, data: User) => void): void;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata): Promise<User>;
updateUserMetadata(params: UpdateUserParameters, data: UserMetadata, cb: (err: Error, data: User) => void): void;
updateUserMetadata(params: ObjectWithId, data: UserMetadata): Promise<User>;
updateUserMetadata(params: ObjectWithId, data: UserMetadata, cb: (err: Error, data: User) => void): void;
// Should be removed from auth0 also. Doesn't exist in api.
deleteAllUsers(): Promise<User>;
deleteAllUsers(cb: (err: Error, data: any) => void): void;
deleteUser(params?: ObjectWithId): Promise<any>;
deleteUser(params?: ObjectWithId, cb?: (err: Error, users: User[]) => void): void;
deleteUser(params: ObjectWithId): Promise<void>;
deleteUser(params: ObjectWithId, cb?: (err: Error) => void): void;
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata): Promise<User>;
updateAppMetadata(params: UpdateUserParameters, data: AppMetadata, cb: (err: Error, data: User) => void): void;
updateAppMetadata(params: ObjectWithId, data: AppMetadata): Promise<User>;
updateAppMetadata(params: ObjectWithId, data: AppMetadata, cb: (err: Error, data: User) => void): void;
deleteUserMultifactor(params: DeleteMultifactorParams): Promise<any>;
deleteUserMultifactor(params: DeleteMultifactorParams, cb: (err: Error, data: any) => void): void;
deleteUserMultifactor(params: DeleteMultifactorParams): Promise<void>;
deleteUserMultifactor(params: DeleteMultifactorParams, cb: (err: Error) => void): void;
unlinkUsers(params: LinkAccountsParams): Promise<any>;
unlinkUsers(params: LinkAccountsParams, cb: (err: Error, data: any) => void): void;
unlinkUsers(params: UnlinkAccountsParams): Promise<UnlinkAccountsResponse>;
unlinkUsers(params: UnlinkAccountsParams, cb: (err: Error, data: UnlinkAccountsResponse) => void): void;
linkUsers(params: ObjectWithId, data: LinkAccountsData): Promise<any>;
linkUsers(params: ObjectWithId, data: LinkAccountsData, cb: (err: Error, data: any) => void): void;
+17 -18
View File
@@ -1,24 +1,23 @@
import AutoLaunch = require('auto-launch');
var a1 = new AutoLaunch({
name: 'Foo',
const minecraftAutoLauncher = new AutoLaunch({
name: 'Minecraft',
path: '/Applications/Minecraft.app',
mac: {
useLaunchAgent: true
}
});
var a2 = new AutoLaunch({
name: 'Foo',
path: '/Applications/Foo.app',
isHidden: true,
});
minecraftAutoLauncher.enable();
minecraftAutoLauncher.disable();
a1.enable();
a2.disable();
a1.isEnabled(function(enabled: boolean) {
if (enabled) {
return;
minecraftAutoLauncher.isEnabled()
.then((isEnabled) => {
if (isEnabled) {
return;
}
a1.enable(function(err){ console.log(err.message); });
});
minecraftAutoLauncher.enable();
})
.catch((err) => {
console.error(err);
});
+39 -33
View File
@@ -1,41 +1,47 @@
// Type definitions for auto-launch 0.1.18
// Type definitions for auto-launch 5.0
// Project: https://github.com/Teamwork/node-auto-launch
// Definitions by: rhysd <https://github.com/rhysd>
// Definitions by: rhysd <https://github.com/rhysd>, Daniel Perez Alvarez <https://github.com/unindented>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface AutoLaunchOption {
/**
* Application name.
*/
name: string;
/**
* Hidden on launch or not. Default is false.
*/
isHidden?: boolean;
/**
* Path to application directory.
* Default is process.execPath.
*/
path?: string;
interface AutoLaunchOptions {
/**
* Application name.
*/
name: string;
/**
* Path to application. Default is `process.execPath`.
*/
path?: string;
/**
* Hidden on launch. Default is `false`.
*/
isHidden?: boolean;
/**
* For Mac-only options.
*/
mac?: {
/**
* By default, AppleScript is used to add a Login Item. If this is `true`, Launch Agent will be used to auto-launch your app. Defaults is `false`.
*/
useLaunchAgent?: boolean;
};
}
declare class AutoLaunch {
constructor(opts: AutoLaunchOption);
/**
* Enables to launch at start up
*/
enable(callback?: (err: Error) => void): void;
/**
* Disables to launch at start up
*/
disable(callback?: (err: Error) => void): void;
/**
* Returns if auto start up is enabled
*/
isEnabled(callback: (enabled: boolean) => void): void;
constructor(options: AutoLaunchOptions);
/**
* Enables auto-launch at start up.
*/
enable(): Promise<void>;
/**
* Disables auto-launch at start up.
*/
disable(): Promise<void>;
/**
* Returns true if auto-launch is enabled.
*/
isEnabled(): Promise<boolean>;
}
declare module "auto-launch" {
var al: typeof AutoLaunch;
export = al;
}
export = AutoLaunch;
+2 -2
View File
@@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -20,4 +20,4 @@
"index.d.ts",
"auto-launch-tests.ts"
]
}
}
+1
View File
@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }
+1 -1
View File
@@ -7,7 +7,7 @@ import { Plugin, Transformer as PostcssTransformer } from 'postcss';
declare namespace autoprefixer {
interface Options {
browsers?: string[];
browsers?: string[] | string;
env?: string;
cascade?: boolean;
add?: boolean;
+29
View File
@@ -61,6 +61,8 @@ var S3CreateEvent: AWSLambda.S3CreateEvent = {
]
};
var cognitoUserPoolEvent: AWSLambda.CognitoUserPoolEvent;
var cloudformationCustomResourceEvent: AWSLambda.CloudFormationCustomResourceEvent;
var cloudformationCustomResourceResponse: AWSLambda.CloudFormationCustomResourceResponse;
/* API Gateway Event */
str = apiGwEvt.body;
@@ -213,6 +215,33 @@ str = cognitoUserPoolEvent.response.privateChallengeParameters["answer"];
str = cognitoUserPoolEvent.response.challengeMetaData;
b = cognitoUserPoolEvent.response.answerCorrect;
// CloudFormation Custom Resource
switch (cloudformationCustomResourceEvent.RequestType) {
case "Create":
str = cloudformationCustomResourceEvent.LogicalResourceId;
str = cloudformationCustomResourceEvent.RequestId;
anyObj = cloudformationCustomResourceEvent.ResourceProperties;
str = cloudformationCustomResourceEvent.ResourceProperties.ServiceToken;
str = cloudformationCustomResourceEvent.ResourceType;
str = cloudformationCustomResourceEvent.ResponseURL;
str = cloudformationCustomResourceEvent.ServiceToken;
str = cloudformationCustomResourceEvent.StackId;
break;
case "Update":
anyObj = cloudformationCustomResourceEvent.OldResourceProperties;
break;
case "Delete":
str = cloudformationCustomResourceEvent.PhysicalResourceId;
break;
}
anyObj = cloudformationCustomResourceResponse.Data;
str = cloudformationCustomResourceResponse.LogicalResourceId;
str = cloudformationCustomResourceResponse.PhysicalResourceId;
str = cloudformationCustomResourceResponse.Reason;
str = cloudformationCustomResourceResponse.RequestId;
str = cloudformationCustomResourceResponse.StackId;
str = cloudformationCustomResourceResponse.Status;
/* Context */
b = context.callbackWaitsForEmptyEventLoop;
str = context.functionName;
+58
View File
@@ -168,6 +168,64 @@ interface CognitoUserPoolEvent {
};
}
/**
* CloudFormation Custom Resource event and response
* http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/crpg-ref.html
*/
type CloudFormationCustomResourceEventCommon = {
ServiceToken: string;
ResponseURL: string;
StackId: string;
RequestId: string;
LogicalResourceId: string;
ResourceType: string;
ResourceProperties: {
ServiceToken: string;
[Key: string]: any;
}
}
type CloudFormationCustomResourceCreateEvent = CloudFormationCustomResourceEventCommon & {
RequestType: "Create";
}
type CloudFormationCustomResourceUpdateEvent = CloudFormationCustomResourceEventCommon & {
RequestType: "Update";
PhysicalResourceId: string;
OldResourceProperties: {
[Key: string]: any;
};
}
type CloudFormationCustomResourceDeleteEvent = CloudFormationCustomResourceEventCommon & {
RequestType: "Delete";
PhysicalResourceId: string;
}
export type CloudFormationCustomResourceEvent = CloudFormationCustomResourceCreateEvent | CloudFormationCustomResourceUpdateEvent | CloudFormationCustomResourceDeleteEvent;
type CloudFormationCustomResourceResponseCommon = {
PhysicalResourceId: string;
StackId: string;
RequestId: string;
LogicalResourceId: string;
Data?: {
[Key: string]: any;
}
}
type CloudFormationCustomResourceSuccessResponse = CloudFormationCustomResourceResponseCommon & {
Status: "SUCCESS";
Reason?: string;
}
type CloudFormationCustomResourceFailedResponse = CloudFormationCustomResourceResponseCommon & {
Status: "FAILED";
Reason: string;
}
export type CloudFormationCustomResourceResponse = CloudFormationCustomResourceSuccessResponse | CloudFormationCustomResourceFailedResponse;
// Context
// http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
interface Context {
@@ -1,7 +1,3 @@
/// <reference types="babylon" />
// Example from https://github.com/babel/babel/tree/master/packages/babel-generator
import {parse} from 'babylon';
import generate from 'babel-generator';
@@ -14,13 +10,13 @@ ast.loc.start;
const output = generate(ast, { /* options */ }, code);
// Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-generator
let result = generate(ast, {
retainLines: false,
compact: "auto",
concise: false,
quotes: "double",
jsonCompatibleStrings: true,
// ...
}, code);
result.code;
+14 -13
View File
@@ -1,12 +1,10 @@
// Type definitions for babel-generator v6.7
// Type definitions for babel-generator 6.25
// Project: https://github.com/babel/babel/tree/master/packages/babel-generator
// Definitions by: Troy Gerwien <https://github.com/yortus>
// Johnny Estilles <https://github.com/johnnyestilles>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="babel-types" />
import * as t from 'babel-types';
type Node = t.Node;
/**
* Turns an AST into code, maintaining sourcemaps, user preferences, and valid output.
@@ -15,18 +13,17 @@ type Node = t.Node;
* @param code - the original source code, used for source maps.
* @returns - an object containing the output code and source map.
*/
export default function generate(ast: Node, opts?: GeneratorOptions, code?: string | {[filename: string]: string}): GeneratorResult;
export default function generate(ast: t.Node, opts?: GeneratorOptions, code?: string | {[filename: string]: string}): GeneratorResult;
export interface GeneratorOptions {
/**
* Optional string to add as a block comment at the start of the output file.
*/
*/
auxiliaryCommentBefore?: string;
/**
* Optional string to add as a block comment at the end of the output file.
*/
*/
auxiliaryCommentAfter?: string;
/**
@@ -34,7 +31,7 @@ export interface GeneratorOptions {
* By default, comments are included if `opts.comments` is `true` or if `opts.minifed` is `false` and the comment
* contains `@preserve` or `@license`.
*/
shouldPrintComment?: (comment: string) => boolean;
shouldPrintComment?(comment: string): boolean;
/**
* Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces).
@@ -60,7 +57,7 @@ export interface GeneratorOptions {
/**
* Set to true to reduce whitespace (but not as much as opts.compact). Defaults to `false`.
*/
concise?: boolean;
concise?: boolean;
/**
* The type of quote to use in the output. If omitted, autodetects based on `ast.tokens`.
@@ -70,7 +67,7 @@ export interface GeneratorOptions {
/**
* Used in warning messages
*/
filename?: string;
filename?: string;
/**
* Enable generating source maps. Defaults to `false`.
@@ -92,10 +89,14 @@ export interface GeneratorOptions {
* This will only be used if `code` is a string.
*/
sourceFileName?: string;
/**
* Set to true to run jsesc with "json": true to print "\u00A9" vs. "©";
*/
jsonCompatibleStrings?: boolean;
}
export interface GeneratorResult {
map: Object;
map: {};
code: string;
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+8 -8
View File
@@ -1265,17 +1265,17 @@ declare namespace Marionette {
*/
start(options?: any): void;
/** Deprecated! nstead of using the Application as the root of your view tree, you should use a Layout View.*/
addRegions(regions: any): any;
/** Root region of the application*/
region: string;
/** Deprecated! nstead of using the Application as the root of your view tree, you should use a Layout View.*/
emptyRegions(): void;
/** Get the root region */
getRegion(): Region;
/** Deprecated! nstead of using the Application as the root of your view tree, you should use a Layout View.*/
removeRegion(region: Region): void;
/** Show a view in the root region */
showView(view: Backbone.View<Backbone.Model>): void;
/** Deprecated! nstead of using the Application as the root of your view tree, you should use a Layout View.*/
getRegion(regionName: string): Region;
/** Get the view from the root region*/
getView(): any;
module(moduleNames: any, moduleDefinition: any): Module;
+54
View File
@@ -0,0 +1,54 @@
import * as block from "bem-cn";
import { Settings } from "bem-cn";
// expected 'block'
block("block")();
// expected 'block__elem'
block("block")("elem")();
// expected 'block__elem block__elem_disabled block__elem_size_small'
block("block")("elem", { disabled: true, size: 'small' })();
// expected 'block block_disabled'
block("block")({ disabled: true})();
// expected 'block mix'
block("block").mix("mix");
// expected 'block mix mix2'
block("block").mix(["mix", "mix2"]);
// expected 'block is-hidden'
block("block").state({ hidden: true });
// expected 'block'
block("block").state({ hidden: false });
// expected 'block is-hidden is-error'
block("block").state({ hidden: true, error: true });
// expected 'block is-loading'
block("block").is({ loading: true });
// expected 'block has-content'
block("block").has({ content: true });
block.setup({
el: '~~',
mod: '--',
modValue: '-'
});
// expected 'block~~elem'
block("block")("elem");
// expected 'block block--mod-value'
block("block")({ mod: "value"});
// I can use bem-cn interfaces
const customSettings: Settings = {
ns: 'prefix'
};
block.setup(customSettings);
+41
View File
@@ -0,0 +1,41 @@
// Type definitions for bem-cn 2.1
// Project: https://github.com/albburtsev/bem-cn
// Definitions by: Vitaly Selkin <https://github.com/selkinvitaly>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
type StateFn = (states: { [key: string]: boolean }) => BemCn.Inner;
declare function BemCn(name: string): BemCn.Inner;
declare namespace BemCn {
function reset(): void;
function setup(settings?: Settings): void;
interface Modifications {
[key: string]: (string | boolean);
}
interface Inner {
(elem: string | Modifications): Inner;
(elem: string, mods: Modifications): Inner;
(): string;
mix(mixes: string | string[]): Inner;
has: StateFn;
state: StateFn;
is: StateFn;
toString(): string;
valueOf(): string;
split(separator: string, limit?: number): string[];
}
interface Settings {
ns?: string;
el?: string;
mod?: string;
modValue?: string;
classMap?: { [className: string]: string } | null;
}
}
export as namespace BemCn;
export = BemCn;
+22
View File
@@ -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",
"bem-cn-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"extends": "dtslint/dt.json"
}
+119
View File
@@ -0,0 +1,119 @@
// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4)
// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions
// Definitions by: Ricky Brundritt <https://github.com/rbrundritt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="Microsoft.Maps.d.ts"/>
declare module Microsoft.Maps {
/** Options used to customize the autosuggest functionality. */
export interface IAutosuggestOptions {
/** Specifies if street address suggestions should be returned. Default: true */
addressSuggestions?: boolean;
/**
* Specifies if the user’s location should be auto detected using their IP address, if no location information is provided
* in the userLocation property. Default: true
*/
autoDetectLocation?: boolean;
/**
* A bounding box that is used to help influence the results such that locations that are in or near this bounding box
* are given more weight than they would normally.
*/
bounds?: LocationRect;
/**
* A reference to a map instance. If the useMapView property is set to true, the bounding box of the map view will be used
* to influence the weight of suggestions.
*/
map?: Map;
/** The maximum number of results to return. Can be any value between 1 and 10. Default: 5 */
maxResults?: number;
/** Specifies if place suggestions (city, landmark, etc.) should be returned. Default: true */
placeSuggestions?: boolean;
/**
* Indicates if the maps bounding box should be used to influence the suggested results. Ignored if the bounds property is
* set. Default: true
*/
useMapView?: boolean;
/** A coordinate indicating where the user is located. This will influence the results to be more relevant to the user. */
userLocation?: Location;
}
/** Represents the suggestion result from the Autosuggest manager. */
export interface ISuggestionResult {
/** A structured address object for the result. */
address: IAddress;
/** A LocationRect that can be used to set the map view over the result. */
bestView: LocationRect;
/** Unique entity id to be used for searching the entity. */
entityId: string;
/** The type of the result; Address, Place */
entityType: string;
/** The sub type of result; Address, RoadBlock, PopulatedPlace, CountryRegion, etc. */
entitySubType: string;
/** A nicely formatted suggestion string for the result based on market. */
formattedSuggestion: string;
/**
* The coordinate of the result. This value is only returned for place (city, landmarks) results and not for addresses.
* Street addresses will need to be geocoded to get their location.
*/
location: Location;
/** A secondary title that provides additional context to the title value of the suggestion. **/
subtitle: string;
/** The display title for the result (i.e. “Redmond”). */
title: string;
}
/**
* The AutosuggestManager is the primary class in the Autosuggest module that powers the autosuggest functionality.
* @requires The Microsoft.Maps.Autosuggest module.
*/
export class AutosuggestManager {
/**
* @constructor
* @requires The Microsoft.Maps.Autosuggest module.
* @param options The options to use with the autosuggest manager.
*/
constructor(options?: IAutosuggestOptions);
/**
* Attaches the Autosuggest functionality to an input box.
* @param suggestionBoxId The HTML element identifier of the input box.
* @param suggestionContainerId The Id of container where suggestions will be displayed.
* @param selectedSuggestionCallback A reference to a callback function that will be called when a user selects a suggestion from the Autosuggest UI.
*/
public attachAutosuggest(suggestionBoxId: string, suggestionContainerId: string, selectedSuggestionCallback: (result: ISuggestionResult) => void) : void;
/** Detaches the autosuggest functionality from the input box, freeing any resources it has or events it has tied to. */
public detachAutosuggest(): void;
/** Disposes the Autosuggest object, freeing any resources it has or events it has tied to. */
public dispose(): void;
/**
* Gets the options currently used by the autosuggest manager.
* @returns The options currently used by the autosuggest manager.
*/
public getOptions(): IAutosuggestOptions;
/**
* Sets the options currently used by the autosuggest manager.
* @param options The options to use with the autosuggest manager.
*/
public setOptions(options?: IAutosuggestOptions): void;
}
}
+149
View File
@@ -0,0 +1,149 @@
// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4)
// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions
// Definitions by: Ricky Brundritt <https://github.com/rbrundritt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="Microsoft.Maps.d.ts"/>
declare module Microsoft.Maps {
/** The options used to customize how the ClusterLayer functions. */
export interface IClusterLayerOptions {
/**
* A callback function that is fired after the clustering for a map view has completed. This is useful if you want to generate a list of locations based on what is in the current view.
*/
callback?: () => void;
/**
* A callback function that allows you to process a clustered pushpin before it is added to a layer. This is useful if you want to add events or set style options on the clustered pushpin.
*/
clusteredPinCallback?: (pin: ClusterPushpin) => void;
/**
* Indicates if the layer should cluster the locations or not. Default: true
*/
clusteringEnabled?: boolean;
/**
* Defines how clusters are positioned on the map. Default: MeanAverage
*/
clusterPlacementType?: ClusterPlacementType;
/**
* The width and height of the gird cells used for clustering in pixels. Default: 45
*/
gridSize?: number;
/**
* Offsets the placement of clustered pushpins by a set number of pixels. This option is only available when the placement type is set to GridCenter.
* This is useful if you have multiple cluster layers on the map and you want to offset the clustered pushpins between the layers so that they are visible,
* otherwise the clusters from the different layers would overlap completely.
*/
layerOffset?: Point;
/**
* A boolean indicating if the layer is visible or not.
*/
visible?: boolean;
/**
* The z-index of the layer.
*/
zIndex?: number;
}
/**
* Used to specify how a clustered pushpin should be positioned relative to the pushpins it contains.
* @requires The Microsoft.Maps.Clustering module.
*/
export enum ClusterPlacementType {
/**
* Mean Average placement calculates the average position of a group of coordinates. This method creates a more realistic representation of the data,
* however requires more processing power and increases the chances of pushpins overlapping.
*/
MeanAverage,
/**
* This method is the simplest way to represent a cluster. It places the cluster at the first location in the cluster. This method may not accurately
* represent the data but requires little processing power.
*/
FirstLocation
}
/**
* This class extends the Pushpin class and has all the same methods and properties plus the following properties.
* @requires The Microsoft.Maps.Clustering module.
*/
export class ClusterPushpin extends Pushpin {
/** An array of all the pushpins that are in the cluster. */
containedPushpins: Pushpin[];
/**
* The grid cell key that can be used retrieve the clustered pushpin(s) from the clustering layer. This is useful when creating a clickable list that
* link items in the list to clusters or pushpins on the map. Your list just needs to store the gridKey value.
*/
gridKey: number;
}
/**
* This class allows you to easily add in client side clustering to your application. Client Side Clustering is a method where pushpins that are close
* together are grouped and represented as a single pushpin, often using a different icon to indicate the cluster. This is a great way to improve both
* the user experience and performance of the map.
* @requires The Microsoft.Maps.Clustering module.
*/
export class ClusterLayer implements IDataLayer {
/**
* @constructor
* @requires The Microsoft.Maps.Clustering module.
* @param pushpins An array of pushpins to cluster in the layer.
* @param options The options used to customize how the ClusterLayer functions.
*/
constructor(pushpins: Pushpin[], options?: IClusterLayerOptions);
/** Clears all the data in the cluster layer. */
public clear(): void;
/**
* Gets all the pushpins that are in the current map view. If clustering is disabled, all pushpins in the clustering layer are returned.
* @returns All the pushpins that are in the current map view. If clustering is disabled, all pushpins in the clustering layer are returned.
*/
public getDisplayedPushpins(): Pushpin[];
/**
* Gets the current options used by the cluster layer.
* @returns The current options used by the cluster layer.
*/
public getOptions(): IClusterLayerOptions;
/**
* Gets all pushpins that are in the layers.
* @returns An array of all the pushpins that are in the layers.
*/
public getPushpins(): Pushpin[];
/**
* Gets the original pushpins that are in the specified grid cell.
* @param The gridKey index to retrieve the pushpins for.
* @returns The original pushpins that are in the specified grid cell.
*/
public getPushpinsByGridKey(gridKey: number): Pushpin[];
/**
* Gets the pushpin in the specified cluster grid cell which can be either a ClusterPushpin if there are multiple pushpins in a cell or a single Pushpin.
* @param The gridKey index to retrieve the pushpins for.
* @returns The pushpin in the specified cluster grid cell which can be either a ClusterPushpin if there are multiple pushpins in a cell or a single Pushpin.
*/
public getClusterPushpinByGridKey(gridKey: number): ClusterPushpin | Pushpin;
/**
* Sets the clustering options to use in the layer.
* @params options The clustering options to use in the layer.
*/
public setOptions(options: IClusterLayerOptions): void;
/**
* Sets the array of pushpins that are used in the clustering layer.
* @param pushpins An array of pushpins that are to be used by the clustering layer.
*/
public setPushpins(pushpins: Pushpin[]): void;
}
}
+94
View File
@@ -0,0 +1,94 @@
// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4)
// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions
// Definitions by: Ricky Brundritt <https://github.com/rbrundritt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="Microsoft.Maps.d.ts"/>
declare module Microsoft.Maps {
/**
* The contour layer options
*/
interface IContourLayerOptions {
/** The z-index of this layer */
zIndex?: number;
/** Whether the layer is visible */
visible?: boolean;
/** A callback function which defines the color of the contour line fill. */
colorCallback?: (contourValue: number | string) => string | Color;
/** The polygon options that apply to all contour lines of this layer */
polygonOptions?: IPolygonOptions;
}
/**
* The contour line of a contour layer
*/
export class ContourLine extends Polygon {
/** The contour lines that are directly nested inside this contour line */
public innerContourLines: ContourLine[];
/** The outer/parent contour line of this contour */
public outerContourLine: ContourLine;
/** The data value associated with this contour line */
public contourValue: number | string;
/**
* @constructor
* @param boundary The boundary of this contour line
* @param contourValue The value associated with this contour line
*/
constructor(boundary: Location[], contourValue?: number | string);
}
/**
* The contour layer class.
*/
export class ContourLayer extends Layer {
/**
* @constructor
* @param contourLines The contour lines that compose this layer.
* @param options The contour layer options.
*/
constructor(contourLines: ContourLine[], options?: IContourLayerOptions);
/**
* Clears all data on the contour layer.
*/
public clear(): void;
/**
* Gets the contour lines of this layer.
* @returns The contour lines of this layer.
*/
public getContourLines(): ContourLine[];
/**
* Gets the polygons that were generated from the contour lines in this layer.
* @returns The polygons that were generated from the contour lines in this layer.
*/
public getContourPolygons(): Polygon[];
/**
* Retrieves the options of this contour layer.
* @returns The options of this contour layer.
*/
public getOptions(): IContourLayerOptions;
/**
* Sets the contour lines used to calculate the polygon areas of this layer.
* @param contourLines The contour lines used to calculate the polygon areas of this layer.
*/
public setContourLines(contourLines: ContourLine[]): void;
/**
* Sets the options of the contour layer.
* @param options The new options to update the layer.
*/
public setOptions(options: IContourLayerOptions): void;
}
}
+154
View File
@@ -0,0 +1,154 @@
// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4)
// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions
// Definitions by: Ricky Brundritt <https://github.com/rbrundritt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="Microsoft.Maps.d.ts"/>
/// <reference path="SpatialMath.d.ts"/>
declare module Microsoft.Maps {
/**
* Specifies the shape of data bin rendered in the layer.
*/
export enum DataBinType {
/* Renders data bins as circles in a square grid. */
circle,
/* Renders data bins as hexagons with a flat top edge. */
hexagon,
/* Renders data bins as circles in a hexagonal grid. */
hexCircle,
/* Renders data bins as hexagons with a pointy top corner. */
pointyHexagon,
/* Renders data bins as a square grid. */
square
}
/**
* A set options the define how a data binning layer is rendered.
*/
export interface IDataBinningOptions {
/* The name of a property in the Pushpin.metadata object on which to perform calculations (average, count, sum) against the pushpins in each data bin. */
aggregationProperty?: string;
/*
* A callback function which defines the color a data bin polygon should be. This callback recieves data bin information
* along with the min and max calculated metrics for the data set. If set, this callback function must return a color value.
*/
colorCallback?: (binInfo: IDataBinInfo, min: IDataBinMetrics, max: IDataBinMetrics) => string | Color;
/* The shape of the data bin to generate. Default: hexagon */
dataBinType?: DataBinType;
/* The distance units of the radius option. Default: meters */
distanceUnits?: SpatialMath.DistanceUnits;
/* The default options used for rendering the data bin polygons. */
polygonOptions?: IPolygonOptions;
/*
* A spatial distance which will be converted into a pixel distance at the equater and used to generate symetrically sized data bins
* that have the apprimate spatial distance radius. Default: 1000
*/
radius?: number;
/*
* A callback function which defines how much to scale a data bins size. This callback recieves data bin information
* along with the min and max calculated metrics for the data set. If set, this callback function must return a number between 0 and 1.
*/
scaleCallback?: (binInfo: IDataBinInfo, min: IDataBinMetrics, max: IDataBinMetrics) => number;
}
/**
* A set of values calculated from the pushpins in a data bin.
*/
export interface IDataBinMetrics {
/* The average value of the aggregation property of the pushpins in a data bin. */
average?: number;
/* The number of pushpins in a data bin. */
count?: number;
/* The number of pushpins in the data bin who's aggregation property has a value. */
countNotBlank?: number;
/* The number of pushpins in the data bin who's aggregation property is a valid number. */
countNumbers?: number;
/* The sum of the aggregation property of the pushpins in a data bin. */
sum?: number;
}
/**
* The result of a calculated data bin.
*/
export interface IDataBinInfo {
/* An array of all the pushpins that are in the data bin. */
containedPushpins: Microsoft.Maps.Pushpin[];
/* A set of calculated metric values determined using the aggregationProperty value of all the pushpins contained in the data bin. */
metrics: IDataBinMetrics;
}
/**
* A polygon which represents a data bin on the map and contains the data bin information.
*/
export class DataBinPolygon extends Polygon {
/* Information about the data bin; the contained pushpins and calculated metrics. */
public dataBinInfo: IDataBinInfo;
}
/**
* This class provides a data binning visualization for the map. It takes in an array of pushpins, groups them into
* symmetrical shapes that fit together in a grid such as hexagons. Aggregation of data values are done and can be
* used to customize how the data bins are rendered on the map (i.e. scale / color) .
*/
export class DataBinningLayer extends Layer {
/**
* Initializes the data binning layer.
* @param pushpins The array of pushpins that are used to generate the data bins.
* @param options The options used for calculating and rendering the data bins.
*/
constructor(pushpins?: Pushpin[], options?: IDataBinningOptions);
/**
* Gets the options used for calculating and rendering the data bins.
* @returns The options used for calculating and rendering the data bins.
*/
public getOptions(): IDataBinningOptions;
/**
* Gets all pushpins that are in the layers.
* @returns All pushpins that are in the layers.
*/
public getPushpins(): Pushpin[];
/**
* Sets the array of pushpins that are used to generate the data bins.
* @param pushpins The array of pushpins that are used to generate the data bins.
*/
public setPushpins(pushpins: Pushpin[]): void;
/**
* Clears all the data in the data binning layer.
*/
public clear(): void;
/**
* Cleans up any resources this object is consuming.
*/
public dispose(): void;
/**
* Sets the options used for calculating and rendering the data bins.
* @param options The options used for calculating and rendering the data bins.
*/
public setOptions(options: IDataBinningOptions): void;
}
}
+618
View File
@@ -0,0 +1,618 @@
// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4)
// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions
// Definitions by: Ricky Brundritt <https://github.com/rbrundritt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="Microsoft.Maps.d.ts"/>
declare module Microsoft.Maps.Directions {
/////////////////////////////////////
/// Enumerations
////////////////////////////////////
/** Distance units for calculating the directions in. */
export enum DistanceUnit {
/** A distance in Kilometers. */
km,
/** A distance in Miles. */
miles
}
/** Defines the type of route to calculate. */
export enum RouteMode {
/** Driving directions are calculated. */
driving,
/** Transit directions are calculated. */
transit,
/** Walking directions are calculated. */
walking
}
/** Defines features to avoid when calculating the route. */
export enum RouteAvoidance {
/** Calculate the best route using any travel option available. */
none = 0,
/** Reduce the use of limited access highways when calculating the route. */
minimizeHighways = 1,
/** Reduce the use of roads with tolls when calculating the route. */
minimizeToll = 2,
/** Avoid using limited access highways when calculating the route. */
avoidHighways = 4,
/** Avoid using roads with tolls when calculating the route. */
avoidToll = 8,
/** Avoid using express trains when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */
avoidExpressTrain = 16,
/** Avoid using airlines when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */
avoidAirline = 32,
/** Avoid using bullet trains when calculating the route. This option only affects routes with a transitRouteMode that have the culture set to ja-jp. */
avoidBulletTrain = 64
}
/** Response codes for a route calculation request. */
export enum RouteResponseCode {
/** The route was successfully calculated. */
success = 0,
/** An unknown error has occurred. */
unknownError = 1,
/** A nearby road cannot be found for one or more of the route waypoints. */
cannotFindNearbyRoad = 2,
/**
* The distance between two route waypoints, or the total length of the route exceeds the limit of the route mode.
* Modify the waypoint locations so that they are closer together.
*/
tooFar = 3,
/**
* A route cannot be calculated for the specified waypoints. For example, this code is returned when a route between
* “Seattle, WA” and “Honolulu, HI” is requested.
*/
noSolution = 4,
/** There is no route data for the specified waypoints. */
dataSourceNotFound = 5,
/** There are no transit options available for the specified time. */
noAvailableTransitTrip = 7,
/** The transit stops are so close that walking is always a better option. */
transitStopsTooClose = 8,
/** The transit stops are so close that walking is a better option. */
walkingBestAlternative = 9,
/**
* There is no transit data available for the route or for one or more of the specified waypoints,
* or the waypoints are in different transit areas that do not overlap.
*/
outOfTransitBounds = 10,
/** The directions calculation request has timed out. */
timeOut = 11,
/**
* One or more waypoints need to be disambiguated. This error does not occur if the
* autoDisplayDisambiguation directions render option is set to true.
*/
waypointDisambiguation = 12,
/** One or more waypoints do not have an address or location specified. */
hasEmptyWaypoint = 13,
/** The maximum number of waypoints, which is 25, has been exceeded. */
exceedMaxWaypointLimit = 14,
/** At least two waypoints are required to calculate a route. */
atleastTwoWaypointRequired = 15,
/** The first or last waypoint is a via point, which is not allowed. */
firstOrLastStoppointIsVia = 16,
/** The search service failed to return results. */
searchServiceFailed = 17,
/** The credentials passed to the Directions module are invalid. */
invalidCredentials = 18
}
/** Defines optimization options for calculating directions. */
export enum RouteOptimization {
/** Calculate a route the shortest time. */
shortestTime = 0,
/** Calculate a route with the shortest distance. */
shortestDistance = 1,
/** The route is calculated to minimize the time and uses current traffic information. */
timeWithTraffic = 2,
/** The route is calculated to minimize the time and avoid road closures. Traffic information is not used in the calculation. */
timeAvoidClosure = 3,
/** Minimize the cost when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/
minimizeMoney = 4,
/** Minimize transit transfers when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/
minimizeTransfers = 5,
/** Minimize the amount of walking when calculating directions. This option only affects routes with a transitRouteMode that have the culture set to ja-jp.*/
minimizeWalking = 6
}
/** An enumeration that specifies the releance of a dateTime when calculating a route. */
export enum TimeType {
/** The dateTime parameter contains the desired arrival time for a transit request. */
arrival,
/** The dateTime parameter contains the desired departure time for a transit request. */
departure,
/** The dateTime parameter should be ignored and the first available transit taken. */
firstAvailable,
/** The dateTime parameter contains the latest departure time available for a transit request. */
lastAvailable
}
/////////////////////////////////////
/// Interfaces
////////////////////////////////////
/** Contains the arguments for directions events. */
export interface IDirectionsEventArgs {
/** The calculated route (or routes, if the route mode is transit). */
route: IRoute[];
/** The route summary (or summaries) of the route(s) defined in the route property. */
routeSummary: IRouteSummary[];
}
/** Contains arguments for directions error events. */
export interface IDirectionsErrorEventArgs {
/** The code which identifies the error that occurred. */
responseCode: RouteResponseCode;
/** The error message. */
message: string;
}
/** Represents one direction in a set of route directions. */
export interface IDirectionsStep {
/** The child direction items for this directions step. */
childItineraryItems: IDirectionsStep[];
/** The location of the start of the direction. */
coordinate: Location;
/** The total distance of the step in the unit specified in the distanceUnit property of the DirectionsRequestOptions. */
distance: string;
/** The total time, in seconds, of the direction step. */
durationInSeconds: number;
/** The HTML formatted route instruction associated with the step. */
formattedText: string;
/** A boolean indicating whether the maneuver image is a road shield image. */
isImageRoadShield: boolean;
/** The name of the maneuver image. */
maneuverImageName: string;
/** An array of strings, where each string is a hint to help determine when to move to the next direction step. Not all direction steps have hints. */
postIntersectionHints: string[];
/** An array of strings, where each string is a hint to help determine when you have arrived at this direction step. Not all direction steps have hints. */
preIntersectionHints: string[];
/** The name of the transit stop where this step originates. */
startStopName: string;
/** The transit line associated with this step. */
transitLine: ITransitLine;
/** The URL of the image to use for transit direction steps. */
transitStepIcon: string;
/** The ID of the transit stop. */
transitStopId: string;
/** The name of the transit line end. */
transitTerminus: string;
}
/** Represents a route. */
export interface IRoute {
/** The legs of the route. Each route leg represents the route between two waypoints. */
routeLegs: IRouteLeg[];
/** An array of locations that makes up the path of the route. */
routePath: Location[];
}
/** Represents a leg of a route. A route leg is the part of the route between two stop waypoints. */
export interface IRouteLeg {
/** The end time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit. */
endTime: Date;
/** The location of the last waypoint of this leg. */
endWaypointLocation: Location;
/** The directions steps associated with this route leg. */
itineraryItems: IDirectionsStep[];
/** The index of the route to which this route leg belongs. */
originalRouteIndex: number;
/** The start time of the route leg. This property only applies when the routeMode of the DirectionsRequestOptions is set to transit. */
startTime: Date;
/** The location of the first waypoint of this route leg. */
startWaypointLocation: Location;
/** The sub legs of this route leg. A sub leg of a route is the part of the route between a stop point and a via point or between two via points.*/
subLegs: IRouteSubLeg[];
/** The summary which describes this route leg. */
summary: IRouteSummary;
}
/** Represents a route sub leg. A route sub leg is the part of the route between a stop point and a via point or between two via points. */
export interface IRouteSubLeg {
/** The location of the last waypoint of the sub leg. */
actualEnd: Location;
/** The location of the first waypoint of the sub leg. */
actualStart: Location;
/** The description of the last waypoint of the sub leg. */
endDescription: string;
/** The description of the first waypoint of the sub leg. */
startDescription: string;
}
/** Represents a route summary. */
export interface IRouteSummary {
/** The total travel distance of the route */
distance: number;
/** The cost of the route. This property is only returned if the routeMode of the IDirectionsRequestOptions is set to transit and the map culture is set to ja-jp. */
monetaryCost: number;
/** The location of the northeast corner of bounding box that defines the best map view of the route. */
northEast: Location;
/** The location of the southwest corner of bounding box that defines the best map view of the route. */
southWest: Location;
/** The total travel time, in seconds, for the route. */
time: number;
/**
* The total travel time, in seconds, taking into account traffic delays, for the route.
* This property is 0 if the avoidTraffic property of the IDirectionsRequestOptions is set to false.
*/
timeWithTraffic: number;
}
/** Contains information about a transit line. */
export interface ITransitLine {
/** The short name for the transit line. */
abbreviatedName: string;
/** The ID of the agency that owns the transit line. */
agencyId: number;
/** The name of the agency that owns the transit line. */
agencyName: string;
/** The URL of the website of the agency that owns the transit line. */
agencyUrl: string;
/** Phone number for the transit agency. */
phoneNumber: string;
/** Information about the provider of this transit line data. */
providerInfo: string;
/** The uri for the transit agencies website. */
uri: string;
/** The full name of this transit line. */
verboseName: string;
}
/** Options that can be used to define a waypoint. */
export interface IWaypointOptions {
/**
* The address string of the waypoint. For example, the following strings are valid for this parameter: "Seattle", "1 Microsoft Way, Redmond, WA". Either the address or location property must be specified.
*/
address?: string;
/**
* A boolean indicating whether the waypoint is a via point. A via point is a point along the route that is not a stop point. Set this property to
* true if you just want the route to pass through this location. Default: false
*/
isViaPoint?: boolean;
/** The location of the waypoint. Either the address or location property must be specified. */
location?: Location;
}
/** Contains options for the directions to calculate. */
export interface IDirectionsRequestOptions {
/** The unit to use when displaying direction distances. */
distanceUnit?: DistanceUnit;
/** The number of routes to calculate. */
maxRoutes?: number;
/** The features to avoid when calculating the route. */
routeAvoidance?: RouteAvoidance[];
/** A boolean indicating whether the route line on the map can be dragged with the mouse cursor. */
routeDraggable?: boolean;
/** If multiple routes are returned, the index of the route and directions to display. */
routeIndex?: number;
/** The type of directions to calculate. */
routeMode?: RouteMode;
/** The optimization setting for the route calculation. */
routeOptimization?: RouteOptimization;
/** The type of the time specified. The default value is departure. */
timeType?: TimeType;
/** The time to use when calculating the route. If this property is set to null, the current time is used */
time?: Date;
}
/** Represents render options for a route. */
export interface IDirectionsRenderOptions {
/** A boolean indicating whether to automatically set the map view to the best map view of the calculated route. Default: true */
autoUpdateMapView?: boolean;
/** A boolean indicating whether to display the disclaimer about the accuracy of the directions. Default: true */
displayDisclaimer?: boolean;
/** A boolean indicating whether to display the icons for each direction maneuver. Default: true */
displayManeuverIcons?: boolean;
/** A boolean indicating whether to display direction hints that describe when a direction step was missed. Default: true */
displayPostItineraryItemHints?: boolean;
/**
* A boolean indicating whether to display direction hints that describe what to look for before you come to the next
* direction step. The default value is true.
*/
displayPreItineraryItemHints?: boolean;
/** A boolean indicating whether to display the route selector control. Default: true */
displayRouteSelector?: boolean;
/** A boolean indicating whether to display direction warnings. Default: true */
displayStepWarnings?: boolean;
/** A boolean indicating whether to display a warning about walking directions. Default: true */
displayWalkingWarning?: boolean;
/** The polyline options that define how to draw the route line on the map, if the RouteMode is driving. */
drivingPolylineOptions?: IPolylineOptions;
/** The pushpin options that define how the first waypoint should be rendered. */
firstWaypointPushpinOptions?: IPushpinOptions;
/** The DOM element inside which the directions itinerary will be rendered. */
itineraryContainer?: HTMLElement;
/** The pushpin options that define how the last waypoint should be rendered. */
lastWaypointPushpinOptions?: IPushpinOptions;
/** A boolean indicating whether to show the input panel. Default: false */
showInputPanel?: boolean;
/** The options that define how to draw the route line on the map, if the RouteMode is transit. */
transitPolylineOptions?: IPolylineOptions;
/** The options that define how to draw the route line on the map, if the RouteMode is walking. */
walkingPolylineOptions?: IPolylineOptions;
/** The options that define the pushpin to use for all route waypoints by default. The first and last waypoints in the route will be overriden by firstWaypointPushpinOptions and lastWaypointPushpinOptions if set. */
waypointPushpinOptions?: IPushpinOptions;
}
/////////////////////////////////////
/// Classes
////////////////////////////////////
/** An object used to define a start, end or stop location along a route. */
export class Waypoint {
/**
* @constructor
* @param options: Options used to define the Waypoint.
*/
constructor(options: IWaypointOptions);
/** Releases any resources associated with the waypoint. */
public dispose(): void;
/**
* Gets the address associated with the waypoint.
* @returns The address associated with the waypoint.
*/
public getAddress(): string;
/**
* Gets the location of the waypoint.
* @returns The location of the waypoint.
*/
public getLocation(): Location;
/**
* Gets a boolean value indicating whether the waypoint is a via point.
* @returns A boolean value indicating whether the waypoint is a via point.
*/
public isViapoint(): boolean;
/**
* Sets options for the waypoint. For these options to take effect, you must recalculate the route.
* @param options Options used to define the Waypoint.
*/
public setOptions(options: IWaypointOptions): void;
}
/** The main class in the Directions module that process direction calculations and rendering. */
export class DirectionsManager {
/**
* @constructor
* @param map A map to calculate directions for.
* @param waypoints An array of waypoints to be added to the route.
*/
constructor(map: Map, waypoints?: Waypoint[]);
/**
* Adds a waypoint to the route at the given index, if specified. If an index is not specified, the waypoint is added as the last waypoint in the route. The maximum number of walking or driving waypoints is 25. The maximum number of transit waypoints is 2. Up to 10 via points are allowed between two stop waypoints. To recalculate the route, use calculateDirections.
* @param waypoint The waypoint to be added to the directions manager.
* @param index An index at which the waypoint is to be added.
*/
public addWaypoint(waypoint: Waypoint, index?: number): void;
/**
* Calculates directions based on request and render options set
*/
public calculateDirections(): void;
/** Clears the directions request and render options and removes all waypoints */
public clearAll(): void;
/**
* Clears the directions displayed and removes the route line from the map.
* This method does not remove waypoints from the route and retains all calculated direction information and option settings.
*/
public clearDisplay(): void;
/** Deletes the DirectionsManager object and releases any associated resources. */
public dispose(): void;
/**
* Gets all the waypoints in the directions manager.
* @returns All the waypoints in the directions manager.
*/
public getAllWaypoints(): Waypoint[];
/**
* Gets the currently displayed route information.
* @returns The currently displayed route information.
*/
public getCurrentRoute(): IRoute;
/**
* Gets the route render options.
* @returns The route render options
*/
public getRenderOptions(): IDirectionsRenderOptions;
/**
* Gets the directions request options.
* @returns The directions request options.
*/
public getRequestOptions(): IDirectionsRequestOptions;
/**
* Gets the current calculated route(s)
* @returns The current calculated route(s). If the route was not successfully calculated, null is returned.
*/
public getRouteResult(): IRoute[];
/**
* Removes the given waypoint or the waypoint identified by the given index from the route.
* @param waypointOrIndex A Waypoint object to be removed or the index of the waypoint to be removed
*/
public removeWaypoint(waypointOrIndex: Waypoint | number): void;
/**
* Sets the specified render options for the route.
* @param options The options that customize the rendering of the calculated route.
*/
public setRenderOptions(options: IDirectionsRenderOptions): void;
/**
* Sets the specified route calculation options.
* @param options The route calculation options.
*/
public setRequestOptions(options: IDirectionsRequestOptions): void;
/**
* Displays an input panel for calculating directions in the specified container. Provides autosuggest for location inputs.
* @param inputContainerId The id name of the HTML container in which to render the directions input panel.
*/
public showInputPanel(inputContainerId: string): void;
}
}
declare module Microsoft.Maps {
/** A static class that manages events within the map SDK. */
module Events {
/////////////////////////////////////
/// addHandler Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* • directionsError
* • directionsUpdated
* @param handler The callback function to handle the event when triggered.
* @returns The handler id.
*/
export function addHandler(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void): IHandlerId;
/////////////////////////////////////
/// addOne Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* • directionsError
* • directionsUpdated
* @param handler The callback function to handle the event when triggered.
*/
export function addOne(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void): void;
/////////////////////////////////////
/// addThrottledHandler Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* • directionsError
* • directionsUpdated
* @param handler The callback function to handle the event when triggered.
* @param throttleInterval throttle interval (in ms)
* @returns The handler id.
*/
export function addThrottledHandler(target: Directions.DirectionsManager, eventName: string, handler: (eventArg?: Directions.IDirectionsEventArgs | Directions.IDirectionsErrorEventArgs) => void, throttleInterval: number): IHandlerId;
}
}
+241
View File
@@ -0,0 +1,241 @@
// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4)
// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions
// Definitions by: Ricky Brundritt <https://github.com/rbrundritt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="Microsoft.Maps.d.ts"/>
declare module Microsoft.Maps {
/** An object that contains the event arguments for when the drawing mode changes in the drawing tools. **/
export interface IDrawingModeChangedData {
/** The shape being modified by the drawing tools. **/
shape: IPrimitive;
/** The new drawing mode. **/
mode: DrawingTools.DrawingMode;
}
/**
* The DrawingManager class manages the ability to draw and edit multiple shapes on the map. Shapes managed by this class are rendered on a separate drawing layer.
* User can use a mouse or a touch screen to draw on the map. When they are done, pressing the escape button or any button on the toolbar will exit the current drawing mode.
* This class does not have a publicly accessible constructor and can only be accessed using the showDrawingManager of the DrawingTools class.
*/
export interface DrawingManager {
/**
* Adds a shapes to the layer, at the specified index if specified.
• @param data The shape(s) to be added to the layer.
• @param index The index at which to insert the shape into the layer.
*/
add(data: IPrimitive | IPrimitive[], index?: number): void;
/**
* Disposes the drawing manager instance.
*/
dispose(): void;
/**
* Resets the drawing manager and clears all shapes in the drawing layer.
*/
clear(): void;
/**
* Gets the current drawing mode of the drawing manager.
* @returns The current drawing mode of the drawing manager.
*/
getDrawingMode(): DrawingTools.DrawingMode;
/**
* Gets an array of shapes that are in the layer. This can be used to iterate over the individual shapes.
* @returns An array of shapes that are in the layer. This can be used to iterate over the individual shapes.
*/
getPrimitives(): IPrimitive[];
/**
* Returns the index of the shape in the drawing layer.
* @param primitive The shape to find the index of.
* @param fromIndex The index to start the search from.
* @returns The index of the shape in the drawing layer. Returns -1 if shape is not found.
*/
indexOf(primitive: IPrimitive, fromIndex?: number): number;
/**
* Removes a shape from the layer and returns it.
* @param primitive The shape to remove from the layer.
* @returns The shape that was removed from the layer.
*/
remove(primitive: IPrimitive): IPrimitive;
/**
* Removes a shape from the layer at the specified index.
* @param index The index of the shape to remove from the layer.
* @returns The shape that was removed from the layer.
*/
removeAt(index: number): IPrimitive;
/**
* Sets the drawing mode of the drawing manager.
* @param mode The drawing mode to set the DrawingManager to.
*/
setDrawingMode(mode: DrawingTools.DrawingMode): void;
/**
* Replaces all shapes in the layer with the new array of shapes that have been provided.
* @param primitives An array of shapes to add to the drawing layer.
*/
setPrimitives(primitives: IPrimitive[]): void;
}
/**
* Provides a set of tools for drawing and editing shapes on top of the map.
* @requires The Microsoft.Maps.DrawingTools module.
*/
export class DrawingTools {
/**
* @constructor
* @requires The Microsoft.Maps.DrawingTools module.
* @param map A map instanct to attach the drawing tools to.
*/
constructor(map: Map);
/**
* Initializes the drawing layer and instructs it to create a new shape of a given type.
* @param shapeType The type of new shape to create.
* @param created A callback function that is fired after the initial shape is created.
*/
public create(shapeType: DrawingTools.ShapeType, created?: (shape: IPrimitive) => void): void;
/** Disposes the instance of the DrawingTools class. */
public dispose(): void;
/**
* Adds a shape to the drawing layer and puts it into edit mode.
* @param shape A shape to put into editting mode.
*/
public edit(shape: IPrimitive): void;
/**
* Finishes any shape create / edit operation currently in progress, and returns the shape that was created or editted through a specified callback function.
* @param finished A callback function to return the completed shape with.
*/
public finish(finished?: (shape: IPrimitive) => void): void;
/**
* Creates a drawing manager which allows multi-shape editing and displays the toolbar.
* @param callback A callback function that is triggered after the DrawingTools have loaded.
*/
public showDrawingManager(callback?: (manager: DrawingManager) => void): void;
}
export module Events {
/////////////////////////////////////
/// addHandler Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted
* @param handler The callback function to handle the event when triggered.
* @returns The handler id.
*/
export function addHandler(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): IHandlerId;
/**
* Attaches the handler for the event that is thrown by the target. Use the return object to remove the handler using the removeHandler method.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted
* @param handler The callback function to handle the event when triggered.
* @returns The handler id.
*/
export function addHandler(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void): IHandlerId;
/////////////////////////////////////
/// addOne Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted
* @param handler The callback function to handle the event when triggered.
*/
export function addOne(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): void;
/**
* Attaches the handler for the event that is thrown by the target, but only triggers the handler the first once after being attached.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted
* @param handler The callback function to handle the event when triggered.
*/
export function addOne(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void): void;
/////////////////////////////////////
/// addThrottledHandler Definitions
////////////////////////////////////
/**
* Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* drawingChanged, drawingChanging, drawingEnded, drawingModeChanged, drawingStarted
* @param handler The callback function to handle the event when triggered.
* @returns The handler id.
*/
export function addThrottledHandler(target: DrawingTools, eventName: string, handler: (eventArg?: IPrimitive | IDrawingModeChangedData) => void): IHandlerId;
/**
* Attaches the handler for the event that is thrown by the target, where the minimum interval between events (in milliseconds) is specified as a parameter.
* @param target The object to attach the event to; Map, IPrimitive, Infobox, Layer, DrawingTools, DrawingManager, DirectionsManager, etc.
* @param eventName The type of event to attach. Supported Events:
* disposed, drawingChanged, drawingChanging, drawingEnded, drawingErased, drawingModeChanged, drawingStarted
* @param handler The callback function to handle the event when triggered.
* @param throttleInterval throttle interval (in ms)
* @returns The handler id.
*/
export function addThrottledHandler(target: DrawingManager, eventName: string, handler: (eventArg?: IPrimitive | DrawingTools.DrawingMode) => void, throttleInterval: number): IHandlerId;
}
}
declare module Microsoft.Maps.DrawingTools {
/**
* The different drawing modes that the drawing manager can be set to.
* @requires The Microsoft.Maps.DrawingTools module.
*/
export enum DrawingMode {
/** Edit an existing shape. Click on a shape to edit it. */
edit,
/** Erase and existing shape. Click on the shapes to erase them. */
erase,
/** Sets the drawing manager into an idle mode. */
none,
/** Allow the user to draw a polygon. */
polygon,
/** Allow the user to draw a polyline. */
polyline,
/** Allow the user to draw a pushpin. */
pushpin
}
/**
* The different types of shapes that are created or edited by the drawing tools.
* @requires The Microsoft.Maps.DrawingTools module.
*/
export enum ShapeType {
/** A polygon shape type. */
polygon,
/** A polyline shape type. */
polyline
}
}
+75
View File
@@ -0,0 +1,75 @@
// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4)
// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions
// Definitions by: Ricky Brundritt <https://github.com/rbrundritt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="Microsoft.Maps.d.ts"/>
declare module Microsoft.Maps {
/** GeoJSON object definition */
export interface IGeoJsonObject {
/**
* Type of the object
* could be one of the following:
* Point
* LineString
* Polygon
* MultiPoint
* MultiLineString
* MultiPolygon
* GeometryCollection
* Feature
* FeatureCollection
*/
type: string;
/** Geometric coordinates of the object */
coordinates?: number[] | number[][] | number[][][] | number[][][][];
/** Additional properties of the object as a key,value pair */
properties?: any;
/** Set of features (only applicable if the type is 'featurecollection') */
features?: IGeoJsonObject[];
/** Set of geometries (only applicable if the type is 'geometrycollection') */
geometries?: IGeoJsonObject[];
/** Geometry (only applicable if the type is 'feature') */
geometry?: IGeoJsonObject;
/** identifier of a feature (only applicable if the type is 'feature') */
id?: any;
}
/**
* Class responsible for reading/writing geo data in GeoJson format
* @requires The Microsoft.Maps.GeoJson module.
*/
export module GeoJson {
/**
* Reads the data from a given url and returns the shapes.
* @param url GeoJson download url.
* @param callback Callback function that needs to be called once the data is downloaded and parsed.
* @param jsonpQueryParam The name of the url query param to make a jsonp request.
* @param styles Styles that needs to be applied.
*/
export function readFromUrl(url: string, callback: (data: IPrimitive | IPrimitive[]) => void, jsonpQueryParam?: string, styles?: IStylesOptions): void;
/**
* Reads the data in geoJson format and returns the shapes.
* @param geoJson GeoJson data object that needs to be parsed into shapes.
* @param styles Styles that needs to be applied.
* @returns An array of shapes.
*/
export function read(geoJson: IGeoJsonObject | string, styles?: IStylesOptions): IPrimitive | IPrimitive[];
/**
* Writes the data into geoJson format.
* @param data Data that needs to be serialized.
* @returns A geoJson formatted string.
*/
export function write(data: IPrimitive | IPrimitive[]): IGeoJsonObject;
}
}
+113
View File
@@ -0,0 +1,113 @@
// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4)
// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions
// Definitions by: Ricky Brundritt <https://github.com/rbrundritt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="Microsoft.Maps.d.ts"/>
declare module Microsoft.Maps {
/** A standard dictionary object (associative array). */
export interface IDictionary<T> {
[K: string]: T;
}
/** Options for customizing how the heat map is rendered. */
export interface IHeatMapLayerOptions {
/**
* The temperature gradient that is used to colorize the map. Default gradient:
* {
* '0.00': 'rgb(255,0,255)', // Magenta
* '0.25': 'rgb(0,0,255)', // Blue
* '0.50': 'rgb(0,255,0)', // Green
* '0.75': 'rgb(255,255,0)', // Yellow
* '1.00': 'rgb(255,0,0)' // Red
* }
*/
colorGradient?: IDictionary<string>;
/**
* The intensity of each heat point. This is a decimal value between 0 and 1. This is used to specify how "hot" a single data point should be. Default: 0.5
*/
intensity?: number;
/**
* The opacity of the HeatMapLayer canvas. Value should be a decimal between 0 and 1. Default: 1
*/
opacity?: number;
/**
* The radius to draw each data point on the map. Default: 10
*/
radius?: number;
/**
* The distance units of the radius. Possible values are:
*
* • 'pixels' (defualt)
* • 'meters'
*
* When set to pixels the size of each data point will always be the same radius, regardless of zoom level. When set to meters, the size of the data points
* will scale based on zoom level so as to ensure that the radius is spatially accurate.
*/
unit?: 'meters' | 'pixel';
/** A boolean indicating if the heat map layer is visible or not. **/
visible?: boolean;
}
/**
* Class for rendering data as a heat map layer.
* @requires The Microsoft.Maps.Heatmap module.
*/
export class HeatMapLayer implements IDataLayer {
/**
* @constructor
* @requires The Microsoft.Maps.Heatmap module.
* @param locations Set of locations to visualize as a heat map.
* @param options Options for customizing how the heat map is rendered.
*/
constructor(locations: (Location | Pushpin)[], options?: IHeatMapLayerOptions);
/** Clears all data in the heat map layer. */
public clear(): void;
/** Disposes the heat map layer. */
public dispose(): void;
/**
* Gets a boolean indicating if the heat map layer is visible or not.
* @returns A boolean indicating if the heat map layer is visible or not.
*/
public getVisible(): boolean;
/**
* @deprecated
* Hides the heat map layer.
*/
public hide(): void;
/**
* Specifies the locations to use when generating the heat map.
* @param locations Set of locations.
*/
public setLocations(locations: (Location | Pushpin)[]): void;
/**
* Sets the options to use with the heat map layer.
* @param options Set of heat map layer options.
*/
public setOptions(options: IHeatMapLayerOptions): void;
/**
* Sets the visibility of the heat map layer.
* @param visible A boolean indicating if the heat map layer is visible or not.
*/
public setVisible(visible: boolean): void;
/**
* @deprecated
* Shows the heat map layer.
*/
public show(): void;
}
}
-42
View File
@@ -1,42 +0,0 @@
// Type definitions for Microsoft.Maps.AdvancedShapes 7.0
// Project: http://msdn.microsoft.com/en-us/library/hh921952.aspx
// Definitions by: Eric Todd <https://github.com/ericrtodd>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Microsoft.Maps.AdvancedShapes {
export class EntityCollection {
constructor(options?: EntityCollectionOptions);
clear(): void;
get(index: number): Entity;
getLength(): number;
getVisible(): boolean;
getZIndex(): number;
indexOf(entity: Entity): number;
insert(entity: Entity, index: number): void;
pop(): Entity;
push(entity: Entity): void;
remove(entity: Entity): Entity;
removeAt(index: number): Entity;
setOptions(options: EntityCollectionOptions): void;
toString(): string;
}
export class Polygon implements Entity {
constructor(locations: Array<Location>, options?: PolygonOptions);
getFillColor(): Color;
getLocations(): Array<Location>;
getStrokeColor(): Color;
getStrokeDashArray(): string;
getStrokeThickness(): number;
getVisible(): boolean;
setLocations(locations: Location[]): void;
setOptions(options: PolylineOptions): void;
toString(): string;
}
}
-434
View File
@@ -1,434 +0,0 @@
// Type definitions for Microsoft.Maps.Directions 7.0
// Project: http://msdn.microsoft.com/en-us/library/hh312813.aspx
// Definitions by: Eric Todd <https://github.com/ericrtodd>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Microsoft.Maps.Directions {
export interface BusinessDetails {
businessName?: string;
entityId?: string;
phoneNumber?: string;
website?: string;
}
export interface WaypointOptions {
address?: string;
businessDetails?: BusinessDetails;
disambiguationContainer?: HTMLElement;
exactLocation?: string;
isViapoint?: boolean;
location?: Location;
pushpin?: Pushpin;
shortAddress?: string;
}
export interface BusinessDisambiguationSuggestion {
address?: string;
distance?: number;
entityId?: number;
index?: number;
isApproximate?: boolean;
location?: Location;
name?: string;
phoneNumber?: string;
photoUrl?: string;
rooftopLocation?: Location;
website?: string;
}
export interface LocationDisambiguationSuggestion {
formattedSuggestion?: string;
location?: Location;
rooftopLocation?: Location;
suggestion?: string;
}
export interface Disambiguation {
businessSuggestions?: Array<BusinessDisambiguationSuggestion>;
hasMoreSuggestions?: boolean;
headerText?: string;
locationSuggestions?: Array<LocationDisambiguationSuggestion>;
}
export interface WaypointEventArgs {
waypoint: Waypoint;
}
export class Waypoint {
constructor(options: WaypointOptions);
clear(): void;
dispose(): void;
getAddress(): string;
getBusinessDetails(): BusinessDetails;
getDisambiguationContainer(): HTMLElement;
getDisambiguationResult(): Disambiguation;
getLocation(): Location;
getPushpin(): Pushpin;
getShortAddress(): string;
isExactLocation(): boolean;
isViapoint(): boolean;
setOptions(options: WaypointOptions): void;
}
export interface DirectionsRenderOptions {
autoDisplayDisambiguation?: boolean;
autoUpdateMapView?: boolean;
disambiguationPushpinOptions?: PushpinOptions;
displayDisclaimer?: boolean;
displayManeuverIcons?: boolean;
displayPostItineraryItemHints?: boolean;
displayPreItineraryItemHints?: boolean;
displayRouteSelector?: boolean;
displayStepWarnings?: boolean;
displayTrafficAvoidanceOption?: boolean;
displayWalkingWarning?: boolean;
drivingPolylineOptions?: PolylineOptions;
itineraryContainer?: HTMLElement;
lastWaypointIcon?: string;
middleWaypointIcon?: string;
stepPushpinOptions?: PushpinOptions;
transitPolylineOptions?: PolylineOptions;
viapointPushpinsOptions?: PushpinOptions;
walkingPolylineOptions?: PolylineOptions;
waypointPushpinOptions?: PushpinOptions;
}
export enum DistanceUnit {
kilometers= 0,
miles= 1
}
export enum RouteAvoidance {
none= 0,
minimizeLimitedAccessHighway= 1,
minimizeToll= 2,
avoidLimitedAccessHighway= 4,
avoidToll= 8,
avoidExpressTrain= 16,
avoidAirline= 32,
avoidBulletTrain= 64
}
export enum RouteMode {
driving,
transit,
walking
}
export enum RouteOptimization {
shortestTime= 0,
shortestDistance= 1,
minimizeMoney= 3,
minimizeTransfers= 4,
minimizeWalking= 5
}
export enum TimeType {
arrival,
departure,
lastAvailable
}
export interface TransitOptions {
timeType?: TimeType;
transitTime?: Date;
}
export interface DirectionsRequestOptions {
avoidTraffic?: boolean;
distanceUnit?: DistanceUnit;
maxRoutes?: number;
routeAvoidance?: Array<RouteAvoidance>;
routeDraggable?: boolean;
routeIndex?: boolean;
routeMode?: RouteMode;
routeOptimization?: RouteOptimization;
transitOptions?: TransitOptions;
}
export class DirectionsManager {
constructor(map: Microsoft.Maps.Map);
resetDirections(): void;
addWaypoint(waypoint: Waypoint, index?: number): void;
calculateDirections(): void;
clearDisplay(): void;
dispose(): void;
getAllWaypoints(): Array<Waypoint>;
getMap(): Map;
getNearbyMajorRoads(location: Location, callback: any, errorCallback: any, userData: any): void;
getRenderOptions(): DirectionsRenderOptions;
getRequestOptions(): DirectionsRequestOptions;
getRouteResult(): Array<Route>;
removeWaypoint(waypoint: Waypoint): void;
removeWaypoint(index: number): void;
resetDirections(options: ResetDirectionsOptions): void;
reverseGeocode(location: Location, callback: any, errorCallback: any, userData: any): void;
setMapView(): void;
setRenderOptions(options: DirectionsRenderOptions): void;
setRequestOptions(options: DirectionsRequestOptions): void;
}
export interface DirectionsStepEventArgs {
handled: boolean;
location: Location;
routeIndex: number;
routeLegIndex: number;
step: DirectionsStep;
stepIndex: number;
stepNumber: number;
}
export interface DirectionsErrorEventArgs {
responseCode: RouteResponseCode;
message: string;
}
export interface DirectionsEventArgs {
routeSummary: Array<RouteSummary>;
route: Array<Route>;
}
export interface DisambiguationRenderEventArgs {
containerElement: HTMLElement;
handled: boolean;
waypoint: Waypoint;
}
export interface DirectionsStepRenderEventArgs {
containerElement: HTMLElement;
handled: boolean;
lastStep: boolean;
routeIndex: number;
routeLegIndex: number;
step: DirectionsStep;
stepIndex: number;
}
export interface RouteSummaryRenderEventArgs {
containerElement: HTMLElement;
handled: boolean;
routeLegIndex: number;
summary: RouteSummary;
}
export interface WaypointRenderEventArgs {
containerElement: HTMLElement;
handled: boolean;
waypoint: Waypoint;
}
export interface DirectionsStep {
childItineraryItems: Array<DirectionsStep>;
coordinate: Location;
distance: string;
durationInSeconds: number;
formattedText: string;
iconType: IconType;
isImageRoadShield: boolean;
maneuver: Maneuver;
maneuverImageName: string;
monetaryCost: number;
postIntersectionHints: Array<string>;
preIntersectionHings: Array<string>;
startStopName: string;
transitLine: TransitLine;
transitStepIcon: string;
transitStopId: string;
transitTerminus: string;
warnings: Array<DirectionsStepWarning>;
}
export enum IconType {
none,
other,
auto,
ferry,
walk,
bus,
train,
airline
}
export enum Maneuver {
none= 0,
unknown= 1,
departStart= 2,
departIntermediateStop= 3,
departIntermediateStopReturning= 4,
arriveFinish= 5,
arriveIntermediateStop= 6,
turnLeft= 7,
turnRight= 8,
turnBack= 9,
uTurn= 10,
turnToStayLeft= 11,
turnToStayRight= 12,
bearLeft= 13,
bearRight= 14,
keepToStayLeft= 15,
keepToStayRight= 16,
keepToStayStraight= 17,
keepLeft= 18,
keepRight= 19,
keepStraight= 20,
take= 21,
takeRampLeft= 22,
takeRampRight= 23,
takeRampStraight= 24,
keepOnRampLeft= 25,
keepOnRampRight= 26,
keepOnRampStraight= 27,
merge= 28,
continueRoute= 29,
roadNameChange= 30,
enterRoundabout= 31,
exitRoundabout= 32,
turnRightThenTurnRight= 33,
turnRightThenTurnLeft= 34,
turnRightThenBearRight= 35,
turnRightThenBearLeft= 36,
turnLeftThenTurnLeft= 37,
turnLeftThenTurnRight= 38,
turnLeftThenBearLeft= 39,
turnLeftThenBearRight= 40,
bearRightThenTurnRight= 41,
bearRightThenTurnLeft= 42,
bearRightThenBearRight= 43,
bearRightThenBearLeft= 44,
bearLeftThenTurnLeft= 45,
bearLeftThenTurnRight= 46,
bearLeftThenBearRight= 47,
bearLeftThenBearLeft= 48,
rampThenHighwayRight= 49,
rampThenHighwayLeft= 50,
rampToHighwayStraight= 51,
enterThenExitRoundabout= 52,
bearThenMerge= 53,
turnThenMerge= 54,
bearThenKeep= 55,
transfer= 56,
wait = 57,
takeTransit= 58,
walk = 59,
transitDepart = 60,
transitArrive= 61,
}
export interface TransitLine {
abbreviatedName: string;
agencyId: number;
agencyName: string;
agencyUrl: string;
lineColor: Color;
lineTextColor: Color;
providerInfo: string;
verboseName: string;
}
export interface DirectionsStepWarning {
style: StepWarningStyle;
text: string;
}
export enum StepWarningStyle {
info= 0,
minor= 1,
moderate= 2,
major= 3,
ccZoneEnter= 4,
ccZoneExit= 5
}
export interface ResetDirectionsOptions {
removeAllWaypoints?: boolean;
resetRenderOptions?: boolean;
resetRequestOptions?: boolean;
}
export interface Route {
routeLegs: Array<RouteLeg>;
}
export interface RouteLeg {
endTime: Date;
endWaypointLocation: Location;
itineraryItems: Array<DirectionsStep>;
originalRouteIndex: number;
startTime: Date;
startWaypointLocation: Location;
subLegs: Array<RouteSubLeg>;
summary: RouteSummary;
}
export interface RouteSubLeg {
actualEnd: Location;
actualStart: Location;
endDescription: string;
routePath: RoutePath;
startDescription: string;
summary: RouteSummary;
}
export interface RoutePath {
decodedLatitudes: Array<number>;
decodedLongitudes: Array<number>;
decodedRegions: Array<any>;
}
export interface RouteSummary {
distance: number;
monetaryCost: number;
northEast: Location;
southWest: Location;
time: number;
timeWithTraffic: number;
}
export enum RouteResponseCode {
success= 0,
unknownError= 1,
cannotFindNearbyRoad= 2,
tooFar= 3,
noSolution= 4,
dataSourceNotFound= 5,
noAvailableTransitTrip= 7,
transitStopsTooClose= 8,
walkingBestAlternative= 9,
outOfTransitBounds= 10,
timeout= 11,
waypointDisambiguation= 12,
hasEmptyWaypoint= 13,
exceedMaxWaypointLimit= 14,
atleastTwoWaypointRequired= 15,
firstOrLastStoppointsIsVia= 16,
searchServiceFailed= 17,
invalidCredentials= 18
}
export interface RouteSelectorEventArgs {
handled: boolean;
routeIndex: number;
}
export interface RouteSelectorRenderEventArgs {
containerElement: HTMLElement;
handled: boolean;
routeIndex: number;
routeLeg: RouteLeg;
}
}
-150
View File
@@ -1,150 +0,0 @@
// Type definitions for Microsoft.Maps.Search 7.0
// Project: http://msdn.microsoft.com/en-us/library/hh868061.aspx
// Definitions by: Eric Todd <https://github.com/ericrtodd>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Microsoft.Maps.Search {
export interface Address {
addressLine: string;
adminDistrict: string;
countryRegion: string;
district: string;
formattedAddress: string;
locality: string;
postalCode: string;
postalTown:string;
}
export interface GeocodeLocation {
location: Location;
name: string;
precision:LocationPrecision;
}
export interface GeocodeRequestOptions {
bounds?: LocationRect;
callback?: (result: GeocodeResult, userData: any) => any;
count: number;
errorCallback?: (options: GeocodeRequestOptions) => any;
timeout?: number;
userData?: any;
where:string;
}
export interface GeocodeResult {
parsedAddress: Address;
parsedKeyword: string;
parsedSeparator: string;
results:Array<PlaceResult>;
}
export enum LocationPrecision {
interpolated,
rooftop,
}
export enum MatchCode {
none,
good,
ambiguous,
upHierarchy,
modified,
}
export enum MatchConfidence {
high,
medium,
low,
unknown,
}
export interface PlaceResult {
bestView: LocationRect;
location: GeocodeLocation;
locations: Array<GeocodeLocation>;
matchCode: MatchCode;
matchConfidence: MatchConfidence;
name:string;
}
export interface ReverseGeocodeRequestOptions {
callback?: (result: PlaceResult, userData: any) => any;
errorCallback?: (options: ReverseGeocodeRequestOptions) => any;
location?: Location;
timeout?: number;
userData?:any;
}
export class SearchManager {
constructor(map: Map);
geocode(request: GeocodeRequestOptions): void;
reverseGeocode(request: ReverseGeocodeRequestOptions): void;
search(request:SearchRequestOptions):void;
}
export interface SearchParseResult {
keyword: string;
location: GeocodeLocation;
matchConfidence:MatchConfidence;
}
export interface SearchRegion {
address: Address;
geocodeLocations: Array<GeocodeLocation>;
explicitLocation: GeocodeLocation;
mapBounds: LocationRect;
matchCode: MatchCode;
matchConfidence: MatchConfidence;
source:string;
}
export interface SearchRequestOptions {
callback?:(result: SearchResponse, userData: any)=>any;
count: number;
errorCallback?:(options: SearchRequestOptions)=>any;
query?: string;
startIndex?: number;
timeout?: number;
entityType?: string;
userData?: any;
what?: string;
where?:string;
}
export interface SearchResponse {
alternateSearchRegions: Array<SearchRegion>;
hasMore: boolean;
parseResults: Array<SearchParseResult>;
responseSummary: SearchResponseSummary;
searchRegion: SearchRegion;
searchResults:Array<SearchResult>;
}
export interface SearchResponseSummary {
authResultCode: number;
copyright: string;
errorMessage: string;
statusCode: number;
traceId:number;
}
export interface SearchResult {
address: Address;
city: string;
country: string;
entityType: string;
hoursOfOperation: string;
id: number;
location: Location;
name: string;
phone: string;
postalCode: string;
reviewCount: number;
userRating: number;
website:string;
}
}
-12
View File
@@ -1,12 +0,0 @@
// Type definitions for Microsoft.Maps.Themes 7.0
// Project: http://msdn.microsoft.com/en-us/library/hh868061.aspx
// Definitions by: Eric Todd <https://github.com/ericrtodd>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Microsoft.Maps.Themes {
export class BingTheme {
constructor();
}
}
-22
View File
@@ -1,22 +0,0 @@
// Type definitions for Microsoft.Maps.Traffic 7.0
// Project: http://msdn.microsoft.com/en-us/library/hh312840.aspx
// Definitions by: Eric Todd <https://github.com/ericrtodd>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Microsoft.Maps.Traffic {
export class TrafficManager {
constructor(map: Map);
hide(): void;
hideFlow(): void;
hideIncidents(): void;
hideLegend(): void;
show(): void;
showFlow(): void;
showIncidents(): void;
showLegend():void;
}
}
-136
View File
@@ -1,136 +0,0 @@
// Type definitions for Microsoft.Maps.VenueMaps 7.0
// Project: http://msdn.microsoft.com/en-us/library/hh312797.aspx
// Definitions by: Eric Todd <https://github.com/ericrtodd>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace Microsoft.Maps.VenueMaps {
export interface MouseResponse {
eventArgs: MouseEventArgs;
}
export interface PrimitiveResponse {
eventArgs: Primitive;
}
export interface Directory {
addToDOM(div: HTMLElement, sortOrder: DirectorySortOrder, to_group_or_not: DirectoryGrouping): void;
createUIElements(): void;
handleMouseClick(e: (response: MouseResponse) => void): void;
handleMouseClick(e: (response: PrimitiveResponse) => void): void;
handleMouseOut(e: (response: MouseResponse) => void): void;
handleMouseOut(e: (response: PrimitiveResponse) => void): void;
handleMouseOver(e: (response: MouseResponse) => void): void;
handleMouseOver(e: (response: PrimitiveResponse) => void): void;
isInDOM(): boolean;
removeFromDOM(): void;
setHeight(height: number): void;
}
export enum DirectoryGrouping {
byCategory,
none,
}
export enum DirectorySortOrder {
alphabetical,
byFloor,
}
export interface Floor {
name: string;
primitives: Array<Primitive>;
zoomRange: Array<number>;
}
export interface Footprint {
polygons: Array<Polygon>;
zoomRange: Array<number>;
}
export interface Metadata {
CenterLatitude: number;
CenterLongitude: number;
DefaultFloor: string;
FloorHeader: string;
Floors: Array<Floor>;
Footprint: Footprint;
MapId: string;
MapType: string;
Name: string;
YpId: string;
}
export interface NearbyVenue {
distance: number;
metadata: Metadata;
}
export interface NearbyVenueOptions {
callback?: (maps: Array<VenueMap>) => any;
location?: Location;
map?: Map;
radius?: number;
}
export interface Polygon {
bounds: LocationRect;
center: Location;
locations: Array<Location>;
}
export interface Primitive {
bounds: LocationRect;
businessId: string;
categoryId: string;
categoryName: string;
center: Location;
floor: Floor;
id: string;
locations: Array<Location>;
name: string;
highlight(): void;
unhighlight(): void;
}
export interface VenueMap {
address: string;
bestMapView: ViewOptions;
businessId: string;
center: Location;
defaultFloor: string;
directory: Directory;
floorHeader: string;
floors: Array<Floor>;
footprint: Footprint;
id: string;
name: string;
phoneNumber: string;
type: string;
dispose(): void;
getActiveFloor(): string;
hide(): void;
setActiveFloor(floor: string): void;
show(): void;
}
export interface VenueMapCreationOptions {
error: (errorCode: number, args: any) => any;
success: (venueMap: VenueMap, args: any) => any;
venueMapId: string;
}
export class VenueMapFactory {
constructor(map: Map);
create(options: VenueMapCreationOptions): void;
getNearbyVenues(options: NearbyVenueOptions): void;
}
}
+235
View File
@@ -0,0 +1,235 @@
// Type definitions for Microsoft.Maps 8.0 (Change set e6d7cc4)
// Project: https://github.com/Microsoft/Bing-Maps-V8-TypeScript-Definitions
// Definitions by: Ricky Brundritt <https://github.com/rbrundritt>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="Microsoft.Maps.d.ts"/>
/**
* Provides an easy method for geocoding address and searching for points of interest from JavaScript.
* @requires The Microsoft.Maps.Search module.
*/
declare module Microsoft.Maps.Search {
/**
* Defines the match precision of a geocdoed result.
* @requires The Microsoft.Maps.Search module.
*/
export enum LocationPrecision {
/** The geocode result was matched to a point on a road using interpolation. */
interpolated,
/**
* The geocode result was matched to a point on a road using interpolation with an additional offset to shift the
* Location to the side of the street.
*/
InterpolatedOffset,
/** The geocode result was matched to the center of a parcel (property boundary). */
parcel,
/** The geocode result was matched to the rooftop of a building. */
rooftop
}
/**
* Defines the geocoding level of the location match found by the geocoder.
* @requires The Microsoft.Maps.Search module.
*/
export enum MatchCode {
/** No match was found. */
none,
/** The match was good. */
good,
/** The match was ambiguous. Multiple results were returned. */
ambiguous,
/** The match was found by a broader search. */
upHierarchy,
/** The match was found, but possibly using a modified query. */
modified
}
/**
* Defines the confidence of the location match found by the geocoding service.
* @requires The Microsoft.Maps.Search module.
*/
export enum MatchConfidence {
/** The confidence of the match is high. */
high,
/** The confidence of the match is medium. */
medium,
/** The confidence of the match is low. */
low,
/** The confidence of the match is unknown. */
unknown
}
/** A object that represents a geocoded location. */
export interface IGeocodeLocation {
/** The map location of this geocode location match. */
location: Location;
/** The name of this geocode location match. */
name: string;
/** The precision of this geocode location match. */
precision: string | LocationPrecision;
}
/** An object that represents an place result. */
export interface IPlaceResult {
/** The geocoded address of the place result. */
address: IAddress;
/** The location rectangle that defines the boundaries of the best map view of the place result. */
bestView: LocationRect;
/** The classification of the geographic entity returned, such as PopulatedPlace. */
entityType: string;
/** The geocoded location of the best result. */
location: Location;
/** The geocoded locations. */
locations: IGeocodeLocation[];
/** The match code of the best result. */
matchCode: string | MatchCode;
/** The match confidence of the best result. */
matchConfidence: string | MatchConfidence;
/** The name of the place result, if one exists. */
name: string;
}
/** An object that represents a geocode result returned by REST service. */
export interface IGeocodeResult {
/** An array of geocode results. */
results: IPlaceResult[];
}
/** The options for a geocode request. */
export interface IGeocodeRequestOptions {
/**
* A location rectangle that defines the boundaries of the area in which to search for
* location results. The default is the bounds of the map view associated with this
* instance of the SearchManager, which is usually the current map view.
*/
bounds?: LocationRect;
/**
* The name of the function to call when a successful result is returned from the
* geocode request. The callback function must accept two parameters: result, which is
* a GeocodeResult type, and a userData object.
*/
callback: (geocodeResult: IGeocodeResult, userData: any) => void;
/** The maximum number of results to return. Required. The maximum number than can be returned is 20. */
count?: number;
/**
* The name of the function to call when the request is returned with an error. The
* error callback function must accept an IGeocodeRequestOptions object.
*/
errorCallback?: (geocodeRequestOptions: IGeocodeRequestOptions) => void;
/** Specifies to include the two-letter ISO country code. */
includeCountryIso2?: boolean;
/** Specifies to include the neighborhood in the response when it is available. */
includeNeighborhood?: boolean;
/** A number indicating how long to wait, in seconds, for the geocode request to return. The default value is 5 seconds. */
timeout?: number;
/** An object containing any data that needs to be passed to the callback when the request is completed. */
userData?: any;
/** A string containing the address or place to be matched to a location on the map. */
where: string;
}
/** The options for a reverse geocode request. */
export interface ReverseGeocodeRequestOptions {
/**
* A reference to a function to call when a successful result is returned from the geocode request. The callback function
* will receive a PlaceResult object as an argument.
*/
callback: (placeResult: IPlaceResult, userData: any) => void;
/**
* A reference to a function to call when the request is returned with an error. The error callback function will receive
* an object containing the geocode request options used in the request.
*/
errorCallback?: (reverseGeocodeRequestOptions: ReverseGeocodeRequestOptions) => void;
/** Specifies to include the two-letter ISO country code. Default: false */
includeCountryIso2?: boolean;
/**
* An array of entity types selected from the following options.
* • Address
* • Neighborhood
* • PopulatedPlace
* • Postcode1
* • AdminDivision1
* • AdminDivision2
* • CountryRegion
* These entity types are ordered from the most specific entity to the least specific entity. When entities of more than one entity type are found, only the most specific
* entity is returned. For example, if you specify Address and AdminDistrict1 as entity types and entities were found for both types, only the Address entity information is
* returned in the response. One exception to this rule is when both PopulatedPlace and Neighborhood entity types are specified and information is found for both. In this case,
* the information for both entity types is returned. Also, more than one Neighborhood may be returned because the area covered by two different neighborhoods can overlap.
*/
includeEntityTypes?: string[];
/**
* Specifies to include the neighborhood in the response when it is available. Note: This feature isn’t
* available in all locations.
*/
includeNeighborhood?: boolean;
/** The location to use to match to geographic entities and addresses. */
location: Location;
/** A number indicating how long to wait, in seconds, for the reverse geocode request to return. The default value is 5 seconds. */
timeout?: number;
/** An object containing any data that needs to be passed to the callback when the request is completed. */
userData?: any;
}
/**
* A class that contains methods for returning search and location results.
* @requires The Microsoft.Maps.Search module.
*/
export class SearchManager {
/**
* @constructor
* @requires The Microsoft.Maps.Search module.
* @param map A Map object
*/
constructor(map: Map);
/**
* Matches the address or place query in the specified request
* options to a location and returns the results to the request
* options callback function.
* @param request Options for sending geocode request
*/
public geocode(request: IGeocodeRequestOptions): void;
/**
* Matches the specified location to an address and returns the
* address results to the specified request options callback function.
* @param request Options for sending reverse geocode request
*/
public reverseGeocode(request: ReverseGeocodeRequestOptions): void;
}
}

Some files were not shown because too many files have changed in this diff Show More