diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 6140babecd..4317128869 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -695,7 +695,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](heap/heap.d.ts) [heap](https://github.com/qiao/heap.js) by [Ryan McNamara](https://github.com/ryan10132)
* [:link:](heatmap.js/heatmap.d.ts) [heatmap.js](https://github.com/pa7/heatmap.js) by [Yang Guan](https://github.com/lookuptable)
* [:link:](hellojs/hellojs.d.ts) [hello.js](http://adodson.com/hello.js) by [Pavel Zika](https://github.com/PavelPZ)
-* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher)
+* [:link:](helmet/helmet.d.ts) [helmet](https://github.com/helmetjs/helmet) by [Cyril Schumacher](https://github.com/cyrilschumacher), [Evan Hahn](https://github.com/EvanHahn)
* [:link:](highcharts/highcharts.d.ts) [Highcharts](http://www.highcharts.com) by [Damiano Gambarotto](http://github.com/damianog), [Dan Lewi Harkestad](http://github.com/baltie)
* [:link:](highcharts-ng/highcharts-ng.d.ts) [highcharts-ng](https://github.com/pablojim/highcharts-ng) by [Scott Hatcher](https://github.com/scatcher)
* [:link:](highland/highland.d.ts) [Highland](http://highlandjs.org) by [Bart van der Schoor](https://github.com/Bartvds)
diff --git a/CybozuLabs-md5/CybozuLabs-md5-tests.ts b/CybozuLabs-md5/CybozuLabs-md5-tests.ts
new file mode 100644
index 0000000000..16dd05b059
--- /dev/null
+++ b/CybozuLabs-md5/CybozuLabs-md5-tests.ts
@@ -0,0 +1,9 @@
+///
+
+var hash: string;
+hash = CybozuLabs.MD5.calc("abc");
+hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_ASCII);
+hash = CybozuLabs.MD5.calc("abc", CybozuLabs.MD5.BY_UTF16);
+
+var version: string;
+version = CybozuLabs.MD5.VERSION;
\ No newline at end of file
diff --git a/CybozuLabs-md5/CybozuLabs-md5.d.ts b/CybozuLabs-md5/CybozuLabs-md5.d.ts
new file mode 100644
index 0000000000..6e1f31739d
--- /dev/null
+++ b/CybozuLabs-md5/CybozuLabs-md5.d.ts
@@ -0,0 +1,11 @@
+// Type definitions for CybozuLabs.MD5
+// Project: http://labs.cybozu.co.jp/blog/mitsunari/2007/07/md5js_1.html
+// Definitions by: MIZUNE Pine
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare namespace CybozuLabs.MD5 {
+ var VERSION: string;
+ var BY_ASCII: number;
+ var BY_UTF16: number;
+ function calc(str: string, option?: number): string;
+}
diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts
index 3c70dd27e8..cecaf07e67 100644
--- a/angular-material/angular-material-tests.ts
+++ b/angular-material/angular-material-tests.ts
@@ -55,6 +55,18 @@ myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.
$scope['confirmDialog'] = () => {
$mdDialog.show($mdDialog.confirm().htmlContent('Confirm!'));
};
+ $scope['promptDialog'] = () => {
+ $mdDialog.show($mdDialog.prompt().textContent('Prompt!'));
+ };
+ $scope['promptDialog'] = () => {
+ $mdDialog.show($mdDialog.prompt().htmlContent('Prompt!'));
+ };
+ $scope['promptDialog'] = () => {
+ $mdDialog.show($mdDialog.prompt().cancel('Prompt "Cancel" button text'));
+ };
+ $scope['promptDialog'] = () => {
+ $mdDialog.show($mdDialog.prompt().placeholder('Prompt input placeholder text'));
+ };
$scope['hideDialog'] = $mdDialog.hide.bind($mdDialog, 'hide');
$scope['cancelDialog'] = $mdDialog.cancel.bind($mdDialog, 'cancel');
});
diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts
index 12fe28a9b8..bb144d15d4 100644
--- a/angular-material/angular-material.d.ts
+++ b/angular-material/angular-material.d.ts
@@ -59,6 +59,11 @@ declare namespace angular.material {
interface IConfirmDialog extends IPresetDialog {
cancel(cancel: string): IConfirmDialog;
}
+
+ interface IPromptDialog extends IPresetDialog {
+ cancel(cancel: string): IPromptDialog;
+ placeholder(placeholder: string): IPromptDialog;
+ }
interface IDialogOptions {
templateUrl?: string;
@@ -90,6 +95,7 @@ declare namespace angular.material {
show(dialog: IDialogOptions|IAlertDialog|IConfirmDialog): angular.IPromise;
confirm(): IConfirmDialog;
alert(): IAlertDialog;
+ prompt(): IPromptDialog;
hide(response?: any): angular.IPromise;
cancel(response?: any): void;
}
diff --git a/angular-ui-router/angular-ui-router.d.ts b/angular-ui-router/angular-ui-router.d.ts
index 0512528097..88f00c9b5d 100644
--- a/angular-ui-router/angular-ui-router.d.ts
+++ b/angular-ui-router/angular-ui-router.d.ts
@@ -35,7 +35,7 @@ declare namespace angular.ui {
/**
* String HTML content, or function that returns an HTML string
*/
- template?: string | {(): string};
+ template?: string | {(params: IStateParamsService): string};
/**
* String URL path to template file OR Function, returns URL path string
*/
@@ -229,9 +229,9 @@ declare namespace angular.ui {
*/
notify?: boolean;
/**
- * {boolean=false}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params.
+ * {boolean=false|string|IState}, If true will force transition even if the state or params have not changed, aka a reload of the same state. It differs from reloadOnSearch because you'd use this when you want to force a reload when everything is the same, including search params.
*/
- reload?: boolean;
+ reload?: boolean | string | IState;
}
interface IHrefOptions {
diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts
index 3d2b248637..204c645b0c 100644
--- a/angularjs/angular.d.ts
+++ b/angularjs/angular.d.ts
@@ -389,9 +389,9 @@ declare namespace angular {
$submitted: boolean;
$error: any;
$pending: any;
- $addControl(control: INgModelController): void;
- $removeControl(control: INgModelController): void;
- $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController): void;
+ $addControl(control: INgModelController | IFormController): void;
+ $removeControl(control: INgModelController | IFormController): void;
+ $setValidity(validationErrorKey: string, isValid: boolean, control: INgModelController | IFormController): void;
$setDirty(): void;
$setPristine(): void;
$commitViewValue(): void;
@@ -1845,7 +1845,7 @@ declare namespace angular {
controller(name: string): any;
injector(): any;
scope(): IScope;
-
+
/**
* Overload for custom scope interfaces
*/
@@ -1870,6 +1870,33 @@ declare namespace angular {
annotate(fn: Function, strictDi?: boolean): string[];
annotate(inlineAnnotatedFunction: any[]): string[];
get(name: string, caller?: string): T;
+ get(name: '$anchorScroll'): IAnchorScrollService
+ get(name: '$cacheFactory'): ICacheFactoryService
+ get(name: '$compile'): ICompileService
+ get(name: '$controller'): IControllerService
+ get(name: '$document'): IDocumentService
+ get(name: '$exceptionHandler'): IExceptionHandlerService
+ get(name: '$filter'): IFilterService
+ get(name: '$http'): IHttpService
+ get(name: '$httpBackend'): IHttpBackendService
+ get(name: '$httpParamSerializer'): IHttpParamSerializer
+ get(name: '$httpParamSerializerJQLike'): IHttpParamSerializer
+ get(name: '$interpolate'): IInterpolateService
+ get(name: '$interval'): IIntervalService
+ get(name: '$locale'): ILocaleService
+ get(name: '$location'): ILocationService
+ get(name: '$log'): ILogService
+ get(name: '$parse'): IParseService
+ get(name: '$q'): IQService
+ get(name: '$rootElement'): IRootElementService
+ get(name: '$rootScope'): IRootScopeService
+ get(name: '$sce'): ISCEService
+ get(name: '$sceDelegate'): ISCEDelegateService
+ get(name: '$templateCache'): ITemplateCacheService
+ get(name: '$templateRequest'): ITemplateRequestService
+ get(name: '$timeout'): ITimeoutService
+ get(name: '$window'): IWindowService
+ get(name: '$xhrFactory'): IXhrFactory
has(name: string): boolean;
instantiate(typeConstructor: Function, locals?: any): T;
invoke(inlineAnnotatedFunction: any[]): any;
diff --git a/argv/argv-tests.ts b/argv/argv-tests.ts
new file mode 100644
index 0000000000..6d73c53ec7
--- /dev/null
+++ b/argv/argv-tests.ts
@@ -0,0 +1,15 @@
+///
+import argv = require('argv');
+argv.version( 'v1.0' );
+argv.info( 'Special script info' );
+argv.clear()
+.option({
+ name: 'option',
+ short: 'o',
+ type: 'string',
+ description: 'Defines an option for your script',
+ example: "'script --opiton=value' or 'script -o value'"
+})
+.run([ '--option=123', '-o', '123' ]);
+argv.run();
+argv.help();
diff --git a/argv/argv.d.ts b/argv/argv.d.ts
new file mode 100644
index 0000000000..182ffde861
--- /dev/null
+++ b/argv/argv.d.ts
@@ -0,0 +1,59 @@
+// Type definitions for argv
+// Project: https://www.npmjs.com/package/argv
+// Definitions by: Hookclaw
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+declare module "argv" {
+ // argv module
+ type args = {
+ targets:string[],
+ options:{[key:string]:any}
+ };
+
+ type helpOption = {
+ name: string,
+ type: string,
+ short?: string,
+ description?: string,
+ example?: string
+ };
+
+ type module = {
+ mod: string,
+ description: string,
+ options: {[key:string]:helpOption}
+ };
+
+ type typeFunction = (value:any, ...arglist:any[]) => any;
+
+ type argv = {
+
+ // Runs the arguments parser
+ run: ( argv?:string[] ) => args,
+
+ // Adding options to definitions list
+ option: ( mod:helpOption|helpOption[] ) => argv,
+
+ // Creating module
+ mod: ( object:module|module[] ) => argv,
+
+ // Creates custom type function
+ type: ( name:string|{[key:string]:typeFunction}, callback?:typeFunction ) => any,
+
+ // Setting version number, and auto setting version option
+ version: ( v:string ) => argv,
+
+ // Description setup
+ info: ( mod:string, description?:module ) => argv,
+
+ // Cleans out current options
+ clear: () => argv,
+
+ // Prints out the help doc
+ help: ( mod?:string ) => argv
+
+ };
+
+ var argv:argv;
+
+ export = argv;
+}
diff --git a/atmosphere/atmosphere.d.ts b/atmosphere/atmosphere.d.ts
index bf26ba0db4..239986b3a1 100644
--- a/atmosphere/atmosphere.d.ts
+++ b/atmosphere/atmosphere.d.ts
@@ -102,5 +102,6 @@ declare namespace Atmosphere {
}
declare var atmosphere:Atmosphere.Atmosphere;
-
-
+declare module 'atmosphere' {
+ export = atmosphere;
+}
diff --git a/backbone.radio/backbone.radio-tests.ts b/backbone.radio/backbone.radio-tests.ts
index 295c552af2..764fb65943 100644
--- a/backbone.radio/backbone.radio-tests.ts
+++ b/backbone.radio/backbone.radio-tests.ts
@@ -101,4 +101,10 @@ function TestGlobalApiAndChannels() {
Backbone.Radio.reply('auth', 'authenticate', onStart);
Backbone.Radio.request('auth', 'authenticate', 'pelle', 42);
-}
\ No newline at end of file
+}
+
+import Radio = require('backbone.radio');
+function TestImport() {
+ var channel: Backbone.Radio.Channel = Radio.channel('channel-name');
+ channel.command('show:view');
+}
diff --git a/backbone.radio/backbone.radio.d.ts b/backbone.radio/backbone.radio.d.ts
index 50895b0275..dd049ec1fe 100644
--- a/backbone.radio/backbone.radio.d.ts
+++ b/backbone.radio/backbone.radio.d.ts
@@ -90,3 +90,9 @@ declare namespace Backbone {
}
}
}
+
+declare module 'backbone.radio' {
+ import Backbone = require('backbone');
+
+ export = Backbone.Radio;
+}
diff --git a/backbone/backbone-global.d.ts b/backbone/backbone-global.d.ts
index 2d40a2a8a4..ef0a10f006 100644
--- a/backbone/backbone-global.d.ts
+++ b/backbone/backbone-global.d.ts
@@ -316,7 +316,7 @@ declare namespace Backbone {
stop(): void;
route(route: string, callback: Function): number;
checkUrl(e?: any): void;
- loadUrl(fragmentOverride: string): boolean;
+ loadUrl(fragmentOverride?: string): boolean;
navigate(fragment: string, options?: any): boolean;
static started: boolean;
options: any;
diff --git a/backbone/backbone-tests.ts b/backbone/backbone-tests.ts
index 3669a6c4e1..50632712a6 100644
--- a/backbone/backbone-tests.ts
+++ b/backbone/backbone-tests.ts
@@ -166,6 +166,9 @@ function test_collection() {
//////////
Backbone.history.start();
+Backbone.History.started;
+Backbone.history.loadUrl();
+Backbone.history.loadUrl('12345');
namespace v1Changes {
namespace events {
diff --git a/bezier-js/bezier-js-tests.ts b/bezier-js/bezier-js-tests.ts
new file mode 100644
index 0000000000..1814d67dc0
--- /dev/null
+++ b/bezier-js/bezier-js-tests.ts
@@ -0,0 +1,95 @@
+///
+
+function test() {
+
+ var bezierjs: typeof BezierJs;
+
+ var bezier = new bezierjs.Bezier([1,2,3,4]);
+ var cap = new bezierjs.BezierCap([]);
+ var point: BezierJs.Point = { x: 0, y: 0 };
+ var utils = bezier.getUtils();
+ var line: BezierJs.Line = { p1: { x:0, y: 0}, p2: {x:1, y: 1}};
+ var abc: BezierJs.ABC = { A: null, B: null, C: null };
+ var arc: BezierJs.Arc = { e: 0, s: 0, x: 0, y: 0, r: 1 };
+ var bbox: BezierJs.BBox = bezier.bbox();
+ var closest: BezierJs.Closest = { mdist: 1, mpos: 0 };
+ var inflection: BezierJs.Inflection = { values: null, x: [0], y: [0], z:[0] };
+ var minmax: BezierJs.MinMax = { min: 0, max: 0 };
+ var offset: BezierJs.Offset = { x: 0, y: 0, c: point, n: point };
+ var pair: BezierJs.Pair = { left: bezier, right: bezier };
+ var poly: BezierJs.PolyBezier = bezier.outline(1);
+ var projection: BezierJs.Projection = { x: 0, y: 0, t: 9, d: 4 };
+ var shape: BezierJs.Shape = { startcap: cap, endcap: cap, forward: bezier, back: bezier, bbox: bbox };
+ var split: BezierJs.Split = { left: bezier, right: bezier, span: [point] };
+
+ bezier.arcs();
+ bezier.clockwise;
+ bezier.compute(.5);
+ bezier.computedirection();
+ bezier.curveintersects([bezier], [bezier]);
+ bezier.derivative(0);
+ bezier.get(1);
+ bezier.getLUT()[0].x;
+ bezier.hull(0);
+ bezier.inflections().values;
+ bezier.intersects(bezier);
+ bezier.length();
+ bezier.lineIntersects(line);
+ bezier.normal(0);
+ bezier.offset(1,2);
+ bezier.on(point, 0);
+ bezier.order = 5;
+ bezier.outlineshapes(1,3);
+ bezier.overlaps(bezier);
+ bezier.point(9);
+ bezier.project(point);
+ bezier.raise();
+ bezier.reduce();
+ bezier.scale(4);
+ bezier.selfintersects();
+ bezier.simple();
+ bezier.split(0, 1);
+ bezier.toSVG();
+ bezier.update();
+
+ cap.virtual = true;
+
+ poly.addCurve(bezier);
+ poly.bbox();
+ poly.curve(7);
+ poly.curves[0]._3d;
+ poly.length();
+ poly.offset(9).points[0].y;
+ poly.points[0];
+
+ utils.abcratio(0, 1);
+ utils.align([point], line);
+ utils.angle(point, point, point);
+ utils.approximately(5, 7, .001);
+ utils.arcfn(1, function(){});
+ utils.bboxoverlap(bbox, bbox);
+ utils.between(0, 0, 1);
+ utils.closest([point], point);
+ utils.copy({});
+ utils.dist(point, point);
+ utils.droots([9]);
+ utils.expandbox(bbox, bbox);
+ utils.findbbox([bezier]);
+ utils.getccenter(point, point, point);
+ utils.getminmax(bezier, 'x', [0]);
+ utils.length(function(){});
+ utils.lerp(1, point, point);
+ utils.lli(offset, offset);
+ utils.lli4(point, point, point, point);
+ utils.lli8(0, 0, 0, 0, 0, 0, 0, 0);
+ utils.makeline(point, point);
+ utils.makeshape(bezier, bezier);
+ utils.map(0, 0, 0, 0, 0);
+ utils.pairiteration(bezier, bezier);
+ utils.pointsToString([point]);
+ utils.projectionratio(0, 0);
+ utils.roots([point], line);
+ utils.round(.999, .001);
+ utils.shapeintersections(shape, bbox, shape, bbox);
+
+}
\ No newline at end of file
diff --git a/bezier-js/bezier-js.d.ts b/bezier-js/bezier-js.d.ts
new file mode 100644
index 0000000000..7d54a19d95
--- /dev/null
+++ b/bezier-js/bezier-js.d.ts
@@ -0,0 +1,197 @@
+// Type definitions for Bezier.js
+// Project: https://github.com/Pomax/bezierjs
+// Definitions by: Dan Marshall
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+declare module BezierJs {
+ interface Point {
+ x: number;
+ y: number;
+ z?: number;
+ }
+ interface Projection extends Point {
+ t?: number;
+ d?: number;
+ }
+ interface Inflection {
+ x: number[];
+ y: number[];
+ z?: number[];
+ values: number[];
+ }
+ interface Offset extends Point {
+ c: Point;
+ n: Point;
+ }
+ interface Pair {
+ left: Bezier;
+ right: Bezier;
+ }
+ interface Split extends Pair {
+ span: Point[];
+ _t1?: number;
+ _t2?: number;
+ }
+ interface MinMax {
+ min: number;
+ mid?: number;
+ max: number;
+ size?: number;
+ }
+ interface BBox {
+ x: MinMax;
+ y: MinMax;
+ z?: MinMax;
+ }
+ interface Line {
+ p1: Point;
+ p2: Point;
+ }
+ interface Arc extends Point {
+ e: number;
+ r: number;
+ s: number;
+ }
+ interface Shape {
+ startcap: BezierCap;
+ forward: Bezier;
+ back: Bezier;
+ endcap: BezierCap;
+ bbox: BBox;
+ }
+ interface ABC {
+ A: Point;
+ B: Point;
+ C: Point;
+ }
+ interface Closest {
+ mdist: number;
+ mpos: number;
+ }
+ /**
+ * Bezier curve constructor. The constructor argument can be one of three things:
+ *
+ * 1. array/4 of {x:..., y:..., z:...}, z optional
+ * 2. numerical array/8 ordered x1,y1,x2,y2,x3,y3,x4,y4
+ * 3. numerical array/12 ordered x1,y1,z1,x2,y2,z2,x3,y3,z3,x4,y4,z4
+ *
+ */
+ class Bezier {
+ clockwise: boolean;
+ private _linear;
+ _3d: boolean;
+ _t1: number;
+ _t2: number;
+ _lut: Point[];
+ dpoints: Point[][];
+ order: number;
+ points: Point[];
+ dims: string[];
+ dimlen: number;
+ constructor(points: Point[]);
+ constructor(coords: number[]);
+ constructor(n1: number, n2: number, n3: number, n4: number, n5: number, n6: number, n7: number, n8: number);
+ constructor(p1: Point, p2: Point, p3: Point, p4?: Point);
+ static fromSVG(svgString: string): Bezier;
+ static getABC(n: number, S: Point, B: Point, E: Point, t: number): ABC;
+ static quadraticFromPoints(p1: Point, p2: Point, p3: Point, t: number): Bezier;
+ static cubicFromPoints(S: Point, B: Point, E: Point, t: number, d1: number): Bezier;
+ static getUtils(): typeof utils;
+ getUtils(): typeof utils;
+ valueOf(): string;
+ toString(): string;
+ toSVG(): string;
+ update(): void;
+ computedirection(): void;
+ length(): number;
+ getLUT(steps?: number): Point[];
+ on(point: Point, error: number): number;
+ project(point: Point): Projection;
+ get(t: number): Point;
+ point(idx: number): Point;
+ compute(t: number): Point;
+ raise(): Bezier;
+ derivative(t: number): Point;
+ inflections(): number[];
+ normal(t: number): Point;
+ private __normal2(t);
+ private __normal3(t);
+ private __normal(t);
+ hull(t: number): Point[];
+ split(t1: number, t2?: number): Bezier | Split;
+ extrema(): Inflection;
+ bbox(): BBox;
+ overlaps(curve: Bezier): boolean;
+ offset(t: number, d?: number): Offset | Bezier[];
+ simple(): boolean;
+ reduce(): any[];
+ scale(d: Function): Bezier;
+ scale(d: number): Bezier;
+ outline(d1: number, d2?: number, d3?: number, d4?: number): PolyBezier;
+ outlineshapes(d1: number, d2: number): Shape[];
+ intersects(curve: Bezier): string[] | number[];
+ intersects(curve: Line): string[] | number[];
+ lineIntersects(line: Line): number[];
+ selfintersects(): string[];
+ curveintersects(c1: Bezier[], c2: Bezier[]): string[];
+ arcs(errorThreshold?: number): Arc[];
+ private _error(pc, np1, s, e);
+ private _iterate(errorThreshold, circles);
+ }
+ class BezierCap extends Bezier {
+ virtual: boolean;
+ }
+}
+declare module BezierJs.utils {
+ var Tvalues: number[];
+ var Cvalues: number[];
+ function arcfn(t: number, derivativeFn: Function): number;
+ function between(v: number, m: number, M: number): boolean;
+ function approximately(a: number, b: number, precision?: number): boolean;
+ function length(derivativeFn: Function): number;
+ function map(v: number, ds: number, de: number, ts: number, te: number): number;
+ function lerp(r: number, v1: Point, v2: Point): Point;
+ function pointToString(p: Point): string;
+ function pointsToString(points: Point[]): string;
+ function copy(obj: Object): any;
+ function angle(o: Point, v1: Point, v2: Point): number;
+ function round(v: number, d: number): number;
+ function dist(p1: Point, p2: Point): number;
+ function closest(LUT: Point[], point: Point): Closest;
+ function abcratio(t: number, n: number): number;
+ function projectionratio(t: number, n: number): number;
+ function lli8(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): Point;
+ function lli4(p1: Point, p2: Point, p3: Point, p4: Point): Point;
+ function lli(v1: Offset, v2: Offset): Point;
+ function makeline(p1: Point, p2: Point): Bezier;
+ function findbbox(sections: Bezier[]): BBox;
+ function shapeintersections(s1: Shape, bbox1: BBox, s2: Shape, bbox2: BBox): string[][] | number[][];
+ function makeshape(forward: Bezier, back: Bezier): Shape;
+ function getminmax(curve: Bezier, d: string, list: number[]): MinMax;
+ function align(points: Point[], line: Line): Point[];
+ function roots(points: Point[], line: Line): number[];
+ function droots(p: number[]): number[];
+ function inflections(points: Point[]): number[];
+ function bboxoverlap(b1: BBox, b2: BBox): boolean;
+ function expandbox(bbox: BBox, _bbox: BBox): void;
+ function pairiteration(c1: Bezier, c2: Bezier): string[];
+ function getccenter(p1: Point, p2: Point, p3: Point): Arc;
+}
+declare module BezierJs {
+ /**
+ * Poly Bezier
+ * @param {[type]} curves [description]
+ */
+ class PolyBezier {
+ curves: Bezier[];
+ private _3d;
+ points: Point[];
+ constructor(curves: Bezier[]);
+ valueOf(): string;
+ toString(): string;
+ addCurve(curve: Bezier): void;
+ length(): number;
+ curve(idx: number): Bezier;
+ bbox(): BBox;
+ offset(d: number): PolyBezier;
+ }
+}
diff --git a/bookshelf/bookshelf-tests.ts b/bookshelf/bookshelf-tests.ts
index 92758e143a..5d6080b99a 100644
--- a/bookshelf/bookshelf-tests.ts
+++ b/bookshelf/bookshelf-tests.ts
@@ -1,17 +1,52 @@
///
///
+///
+///
import * as Knex from 'knex';
import * as Bookshelf from 'bookshelf';
+import * as assert from 'assert';
+import * as express from 'express';
+
+
+/**
+ * The examples/tests below follow Bookshelf documentation chapter after chapter: http://bookshelfjs.org/
+ */
+
+
+/* Installation, see http://bookshelfjs.org/#installation */
var knex = Knex({
- client: 'sqlite3',
+ client: 'mysql',
connection: {
- filename: ':memory:',
- },
+ host : '127.0.0.1',
+ user : 'your_database_user',
+ password : 'your_database_password',
+ database : 'myapp_test',
+ charset : 'utf8'
+ }
});
-// Examples
+var bookshelf = Bookshelf(knex);
+
+{
+ class User extends bookshelf.Model {
+ get tableName() { return 'users'; }
+ }
+
+ // In a file named something like bookshelf.js
+ const dbConfig: Knex.Config = {};
+ var knex = Knex(dbConfig);
+
+ // elsewhere, to use the bookshelf client:
+ var bookshelf = Bookshelf(knex);
+
+ class Post extends bookshelf.Model {
+ // ...
+ }
+}
+
+/* Examples, see http://bookshelfjs.org/#examples */
var bookshelf = Bookshelf(knex);
@@ -20,14 +55,14 @@ bookshelf.plugin(['virtuals']);
class User extends bookshelf.Model {
get tableName() { return 'users'; }
- messages() : Bookshelf.Collection {
- return this.hasMany(Posts);
+ messages(): Bookshelf.Collection {
+ return this.hasMany(Post);
}
}
-class Posts extends bookshelf.Model {
+class Post extends bookshelf.Model {
get tableName() { return 'messages'; }
- tags() : Bookshelf.Collection {
+ tags(): Bookshelf.Collection {
return this.belongsToMany(Tag);
}
}
@@ -36,67 +71,1256 @@ class Tag extends bookshelf.Model {
get tableName() { return 'tags'; }
}
-new User({}).where('id', 1).fetch({withRelated: ['posts.tags']})
+new User().where('id', 1).fetch({withRelated: ['posts.tags']})
.then(user => {
- console.log(user.related('posts').toJSON());
+ const posts = user.related('posts');
+ console.log(posts.toJSON());
}).catch(err => {
console.error(err);
});
+/* Plugins, see http://bookshelfjs.org/#plugins */
-// Associations
+/* Support, see http://bookshelfjs.org/#support */
+
+/* F.A.Q., see http://bookshelfjs.org/#faq*/
+
+/* Associations, see http://bookshelfjs.org/#associations */
+
+/* One-to-one, see http://bookshelfjs.org/#one-to-one */
class Book extends bookshelf.Model {
get tableName() { return 'books'; }
- summary() {
+ summary(): Summary {
return this.hasOne(Summary);
}
- pages() {
- return this.hasMany(Pages);
+ pages(): Bookshelf.Collection {
+ return this.hasMany(Page);
}
- authors() {
+ authors(): Bookshelf.Collection {
return this.belongsToMany(Author);
}
}
class Summary extends bookshelf.Model {
get tableName() { return 'summaries'; }
- book() : Book {
+ book(): Book {
return this.belongsTo(Book);
}
}
-class Pages extends bookshelf.Model {
+exports.up = (knex: Knex) => {
+ return knex.schema.createTable('books', table => {
+ table.increments('id').primary();
+ table.string('name');
+ }).createTable('summaries', table => {
+ table.increments('id').primary();
+ table.string('details');
+ table.integer('book_id').unique().references('books.id');
+ });
+};
+
+exports.down = (knex: Knex) => {
+ return knex.schema.dropTable('books')
+ .dropTable('summaries');
+};
+
+/* One-to-many, see http://bookshelfjs.org/#one-to-many */
+
+class Page extends bookshelf.Model {
get tableName() { return 'pages'; }
- book() {
+ book(): Book {
return this.belongsTo(Book);
}
}
+exports.up = (knex: Knex) => {
+ return knex.schema.createTable('books', table => {
+ table.increments('id').primary();
+ table.string('name');
+ }).createTable('pages', table => {
+ table.increments('id').primary();
+ table.string('content');
+ table.integer('book_id').references('books.id')
+ });
+};
+
+exports.down = (knex: Knex) => {
+ return knex.schema.dropTable('books')
+ .dropTable('pages');
+};
+
+/* Many-to-many, see http://bookshelfjs.org/#many-to-many */
+
class Author extends bookshelf.Model {
- get tableName() { return 'author'; }
+ get tableName() { return 'authors'; }
books() {
return this.belongsToMany(Book);
}
}
-class Site extends bookshelf.Model {
- get tableName() { return 'sites'; }
- photo() {
- return this.morphOne(Photo, 'imageable');
+exports.up = (knex: Knex) => {
+ return knex.schema.createTable('books', table => {
+ table.increments('id').primary();
+ table.string('name');
+ }).createTable('authors', table => {
+ table.increments('id').primary();
+ table.string('name');
+ }).createTable('authors_books', table => {
+ table.integer('author_id').references('authors.id');
+ table.integer('book_id').references('books.id');
+ });
+};
+
+exports.down = (knex: Knex) => {
+ return knex.schema.dropTable('books')
+ .dropTable('authors')
+ .dropTable('authors_books');
+};
+
+/* Polymorphic, see http://bookshelfjs.org/#polymorphic */
+
+{
+ class Site extends bookshelf.Model {
+ get tableName() { return 'sites'; }
+ photo(): Photo {
+ return this.morphOne(Photo, 'imageable');
+ }
+ }
+
+ class Post extends bookshelf.Model {
+ get tableName() { return 'posts'; }
+ photos(): Bookshelf.Collection {
+ return this.morphMany(Photo, 'imageable');
+ }
+ }
+
+ class Photo extends bookshelf.Model {
+ get tableName() { return 'photos'; }
+ imageable(): Photo {
+ return this.morphTo('imageable', Site, Post);
+ }
}
}
-class Post extends bookshelf.Model {
- get tableName() { return 'posts'; }
- photos() {
- return this.morphMany(Photo, 'imageable');
+/* Bookshelf, see http://bookshelfjs.org/#section-Bookshelf */
+
+/* Construction, see http://bookshelfjs.org/#Bookshelf-subsection-construction */
+
+/* new Bookshelf(), see http://bookshelfjs.org/#Bookshelf */
+
+/* Members, see http://bookshelfjs.org/#Bookshelf-subsection-members */
+
+/* bookshelf.knex, see http://bookshelfjs.org/#Bookshelf-instance-knex */
+
+/* Methods, see http://bookshelfjs.org/#Bookshelf-subsection-methods */
+
+/* bookshelf.transaction(), see http://bookshelfjs.org/#Bookshelf-instance-transaction */
+
+class Library extends bookshelf.Model {
+ get tableName() { return 'libraries'; }
+
+ relatedBooks(): Bookshelf.Collection {
+ return > this.related('books');
}
}
-class Photo extends bookshelf.Model {
- get tableName() { return 'photos'; }
- imageable() {
- return this.morphTo('imageable', Site, Post);
+bookshelf.transaction(t => {
+ return new Library({name: 'Old Books'})
+ .save(null, {transacting: t})
+ .tap(model => {
+ return Promise.map([
+ {title: 'Canterbury Tales'},
+ {title: 'Moby Dick'},
+ {title: 'Hamlet'}
+ ], info => {
+ // Some validation could take place here.
+ return new Book(info).save({'shelf_id': model.id}, {transacting: t});
+ });
+ });
+}).then(library => {
+ console.log(library.relatedBooks().pluck('title'));
+}).catch(err => {
+ console.error(err);
+});
+
+/* Type definitions */
+
+/* transactionCallback(), see http://bookshelfjs.org/#Bookshelf~transactionCallback */
+
+/* Model, see http://bookshelfjs.org/#section-Model */
+
+/* Construction, see http://bookshelfjs.org/#Model-subsection-construction */
+
+/* new Model(), see http://bookshelfjs.org/#Model */
+
+{
+ new Book({
+ title: "One Thousand and One Nights",
+ author: "Scheherazade"
+ });
+
+ class Book extends bookshelf.Model {
+ get tableName() { return 'documents'; }
+
+ constructor(json: Object) {
+ super(json);
+
+ this.on('saving', (model, attrs, options) => {
+ options.query.where('type', '=', 'book');
+ });
+ }
}
}
+
+/* model.initialize(), see http://bookshelfjs.org/#Model-instance-initialize */
+
+/* Static, see http://bookshelfjs.org/#Model-subsection-static */
+
+/* Model.collection(), see http://bookshelfjs.org/#Model-static-collection */
+
+class Customer extends bookshelf.Model {
+ get tableName() { return 'customers'; }
+}
+Customer.collection().fetch().then(collection => {
+ // ...
+});
+
+/* Model.count(), see http://bookshelfjs.org/#Model-static-count */
+
+/* Model.extend(), see http://bookshelfjs.org/#Model-static-extend */
+
+class Account extends bookshelf.Model {
+ get tableName() { return 'accounts'; }
+}
+{
+ var checkit = require('checkit');
+ var bcrypt = Promise.promisifyAll(require('bcrypt'));
+
+ class Customer extends bookshelf.Model {
+ get tableName() { return 'customers'; }
+
+ initialize() {
+ this.on('saving', this.validateSave);
+ }
+
+ validateSave() {
+ let rules: any;
+ return checkit(rules).run(this.attributes);
+ }
+
+ account() {
+ return this.belongsTo(Account);
+ }
+
+ static login(email: string, password: string): Promise {
+ if (!email || !password) throw new Error('Email and password are both required');
+ return new this({email: email.toLowerCase().trim()}).fetch({require: true}).tap(customer => {
+ return bcrypt.compareAsync(password, customer.get('password'))
+ .then((res: boolean) => {
+ if (!res) throw new Error('Invalid password');
+ });
+ });
+ }
+ }
+
+ const email = 'email';
+ const password = 'password';
+ Customer.login(email, password)
+ .then(customer => {
+ console.log(customer.omit('password'));
+ }).catch(Customer.NotFoundError, () => {
+ console.log({error: email + ' not found'});
+ }).catch(err => {
+ console.error(err);
+ });
+}
+
+/* Model.fetchAll(), see http://bookshelfjs.org/#Model-static-fetchAll */
+
+/* Model.forge(), see http://bookshelfjs.org/#Model-static-forge */
+
+/* Members, see http://bookshelfjs.org/#Model-subsection-members */
+
+/* model.hasTimestamps, see http://bookshelfjs.org/#Model-instance-hasTimestamps */
+
+/* model.idAttribute, see http://bookshelfjs.org/#Model-instance-idAttribute */
+
+/* model.tableName, see http://bookshelfjs.org/#Model-instance-tableName */
+
+class Television extends bookshelf.Model {
+ get tableName() { return 'televisions'; }
+}
+
+/* Methods, see http://bookshelfjs.org/#Model-subsection-methods */
+
+/* model.belongsTo(), see http://bookshelfjs.org/#Model-instance-belongsTo */
+
+{
+ class Book extends bookshelf.Model {
+ get tableName() { return 'books'; }
+ author(): Author {
+ return this.belongsTo(Author);
+ }
+ }
+
+ // select * from `books` where id = 1
+ // select * from `authors` where id = book.author_id
+ new Book().where({id: 1}).fetch({withRelated: ['author']}).then(book => {
+ console.log(JSON.stringify(book.related('author')));
+ });
+}
+
+/* model.belongsToMany(), see http://bookshelfjs.org/#Model-instance-belongsToMany */
+
+{
+ class Account extends bookshelf.Model {
+ get tableName() { return 'accounts'; }
+ }
+
+ class User extends bookshelf.Model {
+ get tableName() { return 'users'; }
+ allAccounts() {
+ return this.belongsToMany(Account);
+ }
+ adminAccounts() {
+ return this.belongsToMany(Account).query({where: {access: 'admin'}});
+ }
+ viewAccounts() {
+ return this.belongsToMany(Account).query({where: {access: 'readonly'}});
+ }
+ }
+
+ class Doctor extends bookshelf.Model {
+ patients(): Bookshelf.Collection {
+ return this.belongsToMany(Patient).through(Appointment);
+ }
+ }
+
+ class Appointment extends bookshelf.Model {
+ patient(): Patient {
+ return this.belongsTo(Patient);
+ }
+ doctor(): Doctor {
+ return this.belongsTo(Doctor);
+ }
+ }
+
+ class Patient extends bookshelf.Model {
+ doctors(): Bookshelf.Collection {
+ return this.belongsToMany(Doctor).through(Appointment);
+ }
+ }
+}
+
+/* model.clear(), see http://bookshelfjs.org/#Model-instance-clear */
+
+/* model.clone(), see http://bookshelfjs.org/#Model-instance-clone */
+
+/* model.count(), see http://bookshelfjs.org/#Model-instance-count */
+
+class Duck extends bookshelf.Model {
+}
+new Duck().where('color', 'blue').count('name')
+ .then(count => {
+ //...
+ });
+
+/* model.destroy(), see http://bookshelfjs.org/#Model-instance-destroy */
+new User({id: 1})
+ .destroy()
+ .then(model => {
+ // ...
+ });
+
+/* model.escape(), see http://bookshelfjs.org/#Model-instance-escape */
+
+/* model.fetch(), see http://bookshelfjs.org/#Model-instance-fetch */
+
+// select * from `books` where `ISBN-13` = '9780440180296'
+new Book({'ISBN-13': '9780440180296'})
+ .fetch()
+ .then(model => {
+ // outputs 'Slaughterhouse Five'
+ console.log(model.get('title'));
+ });
+{
+ class Edition extends bookshelf.Model {}
+ class Chapter extends bookshelf.Model {}
+ class Genre extends bookshelf.Model {}
+
+ class Book extends bookshelf.Model {
+ get tableName() { return 'books'; }
+ editions() {
+ return this.hasMany(Edition);
+ }
+ chapters() {
+ return this.hasMany(Chapter);
+ }
+ genre() {
+ return this.belongsTo(Genre);
+ }
+ }
+
+ new Book({'ISBN-13': '9780440180296'}).fetch({
+ withRelated: [
+ 'genre', 'editions',
+ { chapters: query => query.orderBy('chapter_number') }
+ ]
+ }).then(book => {
+ console.log(book.related('genre').toJSON());
+ console.log(book.related('editions').toJSON());
+ console.log(book.toJSON());
+ });
+}
+
+/* model.fetchAll(), see http://bookshelfjs.org/#Model-instance-fetchAll */
+
+/* model.format(), see http://bookshelfjs.org/#Model-instance-format */
+
+/* model.get(), see http://bookshelfjs.org/#Model-instance-get */
+const note = new bookshelf.Model();
+note.get("title");
+
+/* model.has(), see http://bookshelfjs.org/#Model-instance-has */
+
+/* model.hasChanged(), see http://bookshelfjs.org/#Model-instance-hasChanged */
+
+/* model.hasMany(), see http://bookshelfjs.org/#Model-instance-hasMany */
+
+{
+ class Author extends bookshelf.Model {
+ get tableName() { return 'authors'; }
+
+ books() {
+ return this.hasMany(Book);
+ }
+ }
+
+ // select * from `authors` where id = 1
+ // select * from `books` where author_id = 1
+ new Author().where({id: 1}).fetch({withRelated: ['books']}).then(author => {
+ console.log(JSON.stringify(author.related('books')));
+ });
+}
+
+/* model.hasOne(), see http://bookshelfjs.org/#Model-instance-hasOne */
+
+{
+ class Record extends bookshelf.Model {
+ get tableName() { return 'health_records'; }
+ }
+
+ class Patient extends bookshelf.Model {
+ get tableName() { return 'patients'; }
+ record(): Record {
+ return this.hasOne(Record);
+ }
+ }
+
+ // select * from `health_records` where `patient_id` = 1;
+ const record = new Patient({id: 1}).related('record');
+ record.fetch().then(model => {
+ // ...
+ });
+
+ // alternatively, if you don't need the relation loaded on the patient's relations hash:
+ new Patient({id: 1}).record().fetch().then(model => {
+ // ...
+ });
+}
+
+/* model.isNew(), see http://bookshelfjs.org/#Model-instance-isNew */
+
+var modelA = new bookshelf.Model();
+modelA.isNew(); // true
+
+var modelB = new bookshelf.Model({id: 1});
+modelB.isNew(); // false
+
+/* model.load(), see http://bookshelfjs.org/#Model-instance-load */
+class Posts extends bookshelf.Collection {}
+new Posts().fetch().then(collection => {
+ collection.at(0)
+ .load(['author', 'content', 'comments.tags'])
+ .then(model => {
+ JSON.stringify(model);
+ });
+});
+/*
+{
+ title: 'post title',
+ author: {...},
+ content: {...},
+ comments: [
+ {tags: [...]}, {tags: [...]}
+ ]
+}
+*/
+
+/* model.morphMany(), see http://bookshelfjs.org/#Model-instance-morphMany */
+
+class Photo extends bookshelf.Model {}
+{
+ class Post extends bookshelf.Model {
+ get tableName() { return 'posts'; }
+ photos() {
+ return this.morphMany(Photo, 'imageable');
+ }
+ }
+}
+{
+ class Post extends bookshelf.Model {
+ get tableName() { return 'posts'; }
+ photos() {
+ return this.morphMany(Photo, 'imageable', ["ImageableType", "ImageableId"]);
+ }
+ }
+}
+
+/* model.morphOne(), see http://bookshelfjs.org/#Model-instance-morphOne */
+
+{
+ class Site extends bookshelf.Model {
+ get tableName() { return 'sites'; }
+ photo() {
+ return this.morphOne(Photo, 'imageable');
+ }
+ }
+}
+{
+ class Site extends bookshelf.Model {
+ get tableName() { return 'sites'; }
+ photo() {
+ return this.morphOne(Photo, 'imageable', ["ImageableType", "ImageableId"]);
+ }
+ }
+}
+
+/* model.morphTo(), see http://bookshelfjs.org/#Model-instance-morphTo */
+
+class Site extends bookshelf.Model {}
+{
+ class Photo extends bookshelf.Model {
+ get tableName() { return 'photos'; }
+ imageable() {
+ return this.morphTo('imageable', Site, Post);
+ }
+ }
+}
+{
+ class Photo extends bookshelf.Model {
+ get tableName() { return 'photos'; }
+ imageable() {
+ return this.morphTo('imageable', ["ImageableType", "ImageableId"], Site, Post);
+ }
+ }
+}
+
+/* model.off(), see http://bookshelfjs.org/#Model-instance-off */
+
+const customer = new Customer();
+const ship = new bookshelf.Model();
+customer.off('fetched fetching');
+ship.off(); // This will remove all event listeners
+
+/* model.on(), see http://bookshelfjs.org/#Model-instance-on */
+
+customer.on('fetching', (model, columns) => {
+ // Do something before the data is fetched from the database
+});
+
+/* model.once(), see http://bookshelfjs.org/#Model-instance-once */
+
+/* model.parse(), see http://bookshelfjs.org/#Model-instance-parse */
+
+// Example of a "parse" to convert snake_case to camelCase, using `underscore.string`
+customer.parse = attrs => {
+ return _.reduce(<_.Dictionary> attrs, (memo, val, key) => {
+ (<_.Dictionary> memo)[_.camelCase(key)] = val;
+ return memo;
+ }, {});
+};
+
+/* model.previous(), see http://bookshelfjs.org/#Model-instance-previous */
+
+/* model.previousAttributes(), see http://bookshelfjs.org/#Model-instance-previousAttributes */
+
+/* model.query(), see http://bookshelfjs.org/#Model-instance-query */
+
+const model = new bookshelf.Model();
+model
+ .query('where', 'other_id', '=', '5')
+ .fetch()
+ .then(model => {
+ // ...
+ });
+
+model
+ .query({where: {other_id: '5'}, orWhere: {key: 'value'}})
+ .fetch()
+ .then(model => {
+ // ...
+ });
+
+model.query(qb => {
+ qb.where('other_person', 'LIKE', '%Demo').orWhere('other_id', '>', 10);
+}).fetch()
+ .then(model => {
+ // ...
+ });
+
+let qb = model.query();
+qb.where({id: 1}).select().then(resp => {
+ // ...
+});
+
+/* model.refresh(), see http://bookshelfjs.org/#Model-instance-refresh */
+
+/* model.related(), see http://bookshelfjs.org/#Model-instance-related */
+class Trip extends bookshelf.Model {}
+class Trips extends bookshelf.Collection {}
+new Photo({id: 1}).fetch({
+ withRelated: ['account']
+}).then(photo => {
+ if (photo) {
+ var account = photo.related('account');
+ if (account.id) {
+ return ( account.related('trips')).fetch();
+ }
+ }
+});
+
+/* model.resetQuery(), see http://bookshelfjs.org/#Model-instance-resetQuery */
+
+/* model.save(), see http://bookshelfjs.org/#Model-instance-save */
+
+new Post({name: 'New Article'}).save().then(model => {
+ // ...
+});
+// update authors set "bio" = 'Short user bio' where "id" = 1
+new Author({id: 1, first_name: 'User'})
+ .save({bio: 'Short user bio'}, {patch: true})
+ .then(model => {
+ // ...
+ });
+
+// Save with no arguments
+bookshelf.Model.forge({id: 5, firstName: "John", lastName: "Smith"}).save().then(() => {
+ //...
+});
+
+// Or add attributes during save
+bookshelf.Model.forge({id: 5}).save({firstName: "John", lastName: "Smith"}).then(() => {
+ //...
+});
+
+// Or, if you prefer, for a single attribute
+bookshelf.Model.forge({id: 5}).save('name', 'John Smith').then(() => {
+ //...
+});
+
+/* model.serialize(), see http://bookshelfjs.org/#Model-instance-serialize */
+
+var artist = new bookshelf.Model({
+ firstName: "Wassily",
+ lastName: "Kandinsky"
+});
+
+artist.set({birthday: "December 16, 1866"});
+
+console.log(JSON.stringify(artist));
+// {firstName: "Wassily", lastName: "Kandinsky", birthday: "December 16, 1866"}
+
+/* model.set(), see http://bookshelfjs.org/#Model-instance-set */
+
+customer.set({first_name: "Joe", last_name: "Customer"});
+customer.set("telephone", "555-555-1212");
+
+/* model.through(), see http://bookshelfjs.org/#Model-instance-through */
+
+{
+ class Book extends bookshelf.Model {
+ get tableName() { return 'books'; }
+
+ // Find all paragraphs associated with this book, by
+ // passing through the "Chapter" model.
+ paragraphs(): Paragraphs {
+ return this.hasMany(Paragraph).through(Chapter);
+ }
+
+ chapters(): Chapters {
+ return this.hasMany(Chapter);
+ }
+ }
+
+ class Chapter extends bookshelf.Model {
+ get tableName() { return 'chapters'; }
+
+ paragraphs(): Bookshelf.Collection {
+ return this.hasMany(Paragraph);
+ }
+ }
+
+ class Chapters extends bookshelf.Collection {
+ }
+
+ class Paragraph extends bookshelf.Model {
+ get tableName() { return 'paragraphs'; }
+
+ chapter(): Chapter {
+ return this.belongsTo(Chapter);
+ }
+
+ // A reverse relation, where we can get the book from the chapter.
+ book(): Book {
+ return this.belongsTo(Book).through(Chapter);
+ }
+ }
+
+ class Paragraphs extends bookshelf.Collection {
+ }
+}
+
+/* model.timestamp(), see http://bookshelfjs.org/#Model-instance-timestamp */
+
+/* model.toJSON(), see http://bookshelfjs.org/#Model-instance-toJSON */
+
+// TODO No example provided on Bookshelf website
+
+{
+ interface UserJson {
+ name: string;
+ }
+
+ class User extends bookshelf.Model {
+ get tableName() { return 'users'; }
+
+ toJSON(): UserJson {
+ return super.toJSON();
+ }
+
+ fetchAll(): Promise {
+ return super.fetchAll();
+ }
+ }
+
+ class Users extends bookshelf.Collection {
+ toJSON(): UserJson[] {
+ return super.toJSON();
+ }
+ }
+
+ new User({id: 1}).fetch().then(user => {
+ const userJson = user.toJSON();
+ console.log('User name:', userJson.name);
+ });
+
+ new User({name: 'John'}).fetchAll().then(users => {
+ const usersJson = users.toJSON();
+ console.log('First user name:', usersJson[0].name);
+ });
+}
+
+/* model.trigger(), see http://bookshelfjs.org/#Model-instance-trigger */
+
+ship.trigger('fetched');
+
+/* model.triggerThen(), see http://bookshelfjs.org/#Model-instance-triggerThen */
+
+/* model.unset(), see http://bookshelfjs.org/#Model-instance-unset */
+
+/* model.where(), see http://bookshelfjs.org/#Model-instance-where */
+
+model.where('favorite_color', '<>', 'green').fetch().then(() => {
+ //...
+});
+// or
+model.where('favorite_color', 'red').fetch().then(() => {
+ //...
+});
+// or
+model.where({favorite_color: 'red', shoe_size: 12}).fetch().then(() => {
+ //...
+});
+
+/* Lodash methods, see http://bookshelfjs.org/#Model-subsection-lodash-methods */
+
+/* invert(), see http://lodash.com/docs/#invert */
+
+/* keys(), see http://lodash.com/docs/#keys */
+
+/* omit(), see http://lodash.com/docs/#omit */
+
+/* pairs(), see http://lodash.com/docs/#pairs */
+
+/* pick(), see http://lodash.com/docs/#pick */
+
+/* values(), see http://lodash.com/docs/#values */
+
+/* Events, see http://bookshelfjs.org/#Model-subsection-events */
+
+/* model.on("created"), see http://bookshelfjs.org/#Model-event-created */
+
+/* model.on("creating"), see http://bookshelfjs.org/#Model-event-creating */
+
+/* model.on("destroyed"), see http://bookshelfjs.org/#Model-event-destroyed */
+
+/* model.on("destroying"), see http://bookshelfjs.org/#Model-event-destroying */
+
+/* model.on("fetched"), see http://bookshelfjs.org/#Model-event-fetched */
+
+/* model.on("fetching"), see http://bookshelfjs.org/#Model-event-fetching */
+
+/* model.on("saved"), see http://bookshelfjs.org/#Model-event-saved */
+
+/* model.on("saving"), see http://bookshelfjs.org/#Model-event-saving */
+
+/* model.on("updated"), see http://bookshelfjs.org/#Model-event-updated */
+
+/* model.on("updating"), see http://bookshelfjs.org/#Model-event-updating */
+
+/* new Model.NoRowsDeletedError(), see http://bookshelfjs.org/#Model-static-NoRowsDeletedError */
+
+// TODO No example provided on Bookshelf website
+
+new User({id: 1}).destroy({require: true})
+.then(user => {
+ console.log(user.toJSON());
+})
+.catch(User.NoRowsDeletedError, () => {
+ console.log('User not found');
+})
+.catch(error => {
+ console.log('Internal error:', error);
+});
+
+/* new Model.NoRowsUpdatedError(), see http://bookshelfjs.org/#Model-static-NoRowsUpdatedError */
+
+// TODO No example provided on Bookshelf website
+
+new User({id: 1}).save({}, {patch: true, require: true})
+.then(user => {
+ console.log(user.toJSON());
+})
+.catch(User.NoRowsUpdatedError, () => {
+ console.log('User not updated');
+})
+.catch(error => {
+ console.log('Internal error:', error);
+});
+
+/* new Model.NotFoundError(), see http://bookshelfjs.org/#Model-static-NotFoundError */
+
+// TODO No example provided on Bookshelf website
+
+new User({id: 1}).fetch({require: true})
+.then(user => {
+ console.log(user.toJSON());
+})
+.catch(User.NotFoundError, () => {
+ console.log('User not found');
+})
+.catch(error => {
+ console.log('Internal error:', error);
+});
+
+/* Collection, see http://bookshelfjs.org/#section-Collection */
+
+/* Construction, see http://bookshelfjs.org/#Collection-subsection-construction */
+
+/* new Collection(), see http://bookshelfjs.org/#Collection */
+
+class Tab extends bookshelf.Model {
+}
+const tab1 = new Tab();
+const tab2 = new Tab();
+const tab3 = new Tab();
+class TabSet extends bookshelf.Collection {
+}
+let tabs = new TabSet([tab1, tab2, tab3]);
+
+/* collection.initialize(), see http://bookshelfjs.org/#Collection-instance-initialize */
+
+/* Static, see http://bookshelfjs.org/#Collection-subsection-static */
+
+/* Collection.extend(), see http://bookshelfjs.org/#Collection-static-extend */
+
+/* Collection.forge(), see http://bookshelfjs.org/#Collection-static-forge */
+
+class Accounts extends bookshelf.Collection {
+ model: Account
+}
+
+var accounts = Accounts.forge([
+ {name: 'Person1'},
+ {name: 'Person2'}
+]);
+
+Promise.all(accounts.invoke('save')).then(() => {
+ // collection models should now be saved...
+});
+
+/* Methods, see http://bookshelfjs.org/#Collection-subsection-methods */
+
+/* collection.add(), see http://bookshelfjs.org/#Collection-instance-add */
+
+const ships = new bookshelf.Collection;
+
+ships.add([
+ {name: "Flying Dutchman"},
+ {name: "Black Pearl"}
+]);
+
+/* collection.at(), see http://bookshelfjs.org/#Collection-instance-at */
+
+/* collection.attach(), see http://bookshelfjs.org/#Collection-instance-attach */
+
+{
+ class Admin extends bookshelf.Model {
+ }
+ class Site extends bookshelf.Model {
+ admins() {
+ return this.hasMany(Admin);
+ }
+ }
+ var admin1 = new Admin({username: 'user1', password: 'test'});
+ var admin2 = new Admin({username: 'user2', password: 'test'});
+
+ Promise.all([admin1.save(), admin2.save()])
+ .then(() => {
+ return Promise.all([
+ new Site({id: 1}).admins().attach([admin1, admin2]),
+ new Site({id: 2}).admins().attach(admin2)
+ ]);
+ });
+}
+
+/* collection.clone(), see http://bookshelfjs.org/#Collection-instance-clone */
+
+/* collection.count(), see http://bookshelfjs.org/#Collection-instance-count */
+
+class Shareholder extends bookshelf.Model {}
+class Company extends bookshelf.Model {
+ shareholders() {
+ return this.hasMany(Shareholder);
+ }
+}
+
+// select count(*) from shareholders where company_id = 1 and share > 0.1;
+Company.forge({id:1})
+ .shareholders()
+ .query('where', 'share', '>', '0.1')
+ .count()
+ .then(count => {
+ assert(count === 3);
+ });
+
+/* collection.create(), see http://bookshelfjs.org/#Collection-instance-create */
+
+class Student extends bookshelf.Model {}
+
+function get(req: express.Request, res: express.Response) {
+ // FIXME Support proposed ES Rest/Spread properties https://github.com/Microsoft/TypeScript/issues/2103
+ //const { courses, ...attributes } = req.body;
+ const { courses, attributes } = req.body;
+
+ Student.forge(attributes).save().tap(student =>
+ Promise.map(courses, course => (> student.related('courses')).create(course))
+ ).then(student =>
+ res.status(200).send(student)
+ ).catch(error =>
+ res.status(500).send(error.message)
+ );
+}
+
+/* collection.detach(), see http://bookshelfjs.org/#Collection-instance-detach */
+
+/* collection.fetch(), see http://bookshelfjs.org/#Collection-instance-fetch */
+
+/* collection.fetchOne(), see http://bookshelfjs.org/#Collection-instance-fetchOne */
+
+{
+ class Site extends bookshelf.Model {
+ authors() {
+ return this.hasMany(Author);
+ }
+ }
+
+ // select * from authors where site_id = 1 and id = 2 limit 1;
+ new Site({id: 1})
+ .authors()
+ .query({where: {id: 2}})
+ .fetchOne()
+ .then(model => {
+ // ...
+ });
+}
+
+/* collection.findWhere(), see http://bookshelfjs.org/#Collection-instance-findWhere */
+
+/* collection.get(), see http://bookshelfjs.org/#Collection-instance-get */
+
+const library = new bookshelf.Collection();
+const book = library.get(110);
+
+/* collection.invokeThen(), see http://bookshelfjs.org/#Collection-instance-invokeThen */
+
+const options = {};
+const collection = new bookshelf.Collection();
+collection.invokeThen('save', null, options).then(() => {
+ // ... all models in the collection have been saved
+});
+
+collection.invokeThen('destroy', options).then(() => {
+ // ... all models in the collection have been destroyed
+});
+
+/* collection.load(), see http://bookshelfjs.org/#Collection-instance-load */
+
+/* collection.off(), see http://bookshelfjs.org/#Collection-instance-off */
+
+ships.off('fetched') // Remove the 'fetched' event listener
+
+/* collection.on(), see http://bookshelfjs.org/#Collection-instance-on */
+
+ships.on('fetched', (collection, response) => {
+ // Do something after the data has been fetched from the database
+})
+
+/* collection.once(), see http://bookshelfjs.org/#Collection-instance-once */
+
+/* collection.parse(), see http://bookshelfjs.org/#Collection-instance-parse */
+
+/* collection.pluck(), see http://bookshelfjs.org/#Collection-instance-pluck */
+
+/* collection.pop(), see http://bookshelfjs.org/#Collection-instance-pop */
+
+/* collection.push(), see http://bookshelfjs.org/#Collection-instance-push */
+
+/* collection.query(), see http://bookshelfjs.org/#Collection-instance-query */
+
+{
+ let qb = collection.query();
+ qb.where({id: 1}).select().then(resp => {
+ // ...
+ });
+
+ collection.query(qb => {
+ qb.where('id', '>', 5).andWhere('first_name', '=', 'Test');
+ }).fetch()
+ .then(collection => {
+ // ...
+ });
+
+ collection
+ .query('where', 'other_id', '=', '5')
+ .fetch()
+ .then(collection => {
+ // ...
+ });
+}
+
+/* collection.reduceThen(), see http://bookshelfjs.org/#Collection-instance-reduceThen */
+
+/* collection.remove(), see http://bookshelfjs.org/#Collection-instance-remove */
+
+/* collection.reset(), see http://bookshelfjs.org/#Collection-instance-reset */
+
+/* collection.resetQuery(), see http://bookshelfjs.org/#Collection-instance-resetQuery */
+
+/* collection.serialize(), see http://bookshelfjs.org/#Collection-instance-serialize */
+
+/* collection.set(), see http://bookshelfjs.org/#Collection-instance-set */
+
+class BandMember extends bookshelf.Model {}
+const eddie = new BandMember();
+const alex = new BandMember();
+const stone = new BandMember();
+const roth = new BandMember();
+const hagar = new BandMember();
+var vanHalen = new bookshelf.Collection([eddie, alex, stone, roth]);
+vanHalen.set([eddie, alex, stone, hagar]);
+
+/* collection.shift(), see http://bookshelfjs.org/#Collection-instance-shift */
+
+/* collection.slice(), see http://bookshelfjs.org/#Collection-instance-slice */
+
+/* collection.through(), see http://bookshelfjs.org/#Collection-instance-through */
+
+/* collection.toJSON(), see http://bookshelfjs.org/#Collection-instance-toJSON */
+
+/* collection.trigger(), see http://bookshelfjs.org/#Collection-instance-trigger */
+
+ships.trigger('fetched');
+
+/* collection.triggerThen(), see http://bookshelfjs.org/#Collection-instance-triggerThen */
+
+/* collection.unshift(), see http://bookshelfjs.org/#Collection-instance-unshift */
+
+/* collection.updatePivot(), see http://bookshelfjs.org/#Collection-instance-updatePivot */
+
+/* collection.where(), see http://bookshelfjs.org/#Collection-instance-where */
+
+/* collection.withPivot(), see http://bookshelfjs.org/#Collection-instance-withPivot */
+
+{
+ class Comment extends bookshelf.Model {}
+ class Tag extends bookshelf.Model {
+ comments() {
+ return this.belongsToMany(Comment).withPivot(['created_at', 'order']);
+ }
+ }
+}
+
+/* Lodash methods, see http://bookshelfjs.org/#Collection-subsection-lodash-methods */
+
+/* all(), see http://lodash.com/docs/#all */
+
+/* any(), see http://lodash.com/docs/#any */
+
+/* chain(), see http://lodash.com/docs/#chain */
+
+/* collect(), see http://lodash.com/docs/#collect */
+
+/* contains(), see http://lodash.com/docs/#contains */
+
+/* countBy(), see http://lodash.com/docs/#countBy */
+
+/* detect(), see http://lodash.com/docs/#detect */
+
+/* difference(), see http://lodash.com/docs/#difference */
+
+/* drop(), see http://lodash.com/docs/#drop */
+
+/* each(), see http://lodash.com/docs/#each */
+
+/* every(), see http://lodash.com/docs/#every */
+
+/* filter(), see http://lodash.com/docs/#filter */
+
+/* find(), see http://lodash.com/docs/#find */
+
+/* first(), see http://lodash.com/docs/#first */
+
+/* foldl(), see http://lodash.com/docs/#foldl */
+
+/* foldr(), see http://lodash.com/docs/#foldr */
+
+/* forEach(), see http://lodash.com/docs/#forEach */
+
+/* groupBy(), see http://lodash.com/docs/#groupBy */
+
+/* head(), see http://lodash.com/docs/#head */
+
+/* include(), see http://lodash.com/docs/#include */
+
+/* indexOf(), see http://lodash.com/docs/#indexOf */
+
+/* initial(), see http://lodash.com/docs/#initial */
+
+/* inject(), see http://lodash.com/docs/#inject */
+
+/* invoke(), see http://lodash.com/docs/#invoke */
+
+/* isEmpty(), see http://lodash.com/docs/#isEmpty */
+
+/* last(), see http://lodash.com/docs/#last */
+
+/* lastIndexOf(), see http://lodash.com/docs/#lastIndexOf */
+
+/* map(), see http://lodash.com/docs/#map */
+
+// TODO No example provided on Bookshelf website
+
+{
+ class Author extends bookshelf.Model {
+ get tableName() { return 'author'; }
+ books() {
+ return this.belongsToMany(Book);
+ }
+ relatedBooks() {
+ return > this.related('books');
+ }
+ }
+ new Author({id: 1}).fetch({require: true, withRelated: ['books']})
+ .then(author => {
+ const books = author.relatedBooks();
+ const booksJson = books.map(book => book.toJSON());
+ });
+
+ class AuthorOutput {
+ constructor(bookJson: Object) {}
+ }
+
+ new Author({id: 1}).fetch({require: true, withRelated: ['books']})
+ .then(author => {
+ const books = author.relatedBooks();
+ const booksOutput = books.map(book => new AuthorOutput(book.toJSON()));
+ });
+}
+
+/* max(), see http://lodash.com/docs/#max */
+
+/* min(), see http://lodash.com/docs/#min */
+
+/* reduce(), see http://lodash.com/docs/#reduce */
+
+/* reduceRight(), see http://lodash.com/docs/#reduceRight */
+
+/* reject(), see http://lodash.com/docs/#reject */
+
+/* rest(), see http://lodash.com/docs/#rest */
+
+/* select(), see http://lodash.com/docs/#select */
+
+/* shuffle(), see http://lodash.com/docs/#shuffle */
+
+/* size(), see http://lodash.com/docs/#size */
+
+/* some(), see http://lodash.com/docs/#some */
+
+/* sortBy(), see http://lodash.com/docs/#sortBy */
+
+/* tail(), see http://lodash.com/docs/#tail */
+
+/* take(), see http://lodash.com/docs/#take */
+
+/* toArray(), see http://lodash.com/docs/#toArray */
+
+/* without(), see http://lodash.com/docs/#without */
+
+/* Events, see http://bookshelfjs.org/#Collection-subsection-events */
+
+/* collection.on("fetched"), see http://bookshelfjs.org/#Collection-event-fetched */
+
+/* new Collection.EmptyError(), see http://bookshelfjs.org/#Collection-static-EmptyError */
+
+// TODO No example provided on Bookshelf website
+
+class Users extends bookshelf.Collection {
+}
+new User({name: 'John'}).fetchAll({require: true})
+.then(users => {
+ console.log(users.toJSON());
+})
+.catch(Users.EmptyError, () => {
+ console.log('No user found');
+})
+.catch(error => {
+ console.log('Internal error:', error);
+});
+
+/* Events, see http://bookshelfjs.org/#section-Events */
+
+/* new Events(), see http://bookshelfjs.org/#Events */
+
+/* events.off(), see http://bookshelfjs.org/#Events-instance-off */
+
+/* events.on(), see http://bookshelfjs.org/#Events-instance-on */
+
+/* events.once(), see http://bookshelfjs.org/#Events-instance-once */
+
+/* events.trigger(), see http://bookshelfjs.org/#Events-instance-trigger */
+
+/* events.triggerThen(), see http://bookshelfjs.org/#Events-instance-triggerThen */
diff --git a/bookshelf/bookshelf.d.ts b/bookshelf/bookshelf.d.ts
index cf70220840..0ca3a1ebcd 100644
--- a/bookshelf/bookshelf.d.ts
+++ b/bookshelf/bookshelf.d.ts
@@ -6,23 +6,25 @@
///
///
///
+///
declare module 'bookshelf' {
- import knex = require('knex');
- import Promise = require('bluebird');
- import Lodash = require('lodash');
+ import * as Knex from 'knex';
+ import * as Promise from 'bluebird';
+ import * as Lodash from 'lodash';
+ import * as createError from 'create-error';
interface Bookshelf extends Bookshelf.Events {
VERSION : string;
- knex : knex;
+ knex : Knex;
Model : typeof Bookshelf.Model;
Collection : typeof Bookshelf.Collection;
plugin(name: string | string[] | Function, options?: any) : Bookshelf;
- transaction(callback : (transaction : knex.Transaction) => T) : Promise;
+ transaction(callback : (transaction : Knex.Transaction) => T) : T;
}
- function Bookshelf(knex : knex) : Bookshelf;
+ function Bookshelf(knex : Knex) : Bookshelf;
namespace Bookshelf {
abstract class Events {
@@ -44,6 +46,13 @@ declare module 'bookshelf' {
/** If overriding, must use a getter instead of a plain property. */
idAttribute : string;
+ // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L178
+ // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L213
+ id : any;
+
+ // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/model.js#L28
+ attributes : any;
+
constructor(attributes? : any, options? : ModelOptions);
clear() : T;
@@ -54,7 +63,7 @@ declare module 'bookshelf' {
has(attribute : string) : boolean;
hasChanged(attribute? : string) : boolean;
isNew() : boolean;
- parse(response : any) : any;
+ parse(response : Object) : Object;
previousAttributes() : any;
previous(attribute : string) : any;
related>(relation : string) : R | Collection;
@@ -88,7 +97,7 @@ declare module 'bookshelf' {
belongsTo>(target : {new(...args : any[]) : R}, foreignKey? : string) : R;
belongsToMany>(target : {new(...args : any[]) : R}, table? : string, foreignKey? : string, otherKey? : string) : Collection;
count(column? : string, options? : SyncOptions) : Promise;
- destroy(options? : SyncOptions) : Promise;
+ destroy(options? : DestroyOptions) : Promise;
fetch(options? : FetchOptions) : Promise;
fetchAll(options? : FetchAllOptions) : Promise>;
hasMany>(target : {new(...args : any[]) : R}, foreignKey? : string) : Collection;
@@ -98,20 +107,35 @@ declare module 'bookshelf' {
morphOne>(target : {new(...args : any[]) : R}, name? : string, columnNames? : string[], morphValue? : string) : R;
morphTo(name : string, columnNames? : string[], ...target : typeof Model[]) : T;
morphTo(name : string, ...target : typeof Model[]) : T;
+
+ // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[])
+ query() : Knex.QueryBuilder;
+ query(callback : (qb : Knex.QueryBuilder) => void) : T;
query(...query : string[]) : T;
query(query : {[key : string] : any}) : T;
- query(callback : (qb : knex.QueryBuilder) => void) : T;
- query() : knex.QueryBuilder;
+
refresh(options? : FetchOptions) : Promise;
resetQuery() : T;
- save(key? : string, val? : string, options? : SaveOptions) : Promise;
+ save(key? : string, val? : any, options? : SaveOptions) : Promise;
save(attrs? : {[key : string] : any}, options? : SaveOptions) : Promise;
- through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection;
+ through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R;
where(properties : {[key : string] : any}) : T;
where(key : string, operatorOrValue : string|number|boolean, valueIfOperator? : string|number|boolean) : T;
+
+ // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/errors.js
+ // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/model.js#L1280
+ static NotFoundError: createError.Error;
+ static NoRowsUpdatedError: createError.Error;
+ static NoRowsDeletedError: createError.Error;
}
abstract class CollectionBase> extends Events {
+ // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/collection.js#L573
+ length : number;
+
+ // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/base/collection.js#L21
+ constructor(models? : T[], options? : CollectionOptions);
+
add(models : T[]|{[key : string] : any}[], options? : CollectionAddOptions) : Collection;
at(index : number) : T;
clone() : Collection;
@@ -127,11 +151,11 @@ declare module 'bookshelf' {
remove(model : T, options? : EventOptions) : T;
remove(model : T[], options? : EventOptions) : T[];
reset(model : any[], options? : CollectionAddOptions) : T[];
- serialize(options? : SerializeOptions) : any;
+ serialize(options? : SerializeOptions) : any[];
set(models : T[]|{[key : string] : any}[], options? : CollectionSetOptions) : Collection;
shift(options? : EventOptions) : void;
slice(begin? : number, end? : number) : void;
- toJSON(options? : SerializeOptions) : any;
+ toJSON(options? : SerializeOptions) : any[];
unshift(model : any, options? : CollectionAddOptions) : void;
where(match : {[key : string] : any}, firstOnly : boolean) : T|Collection;
@@ -177,8 +201,13 @@ declare module 'bookshelf' {
keys() : string[];
last() : T;
lastIndexOf(value : any, fromIndex? : number) : number;
- map(predicate? : Lodash.ListIterator|Lodash.DictionaryIterator|string, thisArg? : any) : T[];
- map(predicate? : R) : T[];
+
+ // See https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1ec3d51/lodash/lodash-3.10.d.ts#L7119
+ // See https://github.com/Microsoft/TypeScript/blob/v1.8.10/lib/lib.core.es7.d.ts#L1122
+ map(predicate? : Lodash.ListIterator|string, thisArg? : any) : U[];
+ map(predicate? : Lodash.DictionaryIterator|string, thisArg? : any) : U[];
+ map(predicate? : string) : U[];
+
max(predicate? : Lodash.ListIterator|string, thisArg? : any) : T;
max(predicate? : R) : T;
min(predicate? : Lodash.ListIterator|string, thisArg? : any) : T;
@@ -208,20 +237,27 @@ declare module 'bookshelf' {
/** @deprecated should use `new` objects instead. */
static forge(attributes? : any, options? : ModelOptions) : T;
- attach(ids : any[], options? : SyncOptions) : Promise>;
+ attach(ids : any|any[], options? : SyncOptions) : Promise>;
count(column? : string, options? : SyncOptions) : Promise;
create(model : {[key : string] : any}, options? : CollectionCreateOptions) : Promise;
detach(ids : any[], options? : SyncOptions) : Promise;
+ detach(options? : SyncOptions) : Promise;
fetchOne(options? : CollectionFetchOneOptions) : Promise;
load(relations : string|string[], options? : SyncOptions) : Promise>;
+
+ // Declaration order matters otherwise TypeScript gets confused between query() and query(...query: string[])
+ query() : Knex.QueryBuilder;
+ query(callback : (qb : Knex.QueryBuilder) => void) : Collection;
query(...query : string[]) : Collection;
query(query : {[key : string] : any}) : Collection;
- query(callback : (qb : knex.QueryBuilder) => void) : Collection;
- query() : knex.QueryBuilder;
+
resetQuery() : Collection;
- through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : R | Collection;
+ through>(interim : typeof Model, throughForeignKey? : string, otherKey? : string) : Collection;
updatePivot(attributes : any, options? : PivotOptions) : Promise;
withPivot(columns : string[]) : Collection;
+
+ // See https://github.com/tgriesser/bookshelf/blob/0.9.4/src/collection.js#L389
+ static EmptyError: createError.Error;
}
interface ModelOptions {
@@ -231,13 +267,17 @@ declare module 'bookshelf' {
}
interface LoadOptions extends SyncOptions {
- withRelated: string|any|any[];
+ withRelated : (string|WithRelatedQuery)[];
}
interface FetchOptions extends SyncOptions {
require? : boolean;
columns? : string|string[];
- withRelated? : string|any|any[];
+ withRelated? : (string|WithRelatedQuery)[];
+ }
+
+ interface WithRelatedQuery {
+ [index : string] : (query : Knex.QueryBuilder) => Knex.QueryBuilder;
}
interface FetchAllOptions extends SyncOptions {
@@ -251,6 +291,10 @@ declare module 'bookshelf' {
require? : boolean;
}
+ interface DestroyOptions extends SyncOptions {
+ require? : boolean;
+ }
+
interface SerializeOptions {
shallow? : boolean;
omitPivot? : boolean;
@@ -265,7 +309,7 @@ declare module 'bookshelf' {
}
interface SyncOptions {
- transacting? : knex.Transaction;
+ transacting? : Knex.Transaction;
debug? : boolean;
}
diff --git a/browser-sync/browser-sync-tests.ts b/browser-sync/browser-sync-tests.ts
index 822c941d9f..72bcb6465e 100644
--- a/browser-sync/browser-sync-tests.ts
+++ b/browser-sync/browser-sync-tests.ts
@@ -1,5 +1,5 @@
///
-import browserSync = require("browser-sync");
+import * as browserSync from "browser-sync";
(() => {
//make sure that the interfaces are correctly exposed
diff --git a/browser-sync/browser-sync.d.ts b/browser-sync/browser-sync.d.ts
index 3bc083d1f1..00d234f958 100644
--- a/browser-sync/browser-sync.d.ts
+++ b/browser-sync/browser-sync.d.ts
@@ -8,10 +8,10 @@
///
declare module "browser-sync" {
- import chokidar = require("chokidar");
- import fs = require("fs");
- import http = require("http");
- import mm = require("micromatch");
+ import * as chokidar from "chokidar";
+ import * as fs from "fs";
+ import * as http from "http";
+ import * as mm from "micromatch";
namespace browserSync {
interface Options {
@@ -23,14 +23,14 @@ declare module "browser-sync" {
* weinre.port - Default: 8080
* Note: requires at least version 2.0.0
*/
- ui?: UIOptions;
+ ui?: UIOptions | boolean;
/**
* 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[];
+ files?: string | (string | FileCallback)[];
/**
* File watching options that get passed along to Chokidar. Check their docs for available options
* Default: undefined
@@ -245,7 +245,7 @@ declare module "browser-sync" {
* Note: requires at least version 1.6.2
*/
socket?: SocketOptions;
- middleware?: MiddlewareHandler | MiddlewareHandler[];
+ middleware?: MiddlewareHandler | PerRouteMiddleware | (MiddlewareHandler | PerRouteMiddleware)[];
}
interface Hash {
@@ -261,6 +261,12 @@ declare module "browser-sync" {
};
}
+ interface FileCallback {
+ match?: string | string[];
+ fn: (event: string, file: string) => any;
+ options?: chokidar.WatchOptions;
+ }
+
interface ServerOptions {
/** set base directory */
baseDir?: string | string[];
@@ -274,7 +280,7 @@ declare module "browser-sync" {
*/
routes?: Hash;
/** configure custom middleware */
- middleware?: MiddlewareHandler[];
+ middleware?: (MiddlewareHandler | PerRouteMiddleware)[];
}
interface ProxyOptions {
@@ -289,6 +295,11 @@ declare module "browser-sync" {
(req: http.ServerRequest, res: http.ServerResponse, next: Function): any;
}
+ interface PerRouteMiddleware {
+ route: string;
+ handle: MiddlewareHandler;
+ }
+
interface GhostOptions {
clicks?: boolean;
scroll?: boolean;
diff --git a/cachefactory/cachefactory-tests.ts b/cachefactory/cachefactory-tests.ts
new file mode 100644
index 0000000000..0c859e749d
--- /dev/null
+++ b/cachefactory/cachefactory-tests.ts
@@ -0,0 +1,34 @@
+///
+
+CacheFactory.get('test');
+
+CacheFactory.createCache('test', {
+ deleteOnExpire: 'aggressive',
+ recycleFreq: 60000
+});
+
+let testCache = CacheFactory.get('test');
+
+testCache.put('testOne', {title: 'testOne', id: 1});
+
+let item = testCache.get('testOne');
+
+
+let profileCache = CacheFactory('profileCache', {
+ maxAge: 60 * 60 * 1000,
+ deleteOnExpire: 'aggressive'
+});
+
+let localStoragePolyfill = {
+ getItem: (key: string) => { return ""; },
+ setItem: (key: string, value: string) => { },
+ removeItem: (key: string) => { }
+};
+
+let myAwesomeCache = CacheFactory('myAwesomeCache', {
+ maxAge: 15 * 60 * 1000,
+ cacheFlushInterval: 60 * 60 * 1000,
+ deleteOnExpire: 'aggressive',
+ storageMode: 'localStorage',
+ storageImpl: localStoragePolyfill
+});
\ No newline at end of file
diff --git a/cachefactory/cachefactory.d.ts b/cachefactory/cachefactory.d.ts
new file mode 100644
index 0000000000..ac416e6837
--- /dev/null
+++ b/cachefactory/cachefactory.d.ts
@@ -0,0 +1,443 @@
+// Type definitions for CacheFactory 1.4.0
+// Project: https://github.com/jmdobry/CacheFactory
+// Definitions by: Vaggelis Mparmpas , Daniel Massa
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare module CacheFactory {
+ export interface IStoreImplementation {
+ getItem(key: string): string;
+
+ setItem(key: string, value: string): void;
+
+ removeItem(key: string): void;
+ }
+
+ export interface CacheGetOptions {
+ /*
+ * A callback function to be executed whenever an expired item is removed from a cache when the cache is in passive
+ * or aggressive mode. Will be passed the key and value of the expired item.
+ *
+ * Will be passed a third done argument if the cache is in passive mode. This allows you to synchronously access the
+ * key and value of the expired item when you make the cache#get(key[, options]) call that is the reason the expired
+ * item is being removed in the first place. Default: null.
+ */
+ onExpire?(key: string, value: any): any;
+ }
+
+ export interface CachePutOptions {
+ /*
+ * The number of milliseconds until a newly inserted item expires. Default: Number.MAX_VALUE.
+ */
+ maxAge?: number;
+
+ /*
+ * If inserting a promise into a cache, also insert the rejection value if the promise rejects. Default: false.
+ */
+ storeOnReject?: boolean;
+
+ /*
+ * If inserting a promise into a cache, also insert the resolved value if the promise resolves. Default: false.
+ */
+ storeOnResolve?: boolean;
+
+ created?: Date;
+ access?: Date;
+ expires?: Date;
+ }
+
+ export interface CacheTouchOptions extends CachePutOptions { }
+
+ export interface CacheOptions {
+ /*
+ * If set, remove all items from a cache on an interval after the given number of milliseconds. Default: null.
+ */
+ cacheFlushInterval?: number;
+
+ /*
+ * Maximum number of items a cache can hold. Adding more items than the capacity will cause the cache to operate
+ * like an LRU cache, removing the least recently used items to stay under capacity. Default: Number.MAX_VALUE.
+ */
+
+ capacity?: number;
+
+ /*
+ * Determines the behavior of a cache when an item expires. Default: none.
+ *
+ * Possible values:
+ *
+ * none - cache will do nothing when an item expires.
+ * passive - cache will do nothing when an item expires. Expired items will remain in the cache until requested,
+ * at which point they are removed, and undefined is returned.
+ * aggressive - cache will remove expired items as soon as they are discovered.
+ */
+ deleteOnExpire?: string;
+
+ /*
+ * Determines whether a cache is disabled. Default: false.
+ */
+ disabled?: boolean;
+
+ /*
+ * The number of milliseconds until a newly inserted item expires. Default: Number.MAX_VALUE.
+ */
+ maxAge?: number;
+
+ /*
+ * Determines how often a cache will scan for expired items when in aggressive mode. Default: 1000 (milliseconds).
+ */
+ recycleFreq?: number;
+
+ /*
+ * If inserting a promise into a cache, also insert the rejection value if the promise rejects. Default: false.
+ */
+ storeOnReject?: boolean;
+
+ /*
+ * If inserting a promise into a cache, also insert the resolved value if the promise resolves. Default: false.
+ */
+ storeOnResolve?: boolean;
+
+ /*
+ * Provide a custom storage medium, e.g. a polyfill for localStorage. Default: null.
+ *
+ * Must implement:
+ *
+ * setItem - Same API as localStorage.setItem(key, value)
+ * getItem - Same API as localStorage.getItem(key)
+ * removeItem - Same API as localStorage.removeItem(key)
+ */
+ storageImpl?: IStoreImplementation;
+
+ /*
+ * Determines the storage medium used by a cache. Default: memory.
+ *
+ * Possible values:
+ *
+ * memory - cache will hold data in memory. Data is cleared when the page is refreshed.
+ * localStorage - cache will hold data in localStorage if available. Data is not cleared when the page is refreshed.
+ * sessionStorage - cache will hold data in sessionStorage if available. Data is not cleared when the page is refreshed.
+ */
+ storageMode?: string;
+
+ /*
+ * Determines the namespace of a cache when storageMode is set to localStorage or sessionStorage. Make it a shorter
+ * string to save space. Default: angular-cache.caches.
+ */
+ storagePrefix?: string;
+
+ /*
+ * A callback function to be executed whenever an expired item is removed from a cache when the cache is in passive
+ * or aggressive mode. Will be passed the key and value of the expired item.
+ *
+ * Will be passed a third done argument if the cache is in passive mode. This allows you to synchronously access the
+ * key and value of the expired item when you make the cache#get(key[, options]) call that is the reason the expired
+ * item is being removed in the first place. Default: null.
+ */
+ onExpire?(key: string, value: any): any;
+ }
+
+ export interface ICache {
+
+ $$id: string;
+
+ /**
+ * Return the item with the given key.options, if provided, must be an object.
+ *
+ * If the cache is in passive mode, then options.onExpire can be a function that will be called with the key
+ * and value of the requested item if the requested item is expired, with the get call itself returning undefined.
+ * @param key
+ * @returns {}
+ */
+ get(key: string, options?: CacheGetOptions): T;
+
+ /**
+ * Insert the item with the given key and value into the cache.options, if provided, must be an object.
+ *
+ * If inserting a promise, options.storeOnReject determines whether to insert the rejection value if the promise
+ * rejects (overriding the default storeOnReject setting for the cache). If inserting a promise, options.storeOnResolve
+ * determines whether to insert the resolved value if the promise resolves (overriding the default storeOnResolve setting for the cache).
+ *
+ * @param key
+ * @param value
+ * @param options
+ */
+ put(key: string, value: T, options?: CachePutOptions): void;
+
+ /**
+ * Remove and return the item with the given key, if it is in the cache.
+ * @param key
+ * @returns {}
+ */
+ remove(key: string): T;
+
+ /**
+ * Remove all items in the cache.
+ */
+ removeAll(): void;
+
+ /**
+ * Remove and return all expired items in the cache.
+ * @returns {}
+ */
+ removeExpired(): { [key: string]: any };
+
+ /**
+ * Completely destroy this cache and its data.
+ * @returns {}
+ */
+ destroy(): void;
+
+ /**
+ * Returns an object containing information about the cache.
+ *
+ * @param key
+ */
+ info(): CacheInfo;
+
+ /**
+ * Returns an object containing information about the item with the given key, if the item is in the cache.
+ *
+ * @param key
+ */
+ info(key: string): CacheItemInfo;
+
+ /**
+ * Return the keys of all items in the cache as an object.
+ * @returns {}
+ */
+ keySet(): any;
+
+ /**
+ * Return the keys of all items in the cache as an array.
+ * @returns []
+ */
+ keys(): Array;
+
+ /**
+ * Enable the cache.
+ */
+ enable(): void;
+
+ /**
+ * Disable the cache.
+ */
+ disable(): void;
+
+ /**
+ * cache#touch() will "touch" all items in the cache.
+ * cache#touch(key) will "touch" the item with the given key.
+ *
+ * @param key
+ */
+ touch(key?: string, options?: CacheTouchOptions): void;
+
+ /**
+ * Set the cacheFlushInterval for the cache.
+ * @param cacheFlushInterval
+ */
+ setCacheFlushInterval(cacheFlushInterval: number): void;
+
+ /**
+ * Set the capacity for the cache.Setting this lower than the current item count will result in those items being removed.
+ * @param capacity
+ */
+ setCapacity(capacity: number): void;
+
+ /**
+ * Set the deleteOnExpire for the cache.
+ * @param deleteOnExpire
+ */
+ setDeleteOnExpire(deleteOnExpire: string): void;
+
+ /**
+ * Set the maxAge for the cache.
+ */
+ setMaxAge(maxAge: number): void;
+
+ /**
+ * Set the onExpire for the cache.
+ * @param onExpire
+ */
+ setOnExpire(onExpire: Function): void;
+
+ /**
+ * Set the recycleFreq for the cache.
+ * @param recycleFreq
+ */
+ setRecycleFreq(recycleFreq: number): void;
+
+ /**
+ * Set the storageMode for the cache.This will move data from the current storage medium to the new one.
+ * @param storageMode
+ */
+ setStorageMode(storageMode: string): void;
+
+ /**
+ * Set multiple options for the cache at a time.Setting strict to true will reset options for the cache
+ * that are not specifically set in the options hash to CacheFactoryProvider.defaults.
+ * @param options
+ */
+ setOptions(options: CacheOptions, strict?: boolean): void;
+
+ /**
+ * Return the values of all items in the cache as an array.
+ * @returns Array
+ */
+ values(): Array
+ }
+
+ export interface ICacheFactory {
+
+ BinaryHeap: IBinaryHeap;
+ utils: IUtils;
+ defaults: CacheOptions;
+
+ /**
+ * Create a cache. cache must not already exist. cacheId must be a string. options is an optional argument and must be an object.
+ * Any options you pass here will override any default options.
+ * @param cacheId
+ * @param options
+ * @returns ICache
+ */
+ (cacheId: string, options?: CacheOptions): ICache;
+
+ /**
+ * Create a cache. cache must not already exist. cacheId must be a string. options is an optional argument and must be an object.
+ * Any options you pass here will override any default options.
+ * @param cacheId
+ * @param options
+ * @returns ICache
+ */
+ createCache(cacheId: string, options?: CacheOptions): ICache;
+
+ /**
+ * Return the cache with the given cacheId.
+ * @param cacheId The id of the cache storage.
+ * @returns ICache
+ */
+ get(cacheId: string, options?: CacheOptions): ICache;
+
+ /**
+ * Return an object of key- value pairs, the keys being cache ids and the values being the result of .info() being called on each cache.
+ * @returns CacheInfo
+ */
+ info(): CacheInfo;
+
+ /**
+ * Return the ids of all registered caches as an object.
+ * @returns {[key: string]: ICache}
+ */
+ keySet(): { [key: string]: ICache };
+
+ /**
+ * Return the ids of all registered caches as an array.
+ * @returns Array
+ */
+ keys(): Array;
+
+ /**
+ * Destroy the cache with the given cacheId.
+ * @param cacheId
+ */
+ destroy(cacheId: string): void;
+
+ /**
+ * Destroy all registered caches.
+ */
+ destroyAll(): void;
+
+ /**
+ * Remove all data from all registered caches.
+ */
+ clearAll(): void;
+
+ /**
+ * Enable all registered caches.
+ */
+ enableAll(): void;
+
+ /**
+ * Disable all registered caches.
+ */
+ disableAll(): void;
+
+ /**
+ * Call.touch() on all registered caches.
+ */
+ touchAll(): void;
+
+ /**
+ * Call.removeExpired() on all registered caches.Returns a hash of any expired items, keyed by cache id.
+ * @returns {}
+ */
+ removeExpiredFromAll(): Array<{ [key: string]: Array<{ [key: string]: any }> }>;
+ }
+
+ export interface IUtils {
+ isNumber(value: any): boolean;
+ isString(value: any): boolean;
+ isObject(value: any): boolean;
+ isFunction(value: any): boolean;
+ equals(a: any, b: any): boolean;
+ fromJson(value: any): {}
+ Promise: any;
+ }
+
+ export interface HeapItem {
+ key: string;
+ accessed: Date;
+ }
+
+ export interface IBinaryHeap {
+ (w?: IWeightFunc, c?: ICompareFunc): void;
+
+ heap: Array;
+ weightFunc: IWeightFunc;
+ compareFunc: ICompareFunc;
+
+ push(node: HeapItem): void;
+ pop(): HeapItem;
+ peek(): HeapItem;
+ remove(node: HeapItem): HeapItem;
+ removeAll(): void;
+ size(): Number;
+ }
+
+ export interface IWeightFunc {
+ (x: T): T;
+ }
+
+ export interface ICompareFunc {
+ (x: T, y: T): boolean;
+ }
+
+ export interface CacheInfo {
+ size: Number;
+ caches: { [key: string]: any };
+ capacity: Number;
+ maxAge: Number;
+ deleteOnExpire: string;
+ onExpire: Function;
+ cacheFlushInterval: Number;
+ recycleFreq: Number;
+ storageMode: string;
+ storageImpl: IStoreImplementation;
+ disabled: boolean;
+ storagePrefix: string;
+ storeOnResolve: boolean;
+ storeOnReject: boolean;
+ }
+
+ export interface CacheItemInfo {
+ created: Date;
+ accessed: Date;
+ expires: Date;
+ isExpired: boolean;
+ }
+}
+
+declare var CacheFactory: CacheFactory.ICacheFactory;
+
+declare module "cachefactory" {
+ export = CacheFactory;
+}
\ No newline at end of file
diff --git a/codemirror/codemirror.d.ts b/codemirror/codemirror.d.ts
index bade422821..4d95220c67 100644
--- a/codemirror/codemirror.d.ts
+++ b/codemirror/codemirror.d.ts
@@ -1125,6 +1125,115 @@ declare namespace CodeMirror {
severity?: string;
to?: Position;
}
+
+ /**
+ * A function that calculates either a two-way or three-way merge between different sets of content.
+ */
+ function MergeView(element: HTMLElement, options?: MergeView.MergeViewEditorConfiguration): MergeView.MergeViewEditor;
+
+ namespace MergeView {
+ /**
+ * Options available to MergeView.
+ */
+ interface MergeViewEditorConfiguration extends EditorConfiguration {
+ /**
+ * Determines whether the original editor allows editing. Defaults to false.
+ */
+ allowEditingOriginals?: boolean;
+
+ /**
+ * When true stretches of unchanged text will be collapsed. When a number is given, this indicates the amount
+ * of lines to leave visible around such stretches (which defaults to 2). Defaults to false.
+ */
+ collapseIdentical?: boolean | number;
+
+ /**
+ * Sets the style used to connect changed chunks of code. By default, connectors are drawn. When this is set to "align",
+ * the smaller chunk is padded to align with the bigger chunk instead.
+ */
+ connect?: string;
+
+ /**
+ * Callback for when stretches of unchanged text are collapsed.
+ */
+ onCollapse?(mergeView: MergeViewEditor, line: number, size: number, mark: TextMarker): void;
+
+ /**
+ * Provides original version of the document to be shown on the right of the editor.
+ */
+ orig: any;
+
+ /**
+ * Provides original version of the document to be shown on the left of the editor.
+ * To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight.
+ */
+ origLeft?: any;
+
+ /**
+ * Provides original version of document to be shown on the right of the editor.
+ * To create a 2-way (as opposed to 3-way) merge view, provide only one of origLeft and origRight.
+ */
+ origRight?: any;
+
+ /**
+ * Determines whether buttons that allow the user to revert changes are shown. Defaults to true.
+ */
+ revertButtons?: boolean;
+
+ /**
+ * When true, changed pieces of text are highlighted. Defaults to true.
+ */
+ showDifferences?: boolean;
+ }
+
+ interface MergeViewEditor extends Editor {
+ /**
+ * Returns the editor instance.
+ */
+ editor(): Editor;
+
+ /**
+ * Left side of the merge view.
+ */
+ left: DiffView;
+ leftChunks(): MergeViewDiffChunk;
+ leftOriginal(): Editor;
+
+ /**
+ * Right side of the merge view.
+ */
+ right: DiffView;
+ rightChunks(): MergeViewDiffChunk;
+ rightOriginal(): Editor;
+
+ /**
+ * Sets whether or not the merge view should show the differences between the editor views.
+ */
+ setShowDifferences(showDifferences: boolean): void;
+ }
+
+ /**
+ * Tracks changes in chunks from oroginal to new.
+ */
+ interface MergeViewDiffChunk {
+ editFrom: number;
+ editTo: number;
+ origFrom: number;
+ origTo: number;
+ }
+
+ interface DiffView {
+ /**
+ * Forces the view to reload.
+ */
+ forceUpdate(): (mode: string) => void;
+
+ /**
+ * Sets whether or not the merge view should show the differences between the editor views.
+ */
+ setShowDifferences(showDifferences: boolean): void;
+ }
+ }
}
declare module "codemirror" {
diff --git a/cordova/cordova.d.ts b/cordova/cordova.d.ts
index 299e2da4d9..24adab6928 100644
--- a/cordova/cordova.d.ts
+++ b/cordova/cordova.d.ts
@@ -35,7 +35,7 @@ interface Cordova {
* @param action The action name to call on the native side (generally corresponds to the native class method).
* @param args An array of arguments to pass into the native environment.
*/
- exec(success: () => any, fail: () => any, service: string, action: string, args?: string[]): void;
+ exec(success: () => any, fail: () => any, service: string, action: string, args?: any[]): void;
/** Gets the operating system name. */
platformId: string;
/** Gets Cordova framework version */
diff --git a/cordova/plugins/NetworkInformation.d.ts b/cordova/plugins/NetworkInformation.d.ts
index 4f80fdbb7e..0d49597e3a 100644
--- a/cordova/plugins/NetworkInformation.d.ts
+++ b/cordova/plugins/NetworkInformation.d.ts
@@ -47,6 +47,7 @@ interface Connection {
*/
type: string;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
+ removeEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
declare var Connection: {
diff --git a/core-js/core-js-tests.ts b/core-js/core-js-tests.ts
index bc690d434c..965acc6855 100644
--- a/core-js/core-js-tests.ts
+++ b/core-js/core-js-tests.ts
@@ -500,3 +500,5 @@ s = s.unescapeHTML();
// #############################################################################################
promiseOfVoid = delay(i);
+
+console.log('core-js version number:', core.version);
diff --git a/core-js/core-js.d.ts b/core-js/core-js.d.ts
index 16441df233..2c1fa4bd99 100644
--- a/core-js/core-js.d.ts
+++ b/core-js/core-js.d.ts
@@ -1266,6 +1266,8 @@ interface String {
declare function delay(msec: number): Promise;
declare namespace core {
+ var version: string;
+
namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike): any;
function construct(target: Function, argumentsList: ArrayLike): any;
diff --git a/d3/d3-tests.ts b/d3/d3-tests.ts
index c9027b0889..7991dcaa03 100644
--- a/d3/d3-tests.ts
+++ b/d3/d3-tests.ts
@@ -2706,3 +2706,17 @@ function testMultiUtcFormat() {
["%Y", function() { return true; }]
]);
}
+
+function testEnterSizeEmpty() {
+
+ var selectionSize: number,
+ emptyStatus: boolean;
+
+ var newNodes = d3.selectAll('.test')
+ .data(['1', '2', '3'])
+ .enter();
+
+ emptyStatus = newNodes.empty();
+ selectionSize = newNodes.size();
+
+}
\ No newline at end of file
diff --git a/d3/d3.d.ts b/d3/d3.d.ts
index c80a922f1f..85a1b70f82 100644
--- a/d3/d3.d.ts
+++ b/d3/d3.d.ts
@@ -415,6 +415,9 @@ declare namespace d3 {
select(name: (datum: Datum, index: number, outerIndex: number) => EventTarget): Selection;
call(func: (selection: Enter, ...args: any[]) => any, ...args: any[]): Enter;
+
+ empty(): boolean;
+ size(): number;
}
}
diff --git a/dagre-d3/dagre-d3-tests.ts b/dagre-d3/dagre-d3-tests.ts
index 2ba8675436..ef5fddffac 100644
--- a/dagre-d3/dagre-d3-tests.ts
+++ b/dagre-d3/dagre-d3-tests.ts
@@ -14,5 +14,6 @@ namespace DagreD3Tests {
const render = new dagreD3.render();
const svg = d3.select("svg");
+ render.arrows()["arrowType"] = (parent: JQuery, id: string, edge: Dagre.Edge, type: string) => {};
render(svg, graph);
}
diff --git a/dagre-d3/dagre-d3.d.ts b/dagre-d3/dagre-d3.d.ts
index 0bc71294c8..68e24c2fa5 100644
--- a/dagre-d3/dagre-d3.d.ts
+++ b/dagre-d3/dagre-d3.d.ts
@@ -5,6 +5,7 @@
///
///
+///
declare namespace Dagre {
@@ -23,6 +24,8 @@ declare namespace Dagre {
}
interface Render {
+ // see http://cpettitt.github.io/project/dagre-d3/latest/demo/user-defined.html for example usage
+ arrows (): { [arrowStyleName: string]: (parent: JQuery, id: string, edge: Dagre.Edge, type: string) => void };
new (): Render;
(selection: d3.Selection, g: Dagre.Graph): void;
}
diff --git a/daterangepicker/daterangepicker-tests.ts b/daterangepicker/daterangepicker-tests.ts
new file mode 100644
index 0000000000..ca1f99961c
--- /dev/null
+++ b/daterangepicker/daterangepicker-tests.ts
@@ -0,0 +1,59 @@
+///
+
+function tests_simple() {
+ $('#daterange').daterangepicker();
+ $('input[name="daterange"]').daterangepicker({
+ timePicker: true,
+ timePickerIncrement: 30,
+ locale: {
+ format: 'MM/DD/YYYY h:mm A'
+ }
+ });
+
+ $('#reportrange').daterangepicker({
+ ranges: {
+ 'Today': [moment(), moment()],
+ 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
+ 'Last 7 Days': [moment().subtract(6, 'days'), moment()],
+ 'Last 30 Days': [moment().subtract(29, 'days'), moment()],
+ 'This Month': [moment().startOf('month'), moment().endOf('month')],
+ 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
+ }
+ });
+
+ $('input[name="datefilter"]').on('apply.daterangepicker', function (ev, picker) {
+ $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
+ });
+
+
+ $('input[name="datefilter"]').on('cancel.daterangepicker', function (ev, picker) {
+ $(this).val('');
+ });
+
+ $('#demo').daterangepicker({
+ "startDate": "05/06/2016",
+ "endDate": "05/12/2016"
+ }, function (start: string, end: string, label: string) {
+ console.log("New date range selected: ' + start.format('YYYY-MM-DD') + ' to ' + end.format('YYYY-MM-DD') + ' (predefined range: ' + label + ')");
+ });
+
+ $(function() {
+
+ function cb(start: moment.Moment, end: moment.Moment) {
+ $('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
+ }
+ cb(moment().subtract(29, 'days'), moment());
+
+ $('#reportrange').daterangepicker({
+ ranges: {
+ 'Today': [moment(), moment()],
+ 'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
+ 'Last 7 Days': [moment().subtract(6, 'days'), moment()],
+ 'Last 30 Days': [moment().subtract(29, 'days'), moment()],
+ 'This Month': [moment().startOf('month'), moment().endOf('month')],
+ 'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')]
+ }
+ }, cb);
+
+});
+}
diff --git a/daterangepicker/daterangepicker.d.ts b/daterangepicker/daterangepicker.d.ts
new file mode 100644
index 0000000000..11190aa85d
--- /dev/null
+++ b/daterangepicker/daterangepicker.d.ts
@@ -0,0 +1,142 @@
+// Type definitions for Date Range Picker v2.1.19
+// Project: http://www.daterangepicker.com/
+// Definitions by: SirMartin
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+///
+///
+
+interface JQuery {
+ daterangepicker(settings?: daterangepicker.Settings): JQuery;
+ daterangepicker(settings?: daterangepicker.Settings, callback?: (start?: string | Date | moment.Moment, end?: string | Date | moment.Moment, label?: string) => any): JQuery;
+}
+
+declare module daterangepicker {
+
+ interface DatepickerEventObject extends JQueryEventObject {
+ date: Date;
+ format(format?: string): string;
+ }
+
+ interface Settings {
+ /**
+ * The start of the initially selected date range
+ */
+ startDate?: string | moment.Moment | Date;
+ /**
+ * The end of the initially selected date range
+ */
+ endDate?: string | moment.Moment | Date;
+ /**
+ * The earliest date a user may select
+ */
+ minDate?: string | moment.Moment | Date;
+ /**
+ * The latest date a user may select
+ */
+ maxDate?: string | moment.Moment | Date;
+ /**
+ * The maximum span between the selected start and end dates. Can have any property you can add to a moment object (i.e. days, months)
+ */
+ dateLimit?: any;
+ /**
+ * Show year and month select boxes above calendars to jump to a specific month and year
+ */
+ showDropdowns?: boolean;
+ /**
+ * Show localized week numbers at the start of each week on the calendars
+ */
+ showWeekNumbers?: boolean;
+ /**
+ * Show ISO week numbers at the start of each week on the calendars
+ */
+ showISOWeekNumbers?: boolean;
+ /**
+ * Allow selection of dates with times, not just dates
+ */
+ timePicker?: boolean;
+ /**
+ * Increment of the minutes selection list for times (i.e. 30 to allow only selection of times ending in 0 or 30)
+ */
+ timePickerIncrement?: number;
+ /**
+ * Use 24- hour instead of 12- hour times, removing the AM/ PM selection.
+ */
+ timePicker24Hour?: boolean;
+ /**
+ * Show seconds in the timePicker.
+ */
+ timePickerSeconds?: boolean;
+ /**
+ * Set predefined date ranges the user can select from.Each key is the label for the range, and its value an array with two dates representing the bounds of the range.
+ */
+ ranges?: any;
+ /**
+ * (string: 'left'/'right'/'center') Whether the picker appears aligned to the left, to the right, or centered under the HTML element it's attached to
+ */
+ opens?: string;
+ /**
+ * (string: 'down' or 'up') Whether the picker appears below (default) or above the HTML element it's attached to
+ */
+ drops?: string;
+ /**
+ * CSS class names that will be added to all buttons in the picker
+ */
+ buttonClasses?: string[];
+ /**
+ * CSS class string that will be added to the apply button
+ */
+ applyClass?: string;
+ /**
+ * CSS class string that will be added to the cancel button
+ */
+ cancelClass?: string;
+ /**
+ * Allows you to provide localized strings for buttons and labels, customize the date display format, and change the first day of week for the calendars.
+ */
+ locale?: Locale;
+ /**
+ * Show only a single calendar to choose one date, instead of a range picker with two calendars; the start and end dates provided to your callback will be the same single date chosen.
+ */
+ singleDatePicker?: boolean;
+ /**
+ * Hide the apply and cancel buttons, and automatically apply a new date range as soon as two dates or a predefined range is selected.
+ */
+ autoApply?: boolean;
+ /**
+ * When enabled, the two calendars displayed will always be for two sequential months (i.e.January and February), and both will be advanced when clicking the left or right arrows above the calendars.When disabled, the two calendars can be individually advanced and display any month/ year.
+ */
+ linkedCalendars?: boolean;
+ /**
+ * jQuery selector of the parent element that the date range picker will be added to, if not provided this will be 'body'
+ */
+ parentEl?: string;
+ /**
+ * A function that is passed each date in the two calendars before they are displayed, and may return true or false to indicate whether that date should be available for selection or not.
+ */
+ isInvalidDate?(startDate: string | moment.Moment | Date, endDate?: string | moment.Moment | Date): boolean;
+ /**
+ * Indicates whether the date range picker should automatically update the value of an < input > element it's attached to at initialization and when the selected dates change.
+ */
+ autoUpdateInput?: boolean;
+ /**
+ * Normally, if you use the ranges option to specify pre- defined date ranges, calendars for choosing a custom date range are not shown until the user clicks "Custom Range".When this option is set to true, the calendars for choosing a custom date range are always shown instead.
+ */
+ alwaysShowCalendars?: boolean;
+ }
+
+ interface Locale {
+ /**
+ * Text for cancel label.
+ */
+ cancelLabel?: string;
+ /**
+ * Text for apply label.
+ */
+ applyLabel?: string;
+ /**
+ * Format of the date string. example: 'YYYY-MM-DD'
+ */
+ format?: string;
+ }
+}
diff --git a/db.js/db.js-tests.ts b/db.js/db.js-tests.ts
new file mode 100644
index 0000000000..e2aacb27f0
--- /dev/null
+++ b/db.js/db.js-tests.ts
@@ -0,0 +1,259 @@
+// Test file for db.js Definition file
+///
+
+/* Type for use in tests */
+
+interface Person {
+ firstName: string;
+ lastName: string;
+ answer: number;
+ group?: string;
+}
+
+/* Opening/creating a database and connection */
+
+var server: DbJs.Server;
+
+db.open({
+ server: 'my-app',
+ version: 1,
+ schema: {
+ people: {
+ key: { keyPath: 'id', autoIncrement: true },
+ indexes: {
+ firstName: {},
+ answer: { unique: true }
+ }
+ }
+ }
+}).then(function (s: DbJs.Server) {
+ server = s;
+});
+
+var typedStore: DbJs.TypedObjectStoreServer = server['people'];
+
+/* Basic server operations */
+
+var idb = server.getIndexedDB();
+server.close();
+
+/* General server/store methods */
+
+// Adding items
+server.add('people', {
+ firstName: 'Aaron',
+ lastName: 'Powell',
+ answer: 42
+}).then(function (item) { });
+
+typedStore.add({
+ firstName: 'Aaron',
+ lastName: 'Powell',
+ answer: 42
+}).then(function (item) { });
+
+// Updating
+server.update('people', {
+ firstName: 'Aaron',
+ lastName: 'Powell',
+ answer: 42
+}).then(function (item) { });
+
+typedStore.update({
+ firstName: 'Aaron',
+ lastName: 'Powell',
+ answer: 42
+}).then(function (item) { });
+
+// Removing
+server.remove('people', 1).then(function (key) { });
+typedStore.remove(1).then(function (key) { });
+
+// Clearing
+server.clear('people').then(function() { });
+typedStore.clear().then(function() { });
+
+// Fetching
+
+// Getting a single object by key
+server.get('people', 5).then(function (results) { });
+typedStore.get(5).then(function (results) { });
+
+// Getting a single object by key range
+
+// With a MongoDB-style range:
+
+server.get('people', {gte: 1, lt: 3})
+ .then(function (results) { });
+typedStore.get({gte: 1, lt: 3})
+ .then(function (results) { });
+
+// With an IDBKeyRange :
+
+server.get('people', IDBKeyRange.bound(1, 3, false, true))
+ .then(function (results) { });
+typedStore.get(IDBKeyRange.bound(1, 3, false, true))
+ .then(function (results) { });
+
+// Querying
+
+// Querying all objects
+server.query('people')
+ .all()
+ .execute()
+ .then(function (results) { });
+
+typedStore.query()
+ .all()
+ .execute()
+ .then(function (results) { });
+
+// Querying using indexes
+server.query('people', 'specialProperty')
+ .all()
+ .execute()
+ .then(function (results) { });
+
+ typedStore.query('specialProperty')
+ .all()
+ .execute()
+ .then(function (results) { });
+
+// Filter with property and value
+server.query('people')
+ .filter('firstName', 'Aaron')
+ .execute()
+ .then(function (results) { });
+
+// Filter with function
+server.query('people')
+ .filter(function(person: any) { return person.group === 'hipster'; })
+ .execute()
+ .then(function (results) { });
+
+typedStore.query('people')
+ .filter(function(person) { return person.group === 'hipster'; })
+ .execute()
+ .then(function (results) { });
+
+// Querying with ranges
+server.query('people', 'firstName')
+ .only('Aaron')
+ .then(function (results) { });
+
+server.query('people', 'answer')
+ .bound(30, 50)
+ .then(function (results) { });
+
+server.query('people', 'firstName')
+ .range({ eq: 'Aaron' })
+ .then(function (results) { });
+
+server.query('people', 'answer')
+ .range({ gte: 30, lte: 50 })
+ .then(function (results) { });
+
+// Querying for distinct values
+ server.query('people', 'firstName')
+ .only('Aaron')
+ .distinct()
+ .execute()
+ .then(function (data) { });
+
+// Limiting cursor range
+server.query('people', 'firstName')
+ .all()
+ .limit(1, 3)
+ .execute()
+ .then(function (data) { });
+
+// Cursor direction (desc)
+server.query('people')
+ .all()
+ .desc()
+ .execute()
+ .then(function (results) { });
+
+// Keys
+server.query('people', 'firstName')
+ .only('Aaron')
+ .keys()
+ .execute()
+ .then(function (results) { });
+
+// Mapping
+server.query('people', 'age')
+ .lowerBound(30)
+ .map(function (value) {
+ return {
+ fullName: value.firstName + ' ' + value.lastName,
+ raw: value
+ };
+ })
+ .execute()
+ .then(function (data) { });
+
+// Counting
+server.query('people', 'firstName')
+ .only('Aaron')
+ .count()
+ .execute()
+ .then(function (results) { });
+
+// With no arguments (count all items)
+server.count().then(function (ct) { });
+
+// With a key
+server.count('myKey').then(function (ct) { });
+
+// With a MongoDB-style range
+server.count({gte: 1, lt: 3}).then(function (ct) { });
+
+// With an IDBKeyRange range
+server.count(IDBKeyRange.bound(1, 3, false, true)).then(function (ct) { });
+
+// Atomic updates
+server.query('users', 'last_mod')
+ .lowerBound(new Date().getTime() - 10000)
+ .modify({ last_mod: new Date().getTime() })
+ .execute()
+ .then(function(results) { });
+
+server.query('users', 'changed')
+ .only(true)
+ .modify({ changed: false })
+ .execute()
+ .then(function () { });
+
+server.query('users', 'name')
+ .lowerBound('marcy')
+ .modify({ views: function(profile: any) { return profile.views + 1; } })
+ .execute()
+ .then(function () { });
+
+/* Other server methods */
+
+// Closing connection
+server.close();
+
+// Retrieving the indexedDB.open result object in use
+var storeNames = server.getIndexedDB().objectStoreNames;
+
+// Server event handlers
+
+server.addEventListener('abort', function (e: Event) { });
+server.addEventListener('error', function (err: Event) { });
+server.addEventListener('versionchange', function (e: Event) { });
+
+server
+ .abort(function (e) { })
+ .error(function (err) { })
+ .versionchange(function (e) { });
+
+// Deleting a database
+db.delete('dbName').then(function () { }, function (err: Error) { });
+db.delete('dbName').catch(function (err) { }).then(function (ev) { });
+
+// Comparing two keys
+
+db.cmp('key1', 'key2');
diff --git a/db.js/db.js.d.ts b/db.js/db.js.d.ts
new file mode 100644
index 0000000000..83e21fa529
--- /dev/null
+++ b/db.js/db.js.d.ts
@@ -0,0 +1,154 @@
+// Type definitions for db.js v0.14.0
+// Project: https://github.com/aaronpowell/db.js/
+// Definitions by: Chris Wrench
+// Definitions: https://github.com/borisyankov/DefinitelyTyped
+
+declare module DbJs {
+ interface ErrorListener {
+ (err: Error): void;
+ }
+
+ interface OpenOptions {
+ server: string;
+ version: number;
+ schema?: any;
+ }
+
+ interface DbJsStatic {
+ open(options: OpenOptions): Promise;
+ delete(dbName: string): Promise;
+ cmp(key1: any, key2: any): number;
+ }
+
+ // Query API
+
+ interface ExecutableQuery {
+ execute(): Promise;
+ }
+
+ interface CountableQuery {
+ count(): ExecutableQuery;
+ }
+
+ interface KeysQuery extends DescableQuery, ExecutableQuery, FilterableQuery, DistinctableQuery, MappableQuery {
+ }
+
+ interface KeyableQuery {
+ keys(): KeysQuery;
+ }
+
+ interface FilterQuery extends KeyableQuery, ExecutableQuery, FilterableQuery, DescableQuery, DistinctableQuery, ModifiableQuery, LimitableQuery, MappableQuery {
+ }
+
+ interface FilterableQuery {
+ filter(index: string, value: TValue): FilterQuery;
+ filter(filter: (value: T) => boolean): FilterQuery;
+ }
+
+ interface DescQuery extends KeyableQuery, CountableQuery, ExecutableQuery, FilterableQuery