tried to merge

This commit is contained in:
lars
2015-08-13 18:19:03 +02:00
2511 changed files with 1229888 additions and 622730 deletions

9
.editorconfig Normal file
View File

@@ -0,0 +1,9 @@
root = true
[*]
trim_trailing_whitespace = true
insert_final_newline = true
[{*.json,*.yml}]
indent_style = space
indent_size = 2

14
.gitignore vendored
View File

@@ -23,18 +23,14 @@ Properties
*~
# test folder
!_infrastructure/*.js
!_infrastructure/tests/*
!_infrastructure/tests/*.js
!_infrastructure/tests/*/*.js
!_infrastructure/tests/*/*/*.js
!_infrastructure/tests/*/*/*/*.js
_infrastructure/tests/build
.idea
*.iml
*.js.map
#rx.js
!rx.js
!*.js/
node_modules
.sublimets
.settings/launch.json

View File

@@ -1,6 +1,8 @@
language: node_js
node_js:
- 0.10
- "iojs-v2"
sudo: false
notifications:
email: false

View File

@@ -1 +1 @@
Please see the [contribution guide](https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute) for information on how to contribute to this project.
Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) at [definitelytyped.org](http://definitelytyped.org/guides/contributing.html) for information on how to contribute to DefinitelyTyped.

1174
CONTRIBUTORS.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,180 @@
/// <reference path="DataStream.js.d.ts" />
var buf = new ArrayBuffer(100);
var ds = new DataStream(buf);
ds = new DataStream(buf, 10);
ds = new DataStream(buf, 10, DataStream.BIG_ENDIAN);
ds.save('somefile.ext');
ds.dynamicSize = true;
for (var i=0; i<ds.byteLength; i++) {
}
ds.buffer = buf;
ds.byteOffset = 10;
ds.seek(0);
ds.isEof();
var int32arr: Int32Array;
var int16arr: Int16Array;
var int8arr: Int8Array;
var uint32arr: Uint32Array;
var uint16arr: Uint16Array;
var uint8arr: Uint8Array;
var float64arr: Float64Array;
var float32arr: Float32Array;
var val: number;
var str: string;
int32arr = ds.mapInt32Array(2);
int32arr = ds.mapInt32Array(2, DataStream.LITTLE_ENDIAN);
int16arr = ds.mapInt16Array(2);
int16arr = ds.mapInt16Array(2, DataStream.BIG_ENDIAN);
int8arr = ds.mapInt8Array(2);
uint32arr = ds.mapUint32Array(2);
uint32arr = ds.mapUint32Array(2, DataStream.LITTLE_ENDIAN);
uint16arr = ds.mapUint16Array(2);
uint16arr = ds.mapUint16Array(2, DataStream.BIG_ENDIAN);
uint8arr = ds.mapUint8Array(2);
float64arr = ds.mapFloat64Array(2);
float64arr = ds.mapFloat64Array(2, DataStream.LITTLE_ENDIAN);
float32arr = ds.mapFloat32Array(2);
float32arr = ds.mapFloat32Array(2, DataStream.BIG_ENDIAN);
int32arr = ds.readInt32Array(2);
int32arr = ds.readInt32Array(2, DataStream.LITTLE_ENDIAN);
int16arr = ds.readInt16Array(2);
int16arr = ds.readInt16Array(2, DataStream.BIG_ENDIAN);
int8arr = ds.readInt8Array(2);
uint32arr = ds.readUint32Array(2);
uint32arr = ds.readUint32Array(2, DataStream.LITTLE_ENDIAN);
uint16arr = ds.readUint16Array(2);
uint16arr = ds.readUint16Array(2, DataStream.BIG_ENDIAN);
uint8arr = ds.readUint8Array(2);
float64arr = ds.readFloat64Array(2);
float64arr = ds.readFloat64Array(2, DataStream.LITTLE_ENDIAN);
float32arr = ds.readFloat32Array(2);
float32arr = ds.readFloat32Array(2, DataStream.BIG_ENDIAN);
ds.writeInt32Array(new Int32Array([1,2,3]));
ds.writeInt32Array(new Int32Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeInt16Array(new Int16Array([1,2,3]));
ds.writeInt16Array(new Int16Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeInt8Array(new Int8Array([1,2,3]));
ds.writeUint32Array(new Uint32Array([1,2,3]));
ds.writeUint32Array(new Uint32Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeUint16Array(new Uint16Array([1,2,3]));
ds.writeUint16Array(new Uint16Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeUint8Array(new Uint8Array([1,2,3]));
ds.writeFloat64Array(new Float64Array([1,2,3]));
ds.writeFloat64Array(new Float64Array([1,2,3]), DataStream.BIG_ENDIAN);
ds.writeFloat32Array(new Float32Array([1,2,3]));
ds.writeFloat32Array(new Float32Array([1,2,3]), DataStream.BIG_ENDIAN);
val = ds.readInt32();
val = ds.readInt32(DataStream.LITTLE_ENDIAN);
val = ds.readInt16();
val = ds.readInt16(DataStream.BIG_ENDIAN);
val = ds.readInt8();
val = ds.readUint32();
val = ds.readUint32(DataStream.LITTLE_ENDIAN);
val = ds.readUint16();
val = ds.readUint16(DataStream.BIG_ENDIAN);
val = ds.readUint8();
val = ds.readFloat64();
val = ds.readFloat64(DataStream.LITTLE_ENDIAN);
val = ds.readFloat32();
val = ds.readFloat32(DataStream.BIG_ENDIAN);
ds.writeInt32(1);
ds.writeInt32(2, DataStream.BIG_ENDIAN);
ds.writeInt16(1);
ds.writeInt16(2, DataStream.LITTLE_ENDIAN);
ds.writeInt8(1);
ds.writeUint32(1);
ds.writeUint32(2, DataStream.BIG_ENDIAN);
ds.writeUint16(1);
ds.writeUint16(2, DataStream.LITTLE_ENDIAN);
ds.writeUint8(1);
ds.writeFloat32(1);
ds.writeFloat32(2, DataStream.BIG_ENDIAN);
ds.writeFloat64(1);
ds.writeFloat64(2, DataStream.LITTLE_ENDIAN);
var embed = [
'tag', 'uint32be',
'code', 'uint32le',
'greet', 'cstring'
];
var def = [
'tag', 'cstring:4',
'code', 'uint32le',
'embed', embed,
'length', 'uint16be',
'data', ['[]', 'float32be', 'length'],
'greet', 'cstring:20',
'endNote', 'uint8'
];
var obj = ds.readStruct(def);
ds.writeStruct(def, obj);
str = ds.readUCS2String(2);
str = ds.readUCS2String(2, DataStream.LITTLE_ENDIAN);
ds.writeUCS2String("str");
ds.writeUCS2String("str", DataStream.LITTLE_ENDIAN);
ds.writeUCS2String("str", DataStream.LITTLE_ENDIAN, 1);
str = ds.readString(2);
str = ds.readString(2, "ASCII");
ds.writeString("str");
ds.writeString("str", "ASCII");
ds.writeString("str", "ASCII", 1);
str = ds.readCString();
str = ds.readCString(2);
ds.writeCString("str");
ds.writeCString("str", 1);

937
DataStream.js/DataStream.js.d.ts vendored Normal file
View File

@@ -0,0 +1,937 @@
// Type definitions for DataStream.js
// Project: https://github.com/kig/DataStream.js
// Definitions by: Tat <https://github.com/tatchx/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare class DataStream {
/**
Big-endian const to use as default endianness.
*/
static BIG_ENDIAN: boolean;
/**
Little-endian const to use as default endianness.
*/
static LITTLE_ENDIAN: boolean;
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param {ArrayBuffer} arrayBuffer ArrayBuffer to read from.
*/
constructor(arrayBuffer: ArrayBuffer);
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param arrayBuffer ArrayBuffer to read from.
@param byteOffset Offset from arrayBuffer beginning for the DataStream.
*/
constructor(arrayBuffer: ArrayBuffer, byteOffset: number);
/**
DataStream reads scalars, arrays and structs of data from an ArrayBuffer.
It's like a file-like DataView on steroids.
@param arrayBuffer ArrayBuffer to read from.
@param byteOffset Offset from arrayBuffer beginning for the DataStream.
@param endianness DataStream.BIG_ENDIAN or DataStream.LITTLE_ENDIAN (the default).
*/
constructor(arrayBuffer: ArrayBuffer, byteOffset: number, endianness: boolean);
/**
Saves the DataStream contents to the given filename.
Uses Chrome's anchor download property to initiate download.
*
@param filename Filename to save as.
@return nothing
*/
save(filename: string): void;
/**
Whether to extend DataStream buffer when trying to write beyond its size.
If set, the buffer is reallocated to twice its current size until the
requested write fits the buffer.
*/
dynamicSize: boolean;
/**
Returns the byte length of the DataStream object.
*/
byteLength: number;
/**
Set/get the backing ArrayBuffer of the DataStream object.
The setter updates the DataView to point to the new buffer.
*/
buffer: ArrayBuffer;
/**
Set/get the byteOffset of the DataStream object.
The setter updates the DataView to point to the new byteOffset.
*/
byteOffset: number;
/**
Set/get the backing DataView of the DataStream object.
The setter updates the buffer and byteOffset to point to the DataView values.
*/
dataView: Object;
/**
Sets the DataStream read/write position to given position.
Clamps between 0 and DataStream length.
*
@param pos Position to seek to.
@return nothing
*/
seek(pos: number): void;
/**
Returns true if the DataStream seek pointer is at the end of buffer and
there's no more data to read.
*
@return true if the seek pointer is at the end of the buffer.
*/
isEof(): boolean;
/**
Maps an Int32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Int32Array to the DataStream backing buffer.
*/
mapInt32Array(length: number): Int32Array;
/**
Maps an Int32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Int32Array to the DataStream backing buffer.
*/
mapInt32Array(length: number, e: boolean): Int32Array;
/**
Maps an Int16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Int16Array to the DataStream backing buffer.
*/
mapInt16Array(length: number): Int16Array;
/**
Maps an Int16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Int16Array to the DataStream backing buffer.
*/
mapInt16Array(length: number, e: boolean): Int16Array;
/**
Maps an Int8Array into the DataStream buffer.
*
Nice for quickly reading in data.
*
@param length Number of elements to map.
@return Int8Array to the DataStream backing buffer.
*/
mapInt8Array(length: number): Int8Array;
/**
Maps a Uint32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Uint32Array to the DataStream backing buffer.
*/
mapUint32Array(length: number): Uint32Array;
/**
Maps a Uint32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Uint32Array to the DataStream backing buffer.
*/
mapUint32Array(length: number, e: boolean): Uint32Array;
/**
Maps a Uint16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Uint16Array to the DataStream backing buffer.
*/
mapUint16Array(length: number): Uint16Array;
/**
Maps a Uint16Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Uint16Array to the DataStream backing buffer.
*/
mapUint16Array(length: number, e: boolean): Uint16Array;
/**
Maps a Uint8Array into the DataStream buffer.
*
Nice for quickly reading in data.
*
@param length Number of elements to map.
@return Uint8Array to the DataStream backing buffer.
*/
mapUint8Array(length: number): Uint8Array;
/**
Maps a Float64Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Float64Array to the DataStream backing buffer.
*/
mapFloat64Array(length: number): Float64Array;
/**
Maps a Float64Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Float64Array to the DataStream backing buffer.
*/
mapFloat64Array(length: number, e: boolean): Float64Array;
/**
Maps a Float32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@return Float32Array to the DataStream backing buffer.
*/
mapFloat32Array(length: number): Float32Array;
/**
Maps a Float32Array into the DataStream buffer, swizzling it to native
endianness in-place. The current offset from the start of the buffer needs to
be a multiple of element size, just like with typed array views.
*
Nice for quickly reading in data. Warning: potentially modifies the buffer
contents.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return Float32Array to the DataStream backing buffer.
*/
mapFloat32Array(length: number, e: boolean): Float32Array;
/**
Reads an Int32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Int32Array.
*/
readInt32Array(length: number): Int32Array;
/**
Reads an Int32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Int32Array.
*/
readInt32Array(length: number, e: boolean): Int32Array;
/**
Reads an Int16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Int16Array.
*/
readInt16Array(length: number): Int16Array;
/**
Reads an Int16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Int16Array.
*/
readInt16Array(length: number, e: boolean): Int16Array;
/**
Reads an Int8Array of desired length from the DataStream.
*
@param length Number of elements to map.
@return The read Int8Array.
*/
readInt8Array(length: number): Int8Array;
/**
Reads an Uint32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Uint32Array.
*/
readUint32Array(length: number): Uint32Array;
/**
Reads an Uint32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Uint32Array.
*/
readUint32Array(length: number, e: boolean): Uint32Array;
/**
Reads an Uint16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Uint16Array.
*/
readUint16Array(length: number): Uint16Array;
/**
Reads an Uint16Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Uint16Array.
*/
readUint16Array(length: number, e: boolean): Uint16Array;
/**
Reads an Uint8Array of desired length from the DataStream.
*
@param length Number of elements to map.
@return The read Uint8Array.
*/
readUint8Array(length: number): Uint8Array;
/**
Reads a Float64Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Float64Array.
*/
readFloat64Array(length: number, e: boolean): Float64Array;
/**
Reads a Float64Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Float64Array.
*/
readFloat64Array(length: number): Float64Array;
/**
Reads a Float32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@param e Endianness of the data to read.
@return The read Float32Array.
*/
readFloat32Array(length: number, e: boolean): Float32Array;
/**
Reads a Float32Array of desired length and endianness from the DataStream.
*
@param length Number of elements to map.
@return The read Float32Array.
*/
readFloat32Array(length: number): Float32Array;
/**
Writes an Int32Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeInt32Array(arr: Int32Array, e: boolean): void;
/**
Writes an Int32Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeInt32Array(arr: Int32Array): void;
/**
Writes an Int16Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeInt16Array(arr: Int16Array, e: boolean): void;
/**
Writes an Int16Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeInt16Array(arr: Int16Array): void;
/**
Writes an Int8Array to the DataStream.
*
@param arr The array to write.
*/
writeInt8Array(arr: Int8Array): void;
/**
Writes an Uint32Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeUint32Array(arr: Uint32Array, e: boolean): void;
/**
Writes an Uint32Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeUint32Array(arr: Uint32Array): void;
/**
Writes an Uint16Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeUint16Array(arr: Uint16Array, e: boolean): void;
/**
Writes an Uint16Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeUint16Array(arr: Uint16Array): void;
/**
Writes an Uint8Array to the DataStream.
*
@param arr The array to write.
*/
writeUint8Array(arr: Uint8Array): void;
/**
Writes a Float64Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeFloat64Array(arr: Float64Array): void;
/**
Writes a Float64Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeFloat64Array(arr: Float64Array, e: boolean): void;
/**
Writes a Float32Array of specified endianness to the DataStream.
*
@param arr The array to write.
*/
writeFloat32Array(arr: Float32Array): void;
/**
Writes a Float32Array of specified endianness to the DataStream.
*
@param arr The array to write.
@param e Endianness of the data to write.
*/
writeFloat32Array(arr: Float32Array, e: boolean): void;
/**
Reads a 32-bit int from the DataStream with the desired endianness.
*
@return The read number.
*/
readInt32(): number;
/**
Reads a 32-bit int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readInt32(e: boolean): number;
/**
Reads a 16-bit int from the DataStream with the desired endianness.
*
@return The read number.
*/
readInt16(): number;
/**
Reads a 16-bit int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readInt16(e: boolean): number;
/**
Reads an 8-bit int from the DataStream.
*
@return The read number.
*/
readInt8(): number;
/**
Reads a 32-bit unsigned int from the DataStream with the desired endianness.
*
@return The read number.
*/
readUint32(): number;
/**
Reads a 32-bit unsigned int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readUint32(e: boolean): number;
/**
Reads a 16-bit unsigned int from the DataStream with the desired endianness.
*
@return The read number.
*/
readUint16(): number;
/**
Reads a 16-bit unsigned int from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readUint16(e: boolean): number;
/**
Reads an 8-bit unsigned intfrom the DataStream.
*
@return The read number.
*/
readUint8(): number;
/**
Reads a 32-bit float from the DataStream with the desired endianness.
*
@return The read number.
*/
readFloat32(): number;
/**
Reads a 32-bit float from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readFloat32(e: boolean): number;
/**
Reads a 64-bit float from the DataStream with the desired endianness.
*
@return The read number.
*/
readFloat64(): number;
/**
Reads a 64-bit float from the DataStream with the desired endianness.
*
@param e Endianness of the number.
@return The read number.
*/
readFloat64(e: boolean): number;
/**
Writes a 32-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeInt32(v: number): void;
/**
Writes a 32-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeInt32(v: number, e: boolean): void;
/**
Writes a 16-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeInt16(v: number): void;
/**
Writes a 16-bit int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeInt16(v: number, e: boolean): void;
/**
Writes an 8-bit int to the DataStream.
*
@param v Number to write.
*/
writeInt8(v: number): void;
/**
Writes a 32-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeUint32(v: number): void;
/**
Writes a 32-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeUint32(v: number, e: boolean): void;
/**
Writes a 16-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeUint16(v: number): void;
/**
Writes a 16-bit undigned int to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeUint16(v: number, e: boolean): void;
/**
Writes an 8-bit undigned int to the DataStream.
*
@param v Number to write.
*/
writeUint8(v: number): void;
/**
Writes a 32-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeFloat32(v: number): void;
/**
Writes a 32-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeFloat32(v: number, e: boolean): void;
/**
Writes a 64-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
*/
writeFloat64(v: number): void;
/**
Writes a 64-bit float to the DataStream with the desired endianness.
*
@param v Number to write.
@param e Endianness of the number.
*/
writeFloat64(v: number, e: boolean): void;
/**
Reads a struct of data from the DataStream. The struct is defined as
a flat array of [name, type]-pairs. See the example below:
*
ds.readStruct([
'headerTag', 'uint32', // Uint32 in DataStream endianness.
'headerTag2', 'uint32be', // Big-endian Uint32.
'headerTag3', 'uint32le', // Little-endian Uint32.
'array', ['[]', 'uint32', 16], // Uint32Array of length 16.
'array2Length', 'uint32',
'array2', ['[]', 'uint32', 'array2Length'] // Uint32Array of length array2Length
]);
*
The possible values for the type are as follows:
*
// Number types
// Unsuffixed number types use DataStream endianness.
// To explicitly specify endianness, suffix the type with
// 'le' for little-endian or 'be' for big-endian,
// e.g. 'int32be' for big-endian int32.
'uint8' -- 8-bit unsigned int
'uint16' -- 16-bit unsigned int
'uint32' -- 32-bit unsigned int
'int8' -- 8-bit int
'int16' -- 16-bit int
'int32' -- 32-bit int
'float32' -- 32-bit float
'float64' -- 64-bit float
*
// String types
'cstring' -- ASCII string terminated by a zero byte.
'string:N' -- ASCII string of length N, where N is a literal integer.
'string:variableName' -- ASCII string of length $variableName,
where 'variableName' is a previously parsed number in the current struct.
'string,CHARSET:N' -- String of byteLength N encoded with given CHARSET.
'u16string:N' -- UCS-2 string of length N in DataStream endianness.
'u16stringle:N' -- UCS-2 string of length N in little-endian.
'u16stringbe:N' -- UCS-2 string of length N in big-endian.
*
// Complex types
[name, type, name_2, type_2, ..., name_N, type_N] -- Struct
function(dataStream, struct) {} -- Callback function to read and return data.
{get: function(dataStream, struct) {},
set: function(dataStream, struct) {}}
-- Getter/setter functions to read and return data, handy for using the same
struct definition for reading and writing structs.
['[]', type, length] -- Array of given type and length. The length can be either
a number, a string that references a previously-read
field, or a callback function(struct, dataStream, type){}.
If length is '*', reads in as many elements as it can.
*
@param structDefinition Struct definition object.
@return The read struct. Null if failed to read struct.
*/
readStruct(structDefinition: any[]): Object;
/**
Writes a struct to the DataStream. Takes a structDefinition that gives the
types and a struct object that gives the values. Refer to readStruct for the
structure of structDefinition.
*
@param structDefinition Type definition of the struct.
@param struct The struct data object.
*/
writeStruct(structDefinition: Object, struct: Object): void;
/**
Read UCS-2 string of desired length and endianness from the DataStream.
*
@param length The length of the string to read.
@return The read string.
*/
readUCS2String(length: number): string;
/**
Read UCS-2 string of desired length and endianness from the DataStream.
*
@param length The length of the string to read.
@param endianness The endianness of the string data in the DataStream.
@return The read string.
*/
readUCS2String(length: number, endianness: boolean): string;
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
*
@param str The string to write.
*/
writeUCS2String(str: string): void;
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
*
@param str The string to write.
@param endianness The endianness to use for the written string data.
*/
writeUCS2String(str: string, endianness: boolean): void;
/**
Write a UCS-2 string of desired endianness to the DataStream. The
lengthOverride argument lets you define the number of characters to write.
If the string is shorter than lengthOverride, the extra space is padded with
zeroes.
*
@param str The string to write.
@param endianness The endianness to use for the written string data.
@param lengthOverride The number of characters to write.
*/
writeUCS2String(str: string, endianness: boolean, lengthOverride: number): void;
/**
Read a string of desired length and encoding from the DataStream.
*
@param length The length of the string to read in bytes.
@return The read string.
*/
readString(length: number): string;
/**
Read a string of desired length and encoding from the DataStream.
*
@param length The length of the string to read in bytes.
@param encoding The encoding of the string data in the DataStream. Defaults to ASCII.
@return The read string.
*/
readString(length: number, encoding: string): string;
/**
Writes a string of desired length and encoding to the DataStream.
*
@param s The string to write.
*/
writeString(s: string): void;
/**
Writes a string of desired length and encoding to the DataStream.
*
@param s The string to write.
@param encoding The encoding for the written string data. Defaults to ASCII.
*/
writeString(s: string, encoding: string): void;
/**
Writes a string of desired length and encoding to the DataStream.
*
@param s The string to write.
@param encoding The encoding for the written string data. Defaults to ASCII.
@param length The number of characters to write.
*/
writeString(s: string, encoding: string, length: number): void;
/**
Read null-terminated string of desired length from the DataStream. Truncates
the returned string so that the null byte is not a part of it.
*
@return The read string.
*/
readCString(): string;
/**
Read null-terminated string of desired length from the DataStream. Truncates
the returned string so that the null byte is not a part of it.
*
@param length The length of the string to read.
@return The read string.
*/
readCString(length: number): string;
/**
Writes a null-terminated string to DataStream and zero-pads it to length
bytes. If length is not given, writes the string followed by a zero.
If string is longer than length, the written part of the string does not have
a trailing zero.
*
@param s The string to write.
*/
writeCString(s: string): void;
/**
Writes a null-terminated string to DataStream and zero-pads it to length
bytes. If length is not given, writes the string followed by a zero.
If string is longer than length, the written part of the string does not have
a trailing zero.
*
@param s The string to write.
@param length The number of characters to write.
*/
writeCString(s: string, length: number): void;
/**
Reads an object of type t from the DataStream, passing struct as the thus-far
read struct to possible callbacks that refer to it. Used by readStruct for
reading in the values, so the type is one of the readStruct types.
*
@param t Type of the object to read.
@return Returns the object on successful read, null on unsuccessful.
*/
readType(t: Object): Object;
/**
Reads an object of type t from the DataStream, passing struct as the thus-far
read struct to possible callbacks that refer to it. Used by readStruct for
reading in the values, so the type is one of the readStruct types.
*
@param t Type of the object to read.
@param struct Struct to refer to when resolving length references and for calling callbacks.
@return Returns the object on successful read, null on unsuccessful.
*/
readType(t: Object, struct: Object): Object;
/**
Writes object v of type t to the DataStream.
*
@param t Type of data to write.
@param v Value of data to write.
@param struct Struct to pass to write callback functions.
*/
writeType(t: Object, v: Object, struct: Object): void;
}

View File

@@ -0,0 +1,11 @@
/// <reference path="FileSaver.d.ts" />
/**
* @summary Test for "saveAs" function.
*/
function testSaveAs() {
var data: Blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
var filename: string = 'hello world.txt';
saveAs(data, filename);
}

27
FileSaver/FileSaver.d.ts vendored Normal file
View File

@@ -0,0 +1,27 @@
// Type definitions for FileSaver.js
// Project: https://github.com/eligrey/FileSaver.js/
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* @summary Interface for "saveAs" function.
* @author Cyril Schumacher
* @version 1.0
*/
interface FileSaver {
(
/**
* @summary Data.
* @type {Blob}
*/
data: Blob,
/**
* @summary File name.
* @type {DOMString}
*/
filename: string
): void
}
declare var saveAs: FileSaver;

368
Finch/Finch-tests.ts Normal file
View File

@@ -0,0 +1,368 @@
/// <reference path="Finch.d.ts" />
function test_Finch() {
Finch.route("Hello/Route", function() {
return console.log("Well hello there! How you doin'?!");
});
Finch.route("Hello/Route/:someId", function(bindings) {
return console.log("Hey! Here's Some Id: " + bindings.someId);
});
Finch.route("Hello/Route/:someId", function(bindings, childCallback) {
console.log("Hey! Here's Some Id: " + bindings.someId);
return childCallback();
});
Finch.route("some/route", {
setup: function(bindings) {
return console.log("Some Route has been setup! :)");
},
load: function(bindings) {
return console.log("Some Route has been loaed! :D");
},
unload: function(bindings) {
return console.log("Some Route has been loaed! :(");
},
teardown: function(bindings) {
return console.log("Some Route has been torndown! :'(");
}
});
Finch.route("some/route", {
setup: function(bindings, childCallback) {
console.log("Some Route has been setup! :)");
return childCallback();
},
load: function(bindings, childCallback) {
console.log("Some Route has been loaed! :D");
return childCallback();
},
unload: function(bindings, childCallback) {
console.log("Some Route has been loaed! :(");
return childCallback();
},
teardown: function(bindings, childCallback) {
console.log("Some Route has been torndown! :'(");
return childCallback();
}
});
Finch.call("Some/Route");
Finch.route("Some/Route", function() {
return Finch.observe("hello", "foo", function(hello: any, foo: string) {
return console.log("" + hello + " and " + foo);
});
});
Finch.route("Some/Route", function() {
return Finch.observe(["hello", "foo"], function(hello: any, foo: any) {
return console.log("" + hello + " and " + foo);
});
});
Finch.route("Some/Route", function(bindings) {
return Finch.observe(function(params) {
});
});
Finch.navigate("Some/Route");
Finch.navigate("Some/Route", {
hello: 'world',
foo: 'bar'
});
Finch.navigate("Some/Route", {
foo: 'bar'
}, true);
Finch.navigate("Some/Route", true);
Finch.navigate({
hello: 'world2',
wow: 'wee'
});
Finch.navigate({
foo: 'bar',
wow: 'wee!!!'
});
Finch.navigate({
hello: 'world2'
}, true);
Finch.listen();
Finch.ignore();
Finch.abort();
//test from Finch
Finch.call("/foo/bar");
Finch.call("/foo/bar/123");
Finch.call("/foo/bar/123");
Finch.call("/foo/bar/123?x=Hello&y=World");
Finch.call("/foo/baz/456");
Finch.call("/quux/789?band=Sunn O)))&genre=Post-Progressive Fridgecore");
Finch.call("/foo/bar/baz");
Finch.call("/foo/bar/quux");
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/foo");
Finch.call("/foo");
Finch.call("/");
Finch.call("/");
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/foo/bar?baz=quux");
Finch.call("/foo/bar?baz=xyzzy");
var cb: any;
Finch.route("foo", {
setup: cb.setup_foo = this.stub(),
load: cb.load_foo = this.stub(),
unload: cb.unload_foo = this.stub(),
teardown: cb.teardown_foo = this.stub()
});
Finch.route("[foo]/bar", {
setup: cb.setup_foo_bar = this.stub(),
load: cb.load_foo_bar = this.stub(),
unload: cb.unload_foo_bar = this.stub(),
teardown: cb.teardown_foo_bar = this.stub()
});
Finch.route("[foo/bar]/:id", {
setup: cb.setup_foo_bar_id = this.stub(),
load: cb.load_foo_bar_id = this.stub(),
unload: cb.unload_foo_bar_id = this.stub(),
teardown: cb.teardown_foo_bar_id = this.stub()
});
Finch.route("[foo]/baz", {
setup: cb.setup_foo_baz = this.stub(),
load: cb.load_foo_baz = this.stub(),
unload: cb.unload_foo_baz = this.stub(),
teardown: cb.teardown_foo_baz = this.stub()
});
Finch.route("[foo/baz]/:id", {
setup: cb.setup_foo_baz_id = this.stub(),
load: cb.load_foo_baz_id = this.stub(),
unload: cb.unload_foo_baz_id = this.stub(),
teardown: cb.teardown_foo_baz_id = this.stub()
});
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/foo");
Finch.call("/foo/bar/123?x=abc");
Finch.call("/foo/bar/456?x=aaa&y=zzz");
Finch.call("/foo/bar/456?x=bbb&y=zzz");
Finch.call("/foo/bar/456?y=zzz&x=bbb");
Finch.call("/foo/baz/789");
Finch.call("/foo/baz/abc?term=Hello");
Finch.call("/foo/baz/abc?term=World");
Finch.route("bar", this.stub());
Finch.call("/foo");
Finch.call("/bar");
Finch.route("/", function() {
});
Finch.route("[/]home", function() {
});
Finch.route("[/home]/news", {
setup: function() {
},
load: function() {
},
unload: function() {
return true;
},
teardown: function() {
return false;
}
});
Finch.route("/foo", {
setup: function() {
return true;
},
load: function() {
return true;
},
unload: function() {
},
teardown: function() {
}
});
Finch.route("[/]bar", {
setup: function() {
},
load: function() {
},
unload: function() {
},
teardown: function() {
}
});
Finch.call("/bar");
Finch.call("/home/news");
Finch.call("/foo");
Finch.call("/home/news");
Finch.call("/bar");
Finch.route("baz", this.stub());
Finch.call("/foo");
Finch.call("/foo/bar");
Finch.call("/baz");
Finch.route("/home", {
setup: function(bindings, next) {
return next();
},
load: function(bindings, next) {
return next();
},
unload: function(bindings, next) {
return next();
},
teardown: function(bindings, next) {
return next();
}
});
Finch.route("[/home]/news", {
setup: function(bindings, next) {
return next();
},
load: function(bindings, next) {
return next();
},
unload: function(bindings, next) {
return next();
},
teardown: function(bindings, next) {
return next();
}
});
Finch.call("/home");
Finch.call("/home/news");
Finch.call("/foo");
Finch.route("/", function(bindings) {
return Finch.observe(["x"], function(x) {
});
});
Finch.call("/?x=123");
Finch.call("/?x=123.456");
Finch.call("/?x=true");
Finch.call("/?x=false");
Finch.call("/?x=stuff");
Finch.options({
CoerceParameterTypes: true
});
Finch.call("/?x=123");
Finch.call("/?x=123.456");
Finch.call("/?x=true");
Finch.call("/?x=false");
Finch.call("/?x=stuff");
Finch.route("/:x", function(_arg) {
});
Finch.call("/123");
Finch.call("/123.456");
Finch.call("/true");
Finch.call("/false");
Finch.call("/stuff");
Finch.options({
CoerceParameterTypes: true
});
Finch.call("/123");
Finch.call("/123.456");
Finch.call("/true");
Finch.call("/false");
Finch.call("/stuff");
Finch.navigate("/home");
Finch.navigate("/home/news");
Finch.navigate("/home");
Finch.navigate("/home", {
foo: "bar"
});
Finch.navigate("/home", {
hello: "world"
});
Finch.navigate({
foos: "bars"
});
Finch.navigate({
foos: "baz"
});
Finch.navigate({
hello: "world"
}, true);
Finch.navigate({
foos: null
}, true);
Finch.navigate("/home/news", true);
Finch.navigate("/hello world", {});
Finch.navigate("/hello world", {
foo: "bar bar"
});
Finch.navigate({
foo: "baz baz"
});
Finch.navigate({
hello: 'world world'
}, true);
Finch.navigate("/home?foo=bar", {
hello: "world"
});
Finch.navigate("/home?foo=bar", {
hello: "world",
foo: "baz"
});
Finch.navigate("/home?foo=bar", {
hello: "world",
free: "bird"
});
Finch.navigate("#/home", true);
Finch.navigate("#/home");
Finch.navigate("#/home/news", {
free: "birds",
hello: "worlds"
});
Finch.navigate("#/home/news", {
foo: "bar"
}, true);
Finch.navigate("/home/news");
Finch.navigate("../");
Finch.navigate("./");
Finch.navigate("./news");
Finch.navigate("/home/news/article");
Finch.navigate("../../account");
Finch.listen();
Finch.ignore();
Finch.route("/home", function(bindings, continuation) {
});
Finch.route("/foo", function(bindings, continuation) {
});
Finch.call("home");
Finch.call("foo");
Finch.abort();
Finch.call("foo");
Finch.route("/", {
'setup': cb.slash_setup = this.stub(),
'load': cb.slash_load = this.stub(),
'unload': cb.slash_unload = this.stub(),
'teardown': cb.slash_teardown = this.stub()
});
Finch.route("[/]users/profile", {
'setup': cb.profile_setup = this.stub(),
'load': cb.profile_load = this.stub(),
'unload': cb.profile_unload = this.stub(),
'teardown': cb.profile_teardown = this.stub()
});
Finch.route("[/]:page", {
'setup': cb.page_setup = this.stub(),
'load': cb.page_load = this.stub(),
'unload': cb.page_unload = this.stub(),
'teardown': cb.page_teardown = this.stub()
});
Finch.call("/users");
}

47
Finch/Finch.d.ts vendored Normal file
View File

@@ -0,0 +1,47 @@
// Type definitions for Finch 0.5.13
// Project: https://github.com/stoodder/finchjs
// Definitions by: David Sichau <https://github.com/DavidSichau>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface FinchCallback {
(bindings?: any, childCallback? : () => void): any;
}
interface ExpandedCallback {
setup?: FinchCallback;
load?: FinchCallback;
unload?: FinchCallback;
teardown?: FinchCallback;
}
interface ObserveCallback {
(...args: any[]): string;
}
interface FinchOptions {
CoerceParameterTypes?: boolean;
}
interface FinchStatic {
route(route: string, callback: FinchCallback): void;
route(route: string, callbacks: ExpandedCallback): void;
call( uri: string ): void;
observe(argN: string[], callback: (params: ObserveCallback ) => void): void;
observe(callback: (params: ObserveCallback) => void): void;
observe(...args: any[]): void;
navigate(uri:string, queryParams?:any, doUpdate?:boolean ): void;
navigate(uri:string, doUpdate:boolean ): void;
navigate(queryParams:any, doUpdate?:boolean ): void;
listen(): boolean;
ignore(): boolean;
abort(): void;
options(options: FinchOptions): void;
}
declare var Finch: FinchStatic;
declare module "finch" {
export = Finch;
}

View File

@@ -0,0 +1,13 @@
/// <reference path="headroom.d.ts" />
new Headroom(document.getElementById('siteHead'));
new Headroom(document.getElementsByClassName('siteHead')[0]);
new Headroom(document.getElementsByClassName('siteHead')[0], {
tolerance: 34
});
new Headroom(document.getElementsByClassName('siteHead')[0], {
offset: 500
});

28
Headroom/headroom.d.ts vendored Normal file
View File

@@ -0,0 +1,28 @@
// Type definitions for headroom.js v0.7.0
// Project: http://wicky.nillia.ms/headroom.js/
// Definitions by: Jakub Olek <https://github.com/hakubo/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface HeadroomOptions {
offset?: number;
tolerance?: any;
classes?: {
initial?: string;
pinned?: string;
unpinned?: string;
top?: string;
notTop?: string;
};
scroller?: Element;
onPin?: () => void;
onUnPin?: () => void;
onTop?: () => void;
onNotTop?: () => void;
}
declare class Headroom {
constructor(element: Node, options?: HeadroomOptions);
constructor(element: Element, options?: HeadroomOptions);
init: () => void;
}

View File

@@ -0,0 +1,15 @@
/// <reference path="JSONStream.d.ts" />
import json = require('JSONStream');
var read: NodeJS.ReadableStream;
var write: NodeJS.WritableStream;
read = read.pipe(json.parse('*'));
read = read.pipe(json.parse(['foo/*', 'bar/*']));
read = json.stringify();
read = json.stringify('{', ',', '}');
read = json.stringifyObject();
read = json.stringifyObject('{', ',', '}');

22
JSONStream/JSONStream.d.ts vendored Normal file
View File

@@ -0,0 +1,22 @@
// Type definitions for JSONStream v0.8.0
// Project: http://github.com/dominictarr/JSONStream
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module 'JSONStream' {
export interface Options {
recurse: boolean;
}
export function parse(pattern: any): NodeJS.ReadWriteStream;
export function parse(patterns: any[]): NodeJS.ReadWriteStream;
export function stringify(): NodeJS.ReadWriteStream;
export function stringify(open: string, sep: string, close: string): NodeJS.ReadWriteStream;
export function stringifyObject(): NodeJS.ReadWriteStream;
export function stringifyObject(open: string, sep: string, close: string): NodeJS.ReadWriteStream;
}

View File

@@ -0,0 +1,115 @@
/// <reference path="PayPal-Cordova-Plugin.d.ts"/>
var item: PayPalItem;
item = new PayPalItem("name", 10, "25.00", "USD");
item = new PayPalItem("name", 10, "25.00", "USD", null);
item = new PayPalItem("name", 10, "25.00", "USD", "SKU_ID");
var item_name: string = item.name;
var item_quantity: number = item.quantity;
var item_price: string = item.price;
var item_currency: string = item.currency;
var item_sku: string = item.sku;
var paymentDetails: PayPalPaymentDetails;
paymentDetails = new PayPalPaymentDetails("10.50", "2.50", "1.25");
var paymentDetails_subtotal: string = paymentDetails.subtotal;
var paymentDetails_shipping: string = paymentDetails.shipping;
var paymentDetails_tax: string = paymentDetails.tax;
var shippingAddress: PayPalShippingAddress;
shippingAddress = new PayPalShippingAddress("name", "line1", "line2", "city", "state", "postalCode", "countryCode");
var shippingAddress_recipientName: string = shippingAddress.recipientName;
var shippingAddress_line1: string = shippingAddress.line1;
var shippingAddress_line2: string = shippingAddress.line2;
var shippingAddress_city: string = shippingAddress.city;
var shippingAddress_state: string = shippingAddress.state;
var shippingAddress_postalCode: string = shippingAddress.postalCode;
var shippingAddress_countryCode: string = shippingAddress.countryCode;
var payment: PayPalPayment;
payment = new PayPalPayment("10.00", "USD", "description", "Auth");
payment = new PayPalPayment("10.00", "USD", "description", "Auth", paymentDetails);
var payment_amount: string = payment.amount;
var payment_currency: string = payment.currency;
var payment_shortDescription: string = payment.shortDescription;
var payment_intent: string = payment.intent;
var payment_details: PayPalPaymentDetails = payment.details;
var payment_invoiceNumber: string = payment.invoiceNumber;
var payment_custom: string = payment.custom;
var payment_softDescriptor: string = payment.softDescriptor;
var payment_bnCode: string = payment.bnCode;
var payment_items: PayPalItem[] = [item, item, item];
var payment_shippingAddress: PayPalShippingAddress = shippingAddress;
var configOptions: PayPalConfigurationOptions = {
defaultUserEmail: "email",
defaultUserPhoneCountryCode: "countryCode",
defaultUserPhoneNumber: "phoneNumber",
merchantName: "merchantName",
merchantPrivacyPolicyURL: "merchantPrivacyPolicyURL",
merchantUserAgreementURL: "merchantUserAgreementURL",
acceptCreditCards: true,
payPalShippingAddressOption: 10,
rememberUser: true,
languageOrLocale: "languageOrLocal",
disableBlurWhenBackgrounding: true,
presentingInPopover: true,
forceDefaultsInSandbox: true,
sandboxUserPassword: "sandboxUserPassword",
sandboxUserPin: "sandboxUserPin"
};
var config: PayPalConfiguration;
config = new PayPalConfiguration();
config = new PayPalConfiguration(null);
config = new PayPalConfiguration(configOptions);
var config_defaultUserEmail: string = config.defaultUserEmail;
var config_defaultUserPhoneCountryCode: string = config.defaultUserPhoneCountryCode;
var config_defaultUserPhoneNumber: string = config.defaultUserPhoneNumber;
var config_merchantName: string = config.merchantName;
var config_merchantPrivacyPolicyURL: string = config.merchantPrivacyPolicyURL;
var config_merchantUserAgreementURL: string = config.merchantUserAgreementURL;
var config_acceptCreditCards: boolean = config.acceptCreditCards;
var config_payPalShippingAddressOption: number = config.payPalShippingAddressOption;
var config_rememberUser: boolean = config.rememberUser;
var config_languageOrLocale: string = config.languageOrLocale;
var config_disableBlurWhenBackgrounding: boolean = config.disableBlurWhenBackgrounding;
var config_presentingInPopover: boolean = config.presentingInPopover;
var config_forceDefaultsInSandbox: boolean = config.forceDefaultsInSandbox;
var config_sandboxUserPasword: string = config.sandboxUserPassword;
var config_sandboxUserPin: string = config.sandboxUserPin;
var clientIds: PayPalCordovaPlugin.PayPalClientIds = {
PayPalEnvironmentProduction: "",
PayPalEnvironmentSandbox: ""
};
var apiModule: PayPalCordovaPlugin.PayPalMobileStatic = PayPalMobile;
apiModule.version((result: string) => {});
apiModule.init(clientIds, () => {});
apiModule.prepareToRender("environment", config, () => {});
apiModule.renderSinglePaymentUI(payment, (result: any) => {}, (cancelReason: string) => {});
apiModule.applicationCorrelationIDForEnvironment("environment", (applicationCorrelationId: string) => {});
apiModule.clientMetadataID((clientMetadataId: string) => {});
apiModule.renderFuturePaymentUI((result: any) => {}, (cancelReason: string) => {});
apiModule.renderProfileSharingUI(["openid", "profile", "email"], (result: any) => {}, (cancelReason: string) => {});

View File

@@ -0,0 +1,615 @@
// Type definitions for PayPal-Cordova-Plugin 3.1.10
// Project: https://github.com/paypal/PayPal-Cordova-Plugin
// Definitions by: Justin Unterreiner <https://github.com/Justin-Credible>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
//#region paypal-mobile-js-helper.js
/**
* The PayPalItem class defines an optional itemization for a payment.
*
* @see https://developer.paypal.com/docs/api/#item-object for more details.
*/
declare class PayPalItem {
/**
* @param name Name of the item. 127 characters max.
* @param quantity Number of units. 10 characters max.
* @param price Unit price for this item 10 characters max.
* May be negative for "coupon" etc.
* @param currency ISO standard currency code.
* @param sku The stock keeping unit for this item. 50 characters max (optional).
*/
constructor(name: string, quantity: number, price: string, currency: string, sku?: string);
/**
* Name of the item. 127 characters max.
*/
name: string;
/**
* Number of units. 10 characters max.
*/
quantity: number;
/**
* Unit price for this item 10 characters max.
* May be negative for "coupon" etc.
*/
price: string;
/**
* ISO standard currency code.
*/
currency: string;
/**
* The stock keeping unit for this item. 50 characters max (optional).
*/
sku: string;
}
/**
* The PayPalPaymentDetails class defines optional amount details.
*
* @see https://developer.paypal.com/webapps/developer/docs/api/#details-object for more details.
*/
declare class PayPalPaymentDetails {
/**
* @param subtotal Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places.
* @param shipping Amount charged for shipping. 10 characters max with support for 2 decimal places.
* @param tax Amount charged for tax. 10 characters max with support for 2 decimal places.
*/
constructor(subtotal: string, shipping: string, tax: string);
/**
* Sub-total (amount) of items being paid for. 10 characters max with support for 2 decimal places.
*/
subtotal: string;
/**
* Amount charged for shipping. 10 characters max with support for 2 decimal places.
*/
shipping: string;
/**
* Amount charged for tax. 10 characters max with support for 2 decimal places.
*/
tax: string;
}
/**
* Convenience constructor. Returns a PayPalPayment with the specified amount, currency code, and short description.
*/
declare class PayPalPayment {
/**
* @param amount The amount of the payment.
* @param currencyCode The ISO 4217 currency for the payment.
* @param shortDescription A short descripton of the payment.
* @param intent • "Sale" for an immediate payment.
* • "Auth" for payment authorization only, to be captured separately at a later time.
* • "Order" for taking an order, with authorization and capture to be done separately at a later time.
* @param details PayPalPaymentDetails object (optional).
*/
constructor(amount: string, currency: string, shortDescription: string, intent: string, details?: PayPalPaymentDetails);
/**
* The amount of the payment.
*/
amount: string;
/**
* The ISO 4217 currency for the payment.
*/
currency: string;
/**
* A short descripton of the payment.
*/
shortDescription: string;
/**
* • "Sale" for an immediate payment.
* • "Auth" for payment authorization only, to be captured separately at a later time.
* • "Order" for taking an order, with authorization and capture to be done separately at a later time.
*/
intent: string;
/**
* PayPalPaymentDetails object (optional).
*/
details: PayPalPaymentDetails;
/**
* Optional invoice number, for your tracking purposes. (up to 256 characters).
*/
invoiceNumber: string;
/**
* Optional text, for your tracking purposes. (up to 256 characters).
*/
custom: string;
/**
* Optional text which will appear on the customer's credit card statement. (up to 22 characters).
*/
softDescriptor: string;
/**
* Optional Build Notation code ("BN code"), obtained from partnerprogram@paypal.com, for your tracking purposes.
*/
bnCode: string;
/**
* Optional array of PayPalItem objects.
* @see PayPalItem
* @note If you provide one or more items, be sure that the various prices correctly sum to the payment `amount` or to `paymentDetails.subtotal`.
*/
items: PayPalItem[];
/**
* Optional customer shipping address, if your app wishes to provide this to the SDK.
* @note make sure to set `payPalShippingAddressOption` in PayPalConfiguration to 1 or 3.
*/
shippingAddress: PayPalShippingAddress;
}
declare class PayPalShippingAddress {
/**
* @param recipientName Name of the recipient at this address. 50 characters max.
* @param line1 Line 1 of the address (e.g., Number, street, etc). 100 characters max.
* @param line2 Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional.
* @param city City name. 50 characters max.
* @param state 2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries.
* @param postalCode ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries.
* @param countryCode 2-letter country code. 2 characters max.
*/
constructor(recipientName: string, line1: string, line2: string, city: string, state: string, postalCode: string, countryCode: string);
/**
* Name of the recipient at this address. 50 characters max.
*/
recipientName: string;
/**
* Line 1 of the address (e.g., Number, street, etc). 100 characters max.
*/
line1: string;
/**
* Line 2 of the address (e.g., Suite, apt #, etc). 100 characters max. Optional.
*/
line2: string;
/**
* City name. 50 characters max.
*/
city: string;
/**
* 2-letter code for US states, and the equivalent for other countries. 100 characters max. Required in certain countries.
*/
state: string;
/**
* ZIP code or equivalent is usually required for countries that have them. 20 characters max. Required in certain countries.
*/
postalCode: string;
/**
* 2-letter country code. 2 characters max.
*/
countryCode: string;
}
declare class PayPalConfiguration {
/**
* @param options A set of options to use. Any options not specified will assume default values.
*/
constructor(options?: PayPalConfigurationOptions);
/**
* Will be overridden by email used in most recent PayPal login.
*/
defaultUserEmail: string;
/**
* Will be overridden by phone country code used in most recent PayPal login
*/
defaultUserPhoneCountryCode: string;
/**
* Will be overridden by phone number used in most recent PayPal login.
* @note If you set defaultUserPhoneNumber, be sure to also set defaultUserPhoneCountryCode.
*/
defaultUserPhoneNumber: string;
/**
* Your company name, as it should be displayed to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantName: string;
/**
* URL of your company's privacy policy, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantPrivacyPolicyURL: string;
/**
* URL of your company's user agreement, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantUserAgreementURL: string;
/**
* If set to false, the SDK will only support paying with PayPal, not with credit cards.
* This applies only to single payments (via PayPalPaymentViewController).
* Future payments (via PayPalFuturePaymentViewController) always use PayPal.
* Defaults to true.
*/
acceptCreditCards: boolean;
/**
* For single payments, options for the shipping address.
*
* - 0 - PayPalShippingAddressOptionNone: no shipping address applies.
*
* - 1 - PayPalShippingAddressOptionProvided: shipping address will be provided by your app,
* in the shippingAddress property of PayPalPayment.
*
* - 2 - PayPalShippingAddressOptionPayPal: user will choose from shipping addresses on file
* for their PayPal account.
*
* - 3 - PayPalShippingAddressOptionBoth: user will choose from the shipping address provided by your app,
* in the shippingAddress property of PayPalPayment, plus the shipping addresses on file for the user's PayPal account.
*
* Defaults to 0 (PayPalShippingAddressOptionNone).
*/
payPalShippingAddressOption: number;
/**
* If set to true, then if the user pays via their PayPal account,
* the SDK will remember the user's PayPal username or phone number;
* if the user pays via their credit card, then the SDK will remember
* the PayPal Vault token representing the user's credit card.
*
* If set to false, then any previously-remembered username, phone number, or
* credit card token will be erased, and subsequent payment information will
* not be remembered.
*
* Defaults to true.
*/
rememberUser: boolean;
/**
* If not set, or if set to nil, defaults to the device's current language setting.
*
* Can be specified as a language code ("en", "fr", "zh-Hans", etc.) or as a locale ("en_AU", "fr_FR", "zh-Hant_HK", etc.).
* If the library does not contain localized strings for a specified locale, then will fall back to the language. E.g., "es_CO" -> "es".
* If the library does not contain localized strings for a specified language, then will fall back to American English.
*
* If you specify only a language code, and that code matches the device's currently preferred language,
* then the library will attempt to use the device's current region as well.
* E.g., specifying "en" on a device set to "English" and "United Kingdom" will result in "en_GB".
*
* These localizations are currently included:
* da,de,en,en_AU,en_GB,en_SV,es,es_MX,fr,he,it,ja,ko,nb,nl,pl,pt,pt_BR,ru,sv,tr,zh-Hans,zh-Hant_HK,zh-Hant_TW.
*/
languageOrLocale: string;
/**
* Normally, the SDK blurs the screen when the app is backgrounded,
* to obscure credit card or PayPal account details in the iOS-saved screenshot.
* If your app already does its own blurring upon backgrounding, you might choose to disable this.
* Defaults to false.
*/
disableBlurWhenBackgrounding: boolean;
/**
* If you will present the SDK's view controller within a popover, then set this property to true.
* Defaults to false. (iOS only)
*/
presentingInPopover: boolean;
/**
* Sandbox credentials can be difficult to type on a mobile device. Setting this flag to true will
* cause the sandboxUserPassword and sandboxUserPin to always be pre-populated into login fields.
*
* This setting will have no effect if the operation mode is production.
* Defaults to false.
*/
forceDefaultsInSandbox: boolean;
/**
* Password to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPassword: string;
/**
* PIN to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPin: string;
}
/**
* Describes the options that can be passed into the PayPalConfiguration class constructor.
*/
interface PayPalConfigurationOptions {
/**
* Will be overridden by email used in most recent PayPal login.
*/
defaultUserEmail?: string;
/**
* Will be overridden by phone country code used in most recent PayPal login
*/
defaultUserPhoneCountryCode?: string;
/**
* Will be overridden by phone number used in most recent PayPal login.
* @note If you set defaultUserPhoneNumber, be sure to also set defaultUserPhoneCountryCode.
*/
defaultUserPhoneNumber?: string;
/**
* Your company name, as it should be displayed to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantName?: string;
/**
* URL of your company's privacy policy, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantPrivacyPolicyURL?: string;
/**
* URL of your company's user agreement, which will be offered to the user
* when requesting consent via a PayPalFuturePaymentViewController.
*/
merchantUserAgreementURL?: string;
/**
* If set to false, the SDK will only support paying with PayPal, not with credit cards.
* This applies only to single payments (via PayPalPaymentViewController).
* Future payments (via PayPalFuturePaymentViewController) always use PayPal.
* Defaults to true.
*/
acceptCreditCards?: boolean;
/**
* For single payments, options for the shipping address.
*
* - 0 - PayPalShippingAddressOptionNone?: no shipping address applies.
*
* - 1 - PayPalShippingAddressOptionProvided?: shipping address will be provided by your app,
* in the shippingAddress property of PayPalPayment.
*
* - 2 - PayPalShippingAddressOptionPayPal?: user will choose from shipping addresses on file
* for their PayPal account.
*
* - 3 - PayPalShippingAddressOptionBoth?: user will choose from the shipping address provided by your app,
* in the shippingAddress property of PayPalPayment, plus the shipping addresses on file for the user's PayPal account.
*
* Defaults to 0 (PayPalShippingAddressOptionNone).
*/
payPalShippingAddressOption?: number;
/**
* If set to true, then if the user pays via their PayPal account,
* the SDK will remember the user's PayPal username or phone number;
* if the user pays via their credit card, then the SDK will remember
* the PayPal Vault token representing the user's credit card.
*
* If set to false, then any previously-remembered username, phone number, or
* credit card token will be erased, and subsequent payment information will
* not be remembered.
*
* Defaults to true.
*/
rememberUser?: boolean;
/**
* If not set, or if set to nil, defaults to the device's current language setting.
*
* Can be specified as a language code ("en", "fr", "zh-Hans", etc.) or as a locale ("en_AU", "fr_FR", "zh-Hant_HK", etc.).
* If the library does not contain localized strings for a specified locale, then will fall back to the language. E.g., "es_CO" -> "es".
* If the library does not contain localized strings for a specified language, then will fall back to American English.
*
* If you specify only a language code, and that code matches the device's currently preferred language,
* then the library will attempt to use the device's current region as well.
* E.g., specifying "en" on a device set to "English" and "United Kingdom" will result in "en_GB".
*
* These localizations are currently included:
* da,de,en,en_AU,en_GB,en_SV,es,es_MX,fr,he,it,ja,ko,nb,nl,pl,pt,pt_BR,ru,sv,tr,zh-Hans,zh-Hant_HK,zh-Hant_TW.
*/
languageOrLocale?: string;
/**
* Normally, the SDK blurs the screen when the app is backgrounded,
* to obscure credit card or PayPal account details in the iOS-saved screenshot.
* If your app already does its own blurring upon backgrounding, you might choose to disable this.
* Defaults to false.
*/
disableBlurWhenBackgrounding?: boolean;
/**
* If you will present the SDK's view controller within a popover, then set this property to true.
* Defaults to false. (iOS only)
*/
presentingInPopover?: boolean;
/**
* Sandbox credentials can be difficult to type on a mobile device. Setting this flag to true will
* cause the sandboxUserPassword and sandboxUserPin to always be pre-populated into login fields.
*
* This setting will have no effect if the operation mode is production.
* Defaults to false.
*/
forceDefaultsInSandbox?: boolean;
/**
* Password to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPassword?: string;
/**
* PIN to use for sandbox if 'forceDefaultsInSandbox' is set.
*/
sandboxUserPin?: string;
}
//#endregion
//#region cdv-plugin-paypal-mobile-sdk.js
declare module PayPalCordovaPlugin {
export interface PayPalClientIds {
PayPalEnvironmentProduction: string;
PayPalEnvironmentSandbox: string;
}
/**
* Represents the portion of an object that is common to all responses.
*/
export interface BaseResult {
client: Client;
response_type: string;
}
/**
* Represents the client portion of the response.
*/
export interface Client {
paypal_sdk_version: string;
environment: string;
platform: string;
product_name: string;
}
/**
* Represents the response for a successful callback from renderSinglePaymentUI().
*/
export interface SinglePaymentResult extends BaseResult {
response: {
intent: string;
id: string;
state: string;
authorization_id: string;
create_time: string;
};
}
/**
* Represents the response for a successful callback from renderFuturePaymentUI().
*/
export interface FuturePaymentResult extends BaseResult {
response: {
code: string;
};
}
export interface PayPalMobileStatic {
/**
* Retrieve the version of the PayPal iOS SDK library. Useful when contacting support.
*
* @param completionCallback a callback function accepting a string
*/
version(completionCallback: (result: string) => void): void;
/**
* You MUST call this method to initialize the PayPal Mobile SDK.
*
* The PayPal Mobile SDK can operate in different environments to facilitate development and testing.
*
* @param clientIdsForEnvironments set of client ids for environments
* Example: var clientIdsForEnvironments = {
* PayPalEnvironmentProduction : @"my-client-id-for-Production",
* PayPalEnvironmentSandbox : @"my-client-id-for-Sandbox"
* }
* @param completionCallback a callback function on success
*/
init(clientIdsForEnvironments: PayPalCordovaPlugin.PayPalClientIds, completionCallback: () => void): void;
/**
* You must preconnect to PayPal to prepare the device for processing payments.
* This improves the user experience, by making the presentation of the
* UI faster. The preconnect is valid for a limited time, so
* the recommended time to preconnect is on page load.
*
* @param environment available options are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentProduction" and "PayPalEnvironmentSandbox"
* @param configuration PayPalConfiguration object, for Future Payments merchantName, merchantPrivacyPolicyURL
* and merchantUserAgreementURL must be set be set
* @param completionCallback a callback function on success
*/
prepareToRender(environment: string, configuration: PayPalConfiguration, completionCallback: () => void): void;
/**
* Start PayPal UI to collect payment from the user.
* See https://developer.paypal.com/webapps/developer/docs/integration/mobile/ios-integration-guide/
* for more documentation of the params.
*
* @param payment PayPalPayment object
* @param completionCallback a callback function accepting a js object, called when the user has completed payment
* @param cancelCallback a callback function accepting a reason string, called when the user cancels the payment
*/
renderSinglePaymentUI(payment: PayPalPayment, completionCallback: (result: PayPalCordovaPlugin.SinglePaymentResult) => void, cancelCallback: (cancelReason: string) => void): void;
/**
* @deprecated
* Once a user has consented to future payments, when the user subsequently initiates a PayPal payment
* from their device to be completed by your server, PayPal uses a Correlation ID to verify that the
* payment is originating from a valid, user-consented device+application.
* This helps reduce fraud and decrease declines.
* This method MUST be called prior to initiating a pre-consented payment (a "future payment") from a mobile device.
* Pass the result to your server, to include in the payment request sent to PayPal.
* Do not otherwise cache or store this value.
*
* @param environment available options are "PayPalEnvironmentNoNetwork", "PayPalEnvironmentProduction" and "PayPalEnvironmentSandbox"
* @param callback applicationCorrelationID Your server will send this to PayPal in a 'Paypal-Application-Correlation-Id' header.
*/
applicationCorrelationIDForEnvironment(environment: string, completionCallback: (applicationCorrelationId: string) => void): void;
/**
* Once a user has consented to future payments, when the user subsequently initiates a PayPal payment
* from their device to be completed by your server, PayPal uses a Correlation ID to verify that the
* payment is originating from a valid, user-consented device+application.
* This helps reduce fraud and decrease declines.
* This method MUST be called prior to initiating a pre-consented payment (a "future payment") from a mobile device.
* Pass the result to your server, to include in the payment request sent to PayPal.
* Do not otherwise cache or store this value.
*
* @param callback clientMetadataID Your server will send this to PayPal in a 'PayPal-Client-Metadata-Id' header.
*/
clientMetadataID(completionCallback: (clientMetadataId: string) => void): void;
/**
* Please Read Docs on Future Payments at https://github.com/paypal/PayPal-iOS-SDK#future-payments
*
* @param completionCallback a callback function accepting a js object with future payment authorization
* @param cancelCallback a callback function accepting a reason string, called when the user canceled without agreement
*/
renderFuturePaymentUI(completionCallback: (result: PayPalCordovaPlugin.FuturePaymentResult) => void, cancelCallback: (cancelReason: string) => void): void;
/**
* Please Read Docs on Profile Sharing at https://github.com/paypal/PayPal-iOS-SDK#profile-sharing
*
* @param scopes scopes Set of requested scope-values. Accepted scopes are: openid, profile, address, email, phone, futurepayments and paypalattributes
* See https://developer.paypal.com/docs/integration/direct/identity/attributes/ for more details
* @param completionCallback a callback function accepting a js object with future payment authorization
* @param cancelCallback a callback function accepting a reason string, called when the user canceled without agreement
*/
renderProfileSharingUI(scopes: string[], completionCallback: (result: any) => void, cancelCallback: (cancelReason: string) => void): void;
}
}
declare var PayPalMobile: PayPalCordovaPlugin.PayPalMobileStatic;
//#endregion

323
README.md Executable file → Normal file
View File

@@ -1,306 +1,43 @@
DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped)
===============
# DefinitelyTyped [![Build Status](https://travis-ci.org/borisyankov/DefinitelyTyped.png?branch=master)](https://travis-ci.org/borisyankov/DefinitelyTyped)
The repository for *high quality* TypeScript type definitions.
[![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)
> The repository for *high quality* TypeScript type definitions.
For more information see the [definitelytyped.org](http://definitelytyped.org) website.
## Usage
Usage
-----
Include a line like this:
```
```typescript
/// <reference path="jquery.d.ts" />
```
[TypeScript Directory: tools, libraries, projects and learning resources](https://github.com/DefinitelyTyped/typescript-directory)
## Contributions
Contributor Guidelines
----------------------
DefinitelyTyped only works because of contributions by users like you!
See the section: [How to contribute](https://github.com/borisyankov/DefinitelyTyped/wiki/How-to-contribute)
Please see the [contribution guide](http://definitelytyped.org/guides/contributing.html) on how to contribute to DefinitelyTyped.
Other means to get the definitions
----------------------------------
## How to get the definitions
* Directly from the Github repos
* [NuGet packages](http://nuget.org/packages?q=DefinitelyTyped)
* [TypeScript Definition package manager](https://github.com/DefinitelyTyped/tsd)
* [TypeScript Definition manager](https://github.com/DefinitelyTyped/tsd)
List of Definitions
-------------------
* [accounting.js](http://josscrowcroft.github.io/accounting.js/) (by [Sergey Gerasimov](https://github.com/gerich-home))
* [Ace Cloud9 Editor](http://ace.ajax.org/) (by [Diullei Gomes](https://github.com/Diullei))
* [Add To Home Screen] (http://cubiq.org/add-to-home-screen) (by [James Wilkins] (http://www.codeplex.com/site/users/view/jamesnw))
* [AmCharts](http://www.amcharts.com/) (by [Covobonomo](https://github.com/covobonomo/))
* [AngularFire](https://www.firebase.com/docs/angular/reference.html) (by [Dénes Harmath](https://github.com/thSoft))
* [AngularJS](http://angularjs.org) (by [Diego Vilar](https://github.com/diegovilar)) ([wiki](https://github.com/borisyankov/DefinitelyTyped/wiki/AngularJS-Definitions-Usage-Notes))
* [AngularUI](http://angular-ui.github.io/) (by [Michel Salib](https://github.com/michelsalib))
* [Angular Protractor](https://github.com/angular/protractor) (by [Bill Armstrong](https://github.com/BillArmstrong))
* [Angular Translate](http://pascalprecht.github.io/angular-translate/) (by [Michel Salib](https://github.com/michelsalib))
* [Angular UI Bootstrap](http://angular-ui.github.io/bootstrap) (by [Brian Surowiec](https://github.com/xt0rted))
* [AppFramework](http://app-framework-software.intel.com/) (by [Kyo Ago](https://github.com/kyo-ago))
* [Arbiter](http://arbiterjs.com/) (by [Arash Shakery](https://github.com/arash16))
* [asciify](https://github.com/olizilla/asciify) (by [Alan](http://alan.norbauer.com))
* [assert](https://github.com/Jxck/assert) (by [vvakame](https://github.com/vvakame))
* [async](https://github.com/caolan/async) (by [Boris Yankov](https://github.com/borisyankov))
* [Backbone.js](http://backbonejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Backbone Relational](http://backbonerelational.org/) (by [Eirik Hoem](https://github.com/eirikhm))
* [BigScreen](http://brad.is/coding/BigScreen/) (by [Douglas Eichelberger](https://github.com/dduugg))
* [Bluebird](https://github.com/petkaantonov/bluebird) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Bootbox](https://github.com/makeusabrew/bootbox) (by [Vincent Bortone](https://github.com/vbortone/))
* [Bootstrap](http://twitter.github.com/bootstrap/) (by [Boris Yankov](https://github.com/borisyankov))
* [bootstrap-notify](https://github.com/Nijikokun/bootstrap-notify) (by [Blake Niemyjski](https://github.com/niemyjski))
* [bootstrap.datepicker](https://github.com/eternicode/bootstrap-datepicker) (by [Boris Yankov](https://github.com/borisyankov))
* [Box2DWeb](http://code.google.com/p/box2dweb/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Breeze](http://www.breezejs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Browser Harness](https://github.com/scriby/browser-harness) (by [Chris Scribner](https://github.com/scriby))
* [CasperJS](http://casperjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker))
* [Cheerio](https://github.com/MatthewMueller/cheerio) (by [Bret Little](https://github.com/blittle))
* [Chosen](http://harvesthq.github.com/chosen/) (by [Boris Yankov](https://github.com/borisyankov))
* [Chrome](http://developer.chrome.com/extensions/) (by [Matthew Kimber](https://github.com/matthewkimber) and [otiai10](https://github.com/otiai10))
* [Chrome App](http://developer.chrome.com/apps/) (by [Adam Lay](https://github.com/AdamLay))
* [CKEditor](https://github.com/ckeditor/ckeditor-dev) (by [Ondrej Sevcik](https://github.com/ondrejsevcik))
* [CodeMirror](http://codemirror.net) (by [François de Campredon](https://github.com/fdecampredon))
* [Commander](http://github.com/visionmedia/commander.js) (by [Marcelo Dezem](https://github.com/mdezem))
* [configstore](http://github.com/yeoman/configstore) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Couchbase / Couchnode](https://github.com/couchbase/couchnode) (by [Basarat Ali Syed](https://github.com/basarat))
* [Crossfilter](https://github.com/square/crossfilter) (by [Schmulik Raskin](https://github.com/schmuli))
* [crypto-js](https://code.google.com/p/crypto-js/) (by [Gia Bảo @ Sân Đình](https://github.com/giabao)). @see [cryptojs.d.ts repo](https://github.com/giabao/cryptojs.d.ts)
* [d3.js](http://d3js.org/) (from TypeScript samples)
* [dhtmlxGantt](http://dhtmlx.com/docs/products/dhtmlxGantt) (by [Maksim Kozhukh](http://github.com/mkozhukh))
* [dhtmlxScheduler](http://dhtmlx.com/docs/products/dhtmlxScheduler) (by [Maksim Kozhukh](http://github.com/mkozhukh))
* [Dock Spawn](http://dockspawn.com) (by [Drew Noakes](https://drewnoakes.com))
* [docCookies](https://developer.mozilla.org/en-US/docs/Web/API/document.cookie) (by [Jon Egerton](https://github.com/jonegerton))
* [domo](http://domo-js.com/) (by [Steve Fenton](https://github.com/Steve-Fenton))
* [doT](https://github.com/olado/doT) (by [ZombieHunter](https://github.com/ZombieHunter))
* [dust](http://linkedin.github.com/dustjs) (by [Marcelo Dezem](https://github.com/mdezem))
* [EaselJS](http://www.createjs.com/#!/EaselJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [EasyStar](http://easystarjs.com/) (by [Magnus Gustafsson](https://github.com/Borundin))
* [ember.js](http://emberjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [EpicEditor](http://epiceditor.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [ES6-Promises](https://github.com/jakearchibald/ES6-Promises) (by [François de Campredon](https://github.com/fdecampredon/))
* [expect.js](https://github.com/LearnBoost/expect.js) (by [Teppei Sato](https://github.com/teppeis))
* [expectations](https://github.com/spmason/expectations) (by [vvakame](https://github.com/vvakame))
* [Express](http://expressjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Ext JS](http://www.sencha.com/products/extjs/) (by [Brian Kotek](https://github.com/brian428))
* [Fabric.js](http://fabricjs.com/) (by [Oliver Klemencic](https://github.com/oklemencic/))
* [Fancybox](http://fancybox.net/) (by [Boris Yankov](https://github.com/borisyankov))
* [File API: Directories and System](http://www.w3.org/TR/file-system-api/) (by [Kon](http://phyzkit.net/))
* [File API: Writer](http://www.w3.org/TR/file-writer-api/) (by [Kon](http://phyzkit.net/))
* [Finite State Machine](https://github.com/jakesgordon/javascript-state-machine) (by [Boris Yankov](https://github.com/borisyankov))
* [Firebase](https://www.firebase.com/docs/javascript/firebase) (by [Vincent Bortone](https://github.com/vbortone))
* [Firefox](https://developer.mozilla.org/en-US/docs/Web/API) (by [vvakame](https://github.com/vvakame))
* [FlexSlider](http://www.woothemes.com/flexslider/) (by [Diullei Gomes](https://github.com/Diullei))
* [Flight by Twitter](http://flightjs.github.com/flight/) (by [Jonathan Hedrén](https://github.com/jonathanhedren))
* [Foundation](http://foundation.zurb.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [FPSMeter](http://darsa.in/fpsmeter/) (by [Aaron Lampros](https://github.com/alampros))
* [FullCalendar](http://arshaw.com/fullcalendar/) (by [Neil Stalker](https://github.com/nestalk))
* [Gamepad](http://www.w3.org/TR/gamepad/) (by [Kon](http://phyzkit.net/))
* [Giraffe](https://github.com/barc/backbone.giraffe) (by [Matt McCray](https://github.com/darthapo))
* [glDatePicker](http://glad.github.com/glDatePicker/) (by [Dániel Tar](https://github.com/qcz))
* [GoJS](http://gojs.net/) (by [Barbara Duckworth](https://github.com/barbara42))
* [Greasemonkey](http://www.greasespot.net/) (by [Kota Saito](https://github.com/kotas))
* [GreenSock Animation Platform (GSAP)](http://www.greensock.com/get-started-js/) (by [Robert S.](https://github.com/codeBelt))
* [Grunt JS](http://gruntjs.com/) (by [Jeff May](https://github.com/jeffmay), [Basarat Ali Syed](https://github.com/basarat) and [San Chen](https://github.com/bigsan))
* [Google API Client](https://code.google.com/p/google-api-javascript-client/) (by [Frank M](https://github.com/sgtfrankieboy))
* [Google App Engine Channel API](https://developers.google.com/appengine/docs/java/channel/javascript) (by [vvakame](https://github.com/vvakame))
* [GoogleMaps](https://developers.google.com/maps/) (by [Esben Nepper](https://github.com/eNepper))
* [GoogleMaps InfoBubble](http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobubble/) (by [Johan Nilsson](https://github.com/dashue))
* [Google Geolocation](https://code.google.com/p/geo-location-javascript/) (by [Vincent Bortone](https://github.com/vbortone))
* [Google Page Speed Online API](https://developers.google.com/speed/pagespeed/) (by [Frank M](https://github.com/sgtfrankieboy))
* [Google Translate API](https://developers.google.com/translate/) (by [Frank M](https://github.com/sgtfrankieboy))
* [Google Url Shortener](https://developers.google.com/url-shortener/) (by [Frank M](https://github.com/sgtfrankieboy))
* [Hammer.js](http://eightmedia.github.com/hammer.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [Handlebars](http://handlebarsjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [HashSet](http://www.timdown.co.uk/jshashtable/jshashset.html) (by [Sergey Gerasimov](https://github.com/gerich-home))
* [Hashtable](http://www.timdown.co.uk/jshashtable/) (by [Sergey Gerasimov](https://github.com/gerich-home))
* [Highcharts](http://www.highcharts.com/) (by [damianog](https://github.com/damianog))
* [Highland](http://highlandjs.org/) (by [Bart van der Schoor](https://github.com/Bartvds/))
* [highlight.js](https://github.com/isagalaev/highlight.js) (by [Niklas Mollenhauer](https://github.com/nikeee))
* [History.js](https://github.com/browserstate/history.js) (by [Boris Yankov](https://github.com/borisyankov))
* [Html2Canvas.js](https://github.com/niklasvh/html2canvas/) (by [Richard Hepburn](https://github.com/rwhepburn))
* [Humane.js](http://wavded.github.com/humane-js/) (by [John Vrbanac](https://github.com/jmvrbanac))
* [i18next](http://i18next.com/) (by [Maarten Docter](https://github.com/mdocter))
* [iCheck](http://damirfoy.com/iCheck/) (by [Dániel Tar](https://github.com/qcz))
* [Impress.js](https://github.com/bartaz/impress.js) (by [Boris Yankov](https://github.com/borisyankov))
* [iScroll](http://cubiq.org/iscroll-4) (by [Boris Yankov](https://github.com/borisyankov) and [Christiaan Rakowski](https://github.com/csrakowski))
* [IxJS (Interactive extensions)](https://github.com/Reactive-Extensions/IxJS) (by [Igor Oleinikov](https://github.com/Igorbek))
* [jake](https://github.com/mde/jake) (by [Kon](http://phyzkit.net/))
* [Jasmine](http://pivotal.github.com/jasmine/) (by [Boris Yankov](https://github.com/borisyankov))
* [Jasmine-jQuery](https://github.com/velesin/jasmine-jquery) (by [Gregor Stamac](https://github.com/gstamac))
* [JointJS](http://www.jointjs.com/) (by [Aidan Reel](http://github.com/areel))
* [jQRangeSlider](http://ghusse.github.com/jQRangeSlider) (by [Dániel Tar](https://github.com/qcz))
* [jQuery](http://jquery.com/) (from TypeScript samples)
* [jQuery Mobile](http://jquerymobile.com) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery UI](http://jqueryui.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.Address](https://github.com/asual/jquery-address) (by [Martin Duparc](https://github.com/martinduparc/))
* [jQuery.areYouSure](https://github.com/codedance/jquery.AreYouSure) (by [Jon Egerton](https://github.com/jonegerton))
* [jQuery.autosize](http://www.jacklmoore.com/autosize/) (by [Jack Moore](http://www.jacklmoore.com/))
* [jQuery.BBQ](http://benalman.com/projects/jquery-bbq-plugin/) (by [Adam R. Smith](https://github.com/sunetos))
* [jQuery.CLEditor](http://premiumsoftware.net/CLEditor) (by [Jeffery Grajkowski](https://github.com/pushplay))
* [jQuery.clientSideLogging](https://github.com/remybach/jQuery.clientSideLogging/) (by [Diullei Gomes](https://github.com/diullei/))
* [jQuery.Colorbox](http://www.jacklmoore.com/colorbox/) (by [Gidon Junge](https://github.com/gjunge))
* [jQuery.contextMenu](http://medialize.github.com/jQuery-contextMenu/) (by [Natan Vivo](https://github.com/nvivo/))
* [jQuery.Cookie](https://github.com/carhartl/jquery-cookie) (by [Roy Goode](https://github.com/RoyGoode))
* [jQuery.Cycle](http://jquery.malsup.com/cycle/) (by [François Guillot](http://fguillot.developpez.com/))
* [jQuery.Cycle2](http://jquery.malsup.com/cycle2/) (by [Donny Nadolny](https://github.com/dnadolny))
* [jQuery.dataTables](http://www.datatables.net) (by [Armin Sander](https://github.com/pragmatrix))
* [jQuery.datetimepicker](http://trentrichardson.com/examples/timepicker/) (by [Doug McDonald](https://github.com/dougajmcdonald))
* [jQuery.dynatree](http://code.google.com/p/dynatree/) (by [François de Campredon](https://github.com/fdecampredon))
* [jQuery.Flot](http://www.flotcharts.org/) (by [Matt Burland](https://github.com/burlandm))
* [jQuery.form](http://malsup.com/jquery/form/) (by [François Guillot](http://fguillot.developpez.com/))
* [jQuery.Globalize](https://github.com/jquery/globalize) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.gridster](http://gridster.net) (by [Josh Baldwin](https://github.com/jbaldwin/gridster.d.ts))
* [jQuery.jNotify](http://jnotify.codeplex.com) (by [James Curran](https://github.com/jamescurran/))
* [jQuery.joyride](http://zurb.com/playground/jquery-joyride-feature-tour-plugin) (by [Vincent Bortone](https://github.com/vbortone))
* [jQuery.jSignature] (https://github.com/willowsystems/jSignature) (by [Patrick Magee](https://github.com/pjmagee))
* [jQuery.noty](http://needim.github.io/noty/) (by [Aaron King](https://github.com/kingdango/))
* [jQuery.pickadate](https://github.com/amsul/pickadate.js) (by [Theodore Brown](https://github.com/theodorejb))
* [jQuery.payment](http://needim.github.io/noty/) (by [Eric J. Smith](https://github.com/ejsmith/))
* [jQuery.pnotify](http://sciactive.github.io/pnotify/ (by [David Sichau](https://github.com/DavidSichau/))
* [jQuery.scrollTo](https://github.com/flesler/jquery.scrollTo) (by [Neil Stalker](https://github.com/nestalk/))
* [jQuery.simplePagination](https://github.com/flaviusmatis/simplePagination.js) (by [Natan Vivo](https://github.com/nvivo/))
* [jquery.superLink](http://james.padolsey.com/demos/plugins/jQuery/superLink/superlink.jquery.js) (by [Blake Niemyjski](https://github.com/niemyjski))
* [jQuery.timeago](http://timeago.yarp.com/) (by [François Guillot](http://fguillot.developpez.com/))
* [jQuery.Timepicker](http://fgelinas.com/code/timepicker/) (by [Anwar Javed](https://github.com/anwarjaved))
* [jQuery.Timer](http://jchavannes.com/jquery-timer/demo) (by [Joshua Strobl](https://github.com/JoshStrobl))
* [jQuery.TinyCarousel](http://baijs.nl/tinycarousel/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.TinyScrollbar](http://baijs.nl/tinyscrollbar/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [jQuery.tooltipster] (https://github.com/iamceege/tooltipster) (by [Patrick Magee](https://github.com/pjmagee))
* [jQuery.Transit](http://ricostacruz.com/jquery.transit/) (by [MrBigDog2U](https://github.com/MrBigDog2U))
* [jQuery.Validation](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (by [Boris Yankov](https://github.com/borisyankov))
* [jQuery.Watermark](http://jquery-watermark.googlecode.com) (by [Anwar Javed](https://github.com/anwarjaved))
* [jQuery.base64](https://github.com/yatt/jquery.base64) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki))
* [js-git](https://github.com/creationix/js-git) (by [Bart van der Schoor](https://github.com/Bartvds))
* [js-yaml](https://github.com/nodeca/js-yaml) (by [Bart van der Schoor](https://github.com/Bartvds/))
* [jScrollPane](http://jscrollpane.kelvinluck.com) (by [Dániel Tar](https://github.com/qcz))
* [JSDeferred](http://cho45.stfuawsc.com/jsdeferred/) (by [Daisuke Mino](https://github.com/minodisk))
* [JSONEditorOnline](https://github.com/josdejong/jsoneditoronline) (by [Vincent Bortone](https://github.com/vbortone/))
* [JSON-Pointer](https://www.npmjs.org/package/json-pointer) (by [Bart van der Schoor](https://github.com/Bartvds))
* [JsRender](http://www.jsviews.com/#jsrender) (by [Kensuke MATSUZAKI](https://github.com/zakki))
* [jStorage](http://www.jstorage.info/) (by [Danil Flores](https://github.com/dflor003/))
* [JWPlayer](http://developer.longtailvideo.com/trac/) (by [Martin Duparc](https://github.com/martinduparc/))
* [KeyboardJS](https://github.com/RobertWHurst/KeyboardJS) (by [Vincent Bortone](https://github.com/vbortone/))
* [KineticJS](http://kineticjs.com/) (by [Basarat Ali Syed](https://github.com/basarat))
* [Knockback](http://kmalakoff.github.com/knockback/) (by [Marcel Binot](https://github.com/docgit))
* [Knockout.js](http://knockoutjs.com/) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.DeferredUpdates](https://github.com/mbest/knockout-deferred-updates) (by [Sebastián Galiano](https://github.com/sgaliano))
* [Knockout.ES5](https://github.com/SteveSanderson/knockout-es5) (by [Sebastián Galiano](https://github.com/sgaliano))
* [Knockout.Mapper](https://github.com/LucasLorentz/knockout.mapper) (by [Brandon Meyer](https://github.com/BMeyerKC))
* [Knockout.Mapping](https://github.com/SteveSanderson/knockout.mapping) (by [Boris Yankov](https://github.com/borisyankov))
* [Knockout.Postbox](https://github.com/rniemeyer/knockout-postbox) (by [Judah Gabriel Himango](https://github.com/JudahGabriel))
* [Knockout.Rx](https://github.com/Igorbek/knockout.rx) (by [Igor Oleinikov](https://github.com/Igorbek))
* [Knockout.Validation](https://github.com/ericmbarnard/Knockout-Validation) (by [Dan Ludwig](https://github.com/danludwig))
* [Knockout.Viewmodel](http://coderenaissance.github.com/knockout.viewmodel/) (by [Oisin Grehan](https://github.com/oising))
* [ko.editables](http://romanych.github.com/ko.editables/) (by [Oisin Grehan](https://github.com/oising))
* [KoLite](https://github.com/CodeSeven/kolite) (by [Boris Yankov](https://github.com/borisyankov))
* [Lazy.js](http://danieltao.com/lazy.js/) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Leaflet](https://github.com/Leaflet/Leaflet) (by [Vladimir](https://github.com/rgripper))
* [Libxmljs](https://github.com/polotek/libxmljs) (by [François de Campredon](https://github.com/fdecampredon))
* [ladda](https://github.com/hakimel/Ladda) (by [Danil Flores](https://github.com/dflor003))
* [Levelup](https://github.com/rvagg/node-levelup) (by [Bret Little](https://github.com/blittle))
* [linq.js](http://linqjs.codeplex.com/) (by [Marcin Najder](https://github.com/marcinnajder))
* [Livestamp.js](https://github.com/mattbradley/livestampjs) (by [Vincent Bortone](https://github.com/vbortone))
* [localForage](https://github.com/mozilla/localForage) (by [david pichsenmeister](https://github.com/3x14159265))
* [Lodash](http://lodash.com/) (by [Brian Zengel](https://github.com/bczengel))
* [Logg](https://github.com/dpup/node-logg) (by [Bret Little](https://github.com/blittle))
* [Marked](https://github.com/chjj/marked) (by [William Orr](https://github.com/worr))
* [mCustomScrollbar](https://github.com/malihu/malihu-custom-scrollbar-plugin) (by [Sarah Williams](https://github.com/flurg))
* [Meteor](https://www.meteor.com) (by [Dave Allen](https://github.com/fullflavedave))
* [Microsoft Live Connect](http://msdn.microsoft.com/en-us/library/live/hh243643.aspx) (by [John Vilk](https://github.com/jvilk))
* [minimist](https://github.com/substack/minimist) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Modernizr](http://modernizr.com/) (by [Boris Yankov](https://github.com/borisyankov) and [Theodore Brown](https://github.com/theodorejb/))
* [Moment.js](https://github.com/timrwood/moment) (by [Michael Lakerveld](https://github.com/Lakerfield))
* [MongoDB](http://mongodb.github.io/node-mongodb-native/) (from TypeScript samples, updated by [Niklas Mollenhauer](https://github.com/nikeee))
* [Mousetrap](http://craig.is/killing/mice) (by [Dániel Tar](https://github.com/qcz))
* [msgpack.js](https://github.com/uupaa/msgpack.js) (by [Shinya Mochizuki](https://github.com/enrapt-mochizuki))
* [Mustache.js](https://github.com/janl/mustache.js) (by [Boris Yankov](https://github.com/borisyankov))
* [Node.js](http://nodejs.org/) (from TypeScript samples)
* [node_redis](https://github.com/mranney/node_redis) (by [Boris Yankov](https://github.com/borisyankov))
* [node-ffi](https://github.com/rbranson/node-ffi) (by [Paul Loyd](https://github.com/loyd))
* [node-git](https://github.com/christkv/node-git) (by [vvakame](https://github.com/vvakame))
* [node_zeromq](https://github.com/JustinTulloss/zeromq.node) (by [Dave McKeown](https://github.com/davemckeown))
* [node-sqlserver](https://github.com/WindowsAzure/node-sqlserver) (by [Boris Yankov](https://github.com/borisyankov))
* [NProgress](https://github.com/rstacruz/nprogress) (by [Judah Gabriel Himango](https://github.com/judahgabriel))
* [Numeral.js](https://github.com/adamwdraper/Numeral-js) (by [Vincent Bortone](https://github.com/vbortone/))
* [OpenLayers](https://github.com/openlayers/openlayers) (by [Ilya Bolkhovsky](https://github.com/bolhovsky/))
* [Passport](http://passportjs.org/) (by [Hiroki Horiuchi](https://github.com/horiuchi/))
* [Parallel.js](https://github.com/adambom/parallel.js) (by [Josh Baldwin](https://github.com/jbaldwin))
* [Parsimmon](https://github.com/jayferd/parsimmon) (by [Bart van der Schoor](https://github.com/Bartvds))
* [PDF.js](https://github.com/mozilla/pdf.js) (by [Josh Baldwin](https://github.com/jbaldwin))
* [PEG.js](http://pegjs.majda.cz/) (by [vvakame](https://github.com/vvakame))
* [Persona](http://www.mozilla.org/en-US/persona) (by [James Frasca](https://github.com/Nycto))
* [PhantomJS](http://phantomjs.org) (by [Jed Hunsaker](https://github.com/jedhunsaker))
* [PhoneGap](http://phonegap.com) (by [Boris Yankov](https://github.com/borisyankov))
* [PixiJS](https://github.com/GoodBoyDigital/pixi.js) (by [Pedro Casaubon](https://github.com/xperiments))
* [Platform](https://github.com/bestiejs/platform.js) (by [Jake Hickman](https://github.com/JakeH))
* [PouchDB](http://pouchdb.com) (by [Bill Sears](https://github.com/MrBigDog2U/))
* [PreloadJS](http://www.createjs.com/#!/PreloadJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [Q](https://github.com/kriskowal/q) (by Barrie Nemetchek, Andrew Gaspar)
* [Q-io](https://github.com/kriskowal/q-io) (by [Bart van der Schoor](https://github.com/Bartvds))
* [QUnit](http://qunitjs.com/) (by [Diullei Gomes](https://github.com/Diullei))
* [Raven.js](https://github.com/getsentry/raven-js) (by [Santi Albo](https://github.com/santialbo))
* [Rickshaw](http://code.shutterstock.com/rickshaw/) (by [Blake Niemyjski](https://github.com/niemyjski))
* [Riot.js](https://github.com/moot/riotjs) (by [vvakame](https://github.com/vvakame))
* [Restify](https://github.com/mcavage/node-restify) (by [Bret Little](https://github.com/blittle))
* [Royalslider](http://dimsemenov.com/plugins/royal-slider/) (by [Christiaan Rakowski](https://github.com/csrakowski))
* [Rx.js](http://rx.codeplex.com/) (by [gsino](http://www.codeplex.com/site/users/view/gsino), [Igor Oleinikov](https://github.com/Igorbek), [Carl de Billy](http://carl.debilly.net/), [zoetrope](https://github.com/zoetrope))
* [Raphael](http://raphaeljs.com/) (by [CheCoxshall](https://github.com/CheCoxshall))
* [Restangular](https://github.com/mgonto/restangular/) (by [Boris Yankov](https://github.com/borisyankov))
* [require.js](http://requirejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Sammy.js](http://sammyjs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Select2](http://ivaynberg.github.com/select2/) (by [Boris Yankov](https://github.com/borisyankov))
* [Selenium WebDriverJS](https://code.google.com/p/selenium/) (by [Bill Armstrong](https://github.com/BillArmstrong))
* [Semver](https://github.com/isaacs/node-semver) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Sencha Touch](http://www.sencha.com/products/touch/) (by [Brian Kotek](https://github.com/brian428))
* [SharePoint](http://sptypescript.codeplex.com) (by [Stanislav Vyshchepan](http://gandjustas.blogspot.ru) and [Andrey Markeev](http://markeev.com))
* [SignalR](http://www.asp.net/signalr) (by [Boris Yankov](https://github.com/borisyankov))
* [simple-cw-node](https://github.com/astronaughts/simple-cw-node) (by [vvakame](https://github.com/vvakame))
* [Sinon](http://sinonjs.org/) (by [William Sears](https://github.com/mrbigdog2u))
* [SlickGrid](https://github.com/mleibman/SlickGrid) (by [Josh Baldwin](https://github.com/jbaldwin))
* [smoothie](https://github.com/joewalnes/smoothie) (by [Mike H. Hawley](https://github.com/mikehhawley) and [Drew Noakes](https://drewnoakes.com))
* [socket.io](http://socket.io) (by [William Orr](https://github.com/worr))
* [socket.io-client](http://socket.io) (by [Maido Kaara](https://github.com/v3rm0n))
* [SockJS](https://github.com/sockjs/sockjs-client) (by [Emil Ivanov](https://github.com/vladev))
* [SoundJS](http://www.createjs.com/#!/SoundJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [Spin](http://fgnass.github.com/spin.js/) (by [Boris Yankov](https://github.com/borisyankov))
* [stripe](https://stripe.com/) (by [Eric J. Smith](https://github.com/ejsmith/))
* [Store.js](https://github.com/marcuswestin/store.js/) (by [Vincent Bortone](https://github.com/vbortone))
* [Sugar](http://sugarjs.com/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Swiper](http://www.idangero.us/sliders/swiper) (by [Sebastián Galiano](https://github.com/sgaliano))
* [SwipeView](http://cubiq.org/swipeview) (by [Boris Yankov](https://github.com/borisyankov))
* [TV4](https://github.com/geraintluff/tv4) (by [Bart van der Schoor](https://github.com/Bartvds))
* [Tags Manager](http://welldonethings.com/tags/manager) (by [Vincent Bortone](https://github.com/vbortone))
* [Teechart](http://www.steema.com) (by [Steema](http://www.steema.com))
* [three.js](http://mrdoob.github.com/three.js/) (by [Kon](http://phyzkit.net/))
* [Toastr](https://github.com/CodeSeven/toastr) (by [Boris Yankov](https://github.com/borisyankov))
* [trunk8](https://github.com/rviscomi/trunk8) (by [Blake Niemyjski](https://github.com/niemyjski))
* [TweenJS](http://www.createjs.com/#!/TweenJS) (by [Pedro Ferreira](https://bitbucket.org/drk4))
* [tween.js](https://github.com/sole/tween.js/) (by [Adam R. Smith](https://github.com/sunetos))
* [twitter-bootstrap-wizard](https://github.com/VinceG/twitter-bootstrap-wizard) (by [Blake Niemyjski](https://github.com/niemyjski))
* [Twitter Typeahead](http://twitter.github.io/typeahead.js) (by [Ivaylo Gochkov](https://github.com/igochkov))
* [Ubuntu Unity Web API](https://launchpad.net/libunity-webapps) (by [John Vrbanac](https://github.com/jmvrbanac))
* [Underscore.js](http://underscorejs.org/) (by [Boris Yankov](https://github.com/borisyankov))
* [Underscore.js (Typed)](http://underscorejs.org/) (by [Josh Baldwin](https://github.com/jbaldwin/))
* [Underscore-ko.js](https://github.com/kamranayub/UnderscoreKO) (by [Maurits Elbers](https://github.com/MagicMau))
* [universal-analytics](https://github.com/peaksandpies/universal-analytics) (by [Bart van der Schoor](https://github.com/Bartvds))
* [update-notifier](https://github.com/yeoman/update-notifier) (by [vvakame](https://github.com/vvakame))
* [uri-templates](https://github.com/geraintluff/uri-templates) (by [Bart van der Schoor](https://github.com/Bartvds))
* [urlrouter](https://github.com/fengmk2/urlrouter) (by [Carlos Ballesteros Velasco](https://github.com/soywiz))
* [UUID.js](https://github.com/LiosK/UUID.js) (by [Jason Jarrett](https://github.com/staxmanade))
* [Valerie](https://github.com/davewatts/valerie) (by [Howard Richards](https://github.com/conficient))
* [Viewporter](https://github.com/zynga/viewporter) (by [Boris Yankov](https://github.com/borisyankov))
* [Vimeo](http://developer.vimeo.com/player/js-api) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [WebRTC](http://dev.w3.org/2011/webrtc/editor/webrtc.html) (by [Ken Smith](https://github.com/smithkl42))
* [websocket](https://github.com/Worlize/WebSocket-Node) (by [Paul Loyd](https://github.com/loyd))
* [WinJS](http://msdn.microsoft.com/en-us/library/windows/apps/br229773.aspx) (from TypeScript samples)
* [WinRT](http://msdn.microsoft.com/en-us/library/windows/apps/br211377.aspx) (from TypeScript samples)
* [ws](http://einaros.github.io/ws/) (by [Paul Loyd](https://github.com/loyd))
* [XRegExp](http://xregexp.com/) (by [Bart van der Schoor](https://github.com/Bartvds))
* [YouTube](https://developers.google.com/youtube/) (by [Daz Wilkin](https://github.com/DazWilkin/))
* [YouTube Analytics API](https://developers.google.com/youtube/analytics/) (by [Frank M](https://github.com/sgtfrankieboy))
* [YouTube Data API](https://developers.google.com/youtube/v3/) (by [Frank M](https://github.com/sgtfrankieboy/))
* [Zepto.js](http://zeptojs.com/) (by [Josh Baldwin](https://github.com/jbaldwin))
* [Zynga Scroller](https://github.com/zynga/scroller) (by [Boris Yankov](https://github.com/borisyankov))
* [ZeroClipboard](https://github.com/jonrohan/ZeroClipboard) (by [Eric J. Smith](https://github.com/ejsmith))
## List of definitions
Requested Definitions
---------------------
Here is an updated list of [definitions people have requested](https://github.com/borisyankov/DefinitelyTyped/issues?labels=Definition%3ARequest)
* See [CONTRIBUTORS.md](CONTRIBUTORS.md)
## Requested definitions
Here is are the [currently requested definitions](https://github.com/borisyankov/DefinitelyTyped/labels/Definition%3ARequest).
## Licence
This project is licensed under the MIT license.
Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file.
[![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon)

View File

@@ -0,0 +1,10 @@
/// <reference path="_debugger.d.ts"/>
import _debugger = require("_debugger");
var {Client} = _debugger;
var client = new Client();
client.connect(8888, 'localhost');
client.listbreakpoints((err, res) => {
});

135
_debugger/_debugger.d.ts vendored Normal file
View File

@@ -0,0 +1,135 @@
// Type definitions for Node.js debugger API
// Project: http://nodejs.org/
// Definitions by: Basarat Ali Syed <https://github.com/basarat>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts"/>
declare module NodeJS {
export module _debugger {
export interface Packet {
raw: string;
headers: string[];
body: Message;
}
export interface Message {
seq: number;
type: string;
}
export interface RequestInfo {
command: string;
arguments: any;
}
export interface Request extends Message, RequestInfo {
}
export interface Event extends Message {
event: string;
body?: any;
}
export interface Response extends Message {
request_seq: number;
success: boolean;
/** Contains error message if success === false. */
message?: string;
/** Contains message body if success === true. */
body?: any;
}
export interface BreakpointMessageBody {
type: string;
target: number;
line: number;
}
export class Protocol {
res: Packet;
state: string;
execute(data: string): void;
serialize(rq: Request): string;
onResponse: (pkt: Packet) => void;
}
export var NO_FRAME: number;
export var port: number;
export interface ScriptDesc {
name: string;
id: number;
isNative?: boolean;
handle?: number;
type: string;
lineOffset?: number;
columnOffset?: number;
lineCount?: number;
}
export interface Breakpoint {
id: number;
scriptId: number;
script: ScriptDesc;
line: number;
condition?: string;
scriptReq?: string;
}
export interface RequestHandler {
(err: boolean, body: Message, res: Packet): void;
request_seq?: number;
}
export interface ResponseBodyHandler {
(err: boolean, body?: any): void;
request_seq?: number;
}
export interface ExceptionInfo {
text: string;
}
export interface BreakResponse {
script?: ScriptDesc;
exception?: ExceptionInfo;
sourceLine: number;
sourceLineText: string;
sourceColumn: number;
}
export function SourceInfo(body: BreakResponse): string;
export interface ClientInstance extends EventEmitter {
protocol: Protocol;
scripts: ScriptDesc[];
handles: ScriptDesc[];
breakpoints: Breakpoint[];
currentSourceLine: number;
currentSourceColumn: number;
currentSourceLineText: string;
currentFrame: number;
currentScript: string;
connect(port: number, host: string): void;
req(req: any, cb: RequestHandler): void;
reqFrameEval(code: string, frame: number, cb: RequestHandler): void;
mirrorObject(obj: any, depth: number, cb: ResponseBodyHandler): void;
setBreakpoint(rq: BreakpointMessageBody, cb: RequestHandler): void;
clearBreakpoint(rq: Request, cb: RequestHandler): void;
listbreakpoints(cb: RequestHandler): void;
reqSource(from: number, to: number, cb: RequestHandler): void;
reqScripts(cb: any): void;
reqContinue(cb: RequestHandler): void;
}
export var Client : {
new (): ClientInstance
}
}
}
declare module "_debugger"{
export = NodeJS._debugger;
}

View File

@@ -1 +0,0 @@
/// <reference path="typings/tsd.d.ts" />

View File

@@ -1 +0,0 @@
tsc runner.ts --target ES5 --out runner.js --module commonjs --sourcemap

File diff suppressed because it is too large Load Diff

View File

@@ -1,367 +0,0 @@
/// <reference path="typings/tsd.d.ts" />
/// <reference path="src/exec.ts" />
/// <reference path="src/file.ts" />
/// <reference path="src/tsc.ts" />
/// <reference path="src/timer.ts" />
/// <reference path="src/util.ts" />
/// <reference path="src/index.ts" />
/// <reference path="src/changes.ts" />
/// <reference path="src/printer.ts" />
/// <reference path="src/reporter/reporter.ts" />
/// <reference path="src/suite/suite.ts" />
/// <reference path="src/suite/syntax.ts" />
/// <reference path="src/suite/testEval.ts" />
/// <reference path="src/suite/tscParams.ts" />
module DT {
require('source-map-support').install();
// hacky typing
var Lazy: LazyJS.LazyStatic = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var os = require('os');
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var tsExp = /\.ts$/;
export var DEFAULT_TSC_VERSION = '0.9.7';
interface PackageJSON {
scripts: {[key:string]: string};
}
/////////////////////////////////
// Single test
/////////////////////////////////
export class Test {
constructor(public suite: ITestSuite, public tsfile: File, public options?: TscExecOptions) {
}
public run(): Promise<TestResult> {
return Tsc.run(this.tsfile.filePathWithName, this.options).then((execResult: ExecResult) => {
var testResult = new TestResult();
testResult.hostedBy = this.suite;
testResult.targetFile = this.tsfile;
testResult.options = this.options;
testResult.stdout = execResult.stdout;
testResult.stderr = execResult.stderr;
testResult.exitCode = execResult.exitCode;
return testResult;
});
}
}
/////////////////////////////////
// Parallel execute Tests
/////////////////////////////////
export class TestQueue {
private queue: Function[] = [];
private active: Test[] = [];
private concurrent: number;
constructor(concurrent: number) {
this.concurrent = Math.max(1, concurrent);
}
// add to queue and return a promise
run(test: Test): Promise<TestResult> {
var defer = Promise.defer();
// add a closure to queue
this.queue.push(() => {
// run it
var p = test.run();
p.then(defer.resolve.bind(defer), defer.reject.bind(defer));
p.finally(() => {
var i = this.active.indexOf(test);
if (i > -1) {
this.active.splice(i, 1);
}
this.step();
});
// return it
return test;
});
this.step();
// defer it
return defer.promise;
}
private step(): void {
while (this.queue.length > 0 && this.active.length < this.concurrent) {
this.active.push(this.queue.pop().call(null));
}
}
}
/////////////////////////////////
// Test results
/////////////////////////////////
export class TestResult {
hostedBy: ITestSuite;
targetFile: File;
options: TscExecOptions;
stdout: string;
stderr: string;
exitCode: number;
public get success(): boolean {
return this.exitCode === 0;
}
}
export interface ITestRunnerOptions {
tscVersion:string;
concurrent?:number;
testChanges?:boolean;
skipTests?:boolean;
printFiles?:boolean;
printRefMap?:boolean;
findNotRequiredTscparams?:boolean;
}
/////////////////////////////////
// The main class to kick things off
/////////////////////////////////
export class TestRunner {
private timer: Timer;
private suites: ITestSuite[] = [];
public changes: GitChanges;
public index: FileIndex;
public print: Print;
constructor(public dtPath: string, public options: ITestRunnerOptions = {tscVersion: DT.DEFAULT_TSC_VERSION}) {
this.options.findNotRequiredTscparams = !!this.options.findNotRequiredTscparams;
this.index = new FileIndex(this, this.options);
this.changes = new GitChanges(this);
this.print = new Print(this.options.tscVersion);
}
public addSuite(suite: ITestSuite): void {
this.suites.push(suite);
}
public checkAcceptFile(fileName: string): boolean {
var ok = tsExp.test(fileName);
ok = ok && fileName.indexOf('_infrastructure') < 0;
ok = ok && fileName.indexOf('node_modules/') < 0;
ok = ok && /^[a-z]/i.test(fileName);
return ok;
}
public run(): Promise<boolean> {
this.timer = new Timer();
this.timer.start();
this.print.printChangeHeader();
// only includes .d.ts or -tests.ts or -test.ts or .ts
return this.index.readIndex().then(() => {
return this.changes.readChanges();
}).then((changes: string[]) => {
this.print.printAllChanges(changes);
return this.index.collectDiff(changes);
}).then(() => {
this.print.printRemovals(this.index.removed);
this.print.printRelChanges(this.index.changed);
return this.index.parseFiles();
}).then(() => {
if (this.options.printRefMap) {
this.print.printRefMap(this.index, this.index.refMap);
}
if (Lazy(this.index.missing).some((arr: any[]) => arr.length > 0)) {
this.print.printMissing(this.index, this.index.missing);
this.print.printBoldDiv();
// bail
return Promise.cast(false);
}
if (this.options.printFiles) {
this.print.printFiles(this.index.files);
}
return this.index.collectTargets().then((files) => {
if (this.options.testChanges) {
this.print.printQueue(files);
return this.runTests(files);
}
else {
this.print.printTestAll();
return this.runTests(this.index.files)
}
}).then(() => {
return !this.suites.some((suite) => {
return suite.ngTests.length !== 0
});
});
});
}
private runTests(files: File[]): Promise<boolean> {
return Promise.attempt(() => {
assert(Array.isArray(files), 'files must be array');
var syntaxChecking = new SyntaxChecking(this.options);
var testEval = new TestEval(this.options);
if (!this.options.findNotRequiredTscparams) {
this.addSuite(syntaxChecking);
this.addSuite(testEval);
}
return Promise.all([
syntaxChecking.filterTargetFiles(files),
testEval.filterTargetFiles(files)
]);
}).spread((syntaxFiles, testFiles) => {
this.print.init(syntaxFiles.length, testFiles.length, files.length);
this.print.printHeader(this.options);
if (this.options.findNotRequiredTscparams) {
this.addSuite(new FindNotRequiredTscparams(this.options, this.print));
}
return Promise.reduce(this.suites, (count, suite: ITestSuite) => {
suite.testReporter = suite.testReporter || new DefaultTestReporter(this.print);
this.print.printSuiteHeader(suite.testSuiteName);
if (this.options.skipTests) {
this.print.printWarnCode('skipped test');
return Promise.cast(count++);
}
return suite.start(files, (testResult) => {
this.print.printTestComplete(testResult);
}).then((suite) => {
this.print.printSuiteComplete(suite);
return count++;
});
}, 0);
}).then((count) => {
this.timer.end();
this.finaliseTests(files);
});
}
private finaliseTests(files: File[]): void {
var testEval: TestEval = Lazy(this.suites).filter((suite) => {
return suite instanceof TestEval;
}).first();
if (testEval) {
var existsTestTypings: string[] = Lazy(testEval.testResults).map((testResult) => {
return testResult.targetFile.dir;
}).reduce((a: string[], b: string) => {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
}, []);
var typings: string[] = Lazy(files).map((file) => {
return file.dir;
}).reduce((a: string[], b: string) => {
return a.indexOf(b) < 0 ? a.concat([b]) : a;
}, []);
var withoutTestTypings: string[] = typings.filter((typing) => {
return existsTestTypings.indexOf(typing) < 0;
});
this.print.printDiv();
this.print.printTypingsWithoutTest(withoutTestTypings);
}
this.print.printDiv();
this.print.printTotalMessage();
this.print.printDiv();
this.print.printElapsedTime(this.timer.asString, this.timer.time);
this.suites.filter((suite: ITestSuite) => {
return suite.printErrorCount;
}).forEach((suite: ITestSuite) => {
this.print.printSuiteErrorCount(suite.errorHeadline, suite.ngTests.length, suite.testResults.length);
});
if (testEval) {
this.print.printSuiteErrorCount('Without tests', withoutTestTypings.length, typings.length, true);
}
this.print.printDiv();
if (this.suites.some((suite) => {
return suite.ngTests.length !== 0
})) {
this.print.printErrorsHeader();
this.suites.filter((suite) => {
return suite.ngTests.length !== 0;
}).forEach((suite) => {
suite.ngTests.forEach((testResult) => {
this.print.printErrorsForFile(testResult);
});
this.print.printBoldDiv();
});
}
}
}
var optimist: Optimist = require('optimist')(process.argv);
optimist.default('try-without-tscparams', false);
optimist.default('single-thread', false);
optimist.default('tsc-version', DEFAULT_TSC_VERSION);
optimist.default('test-changes', false);
optimist.default('skip-tests', false);
optimist.default('print-files', false);
optimist.default('print-refmap', false);
optimist.boolean('help');
optimist.describe('help', 'print help');
optimist.alias('h', 'help');
var argv: any = optimist.argv;
var dtPath = path.resolve(path.dirname((module).filename), '..', '..');
var cpuCores = os.cpus().length;
if (argv.help) {
optimist.showHelp();
var pkg: PackageJSON = require('../../package.json');
console.log('Scripts:');
console.log('');
Lazy(pkg.scripts).keys().each((key) => {
console.log(' $ npm run ' + key);
});
process.exit(0);
}
var testFull = process.env['TRAVIS_BRANCH'] ? /\w\/full$/.test(process.env['TRAVIS_BRANCH']) : false;
new TestRunner(dtPath, {
concurrent: argv['single-thread'] ? 1 : Math.max(Math.min(24, cpuCores), 2),
tscVersion: argv['tsc-version'],
testChanges: testFull ? false : argv['test-changes'], // allow magic branch
skipTests: argv['skip-tests'],
printFiles: argv['print-files'],
printRefMap: argv['print-refmap'],
findNotRequiredTscparams: argv['try-without-tscparam']
}).run().then((success) => {
if (!success) {
process.exit(1);
}
}).catch((err) => {
throw err;
process.exit(2);
});
}

View File

@@ -1,36 +0,0 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
module DT {
'use strict';
var fs = require('fs');
var path = require('path');
var Git = require('git-wrapper');
var Promise: typeof Promise = require('bluebird');
export class GitChanges {
git;
options = {};
constructor(private runner: TestRunner) {
var dir = path.join(this.runner.dtPath, '.git');
if (!fs.existsSync(dir)) {
throw new Error('cannot locate git-dir: ' + dir);
}
this.options['git-dir'] = dir;
this.git = new Git(this.options);
this.git.exec = Promise.promisify(this.git.exec);
}
public readChanges(): Promise<string[]> {
var opts = {};
var args = ['--name-only HEAD~1'];
return this.git.exec('diff', opts, args).then((msg: string) => {
return msg.replace(/^\s+/, '').replace(/\s+$/, '').split(/\r?\n/g);
});
}
}
}

View File

@@ -1,30 +0,0 @@
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
var nodeExec = require('child_process').exec;
export class ExecResult {
error;
stdout = '';
stderr = '';
exitCode: number;
}
export function exec(filename: string, cmdLineArgs: string[]): Promise<ExecResult> {
return new Promise((resolve) => {
var result = new ExecResult();
result.exitCode = null;
var cmdLine = filename + ' ' + cmdLineArgs.join(' ');
nodeExec(cmdLine, {maxBuffer: 1 * 1024 * 1024}, (error, stdout, stderr) => {
result.error = error;
result.stdout = stdout;
result.stderr = stderr;
result.exitCode = error ? error.code : 0;
resolve(result);
});
});
}
}

View File

@@ -1,46 +0,0 @@
/// <reference path="../_ref.d.ts" />
module DT {
'use strict';
var path = require('path');
export interface FileDict {
[fullPath:string]: File;
}
export interface FileArrDict {
[fullPath:string]: File[];
}
/////////////////////////////////
// Given a document root + ts file pattern this class returns:
// all the TS files OR just tests OR just definition files
/////////////////////////////////
export class File {
baseDir: string;
filePathWithName: string;
dir: string;
file: string;
ext: string;
fullPath: string;
references: File[] = [];
constructor(baseDir: string, filePathWithName: string) {
// why choose?
this.baseDir = baseDir;
this.filePathWithName = filePathWithName;
this.ext = path.extname(this.filePathWithName);
this.file = path.basename(this.filePathWithName, this.ext);
this.dir = path.dirname(this.filePathWithName);
this.fullPath = path.join(this.baseDir, this.dir, this.file + this.ext);
// lock it (shallow) (needs `use strict` in each file to work)
// Object.freeze(this);
}
toString(): string {
return '[File ' + this.filePathWithName + ']';
}
}
}

View File

@@ -1,208 +0,0 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
/// <reference path="util.ts" />
module DT {
'use strict';
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var Lazy: LazyJS.LazyStatic = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var readFile = Promise.promisify(fs.readFile);
/////////////////////////////////
// Track all files in the repo: map full path to File objects
/////////////////////////////////
export class FileIndex {
files: File[];
fileMap: FileDict;
refMap: FileArrDict;
options: ITestRunnerOptions;
changed: FileDict;
removed: FileDict;
missing: FileArrDict;
constructor(private runner: TestRunner, options: ITestRunnerOptions) {
this.options = options;
}
public hasFile(target: string): boolean {
return target in this.fileMap;
}
public getFile(target: string): File {
if (target in this.fileMap) {
return this.fileMap[target];
}
return null;
}
public setFile(file: File): void {
if (file.fullPath in this.fileMap) {
throw new Error('cannot overwrite file');
}
this.fileMap[file.fullPath] = file;
}
public readIndex(): Promise<void> {
this.fileMap = Object.create(null);
return Promise.promisify(glob).call(glob, '**/*.ts', {
cwd: this.runner.dtPath
}).then((filesNames: string[]) => {
this.files = Lazy(filesNames).filter((fileName) => {
return this.runner.checkAcceptFile(fileName);
}).map((fileName: string) => {
var file = new File(this.runner.dtPath, fileName);
this.fileMap[file.fullPath] = file;
return file;
}).toArray();
});
}
public collectDiff(changes: string[]): Promise<void> {
return new Promise((resolve) => {
// filter changes and bake map for easy lookup
this.changed = Object.create(null);
this.removed = Object.create(null);
Lazy(changes).filter((full) => {
return this.runner.checkAcceptFile(full);
}).uniq().each((local) => {
var full = path.resolve(this.runner.dtPath, local);
var file = this.getFile(full);
if (!file) {
// TODO figure out what to do here
// what does it mean? deleted?ss
file = new File(this.runner.dtPath, local);
this.setFile(file);
this.removed[full] = file;
// console.log('not in index? %', file.fullPath);
}
else {
this.changed[full] = file;
}
});
// console.log('changed:\n' + Object.keys(this.changed).join('\n'));
// console.log('removed:\n' + Object.keys(this.removed).join('\n'));
resolve();
});
}
public parseFiles(): Promise<void> {
return this.loadReferences(this.files).then(() => {
return this.getMissingReferences();
});
}
private getMissingReferences(): Promise<void> {
return Promise.attempt(() => {
this.missing = Object.create(null);
Lazy(this.removed).keys().each((removed) => {
if (removed in this.refMap) {
this.missing[removed] = this.refMap[removed];
}
});
});
}
private loadReferences(files: File[]): Promise<void> {
return new Promise((resolve, reject) => {
var queue = files.slice(0);
var active = [];
var max = 50;
var next = () => {
if (queue.length === 0 && active.length === 0) {
resolve();
return;
}
// queue paralel
while (queue.length > 0 && active.length < max) {
var file = queue.pop();
active.push(file);
this.parseFile(file).then((file) => {
active.splice(active.indexOf(file), 1);
next();
}).catch((err) => {
queue = [];
active = [];
reject(err);
});
}
};
next();
}).then(() => {
// bake reverse reference map (referenced to referrers)
this.refMap = Object.create(null);
Lazy(files).each((file) => {
Lazy(file.references).each((ref) => {
if (ref.fullPath in this.refMap) {
this.refMap[ref.fullPath].push(file);
}
else {
this.refMap[ref.fullPath] = [file];
}
});
});
});
}
// TODO replace with a stream?
private parseFile(file: File): Promise<File> {
return readFile(file.filePathWithName, {
encoding: 'utf8',
flag: 'r'
}).then((content) => {
file.references = Lazy(extractReferenceTags(content)).map((ref) => {
return path.resolve(path.dirname(file.fullPath), ref);
}).reduce((memo: File[], ref) => {
if (ref in this.fileMap) {
memo.push(this.fileMap[ref]);
}
else {
console.log('not mapped? -> ' + ref);
}
return memo;
}, []);
// return the object
return file;
});
}
public collectTargets(): Promise<File[]> {
return new Promise((resolve) => {
// map out files linked to changes
// - queue holds files touched by a change
// - pre-fill with actually changed files
// - loop queue, if current not seen:
// - add to result
// - from refMap queue all files referring to current
var result: FileDict = Object.create(null);
var queue = Lazy<File>(this.changed).values().toArray();
while (queue.length > 0) {
var next = queue.shift();
var fp = next.fullPath;
if (result[fp]) {
continue;
}
result[fp] = next;
if (fp in this.refMap) {
var arr = this.refMap[fp];
for (var i = 0, ii = arr.length; i < ii; i++) {
// just add it and skip expensive checks
queue.push(arr[i]);
}
}
}
resolve(Lazy<File>(result).values().toArray());
});
}
}
}

View File

@@ -1,281 +0,0 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
module DT {
var os = require('os');
/////////////////////////////////
// All the common things that we print are functions of this class
/////////////////////////////////
export class Print {
WIDTH = 77;
typings: number;
tests: number;
tsFiles: number
constructor(public version: string){
}
public init(typings: number, tests: number, tsFiles: number) {
this.typings = typings;
this.tests = tests;
this.tsFiles = tsFiles;
}
public out(s: any): Print {
process.stdout.write(s);
return this;
}
public repeat(s: string, times: number): string {
return new Array(times + 1).join(s);
}
public printChangeHeader() {
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mDefinitelyTyped Diff Detector 0.1.0\33[0m \n');
this.out('=============================================================================\n');
}
public printHeader(options: ITestRunnerOptions) {
var totalMem = Math.round(os.totalmem() / 1024 / 1024) + ' mb';
var freemem = Math.round(os.freemem() / 1024 / 1024) + ' mb';
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mDefinitelyTyped Test Runner 0.5.0\33[0m\n');
this.out('=============================================================================\n');
this.out(' \33[36m\33[1mTypescript version:\33[0m ' + this.version + '\n');
this.out(' \33[36m\33[1mTypings :\33[0m ' + this.typings + '\n');
this.out(' \33[36m\33[1mTests :\33[0m ' + this.tests + '\n');
this.out(' \33[36m\33[1mTypeScript files :\33[0m ' + this.tsFiles + '\n');
this.out(' \33[36m\33[1mTotal Memory :\33[0m ' + totalMem + '\n');
this.out(' \33[36m\33[1mFree Memory :\33[0m ' + freemem + '\n');
this.out(' \33[36m\33[1mCores :\33[0m ' + os.cpus().length + '\n');
this.out(' \33[36m\33[1mConcurrent :\33[0m ' + options.concurrent + '\n');
}
public printSuiteHeader(title: string) {
var left = Math.floor((this.WIDTH - title.length ) / 2) - 1;
var right = Math.ceil((this.WIDTH - title.length ) / 2) - 1;
this.out(this.repeat('=', left)).out(' \33[34m\33[1m');
this.out(title);
this.out('\33[0m ').out(this.repeat('=', right)).printBreak();
}
public printDiv() {
this.out('-----------------------------------------------------------------------------\n');
}
public printBoldDiv() {
this.out('=============================================================================\n');
}
public printErrorsHeader() {
this.out('=============================================================================\n');
this.out(' \33[34m\33[1mErrors in files\33[0m \n');
this.out('=============================================================================\n');
}
public printErrorsForFile(testResult: TestResult) {
this.out('----------------- For file:' + testResult.targetFile.filePathWithName);
this.printBreak().out(testResult.stderr).printBreak();
}
public printBreak(): Print {
this.out('\n');
return this;
}
public clearCurrentLine(): Print {
this.out('\r\33[K');
return this;
}
public printSuccessCount(current: number, total: number) {
var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1mSuccessful :\33[0m \33[32m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printFailedCount(current: number, total: number) {
var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1mFailure :\33[0m \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
public printTypingsWithoutTestsMessage() {
this.out(' \33[36m\33[1mTyping without tests\33[0m\n');
}
public printTotalMessage() {
this.out(' \33[36m\33[1mTotal\33[0m\n');
}
public printElapsedTime(time: string, s: number) {
this.out(' \33[36m\33[1mElapsed time :\33[0m ~' + time + ' (' + s + 's)\n');
}
public printSuiteErrorCount(errorHeadline: string, current: number, total: number, warn: boolean = false) {
var arb = (total === 0) ? 0 : (current / total);
this.out(' \33[36m\33[1m').out(errorHeadline).out(this.repeat(' ', 16 - errorHeadline.length));
if (warn) {
this.out(': \33[31m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
else {
this.out(': \33[33m\33[1m' + (arb * 100).toFixed(2) + '% (' + current + '/' + total + ')\33[0m\n');
}
}
public printSubHeader(file: string) {
this.out(' \33[36m\33[1m' + file + '\33[0m\n');
}
public printWarnCode(str: string) {
this.out(' \33[31m\33[1m<' + str.toLowerCase().replace(/ +/g, '-') + '>\33[0m\n');
}
public printLine(file: string) {
this.out(file + '\n');
}
public printElement(file: string) {
this.out(' - ' + file + '\n');
}
public printElement2(file: string) {
this.out(' - ' + file + '\n');
}
public printTypingsWithoutTestName(file: string) {
this.out(' - \33[33m\33[1m' + file + '\33[0m\n');
}
public printTypingsWithoutTest(withoutTestTypings: string[]) {
if (withoutTestTypings.length > 0) {
this.printTypingsWithoutTestsMessage();
this.printDiv();
withoutTestTypings.forEach((t) => {
this.printTypingsWithoutTestName(t);
});
}
}
public printTestComplete(testResult: TestResult): void {
var reporter = testResult.hostedBy.testReporter;
if (testResult.success) {
reporter.printPositiveCharacter(testResult);
}
else {
reporter.printNegativeCharacter(testResult);
}
}
public printSuiteComplete(suite: ITestSuite): void {
this.printBreak();
this.printDiv();
this.printElapsedTime(suite.timer.asString, suite.timer.time);
this.printSuccessCount(suite.okTests.length, suite.testResults.length);
this.printFailedCount(suite.ngTests.length, suite.testResults.length);
}
public printTests(adding: FileDict): void {
this.printDiv();
this.printSubHeader('Testing');
this.printDiv();
Object.keys(adding).sort().map((src) => {
this.printLine(adding[src].filePathWithName);
return adding[src];
});
}
public printQueue(files: File[]): void {
this.printDiv();
this.printSubHeader('Queued for testing');
this.printDiv();
files.forEach((file) => {
this.printLine(file.filePathWithName);
});
}
public printTestAll(): void {
this.printDiv();
this.printSubHeader('Ignoring changes, testing all files');
}
public printFiles(files: File[]): void {
this.printDiv();
this.printSubHeader('Files');
this.printDiv();
files.forEach((file) => {
this.printLine(file.filePathWithName);
file.references.forEach((file) => {
this.printElement(file.filePathWithName);
});
});
}
public printMissing(index: FileIndex, refMap: FileArrDict): void {
this.printDiv();
this.printSubHeader('Missing references');
this.printDiv();
Object.keys(refMap).sort().forEach((src) => {
var ref = index.getFile(src);
this.printLine('\33[31m\33[1m' + ref.filePathWithName + '\33[0m');
refMap[src].forEach((file) => {
this.printElement(file.filePathWithName);
});
});
}
public printAllChanges(paths: string[]): void {
this.printSubHeader('All changes');
this.printDiv();
paths.sort().forEach((line) => {
this.printLine(line);
});
}
public printRelChanges(changeMap: FileDict): void {
this.printDiv();
this.printSubHeader('Interesting files');
this.printDiv();
Object.keys(changeMap).sort().forEach((src) => {
this.printLine(changeMap[src].filePathWithName);
});
}
public printRemovals(changeMap: FileDict): void {
this.printDiv();
this.printSubHeader('Removed files');
this.printDiv();
Object.keys(changeMap).sort().forEach((src) => {
this.printLine(changeMap[src].filePathWithName);
});
}
public printRefMap(index: FileIndex, refMap: FileArrDict): void {
this.printDiv();
this.printSubHeader('Referring');
this.printDiv();
Object.keys(refMap).sort().forEach((src) => {
var ref = index.getFile(src);
this.printLine(ref.filePathWithName);
refMap[src].forEach((file) => {
this.printLine(' - ' + file.filePathWithName);
});
});
}
}
}

View File

@@ -1,42 +0,0 @@
/// <reference path="../../_ref.d.ts" />
/// <reference path="../printer.ts" />
module DT {
/////////////////////////////////
// Test reporter interface
// for example, . and x
/////////////////////////////////
export interface ITestReporter {
printPositiveCharacter(testResult: TestResult):void;
printNegativeCharacter(testResult: TestResult):void;
}
/////////////////////////////////
// Default test reporter
/////////////////////////////////
export class DefaultTestReporter implements ITestReporter {
index = 0;
constructor(public print: Print) {
}
public printPositiveCharacter(testResult: TestResult) {
this.print.out('\33[36m\33[1m' + '.' + '\33[0m');
this.index++;
this.printBreakIfNeeded(this.index);
}
public printNegativeCharacter( testResult: TestResult) {
this.print.out('x');
this.index++;
this.printBreakIfNeeded(this.index);
}
private printBreakIfNeeded(index: number) {
if (index % this.print.WIDTH === 0) {
this.print.printBreak();
}
}
}
}

View File

@@ -1,82 +0,0 @@
/// <reference path="../../runner.ts" />
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
/////////////////////////////////
// The interface for test suite
/////////////////////////////////
export interface ITestSuite {
testSuiteName:string;
errorHeadline:string;
filterTargetFiles(files: File[]): Promise<File[]>;
start(targetFiles: File[], testCallback: (result: TestResult, index: number) => void): Promise<ITestSuite>;
testResults:TestResult[];
okTests:TestResult[];
ngTests:TestResult[];
timer:Timer;
testReporter:ITestReporter;
printErrorCount:boolean;
}
/////////////////////////////////
// Base class for test suite
/////////////////////////////////
export class TestSuiteBase implements ITestSuite {
timer: Timer = new Timer();
testResults: TestResult[] = [];
testReporter: ITestReporter;
printErrorCount = true;
queue: TestQueue;
constructor(public options: ITestRunnerOptions, public testSuiteName: string, public errorHeadline: string) {
this.queue = new TestQueue(options.concurrent);
}
public filterTargetFiles(files: File[]): Promise<File[]> {
throw new Error('please implement this method');
}
public start(targetFiles: File[], testCallback: (result: TestResult) => void): Promise<ITestSuite> {
this.timer.start();
return this.filterTargetFiles(targetFiles).then((targetFiles) => {
// tests get queued for multi-threading
return Promise.all(targetFiles.map((targetFile) => {
return this.runTest(targetFile).then((result) => {
testCallback(result);
});
}));
}).then(() => {
this.timer.end();
return this;
});
}
public runTest(targetFile: File): Promise<TestResult> {
return this.queue.run(new Test(this, targetFile, {
tscVersion: this.options.tscVersion
})).then((result) => {
this.testResults.push(result);
return result;
});
}
public get okTests(): TestResult[] {
return this.testResults.filter((r) => {
return r.success;
});
}
public get ngTests(): TestResult[] {
return this.testResults.filter((r) => {
return !r.success
});
}
}
}

View File

@@ -1,26 +0,0 @@
/// <reference path="../../runner.ts" />
/// <reference path="../util.ts" />
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
var endDts = /\w\.d\.ts$/i;
/////////////////////////////////
// .d.ts syntax inspection
/////////////////////////////////
export class SyntaxChecking extends TestSuiteBase {
constructor(options: ITestRunnerOptions) {
super(options, 'Syntax checking', 'Syntax error');
}
public filterTargetFiles(files: File[]): Promise<File[]> {
return Promise.cast(files.filter((file) => {
return endDts.test(file.filePathWithName);
}));
}
}
}

View File

@@ -1,26 +0,0 @@
/// <reference path="../../runner.ts" />
/// <reference path="../util.ts" />
module DT {
'use strict';
var Promise: typeof Promise = require('bluebird');
var endTestDts = /\w-tests?\.ts$/i;
/////////////////////////////////
// Compile with *-tests.ts
/////////////////////////////////
export class TestEval extends TestSuiteBase {
constructor(options) {
super(options, 'Typing tests', 'Failed tests');
}
public filterTargetFiles(files: File[]): Promise<File[]> {
return Promise.cast(files.filter((file) => {
return endTestDts.test(file.filePathWithName);
}));
}
}
}

View File

@@ -1,59 +0,0 @@
/// <reference path='../../runner.ts' />
/// <reference path='../file.ts' />
module DT {
'use strict';
var fs = require('fs');
var Promise: typeof Promise = require('bluebird');
/////////////////////////////////
// Try compile without .tscparams
// It may indicate that it is compatible with --noImplicitAny maybe...
/////////////////////////////////
export class FindNotRequiredTscparams extends TestSuiteBase {
testReporter: ITestReporter;
printErrorCount = false;
constructor(options: ITestRunnerOptions, private print: Print) {
super(options, 'Find not required .tscparams files', 'New arrival!');
this.testReporter = {
printPositiveCharacter: (testResult: TestResult) => {
this.print
.clearCurrentLine()
.printTypingsWithoutTestName(testResult.targetFile.filePathWithName);
},
printNegativeCharacter: (testResult: TestResult) => {
}
}
}
public filterTargetFiles(files: File[]): Promise<File[]> {
return Promise.filter(files, (file) => {
return new Promise((resolve) => {
fs.exists(file.filePathWithName + '.tscparams', resolve);
});
});
}
public runTest(targetFile: File): Promise<TestResult> {
this.print.clearCurrentLine().out(targetFile.filePathWithName);
return this.queue.run(new Test(this, targetFile, {
tscVersion: this.options.tscVersion,
useTscParams: false,
checkNoImplicitAny: true
})).then((result) => {
this.testResults.push(result);
this.print.clearCurrentLine();
return result
});
}
public get ngTests(): TestResult[] {
// Do not show ng test results
return [];
}
}
}

View File

@@ -1,50 +0,0 @@
/// <reference path="../_ref.d.ts" />
/// <reference path="../runner.ts" />
module DT {
'use strict';
/////////////////////////////////
// Timer.start starts a timer
// Timer.end stops the timer and sets asString to the pretty print value
/////////////////////////////////
export class Timer {
startTime: number;
time = 0;
asString: string = '<not-started>'
public start() {
this.time = 0;
this.startTime = this.now();
this.asString = '<started>';
}
public now(): number {
return Date.now();
}
public end() {
this.time = (this.now() - this.startTime) / 1000;
this.asString = Timer.prettyDate(this.startTime, this.now());
}
public static prettyDate(date1: number, date2: number): string {
var diff = ((date2 - date1) / 1000);
var day_diff = Math.floor(diff / 86400);
if (isNaN(day_diff) || day_diff < 0 || day_diff >= 31) {
return null;
}
return (<string><any> (day_diff == 0 && (
diff < 60 && (diff + ' seconds') ||
diff < 120 && '1 minute' ||
diff < 3600 && Math.floor(diff / 60) + ' minutes' ||
diff < 7200 && '1 hour' ||
diff < 86400 && Math.floor(diff / 3600) + ' hours') ||
day_diff == 1 && 'Yesterday' ||
day_diff < 7 && day_diff + ' days' ||
day_diff < 31 && Math.ceil(day_diff / 7) + ' weeks'));
}
}
}

View File

@@ -1,54 +0,0 @@
/// <reference path='../_ref.d.ts' />
/// <reference path='../runner.ts' />
/// <reference path='exec.ts' />
module DT {
'use strict';
var fs = require('fs');
var Promise: typeof Promise = require('bluebird');
export interface TscExecOptions {
tscVersion?:string;
useTscParams?:boolean;
checkNoImplicitAny?:boolean;
}
export class Tsc {
public static run(tsfile: string, options: TscExecOptions): Promise<ExecResult> {
var tscPath;
return new Promise.attempt(() => {
options = options || {};
options.tscVersion = options.tscVersion || DEFAULT_TSC_VERSION;
if (typeof options.checkNoImplicitAny === 'undefined') {
options.checkNoImplicitAny = true;
}
if (typeof options.useTscParams === 'undefined') {
options.useTscParams = true;
}
return fileExists(tsfile);
}).then((exists) => {
if (!exists) {
throw new Error(tsfile + ' not exists');
}
tscPath = './_infrastructure/tests/typescript/' + options.tscVersion + '/tsc.js';
return fileExists(tscPath);
}).then((exists) => {
if (!exists) {
throw new Error(tscPath + ' is not exists');
}
return fileExists(tsfile + '.tscparams');
}).then((exists) => {
var command = 'node ' + tscPath + ' --module commonjs ';
if (options.useTscParams && exists) {
command += '@' + tsfile + '.tscparams';
}
else if (options.checkNoImplicitAny) {
command += '--noImplicitAny';
}
return exec(command, [tsfile]);
});
}
}
}

View File

@@ -1,40 +0,0 @@
/// <reference path="../_ref.d.ts" />
module DT {
'use strict';
var fs = require('fs');
var Lazy: LazyJS.LazyStatic = require('lazy.js');
var Promise: typeof Promise = require('bluebird');
var referenceTagExp = /<reference[ \t]*path=["']?([\w\.\/_-]*)["']?[ \t]*\/>/g;
export function endsWith(str: string, suffix: string) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
export function extractReferenceTags(source: string): string[] {
var ret: string[] = [];
var match: RegExpExecArray;
if (!referenceTagExp.global) {
throw new Error('referenceTagExp RegExp must have global flag');
}
referenceTagExp.lastIndex = 0;
while ((match = referenceTagExp.exec(source))) {
if (match.length > 0 && match[1].length > 0) {
ret.push(match[1]);
}
}
return ret;
}
export function fileExists(target: string): Promise<boolean> {
return new Promise((resolve, reject) => {
fs.exists(target, (bool: boolean) => {
resolve(bool);
});
});
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -1,2 +0,0 @@
#!/usr/bin/env node
require('./tsc.js')

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,252 +0,0 @@
// Type definitions for Lazy.js 0.3.2
// Project: https://github.com/dtao/lazy.js/
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module LazyJS {
interface LazyStatic {
<T>(value: T[]):ArrayLikeSequence<T>;
(value: any[]):ArrayLikeSequence<any>;
<T>(value: Object):ObjectLikeSequence<T>;
(value: Object):ObjectLikeSequence<any>;
(value: string):StringLikeSequence;
strict():LazyStatic;
generate<T>(generatorFn: GeneratorCallback<T>, length?: number):GeneratedSequence<T>;
range(to: number):GeneratedSequence<number>;
range(from: number, to: number, step?: number):GeneratedSequence<number>;
repeat<T>(value: T, count?: number):GeneratedSequence<T>;
on<T>(eventType: string):Sequence<T>;
readFile(path: string):StringLikeSequence;
makeHttpRequest(path: string):StringLikeSequence;
}
interface ArrayLike<T> {
length:number;
[index:number]:T;
}
interface Callback {
():void;
}
interface ErrorCallback {
(error: any):void;
}
interface ValueCallback<T> {
(value: T):void;
}
interface GetKeyCallback<T> {
(value: T):string;
}
interface TestCallback<T> {
(value: T):boolean;
}
interface MapCallback<T, U> {
(value: T):U;
}
interface MapStringCallback {
(value: string):string;
}
interface NumberCallback<T> {
(value: T):number;
}
interface MemoCallback<T, U> {
(memo: U, value: T):U;
}
interface GeneratorCallback<T> {
(index: number):T;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
interface Iterator<T> {
new (sequence: Sequence<T>):Iterator<T>;
current():T;
moveNext():boolean;
}
interface GeneratedSequence<T> extends Sequence<T> {
new(generatorFn: GeneratorCallback<T>, length: number):GeneratedSequence<T>;
length():number;
}
interface AsyncSequence<T> extends SequenceBase<T> {
each(callback: ValueCallback<T>):AsyncHandle<T>;
}
interface AsyncHandle<T> {
cancel():void;
onComplete(callback: Callback):void;
onError(callback: ErrorCallback):void;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module Sequence {
function define(methodName: string[], overrides: Object): Function;
}
interface Sequence<T> extends SequenceBase<T> {
each(eachFn: ValueCallback<T>):Sequence<T>;
}
interface SequenceBase<T> extends SequenceBaser<T> {
first():any;
first(count: number):Sequence<T>;
indexOf(value: any, startIndex?: number):Sequence<T>;
last():any;
last(count: number):Sequence<T>;
lastIndexOf(value: any):Sequence<T>;
reverse():Sequence<T>;
}
interface SequenceBaser<T> {
// TODO improve define() (needs ugly overload)
async(interval: number):AsyncSequence<T>;
chunk(size: number):Sequence<T>;
compact():Sequence<T>;
concat(var_args: T[]):Sequence<T>;
consecutive(length: number):Sequence<T>;
contains(value: T):boolean;
countBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
countBy(propertyName: string): ObjectLikeSequence<T>;
dropWhile(predicateFn: TestCallback<T>): Sequence<T>;
every(predicateFn: TestCallback<T>): boolean;
filter(predicateFn: TestCallback<T>): Sequence<T>;
find(predicateFn: TestCallback<T>): Sequence<T>;
findWhere(properties: Object): Sequence<T>;
flatten(): Sequence<T>;
groupBy(keyFn: GetKeyCallback<T>): ObjectLikeSequence<T>;
initial(count?: number): Sequence<T>;
intersection(var_args: T[]): Sequence<T>;
invoke(methodName: string): Sequence<T>;
isEmpty(): boolean;
join(delimiter?: string): string;
map<U>(mapFn: MapCallback<T, U>): Sequence<U>;
max(valueFn?: NumberCallback<T>): T;
min(valueFn?: NumberCallback<T>): T;
pluck(propertyName: string): Sequence<T>;
reduce<U>(aggregatorFn: MemoCallback<T, U>, memo?: U): U;
reduceRight<U>(aggregatorFn: MemoCallback<T, U>, memo: U): U;
reject(predicateFn: TestCallback<T>): Sequence<T>;
rest(count?: number): Sequence<T>;
shuffle(): Sequence<T>;
some(predicateFn?: TestCallback<T>): boolean;
sortBy(sortFn: NumberCallback<T>): Sequence<T>;
sortedIndex(value: T): Sequence<T>;
sum(valueFn?: NumberCallback<T>): Sequence<T>;
takeWhile(predicateFn: TestCallback<T>): Sequence<T>;
union(var_args: T[]): Sequence<T>;
uniq(): Sequence<T>;
where(properties: Object): Sequence<T>;
without(var_args: T[]): Sequence<T>;
zip(var_args: T[]): Sequence<T>;
toArray(): T[];
toObject(): Object;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ArrayLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ArrayLikeSequence<T> extends Sequence<T> {
// define()X;
concat(): ArrayLikeSequence<T>;
first(count?: number): ArrayLikeSequence<T>;
get(index: number): T;
length(): number;
map<U>(mapFn: MapCallback<T, U>): ArrayLikeSequence<U>;
pop(): ArrayLikeSequence<T>;
rest(count?: number): ArrayLikeSequence<T>;
reverse(): ArrayLikeSequence<T>;
shift(): ArrayLikeSequence<T>;
slice(begin: number, end?: number): ArrayLikeSequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module ObjectLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface ObjectLikeSequence<T> extends Sequence<T> {
assign(other: Object): ObjectLikeSequence<T>;
// throws error
//async(): X;
defaults(defaults: Object): ObjectLikeSequence<T>;
functions(): Sequence<T>;
get(property: string): ObjectLikeSequence<T>;
invert(): ObjectLikeSequence<T>;
keys(): Sequence<string>;
omit(properties: string[]): ObjectLikeSequence<T>;
pairs(): Sequence<T>;
pick(properties: string[]): ObjectLikeSequence<T>;
toArray(): T[];
toObject(): Object;
values(): Sequence<T>;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
module StringLikeSequence {
function define(methodName: string[], overrides: Object): Function;
}
interface StringLikeSequence extends SequenceBaser<string> {
charAt(index: number): string;
charCodeAt(index: number): number;
contains(value: string): boolean;
endsWith(suffix: string): boolean;
first(): string;
first(count: number): StringLikeSequence;
indexOf(substring: string, startIndex?: number): number;
last(): string;
last(count: number): StringLikeSequence;
lastIndexOf(substring: string, startIndex?: number): number;
mapString(mapFn: MapStringCallback): StringLikeSequence;
match(pattern: RegExp): StringLikeSequence;
reverse(): StringLikeSequence;
split(delimiter: string): StringLikeSequence;
split(delimiter: RegExp): StringLikeSequence;
startsWith(prefix: string): boolean;
substring(start: number, stop?: number): StringLikeSequence;
toLowerCase(): StringLikeSequence;
toUpperCase(): StringLikeSequence;
}
}
declare var Lazy: LazyJS.LazyStatic;
declare module 'lazy.js' {
export = Lazy;
}

View File

@@ -1,48 +0,0 @@
// https://github.com/substack/node-optimist
// sourced from https://github.com/soywiz/typescript-node-definitions/blob/master/optimist.d.ts
// rehacked by @Bartvds
declare module Optimist {
export interface Argv {
_: string[];
}
export interface Optimist {
default(name: string, value: any): Optimist;
default(args: any): Optimist;
boolean(name: string): Optimist;
boolean(names: string[]): Optimist;
string(name: string): Optimist;
string(names: string[]): Optimist;
wrap(columns): Optimist;
help(): Optimist;
showHelp(fn?: Function): Optimist;
usage(message: string): Optimist;
demand(key: string): Optimist;
demand(key: number): Optimist;
demand(key: string[]): Optimist;
alias(key: string, alias: string): Optimist;
describe(key: string, desc: string): Optimist;
options(key: string, opt: any): Optimist;
check(fn: Function);
parse(args: string[]): Optimist;
argv: Argv;
}
}
interface Optimist extends Optimist.Optimist {
(args: string[]): Optimist.Optimist;
}
declare module 'optimist' {
export = Optimist;
}

View File

@@ -1,4 +0,0 @@
/// <reference path="node/node.d.ts" />
/// <reference path="bluebird/bluebird.d.ts" />
/// <reference path="lazy.js/lazy.js.d.ts" />
/// <reference path="optimist/optimist.d.ts" />

View File

@@ -0,0 +1,36 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="acc-wizard.d.ts" />
/**
* @summary Test for "accwizard" without options.
*/
function testBasic() {
$('#test').accwizard();
}
/**
* @summary Test for "accwizard" with options.
*/
function testWithOptions() {
var options: AccWizardOptions = {
addButtons: true,
sidebar: '.acc-wizard-sidebar',
activeClass: 'acc-wizard-active',
completedClass: 'acc-wizard-completed',
todoClass: 'acc-wizard-todo',
stepClass: 'acc-wizard-step',
nextText: 'Next Step',
backText: 'Go Back',
nextType: 'submit',
backType: 'reset',
nextClasses: 'btn btn-primary',
backClasses: 'btn',
autoScrolling: true,
onNext: function() {},
onBack: function() {},
onInit: function() {},
onDestroy: function() {}
};
$('#test').accwizard(options);
}

113
acc-wizard/acc-wizard.d.ts vendored Normal file
View File

@@ -0,0 +1,113 @@
// Type definitions for acc-wizard
// Project: https://github.com/sathomas/acc-wizard
// Definitions by: Cyril Schumacher <https://github.com/cyrilschumacher>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface AccWizardOptions {
/**
* @summary Add next/prev buttons to panels.
* @type {boolean}
*/
addButtons: boolean;
/**
* @summary Selector for task sidebar.
* @type {string}
*/
sidebar: string;
/**
* @summary Class to indicate the active task in sidebar.
* @type {string}
*/
activeClass: string;
/**
* @summary Class to indicate task is complete.
* @type {string}
*/
completedClass: string;
/**
* @summary Class to indicate task is still pending.
* @type {string}
*/
todoClass: string;
/**
* @summary Class for step buttons within panels.
* @type {string}
*/
stepClass: string;
/**
* @summary Text for next button.
* @type {string}
*/
nextText: string;
/**
* @summary Text for back button.
* @type {string}
*/
backText: string;
/**
* @summary HTML input type for next button. (default: "submit")
* @type {string}
*/
nextType: string;
/**
* @summary HTML input type for back button. (default: "reset")
* @type {string}
*/
backType: string;
/**
* @summary Class(es) for next button.
* @type {string}
*/
nextClasses: string;
/**
* @summary Class(es) for back button.
* @type {string}
*/
backClasses: string;
/**
* @summary Auto-scrolling.
* @type {boolean}
*/
autoScrolling: boolean;
/**
* @summary Function to call on next step.
*/
onNext: Function;
/**
* @summary Function to call on back up.
*/
onBack: Function;
/**
* @summary A chance to hook initialization.
*/
onInit: Function;
/**
* @summary A chance to hook destruction.
*/
onDestroy: Function;
}
/**
* @summary Interface for "acc-wizard" JQuery plugin.
* @author Cyril Schumacher
* @version 1.0
*/
interface JQuery {
accwizard(options?: AccWizardOptions): void;
}

View File

@@ -0,0 +1 @@
--noImplicitAny

47
ace/ace.d.ts vendored
View File

@@ -576,7 +576,7 @@ declare module AceAjax {
/**
* Returns the current tab size.
**/
getTabSize(): string;
getTabSize(): number;
/**
* Returns `true` if the character at the position is a soft tab.
@@ -1034,6 +1034,9 @@ declare module AceAjax {
* Event sessions dealing with the mouse and keyboard are bubbled up from `Document` to the `Editor`, which decides what to do with them.
**/
export interface Editor {
addEventListener(ev: 'change', callback: (ev: EditorChangeEvent) => any);
addEventListener(ev: string, callback: Function);
inMultiSelectMode: boolean;
@@ -1060,6 +1063,31 @@ declare module AceAjax {
onChangeMode(e?);
execCommand(command:string, args?: any);
/**
* Sets a Configuration Option
**/
setOption(optionName: any, optionValue: any);
/**
* Sets Configuration Options
**/
setOptions(keyValueTuples: any);
/**
* Get a Configuration Option
**/
getOption(name: any):any;
/**
* Get Configuration Options
**/
getOptions():any;
/**
* Get rid of console warning by setting this to Infinity
**/
$blockScrolling:number;
/**
* Sets a new key handler, such as "vim" or "windows".
@@ -1710,6 +1738,13 @@ declare module AceAjax {
**/
new(renderer: VirtualRenderer, session?: IEditSession): Editor;
}
interface EditorChangeEvent {
start: Position;
end: Position;
action: string; // insert, remove
lines: any[];
}
////////////////////////////////
/// PlaceHolder
@@ -2574,6 +2609,16 @@ declare module AceAjax {
* Returns `true` if there are redo operations left to perform.
**/
hasRedo(): boolean;
/**
* Returns `true` if the dirty counter is 0
**/
isClean(): boolean;
/**
* Sets dirty counter to 0
**/
markClean(): void;
}
var UndoManager: {

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -1 +1 @@
""

View File

@@ -0,0 +1,16 @@
/// <reference path='acl.d.ts'/>
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
import mongodb = require('mongodb');
var db: mongodb.Db;
// Using the mongo db backend
var acl = new Acl(new Acl.mongodbBackend(db, 'acl_', true));
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);

View File

@@ -0,0 +1,16 @@
/// <reference path='acl.d.ts'/>
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
import redis = require('redis');
var client: redis.RedisClient;
// Using the redis backend
var acl = new Acl(new Acl.redisBackend(client, 'acl_'));
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);

65
acl/acl-tests.ts Normal file
View File

@@ -0,0 +1,65 @@
/// <reference path='acl.d.ts'/>
// Sample code from
// https://github.com/OptimalBits/node_acl/blob/master/Readme.md
import Acl = require('acl');
var report = <T>(err: Error, value: T) => {
if (err) {
console.error(err);
}
console.info(value);
};
// Using the memory backend
var acl = new Acl(new Acl.memoryBackend());
// guest is allowed to view blogs
acl.allow('guest', 'blogs', 'view');
// allow function accepts arrays as any parameter
acl.allow('member', 'blogs', ['edit','view', 'delete']);
acl.addUserRoles('joed', 'guest');
acl.addRoleParents('baz', ['foo','bar']);
acl.allow('foo', ['blogs','forums','news'], ['view', 'delete']);
acl.allow('admin', ['blogs','forums'], '*');
acl.allow([
{
roles:['guest','special-member'],
allows:[
{resources:'blogs', permissions:'get'},
{resources:['forums','news'], permissions:['get','put','delete']}
]
},
{
roles:['gold','silver'],
allows:[
{resources:'cash', permissions:['sell','exchange']},
{resources:['account','deposit'], permissions:['put','delete']}
]
}
]);
acl.isAllowed('joed', 'blogs', 'view', (err, res) => {
if (res) {
console.log("User joed is allowed to view blogs");
}
});
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
.then((result) => {
console.dir('jsmith is allowed blogs ' + result);
acl.addUserRoles('jsmith', 'member');
}).then(() =>
acl.isAllowed('jsmith', 'blogs', ['edit','view','delete'])
).then((result) =>
console.dir('jsmith is allowed blogs ' + result)
).then(() => {
acl.allowedPermissions('james', ['blogs','forums'], report);
acl.allowedPermissions('jsmith', ['blogs','forums'], report);
});

150
acl/acl.d.ts vendored Normal file
View File

@@ -0,0 +1,150 @@
// Type definitions for node_acl 0.4.7
// Project: https://github.com/optimalbits/node_acl
// Definitions by: Qubo <https://github.com/tkQubo>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path='../node/node.d.ts'/>
/// <reference path='../redis/redis.d.ts'/>
/// <reference path="../mongodb/mongodb.d.ts" />
declare module "acl" {
import http = require('http');
import Promise = require("bluebird");
type strings = string|string[];
type Value = string|number;
type Values = Value|Value[];
type Action = () => any;
type Callback = (err: Error) => any;
type AnyCallback = (err: Error, obj: any) => any;
type AllowedCallback = (err: Error, allowed: boolean) => any;
type GetUserId = (req: http.ServerRequest, res: http.ServerResponse) => Value;
interface AclStatic {
new (backend: Backend<any>, logger: Logger, options: Option): Acl;
new (backend: Backend<any>, logger: Logger): Acl;
new (backend: Backend<any>): Acl;
memoryBackend: MemoryBackendStatic;
}
interface Logger {
debug: (msg: string)=>any;
}
interface Acl {
addUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
removeUserRoles: (userId: Value, roles: strings, cb?: Callback) => Promise<void>;
userRoles: (userId: Value, cb?: (err: Error, roles: string[])=>any) => Promise<string[]>;
roleUsers: (role: Value, cb?: (err: Error, users: Values)=>any) => Promise<any>;
hasRole: (userId: Value, role: string, cb?: (err: Error, isInRole: boolean)=>any) => Promise<boolean>;
addRoleParents: (role: string, parents: Values, cb?: Callback) => Promise<void>;
removeRole: (role: string, cb?: Callback) => Promise<void>;
removeResource: (resource: string, cb?: Callback) => Promise<void>;
allow: {
(roles: Values, resources: strings, permissions: strings, cb?: Callback): Promise<void>;
(aclSets: AclSet|AclSet[]): Promise<void>;
}
removeAllow: (role: string, resources: strings, permissions: strings, cb?: Callback) => Promise<void>;
removePermissions: (role: string, resources: strings, permissions: strings, cb?: Function) => Promise<void>;
allowedPermissions: (userId: Value, resources: strings, cb?: AnyCallback) => Promise<void>;
isAllowed: (userId: Value, resources: strings, permissions: strings, cb?: AllowedCallback) => Promise<boolean>;
areAnyRolesAllowed: (roles: strings, resource: strings, permissions: strings, cb?: AllowedCallback) => Promise<any>;
whatResources: (roles: strings, permissions: strings, cb?: AnyCallback) => Promise<any>;
permittedResources: (roles: strings, permissions: strings, cb?: Function) => Promise<void>;
middleware: (numPathComponents: number, userId: Value|GetUserId, actions: strings) => Promise<any>;
}
interface Option {
buckets?: BucketsOption;
}
interface BucketsOption {
meta?: string;
parents?: string;
permissions?: string;
resources?: string;
roles?: string;
users?: string;
}
interface AclSet {
roles: strings;
allows: AclAllow[];
}
interface AclAllow {
resources: strings;
permissions: strings;
}
interface MemoryBackend extends Backend<Action[]> { }
interface MemoryBackendStatic {
new(): MemoryBackend;
}
//
// For internal use
//
interface Backend<T> {
begin: () => T;
end: (transaction: T, cb?: Action) => void;
clean: (cb?: Action) => void;
get: (bucket: string, key: Value, cb?: Action) => void;
union: (bucket: string, keys: Value[], cb?: Action) => void;
add: (transaction: T, bucket: string, key: Value, values: Values) => void;
del: (transaction: T, bucket: string, keys: Value[]) => void;
remove: (transaction: T, bucket: string, key: Value, values: Values) => void;
endAsync: Function; //TODO: Give more specific function signature
getAsync: Function;
cleanAsync: Function;
unionAsync: Function;
}
interface Contract {
(args: IArguments): Contract|NoOp;
debug: boolean;
fulfilled: boolean;
args: any[];
checkedParams: string[];
params: (...types: string[]) => Contract|NoOp;
end: () => void;
}
interface NoOp {
params: (...types: string[]) => NoOp;
end: () => void;
}
// for redis backend
import redis = require('redis');
interface AclStatic {
redisBackend: RedisBackendStatic;
}
interface RedisBackend extends Backend<redis.RedisClient> { }
interface RedisBackendStatic {
new(redis: redis.RedisClient, prefix: string): RedisBackend;
new(redis: redis.RedisClient): RedisBackend;
}
// for mongodb backend
import mongo = require('mongodb');
interface AclStatic {
mongodbBackend: MongodbBackendStatic;
}
interface MongodbBackend extends Backend<Callback> { }
interface MongodbBackendStatic {
new(db: mongo.Db, prefix: string, useSingle: boolean): MongodbBackend;
new(db: mongo.Db, prefix: string): MongodbBackend;
new(db: mongo.Db): MongodbBackend;
}
var _: AclStatic;
export = _;
}

30
acorn/acorn-tests.ts Normal file
View File

@@ -0,0 +1,30 @@
/// <reference path="../estree/estree.d.ts" />
/// <reference path="acorn.d.ts" />
import acorn = require('acorn');
var token: acorn.Token;
var tokens: acorn.Token[];
var comment: acorn.Comment;
var comments: acorn.Comment[];
var program: ESTree.Program;
var any: any;
var string: string;
// acorn
string = acorn.version;
program = acorn.parse('code');
program = acorn.parse('code', {ranges: true, onToken: tokens, onComment: comments});
program = acorn.parse('code', {
ranges: true,
onToken: (token) => tokens.push(token),
onComment: (isBlock, text, start, end) => { }
});
// Token
token = tokens[0];
string = token.type.label;
any = token.value;
// Comment
string = comment.value;

67
acorn/acorn.d.ts vendored Normal file
View File

@@ -0,0 +1,67 @@
// Type definitions for Acorn v1.0.1
// Project: https://github.com/marijnh/acorn
// Definitions by: RReverser <https://github.com/RReverser>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../estree/estree.d.ts" />
declare module acorn {
var version: string;
function parse(input: string, options?: Options): ESTree.Program;
function parseExpressionAt(input: string, pos: number, options?: Options): ESTree.Expression;
var defaultOptions: Options;
interface TokenType {
label: string;
keyword: string;
beforeExpr: boolean;
startsExpr: boolean;
isLoop: boolean;
isAssign: boolean;
prefix: boolean;
postfix: boolean;
binop: number;
updateContext: (prevType: TokenType) => any;
}
interface AbstractToken {
start: number;
end: number;
loc: ESTree.SourceLocation;
range: [number, number];
}
interface Token extends AbstractToken {
type: TokenType;
value: any;
}
interface Comment extends AbstractToken {
type: string;
value: string;
}
interface Options {
ecmaVersion?: number;
sourceType?: string;
onInsertedSemicolon?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any;
onTrailingComma?: (lastTokEnd: number, lastTokEndLoc?: ESTree.Position) => any;
allowReserved?: boolean;
allowReturnOutsideFunction?: boolean;
allowImportExportEverywhere?: boolean;
allowHashBang?: boolean;
locations?: boolean;
onToken?: ((token: Token) => any) | Token[];
onComment?: ((isBlock: boolean, text: string, start: number, end: number, startLoc?: ESTree.Position, endLoc?: ESTree.Position) => any) | Comment[];
ranges?: boolean;
program?: ESTree.Program;
sourceFile?: string;
directSourceFile?: string;
preserveParens?: boolean;
plugins?: { [name: string]: Function; };
}
}
declare module "acorn" {
export = acorn
}

33
adm-zip/adm-zip-tests.ts Normal file
View File

@@ -0,0 +1,33 @@
/// <reference path="adm-zip.d.ts" />
import AdmZip = require("adm-zip");
// reading archives
var zip = new AdmZip("./my_file.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function (zipEntry) {
console.log(zipEntry.toString()); // outputs zip entries information
if (zipEntry.entryName == "my_file.txt") {
console.log(zipEntry.getData().toString('utf8'));
}
});
// outputs the content of some_folder/my_file.txt
console.log(zip.readAsText("some_folder/my_file.txt"));
// extracts the specified file to the specified location
zip.extractEntryTo(/*entry name*/"some_folder/my_file.txt", /*target path*/"/home/me/tempfolder", /*overwrite*/true)
// extracts everything
zip.extractAllTo(/*target path*/"/home/me/zipcontent/", /*overwrite*/true);
// creating archives
var zip = new AdmZip();
// add file directly
zip.addFile("test.txt", new Buffer("inner content of the file"), "entry comment goes here");
// add local file
zip.addLocalFile("/home/me/some_picture.png");
// get everything as a buffer
var willSendthis = zip.toBuffer();
// or write everything to disk
zip.writeZip(/*target file name*/"/home/me/files.zip");

300
adm-zip/adm-zip.d.ts vendored Normal file
View File

@@ -0,0 +1,300 @@
// Type definitions for adm-zip v0.4.4
// Project: https://github.com/cthackers/adm-zip
// Definitions by: John Vilk <https://github.com/jvilk>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module AdmZip {
class ZipFile {
/**
* Create a new, empty archive.
*/
constructor();
/**
* Read an existing archive.
*/
constructor(fileName: string);
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry String with the full path of the entry
* @return Buffer or Null in case of error
*/
readFile(entry: string): Buffer;
/**
* Extracts the given entry from the archive and returns the content as a
* Buffer object.
* @param entry ZipEntry object
* @return Buffer or Null in case of error
*/
readFile(entry: IZipEntry): Buffer;
/**
* Asynchronous readFile
* @param entry String with the full path of the entry
* @param callback Called with a Buffer or Null in case of error
*/
readFileAsync(entry: string, callback: (data: Buffer, err: string) => any): void;
/**
* Asynchronous readFile
* @param entry ZipEntry object
* @param callback Called with a Buffer or Null in case of error
* @return Buffer or Null in case of error
*/
readFileAsync(entry: IZipEntry, callback: (data: Buffer, err: string) => any): void;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry String with the full path of the entry
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: string, encoding?: string): string;
/**
* Extracts the given entry from the archive and returns the content as
* plain text in the given encoding
* @param entry ZipEntry object
* @param encoding Optional. If no encoding is specified utf8 is used
* @return String
*/
readAsText(fileName: IZipEntry, encoding?: string): string;
/**
* Asynchronous readAsText
* @param entry String with the full path of the entry
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: string, callback: (data: string) => any, encoding?: string): void;
/**
* Asynchronous readAsText
* @param entry ZipEntry object
* @param callback Called with the resulting string.
* @param encoding Optional. If no encoding is specified utf8 is used
*/
readAsTextAsync(fileName: IZipEntry, callback: (data: string) => any, encoding?: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry String with the full path of the entry
*/
deleteFile(entry: string): void;
/**
* Remove the entry from the file or the entry and all its nested directories
* and files if the given entry is a directory
* @param entry A ZipEntry object.
*/
deleteFile(entry: IZipEntry): void;
/**
* Adds a comment to the zip. The zip must be rewritten after
* adding the comment.
* @param comment Content of the comment.
*/
addZipComment(comment: string): void;
/**
* Returns the zip comment
* @return The zip comment.
*/
getZipComment(): string;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry String with the full path of the entry
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: string, comment: string): void;
/**
* Adds a comment to a specified zipEntry. The zip must be rewritten after
* adding the comment.
* The comment cannot exceed 65535 characters in length.
* @param entry ZipEntry object.
* @param comment The comment to add to the entry.
*/
addZipEntryComment(entry: IZipEntry, comment: string): void;
/**
* Returns the comment of the specified entry.
* @param entry String with the full path of the entry.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: string): string;
/**
* Returns the comment of the specified entry
* @param entry ZipEntry object.
* @return String The comment of the specified entry.
*/
getZipEntryComment(entry: IZipEntry): string;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry String with the full path of the entry.
* @param content The entry's new contents.
*/
updateFile(entry: string, content: Buffer): void;
/**
* Updates the content of an existing entry inside the archive. The zip
* must be rewritten after updating the content
* @param entry ZipEntry object.
* @param content The entry's new contents.
*/
updateFile(entry: IZipEntry, content: Buffer): void;
/**
* Adds a file from the disk to the archive.
* @param localPath Path to a file on disk.
* @param zipPath Path to a directory in the archive. Defaults to the empty
* string.
*/
addLocalFile(localPath: string, zipPath?: string): void;
/**
* Adds a local directory and all its nested files and directories to the
* archive.
* @param localPath Path to a folder on disk.
* @param zipPath Path to a folder in the archive. Defaults to an empty
* string.
*/
addLocalFolder(localPath: string, zipPath?: string): void;
/**
* Allows you to create a entry (file or directory) in the zip file.
* If you want to create a directory the entryName must end in / and a null
* buffer should be provided.
* @param entryName Entry path
* @param content Content to add to the entry; must be a 0-length buffer
* for a directory.
* @param comment Comment to add to the entry.
* @param attr Attribute to add to the entry.
*/
addFile(entryName: string, data: Buffer, comment?: string, attr?: number): void;
/**
* Returns an array of ZipEntry objects representing the files and folders
* inside the archive
*/
getEntries(): IZipEntry[];
/**
* Returns a ZipEntry object representing the file or folder specified by
* ``name``.
* @param name Name of the file or folder to retrieve.
* @return ZipEntry The entry corresponding to the name.
*/
getEntry(name: string): IZipEntry;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry String with the full path of the entry
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
*
* @return Boolean
*/
extractEntryTo(entryPath: string, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the given entry to the given targetPath.
* If the entry is a directory inside the archive, the entire directory and
* its subdirectories will be extracted.
* @param entry ZipEntry object
* @param targetPath Target folder where to write the file
* @param maintainEntryPath If maintainEntryPath is true and the entry is
* inside a folder, the entry folder will be created in targetPath as
* well. Default is TRUE
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
* @return Boolean
*/
extractEntryTo(entryPath: IZipEntry, targetPath: string, maintainEntryPath?: boolean, overwrite?: boolean): boolean;
/**
* Extracts the entire archive to the given location
* @param targetPath Target location
* @param overwrite If the file already exists at the target path, the file
* will be overwriten if this is true. Default is FALSE
*/
extractAllTo(targetPath: string, overwrite?: boolean): void;
/**
* Writes the newly created zip file to disk at the specified location or
* if a zip was opened and no ``targetFileName`` is provided, it will
* overwrite the opened zip
* @param targetFileName
*/
writeZip(targetPath?: string): void;
/**
* Returns the content of the entire zip file as a Buffer object
* @return Buffer
*/
toBuffer(): Buffer;
}
/**
* The ZipEntry is more than a structure representing the entry inside the
* zip file. Beside the normal attributes and headers a entry can have, the
* class contains a reference to the part of the file where the compressed
* data resides and decompresses it when requested. It also compresses the
* data and creates the headers required to write in the zip file.
*/
interface IZipEntry {
/**
* Represents the full name and path of the file
*/
entryName: string;
rawEntryName: Buffer;
/**
* Extra data associated with this entry.
*/
extra: Buffer;
/**
* Entry comment.
*/
comment: string;
name: string;
/**
* Read-Only property that indicates the type of the entry.
*/
isDirectory: boolean;
/**
* Get the header associated with this ZipEntry.
*/
header: Buffer;
/**
* Retrieve the compressed data for this entry. Note that this may trigger
* compression if any properties were modified.
*/
getCompressedData(): Buffer;
/**
* Asynchronously retrieve the compressed data for this entry. Note that
* this may trigger compression if any properties were modified.
*/
getCompressedDataAsync(callback: (data: Buffer) => void): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: string): void;
/**
* Set the (uncompressed) data to be associated with this entry.
*/
setData(value: Buffer): void;
/**
* Get the decompressed data associated with this entry.
*/
getData(): Buffer;
/**
* Asynchronously get the decompressed data associated with this entry.
*/
getDataAsync(callback: (data: Buffer) => void): void;
/**
* Returns the CEN Entry Header to be written to the output zip file, plus
* the extra data and the entry comment.
*/
packHeader(): Buffer;
/**
* Returns a nicely formatted string with the most important properties of
* the ZipEntry.
*/
toString(): string;
}
}
declare module "adm-zip" {
import zipFile = AdmZip.ZipFile;
export = zipFile;
}

View File

@@ -0,0 +1,32 @@
/// <reference path="alertify.d.ts" />
alertify.init();
alertify.alert("This is an alert");
alertify.alert("This is an alert with a callback", () => {
alertify.success("Alert finished");
}, "myCustomClass");
alertify.confirm("This is a confirm request");
alertify.confirm("This is a confirm request with a callback", () => {
alertify.success("Confirm finished");
}, "myCustomClass");
var custom = alertify.extend("custom");
alertify.log("log message 1");
alertify.log("log message 2", "success", 3000);
alertify.prompt("prompt message 1");
alertify.prompt("prompt message 2", () => { console.log("callback"); }, "ok", "myClass");
alertify.set({ delay: 1000 });
alertify.set({ labels: { ok: "OK", cancel: "Cancel" }});
alertify.set({ buttonFocus: "ok" });
alertify.set({ buttonReverse: true });
alertify.success("This is a success message");
alertify.error("This is an error message");
alertify.debug();

124
alertify/alertify.d.ts vendored Normal file
View File

@@ -0,0 +1,124 @@
// Type definitions for alertify 0.3.11
// Project: http://fabien-d.github.io/alertify.js/
// Definitions by: John Jeffery <http://github.com/jjeffery>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare var alertify: alertify.IAlertifyStatic;
declare module alertify {
interface IAlertifyStatic {
/**
* Create an alert dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param cssClass Class(es) to append to dialog box
* @return alertify (ie this)
* @since 0.0.1
*/
alert(message: string, fn?: Function, cssClass?: string): IAlertifyStatic;
/**
* Create a confirm dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param cssClass Class(es) to append to dialog box
* @return alertify (ie this)
* @since 0.0.1
*/
confirm(message: string, fn?: Function, cssClass?: string): IAlertifyStatic;
/**
* Extend the log method to create custom methods
* @param type Custom method name
* @return function for logging
* @since 0.0.1
*/
extend(type: string): (message: string, wait?: number) => IAlertifyStatic;
/**
* Initialize Alertify and create the 2 main elements.
* Initialization will happen automatically on the first
* use of alert, confirm, prompt or log.
* @since 0.0.1
*/
init(): void;
/**
* Show a new log message box
* @param message The message passed from the callee
* @param type Optional type of log message
* @param wait Optional time (in ms) to wait before auto-hiding
* @return alertify (ie this)
* @since 0.0.1
*/
log(message: string, type?: string, wait?: number): IAlertifyStatic;
/**
* Create a prompt dialog box
* @param message The message passed from the callee
* @param fn Callback function
* @param placeholder Default value for prompt input
* @param cssClass Class(es) to append to dialog
* @return alertify (ie this)
* @since 0.0.1
*/
prompt(message: string, fn?: Function, placeholder?: string, cssClass?: string): IAlertifyStatic;
/**
* Shorthand for log messages
* @param message The message passed from the callee
* @return alertify (ie this)
* @since 0.0.1
*/
success(message: string): IAlertifyStatic;
/**
* Shorthand for log messages
* @param message The message passed from the callee
* @return alertify (ie this)
* @since 0.0.1
*/
error(message: string): IAlertifyStatic;
/**
* Used to set alertify properties
* @param Properties
* @since 0.2.11
*/
set(args: IProperties): void;
/**
* The labels used for dialog buttons
*/
labels: ILabels;
/**
* Attaches alertify.error to window.onerror method
* @since 0.3.8
*/
debug(): void;
}
/**
* Properties for alertify.set function
*/
interface IProperties {
/** Default value for milliseconds display of log messages */
delay?: number;
/** Default values for display of labels */
labels?: ILabels;
/** Default button for focus */
buttonFocus?: string;
/** Should buttons be displayed in reverse order */
buttonReverse?: boolean;
}
/** Labels for altertify.set function */
interface ILabels {
ok?: string;
cancel?: string;
}
}

143
alt/alt-tests.ts Normal file
View File

@@ -0,0 +1,143 @@
/**
* Created by shearerbeard on 6/28/15.
*/
///<reference path="alt.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
import Alt = require("alt");
import Promise = require("es6-promise");
//New alt instance
var alt = new Alt();
//Interfaces for our Action Types
interface TestActionsGenerate {
notifyTest(str:string):void;
}
interface TestActionsExplicit {
doTest(str:string):void;
success():void;
error():void;
loading():void;
}
//Create abstracts to inherit ghost methods
class AbstractActions implements AltJS.ActionsClass {
constructor( alt:AltJS.Alt){}
actions:any;
dispatch: ( ...payload:Array<any>) => void;
generateActions:( ...actions:Array<string>) => void;
}
class AbstractStoreModel<S> implements AltJS.StoreModel<S> {
bindActions:( ...actions:Array<Object>) => void;
bindAction:( ...args:Array<any>) => void;
bindListeners:(obj:any)=> void;
exportPublicMethods:(config:{[key:string]:(...args:Array<any>) => any}) => any;
exportAsync:( source:any) => void;
waitFor:any;
exportConfig:any;
getState:() => S;
}
class GenerateActionsClass extends AbstractActions {
constructor(config:AltJS.Alt) {
this.generateActions("notifyTest");
super(config);
}
}
class ExplicitActionsClass extends AbstractActions {
doTest(str:string) {
this.dispatch(str);
}
success() {
this.dispatch();
}
error() {
this.dispatch();
}
loading() {
this.dispatch();
}
}
var generatedActions = alt.createActions<TestActionsGenerate>(GenerateActionsClass);
var explicitActions = alt.createActions<ExplicitActionsClass>(ExplicitActionsClass);
interface AltTestState {
hello:string;
}
var testSource:AltJS.Source = {
fakeLoad():AltJS.SourceModel<string> {
return {
remote() {
return new Promise.Promise<string>((res:any, rej:any) => {
setTimeout(() => {
if(true) {
res("stuff");
} else {
rej("Things have broken");
}
}, 250)
});
},
local() {
return "local";
},
success: explicitActions.success,
error: explicitActions.error,
loading:explicitActions.loading
};
}
};
class TestStore extends AbstractStoreModel<AltTestState> implements AltTestState {
hello:string = "world";
constructor() {
super();
this.bindAction(generatedActions.notifyTest, this.onTest);
this.bindActions(explicitActions);
this.exportAsync(testSource);
this.exportPublicMethods({
split: this.split
});
}
onTest(str:string) {
this.hello = str;
}
onDoTest(str:string) {
this.hello = str;
}
split():string[] {
return this.hello.split("");
}
}
interface ExtendedTestStore extends AltJS.AltStore<AltTestState> {
fakeLoad():string;
split():Array<string>;
}
var testStore = <ExtendedTestStore>alt.createStore<AltTestState>(TestStore);
function testCallback(state:AltTestState) {
console.log(state);
}
//Listen allows a typed state callback
testStore.listen(testCallback);
testStore.unlisten(testCallback);
//State generic passes to derived store
var name:string = testStore.getState().hello;
var nameChars:Array<string> = testStore.split();
generatedActions.notifyTest("types");
explicitActions.doTest("more types");
export var result = testStore.getState();

167
alt/alt.d.ts vendored Normal file
View File

@@ -0,0 +1,167 @@
// Type definitions for Alt 0.16.10
// Project: https://github.com/goatslacker/alt
// Definitions by: Michael Shearer <https://github.com/Shearerbeard>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
///<reference path="../react/react.d.ts"/>
///<reference path="../es6-promise/es6-promise.d.ts" />
declare module AltJS {
interface StoreReduce {
action:any;
data: any;
}
export interface StoreModel<S> {
//Actions
bindAction?( action:Action<any>, handler:ActionHandler):void;
bindActions?(actions:ActionsClass):void;
//Methods/Listeners
exportPublicMethods?(exportConfig:any):void;
bindListeners?(config:{[methodName:string]:Action<any> | Actions}):void;
exportAsync?(source:Source):void;
registerAsync?(datasource:Source):void;
//state
setState?(state:S):void;
setState?(stateFn:(currentState:S, nextState:S) => S):void;
getState?():S;
waitFor?(store:AltStore<any>):void;
//events
onSerialize?(fn:(data:any) => any):void;
onDeserialize?(fn:(data:any) => any):void;
on?(event:AltJS.lifeCycleEvents, callback:() => any):void;
emitChange?():void;
waitFor?(storeOrStores:AltStore<any> | Array<AltStore<any>>):void;
otherwise?(data:any, action:AltJS.Action<any>):void;
observe?(alt:Alt):any;
reduce?(state:any, config:StoreReduce):Object;
preventDefault?():void;
afterEach?(payload:Object, state:Object):void;
beforeEach?(payload:Object, state:Object):void;
// TODO: Embed dispatcher interface in def
dispatcher?:any;
//instance
getInstance?():AltJS.AltStore<S>;
alt?:Alt;
displayName?:string;
}
export type Source = {[name:string]: () => SourceModel<any>};
export interface SourceModel<S> {
local(state:any):any;
remote(state:any):Promise<S>;
shouldFetch?(fetchFn:(...args:Array<any>) => boolean):void;
loading?:(args:any) => void;
success?:(state:S) => void;
error?:(args:any) => void;
interceptResponse?(response:any, action:Action<any>, ...args:Array<any>):any;
}
export interface AltStore<S> {
getState():S;
listen(handler:(state:S) => any):() => void;
unlisten(handler:(state:S) => any):void;
emitChange():void;
}
export enum lifeCycleEvents {
bootstrap,
snapshot,
init,
rollback,
error
}
export type Actions = {[action:string]:Action<any>};
export interface Action<T> {
( args:T):void;
defer(data:any):void;
}
export interface ActionsClass {
generateActions?( ...action:Array<string>):void;
dispatch( ...payload:Array<any>):void;
actions?:Actions;
}
type StateTransform = (store:StoreModel<any>) => AltJS.AltStore<any>;
interface AltConfig {
dispatcher?:any;
serialize?:(serializeFn:(data:Object) => string) => void;
deserialize?:(deserializeFn:(serialData:string) => Object) => void;
storeTransforms?:Array<StateTransform>;
batchingFunction?:(callback:( ...data:Array<any>) => any) => void;
}
class Alt {
constructor(config?:AltConfig);
actions:Actions;
bootstrap(jsonData:string):void;
takeSnapshot( ...storeNames:Array<string>):string;
flush():Object;
recycle( ...stores:Array<AltJS.AltStore<any>>):void;
rollback():void;
dispatch(action?:AltJS.Action<any>, data?:Object, details?:any):void;
//Actions methods
addActions(actionsName:string, ActionsClass: ActionsClassConstructor):void;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object):T;
createActions<T>(ActionsClass: ActionsClassConstructor, exportObj?: Object, ...constructorArgs:Array<any>):T;
generateActions<T>( ...actions:Array<string>):T;
getActions(actionsName:string):AltJS.Actions;
//Stores methods
addStore(name:string, store:StoreModel<any>, saveStore?:boolean):void;
createStore<S>(store:StoreModel<S>, name?:string):AltJS.AltStore<S>;
getStore(name:string):AltJS.AltStore<any>;
}
export interface AltFactory {
new(config?:AltConfig):Alt;
}
type ActionsClassConstructor = new (alt:Alt) => AltJS.ActionsClass;
type ActionHandler = ( ...data:Array<any>) => any;
type ExportConfig = {[key:string]:(...args:Array<any>) => any};
}
declare module "alt/utils/chromeDebug" {
function chromeDebug(alt:AltJS.Alt):void;
export = chromeDebug;
}
declare module "alt/AltContainer" {
import React = require("react");
interface ContainerProps {
store?:AltJS.AltStore<any>;
stores?:Array<AltJS.AltStore<any>>;
inject?:{[key:string]:any};
actions?:{[key:string]:Object};
render?:(...props:Array<any>) => React.ReactElement<any>;
flux?:AltJS.Alt;
transform?:(store:AltJS.AltStore<any>, actions:any) => any;
shouldComponentUpdate?:(props:any) => boolean;
component?:React.Component<any, any>;
}
type AltContainer = React.ReactElement<ContainerProps>;
var AltContainer:React.ComponentClass<ContainerProps>;
export = AltContainer;
}
declare module "alt" {
var alt:AltJS.AltFactory;
export = alt;
}

View File

@@ -1 +1 @@
""

View File

@@ -176,8 +176,7 @@ amplify.request("twitter-mentions", { user: "amplifyjs" });
//Example:
amplify.request.decoders.appEnvelope =
function (data, status, xhr, success, error) {
var appEnvelopeDecoder: amplifyDecoder = function (data, status, xhr, success, error) {
if (data.status === "success") {
success(data.data);
} else if (data.status === "fail" || data.status === "error") {
@@ -187,6 +186,17 @@ function (data, status, xhr, success, error) {
}
};
//a new decoder can be added to the amplifyDecoders interface
interface amplifyDecoders {
appEnvelope: amplifyDecoder;
}
amplify.request.decoders.appEnvelope = appEnvelopeDecoder;
//but you can also just add it via an index
amplify.request.decoders['appEnvelopeStr'] = appEnvelopeDecoder;
amplify.request.define("decoderExample", "ajax", {
url: "/myAjaxUrl",
type: "POST",

View File

@@ -1 +1 @@
""

View File

@@ -3,11 +3,33 @@
// Definitions by: Jonas Eriksson <https://github.com/joeriks/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface amplifyRequestSettings {
resourceId: string;
data?: any;
success?: Function;
error?: Function;
success?: (...args: any[]) => void;
error?: (...args: any[]) => void;
}
interface amplifyDecoder {
(
data?: any,
status?: string,
xhr?: JQueryXHR,
success?: (...args: any[]) => void,
error?: (...args: any[]) => void
): void
}
interface amplifyDecoders {
[decoderName: string]: amplifyDecoder;
jsSend: amplifyDecoder;
}
interface amplifyAjaxSettings extends JQueryAjaxSettings {
cache?: any;
decoder?: any /* string or amplifyDecoder */;
}
interface amplifyRequest {
@@ -28,7 +50,7 @@ interface amplifyRequest {
* success (optional): Function to invoke on success.
* error (optional): Function to invoke on error.
*/
(settings: amplifyRequestSettings);
(settings: amplifyRequestSettings): any;
/***
* Define a resource.
@@ -39,7 +61,7 @@ interface amplifyRequest {
* cache: See the cache section for more details.
* decoder: See the decoder section for more details.
*/
define(resourceId: string, requestType: string, settings?: any): void;
define(resourceId: string, requestType: string, settings?: amplifyAjaxSettings): void;
/***
* Define a custom request.
@@ -50,9 +72,9 @@ interface amplifyRequest {
* success: Callback to invoke on success.
* error: Callback to invoke on error.
*/
define(resourceId: string, resource: Function): void;
decoders: any;
define(resourceId: string, resource: (settings: amplifyRequestSettings) => void): void;
decoders: amplifyDecoders;
cache: any;
}

View File

@@ -0,0 +1,80 @@
/// <reference path="./amqp-rpc.d.ts" />
import amqp_rpc = require('amqp-rpc');
var rpc = amqp_rpc.factory();
interface Name {
name?: string;
}
rpc.on<number>('inc', function (param, cb) {
var prevVal = param;
var nextVal = param + 2;
cb(++param, prevVal, nextVal);
});
rpc.on<Name>('say.*', function (param, cb, inf) {
var arr = inf.cmd.split('.');
var name = (param && param.name) ? param.name : 'world';
cb(arr[1] + ' ' + name + '!');
});
rpc.on('withoutCB', function (param, cb, inf) {
if (cb) {
cb('please run function without cb parameter')
}
else {
console.log('this is function withoutCB');
}
});
rpc.call<number>('inc', 5, function (param1, param2, param3) {
console.log(param1, param2, param3);
});
rpc.call<Name>('say.Hello', { name: 'John' }, function (msg) {
console.log('results of say.Hello:', msg); //output: Hello John!
});
rpc.call<any>('withoutCB', {}, function (msg) {
console.log('withoutCB results:', msg); //output: please run function without cb parameter
});
rpc.call<any>('withoutCB', {}); //output message on server side console
import os = require('os');
interface State {
type: string;
}
var counter = 0;
rpc.onBroadcast<State>('getWorkerStat', function (params, cb) {
if (params && params.type == 'fullStat') {
cb(null, {
pid: process.pid,
hostname: os.hostname(),
uptime: process.uptime(),
counter: counter++
});
}
else {
cb(null, { counter: counter++ })
}
});
var all_stats: any = {};
rpc.callBroadcast<State>(
'getWorkerStat',
{ type: 'fullStat' }, //request parameters
{ //call options
ttl: 1000, //wait response time (1 seconds), after run onComplete
onResponse: function (err: any, stat: any) { //callback on each worker response
all_stats[stat.hostname + ':' + stat.pid] = stat;
},
onComplete: function () { //callback on ttl expired
console.log('----------------------- WORKER STATISTICS ----------------------------------------');
for (var worker in all_stats) {
var s: any = all_stats[worker];
console.log(worker, '\tuptime=', s.uptime.toFixed(2) + ' seconds', '\tcounter=', s.counter);
}
}
});

72
amqp-rpc/amqp-rpc.d.ts vendored Normal file
View File

@@ -0,0 +1,72 @@
// Type definitions for amqp-rpc v0.0.8
// Project: https://github.com/demchenkoe/node-amqp-rpc/
// Definitions by: Wonshik Kim <https://github.com/wokim/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "amqp-rpc" {
export interface Options {
connection?: any;
url?: string;
exchangeInstance?: any;
exchange?: string;
exchange_options?: {
exclusive?: boolean;
autoDelete?: boolean;
};
ipml_options?: {
defaultExchangeName?: string;
}
conn_options?: any;
}
export interface CallOptions {
correlationId?: string;
autoDeleteCallback?: any;
}
export interface HandlerOptions {
queueName?: string;
durable?: boolean;
exclusive?: boolean;
autoDelete?: boolean;
}
export interface BroadcastOptions {
ttl?: number;
onResponse?: any;
context?: any;
onComplete?: any;
}
export interface CommandInfo {
cmd?: string;
exchange?: string;
contentType?: string;
size?: number;
}
export interface Callback {
(...args: any[]): void;
}
export interface CallbackWithError {
(err: any, ...args: any[]): void;
}
export function factory(opt?: Options): amqpRPC;
export class amqpRPC {
constructor(opt?: Options);
generateQueueName(type: string): string;
disconnect(): void;
call<T>(cmd: string, params: T, cb?: Callback, context?: any, options?: CallOptions): string;
on<T>(cmd: string, cb: (param?: T, cb?: Callback, info?: CommandInfo) => void, context?: any, options?: HandlerOptions): boolean;
off(cmd: string): boolean;
callBroadcast<T>(cmd: string, params: T, options?: BroadcastOptions): void;
onBroadcast<T>(cmd: string, cb?: (params?: T, cb?: CallbackWithError) => void, context?: any, options?: any): boolean;
offBroadcast(cmd: string): boolean;
}
}

21
amqplib/amqplib-tests.ts Normal file
View File

@@ -0,0 +1,21 @@
/// <reference path="amqplib.d.ts" />
import amqp = require("amqplib");
var msg = "Hello World";
amqp.connect("amqp://localhost")
.then(connection => {
return connection.createChannel()
.tap(channel => channel.checkQueue("myQueue"))
.then(channel => channel.sendToQueue("myQueue", new Buffer(msg)))
.ensure(() => connection.close());
});
amqp.connect("amqp://localhost")
.then(connection => {
return connection.createChannel()
.tap(channel => channel.checkQueue("myQueue"))
.then(channel => channel.consume("myQueue", newMsg => console.log("New Message: " + newMsg.content.toString())))
.ensure(() => connection.close());
});

144
amqplib/amqplib.d.ts vendored Normal file
View File

@@ -0,0 +1,144 @@
// Type definitions for amqplib 0.3.x
// Project: https://github.com/squaremo/amqp.node
// Definitions by: Michael Nahkies <https://github.com/mnahkies>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../when/when.d.ts" />
/// <reference path="../node/node.d.ts" />
declare module "amqplib" {
import events = require("events");
import when = require("when");
interface Connection extends events.EventEmitter {
close(): when.Promise<void>;
createChannel(): when.Promise<Channel>;
createConfirmChannel(): when.Promise<Channel>;
}
module Replies {
interface Empty {
}
interface AssertQueue {
queue: string;
messageCount: number;
consumerCount: number;
}
interface DeleteQueue {
messageCount: number;
}
interface AssertExchange {
exchange: string;
}
interface Consume {
consumerTag: string;
}
}
module Options {
interface AssertQueue {
exclusive?: boolean;
durable?: boolean;
autoDelete?: boolean;
arguments?: any;
messageTtl?: number;
expires?: number;
deadLetterExchange?: string;
maxLength?: number;
}
interface DeleteQueue {
ifUnused?: boolean;
ifEmpty?: boolean;
}
interface AssertExchange {
durable?: boolean;
internal?: boolean;
autoDelete?: boolean;
alternateExchange?: string;
arguments?: any;
}
interface DeleteExchange {
ifUnused?: boolean;
}
interface Publish {
expiration?: string;
userId?: string;
CC?: string | string[];
mandatory?: boolean;
persistent?: boolean;
deliveryMode?: boolean | number;
BCC?: string | string[];
contentType?: string;
contentEncoding?: string;
headers?: Object;
priority?: number;
correlationId?: string;
replyTo?: string;
messageId?: string;
timestamp?: number;
type?: string;
appId?: string;
}
interface Consume {
consumerTag?: string;
noLocal?: boolean;
noAck?: boolean;
exclusive?: boolean;
priority?: number;
arguments?: Object;
}
interface Get {
noAck?: boolean;
}
}
interface Message {
content: Buffer;
fields: Object;
properties: Object;
}
interface Channel extends events.EventEmitter {
close(): when.Promise<void>;
assertQueue(queue: string, options?: Options.AssertQueue): when.Promise<Replies.AssertQueue>;
checkQueue(queue: string): when.Promise<Replies.AssertQueue>;
deleteQueue(queue: string, options?: Options.DeleteQueue): when.Promise<Replies.DeleteQueue>;
purgeQueue(queue: string): when.Promise<Replies.DeleteQueue>;
bindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindQueue(queue: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
assertExchange(exchange: string, type: string, options?: Options.AssertExchange): when.Promise<Replies.AssertExchange>;
checkExchange(exchange: string): when.Promise<Replies.Empty>;
deleteExchange(exchange: string, options?: Options.DeleteExchange): when.Promise<Replies.Empty>;
bindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
unbindExchange(destination: string, source: string, pattern: string, args?: any): when.Promise<Replies.Empty>;
publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean;
sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean;
consume(queue: string, onMessage: (msg: Message) => any, options?: Options.Consume): when.Promise<Replies.Consume>;
cancel(consumerTag: string): when.Promise<Replies.Empty>;
get(queue: string, options?: Options.Get): when.Promise<Message | boolean>;
ack(message: Message, allUpTo?: boolean): void;
ackAll(): void;
nack(message: Message, allUpTo?: boolean, requeue?: boolean): void;
nackAll(requeue?: boolean): void;
reject(message: Message, requeue?: boolean): void;
prefetch(count: number, global?: boolean): when.Promise<Replies.Empty>;
recover(): when.Promise<Replies.Empty>;
}
function connect(url: string, socketOptions?: any): when.Promise<Connection>;
}

View File

@@ -0,0 +1,78 @@
/// <reference path="angular-agility.d.ts" />
/// <reference path='../angularjs/angular.d.ts' />
var validIconStrategy:aa.IValidIconStrategy = <aa.IValidIconStrategy>{};
validIconStrategy.validIcon = "";
validIconStrategy.invalidIcon = "";
validIconStrategy.getContainer(<ng.IAugmentedJQueryStatic>{});
var provider:aa.IFormExtensionsProvider = <aa.IFormExtensionsProvider>{};
provider.defaultLabelStrategy = "";
provider.defaultFieldGroupStrategy = "";
provider.defaultValMsgPlacementStrategy = "";
provider.validIconStrategy = validIconStrategy;
provider.defaultSpinnerClickStrategy = "";
provider.defaultNotifyTarget = "";
provider.defaultOnNavigateAwayStrategy = "";
provider.validationMessages['testName'] = 'testMessages';
provider.valMsgForTemplate = "";
provider.confirmResetStrategy = ():boolean=>{ return false; };
provider.globalSettings['testSetting'] = 'test';
provider.labelStrategies['testLabelStratgey'] = (element:ng.IAugmentedJQueryStatic, labelText:string, isRequired:boolean):void=>{};
provider.fieldGroupStrategies['testFieldGroupStratgey'] = (element:ng.IAugmentedJQueryStatic):void=>{};
provider.valMsgPlacementStrategies['testValMsgPlacementStrategy'] = (formFieldElement:ng.IAugmentedJQueryStatic, formName:string, formFieldName:string):void=>{};
provider.spinnerClickStrategies['testSpinnerClickStratgey'] = (element:ng.IAugmentedJQueryStatic):void=>{};
provider.onNavigateAwayStrategies['testOnNavigateAwayStrategy'] = (rootFormScope:ng.IScope, rootForm:ng.IAugmentedJQueryStatic, $injector:ng.auto.IInjectorService)=>{};
var defaults:aa.INotifyDefaults = <aa.INotifyDefaults>{};
defaults.success = (message:string, options:any, notifier:any):any=>{};
defaults.info = (message:string, options:any, notifier:any):any=>{};
defaults.warning = (message:string, options:any, notifier:any):any=>{};
defaults.danger = (message:string, options:any, notifier:any):any=>{};
defaults.error = (message:string, options:any, notifier:any):any=>{};
var configWithoutTemplate:aa.INotifyConfig = {
name: "",
options: <aa.INotifyOptions> {},
namedDefaults: <aa.INotifyDefaults> {}
}
var configWithTemplate:aa.INotifyConfig = {
name: "",
template: "",
templateName: "",
options: <aa.INotifyOptions> {},
namedDefaults: <aa.INotifyDefaults> {}
}
var notifyOptionsWithoutCssClasses:aa.INotifyOptions = {
messageType: "",
allowHtml: true,
message: ""
}
var notifyOptionsWithCssClasses:aa.INotifyOptions = {
cssClasses: "",
messageType: "",
allowHtml: true,
message: ""
}
var notifyConfigProvider:aa.INotifyConfigProvider = <aa.INotifyConfigProvider> {};
notifyConfigProvider.notifyConfigs = {};
notifyConfigProvider.defaultTargetContainerName = "";
notifyConfigProvider.defaultNotifyConfig = "";
notifyConfigProvider.addOrUpdateNotifyConfig("", configWithTemplate);
notifyConfigProvider.optionsTransformer(notifyOptionsWithCssClasses, <ng.ISCEService>{});
var fullExternalConfig:aa.IExternalFormValidationConfig = {
validations: "",
ignore: "",
globals: "",
resolve: "",
resolveFn: (modelValue:string):string=>{ return "" }
}
var minimalExternalConfig:aa.IExternalFormValidationConfig = {
validations: ""
}

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