Merge remote-tracking branch 'refs/remotes/DefinitelyTyped/master' into columngridref

This commit is contained in:
MatejQ
2015-11-12 10:56:28 +01:00
283 changed files with 139253 additions and 52806 deletions

View File

@@ -0,0 +1,266 @@
/// <reference path="./openjscad.d.ts" />
function test() {
var gProcessor: OpenJsCad.Processor = null;
// Show all exceptions to the user:
OpenJsCad.AlertUserOfUncaughtExceptions();
function onload()
{
gProcessor = new OpenJsCad.Processor(<HTMLDivElement>document.getElementById("viewer"));
updateSolid();
}
function updateSolid()
{
gProcessor.setJsCad((<HTMLTextAreaElement>document.getElementById('code')).value);
}
}
function main()
{
// Main entry point; here we construct our solid:
var gear = involuteGear(
15,
10,
20,
0,
5
);
var centerhole = CSG.cylinder({start: [0,0,-5], end: [0,0,5], radius: 2, resolution: 16});
gear = gear.subtract(centerhole);
return gear;
}
function involuteGear(numTeeth: number, circularPitch: number, pressureAngle: number, clearance: number, thickness: number)
{
// default values:
if(arguments.length < 3) pressureAngle = 20;
if(arguments.length < 4) clearance = 0;
if(arguments.length < 4) thickness = 1;
var addendum = circularPitch / Math.PI;
var dedendum = addendum + clearance;
// radiuses of the 4 circles:
var pitchRadius = numTeeth * circularPitch / (2 * Math.PI);
var baseRadius = pitchRadius * Math.cos(Math.PI * pressureAngle / 180);
var outerRadius = pitchRadius + addendum;
var rootRadius = pitchRadius - dedendum;
var maxtanlength = Math.sqrt(outerRadius*outerRadius - baseRadius*baseRadius);
var maxangle = maxtanlength / baseRadius;
var tl_at_pitchcircle = Math.sqrt(pitchRadius*pitchRadius - baseRadius*baseRadius);
var angle_at_pitchcircle = tl_at_pitchcircle / baseRadius;
var diffangle = angle_at_pitchcircle - Math.atan(angle_at_pitchcircle);
var angularToothWidthAtBase = Math.PI / numTeeth + 2*diffangle;
// build a single 2d tooth in the 'points' array:
var resolution = 5;
var points = [new CSG.Vector2D(0,0)];
for(var i = 0; i <= resolution; i++)
{
// first side of the tooth:
var angle = maxangle * i / resolution;
var tanlength = angle * baseRadius;
var radvector = CSG.Vector2D.fromAngle(angle);
var tanvector = radvector.normal();
var p = radvector.times(baseRadius).plus(tanvector.times(tanlength));
points[i+1] = p;
// opposite side of the tooth:
radvector = CSG.Vector2D.fromAngle(angularToothWidthAtBase - angle);
tanvector = radvector.normal().negated();
p = radvector.times(baseRadius).plus(tanvector.times(tanlength));
points[2 * resolution + 2 - i] = p;
}
// create the polygon and extrude into 3D:
var tooth3d = new CSG.Polygon2D(points).extrude({offset: [0, 0, thickness]});
var allteeth = new CSG();
for(var i = 0; i < numTeeth; i++)
{
var angle = i*360/numTeeth;
var rotatedtooth = <CSG>tooth3d.rotateZ(angle);
allteeth = allteeth.unionForNonIntersecting(rotatedtooth);
}
// build the root circle:
points = [];
var toothAngle = 2 * Math.PI / numTeeth;
var toothCenterAngle = 0.5 * angularToothWidthAtBase;
for(var i = 0; i < numTeeth; i++)
{
var angle = toothCenterAngle + i * toothAngle;
var p = CSG.Vector2D.fromAngle(angle).times(rootRadius);
points.push(p);
}
// create the polygon and extrude into 3D:
var rootcircle = new CSG.Polygon2D(points).extrude({offset: [0, 0, thickness]});
var result = rootcircle.union(allteeth);
// center at origin:
result = <CSG>result.translate([0, 0, -thickness/2]);
return result;
}
var cylresolution=16;
function main2()
{
var params =
{
quality: 0,
diameter1: 12.2,
shaftlength1: 15,
outerlength1: 20,
nutradius1: 4.65,
nutthickness1: 4.2,
screwdiameter1: 5,
diameter2: 9.5,
shaftlength2: 10,
outerlength2: 15,
nutradius2: 3.2,
nutthickness2: 2.6,
screwdiameter2: 3,
outerdiameter: 30,
spiderlength: 12,
spidermargin: 0,
numteeth: 2
};
cylresolution=(params.quality == 1)? 64:16;
var outerdiameter=params.outerdiameter;
outerdiameter=Math.max(outerdiameter, params.diameter1+0.5);
outerdiameter=Math.max(outerdiameter, params.diameter2+0.5);
var spidercenterdiameter=outerdiameter/2;
var part1=makeShaft(params.diameter1, outerdiameter,spidercenterdiameter,params.shaftlength1,params.outerlength1,params.spiderlength, params.nutradius1, params.nutthickness1, params.screwdiameter1, params.numteeth);
var part2=makeShaft(params.diameter2, outerdiameter,spidercenterdiameter,params.shaftlength2,params.outerlength2,params.spiderlength, params.nutradius2, params.nutthickness2, params.screwdiameter2, params.numteeth);
var spider=makeSpider(outerdiameter, spidercenterdiameter, params.spiderlength, params.numteeth);
if(params.spidermargin > 0)
{
spider=spider.contract(params.spidermargin, 4);
}
// rotate shaft parts for better 3d printing:
part1=<CSG>part1.rotateX(180).translate([0,0,params.outerlength1+params.spiderlength]);
part2=<CSG>part2.rotateX(180).translate([0,0,params.outerlength2+params.spiderlength]);
var result=<CSG>part1.translate([-outerdiameter-5,0,0]);
result=result.union(<CSG>part2.translate([0,0,0]));
result=result.union(<CSG>spider.translate([outerdiameter+5,0,-params.spidermargin]));
return result;
}
function makeShaft(innerdiameter: number, outerdiameter: number, spidercenterdiameter: number, shaftlength: number, outerlength: number, spiderlength: number, nutradius: number, nutthickness: number, screwdiameter: number, numteeth: number)
{
var result=CSG.cylinder({start:[0,0,0], end:[0,0,outerlength], radius:outerdiameter/2, resolution:cylresolution});
for(var i=0; i < numteeth; i++)
{
var angle=i*360/numteeth;
var pie=makePie(outerdiameter/2, spiderlength,angle-45/numteeth, angle+45/numteeth);
pie=<CSG>pie.translate([0,0,outerlength]);
result=result.union(pie);
}
var spidercylinder=CSG.cylinder({start:[0,0,outerlength], end:[0,0,outerlength+spiderlength],radius:spidercenterdiameter/2,resolution:cylresolution});
result=result.subtract(spidercylinder);
var shaftcylinder=CSG.cylinder({start:[0,0,0], end:[0,0,shaftlength], radius:innerdiameter/2, resolution:cylresolution});
result=result.subtract(shaftcylinder);
var screwz=shaftlength/2;
if(screwz < nutradius) screwz=nutradius;
var nutcutout = <CSG>hexagon(nutradius, nutthickness).translate([0,0,-nutthickness/2]);
var grubnutradiusAtFlatSide = nutradius * Math.cos(Math.PI / 180 * 30);
var nutcutoutrectangle = CSG.cube({
radius: [outerlength/2, grubnutradiusAtFlatSide, nutthickness/2],
center: [outerlength/2, 0, 0],
});
nutcutout = nutcutout.union(nutcutoutrectangle);
nutcutout = <CSG>nutcutout.rotateY(90);
nutcutout = <CSG>nutcutout.translate([(outerdiameter+innerdiameter)/4, 0, screwz]);
result = result.subtract(nutcutout);
var screwcutout=CSG.cylinder({
start: [outerdiameter/2, 0, screwz],
end: [0, 0, screwz],
radius: screwdiameter/2,
resolution:cylresolution
});
result=result.subtract(screwcutout);
//return nutcutout;
// nutcutout = nutcutout.translate([-grubnutheight/2 - centerholeradius - nutdistance,0,0]);
return result;
}
function makePie(radius: number, height: number, startangle: number, endangle: number)
{
var absangle=Math.abs(startangle-endangle);
if(absangle >= 180)
{
throw new Error("Pie angle must be less than 180 degrees");
}
var numsteps=cylresolution*absangle/360;
if(numsteps < 1) numsteps=1;
var points: CSG.Vector2D[] = [];
for(var i=0; i <= numsteps; i++)
{
var angle=startangle+i/numsteps*(endangle-startangle);
var vec = CSG.Vector2D.fromAngleDegrees(angle).times(radius);
points.push(vec);
}
points.push(new CSG.Vector2D(0,0));
var shape2d=new CSG.Polygon2D(points);
var extruded=shape2d.extrude({
offset: [0,0,height], // direction for extrusion
});
return extruded;
}
function hexagon(radius: number, height: number)
{
var vertices: CSG.Vertex[] = [];
for(var i=0; i < 6; i++)
{
var point=CSG.Vector2D.fromAngleDegrees(-i*60).times(radius).toVector3D(0);
vertices.push(new CSG.Vertex(point));
}
var polygon=new CSG.Polygon(vertices);
var hexagon=polygon.extrude([0,0,height]);
return hexagon;
}
function makeSpider(outerdiameter: number, spidercenterdiameter: number, spiderlength: number, numteeth: number)
{
var result=new CSG();
var numspiderteeth=numteeth*2; // spider has twice the number of teeth
for(var i=0; i < numspiderteeth; i++)
{
var angle=i*360/numspiderteeth;
var pie=makePie(outerdiameter/2, spiderlength,angle-90/numspiderteeth, angle+90/numspiderteeth);
pie=<CSG>pie.translate([0,0,0]);
result=result.union(pie);
}
var centercylinder=CSG.cylinder({start:[0,0,0], end:[0,0,spiderlength], radius:spidercenterdiameter/2, resolution:cylresolution});
result=result.union(centercylinder);
return result;
}

912
OpenJsCad/openjscad.d.ts vendored Normal file
View File

@@ -0,0 +1,912 @@
// Type definitions for OpenJsCad.js
// Project: https://github.com/joostn/OpenJsCad
// Definitions by: Dan Marshall <https://github.com/danmarshall>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../threejs/three.d.ts" />
declare module THREE {
var CSG: {
fromCSG: (csg: CSG, defaultColor: any) => {
colorMesh: Mesh;
wireframe: Mesh;
boundLen: number;
};
getGeometryVertex: (geometry: any, vertex_position: any) => number;
};
function OrbitControls(object: any, domElement: any): void;
function SpriteCanvasMaterial(parameters?: any): void;
interface ICanvasRendererOptions {
canvas?: HTMLCanvasElement;
alpha?: boolean;
}
class CanvasRenderer implements Renderer {
domElement: HTMLCanvasElement;
private pixelRatio;
private autoClear;
private sortObjects;
private sortElements;
private info;
private _projector;
private _renderData;
private _elements;
private _lights;
private _canvas;
private _canvasWidth;
private _canvasHeight;
private _canvasWidthHalf;
private _canvasHeightHalf;
private _viewportX;
private _viewportY;
private _viewportWidth;
private _viewportHeight;
private _context;
private _clearColor;
private _clearAlpha;
private _contextGlobalAlpha;
private _contextGlobalCompositeOperation;
private _contextStrokeStyle;
private _camera;
private _contextFillStyle;
private _contextLineWidth;
private _contextLineCap;
private _contextLineJoin;
private _contextLineDash;
private _v1;
private _v2;
private _v3;
private _v4;
private _v5;
private _v6;
private _v1x;
private _v1y;
private _v2x;
private _v2y;
private _v3x;
private _v3y;
private _v4x;
private _v4y;
private _v5x;
private _v5y;
private _v6x;
private _v6y;
private _color;
private _color1;
private _color2;
private _color3;
private _color4;
private _diffuseColor;
private _emissiveColor;
private _lightColor;
private _patterns;
private _image;
private _uvs;
private _uv1x;
private _uv1y;
private _uv2x;
private _uv2y;
private _uv3x;
private _uv3y;
private _clipBox;
private _clearBox;
private _elemBox;
private _ambientLight;
private _directionalLights;
private _pointLights;
private _vector3;
private _centroid;
private _normal;
private _normalViewMatrix;
constructor(parameters: ICanvasRendererOptions);
supportsVertexTextures(): void;
setFaceCulling: () => void;
getPixelRatio(): number;
setPixelRatio(value: any): void;
setSize(width: any, height: any, updateStyle: any): void;
setViewport(x: any, y: any, width: any, height: any): void;
setScissor(): void;
enableScissorTest(): void;
setClearColor(color: any, alpha: any): void;
setClearColorHex(hex: any, alpha: any): void;
getClearColor(): Color;
getClearAlpha(): number;
getMaxAnisotropy(): number;
clear(): void;
clearColor(): void;
clearDepth(): void;
clearStencil(): void;
render(scene: Scene, camera: Camera, renderTarget?: RenderTarget, forceClear?: boolean): void;
calculateLights(): void;
calculateLight(position: any, normal: any, color: any): void;
renderSprite(v1: any, element: any, material: any): void;
renderLine(v1: any, v2: any, element: any, material: any): void;
renderFace3(v1: any, v2: any, v3: any, uv1: any, uv2: any, uv3: any, element: any, material: any): void;
drawTriangle(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any): void;
strokePath(color: any, linewidth: any, linecap: any, linejoin: any): void;
fillPath(color: any): void;
onTextureUpdate(event: any): void;
textureToPattern(texture: any): void;
patternPath(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, u0: any, v0: any, u1: any, v1: any, u2: any, v2: any, texture: any): void;
clipImage(x0: any, y0: any, x1: any, y1: any, x2: any, y2: any, u0: any, v0: any, u1: any, v1: any, u2: any, v2: any, image: any): void;
expand(v1: any, v2: any, pixels: any): void;
setOpacity(value: any): void;
setBlending(value: any): void;
setLineWidth(value: any): void;
setLineCap(value: any): void;
setLineJoin(value: any): void;
setStrokeStyle(value: any): void;
setFillStyle(value: any): void;
setLineDash(value: any): void;
}
function RenderableObject(): void;
function RenderableFace(): void;
function RenderableVertex(): void;
function RenderableLine(): void;
function RenderableSprite(): void;
function Projector(): void;
}
declare module OpenJsCad {
interface ILog {
(x: string): void;
prevLogTime?: number;
}
var log: ILog;
interface IViewerOptions {
drawLines?: boolean;
drawFaces?: boolean;
color?: number[];
bgColor?: number;
noWebGL?: boolean;
}
interface ProcessorOptions extends IViewerOptions {
verbose?: boolean;
viewerwidth?: number;
viewerheight?: number;
viewerheightratio?: number;
}
class Viewer {
private perspective;
private drawOptions;
private size;
private defaultColor_;
private bgColor_;
private containerElm_;
private scene_;
private camera_;
private controls_;
private renderer_;
private canvas;
private pauseRender_;
private requestID_;
constructor(containerElm: any, size: any, options: IViewerOptions);
createScene(drawAxes: any, axLen: any): void;
createCamera(): void;
createControls(canvas: any): void;
webGLAvailable(): boolean;
createRenderer(bool_noWebGL: any): void;
render(): void;
animate(): void;
cancelAnimate(): void;
refreshRenderer(bool_noWebGL: any): void;
drawAxes(axLen: any): void;
setCsg(csg: any, resetZoom: any): void;
applyDrawOptions(): void;
clear(): void;
getUserMeshes(str?: any): THREE.Object3D[];
resetZoom(r: any): void;
parseSizeParams(): void;
handleResize(): void;
}
function makeAbsoluteUrl(url: any, baseurl: any): any;
function isChrome(): boolean;
function runMainInWorker(mainParameters: any): void;
function expandResultObjectArray(result: any): any;
function checkResult(result: any): void;
function resultToCompactBinary(resultin: any): any;
function resultFromCompactBinary(resultin: any): any;
function parseJsCadScriptSync(script: any, mainParameters: any, debugging: any): any;
function parseJsCadScriptASync(script: any, mainParameters: any, options: any, callback: any): Worker;
function getWindowURL(): URL;
function textToBlobUrl(txt: any): string;
function revokeBlobUrl(url: any): void;
function FileSystemApiErrorHandler(fileError: any, operation: any): void;
function AlertUserOfUncaughtExceptions(): void;
function getParamDefinitions(script: any): any[];
interface EventHandler {
(ev?: Event): any;
}
/**
* options parameter:
* - drawLines: display wireframe lines
* - drawFaces: display surfaces
* - bgColor: canvas background color
* - color: object color
* - viewerwidth, viewerheight: set rendering size. Works with any css unit.
* viewerheight can also be specified as a ratio to width, ie number e (0, 1]
* - noWebGL: force render without webGL
* - verbose: show additional info (currently only time used for rendering)
*/
interface ViewerSize {
widthDefault: string;
heightDefault: string;
width: number;
height: number;
heightratio: number;
}
class Processor {
private containerdiv;
private options;
private onchange;
private static widthDefault;
private static heightDefault;
private viewerdiv;
private viewer;
private viewerSize;
private processing;
private currentObject;
private hasValidCurrentObject;
private hasOutputFile;
private worker;
private paramDefinitions;
private paramControls;
private script;
private hasError;
private debugging;
private errordiv;
private errorpre;
private statusdiv;
private controldiv;
private statusspan;
private statusbuttons;
private abortbutton;
private renderedElementDropdown;
private formatDropdown;
private generateOutputFileButton;
private downloadOutputFileLink;
private parametersdiv;
private parameterstable;
private currentFormat;
private filename;
private currentObjects;
private currentObjectIndex;
private isFirstRender_;
private outputFileDirEntry;
private outputFileBlobUrl;
constructor(containerdiv: HTMLDivElement, options?: ProcessorOptions, onchange?: EventHandler);
static convertToSolid(obj: any): any;
cleanOption(option: any, deflt: any): any;
toggleDrawOption(str: any): boolean;
setDrawOption(str: any, bool: any): void;
handleResize(): void;
createElements(): void;
getFilenameForRenderedObject(): string;
setRenderedObjects(obj: any): void;
setSelectedObjectIndex(index: number): void;
selectedFormat(): any;
selectedFormatInfo(): any;
updateDownloadLink(): void;
clearViewer(): void;
abort(): void;
enableItems(): void;
setOpenJsCadPath(path: string): void;
addLibrary(lib: any): void;
setError(txt: string): void;
setDebugging(debugging: boolean): void;
setJsCad(script: string, filename?: string): void;
getParamValues(): {};
rebuildSolid(): void;
hasSolid(): boolean;
isProcessing(): boolean;
clearOutputFile(): void;
generateOutputFile(): void;
currentObjectToBlob(): any;
supportedFormatsForCurrentObject(): string[];
formatInfo(format: any): any;
downloadLinkTextForCurrentObject(): string;
generateOutputFileBlobUrl(): void;
generateOutputFileFileSystem(): void;
createParamControls(): void;
}
}
interface Window {
Worker: Worker;
// URL: URL;
webkitURL: URL;
requestFileSystem: any;
webkitRequestFileSystem: any;
}
interface IAMFStringOptions {
unit: string;
}
declare class CxG {
toStlString(): string;
toStlBinary(): void;
toAMFString(AMFStringOptions?: IAMFStringOptions): void;
getBounds(): CxG[];
transform(matrix4x4: CSG.Matrix4x4): CxG;
mirrored(plane: CSG.Plane): CxG;
mirroredX(): CxG;
mirroredY(): CxG;
mirroredZ(): CxG;
translate(v: number[]): CxG;
translate(v: CSG.Vector3D): CxG;
scale(f: CSG.Vector3D): CxG;
rotateX(deg: number): CxG;
rotateY(deg: number): CxG;
rotateZ(deg: number): CxG;
rotate(rotationCenter: CSG.Vector3D, rotationAxis: CSG.Vector3D, degrees: number): CxG;
rotateEulerAngles(alpha: number, beta: number, gamma: number, position: number[]): CxG;
}
interface ICenter {
center(cAxes: string[]): CxG;
}
declare class CSG extends CxG implements ICenter {
polygons: CSG.Polygon[];
properties: CSG.Properties;
isCanonicalized: boolean;
isRetesselated: boolean;
cachedBoundingBox: CSG.Vector3D[];
static defaultResolution2D: number;
static defaultResolution3D: number;
static fromPolygons(polygons: CSG.Polygon[]): CSG;
static fromSlices(options: any): CSG;
static fromObject(obj: any): CSG;
static fromCompactBinary(bin: any): CSG;
toPolygons(): CSG.Polygon[];
union(csg: CSG[]): CSG;
union(csg: CSG): CSG;
unionSub(csg: CSG, retesselate?: boolean, canonicalize?: boolean): CSG;
unionForNonIntersecting(csg: CSG): CSG;
subtract(csg: CSG[]): CSG;
subtract(csg: CSG): CSG;
subtractSub(csg: CSG, retesselate: boolean, canonicalize: boolean): CSG;
intersect(csg: CSG[]): CSG;
intersect(csg: CSG): CSG;
intersectSub(csg: CSG, retesselate?: boolean, canonicalize?: boolean): CSG;
invert(): CSG;
transform1(matrix4x4: CSG.Matrix4x4): CSG;
transform(matrix4x4: CSG.Matrix4x4): CSG;
toString(): string;
expand(radius: number, resolution: number): CSG;
contract(radius: number, resolution: number): CSG;
stretchAtPlane(normal: number[], point: number[], length: number): CSG;
expandedShell(radius: number, resolution: number, unionWithThis: boolean): CSG;
canonicalized(): CSG;
reTesselated(): CSG;
getBounds(): CSG.Vector3D[];
mayOverlap(csg: CSG): boolean;
cutByPlane(plane: CSG.Plane): CSG;
connectTo(myConnector: CSG.Connector, otherConnector: CSG.Connector, mirror: boolean, normalrotation: number): CSG;
setShared(shared: CSG.Polygon.Shared): CSG;
setColor(args: any): CSG;
toCompactBinary(): {
"class": string;
numPolygons: number;
numVerticesPerPolygon: Uint32Array;
polygonPlaneIndexes: Uint32Array;
polygonSharedIndexes: Uint32Array;
polygonVertices: Uint32Array;
vertexData: Float64Array;
planeData: Float64Array;
shared: CSG.Polygon.Shared[];
};
toPointCloud(cuberadius: any): CSG;
getTransformationAndInverseTransformationToFlatLying(): any;
getTransformationToFlatLying(): any;
lieFlat(): CSG;
projectToOrthoNormalBasis(orthobasis: CSG.OrthoNormalBasis): CAG;
sectionCut(orthobasis: CSG.OrthoNormalBasis): CAG;
fixTJunctions(): CSG;
toTriangles(): any[];
getFeatures(features: any): any;
center(cAxes: string[]): CxG;
toX3D(): Blob;
toStlBinary(): Blob;
toStlString(): string;
toAMFString(m: IAMFStringOptions): Blob;
}
declare module CSG {
function fnNumberSort(a: any, b: any): number;
function parseOption(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAs3DVector(options: any, optionname: any, defaultvalue: any): Vector3D;
function parseOptionAs3DVectorList(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAs2DVector(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAsFloat(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAsInt(options: any, optionname: any, defaultvalue: any): any;
function parseOptionAsBool(options: any, optionname: any, defaultvalue: any): any;
function cube(options: any): CSG;
function sphere(options: any): CSG;
function cylinder(options: any): CSG;
function roundedCylinder(options: any): CSG;
function roundedCube(options: any): CSG;
/**
* polyhedron accepts openscad style arguments. I.e. define face vertices clockwise looking from outside
*/
function polyhedron(options: any): CSG;
function IsFloat(n: any): boolean;
function solve2Linear(a: any, b: any, c: any, d: any, u: any, v: any): number[];
class Vector3D extends CxG {
x: number;
y: number;
z: number;
constructor(v3: Vector3D);
constructor(v2: Vector2D);
constructor(v2: number[]);
constructor(x: number, y: number);
constructor(x: number, y: number, z: number);
static Create(x: number, y: number, z: number): Vector3D;
clone(): Vector3D;
negated(): Vector3D;
abs(): Vector3D;
plus(a: Vector3D): Vector3D;
minus(a: Vector3D): Vector3D;
times(a: number): Vector3D;
dividedBy(a: number): Vector3D;
dot(a: Vector3D): number;
lerp(a: Vector3D, t: number): Vector3D;
lengthSquared(): number;
length(): number;
unit(): Vector3D;
cross(a: Vector3D): Vector3D;
distanceTo(a: Vector3D): number;
distanceToSquared(a: Vector3D): number;
equals(a: Vector3D): boolean;
multiply4x4(matrix4x4: Matrix4x4): Vector3D;
transform(matrix4x4: Matrix4x4): Vector3D;
toString(): string;
randomNonParallelVector(): Vector3D;
min(p: Vector3D): Vector3D;
max(p: Vector3D): Vector3D;
toStlString(): string;
toAMFString(): string;
}
class Vertex extends CxG {
pos: Vector3D;
tag: number;
constructor(pos: Vector3D);
static fromObject(obj: any): Vertex;
flipped(): Vertex;
getTag(): number;
interpolate(other: Vertex, t: number): Vertex;
transform(matrix4x4: Matrix4x4): Vertex;
toString(): string;
toStlString(): string;
toAMFString(): string;
}
class Plane extends CxG {
normal: Vector3D;
w: number;
tag: number;
constructor(normal: Vector3D, w: number);
static fromObject(obj: any): Plane;
static EPSILON: number;
static fromVector3Ds(a: Vector3D, b: Vector3D, c: Vector3D): Plane;
static anyPlaneFromVector3Ds(a: Vector3D, b: Vector3D, c: Vector3D): Plane;
static fromPoints(a: Vector3D, b: Vector3D, c: Vector3D): Plane;
static fromNormalAndPoint(normal: Vector3D, point: Vector3D): Plane;
static fromNormalAndPoint(normal: number[], point: number[]): Plane;
flipped(): Plane;
getTag(): number;
equals(n: Plane): boolean;
transform(matrix4x4: Matrix4x4): Plane;
splitPolygon(polygon: Polygon): {
type: any;
front: any;
back: any;
};
splitLineBetweenPoints(p1: Vector3D, p2: Vector3D): Vector3D;
intersectWithLine(line3d: Line3D): Vector3D;
intersectWithPlane(plane: Plane): Line3D;
signedDistanceToPoint(point: Vector3D): number;
toString(): string;
mirrorPoint(point3d: Vector3D): Vector3D;
}
class Polygon extends CxG {
vertices: Vertex[];
shared: Polygon.Shared;
plane: Plane;
cachedBoundingSphere: any;
cachedBoundingBox: Vector3D[];
static defaultShared: CSG.Polygon.Shared;
constructor(vertices: Vector3D, shared?: Polygon.Shared, plane?: Plane);
constructor(vertices: Vertex[], shared?: Polygon.Shared, plane?: Plane);
static fromObject(obj: any): Polygon;
checkIfConvex(): void;
setColor(args: any): Polygon;
getSignedVolume(): number;
getArea(): number;
getTetraFeatures(features: any): any[];
extrude(offsetvector: any): CSG;
boundingSphere(): any;
boundingBox(): Vector3D[];
flipped(): Polygon;
transform(matrix4x4: Matrix4x4): Polygon;
toString(): string;
projectToOrthoNormalBasis(orthobasis: OrthoNormalBasis): CAG;
/**
* Creates solid from slices (CSG.Polygon) by generating walls
* @param {Object} options Solid generating options
* - numslices {Number} Number of slices to be generated
* - callback(t, slice) {Function} Callback function generating slices.
* arguments: t = [0..1], slice = [0..numslices - 1]
* return: CSG.Polygon or null to skip
* - loop {Boolean} no flats, only walls, it's used to generate solids like a tor
*/
solidFromSlices(options: any): CSG;
/**
*
* @param walls Array of wall polygons
* @param bottom Bottom polygon
* @param top Top polygon
*/
private _addWalls(walls, bottom, top, bFlipped);
static verticesConvex(vertices: Vertex[], planenormal: any): boolean;
static createFromPoints(points: number[][], shared?: CSG.Polygon.Shared, plane?: Plane): Polygon;
static isConvexPoint(prevpoint: any, point: any, nextpoint: any, normal: any): boolean;
static isStrictlyConvexPoint(prevpoint: any, point: any, nextpoint: any, normal: any): boolean;
toStlString(): string;
}
}
declare module CSG.Polygon {
class Shared {
color: any;
tag: any;
constructor(color: any);
static fromObject(obj: any): Shared;
static fromColor(args: any): Shared;
getTag(): any;
getHash(): any;
}
}
declare module CSG {
class PolygonTreeNode {
parent: any;
children: any;
polygon: Polygon;
removed: boolean;
constructor();
addPolygons(polygons: any): void;
remove(): void;
isRemoved(): boolean;
isRootNode(): boolean;
invert(): void;
getPolygon(): Polygon;
getPolygons(result: Polygon[]): void;
splitByPlane(plane: any, coplanarfrontnodes: any, coplanarbacknodes: any, frontnodes: any, backnodes: any): void;
_splitByPlane(plane: any, coplanarfrontnodes: any, coplanarbacknodes: any, frontnodes: any, backnodes: any): void;
addChild(polygon: Polygon): PolygonTreeNode;
invertSub(): void;
recursivelyInvalidatePolygon(): void;
}
class Tree {
polygonTree: PolygonTreeNode;
rootnode: Node;
constructor(polygons: Polygon[]);
invert(): void;
clipTo(tree: Tree, alsoRemovecoplanarFront?: boolean): void;
allPolygons(): Polygon[];
addPolygons(polygons: Polygon[]): void;
}
class Node {
parent: Node;
plane: Plane;
front: any;
back: any;
polygontreenodes: PolygonTreeNode[];
constructor(parent: Node);
invert(): void;
clipPolygons(polygontreenodes: PolygonTreeNode[], alsoRemovecoplanarFront: boolean): void;
clipTo(tree: Tree, alsoRemovecoplanarFront: boolean): void;
addPolygonTreeNodes(polygontreenodes: PolygonTreeNode[]): void;
getParentPlaneNormals(normals: Vector3D[], maxdepth: number): void;
}
class Matrix4x4 {
elements: number[];
constructor(elements?: number[]);
plus(m: Matrix4x4): Matrix4x4;
minus(m: Matrix4x4): Matrix4x4;
multiply(m: Matrix4x4): Matrix4x4;
clone(): Matrix4x4;
rightMultiply1x3Vector(v: Vector3D): Vector3D;
leftMultiply1x3Vector(v: Vector3D): Vector3D;
rightMultiply1x2Vector(v: Vector2D): Vector2D;
leftMultiply1x2Vector(v: Vector2D): Vector2D;
isMirroring(): boolean;
static unity(): Matrix4x4;
static rotationX(degrees: number): Matrix4x4;
static rotationY(degrees: number): Matrix4x4;
static rotationZ(degrees: number): Matrix4x4;
static rotation(rotationCenter: CSG.Vector3D, rotationAxis: CSG.Vector3D, degrees: number): Matrix4x4;
static translation(v: number[]): Matrix4x4;
static translation(v: Vector3D): Matrix4x4;
static mirroring(plane: Plane): Matrix4x4;
static scaling(v: number[]): Matrix4x4;
static scaling(v: Vector3D): Matrix4x4;
}
class Vector2D extends CxG {
x: number;
y: number;
constructor(x: number, y: number);
constructor(x: number[]);
constructor(x: Vector2D);
static fromAngle(radians: number): Vector2D;
static fromAngleDegrees(degrees: number): Vector2D;
static fromAngleRadians(radians: number): Vector2D;
static Create(x: number, y: number): Vector2D;
toVector3D(z: number): Vector3D;
equals(a: Vector2D): boolean;
clone(): Vector2D;
negated(): Vector2D;
plus(a: Vector2D): Vector2D;
minus(a: Vector2D): Vector2D;
times(a: number): Vector2D;
dividedBy(a: number): Vector2D;
dot(a: Vector2D): number;
lerp(a: Vector2D, t: number): Vector2D;
length(): number;
distanceTo(a: Vector2D): number;
distanceToSquared(a: Vector2D): number;
lengthSquared(): number;
unit(): Vector2D;
cross(a: Vector2D): number;
normal(): Vector2D;
multiply4x4(matrix4x4: Matrix4x4): Vector2D;
transform(matrix4x4: Matrix4x4): Vector2D;
angle(): number;
angleDegrees(): number;
angleRadians(): number;
min(p: Vector2D): Vector2D;
max(p: Vector2D): Vector2D;
toString(): string;
abs(): Vector2D;
}
class Line2D extends CxG {
normal: Vector2D;
w: number;
constructor(normal: Vector2D, w: number);
static fromPoints(p1: Vector2D, p2: Vector2D): Line2D;
reverse(): Line2D;
equals(l: Line2D): boolean;
origin(): Vector2D;
direction(): Vector2D;
xAtY(y: number): number;
absDistanceToPoint(point: Vector2D): number;
intersectWithLine(line2d: Line2D): Vector2D;
transform(matrix4x4: Matrix4x4): Line2D;
}
class Line3D extends CxG {
point: Vector3D;
direction: Vector3D;
constructor(point: Vector3D, direction: Vector3D);
static fromPoints(p1: Vector3D, p2: Vector3D): Line3D;
static fromPlanes(p1: Plane, p2: Plane): Line3D;
intersectWithPlane(plane: Plane): Vector3D;
clone(): Line3D;
reverse(): Line3D;
transform(matrix4x4: Matrix4x4): Line3D;
closestPointOnLine(point: Vector3D): Vector3D;
distanceToPoint(point: Vector3D): number;
equals(line3d: Line3D): boolean;
}
class OrthoNormalBasis extends CxG {
v: Vector3D;
u: Vector3D;
plane: Plane;
planeorigin: Vector3D;
constructor(plane: Plane, rightvector?: Vector3D);
static GetCartesian(xaxisid: string, yaxisid: string): OrthoNormalBasis;
static Z0Plane(): OrthoNormalBasis;
getProjectionMatrix(): Matrix4x4;
getInverseProjectionMatrix(): Matrix4x4;
to2D(vec3: Vector3D): Vector2D;
to3D(vec2: Vector2D): Vector3D;
line3Dto2D(line3d: Line3D): Line2D;
line2Dto3D(line2d: Line2D): Line3D;
transform(matrix4x4: Matrix4x4): OrthoNormalBasis;
}
function interpolateBetween2DPointsForY(point1: Vector2D, point2: Vector2D, y: number): number;
function reTesselateCoplanarPolygons(sourcepolygons: CSG.Polygon[], destpolygons: CSG.Polygon[]): void;
class fuzzyFactory {
multiplier: number;
lookuptable: any;
constructor(numdimensions: number, tolerance: number);
lookupOrCreate(els: any, creatorCallback: any): any;
}
class fuzzyCSGFactory {
vertexfactory: fuzzyFactory;
planefactory: fuzzyFactory;
polygonsharedfactory: any;
constructor();
getPolygonShared(sourceshared: Polygon.Shared): Polygon.Shared;
getVertex(sourcevertex: Vertex): Vertex;
getPlane(sourceplane: Plane): Plane;
getPolygon(sourcepolygon: Polygon): Polygon;
getCSG(sourcecsg: CSG): CSG;
}
var staticTag: number;
function getTag(): number;
class Properties {
cube: Properties;
center: any;
facecenters: any[];
roundedCube: Properties;
cylinder: Properties;
start: any;
end: any;
facepointH: any;
facepointH90: any;
sphere: Properties;
facepoint: any;
roundedCylinder: any;
_transform(matrix4x4: Matrix4x4): Properties;
_merge(otherproperties: Properties): Properties;
static transformObj(source: any, result: any, matrix4x4: Matrix4x4): void;
static cloneObj(source: any, result: any): void;
static addFrom(result: any, otherproperties: Properties): void;
}
class Connector extends CxG {
point: Vector3D;
axisvector: Vector3D;
normalvector: Vector3D;
constructor(point: number[], axisvector: Vector3D, normalvector: number[]);
constructor(point: number[], axisvector: number[], normalvector: number[]);
constructor(point: number[], axisvector: number[], normalvector: Vector3D);
constructor(point: Vector3D, axisvector: number[], normalvector: Vector3D);
constructor(point: Vector3D, axisvector: number[], normalvector: number[]);
constructor(point: Vector3D, axisvector: Vector3D, normalvector: Vector3D);
normalized(): Connector;
transform(matrix4x4: Matrix4x4): Connector;
getTransformationTo(other: Connector, mirror: boolean, normalrotation: number): Matrix4x4;
axisLine(): Line3D;
extend(distance: number): Connector;
}
class ConnectorList {
connectors_: Connector[];
closed: boolean;
constructor(connectors: Connector[]);
static defaultNormal: number[];
static fromPath2D(path2D: CSG.Path2D, arg1: any, arg2: any): ConnectorList;
static _fromPath2DTangents(path2D: any, start: any, end: any): ConnectorList;
static _fromPath2DExplicit(path2D: any, angleIsh: any): ConnectorList;
setClosed(bool: boolean): void;
appendConnector(conn: Connector): void;
followWith(cagish: any): CSG;
verify(): void;
}
interface IRadiusOptions {
radius?: number;
resolution?: number;
}
interface ICircleOptions extends IRadiusOptions {
center?: Vector2D | number[];
}
interface IArcOptions extends ICircleOptions {
startangle?: number;
endangle?: number;
maketangent?: boolean;
}
interface IEllpiticalArcOptions extends IRadiusOptions {
clockwise?: boolean;
large?: boolean;
xaxisrotation?: number;
xradius?: number;
yradius?: number;
}
interface IRectangleOptions {
center?: Vector2D;
corner1?: Vector2D;
corner2?: Vector2D;
radius?: Vector2D;
}
interface IRoundRectangleOptions {
roundradius: number;
resolution?: number;
}
class Path2D extends CxG {
closed: boolean;
points: Vector2D[];
lastBezierControlPoint: Vector2D;
constructor(points: number[], closed?: boolean);
constructor(points: Vector2D[], closed?: boolean);
static arc(options: IArcOptions): Path2D;
concat(otherpath: Path2D): Path2D;
appendPoint(point: Vector2D): Path2D;
appendPoints(points: Vector2D[]): Path2D;
close(): Path2D;
rectangularExtrude(width: number, height: number, resolution: number): CSG;
expandToCAG(pathradius: number, resolution: number): CAG;
innerToCAG(): CAG;
transform(matrix4x4: Matrix4x4): Path2D;
appendBezier(controlpoints: any, options: any): Path2D;
appendArc(endpoint: Vector2D, options: IEllpiticalArcOptions): Path2D;
}
}
declare class CAG extends CxG implements ICenter {
sides: CAG.Side[];
isCanonicalized: boolean;
constructor();
static fromSides(sides: CAG.Side[]): CAG;
static fromPoints(points: CSG.Vector2D[]): CAG;
static fromPointsNoCheck(points: CSG.Vector2D[]): CAG;
static fromFakeCSG(csg: CSG): CAG;
static linesIntersect(p0start: CSG.Vector2D, p0end: CSG.Vector2D, p1start: CSG.Vector2D, p1end: CSG.Vector2D): boolean;
static circle(options: CSG.ICircleOptions): CAG;
static rectangle(options: CSG.IRectangleOptions): CAG;
static roundedRectangle(options: any): CAG;
static fromCompactBinary(bin: any): CAG;
toString(): string;
_toCSGWall(z0: any, z1: any): CSG;
_toVector3DPairs(m: CSG.Matrix4x4): CSG.Vector3D[][];
_toPlanePolygons(options: any): CSG.Polygon[];
_toWallPolygons(options: any): any[];
union(cag: CAG[]): CAG;
union(cag: CAG): CAG;
subtract(cag: CAG[]): CAG;
subtract(cag: CAG): CAG;
intersect(cag: CAG[]): CAG;
intersect(cag: CAG): CAG;
transform(matrix4x4: CSG.Matrix4x4): CAG;
area(): number;
flipped(): CAG;
getBounds(): CSG.Vector2D[];
isSelfIntersecting(): boolean;
expandedShell(radius: number, resolution: number): CAG;
expand(radius: number, resolution: number): CAG;
contract(radius: number, resolution: number): CAG;
extrudeInOrthonormalBasis(orthonormalbasis: CSG.OrthoNormalBasis, depth: number, options?: any): CSG;
extrudeInPlane(axis1: any, axis2: any, depth: any, options: any): CSG;
extrude(options: CAG_extrude_options): CSG;
rotateExtrude(options: any): CSG;
check(): void;
canonicalized(): CAG;
toCompactBinary(): {
'class': string;
sideVertexIndices: Uint32Array;
vertexData: Float64Array;
};
getOutlinePaths(): CSG.Path2D[];
overCutInsideCorners(cutterradius: any): CAG;
center(cAxes: string[]): CxG;
toDxf(): Blob;
static PathsToDxf(paths: CSG.Path2D[]): Blob;
}
declare module CAG {
class Vertex {
pos: CSG.Vector2D;
tag: number;
constructor(pos: CSG.Vector2D);
toString(): string;
getTag(): number;
}
class Side extends CxG {
vertex0: Vertex;
vertex1: Vertex;
tag: number;
constructor(vertex0: Vertex, vertex1: Vertex);
static _fromFakePolygon(polygon: CSG.Polygon): Side;
toString(): string;
toPolygon3D(z0: any, z1: any): CSG.Polygon;
transform(matrix4x4: CSG.Matrix4x4): Side;
flipped(): Side;
direction(): CSG.Vector2D;
getTag(): number;
lengthSquared(): number;
length(): number;
}
class fuzzyCAGFactory {
vertexfactory: CSG.fuzzyFactory;
constructor();
getVertex(sourcevertex: Vertex): Vertex;
getSide(sourceside: Side): Side;
getCAG(sourcecag: CAG): CAG;
}
}
interface CAG_extrude_options {
offset?: number[];
twistangle?: number;
twiststeps?: number;
}
declare module CSG {
class Polygon2D extends CAG {
constructor(points: Vector2D[]);
}
}

View File

@@ -5,6 +5,7 @@ import amqp = require("amqplib");
var msg = "Hello World";
// test promise api
amqp.connect("amqp://localhost")
.then(connection => {
return connection.createChannel()
@@ -21,6 +22,13 @@ amqp.connect("amqp://localhost")
.ensure(() => connection.close());
});
// test promise api properties
var amqpMessage: amqp.Message;
amqpMessage.properties.contentType = "application/json";
var amqpAssertExchangeOptions: amqp.Options.AssertExchange;
var anqpAssertExchangeReplies: amqp.Replies.AssertExchange;
// callback api tests
import amqpcb = require("amqplib/callback_api");
@@ -51,3 +59,9 @@ amqpcb.connect("amqp://localhost", (err, connection) => {
});
}
});
// test callback api properties
var amqpcbMessage: amqpcb.Message;
amqpcbMessage.properties.contentType = "application/json";
var amqpcbAssertExchangeOptions: amqpcb.Options.AssertExchange;
var anqpcbAssertExchangeReplies: amqpcb.Replies.AssertExchange;

20
amqplib/amqplib.d.ts vendored
View File

@@ -66,7 +66,7 @@ declare module "amqplib/properties" {
contentType?: string;
contentEncoding?: string;
headers?: Object;
headers?: any;
priority?: number;
correlationId?: string;
replyTo?: string;
@@ -81,7 +81,7 @@ declare module "amqplib/properties" {
noAck?: boolean;
exclusive?: boolean;
priority?: number;
arguments?: Object;
arguments?: any;
}
interface Get {
noAck?: boolean;
@@ -90,8 +90,8 @@ declare module "amqplib/properties" {
interface Message {
content: Buffer;
fields: Object;
properties: Object;
fields: any;
properties: any;
}
}
@@ -100,9 +100,9 @@ declare module "amqplib" {
import events = require("events");
import when = require("when");
import shared = require("amqplib/properties")
import Replies = shared.Replies;
import Options = shared.Options;
import Message = shared.Message;
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
interface Connection extends events.EventEmitter {
close(): when.Promise<void>;
@@ -156,9 +156,9 @@ declare module "amqplib/callback_api" {
import events = require("events");
import shared = require("amqplib/properties")
import Replies = shared.Replies;
import Options = shared.Options;
import Message = shared.Message;
export import Replies = shared.Replies;
export import Options = shared.Options;
export import Message = shared.Message;
interface Connection extends events.EventEmitter {
close(callback?: (err: any) => void): void;

View File

@@ -0,0 +1,16 @@
/// <reference path="angular-dialog-service.d.ts" />
var options : angular.dialogservice.IDialogOptions = {};
options.animation = true;
options.backdrop = true;
options.keyboard = true;
options.backdropClass = "some-css-class";
options.windowClass = "some-css-class";
options.size = 'md';
var dialogs : angular.dialogservice.IDialogService;
dialogs.error('Error','An unknown error occurred preventing the completion of the requested action.');
dialogs.wait('Creating User','Please wait while we attempt to create user "Michael Conroy."<br><br>This should only take a moment.',50);
dialogs.notify('Something Happened','Something happened at this point in the application that I wish to let you know about');
dialogs.create('url/to/a/template','ctrlrToUse',{},{});

View File

@@ -0,0 +1,82 @@
// Type definitions for Angular Dialog Service 5.2.8
// Project: https://github.com/m-e-conroy/angular-dialog-service
// Definitions by: William Comartin <https://github.com/wcomartin>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts"/>
/// <reference path="../angular-ui-bootstrap/angular-ui-bootstrap.d.ts"/>
declare module angular.dialogservice {
interface IDialogOptions {
/**
* Set to false to disable animations on new modal/backdrop. Does not toggle animations for modals/backdrops that are already displayed.
*
* @default false
*/
animation?: boolean;
/**
* controls the presence of a backdrop
* Allowed values:
* - true (default)
* - false (no backdrop)
* - 'static' backdrop is present but modal window is not closed when clicking outside of the modal window
*
* @default true
*/
backdrop?: boolean | string;
/**
* indicates whether the dialog should be closable by hitting the ESC key
*
* @default true
*/
keyboard?: boolean;
/**
* additional CSS class(es) to be added to a modal backdrop template
*
* @default 'dialogs-backdrop-default'
*/
backdropClass?: string;
/**
* additional CSS class(es) to be added to a modal window template
*
* @default 'dialogs-default'
*/
windowClass?: string;
/**
* Optional suffix of modal window class. The value used is appended to the `modal-` class, i.e. a value of `sm` gives `modal-sm`.
*
* @default 'lg'
*/
size?: string;
}
interface IDialogService {
/**
* Opens a new error modal instance.
*/
error(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
/**
* Opens a new wait modal instance.
*/
wait(header: string, msg: string, progress: number, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
/**
* Opens a new notify modal instance.
*/
notify(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
/**
* Opens a new confirm modal instance.
*/
confirm(header: string, msg: string, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
/**
* Opens a new custom modal instance.
*/
create(url: string, ctrlr: string, data: any, opts?: IDialogOptions): ng.ui.bootstrap.IModalServiceInstance
}
}

View File

@@ -297,6 +297,7 @@ declare module AngularFormly {
bound?: any;
expression?: any;
value?: any;
[key: string]: any;
};

View File

@@ -0,0 +1,64 @@
/// <reference path="./angular-httpi.d.ts" />
(function() {
'use strict';
var app = angular.module("Demo", ["httpi"]);
// -------------------------------------------------- //
// -------------------------------------------------- //
// I control the main demo.
app.controller(
"DemoController",
function($scope: ng.IScope, httpi: Httpi.HttpiFactory) {
console.warn("None of the API endpoints exist - they will all throw 404.");
// NOTE: The (.|.) notation will be stripped out automatically; it's only
// here to improve readability of the "happy paths" for interpolation
// labels. The following urls are pre-processed to be identical:
// --
// api/friends/( :listCommand | :id/:itemCommand )
// api/friends/:listCommand:id/:itemCommand
var resource = httpi.resource("api/friends/( :listCommand | :id/:itemCommand )");
// Clear list of friends - matching listCommand.
resource.post({
data: {
listCommand: "reset"
}
});
// Create a new friend - no matching URL parameters.
resource.post({
data: {
name: "Tricia"
}
});
// Get a given friend - ID matching.
resource.get({
data: {
id: 4
}
});
// Make best friend - ID, itemCommand matching.
resource.post({
data: {
id: 4,
itemCommand: "make-best-friend"
}
});
// Get gets friends - no matching URL parameters.
resource.get({
params: {
limit: "besties"
}
});
// Get a friend as a JSONP request.
// --
// NOTE: The "resource" will auto-inject the "JSON_CALLBACK" marker that
// AngularJS will automatically replace with an internal callback name.
resource.jsonp({
data: {
id: 43
}
});
}
);
})();

42
angular-httpi/angular-httpi.d.ts vendored Normal file
View File

@@ -0,0 +1,42 @@
// Type definitions for angular-httpi
// Project: https://github.com/bennadel/httpi
// Definitions by: Andrew Camilleri <https://github.com/Kukks>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module Httpi {
export interface HttpiPayload extends ng.IRequestShortcutConfig {
method?: string;
url?: string;
params?: {};
data?: {};
keepTrailingSlash?: boolean;
}
export interface HttpiFactory {
(config: HttpiPayload): ng.IHttpPromise<{}>;
resource(url: string): HttpiResource;
}
export class HttpiResource {
constructor(http: ng.IHttpService, url: string);
delete<T>(config: HttpiPayload): ng.IHttpPromise<T>;
get<T>(config: HttpiPayload): ng.IHttpPromise<T>;
head<T>(config: HttpiPayload): ng.IHttpPromise<T>;
jsonp<T>(config: HttpiPayload): ng.IHttpPromise<T>;
post<T>(config: HttpiPayload): ng.IHttpPromise<T>;
put<T>(config: HttpiPayload): ng.IHttpPromise<T>;
setKeepTrailingSlash(newKeepTrailingSlash: boolean): HttpiResource;
}
}

View File

@@ -221,4 +221,19 @@ declare module angular.material {
setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
}
interface IDateLocaleProvider {
months: string[];
shortMonths: string[];
days: string[];
shortDays: string[];
dates: string[];
firstDayOfWeek: number;
parseDate(dateString: string): Date;
formatDate(date: Date): string;
monthHeaderFormatter(date: Date): string;
weekNumberFormatter(weekNumber: number): string;
msgCalendar: string;
msgOpenCalendar: string;
}
}

View File

@@ -235,10 +235,10 @@ declare module angular.ui {
*/
go(to: string, params?: {}, options?: IStateOptions): angular.IPromise<any>;
go(to: IState, params?: {}, options?: IStateOptions): angular.IPromise<any>;
transitionTo(state: string, params?: {}, updateLocation?: boolean): ng.IPromise<any>;
transitionTo(state: IState, params?: {}, updateLocation?: boolean): ng.IPromise<any>;
transitionTo(state: string, params?: {}, options?: IStateOptions): ng.IPromise<any>;
transitionTo(state: IState, params?: {}, options?: IStateOptions): ng.IPromise<any>;
transitionTo(state: string, params?: {}, updateLocation?: boolean): angular.IPromise<any>;
transitionTo(state: IState, params?: {}, updateLocation?: boolean): angular.IPromise<any>;
transitionTo(state: string, params?: {}, options?: IStateOptions): angular.IPromise<any>;
transitionTo(state: IState, params?: {}, options?: IStateOptions): angular.IPromise<any>;
includes(state: string, params?: {}): boolean;
is(state:string, params?: {}): boolean;
is(state: IState, params?: {}): boolean;
@@ -250,10 +250,10 @@ declare module angular.ui {
current: IState;
/** A param object, e.g. {sectionId: section.id)}, that you'd like to test against the current active state. */
params: IStateParamsService;
reload(): ng.IPromise<any>;
reload(): angular.IPromise<any>;
/** Currently pending transition. A promise that'll resolve or reject. */
transition: ng.IPromise<{}>;
transition: angular.IPromise<{}>;
$current: IResolvedState;
}

View File

@@ -42,7 +42,7 @@ To avoid cluttering the list of suggestions as you type in your IDE, all interfa
**ngMockE2E** does not define a new namespace, but rather modifies some of **ng**'s interfaces.
Bellow is an example of how to use the interfaces:
Below is an example of how to use the interfaces:
```ts
function MainController($scope: ng.IScope, $http: ng.IHttpService) {
// code assistance will now be available for $scope and $http

View File

@@ -121,7 +121,7 @@ declare module angular.animate {
}
/**
* AngularProvider
* AnimateProvider
* see http://docs.angularjs.org/api/ngAnimate/provider/$animateProvider
*/
interface IAnimateProvider {

View File

@@ -8,11 +8,24 @@ interface IMyResourceClass extends angular.resource.IResourceClass<IMyResource>
///////////////////////////////////////
var actionDescriptor: angular.resource.IActionDescriptor;
actionDescriptor.url = '/api/test-url/'
actionDescriptor.headers = { header: 'value' };
actionDescriptor.isArray = true;
actionDescriptor.method = 'method action';
actionDescriptor.params = { key: 'value' };
angular.injector(['ng']).invoke(function ($cacheFactory: angular.ICacheFactoryService, $timeout: angular.ITimeoutService) {
actionDescriptor.method = 'method action';
actionDescriptor.params = { key: 'value' };
actionDescriptor.url = '/api/test-url/';
actionDescriptor.isArray = true;
actionDescriptor.transformRequest = function () { };
actionDescriptor.transformRequest = [function () { }];
actionDescriptor.transformResponse = function () { };
actionDescriptor.transformResponse = [function () { }];
actionDescriptor.headers = { header: 'value' };
actionDescriptor.cache = true;
actionDescriptor.cache = $cacheFactory('cacheId');
actionDescriptor.timeout = 1000;
actionDescriptor.timeout = $timeout(function () { });
actionDescriptor.withCredentials = true;
actionDescriptor.responseType = 'response type';
actionDescriptor.interceptor = { key: 'value' };
});
///////////////////////////////////////

View File

@@ -46,11 +46,18 @@ declare module angular.resource {
// Just a reference to facilitate describing new actions
interface IActionDescriptor {
url?: string;
method: string;
isArray?: boolean;
params?: any;
url?: string;
isArray?: boolean;
transformRequest?: angular.IHttpRequestTransformer | angular.IHttpRequestTransformer[];
transformResponse?: angular.IHttpResponseTransformer | angular.IHttpResponseTransformer[];
headers?: any;
cache?: boolean | angular.ICacheObject;
timeout?: number | angular.IPromise<any>;
withCredentials?: boolean;
responseType?: string;
interceptor?: any;
}
// Baseclass for everyresource with default actions.

View File

@@ -620,7 +620,7 @@ declare module angular {
}
///////////////////////////////////////////////////////////////////////////
// AngularProvider
// AnimateProvider
// see http://docs.angularjs.org/api/ng/provider/$animateProvider
///////////////////////////////////////////////////////////////////////////
interface IAnimateProvider {
@@ -1390,7 +1390,7 @@ declare module angular {
}
// See the jsdoc for transformData() at https://github.com/angular/angular.js/blob/master/src/ng/http.js#L228
interface IHttpResquestTransformer {
interface IHttpRequestTransformer {
(data: any, headersGetter: IHttpHeadersGetter): any;
}
@@ -1427,7 +1427,7 @@ declare module angular {
* headers and returns its transformed (typically serialized) version.
* @see {@link https://docs.angularjs.org/api/ng/service/$http#transforming-requests-and-responses}
*/
transformRequest?: IHttpResquestTransformer |IHttpResquestTransformer[];
transformRequest?: IHttpRequestTransformer |IHttpRequestTransformer[];
/**
* Transform function or an array of such functions. The transform function takes the http response body and

View File

@@ -1,4 +1,4 @@
/// Type definitions for Angular JS 1.0 (ngCookies module)
// Type definitions for Angular JS 1.0 (ngCookies module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

View File

@@ -1,6 +1,6 @@
// Type definitions for Angular Scenario Testing 1.0 (ngScenario module)
// Project: [http://angularjs.org]
// Definitions by: [RomanoLindano]
// Project: http://angularjs.org
// Definitions by: RomanoLindano <https://github.com/RomanoLindano>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angularScenario {

View File

@@ -0,0 +1,17 @@
/// <reference path="../anydb-sql/anydb-sql.d.ts" />
/// <reference path="anydb-sql-migrations" />
import anydbsql = require('anydb-sql');
import { Table, Column } from 'anydb-sql'
import migrator = require('anydb-sql-migrations');
function do_not_run() {
var db = anydbsql({
url: 'postgres://user:pass@host:port/database',
connections: { min: 2, max: 20 }
});
migrator
.create(db, '/path/to/migrations/dir')
.run();
}

View File

@@ -0,0 +1,34 @@
// Type definitions for anydb-sql-migrations
// Project: https://github.com/spion/anydb-sql-migrations
// Definitions by: Gorgi Kosev <https://github.com/spion>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
/// <reference path="../anydb-sql/anydb-sql.d.ts" />
declare module "anydb-sql-migrations" {
import Promise = require('bluebird');
import { Column, Table, Transaction, AnydbSql } from 'anydb-sql';
export interface Migration {
version: string;
}
export interface MigrationsTable extends Table<Migration> {
version: Column<string>;
}
export interface MigFn {
(tx: Transaction): Promise<any>;
}
export interface MigrationTask {
up: MigFn;
down: MigFn;
name: string;
}
export function create(db: AnydbSql, tasks: any): {
run: () => Promise<any>;
migrateTo: (target?: string) => Promise<any>;
check: (f: (m: {
type: string;
items: MigrationTask[];
}) => any) => Promise<any>;
};
}

View File

@@ -0,0 +1,70 @@
/// <reference path="anydb-sql.d.ts" />
import anydbsql = require('anydb-sql');
import { Table, Column } from 'anydb-sql'
function do_not_run() {
var db = anydbsql({
url: 'postgres://user:pass@host:port/database',
connections: { min: 2, max: 20 }
});
// Table Post
interface Post {
content: string;
userId: string;
date: string;
}
interface PostTable extends Table<Post> {
content: Column<string>;
userId: Column<string>;
date: Column<string>;
}
var post = <PostTable>db.define<Post>({
name: 'posts',
columns: {
content: {},
userId: {},
date: {}
}
});
// Table User
interface User {
id: string;
email: string;
password: string;
name: string;
}
interface UserTable extends Table<User> {
id: Column<string>;
email: Column<string>;
password: Column<string>;
name: Column<string>;
}
var user = <UserTable>db.define<User>({
name: 'users',
columns: {
id: { primaryKey: true },
email: {},
password: {},
name: {},
date: {}
},
has: {
posts: { from: 'posts', many: true },
group: { from: 'groups'}
}
});
user.select(user.name, post.content)
.from(user.join(post).on(user.id.equals(post.userId)))
.where(post.date.gt('123'))
.all()
}

194
anydb-sql/anydb-sql.d.ts vendored Normal file
View File

@@ -0,0 +1,194 @@
// Type definitions for anydb-sql
// Project: https://github.com/doxout/anydb-sql
// Definitions by: Gorgi Kosev <https://github.com/spion>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../bluebird/bluebird.d.ts" />
declare module "anydb-sql" {
import Promise = require('bluebird');
interface AnyDBPool extends anydbSQL.DatabaseConnection {
query:(text:string, values:any[], callback:(err:Error, result:any)=>void)=>void
begin:()=>anydbSQL.Transaction
close:(err:Error)=>void
}
interface Dictionary<T> { [key:string]:T; }
module anydbSQL {
export interface OrderByValueNode {}
export interface ColumnDefinition {
primaryKey?:boolean;
dataType?:string;
references?: {table:string; column: string}
notNull?:boolean
}
export interface TableDefinition {
name:string
columns:Dictionary<ColumnDefinition>
has?:Dictionary<{from:string; many?:boolean}>
}
export interface QueryLike {
query:string;
values: any[]
text:string
}
export interface DatabaseConnection {
queryAsync<T>(query:string, ...params:any[]):Promise<{rowCount:number;rows:T[]}>
queryAsync<T>(query:QueryLike):Promise<{rowCount:number;rows:T[]}>
}
export interface Transaction extends DatabaseConnection {
rollback():void
commitAsync():Promise<void>
}
export interface SubQuery<T> {
select(node:Column<T>):SubQuery<T>
where(...nodes:any[]):SubQuery<T>
from(table:TableNode):SubQuery<T>
group(...nodes:any[]):SubQuery<T>
order(criteria:OrderByValueNode):SubQuery<T>
notExists(subQuery:SubQuery<any>):SubQuery<T>
}
interface Executable<T> {
get():Promise<T>
getWithin(tx:DatabaseConnection):Promise<T>
exec():Promise<void>
all():Promise<T[]>
execWithin(tx:DatabaseConnection):Promise<void>
allWithin(tx:DatabaseConnection):Promise<T[]>
toQuery():QueryLike;
}
interface Queryable<T> {
where(...nodes:any[]):Query<T>
delete():ModifyingQuery
select<U>(...nodes:any[]):Query<U>
selectDeep<U>(table: Table<T>): Query<T>
selectDeep<U>(...nodesOrTables:any[]):Query<U>
}
export interface Query<T> extends Executable<T>, Queryable<T> {
from(table:TableNode):Query<T>
update(o:Dictionary<any>):ModifyingQuery
update(o:{}):ModifyingQuery
group(...nodes:any[]):Query<T>
order(...criteria:OrderByValueNode[]):Query<T>
limit(l:number):Query<T>
offset(o:number):Query<T>
}
export interface ModifyingQuery extends Executable<void> {
returning<U>(...nodes:any[]):Query<U>
where(...nodes:any[]):ModifyingQuery
}
export interface TableNode {
join(table:TableNode):JoinTableNode
leftJoin(table:TableNode):JoinTableNode
}
export interface JoinTableNode extends TableNode {
on(filter:BinaryNode):TableNode
on(filter:string):TableNode
}
interface CreateQuery extends Executable<void> {
ifNotExists():Executable<void>
}
interface DropQuery extends Executable<void> {
ifExists():Executable<void>
}
export interface Table<T> extends TableNode, Queryable<T> {
create():CreateQuery
drop():DropQuery
as(name:string):Table<T>
update(o:any):ModifyingQuery
insert(row:T):ModifyingQuery
insert(rows:T[]):ModifyingQuery
select():Query<T>
select<U>(...nodes:any[]):Query<U>
from<U>(table:TableNode):Query<U>
star():Column<any>
subQuery<U>():SubQuery<U>
eventEmitter:{emit:(type:string, ...args:any[])=>void
on:(eventName:string, handler:Function)=>void}
columns:Column<any>[]
sql: SQL;
alter():AlterQuery<T>
}
export interface AlterQuery<T> extends Executable<void> {
addColumn(column:Column<any>): AlterQuery<T>;
addColumn(name: string, options:string): AlterQuery<T>;
dropColumn(column: Column<any>): AlterQuery<T>;
renameColumn(column: Column<any>, newColumn: Column<any>):AlterQuery<T>;
renameColumn(column: Column<any>, newName: string):AlterQuery<T>;
renameColumn(name: string, newName: string):AlterQuery<T>;
rename(newName: string): AlterQuery<T>
}
export interface SQL {
functions: {
LOWER(c:Column<string>):Column<string>
}
}
export interface BinaryNode {
and(node:BinaryNode):BinaryNode
or(node:BinaryNode):BinaryNode
}
export interface Column<T> {
in(arr:T[]):BinaryNode
in(subQuery:SubQuery<T>):BinaryNode
notIn(arr:T[]):BinaryNode
equals(node:any):BinaryNode
notEquals(node:any):BinaryNode
gte(node:any):BinaryNode
lte(node:any):BinaryNode
gt(node:any):BinaryNode
lt(node:any):BinaryNode
like(str:string):BinaryNode
multiply:{
(node:Column<T>):Column<T>
(n:number):Column<number>
}
isNull():BinaryNode
isNotNull():BinaryNode
sum():Column<number>
count():Column<number>
count(name:string):Column<number>
distinct():Column<T>
as(name:string):Column<T>
ascending:OrderByValueNode
descending:OrderByValueNode
asc:OrderByValueNode
desc:OrderByValueNode
}
export interface AnydbSql extends DatabaseConnection {
define<T>(map:TableDefinition):Table<T>;
transaction<T>(fn:(tx:Transaction)=>Promise<T>):Promise<T>
allOf(...tables:Table<any>[]):any
models:Dictionary<Table<any>>
functions:{LOWER:(name:Column<string>)=>Column<string>
RTRIM:(name:Column<string>)=>Column<string>}
makeFunction(name:string):Function
begin():Transaction
open():void;
close():void;
getPool():AnyDBPool;
dialect():string;
}
}
function anydbSQL(config:Object):anydbSQL.AnydbSql;
export = anydbSQL;
}

View File

@@ -18,6 +18,7 @@ appInsights.client.trackEvent("custom event", {customProperty: "custom property
appInsights.client.trackException(new Error("handled exceptions can be logged with this method"));
appInsights.client.trackMetric("custom metric", 3);
appInsights.client.trackTrace("trace message");
appInsights.client.trackDependency("dependency name", "commandName", 500, true);
// assign common properties to all telemetry
appInsights.client.commonProperties = {

View File

@@ -1,4 +1,4 @@
// Type definitions for Application Insights v0.15.1
// Type definitions for Application Insights v0.15.7
// Project: https://github.com/Microsoft/ApplicationInsights-node.js
// Definitions by: Scott Southwood <https://github.com/scsouthw/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -342,6 +342,19 @@ interface Client {
trackRequest(request: any /* http.ServerRequest */, response: any /* http.ServerResponse */, properties?: {
[key: string]: string;
}): void;
/**
* Log information about a dependency of your app. Typically used to track the time database calls or outgoing http requests take from your server.
* @param name The name of the dependency (i.e. "myDatabse")
* @param commandname The name of the command executed on the dependency
* @param elapsedTimeMs The amount of time in ms that the dependency took to return the result
* @param success True if the dependency succeeded, false otherwise
* @param dependencyTypeName The type of the dependency (i.e. "SQL" "HTTP"). Defaults to empty.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param dependencyKind ContractsModule.DependencyKind of this dependency. Defaults to Other.
* @param async True if the dependency was executed asynchronously, false otherwise. Defaults to false
* @param dependencySource ContractsModule.DependencySourceType of this dependency. Defaults to Undefined.
*/
trackDependency(name: string, commandName: string, elapsedTimeMs: number, success: boolean, dependencyTypeName?: string, properties?: {}, dependencyKind?: any, async?: boolean, dependencySource?: number): void;
/**
* Immediately send all queued telemetry.
*/

View File

@@ -0,0 +1,16 @@
/// <reference path="./assertsharp.d.ts" />
import Assert from "assertsharp";
Assert.AreEqual(0, 0, "Pass");
Assert.AreNotEqual(0, 1, "Pass");
Assert.AreNotSame(new Date(), new Date(), "Pass");
Assert.AreSequenceEqual([0], [0], (x, y) => x === y, "Pass");
Assert.Fail("Should fail");
Assert.IsFalse(false, "Pass");
Assert.IsInstanceOfType(new Date(), Date, "Pass");
Assert.IsNotInstanceOfType(true, Date, "Pass");
Assert.IsNotNull(new Date(), "Pass");
Assert.IsNull(null, "Pass");
Assert.IsTrue(true, "Pass");
Assert.Throws(() => { throw ""; }, "Pass");

21
assertsharp/assertsharp.d.ts vendored Normal file
View File

@@ -0,0 +1,21 @@
// Type definitions for assertsharp
// Project: https://www.npmjs.com/package/assertsharp
// Definitions by: Bruno Leonardo Michels <https://github.com/brunolm>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "assertsharp" {
export default class Assert {
static AreEqual<T>(expected: T, actual: T, message?: string): void;
static AreNotEqual<T>(notExpected: T, actual: T, message?: string): void;
static AreNotSame<T>(notExpected: T, actual: T, message?: string): void;
static AreSequenceEqual<T>(expected: T[], actual: T[], equals?: (x: any, y: any) => boolean, message?: string): void;
static Fail(message?: string): void;
static IsFalse(actual: boolean, message?: string): void;
static IsInstanceOfType(actual: any, expectedType: Function, message?: string): void;
static IsNotInstanceOfType(actual: any, wrongType: Function, message?: string): void;
static IsNotNull(actual: any, message?: string): void;
static IsNull(actual: any, message?: string): void;
static IsTrue(actual: boolean, message?: string): void;
static Throws(fn: () => void, message?: string): void;
}
}

View File

@@ -1,13 +1,256 @@
/// <reference path="aws-sdk.d.ts" />
import awsSdk = require('aws-sdk');
import AWS = require('aws-sdk');
var str: string;
var creds: awsSdk.Credentials;
var creds: AWS.Credentials;
creds = new awsSdk.Credentials(str, str);
creds = new awsSdk.Credentials(str, str, str);
creds = new AWS.Credentials(str, str);
creds = new AWS.Credentials(str, str, str);
str = creds.accessKeyId;
// more
/*
* SQS
*/
var sqs:AWS.SQS
//Default constructor
sqs = new AWS.SQS();
//Locking the API Version
sqs = new AWS.SQS({apiVersion: '2012-11-05'});
// Locking the API Version Globally
AWS.config.apiVersions = {
sqs: '2012-11-05',
// other service API versions
};
sqs.addPermission({
AWSAccountIds: [ /* required */
'STRING_VALUE',
/* more items */
],
Actions: [ /* required */
'STRING_VALUE',
/* more items */
],
Label: 'STRING_VALUE', /* required */
QueueUrl: 'STRING_VALUE' /* required */
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.changeMessageVisibility({
QueueUrl: 'STRING_VALUE', /* required */
ReceiptHandle: 'STRING_VALUE', /* required */
VisibilityTimeout: 0 /* required */
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.changeMessageVisibilityBatch({
Entries: [ /* required */
{
Id: 'STRING_VALUE', /* required */
ReceiptHandle: 'STRING_VALUE', /* required */
VisibilityTimeout: 0
},
/* more items */
],
QueueUrl: 'STRING_VALUE' /* required */
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.createQueue({
QueueName: 'STRING_VALUE', /* required */
Attributes: {
someKey: 'STRING_VALUE',
/* anotherKey: ... */
}
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.deleteMessage({
QueueUrl: 'STRING_VALUE', /* required */
ReceiptHandle: 'STRING_VALUE' /* required */
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.deleteMessageBatch({
Entries: [ /* required */
{
Id: 'STRING_VALUE', /* required */
ReceiptHandle: 'STRING_VALUE' /* required */
},
/* more items */
],
QueueUrl: 'STRING_VALUE' /* required */
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.deleteQueue({
QueueUrl: 'STRING_VALUE' /* required */
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.getQueueAttributes({
QueueUrl: 'STRING_VALUE', /* required */
AttributeNames: [
'Policy | VisibilityTimeout | MaximumMessageSize | MessageRetentionPeriod | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | CreatedTimestamp | LastModifiedTimestamp | QueueArn | ApproximateNumberOfMessagesDelayed | DelaySeconds | ReceiveMessageWaitTimeSeconds | RedrivePolicy',
/* more items */
]
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.getQueueUrl({
QueueName: 'STRING_VALUE', /* required */
QueueOwnerAWSAccountId: 'STRING_VALUE'
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.listDeadLetterSourceQueues({
QueueUrl: 'STRING_VALUE' /* required */
}, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.listQueues({
QueueNamePrefix: 'STRING_VALUE'
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.purgeQueue({
QueueUrl: 'STRING_VALUE' /* required */
}, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.receiveMessage({
QueueUrl: 'STRING_VALUE', /* required */
AttributeNames: [
'Policy | VisibilityTimeout | MaximumMessageSize | MessageRetentionPeriod | ApproximateNumberOfMessages | ApproximateNumberOfMessagesNotVisible | CreatedTimestamp | LastModifiedTimestamp | QueueArn | ApproximateNumberOfMessagesDelayed | DelaySeconds | ReceiveMessageWaitTimeSeconds | RedrivePolicy',
/* more items */
],
MaxNumberOfMessages: 0,
MessageAttributeNames: [
'STRING_VALUE',
/* more items */
],
VisibilityTimeout: 0,
WaitTimeSeconds: 0
}, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.removePermission({
Label: 'STRING_VALUE', /* required */
QueueUrl: 'STRING_VALUE' /* required */
}, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.sendMessage({
MessageBody: 'STRING_VALUE', /* required */
QueueUrl: 'STRING_VALUE', /* required */
DelaySeconds: 0,
MessageAttributes: {
someKey: {
DataType: 'STRING_VALUE', /* required */
BinaryListValues: [
new Buffer('...') || 'STRING_VALUE',
/* more items */
],
BinaryValue: new Buffer('...') || 'STRING_VALUE',
StringListValues: [
'STRING_VALUE',
/* more items */
],
StringValue: 'STRING_VALUE'
},
/* anotherKey: ... */
}
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.sendMessageBatch({
Entries: [ /* required */
{
Id: 'STRING_VALUE', /* required */
MessageBody: 'STRING_VALUE', /* required */
DelaySeconds: 0,
MessageAttributes: {
someKey: {
DataType: 'STRING_VALUE', /* required */
BinaryListValues: [
new Buffer('...') ,
/* more items */
],
BinaryValue: new Buffer('...'),
StringListValues: [
'STRING_VALUE',
/* more items */
],
StringValue: 'STRING_VALUE'
},
/* anotherKey: ... */
}
},
/* more items */
],
QueueUrl: 'STRING_VALUE' /* required */
},
function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
sqs.setQueueAttributes({
Attributes: { /* required */
someKey: 'STRING_VALUE',
/* anotherKey: ... */
},
QueueUrl: 'STRING_VALUE' /* required */
}, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});

View File

@@ -0,0 +1 @@
--noImplicitAny --module commonjs --target es5

211
aws-sdk/aws-sdk.d.ts vendored
View File

@@ -30,6 +30,16 @@ declare module "aws-sdk" {
xhrAsync?: boolean;
xhrWithCredentials?: boolean;
}
export class Endpoint {
constructor(endpoint:string);
host:string;
hostname:string;
href:string;
port:number;
protocol:string;
}
export interface Services {
autoscaling?: any;
@@ -99,7 +109,25 @@ declare module "aws-sdk" {
export class SQS {
constructor(options?: any);
public client: Sqs.Client;
endpoint:Endpoint;
addPermission(params: SQS.AddPermissionParams, callback: (err:Error, data:any) => void): void;
changeMessageVisibility(params: SQS.ChangeMessageVisibilityParams, callback: (err:Error, data:any) => void): void;
changeMessageVisibilityBatch(params: SQS.ChangeMessageVisibilityBatchParams, callback: (err:Error, data:SQS.ChangeMessageVisibilityBatchResponse) => void): void;
createQueue(params: SQS.CreateQueueParams, callback: (err: Error, data: SQS.CreateQueueResult) => void): void;
deleteMessage(params: SQS.DeleteMessageParams, callback: (err: Error, data: any) => void): void;
deleteMessageBatch(params: SQS.DeleteMessageBatchParams, callback: (err: Error, data: SQS.DeleteMessageBatchResult) => void): void;
deleteQueue(params: { QueueUrl: string; }, callback: (err: Error, data: any) => void): void;
getQueueAttributes(params: SQS.GetQueueAttributesParams, callback: (err: Error, data: SQS.GetQueueAttributesResult) => void): void;
getQueueUrl(params: SQS.GetQueueUrlParams, callback: (err: Error, data: { QueueUrl: string; }) => void): void;
listDeadLetterSourceQueues(params: {QueueUrl:string}, callback: (err: Error, data: {queueUrls: string[]}) => void): void;
listQueues(params: {QueueNamePrefix?:string}, callback: (err: Error, data: {QueueUrls: string[]}) => void): void;
purgeQueue(params: {QueueUrl: string}, callback: (err: Error, data: any) => void): void;
receiveMessage(params: SQS.ReceiveMessageParams, callback: (err: Error, data: SQS.ReceiveMessageResult) => void): void;
removePermission(params: {QueueUrl: string, Label: string}, callback: (err: Error, data: any) => void): void;
sendMessage(params: SQS.SendMessageParams, callback: (err: Error, data: SQS.SendMessageResult) => void): void;
sendMessageBatch(params: SQS.SendMessageBatchParams, callback: (err: Error, data: SQS.SendMessageBatchResult) => void): void;
setQueueAttributes(params: SQS.SetQueueAttributesParams, callback: (err: Error, data: any) => void): void;
}
export class SES {
@@ -126,36 +154,77 @@ declare module "aws-sdk" {
constructor(options?: any);
}
export module Sqs {
export interface Client {
config: ClientConfig;
sendMessage(params: SendMessageRequest, callback: (err: any, data: SendMessageResult) => void): void;
sendMessageBatch(params: SendMessageBatchRequest, callback: (err: any, data: SendMessageBatchResult) => void): void;
receiveMessage(params: ReceiveMessageRequest, callback: (err: any, data: ReceiveMessageResult) => void): void;
deleteMessage(params: DeleteMessageRequest, callback: (err: any, data: any) => void): void;
deleteMessageBatch(params: DeleteMessageBatchRequest, callback: (err: any, data: DeleteMessageBatchResult) => void): void;
createQueue(params: CreateQueueRequest, callback: (err: any, data: CreateQueueResult) => void): void;
deleteQueue(params: DeleteQueueRequest, callback: (err: any, data: any) => void): void;
export module SQS {
export interface SqsOptions {
params?: any;
endpoint?: string;
accessKeyId?: string;
secretAccessKey?: string;
sessionToken?: Credentials;
credentials?: Credentials;
credentialProvider?: any;
region?: string;
maxRetries?: number;
maxRedirects?: number;
sslEnabled?: boolean;
paramValidation?: boolean;
computeChecksums?: boolean;
convertResponseTypes?: boolean;
correctClockSkew?: boolean;
s3ForcePathStyle?: boolean;
s3BucketEndpoint?: boolean;
httpOptions?: HttpOptions;
apiVersion?: string;
apiVersions?: { [serviceName:string]: string};
logger?: Logger;
systemClockOffset?: number;
signatureVersion?: string;
signatureCache?: boolean;
}
export interface AddPermissionParams {
QueueUrl: string;
Label: string;
AWSAccountIds:string[];
Actions:string[];
}
export interface ChangeMessageVisibilityParams {
QueueUrl: string,
ReceiptHandle: string,
VisibilityTimeout: number
}
export interface ChangeMessageVisibilityBatchParams {
QueueUrl: string,
Entries: { Id: string; ReceiptHandle: string; VisibilityTimeout?: number; }[]
}
export interface ChangeMessageVisibilityBatchResponse {
Successful: { Id:string }[];
Failed: BatchResultErrorEntry[];
}
export interface SendMessageRequest {
QueueUrl?: string;
MessageBody?: string;
export interface SendMessageParams {
QueueUrl: string;
MessageBody: string;
DelaySeconds?: number;
MessageAttributes?: { [name:string]: MessageAttribute; }
}
export interface ReceiveMessageRequest {
QueueUrl?: string;
export interface ReceiveMessageParams {
QueueUrl: string;
MaxNumberOfMessages?: number;
VisibilityTimeout?: number;
AttributeNames?: string[];
MessageAttributeNames?: string[];
WaitTimeSeconds?:number;
}
export interface DeleteMessageBatchRequest {
QueueUrl?: string;
Entries?: DeleteMessageBatchRequestEntry[];
export interface DeleteMessageBatchParams {
QueueUrl: string;
Entries: DeleteMessageBatchRequestEntry[];
}
export interface DeleteMessageBatchRequestEntry {
@@ -163,85 +232,117 @@ declare module "aws-sdk" {
ReceiptHandle: string;
}
export interface DeleteMessageRequest {
QueueUrl?: string;
ReceiptHandle?: string;
export interface DeleteMessageParams {
QueueUrl: string;
ReceiptHandle: string;
}
export class Attribute {
Name: string;
Value: string;
export interface SendMessageBatchParams {
QueueUrl: string;
Entries: SendMessageBatchRequestEntry[];
}
export interface SendMessageBatchRequest {
QueueUrl?: string;
Entries?: SendMessageBatchRequestEntry[];
}
export class SendMessageBatchRequestEntry {
export interface SendMessageBatchRequestEntry {
Id: string;
MessageBody: string;
DelaySeconds: number;
}
export interface CreateQueueRequest {
QueueName?: string;
DefaultVisibilityTimeout?: number;
DelaySeconds?: number;
Attributes?: Attribute[];
MessageAttributes?: { [name:string]: MessageAttribute; }
}
export interface DeleteQueueRequest {
QueueUrl?: string;
export interface CreateQueueParams {
QueueName: string;
Attributes: QueueAttributes;
}
export class SendMessageResult {
export interface QueueAttributes {
[name:string]: any;
DelaySeconds?: number;
MaximumMessageSize?: number;
MessageRetentionPeriod?: number;
Policy?: any;
ReceiveMessageWaitTimeSeconds?: number;
VisibilityTimeout?: number;
RedrivePolicy?: any;
}
export interface GetQueueAttributesParams {
QueueUrl: string;
AttributeNames: string[];
}
export interface GetQueueAttributesResult {
Attributes: {[name:string]: string};
}
export interface GetQueueUrlParams {
QueueName: string;
QueueOwnerAWSAccountId?: string;
}
export interface SendMessageResult {
MessageId: string;
MD5OfMessageBody: string;
MD5OfMessageAttributes: string;
}
export class ReceiveMessageResult {
export interface ReceiveMessageResult {
Messages: Message[];
}
export class Message {
export interface Message {
MessageId: string;
ReceiptHandle: string;
MD5OfBody: string;
Body: string;
Attributes: Attribute[];
Attributes: { [name:string]:any };
MD5OfMessageAttributes:string;
MessageAttributes: { [name:string]: MessageAttribute; }
}
export class DeleteMessageBatchResult {
export interface MessageAttribute {
StringValue?: string;
BinaryValue?: any; //(Buffer, Typed Array, Blob, String)
StringListValues?: string[];
BinaryListValues?: any[];
DataType: string;
}
export interface DeleteMessageBatchResult {
Successful: DeleteMessageBatchResultEntry[];
Failed: BatchResultErrorEntry[];
}
export class DeleteMessageBatchResultEntry {
export interface DeleteMessageBatchResultEntry {
Id: string;
}
export class BatchResultErrorEntry {
export interface BatchResultErrorEntry {
Id: string;
Code: string;
Message: string;
SenderFault: string;
Message?: string;
SenderFault: boolean;
}
export class SendMessageBatchResult {
export interface SendMessageBatchResult {
Successful: SendMessageBatchResultEntry[];
Failed: BatchResultErrorEntry[];
}
export class SendMessageBatchResultEntry {
export interface SendMessageBatchResultEntry {
Id: string;
MessageId: string;
MD5OfMessageBody: string;
MD5OfMessageAttributes:string;
}
export class CreateQueueResult {
export interface CreateQueueResult {
QueueUrl: string;
}
export interface SetQueueAttributesParams {
QueueUrl: string;
Attributes: QueueAttributes;
}
}

View File

@@ -65,8 +65,21 @@ declare module Backbone {
reset?: boolean;
}
interface ObjectHash {
[key: string]: any;
}
interface RoutesHash {
[routePattern: string]: string | {(...urlParts: string[]): void};
}
interface EventsHash {
[selector: string]: string | {(eventObject: JQueryEventObject): void};
}
class Events {
on(eventName: string, callback?: Function, context?: any): any;
on(eventMap: EventsHash): any;
off(eventName?: string, callback?: Function, context?: any): any;
trigger(eventName: string, ...args: any[]): any;
bind(eventName: string, callback: Function, context?: any): any;
@@ -102,7 +115,7 @@ declare module Backbone {
* For assigning an object hash, do it like this: this.defaults = <any>{ attribute: value, ... };
* That works only if you set it in the constructor or the initialize method.
**/
defaults(): any;
defaults(): ObjectHash;
id: any;
idAttribute: string;
validationError: any;
@@ -272,7 +285,7 @@ declare module Backbone {
* For assigning routes as object hash, do it like this: this.routes = <any>{ "route": callback, ... };
* That works only if you set it in the constructor or the initialize method.
**/
routes: any;
routes: RoutesHash | any;
constructor(options?: RouterOptions);
initialize(options?: RouterOptions): void;
@@ -301,7 +314,7 @@ declare module Backbone {
checkUrl(e?: any): void;
loadUrl(fragmentOverride: string): boolean;
navigate(fragment: string, options?: any): boolean;
started: boolean;
static started: boolean;
options: any;
private _updateHash(location: Location, fragment: string, replace: boolean): void;
@@ -310,7 +323,7 @@ declare module Backbone {
interface ViewOptions<TModel extends Model> {
model?: TModel;
// TODO: quickfix, this can't be fixed easy. The collection does not need to have the same model as the parent view.
collection?: Backbone.Collection<any>;
collection?: Backbone.Collection<any>; //was: Collection<TModel>;
el?: any;
id?: string;
className?: string;
@@ -333,7 +346,7 @@ declare module Backbone {
* For assigning events as object hash, do it like this: this.events = <any>{ "event:selector": callback, ... };
* That works only if you set it in the constructor or the initialize method.
**/
events(): any;
events(): EventsHash;
$(selector: string): JQuery;
model: TModel;
@@ -353,8 +366,10 @@ declare module Backbone {
render(): View<TModel>;
remove(): View<TModel>;
make(tagName: any, attributes?: any, content?: any): any;
delegateEvents(events?: any): any;
delegateEvents(events?: EventsHash): any;
delegate(eventName: string, selector: string, listener: Function): View<TModel>;
undelegateEvents(): any;
undelegate(eventName: string, selector?: string, listener?: Function): View<TModel>;
_ensureElement(): void;
}

22
barcode/barcode-tests.ts Normal file
View File

@@ -0,0 +1,22 @@
/// <reference path="barcode.d.ts" />
import barcode = require('barcode');
import path = require('path');
var code39 = barcode('code39', {
data: "it works",
width: 400,
height: 100,
});
code39.getStream(function (err, readStream) {
if (err) throw err;
// 'readStream' is an instance of ReadableStream
});
var outfile = path.join(__dirname, 'imgs', 'mycode.png');
code39.saveImage(outfile, function (err) {
if (err) throw err;
console.log('File has been written!');
});

25
barcode/barcode.d.ts vendored Normal file
View File

@@ -0,0 +1,25 @@
// Type definitions for barcode
// Project: https://github.com/samt/barcode
// Definitions by: Pascal Vomhoff <https://github.com/pvomhoff>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "barcode" {
interface BarcodeOptions {
data:string|number;
width:number;
height:number;
}
interface BarcodeResult {
getStream(callback:(err:NodeJS.ErrnoException, stream:NodeJS.ReadableStream) => void):void;
saveImage(outputfilePath:string, callback:(err:NodeJS.ErrnoException) => void):void;
getBase64(callback:(err:NodeJS.ErrnoException, base64String:string) => void):void;
}
function barcode(type:string, options:BarcodeOptions):BarcodeResult;
export = barcode;
}

View File

@@ -4,6 +4,9 @@
var noArgument = bigInt(),
numberArgument = bigInt( 93 ),
stringArgument = bigInt( "75643564363473453456342378564387956906736546456235345" ),
baseArgumentInt = bigInt( "101010", 2 ),
baseArgumentStr = bigInt( "101010", "2" ),
baseArgumentBi = bigInt( "101010", bigInt( 2 ) ),
bigIntArgument = bigInt( noArgument );
// method tests
@@ -111,4 +114,4 @@ isNumber = x.toJSNumber();
isString = x.toString();
isNumber = x.valueOf();
isNumber = x.valueOf();

View File

@@ -214,7 +214,7 @@ interface BigIntegerStatic {
/** Parse a Javascript number into a bigInt */
( number: number ): BigInteger;
/** Parse a string into a bigInt */
( string: string ): BigInteger;
( string: string, base?: string | number | BigInteger): BigInteger;
/** no-op */
( bigInt: BigInteger ): BigInteger;
}
@@ -223,4 +223,4 @@ declare var bigInt: BigIntegerStatic;
declare module "big-integer" {
export = bigInt;
}
}

View File

@@ -1,4 +1,4 @@
/// <reference path="Microsoft.Maps.d.ts"/>
/// <reference path="Microsoft.Maps.d.ts"/>
/// <reference path="Microsoft.Maps.AdvancedShapes.d.ts"/>
/// <reference path="Microsoft.Maps.Directions.d.ts"/>
/// <reference path="Microsoft.Maps.Search.d.ts"/>
@@ -55,7 +55,7 @@ module BingMapsTests {
locations.push(location);
}
// Sets the view of the map to the smallest size that contains all of the
// Sets the view of the map to the smallest size that contains all of the
// specified locations (in this case the pusphin locations)
map.setView({ bounds: Microsoft.Maps.LocationRect.fromLocations(locations) });
}

View File

@@ -36,6 +36,9 @@ interface Foo {
interface Bar {
bar(): string;
}
interface Baz {
baz(): string;
}
// - - - - - - - - - - - - - - - - -
@@ -61,6 +64,7 @@ interface StrBarArrMap {
var foo: Foo;
var bar: Bar;
var baz: Baz;
var fooArr: Foo[];
var barArr: Bar[];
@@ -76,6 +80,7 @@ var voidProm: Promise<void>;
var fooProm: Promise<Foo>;
var barProm: Promise<Bar>;
var bazProm: Promise<Baz>;
// - - - - - - - - - - - - - - - - -
@@ -499,6 +504,30 @@ barProm = fooProm.race<Bar>();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Promise.all([fooProm, barProm]).then(result => {
result[0].foo();
result[1].bar();
});
Promise.all([fooProm, fooProm]).then(result => {
result[0].foo();
result[1].foo();
});
Promise.all([fooProm, barProm, bazProm]).then(result => {
result[0].foo();
result[1].bar();
result[2].baz();
});
Promise.all([fooProm, barProm, fooProm]).then(result => {
result[0].foo();
result[1].bar();
result[2].foo();
});
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
//TODO fix collection inference
barArrProm = fooProm.map<Foo, Bar>((item: Foo, index: number, arrayLength: number) => {

View File

@@ -464,6 +464,11 @@ declare class Promise<R> implements Promise.Thenable<R>, Promise.Inspection<R> {
static all<R>(values: Promise.Thenable<R[]>): Promise<R[]>;
// array with promises of value
static all<R>(values: Promise.Thenable<R>[]): Promise<R[]>;
// array with promises of different types
static all<T1, T2>(values: [Promise.Thenable<T1>, Promise.Thenable<T2>]): Promise<[T1, T2]>;
static all<T1, T2, T3>(values: [Promise.Thenable<T1>, Promise.Thenable<T2>, Promise.Thenable<T3>]): Promise<[T1, T2, T3]>;
static all<T1, T2, T3, T4>(values: [Promise.Thenable<T1>, Promise.Thenable<T2>, Promise.Thenable<T3>, Promise.Thenable<T4>]): Promise<[T1, T2, T3, T4]>;
static all<T1, T2, T3, T4, T5>(values: [Promise.Thenable<T1>, Promise.Thenable<T2>, Promise.Thenable<T3>, Promise.Thenable<T4>, Promise.Thenable<T5>]): Promise<[T1, T2, T3, T4, T5]>;
// array with values
static all<R>(values: R[]): Promise<R[]>;

View File

@@ -0,0 +1,70 @@
/// <reference path="bootstrap-maxlength.d.ts"/>
/// <reference path="../jquery/jquery.d.ts"/>
// Examples from the projects github page
$('input[maxlength]').maxlength();
$('input.className').maxlength({
threshold: 20
});
$('input.className').maxlength({
alwaysShow: true,
threshold: 10,
warningClass: "label label-info",
limitReachedClass: "label label-warning",
placement: 'top',
preText: 'used ',
separator: ' of ',
postText: ' chars.'
});
$('input.className').maxlength({
alwaysShow: true,
threshold: 10,
warningClass: "label label-info",
limitReachedClass: "label label-warning",
placement: 'top',
message: 'used %charsTyped% of %charsTotal% chars.'
});
// Testing the events
$('input.className').on('maxlength.shown', function(){
console.log('shown');
});
$('input.className').on('maxlength.hidden', function(){
console.log('hidden');
});
$('textarea').on('autosize.resized', function () {
$(this).trigger('maxlength.reposition');
});
// using message string
$('input.className').maxlength({
message: 'used %charsTyped% of %charsTotal% chars.'
});
// using message function
$('input.className').maxlength({
threshold: 20,
message: function (currentText, maxLength) {
return '' + Math.ceil(currentText.length / 160) + ' SMS Message(s)';
}
});
// placement string
$('input.className').maxlength({
placement: 'top-left'
});
// placement object
$('input.className').maxlength({
placement: {
top: 10,
left: '30%'
}
});
// placement function
$('input.className').maxlength({
placement: function (currentInput: JQuery, maxLengthIndicator: JQuery, currentInputPosition: BootstrapMaxlength.PositionParam) {
}
});

View File

@@ -0,0 +1,158 @@
// Type definitions for bootstrap-maxlength v1.7.0
// Project: https://github.com/mimo84/bootstrap-maxlength
// Definitions by: Dan Manastireanu <https://github.com/danmana>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
declare module BootstrapMaxlength {
/**
* Possible options for the position of the counter. (passed to $.fn.css)
*/
interface PlacementOptions {
/**
* The top position of the counter (Number of pixels, or a px or percent string)
*/
top?: Number | string,
/**
* The right position of the counter (Number of pixels, or a px or percent string)
*/
right?: Number | string,
/**
* The bottom position of the counter (Number of pixels, or a px or percent string)
*/
bottom?: Number | string,
/**
* The left position of the counter (Number of pixels, or a px or percent string)
*/
left?: Number | string,
/**
* The positioning to use. For example 'relative', 'absolute'
*/
position?: string
}
/**
* Representation of the current input position
*/
interface PositionParam {
top: Number,
right: Number,
bottom: Number,
left: Number,
width: Number,
height: Number
}
export interface Options {
/**
* If true the threshold will be ignored and the remaining length indication will be always showing up while typing or on focus on the input
* @default false
*/
alwaysShow?: Boolean,
/**
* This is a number indicating how many chars are left to start displaying the indications
* @default 10
*/
threshold?: Number,
/**
* It's the class of the element with the indicator. By default is the bootstrap "label label-success" but can be changed to anything you'd like.
* @default 'label label-success'
*/
warningClass?: string,
/**
* It's the class the element gets when the limit is reached. Default is "label label-important label-danger" (to support Bootstrap 2 and 3).
* @default 'label label-important label-danger'
*/
limitReachedClass?: string,
/**
* Represents the separator between the number of typed chars and total number of available chars.
* @default ' / '
*/
separator?: string,
/**
* Is a string of text that can be outputted in front of the indicator.
* @default ''
*/
preText?: string,
/**
* Is a string outputted after the indicator.
* @default ''
*/
postText?: string,
/**
* If false, will display just the number of typed characters, e.g. will not display the max length.
* @default true
*/
showMaxLength?: Boolean,
/**
* If false, will display just the remaining length, e.g. will display remaining lenght instead of number of typed characters.
* @default true
*/
showCharsTyped?: Boolean,
/**
* Is a string, define where to output the counter.
* Options: bottom, left, top, right, bottom-right, top-right, top-left, bottom-left and centered-right
* @default 'bottom'
*/
placement?: string | PlacementOptions | ((currentInput: JQuery, maxLengthIndicator: JQuery, currentInputPosition: PositionParam) => void),
/**
* Appends the maxlength indicator badge to the parent of the input rather than to the body.
* @default false
*/
appendToParent?: boolean,
/**
* An alternative way to provide the message text.
* String example: 'You have typed %charsTyped% chars, %charsRemaining% of %charsTotal% remaining'.
* %charsTyped%, %charsRemaining% and %charsTotal% will be replaced by the actual values. This overrides the options separator, preText, postText and showMaxLength.
* Alternatively you may supply a function that the current text and max length and returns the string to be displayed.
* Function example: function(currentText, maxLength) { return '' + Math.ceil(currentText.length / 160) + ' SMS Message(s)'; }
* @default null
*/
message?: string | ((currentText : string, maxLength: Number) => string),
/**
* If true the input will count using utf8 bytesize/encoding. For example: the '£' character is counted as two characters.
* @default false
*/
utf8?: boolean,
/**
* Shows the badge as soon as it is added to the page, similar to alwaysShow
* @default false
*/
showOnReady?: boolean,
/**
* Count linebreak as 2 characters to match IE/Chrome textarea validation. As well as DB storage.
* @default true
*/
twoCharLinebreak?: boolean,
/**
* Allows a custom attribute to display indicator without triggering native maxlength behaviour.
* Ignored if value greater than a native maxlength attribute.
* 'overmax' class gets added when exceeded to allow user to implement form validation.
* @default null (use the maxlength attribute and browser functionality)
*/
customMaxAttribute?: string,
/**
* Will allow the input to be over the customMaxLength. Useful in soft max situations.
* @default false
*/
allowOverMax?: boolean,
/**
* If the browser doesn't support the maxlength attribute, attempt to type more than
* the indicated chars, will be prevented.
* @default false
*/
validate?: boolean
}
}
interface JQuery {
/** Apply the maxlength plugin on the selected elemens */
maxlength(options?: BootstrapMaxlength.Options): JQuery;
on(events: 'maxlength.shown', handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;
on(events: 'maxlength.hidden', handler: (eventObject: JQueryEventObject, ...args: any[]) => any): JQuery;
trigger(eventType: 'maxlength.reposition', extraParameters?: any[]|Object): JQuery;
}

View File

@@ -1,9 +1,9 @@
/// <reference path="bootstrap-notify.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
//Test for bootstrap-notify v3.1.3
//Copied example directly from Bootstrap-notify site
$.notify({
// options
icon: 'glyphicon glyphicon-warning-sign',
@@ -48,5 +48,5 @@ $.notify({
'<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
'</div>' +
'<a href="{3}" target="{4}" data-notify="url"></a>' +
'</div>'
'</div>'
});

View File

@@ -0,0 +1,25 @@
/// <reference path="../jquery/jquery.d.ts"/>
/// <reference path="bootstrap-switch.d.ts" />
function test_cases() {
$('#switch').bootstrapSwitch();
$('#switch').bootstrapSwitch({
state: false
});
$('#switch').bootstrapSwitch({
state: false,
disabled: true
});
//var mySwitch = $('#switch').get(0);
//mySwitch.toggleAnimate();
$('#switch').bootstrapSwitch('state', true, true);
$('#switch').on('switchChange.bootstrapSwitch', (event) => {
console.log($(event.target).val());
});
}

102
bootstrap-switch/bootstrap-switch.d.ts vendored Normal file
View File

@@ -0,0 +1,102 @@
// Type definitions for Bootstrap Switch
// Project: http://www.bootstrap-switch.org/
// Definitions by: John M. Baughman <https://github.com/johnmbaughman>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* bootstrap-switch - v3.3.2 Copyright (c) 2012-2013 Mattia Larentis
* Available via the Apache license.
* see: http://www.bootstrap-switch.org/ or https://github.com/nostalgiaz/bootstrap-switch for details.
*/
/// <reference path="../jquery/jquery.d.ts"/>
declare module BootstrapSwitch {
interface BootstrapSwitchChangeEventObject extends JQueryEventObject {
state: boolean
}
interface BootstrapSwitchEventObject extends JQueryEventObject { }
interface BootstrapSwitchOptions {
state?: boolean;
size?: string;
animate?: boolean;
disabled?: boolean;
readonly?: boolean;
indeterminate?: boolean;
invers?: boolean;
radioAllOff?: boolean;
onColor?: string;
offColor?: string;
onText?: string;
offText?: string;
labelText?: string;
handleWidth?: string;
labelWidth?: string;
baseClass?: string;
wrapperClass?: string;
onInit?: any;
onSwitchChange?: any;
}
interface Switch {
toggleAnimate(): JQuery;
toggleDisabled(): JQuery;
toggleReadonly(): JQuery;
toggleIndeterminate(): JQuery;
toggleInverse(): JQuery;
destroy(): JQuery;
state(): boolean;
state(value: any): JQuery;
state(value: any, skip: boolean): JQuery;
toggleState(skip?: boolean): JQuery;
radioAllOff(): boolean;
radioAllOff(state: boolean): JQuery;
size(): string;
size(size: string): JQuery;
animate(): boolean;
animate(state: boolean): JQuery;
disabled(): boolean;
disabled(state: boolean): JQuery;
toggleDisabled(): JQuery;
readonly(): boolean;
readonly(state: boolean): JQuery;
toggleReadOnly(): JQuery;
onColor(): string;
onColor(color: string): JQuery;
offColor(): string;
offColor(color: string): JQuery;
onText(): string;
onText(text: string): JQuery;
offText(): string;
offText(text: string): JQuery;
labelText(): string;
labelText(text: string): JQuery;
baseClass(): string;
baseClass(text: string): JQuery;
wrapperClass(): string;
wrapperClass(text: string): JQuery;
}
}
interface JQuery {
bootstrapSwitch(): JQuery;
bootstrapSwitch(options: BootstrapSwitch.BootstrapSwitchOptions): JQuery;
bootstrapSwitch(method: string): JQuery;
bootstrapSwitch(method: string, param: any): JQuery;
bootstrapSwitch(method: string, param1: any, param2: any): JQuery;
off(events: "init.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery;
off(events: "init.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery;
off(events: "switchChange.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery;
off(events: "switchChange.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery;
on(events: "init.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery;
on(events: "init.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchEventObject) => any): JQuery;
on(events: "switchChange.bootstrapSwitch", selector?: string, handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery;
on(events: "switchChange.bootstrapSwitch", handler?: (eventobject: BootstrapSwitch.BootstrapSwitchChangeEventObject) => any): JQuery;
}

View File

@@ -44,8 +44,8 @@ interface DatepickerEventObject extends JQueryEventObject {
interface JQuery {
datepicker(): JQuery;
datepicker(methodName: string): JQuery;
datepicker(methodName: string, params: any): JQuery;
datepicker(methodName: string): any;
datepicker(methodName: string, params: any): any;
datepicker(options: DatepickerOptions): JQuery;
off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery;

View File

@@ -1,6 +1,13 @@
/// <reference path="./browser-sync.d.ts"/>
import browserSync = require("browser-sync");
(() => {
//make sure that the interfaces are correctly exposed
var bsInstance: browserSync.BrowserSyncInstance;
var bsStatic: browserSync.BrowserSyncStatic;
var opts: browserSync.Options;
})();
browserSync({
server: {
baseDir: "./"
@@ -78,8 +85,8 @@ bs.init({
});
bs.reload();
function browserSyncInit() {
function browserSyncInit(): browserSync.BrowserSyncInstance {
var browser = browserSync.create();
browser.init();
console.log(browser.name);

View File

@@ -11,404 +11,406 @@ declare module "browser-sync" {
import fs = require("fs");
import http = require("http");
interface Options {
/**
* Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls
* all devices, push sync updates and much more.
*
* port - Default: 3001
* weinre.port - Default: 8080
* Note: requires at least version 2.0.0
*/
ui?: UIOptions;
/**
* Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS
* & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob
* patterns.
* Default: false
*/
files?: string | string[];
/**
* File watching options that get passed along to Chokidar. Check their docs for available options
* Default: undefined
* Note: requires at least version 2.6.0
*/
watchOptions?: ChokidarOptions;
/**
* Use the built-in static server for basic HTML/JS/CSS websites.
* Default: false
*/
server?: ServerOptions;
/**
* Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site.
* target - Default: undefined
* ws - Default: undefined
* middleware - Default: undefined
* reqHeaders - Default: undefined
* proxyRes - Default: undefined
*/
proxy?: string | boolean | ProxyOptions;
/**
* Use a specific port (instead of the one auto-detected by Browsersync)
* Default: 3000
*/
port?: number;
/**
* Add additional directories from which static files should be served.
* Should only be used in proxy or snippet mode.
* Default: []
* Note: requires at least version 2.8.0
*/
serveStatic?: string[];
/**
* Enable https for localhost development.
* Note - this is not needed for proxy option as it will be inferred from your target url.
* Note: requires at least version 1.3.0
*/
https?: boolean;
/**
* Clicks, Scrolls & Form inputs on any device will be mirrored to all others.
* clicks - Default: true
* scroll - Default: true
* forms - Default: true
*/
ghostMode?: GhostOptions | boolean;
/**
* Can be either "info", "debug", "warn", or "silent"
* Default: info
*/
logLevel?: string;
/**
* Change the console logging prefix. Useful if you're creating your own project based on Browsersync
* Default: BS
* Note: requires at least version 1.5.1
*/
logPrefix?: string;
/**
* Whether or not to log connections
* Default: false
*/
logConnections?: boolean;
/**
* Whether or not to log information about changed files
* Default: false
*/
logFileChanges?: boolean;
/**
* Log the snippet to the console when you're in snippet mode (no proxy/server)
* Default: true
* Note: requires at least version 1.5.2
*/
logSnippet?: boolean;
/**
* You can control how the snippet is injected onto each page via a custom regex + function.
* You can also provide patterns for certain urls that should be ignored from the snippet injection.
* Note: requires at least version 2.0.0
*/
snippetOptions?: SnippetOptions;
/**
* Add additional HTML rewriting rules.
* Default: false
* Note: requires at least version 2.4.0
*/
rewriteRules?: boolean | RewriteRules[];
/**
* Tunnel the Browsersync server through a random Public URL
* Default: null
*/
tunnel?: string | boolean;
/**
* Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're
* working offline, you can reduce start-up time by setting this option to false
*/
online?: boolean;
/**
* Default: true
* Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set.
* Can be true, local, external, ui, ui-external, tunnel or false
*/
open?: string | boolean;
/**
* The browser(s) to open
* Default: default
*/
browser?: string | string[];
/**
* Requires an internet connection - useful for services such as Typekit as it allows you to configure
* domains such as *.xip.io in your kit settings
* Default: false
*/
xip?: boolean;
/**
* Reload each browser when Browsersync is restarted.
* Default: false
*/
reloadOnRestart?: boolean;
/**
* The small pop-over notifications in the browser are not always needed/wanted.
* Default: true
*/
notify?: boolean;
/**
* scrollProportionally: false // Sync viewports to TOP position
* Default: true
*/
scrollProportionally?: boolean
/**
* How often to send scroll events
* Default: 0
*/
scrollThrottle?: number;
/**
* Decide which technique should be used to restore scroll position following a reload.
* Can be window.name or cookie
* Default: 'window.name'
*/
scrollRestoreTechnique?: string;
/**
* Sync the scroll position of any element on the page. Add any amount of CSS selectors
* Default: []
* Note: requires at least version 2.9.0
*/
scrollElements?: string[];
/**
* Default: []
* Note: requires at least version 2.9.0
* Sync the scroll position of any element on the page - where any scrolled element will cause
* all others to match scroll position. This is helpful when a breakpoint alters which element
* is actually scrolling
*/
scrollElementMapping?: string[];
/**
* Time, in milliseconds, to wait before instructing the browser to reload/inject following a file change event
* Default: 0
*/
reloadDelay?: number;
/**
* Restrict the frequency in which browser:reload events can be emitted to connected clients
* Default: 0
* Note: requires at least version 2.6.0
*/
reloadDebounce?: number;
/**
* User provided plugins
* Default: []
* Note: requires at least version 2.6.0
*/
plugins?: any[];
/**
* Whether to inject changes (rather than a page refresh)
* Default: true
*/
injectChanges?: boolean;
/**
* The initial path to load
*/
startPath?: string;
/**
* Whether to minify the client script
* Default: true
*/
minify?: boolean;
/**
* Override host detection if you know the correct IP to use
*/
host?: string;
/**
* Send file-change events to the browser
* Default: true
*/
codeSync?: boolean;
/**
* Append timestamps to injected files
* Default: true
*/
timestamps?: boolean;
/**
* Alter the script path for complete control over where the Browsersync Javascript is served
* from. Whatever you return from this function will be used as the script path.
* Note: requires at least version 1.5.0
*/
scriptPath?: (path: string) => string;
/**
* Configure the Socket.IO path and namespace & domain to avoid collisions.
* path - Default: "/browser-sync/socket.io"
* clientPath - Default: "/browser-sync"
* namespace - Default: "/browser-sync"
* domain - Default: undefined
* port - Default: undefined
* clients.heartbeatTimeout - Default: 5000
* Note: requires at least version 1.6.2
*/
socket?: SocketOptions;
}
interface Hash<T> {
[path: string]: T;
}
interface ChokidarOptions {
interval?: number;
debounceDelay?: number;
mode?: string;
cwd?: string;
}
interface UIOptions {
/** set the default port */
port?: number;
/** set the default weinre port */
weinre?: {
namespace browserSync {
interface Options {
/**
* Browsersync includes a user-interface that is accessed via a separate port. The UI allows to controls
* all devices, push sync updates and much more.
*
* port - Default: 3001
* weinre.port - Default: 8080
* Note: requires at least version 2.0.0
*/
ui?: UIOptions;
/**
* Browsersync can watch your files as you work. Changes you make will either be injected into the page (CSS
* & images) or will cause all browsers to do a full-page refresh. See anymatch for more information on glob
* patterns.
* Default: false
*/
files?: string | string[];
/**
* File watching options that get passed along to Chokidar. Check their docs for available options
* Default: undefined
* Note: requires at least version 2.6.0
*/
watchOptions?: ChokidarOptions;
/**
* Use the built-in static server for basic HTML/JS/CSS websites.
* Default: false
*/
server?: ServerOptions;
/**
* Proxy an EXISTING vhost. Browsersync will wrap your vhost with a proxy URL to view your site.
* target - Default: undefined
* ws - Default: undefined
* middleware - Default: undefined
* reqHeaders - Default: undefined
* proxyRes - Default: undefined
*/
proxy?: string | boolean | ProxyOptions;
/**
* Use a specific port (instead of the one auto-detected by Browsersync)
* Default: 3000
*/
port?: number;
};
/**
* Add additional directories from which static files should be served.
* Should only be used in proxy or snippet mode.
* Default: []
* Note: requires at least version 2.8.0
*/
serveStatic?: string[];
/**
* Enable https for localhost development.
* Note - this is not needed for proxy option as it will be inferred from your target url.
* Note: requires at least version 1.3.0
*/
https?: boolean;
/**
* Clicks, Scrolls & Form inputs on any device will be mirrored to all others.
* clicks - Default: true
* scroll - Default: true
* forms - Default: true
*/
ghostMode?: GhostOptions | boolean;
/**
* Can be either "info", "debug", "warn", or "silent"
* Default: info
*/
logLevel?: string;
/**
* Change the console logging prefix. Useful if you're creating your own project based on Browsersync
* Default: BS
* Note: requires at least version 1.5.1
*/
logPrefix?: string;
/**
* Whether or not to log connections
* Default: false
*/
logConnections?: boolean;
/**
* Whether or not to log information about changed files
* Default: false
*/
logFileChanges?: boolean;
/**
* Log the snippet to the console when you're in snippet mode (no proxy/server)
* Default: true
* Note: requires at least version 1.5.2
*/
logSnippet?: boolean;
/**
* You can control how the snippet is injected onto each page via a custom regex + function.
* You can also provide patterns for certain urls that should be ignored from the snippet injection.
* Note: requires at least version 2.0.0
*/
snippetOptions?: SnippetOptions;
/**
* Add additional HTML rewriting rules.
* Default: false
* Note: requires at least version 2.4.0
*/
rewriteRules?: boolean | RewriteRules[];
/**
* Tunnel the Browsersync server through a random Public URL
* Default: null
*/
tunnel?: string | boolean;
/**
* Some features of Browsersync (such as xip & tunnel) require an internet connection, but if you're
* working offline, you can reduce start-up time by setting this option to false
*/
online?: boolean;
/**
* Default: true
* Decide which URL to open automatically when Browsersync starts. Defaults to "local" if none set.
* Can be true, local, external, ui, ui-external, tunnel or false
*/
open?: string | boolean;
/**
* The browser(s) to open
* Default: default
*/
browser?: string | string[];
/**
* Requires an internet connection - useful for services such as Typekit as it allows you to configure
* domains such as *.xip.io in your kit settings
* Default: false
*/
xip?: boolean;
/**
* Reload each browser when Browsersync is restarted.
* Default: false
*/
reloadOnRestart?: boolean;
/**
* The small pop-over notifications in the browser are not always needed/wanted.
* Default: true
*/
notify?: boolean;
/**
* scrollProportionally: false // Sync viewports to TOP position
* Default: true
*/
scrollProportionally?: boolean
/**
* How often to send scroll events
* Default: 0
*/
scrollThrottle?: number;
/**
* Decide which technique should be used to restore scroll position following a reload.
* Can be window.name or cookie
* Default: 'window.name'
*/
scrollRestoreTechnique?: string;
/**
* Sync the scroll position of any element on the page. Add any amount of CSS selectors
* Default: []
* Note: requires at least version 2.9.0
*/
scrollElements?: string[];
/**
* Default: []
* Note: requires at least version 2.9.0
* Sync the scroll position of any element on the page - where any scrolled element will cause
* all others to match scroll position. This is helpful when a breakpoint alters which element
* is actually scrolling
*/
scrollElementMapping?: string[];
/**
* Time, in milliseconds, to wait before instructing the browser to reload/inject following a file
* change event
* Default: 0
*/
reloadDelay?: number;
/**
* Restrict the frequency in which browser:reload events can be emitted to connected clients
* Default: 0
* Note: requires at least version 2.6.0
*/
reloadDebounce?: number;
/**
* User provided plugins
* Default: []
* Note: requires at least version 2.6.0
*/
plugins?: any[];
/**
* Whether to inject changes (rather than a page refresh)
* Default: true
*/
injectChanges?: boolean;
/**
* The initial path to load
*/
startPath?: string;
/**
* Whether to minify the client script
* Default: true
*/
minify?: boolean;
/**
* Override host detection if you know the correct IP to use
*/
host?: string;
/**
* Send file-change events to the browser
* Default: true
*/
codeSync?: boolean;
/**
* Append timestamps to injected files
* Default: true
*/
timestamps?: boolean;
/**
* Alter the script path for complete control over where the Browsersync Javascript is served
* from. Whatever you return from this function will be used as the script path.
* Note: requires at least version 1.5.0
*/
scriptPath?: (path: string) => string;
/**
* Configure the Socket.IO path and namespace & domain to avoid collisions.
* path - Default: "/browser-sync/socket.io"
* clientPath - Default: "/browser-sync"
* namespace - Default: "/browser-sync"
* domain - Default: undefined
* port - Default: undefined
* clients.heartbeatTimeout - Default: 5000
* Note: requires at least version 1.6.2
*/
socket?: SocketOptions;
}
interface Hash<T> {
[path: string]: T;
}
interface ChokidarOptions {
interval?: number;
debounceDelay?: number;
mode?: string;
cwd?: string;
}
interface UIOptions {
/** set the default port */
port?: number;
/** set the default weinre port */
weinre?: {
port?: number;
};
}
interface ServerOptions {
/** set base directory */
baseDir?: string | string[];
/** enable directory listing */
directory?: boolean;
/** set index filename */
index?: string;
/**
* key-value object hash, where the key is the url to match,
* and the value is the folder to serve (relative to your working directory)
*/
routes?: Hash<string>;
/** configure custom middleware */
middleware?: MiddlewareHandler[];
}
interface ProxyOptions {
target?: string;
middleware?: MiddlewareHandler;
ws: boolean;
reqHeaders: (config: any) => Hash<any>;
proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any;
}
interface MiddlewareHandler {
(req: http.ServerRequest, res: http.ServerResponse, next: Function): any;
}
interface GhostOptions {
clicks?: boolean;
scroll?: boolean;
forms?: boolean;
}
interface SnippetOptions {
ignorePaths?: string;
rule?: { match?: RegExp; fn?: (snippet: string, match: string) => any };
}
interface SocketOptions {
path?: string;
clientPath?: string;
namespace?: string;
domain?: string;
port?: number;
clients?: { heartbeatTimeout?: number; };
}
interface RewriteRules {
match: RegExp;
fn: (match: string) => string;
}
interface BrowserSyncStatic extends BrowserSyncInstance {
/**
* Start the Browsersync service. This will launch a server, proxy or start the snippet mode
* depending on your use-case.
*/
(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance;
/**
* Create a Browsersync instance
* @param name an identifier that can used for retrieval later
*/
create(name?: string): BrowserSyncInstance;
/**
* Get a single instance by name. This is useful if you have your build scripts in separate files
* @param name the identifier used for retrieval
*/
get(name: string): BrowserSyncInstance;
}
interface BrowserSyncInstance {
/** the name of this instance of browser-sync */
name: string;
/**
* Start the Browsersync service. This will launch a server, proxy or start the snippet mode
* depending on your use-case.
*/
init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance;
/**
* Reload the browser
* The reload method will inform all browsers about changed files and will either cause the browser
* to refresh, or inject the files where possible.
*/
reload(): void;
/**
* Reload a single file
* The reload method will inform all browsers about changed files and will either cause the browser
* to refresh, or inject the files where possible.
*/
reload(file: string): void;
/**
* Reload multiple files
* The reload method will inform all browsers about changed files and will either cause the browser
* to refresh, or inject the files where possible.
*/
reload(files: string[]): void;
/**
* The reload method will inform all browsers about changed files and will either cause the browser
* to refresh, or inject the files where possible.
*/
reload(options: { stream: boolean }): NodeJS.ReadWriteStream;
/**
* The stream method returns a transform stream and can act once or on many files.
* @param opts Configuration for the stream method
*/
stream(opts: { once: boolean }): NodeJS.ReadWriteStream;
/**
* Helper method for browser notifications
* @param message Can be a simple message such as 'Connected' or HTML
* @param timeout How long the message will remain in the browser. @since 1.3.0
*/
notify(message: string, timeout?: number): void;
/**
* This method will close any running server, stop file watching & exit the current process.
*/
exit(): void;
/**
* Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system
*/
watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any)
: NodeJS.EventEmitter;
/**
* Method to pause file change events
*/
pause(): void;
/**
* Method to resume paused watchers
*/
resume(): void;
/**
* The internal Event Emitter used by the running Browsersync instance (if there is one). You can use
* this to emit your own events, such as changed files, logging etc.
*/
emitter: NodeJS.EventEmitter;
/**
* A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance.
*/
active: boolean;
/**
* A simple true/false flag to determine if the current instance is paused
*/
paused: boolean;
}
}
interface ServerOptions {
/** set base directory */
baseDir?: string | string[];
/** enable directory listing */
directory?: boolean;
/** set index filename */
index?: string;
/**
* key-value object hash, where the key is the url to match,
* and the value is the folder to serve (relative to your working directory)
* */
routes?: Hash<string>;
/** configure custom middleware */
middleware?: MiddlewareHandler[];
}
interface ProxyOptions {
target?: string;
middleware?: MiddlewareHandler;
ws: boolean;
reqHeaders: (config: any) => Hash<any>;
proxyRes: (res: http.ServerResponse, req: http.ServerRequest, next: Function) => any;
}
interface MiddlewareHandler {
(req: http.ServerRequest, res: http.ServerResponse, next: Function): any;
}
interface GhostOptions {
clicks?: boolean;
scroll?: boolean;
forms?: boolean;
}
interface SnippetOptions {
ignorePaths?: string;
rule?: {match?: RegExp; fn?: (snippet: string, match: string) => any};
}
interface SocketOptions {
path?: string;
clientPath?: string;
namespace?: string;
domain?: string;
port?: number;
clients?: { heartbeatTimeout?: number; };
}
interface RewriteRules {
match: RegExp;
fn: (match: string) => string;
}
interface BrowserSyncStatic extends BrowserSyncInstance {
/**
* Start the Browsersync service. This will launch a server, proxy or start the snippet mode
* depending on your use-case.
*/
(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance;
/**
* Create a Browsersync instance
* @param name an identifier that can used for retrieval later
*/
create(name?: string): BrowserSyncInstance;
/**
* Get a single instance by name. This is useful if you have your build scripts in separate files
* @param name the identifier used for retrieval
*/
get(name: string): BrowserSyncInstance;
}
interface BrowserSyncInstance {
/** the name of this instance of browser-sync */
name: string;
/**
* Start the Browsersync service. This will launch a server, proxy or start the snippet mode
* depending on your use-case.
*/
init(config?: Options, callback?: (err: Error, bs: Object) => any): BrowserSyncInstance;
/**
* Reload the browser
* The reload method will inform all browsers about changed files and will either cause the browser
* to refresh, or inject the files where possible.
*/
reload(): void;
/**
* Reload a single file
* The reload method will inform all browsers about changed files and will either cause the browser
* to refresh, or inject the files where possible.
*/
reload(file: string): void;
/**
* Reload multiple files
* The reload method will inform all browsers about changed files and will either cause the browser
* to refresh, or inject the files where possible.
*/
reload(files: string[]): void;
/**
* The reload method will inform all browsers about changed files and will either cause the browser
* to refresh, or inject the files where possible.
*/
reload(options: {stream: boolean}): NodeJS.ReadWriteStream;
/**
* The stream method returns a transform stream and can act once or on many files.
* @param opts Configuration for the stream method
*/
stream(opts: {once: boolean}): NodeJS.ReadWriteStream;
/**
* Helper method for browser notifications
* @param message Can be a simple message such as 'Connected' or HTML
* @param timeout How long the message will remain in the browser. @since 1.3.0
*/
notify(message: string, timeout?: number): void;
/**
* This method will close any running server, stop file watching & exit the current process.
*/
exit(): void;
/**
* Stand alone file-watcher. Use this along with Browsersync to create your own, minimal build system
*/
watch(patterns: string, opts?: chokidar.WatchOptions, fn?: (event: string, file: fs.Stats) => any)
: NodeJS.EventEmitter;
/**
* Method to pause file change events
*/
pause(): void;
/**
* Method to resume paused watchers
*/
resume(): void;
/**
* The internal Event Emitter used by the running Browsersync instance (if there is one). You can use
* this to emit your own events, such as changed files, logging etc.
*/
emitter: NodeJS.EventEmitter;
/**
* A simple true/false flag that you can use to determine if there's a currently-running Browsersync instance.
*/
active: boolean;
/**
* A simple true/false flag to determine if the current instance is paused
*/
paused: boolean;
}
const browserSync: BrowserSyncStatic;
const browserSync: browserSync.BrowserSyncStatic;
export = browserSync;
}

16
bytes/bytes-tests.ts Normal file
View File

@@ -0,0 +1,16 @@
/// <reference path="./bytes.d.ts"/>
import bytes = require('bytes');
// 1024*1024 = 1048576
console.log(bytes(104857));
console.log(bytes(104857, { thousandsSeparator: ' ' }));
console.log(bytes.format(104857));
console.log(bytes.format(104857, { thousandsSeparator: ' ' }));
console.log(bytes('1024kb'));
console.log(bytes(1024));
console.log(bytes.parse('1024kb'));
console.log(bytes.parse(1024));

62
bytes/bytes.d.ts vendored Normal file
View File

@@ -0,0 +1,62 @@
// Type definitions for bytes v2.1.0
// Project: https://github.com/visionmedia/bytes.js
// Definitions by: Zhiyuan Wang <https://github.com/danny8002/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'bytes' {
/**
*Convert the given value in bytes into a string.
*
* @param {number} value
* @param {{
* thousandsSeparator: [string]
* }} [options] bytes options.
*
* @returns {string}
*/
function bytes(value: number, options?: { thousandsSeparator: string }): string;
/**
*Parse string to an integer in bytes.
*
* @param {string} value
* @returns {number}
*/
function bytes(value: string): number;
module bytes {
/**
* Format the given value in bytes into a string.
*
* If the value is negative, take Math.abs(). If it is a float,
* it is rounded.
*
* @param {number} value
* @param {BytesFormatOptions} [options]
*/
function format(value: number, options?: { thousandsSeparator: string }): string;
/**
* Just return the input number value.
*
* @param {number} value
* @return {number}
*/
function parse(value: number): number;
/**
* Parse the string value into an integer in bytes.
*
* If no unit is given, it is assumed the value is in bytes.
*
* @param {string} value
* @return {number}
*/
function parse(value: string): number;
}
export = bytes;
}

16
c3/c3.d.ts vendored
View File

@@ -177,7 +177,7 @@ declare module c3 {
* Set threshold to show/hide labels.
*/
threshold?: number
},
};
/**
* Enable or disable expanding pie pieces.
*/
@@ -198,7 +198,7 @@ declare module c3 {
* Set threshold to show/hide labels.
*/
threshold?: number
},
};
/**
* Enable or disable expanding pie pieces.
*/
@@ -223,7 +223,7 @@ declare module c3 {
* Set formatter for the label on gauge.
*/
format?: (value: any, ratio: number) => string;
},
};
/**
* Enable or disable expanding gauge.
*/
@@ -686,7 +686,7 @@ declare module c3 {
/**
* Set custom position for the tooltip. This option can be used to modify the tooltip position by returning object that has top and left.
*/
position?: (data: any, width: number, height: number, element: any) => { top: number, left: number };
position?: (data: any, width: number, height: number, element: any) => { top: number; left: number };
/**
* Set custom HTML for the tooltip.
* Specified function receives data, defaultTitleFormat, defaultValueFormat and color of the data point to show. If tooltip.grouped is true, data includes multiple data points.
@@ -909,7 +909,7 @@ declare module c3 {
* Remove regions. This API removes regions.
* @param args This argument should include classes. If classes is given, the regions that have one of the specified classes will be removed. If args is not given, all of regions will be removed.
*/
remove(args?: { value?: number | string, class?: string }): void;
remove(args?: { value?: number | string; class?: string }): void;
};
data: {
@@ -995,7 +995,7 @@ declare module c3 {
* Get and set axis min and max value.
* @param range If range is given, specified axis' min and max value will be updated. If no argument is given, the current min and max values for each axis will be returned.
*/
range(range?: { min?: number | { [key: string]: number }, max?: number | { [key: string]: number } }): { min: number | { [key: string]: number }, max: number | { [key: string]: number } }
range(range?: { min?: number | { [key: string]: number }; max?: number | { [key: string]: number } }): { min: number | { [key: string]: number }; max: number | { [key: string]: number } }
};
legend: {
@@ -1034,7 +1034,7 @@ declare module c3 {
* Resize the chart. If no size is specified it will resize to fit.
* @param size This argument should include width and height in pixels.
*/
resize(size?: { width?: number, height?: number }): void;
resize(size?: { width?: number; height?: number }): void;
/**
* Force to redraw.
@@ -1062,7 +1062,7 @@ declare module c3 {
* Remove x/y grid lines. This API removes x/y grid lines.
* @param args This argument should include value or class. If value is given, the x/y grid lines that have specified x/y value will be removed. If class is given, the x/y grid lines that have specified class will be removed. If args is not given, all of x/y grid lines will be removed.
*/
remove(args?: { class?: string, value?: number | string }): void;
remove(args?: { class?: string; value?: number | string }): void;
}
export function generate(config: ChartConfiguration): ChartAPI;

View File

@@ -8,6 +8,7 @@
declare module 'chai-as-promised' {
function chaiAsPromised(chai: any, utils: any): void;
namespace chaiAsPromised {}
export = chaiAsPromised;
}

View File

@@ -34,3 +34,6 @@ chance.mixin({
});
var timeString: string = chance.time();
var chanceConstructedWithSeed100 = new Chance(100);
var chanceCalledWithSeed100 = Chance()

10
chance/chance.d.ts vendored
View File

@@ -5,7 +5,10 @@
declare module Chance {
interface ChanceStatic {
Chance(): Chance;
(): Chance
(seed: number): Chance
(generator: () => any): Chance
new(): Chance;
new(seed: number): Chance;
new(generator: () => any): Chance;
@@ -209,5 +212,10 @@ declare var Chance: Chance.ChanceStatic;
// import Chance = require('chance');
declare module 'chance' {
interface ExportedChance extends Chance.ChanceStatic {
Chance: ExportedChance;
}
var Chance: ExportedChance;
export = Chance;
}

View File

@@ -0,0 +1,69 @@
/// <reference path="./connect-livereload.d.ts" />
import * as connect from "connect";
import * as livereload from "connect-livereload";
const app = connect();
// With no options
app.use(livereload());
// With string options
app.use(livereload({
port: 35729,
ignore: [".js", ".svg"]
}));
// With RegExp options
app.use(livereload({
port: 35729,
ignore: [/\.js(\?.*)?$/, /\.css(\?.*)?$/]
}));
// With default options
app.use(livereload({
ignore: [
/\.js(\?.*)?$/, /\.css(\?.*)?$/, /\.svg(\?.*)?$/, /\.ico(\?.*)?$/, /\.woff(\?.*)?$/,
/\.png(\?.*)?$/, /\.jpg(\?.*)?$/, /\.jpeg(\?.*)?$/, /\.gif(\?.*)?$/, /\.pdf(\?.*)?$/
],
// include all urls by default
include: [/.*/],
// this function is used to determine if the content of `res.write` or `res.end` is html.
html: function (str) {
if (!str) return false;
return /<[:_-\w\s\!\/\=\"\']+>/i.test(str);
},
// rules are provided to find the place where the snippet should be inserted.
// the main problem is that on the server side it can be tricky to determine if a string will be valid html on the client.
// the function `fn` of the first `match` is executed like this `body.replace(rule.match, rule.fn);`
// the function `fn` has got the arguments `fn(w, s)` where `w` is the matches string and `s` is the snippet.
rules: [{
match: /<\/body>(?![\s\S]*<\/body>)/i,
fn: prepend
}, {
match: /<\/html>(?![\s\S]*<\/html>)/i,
fn: prepend
}, {
match: /<\!DOCTYPE.+?>/i,
fn: append
}],
// port where the script is loaded
port: 35729,
// location where the script is provided (not by connect-livereload). Change this e.g. when serving livereload with a proxy.
src: "http://localhost:35729/livereload.js?snipver=1",
// Set this option to `true` to set `req.headers['accept-encoding']` to 'identity' (disabling compression)
disableCompression: false
}));
function prepend(w: string, s: string): string {
return s + w;
}
function append(w: string, s: string): string {
return w + s;
}

View File

@@ -0,0 +1,38 @@
// Type definitions for connect-livereload v0.5.3
// Project: https://github.com/intesso/connect-livereload
// Definitions by: Maxime LUCE <https://github.com/SomaticIT/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../connect/connect.d.ts" />
declare module "connect-livereload" {
import { HandleFunction } from "connect";
function livereload(): HandleFunction;
function livereload(options: livereload.Options): HandleFunction;
module livereload {
export type FileMatcher = string | RegExp;
export interface Rule {
match: RegExp;
fn: (w: string, s: string) => string;
}
export interface Options {
ignore?: FileMatcher[];
excludeList?: FileMatcher[];
include?: FileMatcher[];
html?: (val: string) => boolean;
rules?: Rule[];
disableCompression?: boolean;
hostname?: string;
port?: number;
src?: string;
}
}
export = livereload;
}

View File

@@ -1,5 +1,5 @@
// Copyright (c) Microsoft Open Technologies, Inc.
// Licensed under the MIT license.
// Licensed under the MIT license.
/// <reference path="cordova.d.ts"/>
@@ -203,7 +203,7 @@ file.abort();
// InAppBrowser plugin
//----------------------------------------------------------------------
// signature of window.open() added by InAppBrowser plugin
// signature of window.open() added by InAppBrowser plugin
// is similar to native window.open signature, so the compiler can's
// select proper overload, but we cast result to InAppBrowser manually.
var iab = <InAppBrowser>window.open('google.com', '_self');
@@ -307,3 +307,28 @@ db.transaction(
navigator.notification.vibrate(100);
navigator.notification.vibrateWithPattern([100, 200, 200, 150, 50], 3);
setTimeout(navigator.notification.cancelVibration, 1000);
// Keyboard plugin
//----------------------------------------------------------------------
Keyboard.shrinkView(true);
Keyboard.shrinkView(false);
Keyboard.hideFormAccessoryBar(true);
Keyboard.hideFormAccessoryBar(false);
Keyboard.disableScrollingInShrinkView(true);
Keyboard.disableScrollingInShrinkView(false);
if (Keyboard.isVisible) {
console.log('Keyboard is visible');
}
Keyboard.automaticScrollToTopOnHiding = true;
Keyboard.onshow = function () {
console.log('onshow');
};
Keyboard.onhide = function () {
console.log('onhide');
};
Keyboard.onshowing = function () {
console.log('onshowing');
};
Keyboard.onhiding= function () {
console.log('onhiding');
};

View File

@@ -25,6 +25,7 @@
/// <reference path="plugins/StatusBar.d.ts"/>
/// <reference path="plugins/Vibration.d.ts"/>
/// <reference path="plugins/WebSQL.d.ts"/>
/// <reference path="plugins/Keyboard.d.ts"/>
interface Cordova {
/** Invokes native functionality by specifying corresponding service name, action and optional parameters.
@@ -94,3 +95,7 @@ interface UrlUtil {
/** Apache Cordova instance */
declare var cordova: Cordova;
declare module 'cordova' {
export = cordova;
}

174
cordova/plugins/Keyboard.d.ts vendored Normal file
View File

@@ -0,0 +1,174 @@
// Type definitions for Apache Cordova Keyboard plugin v0.1.2
// Project: https://github.com/apache/cordova-plugins/tree/master/keyboard
// Definitions by: Dan Manastireanu <https://github.com/danmana>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* The Keyboard object provides some functions to customize the iOS keyboard.
*
* <i>Supported Platforms: iOS</i>
*
* This plugin has only been tested in Cordova 3.2 or greater,
* and its use in previous Cordova versions is not recommended
* (potential conflict with keyboard customization code present in the core in previous Cordova versions).
*
* If you do use this plugin in an older Cordova version (again, not recommended),
* you have to make sure the HideKeyboardFormAccessoryBar and KeyboardShrinksView preference values are always false,
* and only use the API functions to turn things on/off.
*
* This plugin supports the HideKeyboardFormAccessoryBar (boolean)
* and KeyboardShrinksView (boolean) preferences in config.xml.
*
* Permissions in config.xml
* <code>
* <feature name="Keyboard">
* <param name="ios-package" value="CDVKeyboard" onload="true" />
* </feature>
* </code>
*
*/
interface Keyboard {
// Methods
/**
* Shrink the WebView when the keyboard comes up.
*
* Set to true to shrink the WebView when the keyboard comes up.
* The WebView shrinks instead of the viewport shrinking and the page scrollable.
* This applies to apps that position their elements relative to the bottom of the WebView.
* This is the default behaviour on Android, and makes a lot of sense when building apps as opposed to webpages.
*
* Example:
* <code>
* Keyboard.shrinkView(true);
* Keyboard.shrinkView(false);
* </code>
*
* @param shrink
*/
shrinkView(shrink:boolean): void,
/**
* Hide the keyboard toolbar.
*
* Set to true to hide the additional toolbar that is on top of the keyboard.
* This toolbar features the Prev, Next, and Done buttons.
*
* Example:
* <code>
* Keyboard.hideFormAccessoryBar(true);
* Keyboard.hideFormAccessoryBar(false);
* </code>
*
* @param hide
*/
hideFormAccessoryBar(hide:boolean): void,
/**
* Disable scrolling when the the WebView is shrunk.
*
* Set to true to disable scrolling when the WebView is shrunk.
*
* Example:
* <code>
* Keyboard.disableScrollingInShrinkView(true);
* Keyboard.disableScrollingInShrinkView(false);
* </code>
*
* @param disable
*/
disableScrollingInShrinkView(disable:boolean): void,
// Properties
/**
* Determine if the keyboard is visible.
*
* Read this property to determine if the keyboard is visible.
*
* Example:
* <code>
* if (Keyboard.isVisible) {
* // do something
* }
* </code>
*
*/
isVisible: boolean,
/**
* Specifies whenether content of page would be autoamtically scrolled to the top of the page when keyboard is hiding.
*
* Set this to true if you need that page scroll to beginning when keyboard is hiding.
* This is allows to fix issue with elements declared with position: fixed, after keyboard is hiding.
*
* Example:
* <code>
* Keyboard.automaticScrollToTopOnHiding = true;
* </code>
*
*/
automaticScrollToTopOnHiding: boolean,
// Events
/**
* If defined, this function is fired when keyboard fully shown.
*
* Attach handler to this event to be able to receive notification when keyboard is shown.
*
* Example:
* <code>
* Keyboard.onshow = function () {
* // Describe your logic which will be run each time keyboard is shown.
* }
* </code>
*
*/
onshow():void,
/**
* If defined, this function is fired when keyboard fully closed.
*
* Attach handler to this event to be able to receive notification when keyboard is closed.
*
* Example:
* <code>
* Keyboard.onhide = function () {
* // Describe your logic which will be run each time keyboard is closed.
* }
* </code>
*
*/
onhide():void,
/**
* If defined, this function is fired before keyboard will be shown.
*
* Attach handler to this event to be able to receive notification when keyboard is about to be shown on the screen.
*
* Example:
* <code>
* Keyboard.onshowing = function () {
* // Describe your logic which will be run each time when keyboard is about to be shown.
* }
* </code>
*
*/
onshowing():void,
/**
* If defined, this function is fired when keyboard is about to be closed.
*
* Attach handler to this event to be able to receive notification when keyboard is about to be closed.
*
* Example:
* <code>
* Keyboard.onhiding = function () {
* // Describe your logic which will be run each time when keyboard is about to be closed.
* }
* </code>
*
*/
onhiding():void,
}
declare var Keyboard:Keyboard;

View File

@@ -0,0 +1,16 @@
/// <reference path="credential.d.ts" />
import * as credential from 'credential';
credential.hash('password', function(err: Error, hash: string) {
if (err) console.error(err);
else console.log(hash);
});
const hash = '{}';
const password = 'test';
credential.verify(hash, password, function(err: Error, isValid: boolean) {
if (err) console.error(err);
else console.log(isValid ? 'Password match' : 'Incorrect password');
});

18
credential/credential.d.ts vendored Normal file
View File

@@ -0,0 +1,18 @@
// Type definitions for credential
// Project: https://github.com/ericelliott/credential
// Definitions by: Phú <https://github.com/phuvo>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'credential' {
type HashCallback = (err: Error, hash: string) => void;
type VerifyCallback = (err: Error, isValid: boolean) => void;
module credential {
function hash(password: string, callback: HashCallback): void;
function verify(hash: string, password: string, callback: VerifyCallback): void;
}
export = credential;
}

115
decorum/decorum-tests.ts Normal file
View File

@@ -0,0 +1,115 @@
/// <reference path="./decorum.d.ts" />
import {Required} from 'decorum';
import {Email} from 'decorum';
import {MinLength} from 'decorum';
import {MaxLength} from 'decorum';
import {Length} from 'decorum';
import {FieldName} from 'decorum';
import {Validation} from 'decorum';
import {Pattern} from 'decorum';
import {Alpha} from 'decorum';
import {AlphaNumeric} from 'decorum';
import {Validator} from 'decorum';
import {BaseValidator} from 'decorum';
import {IMessageOpts} from 'decorum';
import {MessageHandlers} from 'decorum';
class MyModel {
@FieldName('User name')
@Required()
@MaxLength(50)
username = '';
@FieldName('Email address')
@Email()
@Required('Your email address will be used to send you a confirmation email. You must fill it out')
emailAddress = '';
@Required()
@MinLength(10)
@MaxLength(30)
password = '';
@FieldName('Confirm password')
@Validation<MyModel>(
'The passwords do not match.',
(pwd, model) => model.password === pwd
)
confirmPassword = '';
@Pattern(/^[a-z0-9-]+$/i, 'Must be a valid slug tag')
slug = 'foo';
@Length(6, 'Alias must be 6 characters long')
alias: string;
@Alpha((opts: IMessageOpts) => 'Message overridden for field ' + opts.property + ' with friendly name ' + opts.friendlyName)
alpha: string;
@AlphaNumeric((opts: IMessageOpts) => 'Message overridden for field ' + opts.property + ' with friendly name ' + opts.friendlyName)
alphaNumeric: string;
}
// ES6-style
class MyController {
model = new MyModel();
validator = Validator.new(this.model);
doStuff(): void {
var opts = this.validator.getValidationOptions('alias');
var fieldName = opts.getFriendlyName();
var errs = opts.validateValue('foo', this.model);
opts.setFriendlyName('Foo');
opts.addValidator(null);
var validators = opts.getValidators();
}
validate(): void {
var result = this.validator.validate();
if (!result.isValid) {
for(var i = 0; i < result.errors.length; i++) {
var current = result.errors[i];
console.error(current.fieldName, current.errors);
}
}
}
}
// ES5-style
function MyOtherModel() {
this.foo = '';
this.bar = '';
}
Validator.decorate(MyOtherModel, {
foo: [
decorum.Required()
],
bar: [
decorum.Pattern(/^[a-z][0-9]$/i),
decorum.FieldName('My bar')
]
});
var otherValidator = Validator.new(new MyOtherModel());
otherValidator.validateField('foo', '');
// Custom validator
class MyValidator extends BaseValidator {
validatesEmptyValue(): boolean {
return false;
}
getMessage(opts: IMessageOpts): string {
return opts.friendlyName + ' is not a valid thing because of value ' + opts.value + '! Fyi... its property name is ' + opts.property;
}
isValid(value: any, model: any): boolean {
return false;
}
}
// Message overrides
MessageHandlers['alpha'] = (opts: IMessageOpts) => 'The value ' + opts.value + ' for property ' + opts.property + ' is invalid!';

View File

@@ -0,0 +1,2 @@
--experimentalDecorators
--target ES5

436
decorum/decorum.d.ts vendored Normal file
View File

@@ -0,0 +1,436 @@
// Type definitions for Decorum JS v0.2.0
// Project: https://github.com/dflor003/decorum
// Definitions by: Danil Flores <https://github.com/dflor003>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'decorum' {
export = decorum;
}
declare namespace decorum {
/**
* A generic custom validation. Takes a predicate that will receive the proposed value as the first parameter and
* the current model state as the second.
* @param message The message to display when the predicate fails.
* @param predicate A lambda expression/function that determines if the value is valid. If it returns a falsy
* value, the field will be considered invalid and will return the passed error message upon validation.
* @returns {function(Object, string): void} A field validation decorator.
*/
export function Validation<TModel>(message: string | MessageHandler<CustomValidator<TModel>>, predicate: (value: any, model: TModel) => boolean): PropertyDecorator;
/**
* Validate's that the field is a valid email address. The format used is the same as the webkit browser's internal
* email validation format. For looser or stricter formats, use your own validation based on the @Pattern decorator.
* @param message [Optional] Overrides the default validation error message.
* @returns {function(Object, string): void} A field validation decorator.
*/
export function Email(message?: string | MessageHandler<EmailValidator>): PropertyDecorator;
/**
* Sets the field's "friendly" name in validation error messages.
* @param name The field's friendly name
* @returns {function(Object, string): void} A field validation decorator.
*/
export function FieldName(name: string): PropertyDecorator;
/**
* Validate's a field's EXACT length. Validation fails if the field is not EXACTLY the length passed.
* @param length The exact length the field must be.
* @param message [Optional] Overrides the default validation error message.
* @returns {function(Object, string): void} A field validation decorator.
*/
export function Length(length: number, message?: string | MessageHandler<LengthValidator>): PropertyDecorator;
/**
* Validates a field's maximum length.
* @param maxLength The field's maximum length. Must be a positive integer greater than 1.
* @param message [Optional] Overrides the default validation error message.
* @returns {function(Object, string): void} A field validation decorator.
*/
export function MaxLength(maxLength: number, message?: string | MessageHandler<MaxLengthValidator>): PropertyDecorator;
/**
* Validates the field's minimum length.
* @param minLength The field's minimum length. Must be a positive integer greater than 0
* @param message [Optional] Overrides the default validation error message.
* @returns {function(Object, string): void} A field validation decorator.
*/
export function MinLength(minLength: number, message?: string | MessageHandler<MinLengthValidator>): PropertyDecorator;
/**
* Validates the field against a regular expression pattern.
* @param regex The regex to validate against. Should be a valid JavaScript {RegExp} instance.
* @param message [Optional] Overrides the default validation error message.
* @returns {function(Object, string): void} A field validation decorator.
*/
export function Pattern(regex: RegExp, message?: string | MessageHandler<PatternValidator>): PropertyDecorator;
/**
* Marks the field as required.
* @param message [Optional] Overrides the default validation error message.
* @returns {function(Object, string): void} A field validation decorator.
*/
export function Required(message?: string | MessageHandler<RequiredFieldValidator>): PropertyDecorator;
/**
* Validates that a given field only contains alpha values.
* @param message [Optional] Overrides the default validation error message.
* @returns {function(Object, string): void} A field validation decorator.
*/
export function Alpha(message?: string | MessageHandler<PatternValidator>): PropertyDecorator;
/**
* Validates that a given field only contains alphanumeric values.
* @param message [Optional] Overrides the default validation error message.
* @returns {function(Object, string): void} A field validation decorator.
*/
export function AlphaNumeric(message?: string | MessageHandler<PatternValidator>): PropertyDecorator;
/**
* A map from field name to array of field validation decorators.
*/
export type ValidationDefinitions = {
[field: string]: PropertyDecorator[];
};
/**
* Static container for convenience methods related to field validation.
*/
export class Validator {
/**
* Creates a new model validator for the given model. Model should be a valid class that has a valid constructor
* and a prototype.
* @param model The model to create the validator for.
* @returns {ModelValidator} An instance of {ModelValidator}
*/
static new(model: any): ModelValidator;
/**
* Decorates the passed class with model validations. Use this when you do not have access to ES7 decorators.
* The object passed should be a valid class (ES6 class or ES5 function constructor).
* @param objectType The class to decorate.
* @param definitions One or more field validation definitions of the form { "fieldName": [ decorators ] }.
*/
static decorate(objectType: any, definitions: ValidationDefinitions): void;
/**
* Creates an anonymous validator, immediately validates the model, and returns any validation errors on the
* model as a result.
* @param model The model to validate.
*/
static validate(model: any): IValidationResult;
/**
* Adds a validator to the given object prototype for the given property. Meant to be used inside of validation
* decorators to inject the validation onto the object property.
* @param targetPrototype A valid object prototype to add to.
* @param property The property to add the validator for.
* @param validator The validator to add.
*/
static addValidator(targetPrototype: Object, property: string, validator: BaseValidator): void;
}
/**
* Details about validation errors on a field.
*/
export interface IFieldValidationError {
/**
* The property name of the field on the model.
*/
field: string;
/**
* The "friendly" name of the field. If not set on the model via @FieldName(...), it will default to "Field".
*/
fieldName: string;
/**
* One or more field validation errors. Empty if no errors.
*/
errors: string[];
}
/**
* Result returned when a model is validated.
*/
export interface IValidationResult {
/**
* Whether or not the model is valid.
*/
isValid: boolean;
/**
* A map of field name to validation errors.
*/
errors: IFieldValidationError[];
}
/**
* Wraps a model to allow the consuming class to call validation methods.
*/
export class ModelValidator {
/**
* Creates a new model validator.
* @param model The model to validate. Should be a class that has a valid constructor function and prototype.
*/
constructor(model: any);
/**
* Gets the validation options for the given field name.
* @param fieldKey The name of the field to get options for.
* @returns {FieldOptions} The field options associated with that field or null if no validations defined
* for the field.
*/
getValidationOptions(fieldKey: string): FieldOptions;
/**
* Validates the given field on this {ModelValidator}'s model. If a proposed value is passed, validate
* against that passed value; otherwise, use the field's current value on the model.
* @param fieldKey The name of the field to validate.
* @param proposedValue [Optional] The proposed value to set on the field.
* @returns {string[]} An array of field validation error messages if the field is invalid; otherwise,
* an empty array.
*/
validateField(fieldKey: string, proposedValue?: any): string[];
/**
* Validate the entire model and return a result that indicates whether the model is valid or not and any
* errors
* that have occurred in an object indexed by field name on the model.
* @returns {IValidationResult} An object that contains whether the model is valid or not and errors by field
* name.
*/
validate(): IValidationResult;
}
/**
* Callback invoked when a validation needs to return an error. The first parameter is an object
* wrapping metadata about the field such as the field name, friendly name, value, etc.
* The second parameter is the validator instance that triggered the error.
*/
export interface MessageHandler<TValidator extends BaseValidator> {
(opts: IMessageOpts, validator: TValidator): string;
}
/**
* Options passed to a field to aid in generating a message. Contains data about
* the field such as name, friendly name, and value.
*/
export interface IMessageOpts {
/**
* The property name from the model. I.e. 'emailAddress', 'username', etc.
*/
property: string;
/**
* The friendly name for the field. I.e. 'Email address', 'Password Confirmation', etc.
*/
friendlyName: string;
/**
* The current value of the field at the time the validation error was generated.
*/
value: string;
}
/**
* A map of validation "key" (unique name for a given type of validation) to message handler callback.
*/
export interface IMessageHandlerMap {
[key: string]: MessageHandler<any>;
}
/**
* Mechanism for overriding validation errors to provide for custom or localized error messages.
* @type {{IMessageHandlerMap}}
*/
export let MessageHandlers: IMessageHandlerMap;
/**
* Custom validation class.
*/
export class CustomValidator<TModel> extends BaseValidator {
constructor(predicate: (value: any, model: TModel) => boolean, message: string | MessageHandler<CustomValidator<TModel>>);
getMessage(opts: IMessageOpts): string;
isValid(value: any, model: any): boolean;
}
/**
* An email validator.
*/
export class EmailValidator extends PatternValidator {
static EmailRegex: RegExp;
constructor(message?: string | MessageHandler<EmailValidator>);
getMessage(opts: IMessageOpts): string;
getKey(): string;
}
/**
* An exact length validator.
*/
export class LengthValidator extends BaseValidator {
length: number;
constructor(length: number, message?: string | MessageHandler<LengthValidator>);
getMessage(opts: IMessageOpts): string;
isValid(value: any): boolean;
}
/**
* A maximum length validator.
*/
export class MaxLengthValidator extends BaseValidator {
maxLength: number;
constructor(maxLength: number, message?: string | MessageHandler<MaxLengthValidator>);
getMessage(opts: IMessageOpts): string;
isValid(value: string): boolean;
}
/**
* A minimum length validator.
*/
export class MinLengthValidator extends BaseValidator {
minLength: number;
constructor(minLength: number, message?: string | MessageHandler<MinLengthValidator>);
getMessage(opts: IMessageOpts): string;
isValid(value: string): boolean;
}
/**
* A regular expression validator.
*/
export class PatternValidator extends BaseValidator {
pattern: RegExp;
constructor(pattern: RegExp, message?: string | MessageHandler<PatternValidator>);
getMessage(opts: IMessageOpts): string;
isValid(value: any): boolean;
}
/**
* A field requiredness validator.
*/
export class RequiredFieldValidator extends BaseValidator {
constructor(message?: string | MessageHandler<RequiredFieldValidator>);
validatesEmptyValue(): boolean;
getMessage(opts: IMessageOpts): string;
isValid(value: any): boolean;
}
/**
* Base abstract class for all validators. Methods that must be overridden:
* getMessage(...) - Get error message to return when field is invalid.
* isValid(...) - Check validity of field given proposed value and the rest of the model.
*/
export abstract class BaseValidator {
/**
* Initializes the {BaseValidator}
* @param validatorKey A unique "key" by which to identify this field validator i.e. length, maxlength,
* required. Should be a valid JS property name.
* @param message A custom error message to return. Should be passed down from concrete class' constructors to
* enable customizing error messages.
*/
constructor(validatorKey: string, message: string | MessageHandler<any>);
/**
* Returns true if the validator instance was passed a custom error message.
*/
hasCustomMessage: boolean;
/**
* Check whether this validator should process an "empty" value (i.e. null, undefined, empty string). Override
* this in derived classes to skip validators if the field value hasn't been set. Things like email, min/max
* length, and pattern should return false for this to ensure they don't get fired when the model is initially
* empty before a user has had a chance to input a value. Things like required should override this to true so
* that they are fired for empty values. Base implementation defaults to false
* @returns {boolean}
*/
validatesEmptyValue(): boolean;
/**
* Gets the custom error message set on this validator.
* @param opts Metadata about the field such as name and friendly name.
* @returns {string} The custom error message or null if none has been set.
*/
getCustomMessage(opts: IMessageOpts): string;
/**
* Gets the unique name for this validator.
* @returns {string} The unique name for this validator.
*/
getKey(): string;
/**
* [Abstract] Gets the error message to display when a field fails validation by this validator.
* @param opts Metadata about the field such as name and friendly name.
*/
abstract getMessage(opts: IMessageOpts): string;
/**
* [Abstract] Checks the passed value for validity.
* @param value The field's proposed value.
* @param model The rest of the model if cross-field validity checks are necessary.
*/
abstract isValid(value: any, model: any): boolean;
}
/**
* Validation options for a given field including actual validators and meta data such as the field name.
*/
export class FieldOptions {
constructor(property: string);
/**
* Gets the "friendly" name of the field for use in validation error messages. Defaults to just "Field".
* @returns {string}
*/
getFriendlyName(): string;
/**
* Sets the "friendly" name of the field for use in validation error messages. This name will be used in the
* text of validation errors.
* @param name The new name to set.
*/
setFriendlyName(name: string): void;
/**
* Add a validator to the list of validators for this field.
* @param validator The validator to add. Should be a class that extends from {BaseValidator}.
*/
addValidator(validator: BaseValidator): void;
/**
* Gets the validators assigned to this field.
* @returns {BaseValidator[]} The validators for this field.
*/
getValidators(): BaseValidator[];
/**
* Runs through all of the validators for the field given a particular value and returns any validation errors
* that may have occurred.
* @param value The value to validate.
* @param model The rest of the model. Used in custom cross-field validations.
* @returns {string[]} Any validation errors that may have occurred or an empty array if the value passed is
* valid for the field.
*/
validateValue(value: any, model: any): string[];
}
}

54
depd/depd-tests.ts Normal file
View File

@@ -0,0 +1,54 @@
/// <reference path="./depd.d.ts"/>
import depd = require('depd');
var deprecate = depd("depd-tests");
function assert(condition: boolean, message: string): void {
if (!condition) {
throw new Error(message);
}
}
function testDepdMessage(...args: string[]): boolean {
if (arguments.length < 1) {
deprecate('testDepdMessage argument.lenth<1');
return true;
} else {
console.log('normal logic');
return false;
}
}
assert(testDepdMessage() === true, "Deprecated code must be triggered!");
assert(testDepdMessage('a') === false, "Deprecated code must be triggered!");
interface ITestObject {
p1: string;
p2: string;
}
var obj = <ITestObject>{ p1: 'deprecated property', p2: 'normal property' };
deprecate.property(obj, 'p1', 'property [p1] is deprecated!');
console.log(obj.p1);
interface ITestDeprecatedFunction {
func1?: Function;
func2?: Function;
}
var obj2 = <ITestDeprecatedFunction>{};
// message automatically derived from function name
obj2.func1 = deprecate.function(function func1() {
console.log('all calls to [func1] are deprecated ');
});
// specific message
obj2.func2 = deprecate.function(function () {
console.log('all calls to [func2] are deprecated ');
}, 'func2');
obj2.func1();
obj2.func2();

17
depd/depd.d.ts vendored Normal file
View File

@@ -0,0 +1,17 @@
// Type definitions for depd 1.1.0
// Project: https://github.com/dougwilson/nodejs-depd
// Definitions by: Zhiyuan Wang <https://github.com/danny8002/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module 'depd' {
function depd(namespace: string): Deprecate;
interface Deprecate {
(message: string): void;
function(fn: Function, message?: string): Function;
property(obj: Object, prop: string, message: string): void;
}
export = depd;
}

2
dexie/dexie.d.ts vendored
View File

@@ -38,7 +38,7 @@ declare class Dexie {
static deepClone(obj: Object): Object;
version(versionNumber: Number): Dexie.Version
version(versionNumber: number): Dexie.Version
on: {
(eventName: string, subscriber: () => any): void;

View File

@@ -1229,7 +1229,7 @@ interface SchedulerStatic{
* return the event object by its id
* @param event_id event_id
*/
getEvent(event_id: any);
getEvent<T>(event_id: any): T;
/**
* gets the event's end date
@@ -1601,4 +1601,4 @@ interface SchedulerStatic{
declare var scheduler: SchedulerStatic;
declare var scheduler: SchedulerStatic;

View File

@@ -1 +0,0 @@

133
durandal/durandal.d.ts vendored
View File

@@ -1,4 +1,4 @@
// Type definitions for Durandal 2.1.0
// Type definitions for Durandal 2.1.0
// Project: http://durandaljs.com
// Definitions by: Blue Spire <https://github.com/BlueSpire>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
@@ -12,6 +12,18 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../knockout/knockout.d.ts" />
// By default, Durandal uses JQuery's Defer/Promise implementation, but durandal supports injecting/configuring
// usage of different JavaScript Defer/Promise libraries (f.ex. Q or ES6 Promise polyfills).
// You might therefore want to use a different interface from a community typings file or your custom unified interface.
// When using f.ex. Q as Defer/Promise library replace the lines below with:
// <reference path="../q/Q.d.ts" />
// interface DurandalPromise<T> extends Q.Promise<T>
// interface DurandalDeferred<T> extends Q.Deferred<T>
interface DurandalPromise<T> extends JQueryPromise<T> { }
interface DurandalDeferred<T> extends JQueryDeferred<T> { }
/**
* The system module encapsulates the most basic features used by other modules.
* @requires require
@@ -45,7 +57,7 @@ interface DurandalSystemModule {
* @param {object} obj The object whose module id you wish to set.
* @param {string} id The id to set for the specified object.
*/
setModuleId(obj, id: string): void;
setModuleId(obj: any, id: string): void;
/**
* Resolves the default object instance for a module. If the module is an object, the module is returned. If the module is a function, that function is called with `new` and it's result is returned.
@@ -89,9 +101,9 @@ interface DurandalSystemModule {
/**
* Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise.
* @param {function} [action] The action to defer. You will be passed the deferred object as a paramter.
* @returns {JQueryDeferred} The deferred object.
* @returns {Deferred} The deferred object.
*/
defer<T>(action?: (dfd: JQueryDeferred<T>) => void): JQueryDeferred<T>;
defer<T>(action?: (dfd: DurandalDeferred<T>) => void): DurandalDeferred<T>;
/**
* Creates a simple V4 UUID. This should not be used as a PK in your database. It can be used to generate internal, unique ids. For a more robust solution see [node-uuid](https://github.com/broofa/node-uuid).
@@ -102,23 +114,23 @@ interface DurandalSystemModule {
/**
* Uses require.js to obtain a module. This function returns a promise which resolves with the module instance.
* @param {string} moduleId The id of the module to load.
* @returns {JQueryPromise} A promise for the loaded module.
* @returns {Promise} A promise for the loaded module.
*/
acquire(moduleId: string): JQueryPromise<any>;
acquire(moduleId: string): DurandalPromise<any>;
/**
* Uses require.js to obtain an array of modules. This function returns a promise which resolves with the modules instances in an array.
* @param {string[]} moduleIds The ids of the modules to load.
* @returns {JQueryPromise} A promise for the loaded module.
* @returns {Promise} A promise for the loaded module.
*/
acquire(modules: string[]): JQueryPromise<any[]>;
acquire(modules: string[]): DurandalPromise<any[]>;
/**
* Uses require.js to obtain multiple modules. This function returns a promise which resolves with the module instances in an array.
* @param {string} moduleIds* The ids of the modules to load.
* @returns {JQueryPromise} A promise for the loaded module.
* @returns {Promise} A promise for the loaded module.
*/
acquire(...moduleIds: string[]): JQueryPromise<any[]>;
acquire(...moduleIds: string[]): DurandalPromise<any[]>;
/**
* Extends the first object with the properties of the following objects.
@@ -130,9 +142,9 @@ interface DurandalSystemModule {
/**
* Uses a setTimeout to wait the specified milliseconds.
* @param {number} milliseconds The number of milliseconds to wait.
* @returns {JQueryPromise}
* @returns {Promise}
*/
wait(milliseconds: number): JQueryPromise<any>;
wait(milliseconds: number): DurandalPromise<any>;
/**
* Gets all the owned keys of the specified object.
@@ -295,14 +307,14 @@ interface DurandalViewEngineModule {
* @param {string} id The view id whose view should be cached.
* @param {DOMElement} view The view to cache.
*/
putViewInCache(id: string, view: HTMLElement);
putViewInCache(id: string, view: HTMLElement): void;
/**
* Creates the view associated with the view id.
* @param {string} viewId The view id whose view should be created.
* @returns {JQueryPromise<HTMLElement>} A promise of the view.
* @returns {DurandalPromise<HTMLElement>} A promise of the view.
*/
createView(viewId: string): JQueryPromise<HTMLElement>;
createView(viewId: string): DurandalPromise<HTMLElement>;
/**
* Called when a view cannot be found to provide the opportunity to locate or generate a fallback view. Mainly used to ease development.
@@ -311,7 +323,7 @@ interface DurandalViewEngineModule {
* @param {Error} requirePath The error that was returned from the attempt to locate the default view.
* @returns {Promise} A promise for the fallback view.
*/
createFallbackView(viewId: string, requirePath: string, err: Error): JQueryPromise<HTMLElement>;
createFallbackView(viewId: string, requirePath: string, err: Error): DurandalPromise<HTMLElement>;
}
/**
@@ -439,7 +451,7 @@ interface DurandalViewLocatorModule {
* @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first.
* @returns {Promise} A promise of the view.
*/
locateViewForObject(obj: any, area: string, elementsToSearch?: HTMLElement[]): JQueryPromise<HTMLElement>;
locateViewForObject(obj: any, area: string, elementsToSearch?: HTMLElement[]): DurandalPromise<HTMLElement>;
/**
* Converts a module id into a view id. By default the ids are the same.
@@ -470,7 +482,7 @@ interface DurandalViewLocatorModule {
* @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first.
* @returns {Promise} A promise of the view.
*/
locateView(view: HTMLElement, area?: string, elementsToSearch?: HTMLElement[]): JQueryPromise<HTMLElement>;
locateView(view: HTMLElement, area?: string, elementsToSearch?: HTMLElement[]): DurandalPromise<HTMLElement>;
/**
* Locates the specified view.
@@ -479,7 +491,7 @@ interface DurandalViewLocatorModule {
* @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first.
* @returns {Promise} A promise of the view.
*/
locateView(viewUrlOrId: string, area?: string, elementsToSearch?: HTMLElement[]): JQueryPromise<HTMLElement>;
locateView(viewUrlOrId: string, area?: string, elementsToSearch?: HTMLElement[]): DurandalPromise<HTMLElement>;
}
/**
@@ -514,7 +526,7 @@ declare module 'durandal/composition' {
area?: string;
preserveContext?: boolean;
activate?: boolean;
strategy?: (context: CompositionContext) => JQueryPromise<HTMLElement>;
strategy?: (context: CompositionContext) => DurandalPromise<HTMLElement>;
composingNewView: boolean;
child: HTMLElement;
binding?: (child: HTMLElement, parent: HTMLElement, context: CompositionContext) => void;
@@ -547,7 +559,7 @@ declare module 'durandal/composition' {
* @param {object} [config] The binding handler instance. If none is provided, the name will be used to look up an existing handler which will then be converted to a composition handler.
* @param {function} [initOptionsFactory] If the registered binding needs to return options from its init call back to knockout, this function will server as a factory for those options. It will receive the same parameters that the init function does.
*/
export function addBindingHandler(name, config?: KnockoutBindingHandler, initOptionsFactory?: (element?: HTMLElement, valueAccessor?: any, allBindingsAccessor?: any, viewModel?: any, bindingContext?: KnockoutBindingContext) => any);
export function addBindingHandler(name: string, config?: KnockoutBindingHandler, initOptionsFactory?: (element?: HTMLElement, valueAccessor?: any, allBindingsAccessor?: any, viewModel?: any, bindingContext?: KnockoutBindingContext) => any): void;
/**
* Gets an object keyed with all the elements that are replacable parts, found within the supplied elements. The key will be the part name and the value will be the element itself.
@@ -568,7 +580,7 @@ declare module 'durandal/composition' {
* @param {object} context The composition context containing the model and possibly existing viewElements.
* @returns {promise} A promise for the view.
*/
export var defaultStrategy: (context: CompositionContext) => JQueryPromise<HTMLElement>;
export var defaultStrategy: (context: CompositionContext) => DurandalPromise<HTMLElement>;
/**
* Initiates a composition.
@@ -663,13 +675,13 @@ declare module 'plugins/dialog' {
* In this function, you are expected to add a DOM element to the tree which will serve as the "host" for the modal's composed view. You must add a property called host to the modalWindow object which references the dom element. It is this host which is passed to the composition module.
* @param {Dialog} theDialog The dialog model.
*/
addHost(theDialog: Dialog);
addHost(theDialog: Dialog): void;
/**
* This function is expected to remove any DOM machinery associated with the specified dialog and do any other necessary cleanup.
* @param {Dialog} theDialog The dialog model.
*/
removeHost(theDialog: Dialog);
removeHost(theDialog: Dialog): void;
/**
* This function is called after the modal is fully composed into the DOM, allowing your implementation to do any final modifications, such as positioning or animation. You can obtain the original dialog object by using `getDialog` on context.model.
@@ -677,14 +689,14 @@ declare module 'plugins/dialog' {
* @param {DOMElement} parent The parent view.
* @param {object} context The composition context.
*/
compositionComplete(child: HTMLElement, parent: HTMLElement, context: composition.CompositionContext);
compositionComplete(child: HTMLElement, parent: HTMLElement, context: composition.CompositionContext): void;
}
interface Dialog {
owner: any;
context: DialogContext;
activator: DurandalActivator<any>;
close(): JQueryPromise<any>;
close(): DurandalPromise<any>;
settings: composition.CompositionContext;
}
@@ -745,7 +757,7 @@ declare module 'plugins/dialog' {
* @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified.
* @returns {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing.
*/
export function show(obj: any, activationData?: any, context?: string): JQueryPromise<any>;
export function show(obj: any, activationData?: any, context?: string): DurandalPromise<any>;
/**
* Shows a message box.
@@ -756,7 +768,7 @@ declare module 'plugins/dialog' {
* @param {Object} [settings] Custom settings for this instance of the messsage box, used to change classes and styles.
* @returns {Promise} A promise that resolves when the message box is closed and returns the selected option.
*/
export function showMessage(message: string, title?: string, options?: string[], autoclose?: boolean, settings?: Object): JQueryPromise<string>;
export function showMessage(message: string, title?: string, options?: string[], autoclose?: boolean, settings?: Object): DurandalPromise<string>;
/**
* Shows a message box.
@@ -767,7 +779,7 @@ declare module 'plugins/dialog' {
* @param {Object} [settings] Custom settings for this instance of the messsage box, used to change classes and styles.
* @returns {Promise} A promise that resolves when the message box is closed and returns the selected option.
*/
export function showMessage(message: string, title?: string, options?: DialogButton[], autoclose?: boolean, settings?: Object): JQueryPromise<any>;
export function showMessage(message: string, title?: string, options?: DialogButton[], autoclose?: boolean, settings?: Object): DurandalPromise<any>;
/**
* Installs this module into Durandal; called by the framework. Adds `app.showDialog` and `app.showMessage` convenience methods.
@@ -890,7 +902,7 @@ declare module 'plugins/http' {
* @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
* @returns {Promise} A promise of the get response data.
*/
export function get(url: string, query?: Object, headers?: Object): JQueryPromise<any>;
export function get(url: string, query?: Object, headers?: Object): DurandalPromise<any>;
/**
* Makes an JSONP request.
@@ -900,7 +912,7 @@ declare module 'plugins/http' {
* @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
* @returns {Promise} A promise of the response data.
*/
export function jsonp(url: string, query?: Object, callbackParam?: string, headers?: Object): JQueryPromise<any>;
export function jsonp(url: string, query?: Object, callbackParam?: string, headers?: Object): DurandalPromise<any>;
/**
* Makes an HTTP POST request.
@@ -909,7 +921,7 @@ declare module 'plugins/http' {
* @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
* @returns {Promise} A promise of the response data.
*/
export function post(url: string, data: Object, headers?: Object): JQueryPromise<any>;
export function post(url: string, data: Object, headers?: Object): DurandalPromise<any>;
/**
* Makes an HTTP PUT request.
@@ -919,7 +931,7 @@ declare module 'plugins/http' {
* @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
* @return {Promise} A promise of the response data.
*/
export function put(url: string, data: Object, headers?: Object): JQueryPromise<any>;
export function put(url: string, data: Object, headers?: Object): DurandalPromise<any>;
/**
* Makes an HTTP DELETE request.
@@ -929,7 +941,7 @@ declare module 'plugins/http' {
* @param {object} [headers] The data to add to the request header. It will be converted to JSON. If the data contains Knockout observables, they will be converted into normal properties before serialization.
* @return {Promise} A promise of the get response data.
*/
export function remove(url: string, query?: Object, headers?: Object): JQueryPromise<any>;
export function remove(url: string, query?: Object, headers?: Object): DurandalPromise<any>;
}
/**
@@ -964,7 +976,7 @@ declare module 'plugins/observable' {
* @param {function|object} evaluatorOrOptions The Knockout computed function or computed options object.
* @returns {KnockoutComputed} The underlying computed observable.
*/
export function defineProperty<T>(obj: any, propertyName: string, evaluatorOrOptions?: KnockoutComputedDefine<T>);
export function defineProperty<T>(obj: any, propertyName: string, evaluatorOrOptions?: KnockoutComputedDefine<T>): KnockoutComputed<T>;
/**
* Installs the plugin into the view model binder's `beforeBind` hook so that objects are automatically converted before being bound.
@@ -1046,7 +1058,7 @@ declare module 'plugins/serializer' {
* @param {object} [settings] Settings can specify a replacer or space to override the serializer defaults.
* @returns {string} The JSON string.
*/
export function serialize(object: any, settings?: string);
export function serialize(object: any, settings?: string): string;
/**
* Serializes the object.
@@ -1054,7 +1066,7 @@ declare module 'plugins/serializer' {
* @param {object} [settings] Settings can specify a replacer or space to override the serializer defaults.
* @returns {string} The JSON string.
*/
export function serialize(object: any, settings?: number);
export function serialize(object: any, settings?: number): string;
/**
* Serializes the object.
@@ -1062,7 +1074,7 @@ declare module 'plugins/serializer' {
* @param {object} [settings] Settings can specify a replacer or space to override the serializer defaults.
* @returns {string} The JSON string.
*/
export function serialize(object: any, settings?: SerializerOptions);
export function serialize(object: any, settings?: SerializerOptions): string;
/**
* Gets the type id for an object instance, using the configured `typeAttribute`.
@@ -1081,7 +1093,7 @@ declare module 'plugins/serializer' {
* @param {string} typeId The type id.
* @param {function} constructor The constructor.
*/
export function registerType(typeId: string, constructor: () => any);
export function registerType(typeId: string, constructor: () => any): void;
/**
* The default reviver function used during deserialization. By default is detects type properties on objects and uses them to re-construct the correct object using the provided constructor mapping.
@@ -1091,7 +1103,7 @@ declare module 'plugins/serializer' {
* @param {object} getConstructor A custom function used to get the constructor function associated with a type id.
* @returns {object} The value.
*/
export function reviver(key: string, value: any, getTypeId: (value: any) => string, getConstructor: (string) => () => any): any;
export function reviver(key: string, value: any, getTypeId: (value: any) => string, getConstructor: (id: string) => () => any): any;
/**
* Deserialize the JSON.
@@ -1128,7 +1140,7 @@ declare module 'plugins/widget' {
* Creates a ko binding handler for the specified kind.
* @param {string} kind The kind to create a custom binding handler for.
*/
export function registerKind(kind: string);
export function registerKind(kind: string): void;
/**
* Maps views and module to the kind identifier if a non-standard pattern is desired.
@@ -1136,7 +1148,7 @@ declare module 'plugins/widget' {
* @param {string} [viewId] The unconventional view id to map the kind to.
* @param {string} [moduleId] The unconventional module id to map the kind to.
*/
export function mapKind(kind: string, viewId?: string, moduleId?: string);
export function mapKind(kind: string, viewId?: string, moduleId?: string): void;
/**
* Maps a kind name to it's module id. First it looks up a custom mapped kind, then falls back to `convertKindToModulePath`.
@@ -1172,7 +1184,7 @@ declare module 'plugins/widget' {
* @param {object} settings The widget settings.
* @param {object} [bindingContext] The current binding context.
*/
export function create(element: HTMLElement, settings: WidgetSettings, bindingContext?: KnockoutBindingContext);
export function create(element: HTMLElement, settings: WidgetSettings, bindingContext?: KnockoutBindingContext): void;
}
/**
@@ -1279,14 +1291,14 @@ interface DurandalAppModule extends DurandalEventSupport<DurandalAppModule> {
* @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified.
* @returns {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing.
*/
showDialog(obj: any, activationData?: any, context?: string): JQueryPromise<any>;
showDialog(obj: any, activationData?: any, context?: string): DurandalPromise<any>;
/**
* Closes the dialog associated with the specified object. via the dialog plugin.
* @param {object} obj The object whose dialog should be closed.
* @param {object} results* The results to return back to the dialog caller after closing.
*/
closeDialog(obj: any, ...results);
closeDialog(obj: any, ...results: any[]): void;
/**
* Shows a message box via the dialog plugin.
@@ -1297,7 +1309,7 @@ interface DurandalAppModule extends DurandalEventSupport<DurandalAppModule> {
* @param {Object} [settings] Custom settings for this instance of the messsage box, used to change classes and styles.
* @returns {Promise} A promise that resolves when the message box is closed and returns the selected option.
*/
showMessage(message: string, title?: string, options?: string[], autoclose?: boolean, settings?: Object): JQueryPromise<string>;
showMessage(message: string, title?: string, options?: string[], autoclose?: boolean, settings?: Object): DurandalPromise<string>;
/**
* Shows a message box.
@@ -1308,7 +1320,7 @@ interface DurandalAppModule extends DurandalEventSupport<DurandalAppModule> {
* @param {Object} [settings] Custom settings for this instance of the messsage box, used to change classes and styles.
* @returns {Promise} A promise that resolves when the message box is closed and returns the selected option.
*/
showMessage(message: string, title?: string, options?: DialogButton[], autoclose?: boolean, settings?: Object): JQueryPromise<any>;
showMessage(message: string, title?: string, options?: DialogButton[], autoclose?: boolean, settings?: Object): DurandalPromise<any>;
/**
* Configures one or more plugins to be loaded and installed into the application.
@@ -1322,7 +1334,7 @@ interface DurandalAppModule extends DurandalEventSupport<DurandalAppModule> {
* Starts the application.
* @returns {promise}
*/
start(): JQueryPromise<any>;
start(): DurandalPromise<any>;
/**
* Sets the root module/view for the application.
@@ -1404,7 +1416,7 @@ interface DurandalActivator<T> extends KnockoutComputed<T> {
* @param {boolean} close Whether or not to check if close is possible.
* @returns {promise}
*/
canDeactivateItem(item: T, close: boolean): JQueryPromise<boolean>;
canDeactivateItem(item: T, close: boolean): DurandalPromise<boolean>;
/**
* Deactivates the specified item.
@@ -1412,7 +1424,7 @@ interface DurandalActivator<T> extends KnockoutComputed<T> {
* @param {boolean} close Whether or not to close the item.
* @returns {promise}
*/
deactivateItem(item: T, close: boolean): JQueryPromise<boolean>;
deactivateItem(item: T, close: boolean): DurandalPromise<boolean>;
/**
* Determines whether or not the specified item can be activated.
@@ -1420,7 +1432,7 @@ interface DurandalActivator<T> extends KnockoutComputed<T> {
* @param {object} activationData Data associated with the activation.
* @returns {promise}
*/
canActivateItem(newItem: T, activationData?: any): JQueryPromise<boolean>;
canActivateItem(newItem: T, activationData?: any): DurandalPromise<boolean>;
/**
* Activates the specified item.
@@ -1428,31 +1440,31 @@ interface DurandalActivator<T> extends KnockoutComputed<T> {
* @param {object} newActivationData Data associated with the activation.
* @returns {promise}
*/
activateItem(newItem: T, activationData?: any): JQueryPromise<boolean>;
activateItem(newItem: T, activationData?: any): DurandalPromise<boolean>;
/**
* Determines whether or not the activator, in its current state, can be activated.
* @returns {promise}
*/
canActivate(): JQueryPromise<boolean>;
canActivate(): DurandalPromise<boolean>;
/**
* Activates the activator, in its current state.
* @returns {promise}
*/
activate(): JQueryPromise<boolean>;
activate(): DurandalPromise<boolean>;
/**
* Determines whether or not the activator, in its current state, can be deactivated.
* @returns {promise}
*/
canDeactivate(close: boolean): JQueryPromise<boolean>;
canDeactivate(close: boolean): DurandalPromise<boolean>;
/**
* Deactivates the activator, in its current state.
* @returns {promise}
*/
deactivate(close: boolean): JQueryPromise<boolean>;
deactivate(close: boolean): DurandalPromise<boolean>;
/**
* Adds canActivate, activate, canDeactivate and deactivate functions to the provided model which pass through to the corresponding functions on the activator.
@@ -1462,7 +1474,7 @@ interface DurandalActivator<T> extends KnockoutComputed<T> {
/**
* Sets up a collection representing a pool of objects which the activator will activate. See below for details. Activators without an item bool always close their values on deactivate. Activators with an items pool only deactivate, but do not close them.
*/
forItems(items): DurandalActivator<T>;
forItems(items: any[]): DurandalActivator<T>;
}
interface DurandalHistoryOptions {
@@ -1509,7 +1521,7 @@ interface DurandalRouteConfiguration {
title?: any;
moduleId?: string;
hash?: string;
route?: string|string[];
route?: string | string[];
routePattern?: RegExp;
isActive?: KnockoutComputed<boolean>;
nav?: any;
@@ -1529,6 +1541,7 @@ interface DurandalRelativeRouteSettings {
moduleId?: string;
route?: string;
fromParent?: boolean;
dynamicHash?: string;
}
interface DurandalRouterBase<T> extends DurandalEventSupport<T> {
@@ -1765,7 +1778,7 @@ interface DurandalRouterBase<T> extends DurandalEventSupport<T> {
* @param {object} instruction The route instruction. The instruction object has config, fragment, queryString, params and queryParams properties.
* @returns {Promise|Boolean|String} If a boolean, determines whether or not the route should activate or be cancelled. If a string, causes a redirect to the specified route. Can also be a promise for either of these value types.
*/
guardRoute?: (instance: Object, instruction: DurandalRouteInstruction) => JQueryPromise<boolean|string>|boolean|string;
guardRoute?: (instance: Object, instruction: DurandalRouteInstruction) => DurandalPromise<boolean | string> | boolean | string;
/**
* Parent router of the current child router.
@@ -1785,7 +1798,7 @@ interface DurandalRootRouter extends DurandalRouterBase<DurandalRootRouter> {
* Activates the router and the underlying history tracking mechanism.
* @returns {Promise} A promise that resolves when the router is ready.
*/
activate(options?: DurandalHistoryOptions): JQueryPromise<any>;
activate(options?: DurandalHistoryOptions): DurandalPromise<any>;
/**
* Disable history, perhaps temporarily. Not useful in a real app, but possibly useful for unit testing Routers.

View File

@@ -1 +0,0 @@

View File

@@ -0,0 +1,54 @@
/// <reference path="./electron-builder.d.ts" />
import * as factory from "electron-builder";
const builder = factory.init();
function callback(err: Error) {
const msg = err.message;
}
builder.build({
appPath: ".",
out: "out",
platform: "win",
config: {
osx: {
title: "myapplication",
icon: "icon.icns",
"icon-size": 80,
background: "installer.png",
contents: [
{ x: 438, y: 344, type: "link", path: "/Applications" },
{ x: 192, y: 344, type: "file" },
]
},
win: {
title: "myapplication",
icon: "icon.ico"
}
}
}, callback);
const bldr = require("electron-builder").init();
bldr.build({
appPath: ".",
out: "out",
platform: "osx",
config: {
osx: {
title: "myapplication",
icon: "icon.icns",
"icon-size": 80,
background: "installer.png",
contents: [
{ x: 438, y: 344, type: "link", path: "/Applications" },
{ x: 192, y: 344, type: "file" },
]
},
win: {
title: "myapplication",
icon: "icon.ico"
}
}
}, callback);

90
electron-builder/electron-builder.d.ts vendored Normal file
View File

@@ -0,0 +1,90 @@
// Type definitions for electron-builder v2.0.2
// Project: https://github.com/loopline-systems/electron-builder
// Definitions by: Maxime LUCE <https://github.com/SomaticIT/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare namespace ElectronBuilder {
/** Electron-builder Options. */
export interface Options {
/** Source application path. */
appPath: string;
/** Platforms to build. Allowed values: win, osx, all. */
platform: string;
/** Path or Object. Configuration for build. */
config: string | Config;
/** The output directory. */
out?: string;
}
/** Build configuration by platforms. */
export interface Config {
/** Configurations for Mac OS X. */
osx: {
/** Installer title. */
title: string;
/** Installer background. */
background: string;
/** Installer icon. */
icon: string;
/** Installer icon size. */
"icon-size": number;
/** Installer custom contents. */
contents: [OsxContents, OsxContents]
};
/** Configurations for Windows. */
win: {
/** Installer title. */
title: string;
/** Installer icon. */
icon: string;
};
}
/** OSX Installer custom contents. */
export interface OsxContents {
/** Horizontal position on installer screen (in pixels). */
x: number;
/** Vertical position on installer screen (in pixels). */
y: number;
/** Content type. Allowed values are "file", "link". */
type: string;
/** Link only. Customize link destination path. */
path?: string;
}
/** Electron-builder done callback. */
export interface Callback {
/**
* Callback wich is called when electron-builder is done.
* @param err - Contains errors if any.
*/
(err: Error): void
}
/** Prototype for electron-builder. */
export interface Builder {
/**
* Build the installer for given platform.
*
* @param opts - Options to configure installer.
* @param callback - Callback which is called when building is done or an error occured.
*/
build(opts: Options, callback: Callback): void;
}
}
declare module "electron-builder" {
export function init(): ElectronBuilder.Builder;
}
interface NodeRequireFunction {
(id: "electron-builder"): { init(): ElectronBuilder.Builder };
}

View File

@@ -0,0 +1,41 @@
/// <reference path="./electron-packager.d.ts" />
import * as packager from "electron-packager";
function callback(err: Error, appPath: string) {
const
msg = err.message,
index = appPath.indexOf("test");
}
packager({
dir: ".",
name: "myapplication",
platform: "win32",
arch: "all",
version: "0.34.0"
}, callback);
packager({
dir: ".",
name: "myapplication",
version: "0.34.0",
all: true
}, callback);
const pkger = require("electron-packager");
pkger({
dir: ".",
name: "myapplication",
platform: "win32",
arch: "all",
version: "0.34.0"
}, callback);
pkger({
dir: ".",
name: "myapplication",
version: "0.34.0",
all: true
}, callback);

115
electron-packager/electron-packager.d.ts vendored Normal file
View File

@@ -0,0 +1,115 @@
// Type definitions for electron-packager v5.1.0
// Project: https://github.com/maxogden/electron-packager
// Definitions by: Maxime LUCE <https://github.com/SomaticIT/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare namespace ElectronPackager {
/** Electron-packager Options. */
export interface Options {
/** The source directory. */
dir: string;
/** The application name. */
name: string;
/**
* Allowed values: linux, win32, darwin, all. Not required if `all` is used.
* Arbitrary combinations of individual platforms are also supported via a comma-delimited string or array of strings.
*/
platform?: string | string[];
/** Allowed values: ia32, x64, all Not required if `all` is used. */
arch?: string;
/** Electron version (without the "v"). See https://github.com/atom/electron/releases. */
version: string;
/** Shortcut for `--arch=all --platform=all`. */
all?: boolean;
/** The output directory. */
out?: string;
/**
* Currently you must look for conversion tools in order to supply an icon in the format required by the platform:
* - OS X: `.icns`
* - Windows: `.ico`
*
* For Linux builds, this option is not required, as the dock/window list icon is set via the icon option in the BrowserWindow contructor.
* Setting the icon in the file manager is not currently supported.
*
* If the file extension is omitted, it is auto-completed to the correct extension based on the platform,
* including when `--platform=all` is in effect.
*/
icon?: string;
/** The bundle identifier to use in the app plist. */
"app-bundle-id"?: string;
/** The release version to set for the app. */
"app-version"?: string;
/** The build version to set for the app (OS X only). */
"build-version"?: string;
/** The bundle identifier to use in the app helper plist. */
"helper-bundle-id"?: string;
/** Object hash of application metadata to embed into the executable (Windows only). */
"version-string"?: VersionString;
/** The directory of cached electron downloads. Defaults to "$HOME/.electron". */
cache?: string;
/** Do not copy files into App whose filenames regex .match this string. */
ignore?: RegExp;
/** Runs `npm prune --production` on the app. */
prune?: boolean;
/** If output directory for a platform already exists, replaces it rather than skipping it. */
overwrite?: boolean;
/** Packages the source code within your app into an archive. */
asar?: boolean;
/** Unpacks the files to app.asar.unpacked directory whose filenames regex .match this string. */
"asar-unpack"?: string;
/** Should contain the identity to be used when running `codesign` (OS X only). */
sign?: string;
}
/** Object hash of application metadata to embed into the executable (Windows only). */
export interface VersionString {
CompanyName?: string;
LegalCopyright?: string;
FileDescription?: string;
OriginalFilename?: string;
FileVersion?: string;
ProductVersion?: string;
ProductName?: string;
InternalName?: string;
}
/** Electron-packager done callback. */
export interface Callback {
/**
* Callback wich is called when electron-packager is done.
*
* @param err - Contains errors if any.
* @param appPath - Path to the newly created application.
*/
(err: Error, appPath: string): void
}
/** Electron-packager function */
export interface Packager {
/**
* This will:
* - Find or download the correct release of Electron
* - Use that version of electron to create a app in <out>/<appname>-<platform>-<arch>
*
* You should be able to launch the app on the platform you built for. If not, check your settings and try again.
*
* @param opts - Options to configure packaging.
* @param callback - Callback which is called when packaging is done or an error occured.
*/
(opts: Options, callback: Callback): void;
}
}
declare module "electron-packager" {
const packager: ElectronPackager.Packager;
export = packager;
}
interface NodeRequireFunction {
(id: "electron-packager"): ElectronPackager.Packager;
}

View File

@@ -5,18 +5,18 @@ import EventEmitter = require('eventemitter3');
class EventEmitterTest {
v: EventEmitter;
constructor() {
this.v = new EventEmitter();
this.v = new EventEmitter.EventEmitter();
this.v = new EventEmitter.EventEmitter2();
this.v = new EventEmitter.EventEmitter3();
}
listeners() {
var v1: Function[] = this.v.listeners('click');
}
emit() {
var v1: boolean = this.v.emit('click');
var v2: boolean = this.v.emit('click', 1);
@@ -24,41 +24,41 @@ class EventEmitterTest {
var v4: boolean = this.v.emit('click', 1, '1', true);
var v5: boolean = this.v.emit('click', 1, '1', true, new Date());
}
on() {
var fn = () => console.log(1);
var v1: EventEmitter = this.v.on('click', fn);
var v2: EventEmitter = this.v.on('click', fn, this);
}
once() {
var fn = () => console.log(1);
var v1: EventEmitter = this.v.once('click', fn);
var v2: EventEmitter = this.v.once('click', fn, this);
}
removeListener() {
var fn = () => console.log(1);
var v1: EventEmitter = this.v.removeListener('click', fn);
var v2: EventEmitter = this.v.removeListener('click', fn, true);
}
removeAllListeners() {
var v1: EventEmitter = this.v.removeAllListeners('click');
}
off() {
var fn = () => console.log(1);
var v1: EventEmitter = this.v.off('click', fn);
var v2: EventEmitter = this.v.off('click', fn, true);
}
addListener() {
var fn = () => console.log(1);
var v1: EventEmitter = this.v.addListener('click', fn);
var v2: EventEmitter = this.v.addListener('click', fn, this);
}
setMaxListeners() {
var v1: EventEmitter = this.v.setMaxListeners();
}

View File

@@ -0,0 +1,17 @@
/// <reference path="../node/node.d.ts" />
/// <reference path="../express/express.d.ts" />
/// <reference path="express-handlebars.d.ts" />
import express = require('express');
import exphbs = require('express-handlebars');
var app = express();
var hbs: Exphbs = exphbs.create({defaultLayout: 'main'});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.listen(1337);
console.log('Test Express Handlebars app on port 1337..');
console.log('Done');
process.exit(0);

View File

@@ -0,0 +1,46 @@
// Type definitions for express-handlebars
// Project: https://github.com/ericf/express-handlebars
// Definitions by: Sam Saint-Pettersen <https://github.com/stpettersens>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../es6-promise/es6-promise.d.ts" />
interface PartialTemplateOptions {
cache?: boolean;
precompiled?: boolean;
}
interface RenderOptions {
cache?: boolean;
data?: Object;
helpers?: any;
partials?: any;
}
interface ExphbsOptions {
handlebars?: any;
extname?: string;
layoutsDir?: string;
partialsDir?: string;
defaultLayout?: string;
helpers?: any;
compilerOptions?: any;
}
interface Exphbs {
engine: Function;
extname: string;
compiled: Object;
precompiled: Object;
create(options?: ExphbsOptions): Exphbs;
getPartials(options?: PartialTemplateOptions): Promise<Object>;
getTemplate(filePath: string, options?: PartialTemplateOptions): Promise<Function>;
getTemplates(dirPath: string, options?: PartialTemplateOptions): Promise<Object>;
render(filePath: string, context: Object, options?: RenderOptions): Promise<string>;
renderView(viewPath: string, optionsOrCallback: any, callback?: () => string): void;
}
declare module "express-handlebars" {
var exphbs: Exphbs;
export = exphbs;
}

View File

@@ -1 +0,0 @@

File diff suppressed because one or more lines are too long

11694
fhir/fhir.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
// Type definitions for Firebase API 2.0.2
// Project: https://www.firebase.com/docs/javascript/firebase
// Definitions by: Vincent Botone <https://github.com/vbortone/>, Shin1 Kashimura <https://github.com/in-async/>
// Definitions by: Vincent Botone <https://github.com/vbortone/>, Shin1 Kashimura <https://github.com/in-async/>, Sebastien Dubois <https://github.com/dsebastien/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface FirebaseAuthResult {
@@ -317,6 +317,27 @@ interface FirebaseAuthData {
token: string;
expires: number;
auth: Object;
google?: FirebaseAuthDataGoogle;
}
interface FirebaseAuthDataGoogle {
accessToken: string;
cachedUserProfile: FirebaseAuthDataGoogleCachedUserProfile;
displayName: string;
email?: string;
id: string;
profileImageURL: string;
}
interface FirebaseAuthDataGoogleCachedUserProfile {
"family name"?: string;
gender?: string;
"given name"?: string;
id?: string;
link?: string;
locale?: string;
name?: string;
picture?: string;
}
interface FirebaseCredentials {

View File

@@ -0,0 +1,37 @@
///<reference path="./fixed-data-table.d.ts"" />
/// <reference path="../react/react.d.ts"/>
import * as React from "react";
import * as FixedDataTable from "fixed-data-table";
var rows = [
['a1', 'b1', 'c1'],
['a2', 'b2', 'c2'],
['a3', 'b3', 'c3'],
// .... and more
];
function rowGetter(rowIndex: number) {
return rows[rowIndex];
}
var table = <FixedDataTable.Table
rowHeight={50}
rowGetter={rowGetter}
rowsCount={rows.length}
width={5000}
height={5000}
headerHeight={50}>
<FixedDataTable.Column
label="Col 1"
width={3000}
dataKey={0}
/>
<FixedDataTable.Column
label="Col 2"
width={2000}
dataKey={1}
/>
</FixedDataTable.Table>
React.render(table, document.body);

402
fixed-data-table/fixed-data-table.d.ts vendored Normal file
View File

@@ -0,0 +1,402 @@
// Type definitions for fixed-data-table 0.4.7
// Project: https://github.com/facebook/fixed-data-table
// Definitions by: Petar Paar <https://github.com/pepaar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../react/react.d.ts"/>
declare module FixedDataTable {
export var version: string;
export interface TableProps extends __React.Props<Table> {
/**
* Pixel width of table. If all columns do not fit,
* a horizontal scrollbar will appear.
*/
width: number;
/**
* Pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
height?: number;
/**
* Maximum pixel height of table. If all rows do not fit,
* a vertical scrollbar will appear.
*
* Either `height` or `maxHeight` must be specified.
*/
maxHeight?: number;
/**
* Pixel height of table's owner, this is used in a managed scrolling
* situation when you want to slide the table up from below the fold
* without having to constantly update the height on every scroll tick.
* Instead, vary this property on scroll. By using `ownerHeight`, we
* over-render the table while making sure the footer and horizontal
* scrollbar of the table are visible when the current space for the table
* in view is smaller than the final, over-flowing height of table. It
* allows us to avoid resizing and reflowing table when it is moving in the
* view.
*
* This is used if `ownerHeight < height` (or `maxHeight`).
*/
ownerHeight?: number;
/**
* hidden or auto
*/
overflowX?: string;
overflowY?: string;
/**
* Number of rows in the table.
*/
rowsCount: number;
/**
* Pixel height of rows unless `rowHeightGetter` is specified and returns
* different value.
*/
rowHeight: number;
/**
* If specified, `rowHeightGetter(index)` is called for each row and the
* returned value overrides `rowHeight` for particular row.
*/
rowHeightGetter?: Function;
/**
* To get rows to display in table, `rowGetter(index)`
* is called. `rowGetter` should be smart enough to handle async
* fetching of data and return temporary objects
* while data is being fetched.
*/
rowGetter: Function;
/**
* To get any additional CSS classes that should be added to a row,
* `rowClassNameGetter(index)` is called.
*/
rowClassNameGetter?: Function;
/**
* Pixel height of the column group header.
*/
groupHeaderHeight?: number;
/**
* Pixel height of header.
*/
headerHeight: number;
/**
* Function that is called to get the data for the header row.
* If the function returns null, the header will be set to the
* Column's label property.
*/
headerDataGetter?: Function;
/**
* Pixel height of footer.
*/
footerHeight?: number;
/**
* DEPRECATED - use footerDataGetter instead.
* Data that will be passed to footer cell renderers.
*/
footerData?: any;
/**
* Function that is called to get the data for the footer row.
*/
footerDataGetter?: Function;
/**
* Value of horizontal scroll.
*/
scrollLeft?: number;
/**
* Index of column to scroll to.
*/
scrollToColumn?: number;
/**
* Value of vertical scroll.
*/
scrollTop?: number;
/**
* Index of row to scroll to.
*/
scrollToRow?: number;
/**
* Callback that is called when scrolling starts with current horizontal
* and vertical scroll values.
*/
onScrollStart?: Function;
/**
* Callback that is called when scrolling ends or stops with new horizontal
* and vertical scroll values.
*/
onScrollEnd?: Function;
/**
* Callback that is called when `rowHeightGetter` returns a different height
* for a row than the `rowHeight` prop. This is necessary because initially
* table estimates heights of some parts of the content.
*/
onContentHeightChange?: Function;
/**
* Callback that is called when a row is clicked.
*/
onRowClick?: Function;
/**
* Callback that is called when a row is double clicked.
*/
onRowDoubleClick?: Function;
/**
* Callback that is called when a mouse-down event happens on a row.
*/
onRowMouseDown?: Function;
/**
* Callback that is called when a mouse-enter event happens on a row.
*/
onRowMouseEnter?: Function;
/**
* Callback that is called when a mouse-leave event happens on a row.
*/
onRowMouseLeave?: Function;
/**
* Callback that is called when resizer has been released
* and column needs to be updated.
*
* Required if the isResizable property is true on any column.
*
* ```
* function(
* newColumnWidth: number,
* dataKey: string,
* )
* ```
*/
onColumnResizeEndCallback?: Function;
/**
* Whether a column is currently being resized.
*/
isColumnResizing?: boolean
}
interface ColumnProps {
/**
* The horizontal alignment of the table cell content.
* 'left', 'center', 'right'
*/
align?: string;
/**
* className for this column's header cell.
*/
headerClassName?: string;
/**
* className for this column's footer cell.
*/
footerClassName?: string;
/**
* className for each of this column's data cells.
*/
cellClassName?: string;
/**
* The cell renderer that returns React-renderable content for table cell.
* ```
* function(
* cellData: any,
* cellDataKey: string,
* rowData: object,
* rowIndex: number,
* columnData: any,
* width: number
* ): ?$jsx
* ```
*/
cellRenderer?: Function;
/**
* The getter `function(string_cellDataKey, object_rowData)` that returns
* the cell data for the `cellRenderer`.
* If not provided, the cell data will be collected from
* `rowData[cellDataKey]` instead. The value that `cellDataGetter` returns
* will be used to determine whether the cell should re-render.
*/
cellDataGetter?: Function;
/**
* The key to retrieve the cell data from the data row. Provided key type
* must be either `string` or `number`. Since we use this
* for keys, it must be specified for each column.
*/
dataKey: string|number;
/**
* Controls if the column is fixed when scrolling in the X axis.
*/
fixed?: boolean;
/**
* The cell renderer that returns React-renderable content for table column
* header.
* ```
* function(
* label: ?string,
* cellDataKey: string,
* columnData: any,
* rowData: array<?object>,
* width: number
* ): ?$jsx
* ```
*/
headerRenderer?: Function;
/**
* The cell renderer that returns React-renderable content for table column
* footer.
* ```
* function(
* label: ?string,
* cellDataKey: string,
* columnData: any,
* rowData: array<?object>,
* width: number
* ): ?$jsx
* ```
*/
footerRenderer?: Function;
/**
* Bucket for any data to be passed into column renderer functions.
*/
columnData?: any;
/**
* The column's header label.
*/
label: string;
/**
* The pixel width of the column.
*/
width: number;
/**
* If this is a resizable column this is its minimum pixel width.
*/
minWidth?: number;
/**
* If this is a resizable column this is its maximum pixel width.
*/
maxWidth?: number;
/**
* The grow factor relative to other columns. Same as the flex-grow API
* from http://www.w3.org/TR/css3-flexbox/. Basically, take any available
* extra width and distribute it proportionally according to all columns'
* flexGrow values. Defaults to zero (no-flexing).
*/
flexGrow?: number;
/**
* Whether the column can be resized with the
* FixedDataTableColumnResizeHandle. Please note that if a column
* has a flex grow, once you resize the column this will be set to 0.
*
* This property only provides the UI for the column resizing. If this
* is set to true, you will need ot se the onColumnResizeEndCallback table
* property and render your columns appropriately.
*/
isResizable?: boolean;
/**
* Experimental feature
* Whether cells in this column can be removed from document when outside
* of viewport as a result of horizontal scrolling.
* Setting this property to true allows the table to not render cells in
* particular column that are outside of viewport for visible rows. This
* allows to create table with many columns and not have vertical scrolling
* performance drop.
* Setting the property to false will keep previous behaviour and keep
* cell rendered if the row it belongs to is visible.
*/
allowCellsRecycling?: boolean;
}
export interface ColumnGroupProps {
/**
* The horizontal alignment of the table cell content.
* 'left', 'center', 'right'
*/
align?: string;
/**
* Controls if the column group is fixed when scrolling in the X axis.
*/
fixed?: boolean;
/**
* Bucket for any data to be passed into column group renderer functions.
*/
columnGroupData?: any;
/**
* The column group's header label.
*/
label?: string;
/**
* The cell renderer that returns React-renderable content for a table
* column group header. If it's not specified, the label from props will
* be rendered as header content.
* ```
* function(
* label: ?string,
* cellDataKey: string,
* columnGroupData: any,
* rowData: array<?object>, // array of labels of all columnGroups
* width: number
* ): ?$jsx
* ```
*/
groupHeaderRenderer?: Function;
}
export class Table extends __React.Component<TableProps, {}> {
render(): __React.DOMElement<any>
}
export class Column extends __React.Component<ColumnProps, {}> {
render(): __React.DOMElement<any>
}
export class ColumnGroup extends __React.Component<ColumnGroupProps, {}> {
render(): __React.DOMElement<any>
}
}
declare module "fixed-data-table" {
export = FixedDataTable;
}

View File

@@ -41,7 +41,7 @@ flowOptions.testMethod = "";
flowOptions.uploadMethod = "";
flowOptions.allowDuplicateUploads = true;
flowOptions.prioritizeFirstAndLastChunk = true;
flowOptions.testchunks = true;
flowOptions.testChunks = true;
flowOptions.preprocess = () => {};
flowOptions.initFileFn = () => {};
flowOptions.generateUniqueIdentifier = () => {};

2
flowjs/flowjs.d.ts vendored
View File

@@ -44,7 +44,7 @@ declare module flowjs {
uploadMethod?: string;
allowDuplicateUploads?: boolean;
prioritizeFirstAndLastChunk?: boolean;
testchunks?: boolean;
testChunks?: boolean;
preprocess?: Function;
initFileFn?: Function;
generateUniqueIdentifier?: Function;

View File

@@ -5,27 +5,27 @@ import Fluxxor = require('fluxxor');
class DispatcherTest {
v: Fluxxor.Dispatcher;
constructor() {
var stores: Fluxxor.Store[];
this.v = new Fluxxor.Dispatcher(stores);
}
addStore() {
var store: Fluxxor.Store;
var v1: void = this.v.addStore('mystore', store);
}
dispatch() {
var fn = () => console.log(1);
var v1: void = this.v.dispatch(fn);
}
doDispatchLoop() {
var fn = () => console.log(1);
var v1: void = this.v.doDispatchLoop(fn);
}
waitForStores() {
var store: Fluxxor.Store;
var fn = () => console.log(1);
@@ -35,44 +35,44 @@ class DispatcherTest {
class FluxTest {
v: Fluxxor.Flux;
constructor() {
var stores: any;
var actions: any;
this.v = new Fluxxor.Flux(stores, actions);
}
props() {
var stores: any = this.v.stores;
var actions: any = this.v.actions;
}
addActions() {
var actions: any;
var v1: void = this.v.addActions(actions);
}
addAction() {
var fn = () => console.log(1);
// first form
var v1: void = this.v.addAction('action1', fn);
var v2: void = this.v.addAction('action1', 'action2', fn);
// second form
var v3: void = this.v.addAction(['action1'], fn);
var v4: void = this.v.addAction(['action1','action2'], fn);
}
store() {
var store1: any = this.v.store('mystore');
}
addStore() {
var store: Fluxxor.Store;
var v1: void = this.v.addStore('mystore', store);
}
addStores() {
var stores: any;
var v1: void = this.v.addStores(stores);
@@ -81,24 +81,24 @@ class FluxTest {
class StoreTest {
v: Fluxxor.Store;
bindActions() {
var fn = () => console.log(1);
// first form
var v1: void = this.v.bindActions('action1', fn);
var v2: void = this.v.bindActions(
'action1', fn,
'action2', fn
);
// second form
var v3: void = this.v.bindActions([
'action1', fn,
'action2', fn,
]);
}
waitFor() {
var fn = () => console.log(1);
var v1: void = this.v.waitFor(['mystore1','mystore2'], fn);
@@ -107,7 +107,7 @@ class StoreTest {
class ContextTest {
v: Fluxxor.Context;
props() {
var v1: Fluxxor.Flux = this.v.flux;
}
@@ -115,11 +115,11 @@ class ContextTest {
class FluxMixinTest {
v: Fluxxor.FluxMixin;
constructor() {
this.v = Fluxxor.FluxMixin(React);
}
getFlux() {
var v1: Fluxxor.Flux = this.v.getFlux();
}
@@ -127,11 +127,11 @@ class FluxMixinTest {
class FluxChildMixinTest {
v: Fluxxor.FluxChildMixin;
constructor() {
this.v = Fluxxor.FluxChildMixin(React);
}
getFlux() {
var v1: Fluxxor.Flux = this.v.getFlux();
}
@@ -139,13 +139,13 @@ class FluxChildMixinTest {
class StoreWatchMixinTest<StoreState> {
v: Fluxxor.StoreWatchMixin<StoreState>;
constructor() {
this.v = Fluxxor.StoreWatchMixin<StoreState>('store1');
this.v = Fluxxor.StoreWatchMixin<StoreState>('store1','store2');
this.v = Fluxxor.StoreWatchMixin<StoreState>('store1','store2','store3');
}
getStateFromFlux() {
var v1: StoreState = this.v.getStateFromFlux();
}

View File

@@ -35,6 +35,21 @@ app.on('window-all-closed', () => {
app.quit();
});
// Check single instance app
var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
// Someone tried to run a second instance, we should focus our window
if (mainWindow) {
if (mainWindow.isMinimized()) mainWindow.restore();
mainWindow.focus();
}
return true;
});
if (shouldQuit) {
app.quit();
process.exit(0);
}
// This method will be called when Electron has done everything
// initialization and ready for creating browser windows.
app.on('ready', () => {
@@ -145,7 +160,11 @@ ipc.on('online-status-changed', (event: any, status: any) => {
// https://github.com/atom/electron/blob/master/docs/api/synopsis.md
app.on('ready', () => {
window = new BrowserWindow({ width: 800, height: 600 });
window = new BrowserWindow({
width: 800,
height: 600,
'title-bar-style': 'hidden-inset',
});
window.loadUrl('https://github.com');
});

View File

@@ -515,6 +515,7 @@ declare module GitHubElectron {
'shared-worker'?: boolean;
'direct-write'?: boolean;
'page-visibility'?: boolean;
'title-bar-style'?: string;
}
interface Rectangle {
@@ -986,6 +987,12 @@ declare module GitHubElectron {
setUserTasks(tasks: Task[]): void;
dock: BrowserWindow;
commandLine: CommandLine;
/**
* This method makes your application a Single Instance Application instead of allowing
* multiple instances of your app to run, this will ensure that only a single instance
* of your app is running, and other instances signal this instance and exit.
*/
makeSingleInstance(callback: (args: string[], workingDirectory: string) => boolean): boolean;
}
interface CommandLine {

View File

@@ -822,6 +822,7 @@ declare module google.maps {
bounds?: LatLngBounds;
componentRestrictions?: GeocoderComponentRestrictions;
location?: LatLng|LatLngLiteral;
placeId?: string;
region?: string;
}
@@ -1955,6 +1956,7 @@ declare module google.maps {
bounds?: LatLngBounds;
input?: string;
location?: LatLng;
offset?: number;
radius?: number;
}

View File

@@ -1,5 +1,5 @@
// Type definitions for Graphviz 0.0.8
// Project: git://github.com/glejeune/node-graphviz.git
// Project: https://github.com/glejeune/node-graphviz
// Definitions by: Matt Frantz <https://github.com/mhfrantz/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped

View File

@@ -52,6 +52,7 @@ declare module "gridfs-stream" {
files: mongo.Collection;
collection(name?: string): mongo.Collection;
curCol: string;
createWriteStream(options?: GridFSStream.Options): GridFSStream.WriteStream;
createReadStream(options?: GridFSStream.Options): GridFSStream.ReadStream;
@@ -60,6 +61,7 @@ declare module "gridfs-stream" {
remove(options: GridFSStream.Options, callback: (err: Error) => void): void;
exist(options: GridFSStream.Options, callback: (err: Error, found: boolean) => void): void;
findOne(options: GridFSStream.Options, callback: (err: Error, record: any)=>void):void;
}
}

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