Merge pull request #8095 from DefinitelyTyped/normalize-lineending

normalize line ending (CRLF -> LF)
This commit is contained in:
Masahiro Wakame
2016-02-16 08:54:38 +09:00
508 changed files with 79006 additions and 79006 deletions

74
.gitignore vendored
View File

@@ -1,37 +1,37 @@
*.dll
*.exe
*.cmd
*.pdb
*.suo
*.js
*.user
*.cache
*.cs
*.sln
*.csproj
*.txt
*.map
*.swp
.DS_Store
npm-debug.log
_Resharper.DefinitelyTyped
bin
obj
Properties
# VIM backup files
*~
# test folder
_infrastructure/tests/build
.idea
*.iml
*.js.map
!*.js/
node_modules
.sublimets
.settings/launch.json
*.dll
*.exe
*.cmd
*.pdb
*.suo
*.js
*.user
*.cache
*.cs
*.sln
*.csproj
*.txt
*.map
*.swp
.DS_Store
npm-debug.log
_Resharper.DefinitelyTyped
bin
obj
Properties
# VIM backup files
*~
# test folder
_infrastructure/tests/build
.idea
*.iml
*.js.map
!*.js/
node_modules
.sublimets
.settings/launch.json

View File

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

94
Finch/Finch.d.ts vendored
View File

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

View File

@@ -1,107 +1,107 @@
/// <reference path="accounting.d.ts"/>
// formatMoney
// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00
// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
// Negative values are formatted nicely, too:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000
// Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP
// Example usage with options object:
accounting.formatMoney(5318008, {
symbol: "GBP",
precision: 0,
thousand: "·",
format: {
pos: "%s %v",
neg: "%s (%v)",
zero: "%s --"
}
});
// Will recursively format an array of values:
accounting.formatMoney([123, 456, [78, 9]], "$", 0); // ["$123", "$456", ["$78", "$9"]]
// formatColumn
// Format list of numbers for display:
accounting.formatColumn([123.5, 3456.49, 777888.99, 12345678, -5432], "$ ");
// Example usage (NB. use a space after the symbol to add arbitrary padding to all values):
accounting.formatColumn([123, 12345], "$ ", 0); // ["$ 123", "$ 12,345"]
// List of numbers can be a multi-dimensional array (formatColumn is applied recursively):
accounting.formatColumn([[1, 100], [900, 9]]); // [["$ 1.00", "$100.00"], ["$900.00", "$ 9.00"]]
// formatNumber
// Example usage:
accounting.formatNumber(5318008); // 5,318,008
accounting.formatNumber(9876543.21, 3, " "); // 9 876 543.210
accounting.formatNumber(4999.99, 2, ".", ","); // 4.999,99
// Example usage with options object:
accounting.formatNumber(5318008, {
precision: 3,
thousand: " "
});
// Will recursively format an array of values:
accounting.formatNumber([123456, [7890, 123]]); // ["123,456", ["7,890", "123"]]
// toFixed
(0.615).toFixed(2); // "0.61"
accounting.toFixed(0.615, 2); // "0.62"
// unformat
// Example usage:
accounting.unformat("£ 12,345,678.90 GBP"); // 12345678.9
accounting.unformat("GBP £ 12,345,678.90"); // 12345678.9
// If a non-standard decimal separator was used (eg. a comma) unformat() will need it in order to work out
// which part of the number is a decimal/float:
accounting.unformat("€ 1.000.000,00", ","); // 1000000
// Settings object that controls default parameters for library methods:
accounting.settings = {
currency: {
symbol: "$", // default currency symbol is '$'
format: "%s%v", // controls output: %s = symbol, %v = value/number (can be object: see below)
decimal: ".", // decimal point separator
thousand: ",", // thousands separator
precision: 2 // decimal places
},
number: {
precision: 0, // default precision on numbers is 0
thousand: ",",
decimal: "."
}
};
// These can be changed externally to edit the library's defaults:
accounting.settings.currency.format = "%s %v";
// Format can be an object, with `pos`, `neg` and `zero`:
accounting.settings.currency.format = {
pos: "%s %v", // for positive values, eg. "$ 1.00" (required)
neg: "%s (%v)", // for negative values, eg. "$ (1.00)" [optional]
zero: "%s -- " // for zero values, eg. "$ --" [optional]
};
/// <reference path="accounting.d.ts"/>
// formatMoney
// Default usage:
accounting.formatMoney(12345678); // $12,345,678.00
// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
// Negative values are formatted nicely, too:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000
// Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP", format: "%v %s" }); // 5,318,008.00 GBP
// Example usage with options object:
accounting.formatMoney(5318008, {
symbol: "GBP",
precision: 0,
thousand: "·",
format: {
pos: "%s %v",
neg: "%s (%v)",
zero: "%s --"
}
});
// Will recursively format an array of values:
accounting.formatMoney([123, 456, [78, 9]], "$", 0); // ["$123", "$456", ["$78", "$9"]]
// formatColumn
// Format list of numbers for display:
accounting.formatColumn([123.5, 3456.49, 777888.99, 12345678, -5432], "$ ");
// Example usage (NB. use a space after the symbol to add arbitrary padding to all values):
accounting.formatColumn([123, 12345], "$ ", 0); // ["$ 123", "$ 12,345"]
// List of numbers can be a multi-dimensional array (formatColumn is applied recursively):
accounting.formatColumn([[1, 100], [900, 9]]); // [["$ 1.00", "$100.00"], ["$900.00", "$ 9.00"]]
// formatNumber
// Example usage:
accounting.formatNumber(5318008); // 5,318,008
accounting.formatNumber(9876543.21, 3, " "); // 9 876 543.210
accounting.formatNumber(4999.99, 2, ".", ","); // 4.999,99
// Example usage with options object:
accounting.formatNumber(5318008, {
precision: 3,
thousand: " "
});
// Will recursively format an array of values:
accounting.formatNumber([123456, [7890, 123]]); // ["123,456", ["7,890", "123"]]
// toFixed
(0.615).toFixed(2); // "0.61"
accounting.toFixed(0.615, 2); // "0.62"
// unformat
// Example usage:
accounting.unformat("£ 12,345,678.90 GBP"); // 12345678.9
accounting.unformat("GBP £ 12,345,678.90"); // 12345678.9
// If a non-standard decimal separator was used (eg. a comma) unformat() will need it in order to work out
// which part of the number is a decimal/float:
accounting.unformat("€ 1.000.000,00", ","); // 1000000
// Settings object that controls default parameters for library methods:
accounting.settings = {
currency: {
symbol: "$", // default currency symbol is '$'
format: "%s%v", // controls output: %s = symbol, %v = value/number (can be object: see below)
decimal: ".", // decimal point separator
thousand: ",", // thousands separator
precision: 2 // decimal places
},
number: {
precision: 0, // default precision on numbers is 0
thousand: ",",
decimal: "."
}
};
// These can be changed externally to edit the library's defaults:
accounting.settings.currency.format = "%s %v";
// Format can be an object, with `pos`, `neg` and `zero`:
accounting.settings.currency.format = {
pos: "%s %v", // for positive values, eg. "$ 1.00" (required)
neg: "%s (%v)", // for negative values, eg. "$ (1.00)" [optional]
zero: "%s -- " // for zero values, eg. "$ --" [optional]
};

View File

@@ -3,28 +3,28 @@
// Definitions by: Sergey Gerasimov <https://github.com/gerich-home/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface IAccountingCurrencyFormat {
pos: string; // for positive values, eg. "$ 1.00"
neg?: string; // for negative values, eg. "$ (1.00)"
interface IAccountingCurrencyFormat {
pos: string; // for positive values, eg. "$ 1.00"
neg?: string; // for negative values, eg. "$ (1.00)"
zero?: string; // for zero values, eg. "$ --"
}
interface IAccountingCurrencySettings<TFormat> {
symbol?: string; // default currency symbol is '$'
format?: TFormat; // controls output: %s = symbol, %v = value/number
decimal?: string; // decimal point separator
thousand?: string; // thousands separator
interface IAccountingCurrencySettings<TFormat> {
symbol?: string; // default currency symbol is '$'
format?: TFormat; // controls output: %s = symbol, %v = value/number
decimal?: string; // decimal point separator
thousand?: string; // thousands separator
precision?: number // decimal places
}
interface IAccountingNumberSettings {
precision?: number; // default precision on numbers is 0
thousand?: string;
decimal?: string;
interface IAccountingNumberSettings {
precision?: number; // default precision on numbers is 0
thousand?: string;
decimal?: string;
}
interface IAccountingSettings {
currency: IAccountingCurrencySettings<any>; // IAccountingCurrencySettings<string> or IAccountingCurrencySettings<IAccountingCurrencyFormat>
interface IAccountingSettings {
currency: IAccountingCurrencySettings<any>; // IAccountingCurrencySettings<string> or IAccountingCurrencySettings<IAccountingCurrencyFormat>
number: IAccountingNumberSettings;
}
@@ -76,4 +76,4 @@ declare var accounting: IAccountingStatic;
declare module "accounting" {
export = accounting;
}
}

View File

@@ -1 +1 @@

View File

@@ -1 +1 @@

View File

@@ -1 +1 @@

View File

@@ -1 +1 @@

View File

@@ -1 +1 @@

View File

@@ -1 +1 @@

View File

@@ -1,62 +1,62 @@
// Type definitions for angular-google-analytics v1.1.0
// Project: https://github.com/revolunet/angular-google-analytics
// Definitions by: Matt Wheatley <https://github.com/terrawheat>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.google.analytics {
interface AnalyticsService {
/**
* @summary If logging is enabled then all outbound calls are accessible via an in-memory array.
* This is useful for troubleshooting and seeing the order of outbound calls with parameters.
*/
log: Array<Object>;
/**
* @summary If in offline mode then all calls are queued to an in-memory array for future processing.
* All calls queued to the offlineQueue are not outbound calls yet and hence do not show up in the log.
*/
offlineQueue: Array<Object>;
/**
* @summary Returns the current URL that would be sent if a `trackPage` call was made.
* @return {string} The URL
*/
getUrl: () => string;
/**
* @summary Manually create classic analytics (ga.js) script tag
*/
createScriptTag: () => void;
/**
* @summary Manually create universal analytics (analytics.js) script tag
*/
createAnalyticsScriptTag: () => void;
/**
* @summary Allows for advanced configuration and definitions in univeral analytics only. This is a no-op when using classic analytics.
*/
set: (key: string, value: any, accountName?: string) => void;
/**
* @summary Creates a new page view event
* @param {string} pageURL URL of page view
* @param {string} title Page Title
* @param {Object} dimensions Additional dimensions and metrics
*/
trackPage: (pageURL: string, title?: string, dimensions?: { [expr: string]: any }) => void;
/**
* @summary Create a new event
*/
trackEvent: (category: string, action: string, label: string, value?: any, nonInteractionFlag?: boolean, dimensions?: { [expr: string]: any }) => void;
trackException: (descrption: string, isFatal: boolean) => void;
/**
* @summary While in offline mode, no calls to the ga function or pushes to the gaq array are made.
* This will queue all calls for later sending once offline mode is reset to false.
*/
offline: (offlineMode: boolean) => void;
}
}
// Type definitions for angular-google-analytics v1.1.0
// Project: https://github.com/revolunet/angular-google-analytics
// Definitions by: Matt Wheatley <https://github.com/terrawheat>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module angular.google.analytics {
interface AnalyticsService {
/**
* @summary If logging is enabled then all outbound calls are accessible via an in-memory array.
* This is useful for troubleshooting and seeing the order of outbound calls with parameters.
*/
log: Array<Object>;
/**
* @summary If in offline mode then all calls are queued to an in-memory array for future processing.
* All calls queued to the offlineQueue are not outbound calls yet and hence do not show up in the log.
*/
offlineQueue: Array<Object>;
/**
* @summary Returns the current URL that would be sent if a `trackPage` call was made.
* @return {string} The URL
*/
getUrl: () => string;
/**
* @summary Manually create classic analytics (ga.js) script tag
*/
createScriptTag: () => void;
/**
* @summary Manually create universal analytics (analytics.js) script tag
*/
createAnalyticsScriptTag: () => void;
/**
* @summary Allows for advanced configuration and definitions in univeral analytics only. This is a no-op when using classic analytics.
*/
set: (key: string, value: any, accountName?: string) => void;
/**
* @summary Creates a new page view event
* @param {string} pageURL URL of page view
* @param {string} title Page Title
* @param {Object} dimensions Additional dimensions and metrics
*/
trackPage: (pageURL: string, title?: string, dimensions?: { [expr: string]: any }) => void;
/**
* @summary Create a new event
*/
trackEvent: (category: string, action: string, label: string, value?: any, nonInteractionFlag?: boolean, dimensions?: { [expr: string]: any }) => void;
trackException: (descrption: string, isFatal: boolean) => void;
/**
* @summary While in offline mode, no calls to the ga function or pushes to the gaq array are made.
* This will queue all calls for later sending once offline mode is reset to false.
*/
offline: (offlineMode: boolean) => void;
}
}

View File

@@ -1,65 +1,65 @@
/// <reference path="angular-growl-v2.d.ts" />
var app = angular.module("ag", ["pascalprecht.translate", "$httpProvider"]);
app.config((growlProvider:angular.growl.IGrowlProvider, $httpProvider:angular.IHttpProvider) => {
var ttl:angular.growl.IGrowlTTLConfig = {
success: 5000,
error: 4000
};
growlProvider.globalTimeToLive(ttl)
.globalTimeToLive(5000)
.globalDisableCloseButton(true)
.globalDisableIcons(true)
.globalReversedOrder(false)
.globalDisableCountDown(true)
.messageVariableKey("someKey")
.globalInlineMessages(false)
.globalPosition("top-center")
.messagesKey("someKey")
.messageTextKey("someKey")
.messageTitleKey("someKey")
.messageSeverityKey("someKey")
.onlyUniqueMessages(false);
$httpProvider.interceptors.push(growlProvider.serverMessagesInterceptor);
});
app.controller("Ctrl", ($scope:angular.IScope,
growl:angular.growl.IGrowlService,
growlMessages:angular.growl.IGrowlMessagesService) => {
var config:angular.growl.IGrowlMessageConfig = {
ttl: 5000,
disableCountDown: true,
disableCloseButton: true
};
var message = "Some message";
growl.warning(message);
growl.warning(message, config);
growl.error(message);
growl.error(message, config);
growl.info(message);
growl.info(message, config);
growl.success(message);
growl.success(message, config);
growl.general(message);
growl.general(message, config);
growl.general(message, config, "error");
growl.onlyUnique();
growl.reverseOrder();
growl.inlineMessages();
growl.position();
growlMessages.initDirective(1, 10);
var messages:angular.growl.IGrowlMessage[] = growlMessages.getAllMessages(2);
growlMessages.destroyAllMessages(0);
growlMessages.addMessage(messages[0]);
growlMessages.deleteMessage(messages[1]);
var testMessage = growl.warning(message);
testMessage.setText("Some other message");
testMessage.destroy();
});
/// <reference path="angular-growl-v2.d.ts" />
var app = angular.module("ag", ["pascalprecht.translate", "$httpProvider"]);
app.config((growlProvider:angular.growl.IGrowlProvider, $httpProvider:angular.IHttpProvider) => {
var ttl:angular.growl.IGrowlTTLConfig = {
success: 5000,
error: 4000
};
growlProvider.globalTimeToLive(ttl)
.globalTimeToLive(5000)
.globalDisableCloseButton(true)
.globalDisableIcons(true)
.globalReversedOrder(false)
.globalDisableCountDown(true)
.messageVariableKey("someKey")
.globalInlineMessages(false)
.globalPosition("top-center")
.messagesKey("someKey")
.messageTextKey("someKey")
.messageTitleKey("someKey")
.messageSeverityKey("someKey")
.onlyUniqueMessages(false);
$httpProvider.interceptors.push(growlProvider.serverMessagesInterceptor);
});
app.controller("Ctrl", ($scope:angular.IScope,
growl:angular.growl.IGrowlService,
growlMessages:angular.growl.IGrowlMessagesService) => {
var config:angular.growl.IGrowlMessageConfig = {
ttl: 5000,
disableCountDown: true,
disableCloseButton: true
};
var message = "Some message";
growl.warning(message);
growl.warning(message, config);
growl.error(message);
growl.error(message, config);
growl.info(message);
growl.info(message, config);
growl.success(message);
growl.success(message, config);
growl.general(message);
growl.general(message, config);
growl.general(message, config, "error");
growl.onlyUnique();
growl.reverseOrder();
growl.inlineMessages();
growl.position();
growlMessages.initDirective(1, 10);
var messages:angular.growl.IGrowlMessage[] = growlMessages.getAllMessages(2);
growlMessages.destroyAllMessages(0);
growlMessages.addMessage(messages[0]);
growlMessages.deleteMessage(messages[1]);
var testMessage = growl.warning(message);
testMessage.setText("Some other message");
testMessage.destroy();
});

View File

@@ -1,259 +1,259 @@
// Type definitions for Angular Growl 2 v.0.7.5
// Project: http://janstevens.github.io/angular-growl-2
// Definitions by: Tadeusz Hucal <https://github.com/mkp05>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.growl {
/**
* Global Time-To-Leave configuration.
*/
interface IGrowlTTLConfig {
success?: number;
error?: number;
warning?: number;
info?: number;
}
/**
* Custom configuration used in single message call.
*/
interface IGrowlMessageConfig {
title?: string;
ttl?: number;
disableCountDown?: boolean;
disableIcons?: boolean;
disableCloseButton?: boolean;
onclose?: Function;
onopen?: Function;
position?: string;
referenceId?: number;
translateMessage?: boolean;
variables?: { [variable: string]: any; };
}
/**
* Growl message with configuration.
*/
interface IGrowlMessage extends IGrowlMessageConfig {
text: string;
/**
* Destroy the message.
*/
destroy(): void;
/**
* Update the message body.
* @param newText new message body
*/
setText(newText: string): void;
}
/**
* Growl service provider.
*/
interface IGrowlProvider extends angular.IServiceProvider {
/**
* Pre-defined server error interceptor.
*/
serverMessagesInterceptor: (string|IHttpInterceptorFactory)[];
/**
* Set default TTL settings.
* @param ttl configuration of TTL for different type of message
*/
globalTimeToLive(ttl: IGrowlTTLConfig): IGrowlProvider;
/**
* Set default TTL settings.
* @param ttl ttl in milliseconds
*/
globalTimeToLive(ttl: number): IGrowlProvider;
/**
* Set default setting for disabling close button.
* @param disableCloseButton
*/
globalDisableCloseButton(disableCloseButton: boolean): IGrowlProvider;
/**
* Set default setting for disabling icons.
* @param disableIcons
*/
globalDisableIcons(disableIcons: boolean): IGrowlProvider;
/**
* Set reversing order of displaying new messages.
* @param reverseOrder
*/
globalReversedOrder(reverseOrder: boolean): IGrowlProvider;
/**
* Set default setting for displaying message disappear countdown.
* @param disableCountDown
*/
globalDisableCountDown(disableCountDown: boolean): IGrowlProvider;
/**
* Set default allowance for inline messages.
* @param inline
*/
globalInlineMessages(inline: boolean): IGrowlProvider;
/**
* Set default message position.
* @param position
*/
globalPosition(position: string): IGrowlProvider;
/**
* Enable/disable displaying only unique messages.
* @param onlyUniqueMessages
*/
onlyUniqueMessages(onlyUniqueMessages: boolean): IGrowlProvider;
/**
* Set key where messages are stored (for http interceptor).
* @param messageVariableKey
*/
messagesKey(messageKey: string): IGrowlProvider;
/**
* Set key where message text is stored (for http interceptor).
* @param messageVariableKey
*/
messageTextKey(messageTextKey: string): IGrowlProvider;
/**
* Set key where title of message is stored (for http interceptor).
* @param messageVariableKey
*/
messageTitleKey(messageTitleKey: string): IGrowlProvider;
/**
* Set key where severity of message is stored (for http interceptor).
* @param messageVariableKey
*/
messageSeverityKey(messageSeverityKey: string): IGrowlProvider;
/**
* Set key where variables for message are stored (for http interceptor).
* @param messageVariableKey
*/
messageVariableKey(messageVariableKey: string): IGrowlProvider;
}
/**
* Growl service.
*/
interface IGrowlService {
/**
* Show warning message.
* @param message text to display (or code for angular-translate)
*/
warning(message: string): IGrowlMessage;
/**
* Show warning message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
warning(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show error message.
* @param message text to display (or code for angular-translate)
*/
error(message: string): IGrowlMessage;
/**
* Show error message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
error(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show information message.
* @param message text to display (or code for angular-translate)
*/
info(message: string): IGrowlMessage;
/**
* Show information message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
info(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show success message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
success(message: string): IGrowlMessage;
/**
* Show success message.
* @param message text to display (or code for angular-translate)
*/
success(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show message (generic).
* @param message text to display (or code for angular-translate)
*/
general(message: string): IGrowlMessage;
/**
* Show message (generic).
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
general(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show message (generic).
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
* @param severity message severity (error, warning, success, info).
*/
general(message: string, config: IGrowlMessageConfig, severity: string): IGrowlMessage;
/**
* Get current setting for displaying only unique messages.
*/
onlyUnique(): boolean;
/**
* Get current setting for reversing messages order.
*/
reverseOrder(): boolean;
/**
* Get current allowance for inline messages.
*/
inlineMessages(): boolean;
/**
* Get current messages position.
*/
position(): string;
}
/**
* GrowlMessages service.
*/
interface IGrowlMessagesService {
/**
* Initialize a directive
* We look at the preloaded directive and use this else we
* create a new blank object
* @param referenceId
* @param limitMessages
*/
initDirective(referenceId: number, limitMessages: number): angular.IDirective;
/**
* Get current messages
*/
getAllMessages(referenceId?: number): IGrowlMessage[];
/**
* Destroy all messages
*/
destroyAllMessages(referenceId?: number): void;
/**
* Add a message
*/
addMessage(message: IGrowlMessage): IGrowlMessage;
/**
* Delete a message
*/
deleteMessage(message: IGrowlMessage): void;
}
}
// Type definitions for Angular Growl 2 v.0.7.5
// Project: http://janstevens.github.io/angular-growl-2
// Definitions by: Tadeusz Hucal <https://github.com/mkp05>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.growl {
/**
* Global Time-To-Leave configuration.
*/
interface IGrowlTTLConfig {
success?: number;
error?: number;
warning?: number;
info?: number;
}
/**
* Custom configuration used in single message call.
*/
interface IGrowlMessageConfig {
title?: string;
ttl?: number;
disableCountDown?: boolean;
disableIcons?: boolean;
disableCloseButton?: boolean;
onclose?: Function;
onopen?: Function;
position?: string;
referenceId?: number;
translateMessage?: boolean;
variables?: { [variable: string]: any; };
}
/**
* Growl message with configuration.
*/
interface IGrowlMessage extends IGrowlMessageConfig {
text: string;
/**
* Destroy the message.
*/
destroy(): void;
/**
* Update the message body.
* @param newText new message body
*/
setText(newText: string): void;
}
/**
* Growl service provider.
*/
interface IGrowlProvider extends angular.IServiceProvider {
/**
* Pre-defined server error interceptor.
*/
serverMessagesInterceptor: (string|IHttpInterceptorFactory)[];
/**
* Set default TTL settings.
* @param ttl configuration of TTL for different type of message
*/
globalTimeToLive(ttl: IGrowlTTLConfig): IGrowlProvider;
/**
* Set default TTL settings.
* @param ttl ttl in milliseconds
*/
globalTimeToLive(ttl: number): IGrowlProvider;
/**
* Set default setting for disabling close button.
* @param disableCloseButton
*/
globalDisableCloseButton(disableCloseButton: boolean): IGrowlProvider;
/**
* Set default setting for disabling icons.
* @param disableIcons
*/
globalDisableIcons(disableIcons: boolean): IGrowlProvider;
/**
* Set reversing order of displaying new messages.
* @param reverseOrder
*/
globalReversedOrder(reverseOrder: boolean): IGrowlProvider;
/**
* Set default setting for displaying message disappear countdown.
* @param disableCountDown
*/
globalDisableCountDown(disableCountDown: boolean): IGrowlProvider;
/**
* Set default allowance for inline messages.
* @param inline
*/
globalInlineMessages(inline: boolean): IGrowlProvider;
/**
* Set default message position.
* @param position
*/
globalPosition(position: string): IGrowlProvider;
/**
* Enable/disable displaying only unique messages.
* @param onlyUniqueMessages
*/
onlyUniqueMessages(onlyUniqueMessages: boolean): IGrowlProvider;
/**
* Set key where messages are stored (for http interceptor).
* @param messageVariableKey
*/
messagesKey(messageKey: string): IGrowlProvider;
/**
* Set key where message text is stored (for http interceptor).
* @param messageVariableKey
*/
messageTextKey(messageTextKey: string): IGrowlProvider;
/**
* Set key where title of message is stored (for http interceptor).
* @param messageVariableKey
*/
messageTitleKey(messageTitleKey: string): IGrowlProvider;
/**
* Set key where severity of message is stored (for http interceptor).
* @param messageVariableKey
*/
messageSeverityKey(messageSeverityKey: string): IGrowlProvider;
/**
* Set key where variables for message are stored (for http interceptor).
* @param messageVariableKey
*/
messageVariableKey(messageVariableKey: string): IGrowlProvider;
}
/**
* Growl service.
*/
interface IGrowlService {
/**
* Show warning message.
* @param message text to display (or code for angular-translate)
*/
warning(message: string): IGrowlMessage;
/**
* Show warning message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
warning(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show error message.
* @param message text to display (or code for angular-translate)
*/
error(message: string): IGrowlMessage;
/**
* Show error message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
error(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show information message.
* @param message text to display (or code for angular-translate)
*/
info(message: string): IGrowlMessage;
/**
* Show information message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
info(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show success message.
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
success(message: string): IGrowlMessage;
/**
* Show success message.
* @param message text to display (or code for angular-translate)
*/
success(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show message (generic).
* @param message text to display (or code for angular-translate)
*/
general(message: string): IGrowlMessage;
/**
* Show message (generic).
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
*/
general(message: string, config: IGrowlMessageConfig): IGrowlMessage;
/**
* Show message (generic).
* @param message text to display (or code for angular-translate)
* @param config additional message configuration
* @param severity message severity (error, warning, success, info).
*/
general(message: string, config: IGrowlMessageConfig, severity: string): IGrowlMessage;
/**
* Get current setting for displaying only unique messages.
*/
onlyUnique(): boolean;
/**
* Get current setting for reversing messages order.
*/
reverseOrder(): boolean;
/**
* Get current allowance for inline messages.
*/
inlineMessages(): boolean;
/**
* Get current messages position.
*/
position(): string;
}
/**
* GrowlMessages service.
*/
interface IGrowlMessagesService {
/**
* Initialize a directive
* We look at the preloaded directive and use this else we
* create a new blank object
* @param referenceId
* @param limitMessages
*/
initDirective(referenceId: number, limitMessages: number): angular.IDirective;
/**
* Get current messages
*/
getAllMessages(referenceId?: number): IGrowlMessage[];
/**
* Destroy all messages
*/
destroyAllMessages(referenceId?: number): void;
/**
* Add a message
*/
addMessage(message: IGrowlMessage): IGrowlMessage;
/**
* Delete a message
*/
deleteMessage(message: IGrowlMessage): void;
}
}

View File

@@ -1,255 +1,255 @@
/// <reference path="angular-meteor.d.ts" />
interface ITodo {
_id?: string;
name: string;
public?: boolean;
sticky?: boolean;
}
interface TodoAngularMeteorObject extends ITodo, angular.meteor.AngularMeteorObject<ITodo> {}
interface CustomScope extends angular.meteor.IScope {
sticky: boolean;
todos: angular.meteor.AngularMeteorCollection<ITodo>;
stickyTodos: angular.meteor.AngularMeteorCollection<ITodo>;
notAutoTodos: angular.meteor.AngularMeteorCollection<ITodo>;
todo: ITodo;
todoNotAuto: TodoAngularMeteorObject;
todoSubscribed: TodoAngularMeteorObject;
save: (todo: ITodo) => void;
saveAll: () =>void;
autoSave: (todo: ITodo) => void;
remove: (todoId: string) => void;
removeAll: () => void;
removeAuto: (todo: ITodo) => void;
toSticky: (todo: ITodo) => void;
}
var Todos = new Mongo.Collection<ITodo>('todos');
var app = angular.module('angularMeteorTestApp');
app.controller("mainCtrl", ['$scope', '$meteor', ($scope: CustomScope, $meteor: angular.meteor.IMeteorService) => {
// Bind all the todos to $scope.todos
$scope.todos = $meteor.collection(Todos);
$scope.sticky = true;
// Bind all sticky todos to $scope.stickyTodos
// Binds the query to $scope.sticky so that if it changes, Meteor will re-run the query and bind it
// to $scope.stickyTodos
$scope.stickyTodos = $meteor.collection<ITodo>(function(){
return Todos.find({sticky: $scope.getReactively('sticky')});
});
// Bind without auto-save all todos to $scope.notAutoTodos
$scope.notAutoTodos = $meteor.collection(Todos, false).subscribe("publicTodos");
$scope.todoNotAuto = <TodoAngularMeteorObject>$meteor.object(Todos, 'TodoID', false);
$scope.todoSubscribed = <TodoAngularMeteorObject>$meteor.object(Todos, 'TodoID').subscribe('todos');
$scope.todo = $scope.todoNotAuto.getRawObject();
$scope.todoNotAuto.reset();
$scope.todoNotAuto.save($scope.todo).then((data) => { return data == 1; });;
// todo might be an object like this {text: "Learn Angular", sticky: false}
// or an array like this:
// [{text: "Learn Angular", sticky: false}, {text: "Hello World", sticky: true}]
$scope.save = function(todo) {
$scope.notAutoTodos.save(todo);
};
$scope.saveAll = function() {
$scope.notAutoTodos.save();
};
$scope.autoSave = function(todo) {
$scope.todos.push(todo);
};
// todoId might be an string like this "WhrnEez5yBRgo4yEm"
// or an array like this ["WhrnEez5yBRgo4yEm","gH6Fa4DXA3XxQjXNS"]
$scope.remove = function(todoId) {
$scope.notAutoTodos.remove(todoId);
};
$scope.removeAll = function() {
$scope.notAutoTodos.remove();
};
$scope.removeAuto = function(todo) {
$scope.todos.splice( $scope.todos.indexOf(todo), 1 );
}
$scope.toSticky = function(todo) {
if (angular.isArray(todo)){
angular.forEach(todo, function(object) {
object.sticky = true;
});
} else {
todo.sticky = true;
}
$scope.stickyTodos.save(todo);
};
var todoObject = {name:'first todo'};
var todosArray = [{name:'second todo'}, {name:'third todo'}];
var todoSecondObject = {name:'forth todo'};
$scope.todos.save(todoObject); // todos equals [{name:'first todo'}]
$scope.todos.save(todosArray); // todos equals [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}]
$scope.todos.push(todoSecondObject); // The scope variable equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}, {name:'forth todo'}]
// but the collection still equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}]
$scope.todos.save(); // Now the collection also equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}, {name:'forth todo'}]
$scope.todos.remove('firstTodoId'); // scope and collection equals to [{name:'second todo'}, {name:'third todo'}, {name:'forth todo'}]
var todoIdsArray = ['secondTodoId', 'thirdTodoId'];
$scope.todos.remove(todoIdsArray); // removes everything matches the array of IDs both in scope and in collection
$scope.todos.pop(); // removes only in scope
$scope.todos.remove(); // syncs also in Meteor collection
// Subscribe ->
$meteor.subscribe('todos').then((subscriptionHandle) => {
// Bind all the todos to $scope.todos
$scope.todos = $meteor.collection(Todos);
console.log($scope.todos + ' is ready');
// You can use the subscription handle to stop the subscription if you want
subscriptionHandle.stop();
});
$scope.subscribe('todos').then((subscriptionHandle) => {
// Bind all the todos to $scope.books
$scope.todos = $meteor.collection(Todos);
console.log($scope.todos + ' is ready');
// No need to stop the subscription, it will automatically close on scope destroy
});
$meteor.call<ITodo>('subscribe', $scope.todo._id, $scope.currentUser._id).then((data) => {
// Handle success
console.log('success subscribing', data.name);
}, (err) => {
// Handle error
console.log('failed', err);
});
if (!$scope.loggingIn) {
$meteor.waitForUser();
$meteor.requireUser();
$meteor.requireValidUser(user => {
return user.username == 'admin';
});
$meteor.loginWithPassword('user', 'password').then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.createUser({
username:'moma',
email:'example@gmail.com',
password: 'Bksd@asdf',
profile: {expertize: 'Developer'}
}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.changePassword('old', 'new232f3').then(() => {
console.log('Change password success');
}, err => {
console.log('Error changing password - ', err);
});
$meteor.forgotPassword({email: 'sample@gmail.com'}).then(() => {
console.log('Success sending forgot password email');
}, err => {
console.log('Error sending forgot password email - ', err);
});
$meteor.resetPassword('tokenID', 'new232f3').then(() => {
console.log('Reset password success');
}, err => {
console.log('Error resetting password - ', err);
});
$meteor.verifyEmail('tokenID').then(() => {
console.log('Success verifying password ');
}, err => {
console.log('Error verifying password - ', err);
});
$meteor.logout().then(() => {
console.log('Logout success');
}, err => {
console.log('logout error - ', err);
});
$meteor.logoutOtherClients().then(() => {
console.log('Logout success');
}, err => {
console.log('logout error - ', err);
});
var loginWithOptions = {requestPermissions: ['email']};
$meteor.loginWithFacebook({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithGithub({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithGoogle({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithMeetup({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithTwitter({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithWeibo({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
}
$meteor.autorun($scope, () => { console.log("Aurorun triggered."); });
$meteor.getCollectionByName('collectionName');
// requires meteor add mdg:camera
$meteor.getPicture().then(function(data){
$scope['picture'] = data;
});
$meteor.session('counter').bind($scope, 'counter');
}]);
/// <reference path="angular-meteor.d.ts" />
interface ITodo {
_id?: string;
name: string;
public?: boolean;
sticky?: boolean;
}
interface TodoAngularMeteorObject extends ITodo, angular.meteor.AngularMeteorObject<ITodo> {}
interface CustomScope extends angular.meteor.IScope {
sticky: boolean;
todos: angular.meteor.AngularMeteorCollection<ITodo>;
stickyTodos: angular.meteor.AngularMeteorCollection<ITodo>;
notAutoTodos: angular.meteor.AngularMeteorCollection<ITodo>;
todo: ITodo;
todoNotAuto: TodoAngularMeteorObject;
todoSubscribed: TodoAngularMeteorObject;
save: (todo: ITodo) => void;
saveAll: () =>void;
autoSave: (todo: ITodo) => void;
remove: (todoId: string) => void;
removeAll: () => void;
removeAuto: (todo: ITodo) => void;
toSticky: (todo: ITodo) => void;
}
var Todos = new Mongo.Collection<ITodo>('todos');
var app = angular.module('angularMeteorTestApp');
app.controller("mainCtrl", ['$scope', '$meteor', ($scope: CustomScope, $meteor: angular.meteor.IMeteorService) => {
// Bind all the todos to $scope.todos
$scope.todos = $meteor.collection(Todos);
$scope.sticky = true;
// Bind all sticky todos to $scope.stickyTodos
// Binds the query to $scope.sticky so that if it changes, Meteor will re-run the query and bind it
// to $scope.stickyTodos
$scope.stickyTodos = $meteor.collection<ITodo>(function(){
return Todos.find({sticky: $scope.getReactively('sticky')});
});
// Bind without auto-save all todos to $scope.notAutoTodos
$scope.notAutoTodos = $meteor.collection(Todos, false).subscribe("publicTodos");
$scope.todoNotAuto = <TodoAngularMeteorObject>$meteor.object(Todos, 'TodoID', false);
$scope.todoSubscribed = <TodoAngularMeteorObject>$meteor.object(Todos, 'TodoID').subscribe('todos');
$scope.todo = $scope.todoNotAuto.getRawObject();
$scope.todoNotAuto.reset();
$scope.todoNotAuto.save($scope.todo).then((data) => { return data == 1; });;
// todo might be an object like this {text: "Learn Angular", sticky: false}
// or an array like this:
// [{text: "Learn Angular", sticky: false}, {text: "Hello World", sticky: true}]
$scope.save = function(todo) {
$scope.notAutoTodos.save(todo);
};
$scope.saveAll = function() {
$scope.notAutoTodos.save();
};
$scope.autoSave = function(todo) {
$scope.todos.push(todo);
};
// todoId might be an string like this "WhrnEez5yBRgo4yEm"
// or an array like this ["WhrnEez5yBRgo4yEm","gH6Fa4DXA3XxQjXNS"]
$scope.remove = function(todoId) {
$scope.notAutoTodos.remove(todoId);
};
$scope.removeAll = function() {
$scope.notAutoTodos.remove();
};
$scope.removeAuto = function(todo) {
$scope.todos.splice( $scope.todos.indexOf(todo), 1 );
}
$scope.toSticky = function(todo) {
if (angular.isArray(todo)){
angular.forEach(todo, function(object) {
object.sticky = true;
});
} else {
todo.sticky = true;
}
$scope.stickyTodos.save(todo);
};
var todoObject = {name:'first todo'};
var todosArray = [{name:'second todo'}, {name:'third todo'}];
var todoSecondObject = {name:'forth todo'};
$scope.todos.save(todoObject); // todos equals [{name:'first todo'}]
$scope.todos.save(todosArray); // todos equals [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}]
$scope.todos.push(todoSecondObject); // The scope variable equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}, {name:'forth todo'}]
// but the collection still equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}]
$scope.todos.save(); // Now the collection also equals to [{name:'first todo'}, {name:'second todo'}, {name:'third todo'}, {name:'forth todo'}]
$scope.todos.remove('firstTodoId'); // scope and collection equals to [{name:'second todo'}, {name:'third todo'}, {name:'forth todo'}]
var todoIdsArray = ['secondTodoId', 'thirdTodoId'];
$scope.todos.remove(todoIdsArray); // removes everything matches the array of IDs both in scope and in collection
$scope.todos.pop(); // removes only in scope
$scope.todos.remove(); // syncs also in Meteor collection
// Subscribe ->
$meteor.subscribe('todos').then((subscriptionHandle) => {
// Bind all the todos to $scope.todos
$scope.todos = $meteor.collection(Todos);
console.log($scope.todos + ' is ready');
// You can use the subscription handle to stop the subscription if you want
subscriptionHandle.stop();
});
$scope.subscribe('todos').then((subscriptionHandle) => {
// Bind all the todos to $scope.books
$scope.todos = $meteor.collection(Todos);
console.log($scope.todos + ' is ready');
// No need to stop the subscription, it will automatically close on scope destroy
});
$meteor.call<ITodo>('subscribe', $scope.todo._id, $scope.currentUser._id).then((data) => {
// Handle success
console.log('success subscribing', data.name);
}, (err) => {
// Handle error
console.log('failed', err);
});
if (!$scope.loggingIn) {
$meteor.waitForUser();
$meteor.requireUser();
$meteor.requireValidUser(user => {
return user.username == 'admin';
});
$meteor.loginWithPassword('user', 'password').then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.createUser({
username:'moma',
email:'example@gmail.com',
password: 'Bksd@asdf',
profile: {expertize: 'Developer'}
}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.changePassword('old', 'new232f3').then(() => {
console.log('Change password success');
}, err => {
console.log('Error changing password - ', err);
});
$meteor.forgotPassword({email: 'sample@gmail.com'}).then(() => {
console.log('Success sending forgot password email');
}, err => {
console.log('Error sending forgot password email - ', err);
});
$meteor.resetPassword('tokenID', 'new232f3').then(() => {
console.log('Reset password success');
}, err => {
console.log('Error resetting password - ', err);
});
$meteor.verifyEmail('tokenID').then(() => {
console.log('Success verifying password ');
}, err => {
console.log('Error verifying password - ', err);
});
$meteor.logout().then(() => {
console.log('Logout success');
}, err => {
console.log('logout error - ', err);
});
$meteor.logoutOtherClients().then(() => {
console.log('Logout success');
}, err => {
console.log('logout error - ', err);
});
var loginWithOptions = {requestPermissions: ['email']};
$meteor.loginWithFacebook({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithGithub({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithGoogle({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithMeetup({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithTwitter({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
$meteor.loginWithWeibo({requestPermissions: ['email']}).then(() => {
console.log('Login success');
}, err => {
console.log('Login error - ', err);
});
}
$meteor.autorun($scope, () => { console.log("Aurorun triggered."); });
$meteor.getCollectionByName('collectionName');
// requires meteor add mdg:camera
$meteor.getPicture().then(function(data){
$scope['picture'] = data;
});
$meteor.session('counter').bind($scope, 'counter');
}]);

View File

@@ -1,352 +1,352 @@
// Type definitions for Angular JS Meteor v0.8.8 (angular.meteor module)
// Project: https://github.com/Urigo/angular-meteor
// Definitions by: Peter Grman <https://github.com/pgrm>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../meteor/meteor.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.meteor {
interface IRootScopeService extends angular.IRootScopeService {
/**
* The current logged in user and it's data. it is null if the user is not logged in. A reactive data source.
*/
currentUser: Meteor.User;
/**
* True if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress.
* A reactive data source. Can be use to display animation while user is logging in.
*/
loggingIn: boolean;
}
interface IScope extends angular.IScope, IRootScopeService {
/**
* A method to get a $scope variable and watch it reactivly
*
* @param scopeVariableName - The name of the scope's variable to bind to
* @param [objectEquality=false] - Watch the object equality using angular.equals instead of comparing for reference equality, deeper watch but also slower
*/
getReactively(scopeVariableName: string, objectEquality?: boolean): ReactiveResult;
/**
* A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready.
* Calling $scope.subscribe will automatically stop the subscription when the scope is destroyed.
*
* @param name - Name of the subscription. Matches the name of the server's publish() call.
* @param publisherArguments - Optional arguments passed to publisher function on server.
*
* @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle.
*/
subscribe(name: string, ...publisherArguments: any[]): angular.IPromise<Meteor.SubscriptionHandle>;
/**
* The helpers method is part of the ReactiveContext, and available on every context and $scope.
* These method are defined as Object, where each key is the name of the variable that will be available on the context we run, and each value is a function with a return value.
* Under the hood, each helper starts a new Tracker.autorun. When its reactive dependencies change, the helper is rerun.
* To trigger a rerun every time an specific Angular variable change, use getReactively](/api/1.3.1/get-reactively) to make your Angular variable reactive inside the helper its used in.
* Each helper function should return a MongoDB Cursor and the helpers will expose it as a normal array to the context.
*
* @param definitions - Object containing `name` => `function` definition, where each name is a string and each function is the helper function. Should return a [MongoDB Cursor](http://docs.meteor.com/#/full/mongo_cursor)
* @return This method returns this, which the the reactive context, in order to provide the ability to chain the logic.
*/
helpers(definitions : { [helperName : string] : () => Mongo.Cursor<any> }): IScope;
/**
* This method is a wrapper of Tracker.autorun and shares exactly the same API.
* The autorun method is part of the ReactiveContext, and available on every context and $scope.
* The argument of this method is a callback, which will be called each time Autorun will be used.
* The Autorun will stop automatically when when it's context ($scope) is destroyed.
*
* @param runFunc - The function to run. It receives one argument: the Computation object that will be returned.
*/
autorun(runFunc : () => void) : Tracker.Computation;
}
/**
* $meteor in angularjs
*/
interface IMeteorService {
/**
* A service that wraps the Meteor collections to enable reactivity within AngularJS.
*
* @param collection - A Meteor Collection or a reactive function to bind to.
* - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor.
* @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection.
* - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection.
*/
collection<T>(collection: Mongo.Collection<T>|ReactiveResult|Function|(()=>T), autoClientSave?: boolean): AngularMeteorCollection<T>;
/**
* A service that wraps the Meteor collections to enable reactivity within AngularJS.
*
* @param collection - A Meteor Collection or a reactive function to bind to.
* - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor.
* @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection.
* - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection.
* @param [updateCollection] - A collection object which will be used for updates (insert, update, delete).
*/
collection<T, U>(collection: Mongo.Collection<T>|ReactiveResult|Function|(()=>T), autoClientSave: boolean, updateCollection: Mongo.Collection<U>): AngularMeteorCollection2<T, U>;
/**
* A service that wraps a Meteor object to enable reactivity within AngularJS.
* Finds the first document that matches the selector, as ordered by sort and skip options. Wraps collection.findOne
*
* @param collection - A Meteor Collection to bind to.
* @param selector - A query describing the documents to find or just the ID of the document.
* - $meteor.object will find the first document that matches the selector,
* - as ordered by sort and skip options, exactly like Meteor's collection.findOne
* @param [autoClientSave=true] - By default, changes in the Angular object will automatically update the Meteor object.
* - However if set to false, changes in the client won't be automatically propagated back to the Meteor object.
*/
object<T>(collection: Mongo.Collection<T>, selector: Mongo.Selector|Mongo.ObjectID|string, autoClientSave?: boolean): AngularMeteorObject<T>;
/**
* A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready.
*
* @param name - Name of the subscription. Matches the name of the server's publish() call.
* @param publisherArguments - Optional arguments passed to publisher function on server.
*
* @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle.
*/
subscribe(name: string, ...publisherArguments: any[]): angular.IPromise<Meteor.SubscriptionHandle>;
/**
* A service service which wraps up Meteor.methods with AngularJS promises.
*
* @param name - Name of method to invoke
* @param methodArguments - Optional method arguments
*
* @return The promise solves successfully with the return value of the method or return reject with the error from the method.
*/
call<T>(name: string, ...methodArguments: any[]): angular.IPromise<T>;
// User Authentication BEGIN ->
/**
* Returns a promise fulfilled with the currentUser when the user subscription is ready.
* This is useful when you want to grab the current user before the route is rendered.
* If there is no logged in user, it will return null.
* See the “Authentication with Routers” section of our tutorial for more information and a full example.
*/
waitForUser(): angular.IPromise<Meteor.User>;
/**
* Resolves the promise successfully if a user is authenticated and rejects otherwise.
* This is useful in cases where you want to require a route to have an authenticated user.
* You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page.
* See the “Authentication with Routers” section of our tutorial for more information and a full example.
*/
requireUser(): angular.IPromise<Meteor.User>;
/**
* Resolves the promise successfully if a user is authenticated and the validatorFn returns true; rejects otherwise.
* This is useful in cases where you want to require a route to have an authenticated user and do extra validation like the user's role or group.
* You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page.
* See the “Authentication with Routers” section of our tutorial for more information and a full example.
*
* The mandatory validator function will be called with the authenticated user as the single param and it's expected to return true in order to resolve.
* If it returns a string, the promise will be rejected using said string as the reason.
* Any other return (false, null, undefined) will be rejected with the default "FORBIDDEN" reason.
*/
requireValidUser(validatorFn: (user: Meteor.User) => boolean|string): angular.IPromise<Meteor.User>;
/**
* Log the user in with a password.
*
* @param user - Either a string interpreted as a username or an email; or an object with a single key: email, username or id.
* @param password - The user's password.
*/
loginWithPassword(user: string|{email: string}|{username: string}|{id: string}, password: string): angular.IPromise<void>;
/**
* Create a new user. More information: http://docs.meteor.com/#/full/accounts_createuser
*
* @param options.username - A unique name for this user. Either this, or email is required.
* @param options.email - The user's email address. Either this, or username is required.
* @param options.password - The user's password. This is not sent in plain text over the wire.
* @param options.profile - The user's profile, typically including the name field.
*/
createUser(options: {username?: string; email?: string; password: string; profile?: Object}): angular.IPromise<void>;
/**
* Change the current user's password. Must be logged in.
*
* @param oldPassword - The user's current password. This is not sent in plain text over the wire.
* @param newPassword - A new password for the user. This is not sent in plain text over the wire.
*/
changePassword(oldPassword: string, newPassword: string): angular.IPromise<void>;
/**
* Request a forgot password email.
*
* @param options.email - The email address to send a password reset link.
*/
forgotPassword(options: {email: string}): angular.IPromise<void>;
/**
* Reset the password for a user using a token received in email. Logs the user in afterwards.
*
* @param token - The token retrieved from the reset password URL.
* @param newPassword - A new password for the user. This is not sent in plain text over the wire.
*/
resetPassword(token: string, newPassword: string): angular.IPromise<void>;
/**
* Marks the user's email address as verified. Logs the user in afterwards.
*
* @param token - The token retrieved from the reset password URL.
*/
verifyEmail(token: string): angular.IPromise<void>;
loginWithFacebook: ILoginWithExternalService;
loginWithTwitter: ILoginWithExternalService;
loginWithGoogle: ILoginWithExternalService;
loginWithGithub: ILoginWithExternalService;
loginWithMeetup: ILoginWithExternalService;
loginWithWeibo: ILoginWithExternalService;
/**
* Log the user out.
*
* @return Resolves with no arguments on success, or reject with a Error argument on failure.
*/
logout(): angular.IPromise<void>;
/**
* Log out other clients logged in as the current user, but does not log out the client that calls this function.
* For example, when called in a user's browser, connections in that browser remain logged in,
* but any other browsers or DDP clients logged in as that user will be logged out.
*
* @return Resolves with no arguments on success, or reject with a Error argument on failure.
*/
logoutOtherClients(): angular.IPromise<void>;
// <- User Authentication END
// $meteorUtils BEGIN ->
/**
* @param scope - The AngularJS scope you use the autorun on.
* @param fn - The function that will re-run every time a reactive variable changes inside it.
*/
autorun(scope: angular.IScope, fn: Function): void;
/**
* @param collectionName - The name of the collection you want to get back
*/
getCollectionByName<T>(collectionName: string): Mongo.Collection<T>;
// <- $meteorUtils END
// $meteorCamera BEGIN ->
/**
* A helper service for taking pictures across platforms.
* Must add mdg:camera package to use! (meteor add mdg:camera)
*
* @param [options] - options is an optional argument that is an Object with the following possible keys:
* @param options.width - An integer that specifies the minimum width of the returned photo.
* @param options.height - An integer that specifies the minimum height of the returned photo.
* @param options.quality - A number from 0 to 100 specifying the desired quality of JPEG encoding.
*
* @return The promise solved successfully when the picture is taken with the data as a parameter or rejected with an error as a parameter in case of error.
*/
getPicture(options?: {width?: number; height?: number; quality?: number}): angular.IPromise<any>;
// <- $meteorCamera END
/**
* A service that binds a scope variable to a Meteor Session variable.
*
* @param sessionKey - The name of the session variable
* @return An object with a single function bind - to bind to that variable.
*/
session(sessionKey: string): {
/**
* @param scope - The scope the document will be bound to.
* @param model - The name of the scope's model variable that the document will be bound to.
*/
bind: (scope: IScope, model: string) => void;
};
}
/**
* An object that connects a Meteor Object to an AngularJS scope variable.
*
* The object contains also all the properties from the generic type T,
* unfortunately TypeScript doesn't at the moment allow to extend a generic type (see https://github.com/Microsoft/TypeScript/issues/2225 for details and updates).
* For a workaround, you'll need to implement an interface which will merge AngularMeteorObject<T> together with T and cast it, like this:
*
* interface TodoAngularMeteorObject extends ITodo, AngularMeteorObject<ITodo> { }
* var todo = <TodoAngularMeteorObject>$meteor.object(TodoCollection, 'TodoID');
*/
interface AngularMeteorObject<T> {
/**
* @param [doc] - The doc to save to the Meteor Object. If nothing is passed, the method saves everything in the AngularMeteorObject as is.
* - Unchanged properties will be overridden with their existing values, which may trigger hooks.
* - If doc is passed, the method only updates the Meteor Object with the properties passed, and no other changes will be saved.
*
* @return Returns a promise with an error in case for an error or a number of successful docs changed in case of success.
*/
save(doc?: T): angular.IPromise<number>;
/**
* Reset the current value of the object to the one in the server.
*/
reset(): void;
/**
* Returns a copy of the AngularMeteorObject with all the AngularMeteor-specific internal properties removed.
* The returned object is then safe to use as a parameter for method calls, or anywhere else where the data needs to be converted to JSON.
*/
getRawObject(): T;
/**
* A shorten (Syntactic sugar) function for the $meteor.subscribe function.
* Takes only one parameter and not returns a promise like $meteor.subscribe does.
*
* @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service.
*/
subscribe(subscriptionName:string): AngularMeteorObject<T>;
}
/**
* An object that connects a Meteor Collection to an AngularJS scope variable
*/
interface AngularMeteorCollection<T> extends AngularMeteorCollection2<T, T> { }
/**
* An object that connects a Meteor Collection to an AngularJS scope variable,
* but can use a differen type for updates.
*/
interface AngularMeteorCollection2<T, U> extends Array<T> {
/**
* @param [docs] - The docs to save to the Meteor Collection.
* - If the docs parameter is empty, the method saves everything in the AngularMeteorCollection as is.
* - If an object is passed, the method pushes that object into the AngularMeteorCollection.
* - If an array is passed, the method pushes all objects in the array into the AngularMeteorCollection.
*/
save(docs?: U|U[]): void;
/**
* @param [keys] - The keys of the object to remove from the Meteor Collection.
* - If nothing is passed, the method removes all the documents from the AngularMeteorCollection.
* - If an object is passed, the method removes the object with that key from the AngularMeteorCollection.
* - If an array is passed, the method removes all objects that matches the keys in the array from the AngularMeteorCollection.
*/
remove(keys?: U|string|number|string[]|number[]): void;
/**
* A shorten (Syntactic sugar) function for the $meteor.subscribe function.
* Takes only one parameter and not returns a promise like $meteor.subscribe does.
*
* @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service.
*/
subscribe(subscriptionName:string): AngularMeteorCollection2<T, U>;
}
interface ILoginWithExternalService {
(options: Meteor.LoginWithExternalServiceOptions): angular.IPromise<void>;
}
interface ReactiveResult { }
}
// Type definitions for Angular JS Meteor v0.8.8 (angular.meteor module)
// Project: https://github.com/Urigo/angular-meteor
// Definitions by: Peter Grman <https://github.com/pgrm>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../meteor/meteor.d.ts" />
/// <reference path="../angularjs/angular.d.ts" />
declare module angular.meteor {
interface IRootScopeService extends angular.IRootScopeService {
/**
* The current logged in user and it's data. it is null if the user is not logged in. A reactive data source.
*/
currentUser: Meteor.User;
/**
* True if a login method (such as Meteor.loginWithPassword, Meteor.loginWithFacebook, or Accounts.createUser) is currently in progress.
* A reactive data source. Can be use to display animation while user is logging in.
*/
loggingIn: boolean;
}
interface IScope extends angular.IScope, IRootScopeService {
/**
* A method to get a $scope variable and watch it reactivly
*
* @param scopeVariableName - The name of the scope's variable to bind to
* @param [objectEquality=false] - Watch the object equality using angular.equals instead of comparing for reference equality, deeper watch but also slower
*/
getReactively(scopeVariableName: string, objectEquality?: boolean): ReactiveResult;
/**
* A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready.
* Calling $scope.subscribe will automatically stop the subscription when the scope is destroyed.
*
* @param name - Name of the subscription. Matches the name of the server's publish() call.
* @param publisherArguments - Optional arguments passed to publisher function on server.
*
* @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle.
*/
subscribe(name: string, ...publisherArguments: any[]): angular.IPromise<Meteor.SubscriptionHandle>;
/**
* The helpers method is part of the ReactiveContext, and available on every context and $scope.
* These method are defined as Object, where each key is the name of the variable that will be available on the context we run, and each value is a function with a return value.
* Under the hood, each helper starts a new Tracker.autorun. When its reactive dependencies change, the helper is rerun.
* To trigger a rerun every time an specific Angular variable change, use getReactively](/api/1.3.1/get-reactively) to make your Angular variable reactive inside the helper its used in.
* Each helper function should return a MongoDB Cursor and the helpers will expose it as a normal array to the context.
*
* @param definitions - Object containing `name` => `function` definition, where each name is a string and each function is the helper function. Should return a [MongoDB Cursor](http://docs.meteor.com/#/full/mongo_cursor)
* @return This method returns this, which the the reactive context, in order to provide the ability to chain the logic.
*/
helpers(definitions : { [helperName : string] : () => Mongo.Cursor<any> }): IScope;
/**
* This method is a wrapper of Tracker.autorun and shares exactly the same API.
* The autorun method is part of the ReactiveContext, and available on every context and $scope.
* The argument of this method is a callback, which will be called each time Autorun will be used.
* The Autorun will stop automatically when when it's context ($scope) is destroyed.
*
* @param runFunc - The function to run. It receives one argument: the Computation object that will be returned.
*/
autorun(runFunc : () => void) : Tracker.Computation;
}
/**
* $meteor in angularjs
*/
interface IMeteorService {
/**
* A service that wraps the Meteor collections to enable reactivity within AngularJS.
*
* @param collection - A Meteor Collection or a reactive function to bind to.
* - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor.
* @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection.
* - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection.
*/
collection<T>(collection: Mongo.Collection<T>|ReactiveResult|Function|(()=>T), autoClientSave?: boolean): AngularMeteorCollection<T>;
/**
* A service that wraps the Meteor collections to enable reactivity within AngularJS.
*
* @param collection - A Meteor Collection or a reactive function to bind to.
* - Reactive function can be used with $scope.getReactively to add $scope variable as reactive variable to the cursor.
* @param [autoClientSave=true] - By default, changes in the Angular collection will automatically update the Meteor collection.
* - However if set to false, changes in the client won't be automatically propagated back to the Meteor collection.
* @param [updateCollection] - A collection object which will be used for updates (insert, update, delete).
*/
collection<T, U>(collection: Mongo.Collection<T>|ReactiveResult|Function|(()=>T), autoClientSave: boolean, updateCollection: Mongo.Collection<U>): AngularMeteorCollection2<T, U>;
/**
* A service that wraps a Meteor object to enable reactivity within AngularJS.
* Finds the first document that matches the selector, as ordered by sort and skip options. Wraps collection.findOne
*
* @param collection - A Meteor Collection to bind to.
* @param selector - A query describing the documents to find or just the ID of the document.
* - $meteor.object will find the first document that matches the selector,
* - as ordered by sort and skip options, exactly like Meteor's collection.findOne
* @param [autoClientSave=true] - By default, changes in the Angular object will automatically update the Meteor object.
* - However if set to false, changes in the client won't be automatically propagated back to the Meteor object.
*/
object<T>(collection: Mongo.Collection<T>, selector: Mongo.Selector|Mongo.ObjectID|string, autoClientSave?: boolean): AngularMeteorObject<T>;
/**
* A service which is a wrapper for Meteor.subscribe. It subscribes to a Meteor.publish method in the client and returns a AngularJS promise when ready.
*
* @param name - Name of the subscription. Matches the name of the server's publish() call.
* @param publisherArguments - Optional arguments passed to publisher function on server.
*
* @return The promise solved successfully when subscription is ready. The success promise holds the subscription handle.
*/
subscribe(name: string, ...publisherArguments: any[]): angular.IPromise<Meteor.SubscriptionHandle>;
/**
* A service service which wraps up Meteor.methods with AngularJS promises.
*
* @param name - Name of method to invoke
* @param methodArguments - Optional method arguments
*
* @return The promise solves successfully with the return value of the method or return reject with the error from the method.
*/
call<T>(name: string, ...methodArguments: any[]): angular.IPromise<T>;
// User Authentication BEGIN ->
/**
* Returns a promise fulfilled with the currentUser when the user subscription is ready.
* This is useful when you want to grab the current user before the route is rendered.
* If there is no logged in user, it will return null.
* See the “Authentication with Routers” section of our tutorial for more information and a full example.
*/
waitForUser(): angular.IPromise<Meteor.User>;
/**
* Resolves the promise successfully if a user is authenticated and rejects otherwise.
* This is useful in cases where you want to require a route to have an authenticated user.
* You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page.
* See the “Authentication with Routers” section of our tutorial for more information and a full example.
*/
requireUser(): angular.IPromise<Meteor.User>;
/**
* Resolves the promise successfully if a user is authenticated and the validatorFn returns true; rejects otherwise.
* This is useful in cases where you want to require a route to have an authenticated user and do extra validation like the user's role or group.
* You can catch the rejected promise and redirect the unauthenticated user to a different page, such as the login page.
* See the “Authentication with Routers” section of our tutorial for more information and a full example.
*
* The mandatory validator function will be called with the authenticated user as the single param and it's expected to return true in order to resolve.
* If it returns a string, the promise will be rejected using said string as the reason.
* Any other return (false, null, undefined) will be rejected with the default "FORBIDDEN" reason.
*/
requireValidUser(validatorFn: (user: Meteor.User) => boolean|string): angular.IPromise<Meteor.User>;
/**
* Log the user in with a password.
*
* @param user - Either a string interpreted as a username or an email; or an object with a single key: email, username or id.
* @param password - The user's password.
*/
loginWithPassword(user: string|{email: string}|{username: string}|{id: string}, password: string): angular.IPromise<void>;
/**
* Create a new user. More information: http://docs.meteor.com/#/full/accounts_createuser
*
* @param options.username - A unique name for this user. Either this, or email is required.
* @param options.email - The user's email address. Either this, or username is required.
* @param options.password - The user's password. This is not sent in plain text over the wire.
* @param options.profile - The user's profile, typically including the name field.
*/
createUser(options: {username?: string; email?: string; password: string; profile?: Object}): angular.IPromise<void>;
/**
* Change the current user's password. Must be logged in.
*
* @param oldPassword - The user's current password. This is not sent in plain text over the wire.
* @param newPassword - A new password for the user. This is not sent in plain text over the wire.
*/
changePassword(oldPassword: string, newPassword: string): angular.IPromise<void>;
/**
* Request a forgot password email.
*
* @param options.email - The email address to send a password reset link.
*/
forgotPassword(options: {email: string}): angular.IPromise<void>;
/**
* Reset the password for a user using a token received in email. Logs the user in afterwards.
*
* @param token - The token retrieved from the reset password URL.
* @param newPassword - A new password for the user. This is not sent in plain text over the wire.
*/
resetPassword(token: string, newPassword: string): angular.IPromise<void>;
/**
* Marks the user's email address as verified. Logs the user in afterwards.
*
* @param token - The token retrieved from the reset password URL.
*/
verifyEmail(token: string): angular.IPromise<void>;
loginWithFacebook: ILoginWithExternalService;
loginWithTwitter: ILoginWithExternalService;
loginWithGoogle: ILoginWithExternalService;
loginWithGithub: ILoginWithExternalService;
loginWithMeetup: ILoginWithExternalService;
loginWithWeibo: ILoginWithExternalService;
/**
* Log the user out.
*
* @return Resolves with no arguments on success, or reject with a Error argument on failure.
*/
logout(): angular.IPromise<void>;
/**
* Log out other clients logged in as the current user, but does not log out the client that calls this function.
* For example, when called in a user's browser, connections in that browser remain logged in,
* but any other browsers or DDP clients logged in as that user will be logged out.
*
* @return Resolves with no arguments on success, or reject with a Error argument on failure.
*/
logoutOtherClients(): angular.IPromise<void>;
// <- User Authentication END
// $meteorUtils BEGIN ->
/**
* @param scope - The AngularJS scope you use the autorun on.
* @param fn - The function that will re-run every time a reactive variable changes inside it.
*/
autorun(scope: angular.IScope, fn: Function): void;
/**
* @param collectionName - The name of the collection you want to get back
*/
getCollectionByName<T>(collectionName: string): Mongo.Collection<T>;
// <- $meteorUtils END
// $meteorCamera BEGIN ->
/**
* A helper service for taking pictures across platforms.
* Must add mdg:camera package to use! (meteor add mdg:camera)
*
* @param [options] - options is an optional argument that is an Object with the following possible keys:
* @param options.width - An integer that specifies the minimum width of the returned photo.
* @param options.height - An integer that specifies the minimum height of the returned photo.
* @param options.quality - A number from 0 to 100 specifying the desired quality of JPEG encoding.
*
* @return The promise solved successfully when the picture is taken with the data as a parameter or rejected with an error as a parameter in case of error.
*/
getPicture(options?: {width?: number; height?: number; quality?: number}): angular.IPromise<any>;
// <- $meteorCamera END
/**
* A service that binds a scope variable to a Meteor Session variable.
*
* @param sessionKey - The name of the session variable
* @return An object with a single function bind - to bind to that variable.
*/
session(sessionKey: string): {
/**
* @param scope - The scope the document will be bound to.
* @param model - The name of the scope's model variable that the document will be bound to.
*/
bind: (scope: IScope, model: string) => void;
};
}
/**
* An object that connects a Meteor Object to an AngularJS scope variable.
*
* The object contains also all the properties from the generic type T,
* unfortunately TypeScript doesn't at the moment allow to extend a generic type (see https://github.com/Microsoft/TypeScript/issues/2225 for details and updates).
* For a workaround, you'll need to implement an interface which will merge AngularMeteorObject<T> together with T and cast it, like this:
*
* interface TodoAngularMeteorObject extends ITodo, AngularMeteorObject<ITodo> { }
* var todo = <TodoAngularMeteorObject>$meteor.object(TodoCollection, 'TodoID');
*/
interface AngularMeteorObject<T> {
/**
* @param [doc] - The doc to save to the Meteor Object. If nothing is passed, the method saves everything in the AngularMeteorObject as is.
* - Unchanged properties will be overridden with their existing values, which may trigger hooks.
* - If doc is passed, the method only updates the Meteor Object with the properties passed, and no other changes will be saved.
*
* @return Returns a promise with an error in case for an error or a number of successful docs changed in case of success.
*/
save(doc?: T): angular.IPromise<number>;
/**
* Reset the current value of the object to the one in the server.
*/
reset(): void;
/**
* Returns a copy of the AngularMeteorObject with all the AngularMeteor-specific internal properties removed.
* The returned object is then safe to use as a parameter for method calls, or anywhere else where the data needs to be converted to JSON.
*/
getRawObject(): T;
/**
* A shorten (Syntactic sugar) function for the $meteor.subscribe function.
* Takes only one parameter and not returns a promise like $meteor.subscribe does.
*
* @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service.
*/
subscribe(subscriptionName:string): AngularMeteorObject<T>;
}
/**
* An object that connects a Meteor Collection to an AngularJS scope variable
*/
interface AngularMeteorCollection<T> extends AngularMeteorCollection2<T, T> { }
/**
* An object that connects a Meteor Collection to an AngularJS scope variable,
* but can use a differen type for updates.
*/
interface AngularMeteorCollection2<T, U> extends Array<T> {
/**
* @param [docs] - The docs to save to the Meteor Collection.
* - If the docs parameter is empty, the method saves everything in the AngularMeteorCollection as is.
* - If an object is passed, the method pushes that object into the AngularMeteorCollection.
* - If an array is passed, the method pushes all objects in the array into the AngularMeteorCollection.
*/
save(docs?: U|U[]): void;
/**
* @param [keys] - The keys of the object to remove from the Meteor Collection.
* - If nothing is passed, the method removes all the documents from the AngularMeteorCollection.
* - If an object is passed, the method removes the object with that key from the AngularMeteorCollection.
* - If an array is passed, the method removes all objects that matches the keys in the array from the AngularMeteorCollection.
*/
remove(keys?: U|string|number|string[]|number[]): void;
/**
* A shorten (Syntactic sugar) function for the $meteor.subscribe function.
* Takes only one parameter and not returns a promise like $meteor.subscribe does.
*
* @param subscriptionName - The subscription name to subscribe to. Exactly like the first parameter in $meteor.subscribe service.
*/
subscribe(subscriptionName:string): AngularMeteorCollection2<T, U>;
}
interface ILoginWithExternalService {
(options: Meteor.LoginWithExternalServiceOptions): angular.IPromise<void>;
}
interface ReactiveResult { }
}

View File

@@ -1,230 +1,230 @@
# AngularJS Definitions Usage Notes
## Referencing AngularJS definition files in your code
To do that, simply add `/// <reference path="angular.d.ts" />` at the top of your code.
That will make available to your code all interfaces AngularJS' main module **ng** implements, as well as the **AUTO** module.
If you are including other AngularJS' modules in your code, like **ngResource**, just like you needed to include the additional module implementation file in your code, _angular-resource.js_, you will also need to reference the definitions file related to that module. Your code would then have the following definitions files reference:
/// <reference path="angular.d.ts" />
/// <reference path="angular-resource.d.ts" />
Having these modules in separated files is actually good because they sometimes either augment or modify some of **ng**'s interfaces, and thus those differences should only be available to you when you really need them. Also, it forces you to explicit what you're going to be using.
The following extra definition files are available for referencing:
* angular-resource.d.ts (for the **ngResource** module)
* angular-route.d.ts (for the **ngRoute** module)
* angular-cookies.d.ts (for the **ngCookies** module)
* angular-sanitize.d.ts (for the **ngSanitize** module)
* angular-mocks.d.ts (for the **ngMock** and **ngMockE2E** modules)
(postfix with version number for specific verion, eg. angular-resource-1.0.d.ts)
## The Angular Static
The definitions declare the AngularJS static variable `angular` as ambient. That means that, after referencing the AngularJS definition, you will be able to get type checks and code assistance for the global `angular` member.
## Definitions modularized
To avoid cluttering the list of suggestions as you type in your IDE, all interfaces reside in their respective module namespace:
* `ng` for AngularJS' **ng** module
* `ng.auto` for **AUTO**
* `ng.cookies` for **ngCookies**
* `ng.mock` for **ngMock**
* `ng.resource` for **ngResource**
* `ng.route` for **ngRoute**
* `ng.sanitize` for **ngSanitize**
**ngMockE2E** does not define a new namespace, but rather modifies some of **ng**'s interfaces.
Below is an example of how to use the interfaces:
```ts
function MainController($scope: ng.IScope, $http: ng.IHttpService) {
// code assistance will now be available for $scope and $http
}
```
## Services and other injectables
AngularJS makes vast use of what it calls "injectable" functions. To put it simple, in AngularJS you are constantly annotating your functions and constructors with their dependencies, services that are going to be provided as arguments automagically during invocation.
All known services interfaces have been defined, and were named using the following convention:
**I + 'ServiceName' + 'Service'**
So, for instance, the **$parse** service has it's interface defined as **ng.IParseService**.
Service providers, by the same logic, follow this convention:
**I + 'ServiceName' + 'Provider'**
The **$httpProvider**, thus, is defined by **ng.IHttpProvider**.
## A word on $scope and assigning new members
TypeScript allows for static checking. Among other obvious things, that means you're gonna have to extend interfaces when you need to augment an object whose interface has been defined, because otherwise the compiler will see it as an error to try to assign a value to a unspecified member.
Consider the following ordinary code:
```ts
function Controller($scope) {
$scope.$broadcast('myEvent');
$scope.title = 'Yabadabadu';
}
```
That will not produce any compilation error because the compiler does not know the first thing about $scope to do any checking. For that same reason, you will not get any assistance either.
Now consider this:
```ts
function Controller($scope: ng.IScope) {
$scope.$broadcast('myEvent');
$scope.title = 'Yabadabadu';
}
```
Now we annotated `$scope` with the interface `ng.IScope`. The compiler now knows that, among other members, `$scope` has a method called `$broadcast`. That interface, however, does not define a `title` property. The compiler will complain about it.
Since you are augmenting the $scope object, you should let the compiler know what to expect then:
```ts
interface ICustomScope extends ng.IScope {
title: string;
}
function Controller($scope: ICustomScope) {
$scope.$broadcast('myEvent');
$scope.title = 'Yabadabadu';
}
```
## Examples
### Working with $resource
```ts
/// <reference path="angular.d.ts" />
/// <reference path="angular-resource.d.ts" />
// We have the option to define arguments for a custom resource
interface IArticleParameters {
id: number;
}
interface IArticleResource extends ng.resource.IResource<IArticleResource> {
title: string;
text: string;
date: Date;
author: number;
// Although all actions defined on IArticleResourceClass are avaiable with
// the '$' prefix, we have the choice to expose only what we will use
$publish(): IArticleResource;
$unpublish(): IArticleResource;
}
// Let's define a custom resource
interface IArticleResourceClass extends ng.resource.IResourceClass<IArticleResource> {
// Overload get to accept our custom parameters
get(): ng.resource.IResource;
get(params: IArticleParameters, onSuccess: Function): IArticleResource;
// Add our custom resource actions
publish(): IArticleResource;
publish(params: IArticleParameters): IArticleResource;
unpublish(params: IArticleParameters): IArticleResource;
}
function MainController($resource: ng.resource.IResourceService) {
// IntelliSense will provide IActionDescriptor interface and will validate
// your assignment against it
var publishDescriptor: ng.resource.IActionDescriptor;
publishDescriptor = {
method: 'GET',
isArray: false
};
// I could still create a descriptor without the interface...
var unpublishDescriptor = {
method: 'POST'
}
// A call to the $resource service returns a IResourceClass. Since
// our own IArticleResourceClass defines 2 more actions, we cast the return
// value to make the compiler aware of that
var articleResource = $resource<IArticleResource, IArticleResourceClass>('/articles/:id', null, {
publish : publishDescriptor,
unpublish : unpublishDescriptor
});
// Now we can do this
articleResource.unpublish({ id: 1 });
// IResourceClass.get() will be automatically available here
var article: IArticleResource = articleResource.get({id: 1}, function success() {
// Again, default + custom action here...
article.title = 'New Title';
article.$save();
article.$publish();
});
}
```
### Working with $resource in angular-1.0 definitions
```ts
/// <reference path="angular-1.0.d.ts" />
/// <reference path="angular-resource-1.0.d.ts" />
// Let's define a custom resource
interface IArticleResourceClass extends ng.resource.IResourceClass {
publish: ng.resource.IActionCall;
unpublish: ng.resource.IActionCall;
}
interface IArticleResource extends ng.resource.IResource {
title: string;
text: string;
date: Date;
author: number;
$publish: ng.resource.IActionCall;
$unpublish: ng.resource.IActionCall;
}
function MainController($resource: ng.resource.IResourceService) {
// IntelliSense will provide IActionDescriptor interface and will validate
// your assignment against it
var publishDescriptor: ng.resource.IActionDescriptor;
publishDescriptor = {
method: 'GET',
isArray: false
};
// I could still create a descriptor without the interface...
var unpublishDescriptor = {
method: 'POST'
}
// A call to the $resource service returns a IResourceClass. Since
// our own IArticleResourceClass defines 2 more actions, we cast the return
// value to make the compiler aware of that
var articles = <IArticleResourceClass> $resource('/articles/:id', null, {
publish : publishDescriptor,
unpublish : unpublishDescriptor
});
// Now we can do this
articles.unpublish({ id: 1 });
// IResourceClass.get() will be automatically available here
var article = <IArticleResource> articles.get({id: 1});
// Again, default + custom action here...
article.title = 'New Title';
article.$save();
article.$publish();
}
```
# AngularJS Definitions Usage Notes
## Referencing AngularJS definition files in your code
To do that, simply add `/// <reference path="angular.d.ts" />` at the top of your code.
That will make available to your code all interfaces AngularJS' main module **ng** implements, as well as the **AUTO** module.
If you are including other AngularJS' modules in your code, like **ngResource**, just like you needed to include the additional module implementation file in your code, _angular-resource.js_, you will also need to reference the definitions file related to that module. Your code would then have the following definitions files reference:
/// <reference path="angular.d.ts" />
/// <reference path="angular-resource.d.ts" />
Having these modules in separated files is actually good because they sometimes either augment or modify some of **ng**'s interfaces, and thus those differences should only be available to you when you really need them. Also, it forces you to explicit what you're going to be using.
The following extra definition files are available for referencing:
* angular-resource.d.ts (for the **ngResource** module)
* angular-route.d.ts (for the **ngRoute** module)
* angular-cookies.d.ts (for the **ngCookies** module)
* angular-sanitize.d.ts (for the **ngSanitize** module)
* angular-mocks.d.ts (for the **ngMock** and **ngMockE2E** modules)
(postfix with version number for specific verion, eg. angular-resource-1.0.d.ts)
## The Angular Static
The definitions declare the AngularJS static variable `angular` as ambient. That means that, after referencing the AngularJS definition, you will be able to get type checks and code assistance for the global `angular` member.
## Definitions modularized
To avoid cluttering the list of suggestions as you type in your IDE, all interfaces reside in their respective module namespace:
* `ng` for AngularJS' **ng** module
* `ng.auto` for **AUTO**
* `ng.cookies` for **ngCookies**
* `ng.mock` for **ngMock**
* `ng.resource` for **ngResource**
* `ng.route` for **ngRoute**
* `ng.sanitize` for **ngSanitize**
**ngMockE2E** does not define a new namespace, but rather modifies some of **ng**'s interfaces.
Below is an example of how to use the interfaces:
```ts
function MainController($scope: ng.IScope, $http: ng.IHttpService) {
// code assistance will now be available for $scope and $http
}
```
## Services and other injectables
AngularJS makes vast use of what it calls "injectable" functions. To put it simple, in AngularJS you are constantly annotating your functions and constructors with their dependencies, services that are going to be provided as arguments automagically during invocation.
All known services interfaces have been defined, and were named using the following convention:
**I + 'ServiceName' + 'Service'**
So, for instance, the **$parse** service has it's interface defined as **ng.IParseService**.
Service providers, by the same logic, follow this convention:
**I + 'ServiceName' + 'Provider'**
The **$httpProvider**, thus, is defined by **ng.IHttpProvider**.
## A word on $scope and assigning new members
TypeScript allows for static checking. Among other obvious things, that means you're gonna have to extend interfaces when you need to augment an object whose interface has been defined, because otherwise the compiler will see it as an error to try to assign a value to a unspecified member.
Consider the following ordinary code:
```ts
function Controller($scope) {
$scope.$broadcast('myEvent');
$scope.title = 'Yabadabadu';
}
```
That will not produce any compilation error because the compiler does not know the first thing about $scope to do any checking. For that same reason, you will not get any assistance either.
Now consider this:
```ts
function Controller($scope: ng.IScope) {
$scope.$broadcast('myEvent');
$scope.title = 'Yabadabadu';
}
```
Now we annotated `$scope` with the interface `ng.IScope`. The compiler now knows that, among other members, `$scope` has a method called `$broadcast`. That interface, however, does not define a `title` property. The compiler will complain about it.
Since you are augmenting the $scope object, you should let the compiler know what to expect then:
```ts
interface ICustomScope extends ng.IScope {
title: string;
}
function Controller($scope: ICustomScope) {
$scope.$broadcast('myEvent');
$scope.title = 'Yabadabadu';
}
```
## Examples
### Working with $resource
```ts
/// <reference path="angular.d.ts" />
/// <reference path="angular-resource.d.ts" />
// We have the option to define arguments for a custom resource
interface IArticleParameters {
id: number;
}
interface IArticleResource extends ng.resource.IResource<IArticleResource> {
title: string;
text: string;
date: Date;
author: number;
// Although all actions defined on IArticleResourceClass are avaiable with
// the '$' prefix, we have the choice to expose only what we will use
$publish(): IArticleResource;
$unpublish(): IArticleResource;
}
// Let's define a custom resource
interface IArticleResourceClass extends ng.resource.IResourceClass<IArticleResource> {
// Overload get to accept our custom parameters
get(): ng.resource.IResource;
get(params: IArticleParameters, onSuccess: Function): IArticleResource;
// Add our custom resource actions
publish(): IArticleResource;
publish(params: IArticleParameters): IArticleResource;
unpublish(params: IArticleParameters): IArticleResource;
}
function MainController($resource: ng.resource.IResourceService) {
// IntelliSense will provide IActionDescriptor interface and will validate
// your assignment against it
var publishDescriptor: ng.resource.IActionDescriptor;
publishDescriptor = {
method: 'GET',
isArray: false
};
// I could still create a descriptor without the interface...
var unpublishDescriptor = {
method: 'POST'
}
// A call to the $resource service returns a IResourceClass. Since
// our own IArticleResourceClass defines 2 more actions, we cast the return
// value to make the compiler aware of that
var articleResource = $resource<IArticleResource, IArticleResourceClass>('/articles/:id', null, {
publish : publishDescriptor,
unpublish : unpublishDescriptor
});
// Now we can do this
articleResource.unpublish({ id: 1 });
// IResourceClass.get() will be automatically available here
var article: IArticleResource = articleResource.get({id: 1}, function success() {
// Again, default + custom action here...
article.title = 'New Title';
article.$save();
article.$publish();
});
}
```
### Working with $resource in angular-1.0 definitions
```ts
/// <reference path="angular-1.0.d.ts" />
/// <reference path="angular-resource-1.0.d.ts" />
// Let's define a custom resource
interface IArticleResourceClass extends ng.resource.IResourceClass {
publish: ng.resource.IActionCall;
unpublish: ng.resource.IActionCall;
}
interface IArticleResource extends ng.resource.IResource {
title: string;
text: string;
date: Date;
author: number;
$publish: ng.resource.IActionCall;
$unpublish: ng.resource.IActionCall;
}
function MainController($resource: ng.resource.IResourceService) {
// IntelliSense will provide IActionDescriptor interface and will validate
// your assignment against it
var publishDescriptor: ng.resource.IActionDescriptor;
publishDescriptor = {
method: 'GET',
isArray: false
};
// I could still create a descriptor without the interface...
var unpublishDescriptor = {
method: 'POST'
}
// A call to the $resource service returns a IResourceClass. Since
// our own IArticleResourceClass defines 2 more actions, we cast the return
// value to make the compiler aware of that
var articles = <IArticleResourceClass> $resource('/articles/:id', null, {
publish : publishDescriptor,
unpublish : unpublishDescriptor
});
// Now we can do this
articles.unpublish({ id: 1 });
// IResourceClass.get() will be automatically available here
var article = <IArticleResource> articles.get({id: 1});
// Again, default + custom action here...
article.title = 'New Title';
article.$save();
article.$publish();
}
```

View File

@@ -1,91 +1,91 @@
// Type definitions for Angular JS 1.4 (ngCookies module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Anthony Ciccarello <http://github.com/aciccarello>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
declare module "angular-cookies" {
var _: string;
export = _;
}
/**
* ngCookies module (angular-cookies.js)
*/
declare module angular.cookies {
/**
* Cookies options
* see https://docs.angularjs.org/api/ngCookies/provider/$cookiesProvider#defaults
*/
interface ICookiesOptions {
/**
* The cookie will be available only for this path and its sub-paths.
* By default, this would be the URL that appears in your base tag.
*/
path?: string;
/**
* The cookie will be available only for this domain and its sub-domains.
* For obvious security reasons the user agent will not accept the cookie if the
* current domain is not a sub domain or equals to the requested domain.
*/
domain?: string;
/**
* String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" or a Date object
* indicating the exact date/time this cookie will expire.
*/
expires?: string|Date;
/**
* The cookie will be available only in secured connection.
*/
secure?: boolean;
}
/**
* CookieService
* see http://docs.angularjs.org/api/ngCookies.$cookies
*/
interface ICookiesService {
[index: string]: any;
}
/**
* CookieStoreService
* see http://docs.angularjs.org/api/ngCookies.$cookieStore
*/
interface ICookiesService {
get(key: string): string;
getObject(key: string): any;
getObject<T>(key: string): T;
getAll(): any;
put(key: string, value: string, options?: ICookiesOptions): void;
putObject(key: string, value: any, options?: ICookiesOptions): void;
remove(key: string, options?: ICookiesOptions): void;
}
/**
* CookieStoreService DEPRECATED
* see https://code.angularjs.org/1.2.26/docs/api/ngCookies/service/$cookieStore
*/
interface ICookieStoreService {
/**
* Returns the value of given cookie key
* @param key Id to use for lookup
*/
get(key: string): any;
/**
* Sets a value for given cookie key
* @param key Id for the value
* @param value Value to be stored
*/
put(key: string, value: any): void;
/**
* Remove given cookie
* @param key Id of the key-value pair to delete
*/
remove(key: string): void;
}
}
// Type definitions for Angular JS 1.4 (ngCookies module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Anthony Ciccarello <http://github.com/aciccarello>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
declare module "angular-cookies" {
var _: string;
export = _;
}
/**
* ngCookies module (angular-cookies.js)
*/
declare module angular.cookies {
/**
* Cookies options
* see https://docs.angularjs.org/api/ngCookies/provider/$cookiesProvider#defaults
*/
interface ICookiesOptions {
/**
* The cookie will be available only for this path and its sub-paths.
* By default, this would be the URL that appears in your base tag.
*/
path?: string;
/**
* The cookie will be available only for this domain and its sub-domains.
* For obvious security reasons the user agent will not accept the cookie if the
* current domain is not a sub domain or equals to the requested domain.
*/
domain?: string;
/**
* String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" or a Date object
* indicating the exact date/time this cookie will expire.
*/
expires?: string|Date;
/**
* The cookie will be available only in secured connection.
*/
secure?: boolean;
}
/**
* CookieService
* see http://docs.angularjs.org/api/ngCookies.$cookies
*/
interface ICookiesService {
[index: string]: any;
}
/**
* CookieStoreService
* see http://docs.angularjs.org/api/ngCookies.$cookieStore
*/
interface ICookiesService {
get(key: string): string;
getObject(key: string): any;
getObject<T>(key: string): T;
getAll(): any;
put(key: string, value: string, options?: ICookiesOptions): void;
putObject(key: string, value: any, options?: ICookiesOptions): void;
remove(key: string, options?: ICookiesOptions): void;
}
/**
* CookieStoreService DEPRECATED
* see https://code.angularjs.org/1.2.26/docs/api/ngCookies/service/$cookieStore
*/
interface ICookieStoreService {
/**
* Returns the value of given cookie key
* @param key Id to use for lookup
*/
get(key: string): any;
/**
* Sets a value for given cookie key
* @param key Id for the value
* @param value Value to be stored
*/
put(key: string, value: any): void;
/**
* Remove given cookie
* @param key Id of the key-value pair to delete
*/
remove(key: string): void;
}
}

View File

@@ -1,318 +1,318 @@
// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Tony Curtis <http://github.com/daltin>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
declare module "angular-mocks/ngMock" {
var _: string;
export = _;
}
declare module "angular-mocks/ngMockE2E" {
var _: string;
export = _;
}
declare module "angular-mocks/ngAnimateMock" {
var _: string;
export = _;
}
///////////////////////////////////////////////////////////////////////////////
// ngMock module (angular-mocks.js)
///////////////////////////////////////////////////////////////////////////////
declare module angular {
///////////////////////////////////////////////////////////////////////////
// AngularStatic
// We reopen it to add the MockStatic definition
///////////////////////////////////////////////////////////////////////////
interface IAngularStatic {
mock: IMockStatic;
}
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
interface IInjectStatic {
(...fns: Function[]): any;
(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
strictDi(val?: boolean): void;
}
interface IMockStatic {
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump
dump(obj: any): string;
inject: IInjectStatic
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
module(...modules: any[]): any;
// see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate
TzDate(offset: number, timestamp: number): Date;
TzDate(offset: number, timestamp: string): Date;
}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
// see https://docs.angularjs.org/api/ngMock/service/$exceptionHandler
// see https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider
///////////////////////////////////////////////////////////////////////////
interface IExceptionHandlerProvider extends IServiceProvider {
mode(mode: string): void;
}
///////////////////////////////////////////////////////////////////////////
// TimeoutService
// see https://docs.angularjs.org/api/ngMock/service/$timeout
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
flush(delay?: number): void;
flushNext(expectedDelay?: number): void;
verifyNoPendingTasks(): void;
}
///////////////////////////////////////////////////////////////////////////
// IntervalService
// see https://docs.angularjs.org/api/ngMock/service/$interval
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
flush(millis?: number): number;
}
///////////////////////////////////////////////////////////////////////////
// LogService
// see https://docs.angularjs.org/api/ngMock/service/$log
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ILogService {
assertEmpty(): void;
reset(): void;
}
interface ILogCall {
logs: string[];
}
///////////////////////////////////////////////////////////////////////////
// HttpBackendService
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
/**
* Flushes all pending requests using the trained responses.
* @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed.
*/
flush(count?: number): void;
/**
* Resets all request expectations, but preserves all backend definitions.
*/
resetExpectations(): void;
/**
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
*/
verifyNoOutstandingExpectation(): void;
/**
* Verifies that there are no outstanding requests that need to be flushed.
*/
verifyNoOutstandingRequest(): void;
/**
* Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)) :mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for HEAD requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
*/
expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
}
export module mock {
// returned interface by the the mocked HttpBackendService expect/when methods
interface IRequestHandler {
/**
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text.
*/
respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler;
/**
* Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
/**
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
// Available when ngMockE2E is loaded
/**
* Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)
*/
passThrough(): IRequestHandler;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// functions attached to global object (window)
///////////////////////////////////////////////////////////////////////////////
//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
//declare var module: (...modules: any[]) => any;
declare var inject: angular.IInjectStatic;
// Type definitions for Angular JS 1.3 (ngMock, ngMockE2E module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>, Tony Curtis <http://github.com/daltin>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
declare module "angular-mocks/ngMock" {
var _: string;
export = _;
}
declare module "angular-mocks/ngMockE2E" {
var _: string;
export = _;
}
declare module "angular-mocks/ngAnimateMock" {
var _: string;
export = _;
}
///////////////////////////////////////////////////////////////////////////////
// ngMock module (angular-mocks.js)
///////////////////////////////////////////////////////////////////////////////
declare module angular {
///////////////////////////////////////////////////////////////////////////
// AngularStatic
// We reopen it to add the MockStatic definition
///////////////////////////////////////////////////////////////////////////
interface IAngularStatic {
mock: IMockStatic;
}
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.inject
interface IInjectStatic {
(...fns: Function[]): any;
(...inlineAnnotatedConstructor: any[]): any; // this overload is undocumented, but works
strictDi(val?: boolean): void;
}
interface IMockStatic {
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.dump
dump(obj: any): string;
inject: IInjectStatic
// see https://docs.angularjs.org/api/ngMock/function/angular.mock.module
module(...modules: any[]): any;
// see https://docs.angularjs.org/api/ngMock/type/angular.mock.TzDate
TzDate(offset: number, timestamp: number): Date;
TzDate(offset: number, timestamp: string): Date;
}
///////////////////////////////////////////////////////////////////////////
// ExceptionHandlerService
// see https://docs.angularjs.org/api/ngMock/service/$exceptionHandler
// see https://docs.angularjs.org/api/ngMock/provider/$exceptionHandlerProvider
///////////////////////////////////////////////////////////////////////////
interface IExceptionHandlerProvider extends IServiceProvider {
mode(mode: string): void;
}
///////////////////////////////////////////////////////////////////////////
// TimeoutService
// see https://docs.angularjs.org/api/ngMock/service/$timeout
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ITimeoutService {
flush(delay?: number): void;
flushNext(expectedDelay?: number): void;
verifyNoPendingTasks(): void;
}
///////////////////////////////////////////////////////////////////////////
// IntervalService
// see https://docs.angularjs.org/api/ngMock/service/$interval
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface IIntervalService {
flush(millis?: number): number;
}
///////////////////////////////////////////////////////////////////////////
// LogService
// see https://docs.angularjs.org/api/ngMock/service/$log
// Augments the original service
///////////////////////////////////////////////////////////////////////////
interface ILogService {
assertEmpty(): void;
reset(): void;
}
interface ILogCall {
logs: string[];
}
///////////////////////////////////////////////////////////////////////////
// HttpBackendService
// see https://docs.angularjs.org/api/ngMock/service/$httpBackend
///////////////////////////////////////////////////////////////////////////
interface IHttpBackendService {
/**
* Flushes all pending requests using the trained responses.
* @param count Number of responses to flush (in the order they arrived). If undefined, all pending requests will be flushed.
*/
flush(count?: number): void;
/**
* Resets all request expectations, but preserves all backend definitions.
*/
resetExpectations(): void;
/**
* Verifies that all of the requests defined via the expect api were made. If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.
*/
verifyNoOutstandingExpectation(): void;
/**
* Verifies that there are no outstanding requests that need to be flushed.
*/
verifyNoOutstandingRequest(): void;
/**
* Creates a new request expectation.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expect(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)) :mock.IRequestHandler;
/**
* Creates a new request expectation for DELETE requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url is as expected.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for GET requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectGET(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for HEAD requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object to be compared with the HTTP headers in the request.
*/
expectHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for JSONP requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
*/
expectJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
/**
* Creates a new request expectation for PATCH requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for POST requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new request expectation for PUT requests.
* Throws a preformatted error if expectation(s) don't match supplied string, regular expression, object, or if function returns false.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
expectPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object): mock.IRequestHandler;
/**
* Creates a new backend definition.
* Returns an object with respond method that controls how a matched request is handled.
* @param method HTTP method.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
when(method: string, url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for DELETE requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenDELETE(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for GET requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenGET(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for HEAD requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenHEAD(url: string | RegExp | ((url: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for JSONP requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenJSONP(url: string | RegExp | ((url: string) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PATCH requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPATCH(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for POST requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPOST(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
/**
* Creates a new backend definition for PUT requests.
* Returns an object with respond method that controls how a matched request is handled.
* @param url HTTP url string, regular expression or function that receives a url and returns true if the url matches the current expctation.
* @param data HTTP request body string, json object, regular expression or function that receives the data and returns true if the data matches the current expectation.
* @param headers HTTP headers object or function that receives the headers and returns true if the headers match the current expectation.
*/
whenPUT(url: string | RegExp | ((url: string) => boolean), data?: string | RegExp | Object | ((data: string) => boolean), headers?: Object | ((object: Object) => boolean)): mock.IRequestHandler;
}
export module mock {
// returned interface by the the mocked HttpBackendService expect/when methods
interface IRequestHandler {
/**
* Controls the response for a matched request using a function to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param func Function that receives the request HTTP method, url, data, and headers and returns an array containing response status (number), data, headers, and status text.
*/
respond(func: ((method: string, url: string, data: string | Object, headers: Object) => [number, string | Object, Object, string])): IRequestHandler;
/**
* Controls the response for a matched request using supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param status HTTP status code to add to the response.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(status: number, data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
/**
* Controls the response for a matched request using the HTTP status code 200 and supplied static data to construct the response.
* Returns the RequestHandler object for possible overrides.
* @param data Data to add to the response.
* @param headers Headers object to add to the response.
* @param responseText Response text to add to the response.
*/
respond(data: string | Object, headers?: Object, responseText?: string): IRequestHandler;
// Available when ngMockE2E is loaded
/**
* Any request matching a backend definition or expectation with passThrough handler will be passed through to the real backend (an XHR request will be made to the server.)
*/
passThrough(): IRequestHandler;
}
}
}
///////////////////////////////////////////////////////////////////////////////
// functions attached to global object (window)
///////////////////////////////////////////////////////////////////////////////
//Use `angular.mock.module` instead of `module`, as `module` conflicts with commonjs.
//declare var module: (...modules: any[]) => any;
declare var inject: angular.IInjectStatic;

View File

@@ -1,40 +1,40 @@
// Type definitions for Angular JS 1.3 (ngSanitize module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
declare module "angular-sanitize" {
var _: string;
export = _;
}
///////////////////////////////////////////////////////////////////////////////
// ngSanitize module (angular-sanitize.js)
///////////////////////////////////////////////////////////////////////////////
declare module angular.sanitize {
///////////////////////////////////////////////////////////////////////////
// SanitizeService
// see http://docs.angularjs.org/api/ngSanitize.$sanitize
///////////////////////////////////////////////////////////////////////////
interface ISanitizeService {
(html: string): string;
}
///////////////////////////////////////////////////////////////////////////
// Filters included with the ngSanitize
// see https://github.com/angular/angular.js/tree/v1.2.0/src/ngSanitize/filter
///////////////////////////////////////////////////////////////////////////
export module filter {
// Finds links in text input and turns them into html links.
// Supports http/https/ftp/mailto and plain email address links.
// see http://code.angularjs.org/1.2.0/docs/api/ngSanitize.filter:linky
interface ILinky {
(text: string, target?: string): string;
}
}
}
// Type definitions for Angular JS 1.3 (ngSanitize module)
// Project: http://angularjs.org
// Definitions by: Diego Vilar <http://github.com/diegovilar>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="angular.d.ts" />
declare module "angular-sanitize" {
var _: string;
export = _;
}
///////////////////////////////////////////////////////////////////////////////
// ngSanitize module (angular-sanitize.js)
///////////////////////////////////////////////////////////////////////////////
declare module angular.sanitize {
///////////////////////////////////////////////////////////////////////////
// SanitizeService
// see http://docs.angularjs.org/api/ngSanitize.$sanitize
///////////////////////////////////////////////////////////////////////////
interface ISanitizeService {
(html: string): string;
}
///////////////////////////////////////////////////////////////////////////
// Filters included with the ngSanitize
// see https://github.com/angular/angular.js/tree/v1.2.0/src/ngSanitize/filter
///////////////////////////////////////////////////////////////////////////
export module filter {
// Finds links in text input and turns them into html links.
// Supports http/https/ftp/mailto and plain email address links.
// see http://code.angularjs.org/1.2.0/docs/api/ngSanitize.filter:linky
interface ILinky {
(text: string, target?: string): string;
}
}
}

View File

@@ -1,9 +1,9 @@
// Type definitions for ansicolors
// Project: https://github.com/thlorenz/ansicolors
// Definitions by: rogierschouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "ansicolors" {
var colors: {[index: string]: (s: string) => string;};
export = colors;
}
// Type definitions for ansicolors
// Project: https://github.com/thlorenz/ansicolors
// Definitions by: rogierschouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "ansicolors" {
var colors: {[index: string]: (s: string) => string;};
export = colors;
}

View File

@@ -1,29 +1,29 @@
/// <reference path="../any-db/any-db.d.ts" />
/// <reference path="any-db-transaction.d.ts" />
"use strict";
import anyDB = require("any-db");
import begin = require("any-db-transaction");
var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb");
var transaction = begin(conn);
var transaction2 = begin(transaction);
begin(conn, { autoRollback: true });
begin(conn, (error: Error, result: begin.Transaction): void => {
});
transaction.query("SELECT * FROM MyTable");
transaction.commit();
transaction.commit((error: Error): void => {
});
transaction.rollback();
transaction.rollback((error: Error): void => {
});
/// <reference path="../any-db/any-db.d.ts" />
/// <reference path="any-db-transaction.d.ts" />
"use strict";
import anyDB = require("any-db");
import begin = require("any-db-transaction");
var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb");
var transaction = begin(conn);
var transaction2 = begin(transaction);
begin(conn, { autoRollback: true });
begin(conn, (error: Error, result: begin.Transaction): void => {
});
transaction.query("SELECT * FROM MyTable");
transaction.commit();
transaction.commit((error: Error): void => {
});
transaction.rollback();
transaction.rollback((error: Error): void => {
});

View File

@@ -1,94 +1,94 @@
// Type definitions for any-db-transaction 2.2.1
// Project: https://github.com/grncdr/node-any-db-transaction
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../any-db/any-db.d.ts" />
declare module "any-db-transaction" {
import anyDB = require("any-db");
module begin {
/**
* Transaction objects are are simple wrappers around a Connection that also implement the Queryable API,
* but guarantee that all queries take place within a single database transaction or not at all. Note that
* begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you
* can simply pass a pool to it: var tx = begin(pool)
*
* By default, any queries that error during a transaction will cause an automatic rollback. If a query has
* no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance.
* This enables handling errors for an entire transaction in a single place.
*
* Transactions may also be nested by passing a Transaction to begin and these nested transactions can
* safely error and rollback without rolling back their parent transaction
*
* Transaction events:
* 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object.
* 'commit:start' - Emitted when .commit() is called.
* 'commit:complete' - Emitted after the transaction has committed.
* 'rollback:start' - Emitted when .rollback() is called.
* 'rollback:complete' - Emitted after the transaction has rolled back.
* 'close' - Emitted after rollback or commit completes.
* 'error', err - Emitted under three conditions:
* There was an error acquiring a connection.
* Any query performed in this transaction emits an error that would otherwise go unhandled.
* Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back.
* Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][].
*/
interface Transaction extends anyDB.Queryable {
/**
* Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database.
* If a continuation is provided it will be called (possibly with an error) after the COMMIT
* statement completes. The transaction object itself will be unusable after calling commit().
*/
commit(callback?: (error: Error) => void): void;
/**
* The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method.
*/
rollback(callback?: (error: Error) => void): void;
}
interface TransactionOptions {
/**
* Adapter name e.g. 'mysql'
*/
adapter?: anyDB.Adapter;
/**
* SQL statement for beginning a transaction, default 'BEGIN'
*/
begin?: string;
/**
* SQL statement for committing a transaction, default 'COMMIT'
*/
commit?: string;
/**
* SQL statement for rolling back a transaction, default 'ROLLBACK'
*/
rollback?: string;
/**
* Callback for transaction
*/
callback?: (error: Error, transaction: Transaction) => void;
/**
* Rollback automatically on error, default true
*/
autoRollback?: boolean;
}
}
/**
* Start a transaction
*/
function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction;
function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction;
function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction;
function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction;
export = begin;
}
// Type definitions for any-db-transaction 2.2.1
// Project: https://github.com/grncdr/node-any-db-transaction
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
/// <reference path="../any-db/any-db.d.ts" />
declare module "any-db-transaction" {
import anyDB = require("any-db");
module begin {
/**
* Transaction objects are are simple wrappers around a Connection that also implement the Queryable API,
* but guarantee that all queries take place within a single database transaction or not at all. Note that
* begin also understands how to acquire (and release) a connection from a ConnectionPool as well, so you
* can simply pass a pool to it: var tx = begin(pool)
*
* By default, any queries that error during a transaction will cause an automatic rollback. If a query has
* no callback, the transaction will also handle (and re-emit) 'error' events for the Query instance.
* This enables handling errors for an entire transaction in a single place.
*
* Transactions may also be nested by passing a Transaction to begin and these nested transactions can
* safely error and rollback without rolling back their parent transaction
*
* Transaction events:
* 'query', query - emitted immediately after .query is called on a connection via tx.query. The argument is a query object.
* 'commit:start' - Emitted when .commit() is called.
* 'commit:complete' - Emitted after the transaction has committed.
* 'rollback:start' - Emitted when .rollback() is called.
* 'rollback:complete' - Emitted after the transaction has rolled back.
* 'close' - Emitted after rollback or commit completes.
* 'error', err - Emitted under three conditions:
* There was an error acquiring a connection.
* Any query performed in this transaction emits an error that would otherwise go unhandled.
* Any of query, begin, commit, or rollback are called after the connection has already been committed or rolled back.
* Note that the 'error' event may be emitted multiple times! depending on the callback you are registering, you way want to wrap it using [once][].
*/
interface Transaction extends anyDB.Queryable {
/**
* Issue a COMMIT (or RELEASE ... in the case of nested transactions) statement to the database.
* If a continuation is provided it will be called (possibly with an error) after the COMMIT
* statement completes. The transaction object itself will be unusable after calling commit().
*/
commit(callback?: (error: Error) => void): void;
/**
* The same as Transaction.commit but issues a ROLLBACK. Again, the transaction will be unusable after calling this method.
*/
rollback(callback?: (error: Error) => void): void;
}
interface TransactionOptions {
/**
* Adapter name e.g. 'mysql'
*/
adapter?: anyDB.Adapter;
/**
* SQL statement for beginning a transaction, default 'BEGIN'
*/
begin?: string;
/**
* SQL statement for committing a transaction, default 'COMMIT'
*/
commit?: string;
/**
* SQL statement for rolling back a transaction, default 'ROLLBACK'
*/
rollback?: string;
/**
* Callback for transaction
*/
callback?: (error: Error, transaction: Transaction) => void;
/**
* Rollback automatically on error, default true
*/
autoRollback?: boolean;
}
}
/**
* Start a transaction
*/
function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction;
function begin(q: anyDB.Queryable, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction;
function begin(q: anyDB.Queryable, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction;
function begin(q: anyDB.Queryable, options?: begin.TransactionOptions, beginStatement?: string, callback?: (error: Error, transaction: begin.Transaction) => void): begin.Transaction;
export = begin;
}

View File

@@ -1,38 +1,38 @@
/// <reference path="any-db.d.ts" />
"use strict";
import anyDB = require("any-db");
var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb");
var sql: string = "SELECT * FROM questions";
conn.query(sql, [1, "boo"]);
conn.query(sql).on("data", (row: Object[]): void => {
// nothing
});
conn.query(sql, [1, "s"], (error: Error, result: anyDB.ResultSet): void => {
result.rows.length;
result.fields.length;
});
conn.end();
var poolConfig: anyDB.PoolConfig = {
min: 1,
max: 200
};
var pool: anyDB.ConnectionPool = anyDB.createPool("mysql://user:password@localhost/testdb", poolConfig);
pool.query(sql).on("data", (row: Object[]): void => {
// nothing
});
pool.close((error: Error): void => {
});
/// <reference path="any-db.d.ts" />
"use strict";
import anyDB = require("any-db");
var conn: anyDB.Connection = anyDB.createConnection("mysql://user:password@localhost/testdb");
var sql: string = "SELECT * FROM questions";
conn.query(sql, [1, "boo"]);
conn.query(sql).on("data", (row: Object[]): void => {
// nothing
});
conn.query(sql, [1, "s"], (error: Error, result: anyDB.ResultSet): void => {
result.rows.length;
result.fields.length;
});
conn.end();
var poolConfig: anyDB.PoolConfig = {
min: 1,
max: 200
};
var pool: anyDB.ConnectionPool = anyDB.createPool("mysql://user:password@localhost/testdb", poolConfig);
pool.query(sql).on("data", (row: Object[]): void => {
// nothing
});
pool.close((error: Error): void => {
});

606
any-db/any-db.d.ts vendored
View File

@@ -1,303 +1,303 @@
// Type definitions for any-db 2.1.0
// Project: https://github.com/grncdr/node-any-db
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "any-db" {
import events = require("events");
import stream = require("stream");
export interface ConnectOpts {
adapter: string;
}
export interface Adapter {
name: string;
/**
* Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db.
* If a continuation is given, it must be called, either with an error or the established connection.
*/
createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection;
/**
* Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code,
* it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract
* by synchronously returning a Query stream
*/
createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query;
createQuery(query: Query): Query;
}
/**
* Other properties are driver specific
*/
export interface Field {
name: string;
}
/**
* ResultSet objects are just plain data that collect results of a query when a continuation
* is provided to Queryable.query. The lastInsertId is optional, and currently supported by
* sqlite3 and mysql but not postgres, because it is not supported by Postgres itself.
*/
export interface ResultSet {
/**
* Affected rows. Note e.g. for INSERT queries the rows property is not filled even
* though rowCount is non-zero.
*/
rowCount: number;
/**
* Result rows
*/
rows: any[];
/**
* Result field descriptions
*/
fields: Field[];
/**
* Not supported by all drivers.
*/
fieldCount?: number;
/**
* Not supported by all drivers.
*/
lastInsertId?: any;
/**
* Not supported by all drivers.
*/
affectedRows?: number;
/**
* Not supported by all drivers.
*/
changedRows?: number;
}
/**
* Query objects are returned by the Queryable.query method, available on connections,
* pools, and transactions. Queries are instances of Readable, and as such can be piped
* through transforms and support backpressure for more efficient memory-usage on very
* large results sets. (Note: at this time the sqlite3 driver does not support backpressure)
*
* Internally, Query instances are created by a database Adapter and may have more methods,
* properties, and events than are described here. Consult the documentation for your
* specific adapter to find out about any extensions.
*
* Events:
*
* Error event
* The 'error' event is emitted at most once per query. Note that this event will be
* emitted for errors even if a callback was provided, the callback will
* simply be subscribed to the 'error' event.
* One argument is passed to event listeners:
* error - the error object.
*
* Fields event
* A 'fields' event is emmitted before any 'data' events.
* One argument is passed to event listeners:
* fields - an array of [Field][ResultSet] objects.
*
* The following events are part of the stream.Readable interface which is implemented by Query:
*
* Data event
* A 'data' event is emitted for each row in the query result set.
* One argument is passed to event listeners:
* row contains the contents of a single row in the query result
*
* Close event
* A 'close' event is emitted when the query completes.
* No arguments are passed to event listeners.
*
* End event
* An 'end' event is emitted after all query results have been consumed.
* No arguments are passed to event listeners.
*/
export interface Query extends stream.Readable {
/**
* The SQL query as a string. If you are using MySQL this will contain
* interpolated values after the query has been enqueued by a connection.
*/
text: string;
/**
* The array of parameter values.
*/
values: any[];
/**
* The callback (if any) that was provided to Queryable.query. Note that
* Query objects must not use a closed over reference to their callback,
* as other any-db libraries may rely on modifying the callback property
* of a Query they did not create.
*/
callback: (error: Error, results: ResultSet) => void;
}
/**
* Events:
* The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers:
* - query: a Query object
*/
export interface Queryable extends events.EventEmitter {
/**
* The Adapter instance that will be used by this Queryable for creating Query instances and/or connections.
*/
adapter: Adapter;
/**
* Execute a SQL statement using bound parameters (if they are provided) and return a Query object
* that is a Readable stream of the resulting rows. If a Continuation<ResultSet> is provided the rows
* returned by the database will be aggregated into a [ResultSet][] which will be passed to the
* continuation after the query has completed.
* The second form is not needed for normal use, but must be implemented by adapters to work correctly
* with ConnectionPool and Transaction. See Adapter.createQuery for more details.
*/
query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query
/**
* The second form is not needed for normal use, but must be implemented by adapters to work correctly
* with ConnectionPool and Transaction. See Adapter.createQuery for more details.
*/
// query(query: Query): Query;
}
/**
* Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire,
* both of which delegate to the createConnection implementation of the specified adapter.
* While all Connection objects implement the Queryable interface, the implementations in
* each adapter may add additional methods or emit additional events. If you need to access a
* feature of your database that is not described here (such as Postgres' server-side prepared
* statements), consult the documentation for your adapter.
*
* Events:
* Error event
* The 'error' event is emitted when there is a connection-level error.
* No arguments are passed to event listeners.
*
* Open event
* The 'open' event is emitted when the connection has been established and is ready to query.
* No arguments are passed to event listeners.
*
* Close event
* The 'close' event is emitted when the connection has been closed.
* No arguments are passed to event listeners.
*/
export interface Connection extends Queryable {
/**
* Close the database connection. If a continuation is provided it
* will be called after the connection has closed.
*/
end(callback?: (error: Error) => void): void;
}
export interface ConnectionStatic {
new(): Connection;
name: string;
createConnection(): void;
createPool(): void;
}
/**
* ConnectionPool events
* 'acquire' - emitted whenever pool.acquire is called
* 'release' - emitted whenever pool.release is called
* 'query', query - emitted immediately after .query is called on a
* connection via pool.query. The argument is a Query object.
* 'close' - emitted when the connection pool has closed all of it
* connections after a call to close().
*/
export interface ConnectionPool extends Queryable {
/**
* Implements Queryable.query by automatically acquiring a connection
* and releasing it when the query completes.
*/
query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query;
/**
* Remove a connection from the pool. If you use this method you must
* return the connection back to the pool using ConnectionPool.release
*/
acquire(callback: (error: Error, result: Connection) => void): void;
/**
* Return a connection to the pool. This should only be called with connections
* you've manually acquired. You must not continue to use the connection after releasing it.
*/
release(connection: Connection): void;
/**
* Stop giving out new connections, and close all existing database connections as they
* are returned to the pool.
*/
close(callback?: (error: Error) => void): void;
}
/**
* A PoolConfig is generally a plain object with any of the following properties (they are all optional):
*/
export interface PoolConfig {
/**
* min (default 0) The minimum number of connections to keep open in the pool.
*/
min?: number;
/**
* max (default 10) The maximum number of connections to keep open in the pool.
* When this limit is reached further requests for connections will queue waiting
* for an existing connection to be released back into the pool.
*/
max?: number;
/**
* (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped
*/
idleTimeout?: number;
/**
* (default 1000) How frequently the pool should check for connections that are old enough to be reaped.
*/
reapInterval?: number;
/**
* (default true) When this is true, the pool will reap connections that
* have been idle for more than idleTimeout milliseconds.
*/
refreshIdle?: boolean;
/**
* Called immediately after a connection is first established. Use this to do one-time setup of new connections.
* The supplied Connection will not be added to the pool until you pass it to the done continuation.
*/
onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void;
/**
* Called each time a connection is returned to the pool. Use this to restore a connection to
* it's original state (e.g. rollback transactions, set the database session vars). If reset
* fails to call the done continuation the connection will be lost in limbo.
*/
reset?: (connection: Connection, done: (error: Error) => void) => void;
/**
* (default function (err) { return true }) - Called when an error is encountered
* by pool.query or emitted by an idle connection. If shouldDestroyConnection(error)
* is truthy the connection will be destroyed, otherwise it will be reset.
*/
shouldDestroyConnection?: (error: Error) => boolean;
}
/**
* Create a database connection.
* @param url String of the form adapter://user:password@host/database
* @param callback
* @returns Connection object.
*/
export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection;
/**
* Create a database connection.
* @param opts Object with adapter name and any properties that the given adapter requires
* @param callback
* @returns Connection object.
*/
export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection;
export function createPool(url: string, config: PoolConfig): ConnectionPool;
export function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool;
}
// Type definitions for any-db 2.1.0
// Project: https://github.com/grncdr/node-any-db
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "any-db" {
import events = require("events");
import stream = require("stream");
export interface ConnectOpts {
adapter: string;
}
export interface Adapter {
name: string;
/**
* Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db.
* If a continuation is given, it must be called, either with an error or the established connection.
*/
createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection;
/**
* Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code,
* it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract
* by synchronously returning a Query stream
*/
createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query;
createQuery(query: Query): Query;
}
/**
* Other properties are driver specific
*/
export interface Field {
name: string;
}
/**
* ResultSet objects are just plain data that collect results of a query when a continuation
* is provided to Queryable.query. The lastInsertId is optional, and currently supported by
* sqlite3 and mysql but not postgres, because it is not supported by Postgres itself.
*/
export interface ResultSet {
/**
* Affected rows. Note e.g. for INSERT queries the rows property is not filled even
* though rowCount is non-zero.
*/
rowCount: number;
/**
* Result rows
*/
rows: any[];
/**
* Result field descriptions
*/
fields: Field[];
/**
* Not supported by all drivers.
*/
fieldCount?: number;
/**
* Not supported by all drivers.
*/
lastInsertId?: any;
/**
* Not supported by all drivers.
*/
affectedRows?: number;
/**
* Not supported by all drivers.
*/
changedRows?: number;
}
/**
* Query objects are returned by the Queryable.query method, available on connections,
* pools, and transactions. Queries are instances of Readable, and as such can be piped
* through transforms and support backpressure for more efficient memory-usage on very
* large results sets. (Note: at this time the sqlite3 driver does not support backpressure)
*
* Internally, Query instances are created by a database Adapter and may have more methods,
* properties, and events than are described here. Consult the documentation for your
* specific adapter to find out about any extensions.
*
* Events:
*
* Error event
* The 'error' event is emitted at most once per query. Note that this event will be
* emitted for errors even if a callback was provided, the callback will
* simply be subscribed to the 'error' event.
* One argument is passed to event listeners:
* error - the error object.
*
* Fields event
* A 'fields' event is emmitted before any 'data' events.
* One argument is passed to event listeners:
* fields - an array of [Field][ResultSet] objects.
*
* The following events are part of the stream.Readable interface which is implemented by Query:
*
* Data event
* A 'data' event is emitted for each row in the query result set.
* One argument is passed to event listeners:
* row contains the contents of a single row in the query result
*
* Close event
* A 'close' event is emitted when the query completes.
* No arguments are passed to event listeners.
*
* End event
* An 'end' event is emitted after all query results have been consumed.
* No arguments are passed to event listeners.
*/
export interface Query extends stream.Readable {
/**
* The SQL query as a string. If you are using MySQL this will contain
* interpolated values after the query has been enqueued by a connection.
*/
text: string;
/**
* The array of parameter values.
*/
values: any[];
/**
* The callback (if any) that was provided to Queryable.query. Note that
* Query objects must not use a closed over reference to their callback,
* as other any-db libraries may rely on modifying the callback property
* of a Query they did not create.
*/
callback: (error: Error, results: ResultSet) => void;
}
/**
* Events:
* The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers:
* - query: a Query object
*/
export interface Queryable extends events.EventEmitter {
/**
* The Adapter instance that will be used by this Queryable for creating Query instances and/or connections.
*/
adapter: Adapter;
/**
* Execute a SQL statement using bound parameters (if they are provided) and return a Query object
* that is a Readable stream of the resulting rows. If a Continuation<ResultSet> is provided the rows
* returned by the database will be aggregated into a [ResultSet][] which will be passed to the
* continuation after the query has completed.
* The second form is not needed for normal use, but must be implemented by adapters to work correctly
* with ConnectionPool and Transaction. See Adapter.createQuery for more details.
*/
query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query
/**
* The second form is not needed for normal use, but must be implemented by adapters to work correctly
* with ConnectionPool and Transaction. See Adapter.createQuery for more details.
*/
// query(query: Query): Query;
}
/**
* Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire,
* both of which delegate to the createConnection implementation of the specified adapter.
* While all Connection objects implement the Queryable interface, the implementations in
* each adapter may add additional methods or emit additional events. If you need to access a
* feature of your database that is not described here (such as Postgres' server-side prepared
* statements), consult the documentation for your adapter.
*
* Events:
* Error event
* The 'error' event is emitted when there is a connection-level error.
* No arguments are passed to event listeners.
*
* Open event
* The 'open' event is emitted when the connection has been established and is ready to query.
* No arguments are passed to event listeners.
*
* Close event
* The 'close' event is emitted when the connection has been closed.
* No arguments are passed to event listeners.
*/
export interface Connection extends Queryable {
/**
* Close the database connection. If a continuation is provided it
* will be called after the connection has closed.
*/
end(callback?: (error: Error) => void): void;
}
export interface ConnectionStatic {
new(): Connection;
name: string;
createConnection(): void;
createPool(): void;
}
/**
* ConnectionPool events
* 'acquire' - emitted whenever pool.acquire is called
* 'release' - emitted whenever pool.release is called
* 'query', query - emitted immediately after .query is called on a
* connection via pool.query. The argument is a Query object.
* 'close' - emitted when the connection pool has closed all of it
* connections after a call to close().
*/
export interface ConnectionPool extends Queryable {
/**
* Implements Queryable.query by automatically acquiring a connection
* and releasing it when the query completes.
*/
query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query;
/**
* Remove a connection from the pool. If you use this method you must
* return the connection back to the pool using ConnectionPool.release
*/
acquire(callback: (error: Error, result: Connection) => void): void;
/**
* Return a connection to the pool. This should only be called with connections
* you've manually acquired. You must not continue to use the connection after releasing it.
*/
release(connection: Connection): void;
/**
* Stop giving out new connections, and close all existing database connections as they
* are returned to the pool.
*/
close(callback?: (error: Error) => void): void;
}
/**
* A PoolConfig is generally a plain object with any of the following properties (they are all optional):
*/
export interface PoolConfig {
/**
* min (default 0) The minimum number of connections to keep open in the pool.
*/
min?: number;
/**
* max (default 10) The maximum number of connections to keep open in the pool.
* When this limit is reached further requests for connections will queue waiting
* for an existing connection to be released back into the pool.
*/
max?: number;
/**
* (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped
*/
idleTimeout?: number;
/**
* (default 1000) How frequently the pool should check for connections that are old enough to be reaped.
*/
reapInterval?: number;
/**
* (default true) When this is true, the pool will reap connections that
* have been idle for more than idleTimeout milliseconds.
*/
refreshIdle?: boolean;
/**
* Called immediately after a connection is first established. Use this to do one-time setup of new connections.
* The supplied Connection will not be added to the pool until you pass it to the done continuation.
*/
onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void;
/**
* Called each time a connection is returned to the pool. Use this to restore a connection to
* it's original state (e.g. rollback transactions, set the database session vars). If reset
* fails to call the done continuation the connection will be lost in limbo.
*/
reset?: (connection: Connection, done: (error: Error) => void) => void;
/**
* (default function (err) { return true }) - Called when an error is encountered
* by pool.query or emitted by an idle connection. If shouldDestroyConnection(error)
* is truthy the connection will be destroyed, otherwise it will be reset.
*/
shouldDestroyConnection?: (error: Error) => boolean;
}
/**
* Create a database connection.
* @param url String of the form adapter://user:password@host/database
* @param callback
* @returns Connection object.
*/
export function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection;
/**
* Create a database connection.
* @param opts Object with adapter name and any properties that the given adapter requires
* @param callback
* @returns Connection object.
*/
export function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection;
export function createPool(url: string, config: PoolConfig): ConnectionPool;
export function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool;
}

View File

@@ -1 +1 @@
--noImplicitAny --module commonjs
--noImplicitAny --module commonjs

View File

@@ -1,443 +1,443 @@
/// <reference path="async.d.ts" />
var fs, path;
function callback() {}
async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { });
async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.select(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.parallel([
function () { },
function () { }
], callback);
async.series([
function () { },
function () { }
]);
var data = [];
function asyncProcess(item, callback) { }
async.map(data, asyncProcess, function (err, results) {
console.log(results);
});
var openFiles = ['file1', 'file2'];
var openFilesObj = {
file1: "fileOne",
file2: "fileTwo"
}
var saveFile = function () { }
async.each(openFiles, saveFile, function (err) { });
async.eachSeries(openFiles, saveFile, function (err) { });
var documents, requestApi;
async.eachLimit(documents, 20, requestApi, function (err) { });
// forEachOf* functions. May accept array or object.
function forEachOfIterator(item, key, forEachOfIteratorCallback) {
console.log("ForEach: item=" + item + ", key=" + key);
forEachOfIteratorCallback();
}
async.forEachOf(openFiles, forEachOfIterator, function (err) { });
async.forEachOf(openFilesObj, forEachOfIterator, function (err) { });
async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { });
async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { });
var process;
var numArray = [1, 2, 3];
function reducer(memo, item, callback) {
process.nextTick(function () {
callback(null, memo + item)
});
}
async.reduce(numArray, 0, reducer, function (err, result) { });
async.inject(numArray, 0, reducer, function (err, result) { });
async.foldl(numArray, 0, reducer, function (err, result) { });
async.reduceRight(numArray, 0, reducer, function (err, result) { });
async.foldr(numArray, 0, reducer, function (err, result) { });
async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.sortBy(['file1', 'file2', 'file3'], function (file, callback) {
fs.stat(file, function (err, stats) {
callback(err, stats.mtime);
});
}, function (err, results) { });
async.some(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.any(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.every(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.all(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { });
async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { });
// Control Flow //
async.series([
function (callback) {
callback(null, 'one');
},
function (callback) {
callback(null, 'two');
},
],
function (err, results) { });
async.series<string>([
function (callback) {
callback(null, 'one');
},
function (callback) {
callback(null, 'two');
},
],
function (err, results) { });
async.series({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
function (err, results) { });
async.series<number>({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
function (err, results) { });
async.times(5, function(n, next) {
next(null, n)
}, function(err, results) {
console.log(results)
})
async.timesSeries(5, function(n, next) {
next(null, n)
}, function(err, results) {
console.log(results)
})
async.parallel([
function (callback) {
setTimeout(function () {
callback(null, 'one');
}, 200);
},
function (callback) {
setTimeout(function () {
callback(null, 'two');
}, 100);
},
],
function (err, results) { });
async.parallel<string>([
function (callback) {
setTimeout(function () {
callback(null, 'one');
}, 200);
},
function (callback) {
setTimeout(function () {
callback(null, 'two');
}, 100);
},
],
function (err, results) { });
async.parallel({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
function (err, results) { });
async.parallel<number>({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
function (err, results) { });
async.parallelLimit({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
2,
function (err, results) { }
);
function whileFn(callback) {
count++;
setTimeout(callback, 1000);
}
function whileTest() { return count < 5; }
var count = 0;
async.whilst(whileTest, whileFn, function (err) { });
async.until(whileTest, whileFn, function (err) { });
async.doWhilst(whileFn, whileTest, function (err) { });
async.doUntil(whileFn, whileTest, function (err) { });
async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) });
async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) });
async.forever(function (errBack) {
errBack(new Error("Not going on forever."));
},
function (error) {
console.log(error);
}
);
async.waterfall([
function (callback) {
callback(null, 'one', 'two');
},
function (arg1, arg2, callback) {
callback(null, 'three');
},
function (arg1, callback) {
callback(null, 'done');
}
], function (err, result) { });
var q = async.queue<any>(function (task: any, callback) {
console.log('hello ' + task.name);
callback();
}, 2);
q.drain = function () {
console.log('all items have been processed');
}
q.push({ name: 'foo' });
q.push({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) {
console.log('finished processing bar');
});
q.unshift({ name: 'foo' });
q.unshift({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) {
console.log('finished processing bar');
});
var qLength : number = q.length();
var qStarted : boolean = q.started;
var qPaused : boolean = q.paused;
var qProcessingCount : number = q.running();
var qIsIdle : boolean = q.idle();
q.saturated = function() {
console.log('queue is saturated.');
}
q.empty = function() {
console.log('queue is empty.');
}
q.drain = function() {
console.log('queue was drained.');
}
q.pause();
q.resume();
q.kill();
// tests for strongly typed tasks
var q2 = async.queue<string>(function (task: string, callback) {
console.log('Task: ' + task);
callback();
}, 1);
q2.push('task1');
q2.push('task2', function (error) {
console.log('Finished tasks');
});
q2.push(['task3', 'task4', 'task5'], function (error) {
console.log('Finished tasks');
});
q2.unshift('task1');
q2.unshift('task2', function (error) {
console.log('Finished tasks');
});
q2.unshift(['task3', 'task4', 'task5'], function (error) {
console.log('Finished tasks');
});
// create a cargo object with payload 2
var cargo = async.cargo(function (tasks, callback) {
for (var i = 0; i < tasks.length; i++) {
console.log('hello ' + tasks[i].name);
}
callback();
}, 2);
// add some items
cargo.push({ name: 'foo' }, function (err) {
console.log('finished processing foo');
});
cargo.push({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
cargo.push({ name: 'baz' }, function (err) {
console.log('finished processing baz');
});
var filename = '';
async.auto({
get_data: function (callback) { },
make_folder: function (callback) { },
//arrays with different types are not accepted by TypeScript.
write_file: ['get_data', 'make_folder', <any>function (callback) {
callback(null, filename);
}],
//arrays with different types are not accepted by TypeScript.
email_link: ['write_file', <any>function (callback, results) { }]
});
async.retry(3, function (callback, results) { }, function (err, result) { });
async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { });
async.parallel([
function (callback) { },
function (callback) { }
],
function (results) {
async.series([
function (callback) { },
function email_link(callback) { }
]);
});
var sys;
var iterator = async.iterator([
function () { sys.p('one'); },
function () { sys.p('two'); },
function () { sys.p('three'); }
]);
async.parallel([
async.apply(fs.writeFile, 'testfile1', 'test1'),
async.apply(fs.writeFile, 'testfile2', 'test2'),
]);
async.parallel([
function (callback) {
fs.writeFile('testfile1', 'test1', callback);
},
function (callback) {
fs.writeFile('testfile2', 'test2', callback);
},
]);
var call_order = [];
async.nextTick(function () {
call_order.push('two');
});
call_order.push('one');
var slow_fn = function (name, callback) {
callback(null, 123);
};
var fn = async.memoize(slow_fn);
fn('some name', function () {});
async.unmemoize(fn);
async.ensureAsync(function () { });
async.constant(42);
async.asyncify(function () { });
async.log(function (name, callback) {
setTimeout(function () {
callback(null, 'hello ' + name);
}, 0);
}, "world"
);
async.dir(function (name, callback) {
setTimeout(function () {
callback(null, { hello: name });
}, 1000);
}, "world");
/// <reference path="async.d.ts" />
var fs, path;
function callback() {}
async.map(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.mapSeries(['file1', 'file2', 'file3'], fs.stat, function (err, results) { });
async.mapLimit(['file1', 'file2', 'file3'], 2, fs.stat, function (err, results) { });
async.filter(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.filterSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.filterLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.select(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.selectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.selectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.reject(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.rejectSeries(['file1', 'file2', 'file3'], path.exists, function (results) { });
async.rejectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (results) { });
async.parallel([
function () { },
function () { }
], callback);
async.series([
function () { },
function () { }
]);
var data = [];
function asyncProcess(item, callback) { }
async.map(data, asyncProcess, function (err, results) {
console.log(results);
});
var openFiles = ['file1', 'file2'];
var openFilesObj = {
file1: "fileOne",
file2: "fileTwo"
}
var saveFile = function () { }
async.each(openFiles, saveFile, function (err) { });
async.eachSeries(openFiles, saveFile, function (err) { });
var documents, requestApi;
async.eachLimit(documents, 20, requestApi, function (err) { });
// forEachOf* functions. May accept array or object.
function forEachOfIterator(item, key, forEachOfIteratorCallback) {
console.log("ForEach: item=" + item + ", key=" + key);
forEachOfIteratorCallback();
}
async.forEachOf(openFiles, forEachOfIterator, function (err) { });
async.forEachOf(openFilesObj, forEachOfIterator, function (err) { });
async.forEachOfSeries(openFiles, forEachOfIterator, function (err) { });
async.forEachOfSeries(openFilesObj, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFiles, 2, forEachOfIterator, function (err) { });
async.forEachOfLimit(openFilesObj, 2, forEachOfIterator, function (err) { });
var process;
var numArray = [1, 2, 3];
function reducer(memo, item, callback) {
process.nextTick(function () {
callback(null, memo + item)
});
}
async.reduce(numArray, 0, reducer, function (err, result) { });
async.inject(numArray, 0, reducer, function (err, result) { });
async.foldl(numArray, 0, reducer, function (err, result) { });
async.reduceRight(numArray, 0, reducer, function (err, result) { });
async.foldr(numArray, 0, reducer, function (err, result) { });
async.detect(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.detectSeries(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.detectLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.sortBy(['file1', 'file2', 'file3'], function (file, callback) {
fs.stat(file, function (err, stats) {
callback(err, stats.mtime);
});
}, function (err, results) { });
async.some(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.someLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.any(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.every(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.everyLimit(['file1', 'file2', 'file3'], 2, path.exists, function (result) { });
async.all(['file1', 'file2', 'file3'], path.exists, function (result) { });
async.concat(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { });
async.concatSeries(['dir1', 'dir2', 'dir3'], fs.readdir, function (err, files) { });
// Control Flow //
async.series([
function (callback) {
callback(null, 'one');
},
function (callback) {
callback(null, 'two');
},
],
function (err, results) { });
async.series<string>([
function (callback) {
callback(null, 'one');
},
function (callback) {
callback(null, 'two');
},
],
function (err, results) { });
async.series({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
function (err, results) { });
async.series<number>({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
function (err, results) { });
async.times(5, function(n, next) {
next(null, n)
}, function(err, results) {
console.log(results)
})
async.timesSeries(5, function(n, next) {
next(null, n)
}, function(err, results) {
console.log(results)
})
async.parallel([
function (callback) {
setTimeout(function () {
callback(null, 'one');
}, 200);
},
function (callback) {
setTimeout(function () {
callback(null, 'two');
}, 100);
},
],
function (err, results) { });
async.parallel<string>([
function (callback) {
setTimeout(function () {
callback(null, 'one');
}, 200);
},
function (callback) {
setTimeout(function () {
callback(null, 'two');
}, 100);
},
],
function (err, results) { });
async.parallel({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
function (err, results) { });
async.parallel<number>({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
function (err, results) { });
async.parallelLimit({
one: function (callback) {
setTimeout(function () {
callback(null, 1);
}, 200);
},
two: function (callback) {
setTimeout(function () {
callback(null, 2);
}, 100);
},
},
2,
function (err, results) { }
);
function whileFn(callback) {
count++;
setTimeout(callback, 1000);
}
function whileTest() { return count < 5; }
var count = 0;
async.whilst(whileTest, whileFn, function (err) { });
async.until(whileTest, whileFn, function (err) { });
async.doWhilst(whileFn, whileTest, function (err) { });
async.doUntil(whileFn, whileTest, function (err) { });
async.during(function (testCallback) { testCallback(new Error(), false); }, function (callback) { callback() }, function (error) { console.log(error) });
async.doDuring(function (callback) { callback() }, function (testCallback) { testCallback(new Error(), false); }, function (error) { console.log(error) });
async.forever(function (errBack) {
errBack(new Error("Not going on forever."));
},
function (error) {
console.log(error);
}
);
async.waterfall([
function (callback) {
callback(null, 'one', 'two');
},
function (arg1, arg2, callback) {
callback(null, 'three');
},
function (arg1, callback) {
callback(null, 'done');
}
], function (err, result) { });
var q = async.queue<any>(function (task: any, callback) {
console.log('hello ' + task.name);
callback();
}, 2);
q.drain = function () {
console.log('all items have been processed');
}
q.push({ name: 'foo' });
q.push({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) {
console.log('finished processing bar');
});
q.unshift({ name: 'foo' });
q.unshift({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
q.unshift([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) {
console.log('finished processing bar');
});
var qLength : number = q.length();
var qStarted : boolean = q.started;
var qPaused : boolean = q.paused;
var qProcessingCount : number = q.running();
var qIsIdle : boolean = q.idle();
q.saturated = function() {
console.log('queue is saturated.');
}
q.empty = function() {
console.log('queue is empty.');
}
q.drain = function() {
console.log('queue was drained.');
}
q.pause();
q.resume();
q.kill();
// tests for strongly typed tasks
var q2 = async.queue<string>(function (task: string, callback) {
console.log('Task: ' + task);
callback();
}, 1);
q2.push('task1');
q2.push('task2', function (error) {
console.log('Finished tasks');
});
q2.push(['task3', 'task4', 'task5'], function (error) {
console.log('Finished tasks');
});
q2.unshift('task1');
q2.unshift('task2', function (error) {
console.log('Finished tasks');
});
q2.unshift(['task3', 'task4', 'task5'], function (error) {
console.log('Finished tasks');
});
// create a cargo object with payload 2
var cargo = async.cargo(function (tasks, callback) {
for (var i = 0; i < tasks.length; i++) {
console.log('hello ' + tasks[i].name);
}
callback();
}, 2);
// add some items
cargo.push({ name: 'foo' }, function (err) {
console.log('finished processing foo');
});
cargo.push({ name: 'bar' }, function (err) {
console.log('finished processing bar');
});
cargo.push({ name: 'baz' }, function (err) {
console.log('finished processing baz');
});
var filename = '';
async.auto({
get_data: function (callback) { },
make_folder: function (callback) { },
//arrays with different types are not accepted by TypeScript.
write_file: ['get_data', 'make_folder', <any>function (callback) {
callback(null, filename);
}],
//arrays with different types are not accepted by TypeScript.
email_link: ['write_file', <any>function (callback, results) { }]
});
async.retry(3, function (callback, results) { }, function (err, result) { });
async.retry({ times: 3, interval: 200 }, function (callback, results) { }, function (err, result) { });
async.parallel([
function (callback) { },
function (callback) { }
],
function (results) {
async.series([
function (callback) { },
function email_link(callback) { }
]);
});
var sys;
var iterator = async.iterator([
function () { sys.p('one'); },
function () { sys.p('two'); },
function () { sys.p('three'); }
]);
async.parallel([
async.apply(fs.writeFile, 'testfile1', 'test1'),
async.apply(fs.writeFile, 'testfile2', 'test2'),
]);
async.parallel([
function (callback) {
fs.writeFile('testfile1', 'test1', callback);
},
function (callback) {
fs.writeFile('testfile2', 'test2', callback);
},
]);
var call_order = [];
async.nextTick(function () {
call_order.push('two');
});
call_order.push('one');
var slow_fn = function (name, callback) {
callback(null, 123);
};
var fn = async.memoize(slow_fn);
fn('some name', function () {});
async.unmemoize(fn);
async.ensureAsync(function () { });
async.constant(42);
async.asyncify(function () { });
async.log(function (name, callback) {
setTimeout(function () {
callback(null, 'hello ' + name);
}, 0);
}, "world"
);
async.dir(function (name, callback) {
setTimeout(function () {
callback(null, { hello: name });
}, 1000);
}, "world");

View File

@@ -1 +1 @@

330
async/async.d.ts vendored
View File

@@ -1,165 +1,165 @@
// Type definitions for Async 1.4.2
// Project: https://github.com/caolan/async
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Arseniy Maximov <https://github.com/kern0>, Joe Herman <https://github.com/Penryn>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Dictionary<T> { [key: string]: T; }
interface ErrorCallback { (err?: Error): void; }
interface AsyncResultCallback<T> { (err: Error, result: T): void; }
interface AsyncResultArrayCallback<T> { (err: Error, results: T[]): void; }
interface AsyncResultObjectCallback<T> { (err: Error, results: Dictionary<T>): void; }
interface AsyncFunction<T> { (callback: (err?: Error, result?: T) => void): void; }
interface AsyncIterator<T> { (item: T, callback: ErrorCallback): void; }
interface AsyncForEachOfIterator<T> { (item: T, key: number, callback: ErrorCallback): void; }
interface AsyncResultIterator<T, R> { (item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: (truthValue: boolean) => void): void; }
interface AsyncWorker<T> { (task: T, callback: ErrorCallback): void; }
interface AsyncVoidFunction { (callback: ErrorCallback): void; }
interface AsyncQueue<T> {
length(): number;
started: boolean;
running(): number;
idle(): boolean;
concurrency: number;
push(task: T, callback?: ErrorCallback): void;
push(task: T[], callback?: ErrorCallback): void;
unshift(task: T, callback?: ErrorCallback): void;
unshift(task: T[], callback?: ErrorCallback): void;
saturated: () => any;
empty: () => any;
drain: () => any;
paused: boolean;
pause(): void
resume(): void;
kill(): void;
}
interface AsyncPriorityQueue<T> {
length(): number;
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, priority: number, callback?: AsyncResultArrayCallback<T>): void;
push(task: T[], priority: number, callback?: AsyncResultArrayCallback<T>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
running(): number;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface AsyncCargo {
length(): number;
payload: number;
push(task: any, callback? : Function): void;
push(task: any[], callback? : Function): void;
saturated(): void;
empty(): void;
drain(): void;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface Async {
// Collections
each<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachLimit<T>(arr: T[], limit: number, iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
forEachOf(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOf<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfSeries(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOfSeries<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOfLimit<T>(obj: T[], limit: number, iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
select<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
filterSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
selectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
selectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
reject<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
rejectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
rejectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback?: AsyncResultArrayCallback<T>): any;
some<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
someLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
any<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
every<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
everyLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
// Control Flow
series<T>(tasks: AsyncFunction<T>[], callback?: AsyncResultArrayCallback<T>): void;
series<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallel<T>(tasks: Array<AsyncFunction<T>>, callback?: AsyncResultArrayCallback<T>): void;
parallel<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallelLimit<T>(tasks: Array<AsyncFunction<T>>, limit: number, callback?: AsyncResultArrayCallback<T>): void;
parallelLimit<T>(tasks: Dictionary<AsyncFunction<T>>, limit: number, callback?: AsyncResultObjectCallback<T>): void;
whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void;
forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void;
waterfall(tasks: Function[], callback?: (err: Error, results?: any) => void): void;
compose(...fns: Function[]): void;
seq(...fns: Function[]): void;
applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
queue<T>(worker: AsyncWorker<T>, concurrency?: number): AsyncQueue<T>;
priorityQueue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncPriorityQueue<T>;
cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo;
auto(tasks: any, callback?: (error: Error, results: any) => void): void;
retry<T>(opts: number, task: (callback : AsyncResultCallback<T>, results: any) => void, callback: (error: Error, results: any) => void): void;
retry<T>(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback<T>, results : any) => void, callback: (error: Error, results: any) => void): void;
iterator(tasks: Function[]): Function;
apply(fn: Function, ...arguments: any[]): AsyncFunction<any>;
nextTick(callback: Function): void;
setImmediate(callback: Function): void;
times<T> (n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesSeries<T>(n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesLimit<T>(n: number, limit: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
// Utils
memoize(fn: Function, hasher?: Function): Function;
unmemoize(fn: Function): Function;
ensureAsync(fn: (... argsAndCallback: any[]) => void): Function;
constant(...values: any[]): Function;
asyncify(fn: Function): Function;
wrapSync(fn: Function): Function;
log(fn: Function, ...arguments: any[]): void;
dir(fn: Function, ...arguments: any[]): void;
noConflict(): Async;
}
declare var async: Async;
declare module "async" {
export = async;
}
// Type definitions for Async 1.4.2
// Project: https://github.com/caolan/async
// Definitions by: Boris Yankov <https://github.com/borisyankov/>, Arseniy Maximov <https://github.com/kern0>, Joe Herman <https://github.com/Penryn>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Dictionary<T> { [key: string]: T; }
interface ErrorCallback { (err?: Error): void; }
interface AsyncResultCallback<T> { (err: Error, result: T): void; }
interface AsyncResultArrayCallback<T> { (err: Error, results: T[]): void; }
interface AsyncResultObjectCallback<T> { (err: Error, results: Dictionary<T>): void; }
interface AsyncFunction<T> { (callback: (err?: Error, result?: T) => void): void; }
interface AsyncIterator<T> { (item: T, callback: ErrorCallback): void; }
interface AsyncForEachOfIterator<T> { (item: T, key: number, callback: ErrorCallback): void; }
interface AsyncResultIterator<T, R> { (item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncMemoIterator<T, R> { (memo: R, item: T, callback: AsyncResultCallback<R>): void; }
interface AsyncBooleanIterator<T> { (item: T, callback: (truthValue: boolean) => void): void; }
interface AsyncWorker<T> { (task: T, callback: ErrorCallback): void; }
interface AsyncVoidFunction { (callback: ErrorCallback): void; }
interface AsyncQueue<T> {
length(): number;
started: boolean;
running(): number;
idle(): boolean;
concurrency: number;
push(task: T, callback?: ErrorCallback): void;
push(task: T[], callback?: ErrorCallback): void;
unshift(task: T, callback?: ErrorCallback): void;
unshift(task: T[], callback?: ErrorCallback): void;
saturated: () => any;
empty: () => any;
drain: () => any;
paused: boolean;
pause(): void
resume(): void;
kill(): void;
}
interface AsyncPriorityQueue<T> {
length(): number;
concurrency: number;
started: boolean;
paused: boolean;
push(task: T, priority: number, callback?: AsyncResultArrayCallback<T>): void;
push(task: T[], priority: number, callback?: AsyncResultArrayCallback<T>): void;
saturated: () => any;
empty: () => any;
drain: () => any;
running(): number;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface AsyncCargo {
length(): number;
payload: number;
push(task: any, callback? : Function): void;
push(task: any[], callback? : Function): void;
saturated(): void;
empty(): void;
drain(): void;
idle(): boolean;
pause(): void;
resume(): void;
kill(): void;
}
interface Async {
// Collections
each<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachSeries<T>(arr: T[], iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
eachLimit<T>(arr: T[], limit: number, iterator: AsyncIterator<T>, callback?: ErrorCallback): void;
forEachOf(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOf<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfSeries(obj: any, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOfSeries<T>(obj: T[], iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
forEachOfLimit(obj: any, limit: number, iterator: (item: any, key: string|number, callback?: ErrorCallback) => void, callback: ErrorCallback): void;
forEachOfLimit<T>(obj: T[], limit: number, iterator: AsyncForEachOfIterator<T>, callback?: ErrorCallback): void;
map<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
mapLimit<T, R>(arr: T[], limit: number, iterator: AsyncResultIterator<T, R>, callback?: AsyncResultArrayCallback<R>): any;
filter<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
select<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
filterSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
selectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
filterLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
selectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
reject<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
rejectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
rejectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (results: T[]) => any): any;
reduce<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
inject<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
foldl<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback?: AsyncResultCallback<R>): any;
reduceRight<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
foldr<T, R>(arr: T[], memo: R, iterator: AsyncMemoIterator<T, R>, callback: AsyncResultCallback<R>): any;
detect<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectSeries<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
detectLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: T) => void): any;
sortBy<T, V>(arr: T[], iterator: AsyncResultIterator<T, V>, callback?: AsyncResultArrayCallback<T>): any;
some<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
someLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
any<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => void): any;
every<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
everyLimit<T>(arr: T[], limit: number, iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
all<T>(arr: T[], iterator: AsyncBooleanIterator<T>, callback?: (result: boolean) => any): any;
concat<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
concatSeries<T, R>(arr: T[], iterator: AsyncResultIterator<T, R[]>, callback?: AsyncResultArrayCallback<R>): any;
// Control Flow
series<T>(tasks: AsyncFunction<T>[], callback?: AsyncResultArrayCallback<T>): void;
series<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallel<T>(tasks: Array<AsyncFunction<T>>, callback?: AsyncResultArrayCallback<T>): void;
parallel<T>(tasks: Dictionary<AsyncFunction<T>>, callback?: AsyncResultObjectCallback<T>): void;
parallelLimit<T>(tasks: Array<AsyncFunction<T>>, limit: number, callback?: AsyncResultArrayCallback<T>): void;
parallelLimit<T>(tasks: Dictionary<AsyncFunction<T>>, limit: number, callback?: AsyncResultObjectCallback<T>): void;
whilst(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doWhilst(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
until(test: () => boolean, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doUntil(fn: AsyncVoidFunction, test: () => boolean, callback: (err: any) => void): void;
during(test: (testCallback : (error: Error, truth: boolean) => void) => void, fn: AsyncVoidFunction, callback: (err: any) => void): void;
doDuring(fn: AsyncVoidFunction, test: (testCallback: (error: Error, truth: boolean) => void) => void, callback: (err: any) => void): void;
forever(next: (errCallback : (err: Error) => void) => void, errBack: (err: Error) => void) : void;
waterfall(tasks: Function[], callback?: (err: Error, results?: any) => void): void;
compose(...fns: Function[]): void;
seq(...fns: Function[]): void;
applyEach(fns: Function[], argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
applyEachSeries(fns: Function[], argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional.
queue<T>(worker: AsyncWorker<T>, concurrency?: number): AsyncQueue<T>;
priorityQueue<T>(worker: AsyncWorker<T>, concurrency: number): AsyncPriorityQueue<T>;
cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo;
auto(tasks: any, callback?: (error: Error, results: any) => void): void;
retry<T>(opts: number, task: (callback : AsyncResultCallback<T>, results: any) => void, callback: (error: Error, results: any) => void): void;
retry<T>(opts: { times: number, interval: number }, task: (callback: AsyncResultCallback<T>, results : any) => void, callback: (error: Error, results: any) => void): void;
iterator(tasks: Function[]): Function;
apply(fn: Function, ...arguments: any[]): AsyncFunction<any>;
nextTick(callback: Function): void;
setImmediate(callback: Function): void;
times<T> (n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesSeries<T>(n: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
timesLimit<T>(n: number, limit: number, iterator: AsyncResultIterator<number, T>, callback: AsyncResultArrayCallback<T>): void;
// Utils
memoize(fn: Function, hasher?: Function): Function;
unmemoize(fn: Function): Function;
ensureAsync(fn: (... argsAndCallback: any[]) => void): Function;
constant(...values: any[]): Function;
asyncify(fn: Function): Function;
wrapSync(fn: Function): Function;
log(fn: Function, ...arguments: any[]): void;
dir(fn: Function, ...arguments: any[]): void;
noConflict(): Async;
}
declare var async: Async;
declare module "async" {
export = async;
}

View File

@@ -1,5 +1,5 @@
/// <reference path="./async.d.ts" />
import async = require("async");
async.map(["a", "b", "c"], (item, cb) => cb(null, [item.toUpperCase()]), (err, results) => { });
/// <reference path="./async.d.ts" />
import async = require("async");
async.map(["a", "b", "c"], (item, cb) => cb(null, [item.toUpperCase()]), (err, results) => { });

View File

@@ -1,73 +1,73 @@
// Type definitions for asyncblock 2.1.23
// Project: https://github.com/scriby/asyncblock
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "asyncblock" {
function asyncblock<T>(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void;
module asyncblock {
export function nostack<T>(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void;
export interface IFlow {
add(responseFormat?: string[]): IExecuteFunction;
add(key: string, responseFormat?: string[]): IExecuteFunction;
add(key: number, responseFormat?: string[]): IExecuteFunction;
add(options: IFlowOptions): IExecuteFunction;
callback(responseFormat?: string[]): IExecuteFunction;
callback(key: string, responseFormat?: string[]): IExecuteFunction;
callback(key: number, responseFormat?: string[]): IExecuteFunction;
callback(options: IFlowOptions): IExecuteFunction;
wait<T>(key?: string): T;
wait<T>(key?: number): T;
get<T>(key: string): T;
set(key: string, responseFormat?: string[]): IExecuteFunction;
set(options: IFlowOptions): IExecuteFunction;
del(key: string): void;
sync<T>(task: any): T;
queue(toExecute: IExecuteFunction): void;
queue(key: string, toExecute: IExecuteFunction): void;
queue(key: number, toExecute: IExecuteFunction): void;
queue(responseFormat: string[], toExecute: IExecuteFunction): void;
queue(key: string, responseFormat: string[], toExecute: IExecuteFunction): void;
queue(key: number, responseFormat: string[], toExecute: IExecuteFunction): void;
queue(options: IFlowOptions, toExecute: IExecuteFunction): void;
doneAdding(): void;
forceWait<T>(): T;
maxParallel: number;
errorCallback: (err: any) => void;
taskTimeout: number;
timeoutIsError: boolean;
}
export interface IFlowOptions {
ignoreError?: boolean; // default false
key?: string; // string | number
responseFormat?: string[];
timeout?: number;
timeoutIsError?: boolean;
dontWait?: boolean;
firstArgIsError?: boolean; // default true
}
export interface IExecuteFunction {
<T1, T2, T3>(err: any, res1: T1, res2: T2, res3: T3): any;
<T1, T2>(err: any, res1: T1, res2: T2): any;
<T>(err: any, res: T): any;
(err: any): any;
// firstArgIsError === false
<T1, T2, T3>(res1: T1, res2: T2, res3: T3): any;
<T1, T2>(res1: T1, res2: T2): any;
<T>(res: T): any;
}
}
export = asyncblock;
}
// Type definitions for asyncblock 2.1.23
// Project: https://github.com/scriby/asyncblock
// Definitions by: Hiroki Horiuchi <https://github.com/horiuchi/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "asyncblock" {
function asyncblock<T>(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void;
module asyncblock {
export function nostack<T>(f: (flow: asyncblock.IFlow) => void, callback?: (err: any, res: T) => void): void;
export interface IFlow {
add(responseFormat?: string[]): IExecuteFunction;
add(key: string, responseFormat?: string[]): IExecuteFunction;
add(key: number, responseFormat?: string[]): IExecuteFunction;
add(options: IFlowOptions): IExecuteFunction;
callback(responseFormat?: string[]): IExecuteFunction;
callback(key: string, responseFormat?: string[]): IExecuteFunction;
callback(key: number, responseFormat?: string[]): IExecuteFunction;
callback(options: IFlowOptions): IExecuteFunction;
wait<T>(key?: string): T;
wait<T>(key?: number): T;
get<T>(key: string): T;
set(key: string, responseFormat?: string[]): IExecuteFunction;
set(options: IFlowOptions): IExecuteFunction;
del(key: string): void;
sync<T>(task: any): T;
queue(toExecute: IExecuteFunction): void;
queue(key: string, toExecute: IExecuteFunction): void;
queue(key: number, toExecute: IExecuteFunction): void;
queue(responseFormat: string[], toExecute: IExecuteFunction): void;
queue(key: string, responseFormat: string[], toExecute: IExecuteFunction): void;
queue(key: number, responseFormat: string[], toExecute: IExecuteFunction): void;
queue(options: IFlowOptions, toExecute: IExecuteFunction): void;
doneAdding(): void;
forceWait<T>(): T;
maxParallel: number;
errorCallback: (err: any) => void;
taskTimeout: number;
timeoutIsError: boolean;
}
export interface IFlowOptions {
ignoreError?: boolean; // default false
key?: string; // string | number
responseFormat?: string[];
timeout?: number;
timeoutIsError?: boolean;
dontWait?: boolean;
firstArgIsError?: boolean; // default true
}
export interface IExecuteFunction {
<T1, T2, T3>(err: any, res1: T1, res2: T2, res3: T3): any;
<T1, T2>(err: any, res1: T1, res2: T2): any;
<T>(err: any, res: T): any;
(err: any): any;
// firstArgIsError === false
<T1, T2, T3>(res1: T1, res2: T2, res3: T3): any;
<T1, T2>(res1: T1, res2: T2): any;
<T>(res: T): any;
}
}
export = asyncblock;
}

View File

@@ -1 +1 @@
--noImplicitAny ./underscore/underscore.d.ts
--noImplicitAny ./underscore/underscore.d.ts

View File

@@ -1,313 +1,313 @@
/// <reference path="backbone.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
function test_events() {
var object = new Backbone.Events();
object.on("alert", (eventName: string) => alert("Triggered " + eventName));
object.trigger("alert", "an event");
var onChange = () => alert('whatever');
var context: any;
object.off("change", onChange);
object.off("change");
object.off(null, onChange);
object.off(null, null, context);
object.off();
}
class SettingDefaults extends Backbone.Model {
// 'defaults' could be set in one of the following ways:
defaults() {
return {
name: "Joe"
}
}
constructor(attributes?: any, options?: any) {
this.defaults = <any>{
name: "Joe"
}
// super has to come last
super(attributes, options);
}
// or set it like this
initialize() {
this.defaults = <any>{
name: "Joe"
}
}
// same patterns could be used for setting 'Router.routes' and 'View.events'
}
class Sidebar extends Backbone.Model {
promptColor() {
var cssColor = prompt("Please enter a CSS color:");
this.set({ color: cssColor });
}
}
class Note extends Backbone.Model {
initialize() { }
author() { }
coordinates() { }
allowedToEdit(account: any) {
return true;
}
}
class PrivateNote extends Note {
allowedToEdit(account: any) {
return account.owns(this);
}
set(attributes: any, options?: any): Backbone.Model {
return Backbone.Model.prototype.set.call(this, attributes, options);
}
}
function test_models() {
var sidebar = new Sidebar();
sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color }));
sidebar.set({ color: 'white' });
sidebar.promptColor();
//////////
var note = new PrivateNote();
note.get("title");
note.set({ title: "March 20", content: "In his eyes she eclipses..." });
note.set("title", "A Scandal in Bohemia");
}
class Employee extends Backbone.Model {
reports: EmployeeCollection;
constructor(attributes?: any, options?: any) {
super(options);
this.reports = new EmployeeCollection();
this.reports.url = '../api/employees/' + this.id + '/reports';
}
more() {
this.reports.reset();
}
}
class EmployeeCollection extends Backbone.Collection<Employee> {
findByName(key: any) { }
}
class Book extends Backbone.Model {
title: string;
author: string;
published: boolean;
}
class Library extends Backbone.Collection<Book> {
// This model definition is here only to test type compatibility of the model, but it
// is not necessary in working code as it is automatically inferred through generics.
model: typeof Book;
}
class Books extends Backbone.Collection<Book> { }
function test_collection() {
var books = new Books();
var book1: Book = new Book({ title: "Title 1", author: "Mike" });
books.add(book1);
// Objects can be added to collection by casting to model type.
// Compiler will check if object properties are valid for the cast.
// This gives better type checking than declaring an `any` overload.
books.add(<Book>{ title: "Title 2", author: "Mikey" });
var model: Book = book1.collection.first();
if (model !== book1) {
throw new Error("Error");
}
books.each(book =>
book.get("title"));
var titles = books.map(book =>
book.get("title"));
var publishedBooks = books.filter(book =>
book.get("published") === true);
var alphabetical = books.sortBy((book: Book): number => null);
}
//////////
Backbone.history.start();
module v1Changes {
module events {
function test_once() {
var model = new Employee;
model.once('invalid', () => { }, this);
model.once('invalid', () => { });
}
function test_listenTo() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.listenTo(model, 'invalid', () => { });
}
function test_listenToOnce() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.listenToOnce(model, 'invalid', () => { });
}
function test_stopListening() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.stopListening(model, 'invalid', () => { });
view.stopListening(model, 'invalid');
view.stopListening(model);
}
}
module ModelAndCollection {
function test_url() {
Employee.prototype.url = () => '/employees';
EmployeeCollection.prototype.url = () => '/employees';
}
function test_parse() {
var model = new Employee();
model.parse('{}', {});
var collection = new EmployeeCollection;
collection.parse('{}', {});
}
function test_toJSON() {
var model = new Employee();
model.toJSON({});
var collection = new EmployeeCollection;
collection.toJSON({});
}
function test_sync() {
var model = new Employee();
model.sync();
var collection = new EmployeeCollection;
collection.sync();
}
}
module Model {
function test_validationError() {
var model = new Employee;
if (model.validationError) {
console.log('has validation errors');
}
}
function test_fetch() {
var model = new Employee({ id: 1 });
model.fetch({
success: () => { },
error: () => { }
});
}
function test_set() {
var model = new Employee;
model.set({ name: 'JoeDoe', age: 21 }, { validate: false });
model.set('name', 'JoeDoes', { validate: false });
}
function test_destroy() {
var model = new Employee;
model.destroy({
wait: true,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?, options?) => { }
});
model.destroy({
success: (m?, response?, options?) => { },
error: (m?, jqxhr?) => { }
});
model.destroy({
success: () => { },
error: (m?, jqxhr?) => { }
});
}
function test_save() {
var model = new Employee;
model.save({
name: 'Joe Doe',
age: 21
},
{
wait: true,
validate: false,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?, options?) => { }
});
model.save({
name: 'Joe Doe',
age: 21
},
{
success: () => { },
error: (m?, jqxhr?) => { }
});
}
function test_validate() {
var model = new Employee;
model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false })
}
}
module Collection {
function test_fetch() {
var collection = new EmployeeCollection;
collection.fetch({ reset: true });
}
function test_create() {
var collection = new EmployeeCollection;
var model = new Employee;
collection.create(model, {
validate: false
});
}
}
module Router {
function test_navigate() {
var router = new Backbone.Router;
router.navigate('/employees', { trigger: true });
router.navigate('/employees', true);
}
}
}
/// <reference path="backbone.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
function test_events() {
var object = new Backbone.Events();
object.on("alert", (eventName: string) => alert("Triggered " + eventName));
object.trigger("alert", "an event");
var onChange = () => alert('whatever');
var context: any;
object.off("change", onChange);
object.off("change");
object.off(null, onChange);
object.off(null, null, context);
object.off();
}
class SettingDefaults extends Backbone.Model {
// 'defaults' could be set in one of the following ways:
defaults() {
return {
name: "Joe"
}
}
constructor(attributes?: any, options?: any) {
this.defaults = <any>{
name: "Joe"
}
// super has to come last
super(attributes, options);
}
// or set it like this
initialize() {
this.defaults = <any>{
name: "Joe"
}
}
// same patterns could be used for setting 'Router.routes' and 'View.events'
}
class Sidebar extends Backbone.Model {
promptColor() {
var cssColor = prompt("Please enter a CSS color:");
this.set({ color: cssColor });
}
}
class Note extends Backbone.Model {
initialize() { }
author() { }
coordinates() { }
allowedToEdit(account: any) {
return true;
}
}
class PrivateNote extends Note {
allowedToEdit(account: any) {
return account.owns(this);
}
set(attributes: any, options?: any): Backbone.Model {
return Backbone.Model.prototype.set.call(this, attributes, options);
}
}
function test_models() {
var sidebar = new Sidebar();
sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color }));
sidebar.set({ color: 'white' });
sidebar.promptColor();
//////////
var note = new PrivateNote();
note.get("title");
note.set({ title: "March 20", content: "In his eyes she eclipses..." });
note.set("title", "A Scandal in Bohemia");
}
class Employee extends Backbone.Model {
reports: EmployeeCollection;
constructor(attributes?: any, options?: any) {
super(options);
this.reports = new EmployeeCollection();
this.reports.url = '../api/employees/' + this.id + '/reports';
}
more() {
this.reports.reset();
}
}
class EmployeeCollection extends Backbone.Collection<Employee> {
findByName(key: any) { }
}
class Book extends Backbone.Model {
title: string;
author: string;
published: boolean;
}
class Library extends Backbone.Collection<Book> {
// This model definition is here only to test type compatibility of the model, but it
// is not necessary in working code as it is automatically inferred through generics.
model: typeof Book;
}
class Books extends Backbone.Collection<Book> { }
function test_collection() {
var books = new Books();
var book1: Book = new Book({ title: "Title 1", author: "Mike" });
books.add(book1);
// Objects can be added to collection by casting to model type.
// Compiler will check if object properties are valid for the cast.
// This gives better type checking than declaring an `any` overload.
books.add(<Book>{ title: "Title 2", author: "Mikey" });
var model: Book = book1.collection.first();
if (model !== book1) {
throw new Error("Error");
}
books.each(book =>
book.get("title"));
var titles = books.map(book =>
book.get("title"));
var publishedBooks = books.filter(book =>
book.get("published") === true);
var alphabetical = books.sortBy((book: Book): number => null);
}
//////////
Backbone.history.start();
module v1Changes {
module events {
function test_once() {
var model = new Employee;
model.once('invalid', () => { }, this);
model.once('invalid', () => { });
}
function test_listenTo() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.listenTo(model, 'invalid', () => { });
}
function test_listenToOnce() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.listenToOnce(model, 'invalid', () => { });
}
function test_stopListening() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.stopListening(model, 'invalid', () => { });
view.stopListening(model, 'invalid');
view.stopListening(model);
}
}
module ModelAndCollection {
function test_url() {
Employee.prototype.url = () => '/employees';
EmployeeCollection.prototype.url = () => '/employees';
}
function test_parse() {
var model = new Employee();
model.parse('{}', {});
var collection = new EmployeeCollection;
collection.parse('{}', {});
}
function test_toJSON() {
var model = new Employee();
model.toJSON({});
var collection = new EmployeeCollection;
collection.toJSON({});
}
function test_sync() {
var model = new Employee();
model.sync();
var collection = new EmployeeCollection;
collection.sync();
}
}
module Model {
function test_validationError() {
var model = new Employee;
if (model.validationError) {
console.log('has validation errors');
}
}
function test_fetch() {
var model = new Employee({ id: 1 });
model.fetch({
success: () => { },
error: () => { }
});
}
function test_set() {
var model = new Employee;
model.set({ name: 'JoeDoe', age: 21 }, { validate: false });
model.set('name', 'JoeDoes', { validate: false });
}
function test_destroy() {
var model = new Employee;
model.destroy({
wait: true,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?, options?) => { }
});
model.destroy({
success: (m?, response?, options?) => { },
error: (m?, jqxhr?) => { }
});
model.destroy({
success: () => { },
error: (m?, jqxhr?) => { }
});
}
function test_save() {
var model = new Employee;
model.save({
name: 'Joe Doe',
age: 21
},
{
wait: true,
validate: false,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?, options?) => { }
});
model.save({
name: 'Joe Doe',
age: 21
},
{
success: () => { },
error: (m?, jqxhr?) => { }
});
}
function test_validate() {
var model = new Employee;
model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false })
}
}
module Collection {
function test_fetch() {
var collection = new EmployeeCollection;
collection.fetch({ reset: true });
}
function test_create() {
var collection = new EmployeeCollection;
var model = new Employee;
collection.create(model, {
validate: false
});
}
}
module Router {
function test_navigate() {
var router = new Backbone.Router;
router.navigate('/employees', { trigger: true });
router.navigate('/employees', true);
}
}
}

View File

@@ -1,314 +1,314 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path='../lodash/lodash-3.10.d.ts' />
/// <reference path="./backbone-global.d.ts" />
function test_events() {
var object = new Backbone.Events();
object.on("alert", (eventName: string) => alert("Triggered " + eventName));
object.trigger("alert", "an event");
var onChange = () => alert('whatever');
var context: any;
object.off("change", onChange);
object.off("change");
object.off(null, onChange);
object.off(null, null, context);
object.off();
}
class SettingDefaults extends Backbone.Model {
// 'defaults' could be set in one of the following ways:
defaults() {
return {
name: "Joe"
}
}
constructor(attributes?: any, options?: any) {
this.defaults = <any>{
name: "Joe"
}
// super has to come last
super(attributes, options);
}
// or set it like this
initialize() {
this.defaults = <any>{
name: "Joe"
}
}
// same patterns could be used for setting 'Router.routes' and 'View.events'
}
class Sidebar extends Backbone.Model {
promptColor() {
var cssColor = prompt("Please enter a CSS color:");
this.set({ color: cssColor });
}
}
class Note extends Backbone.Model {
initialize() { }
author() { }
coordinates() { }
allowedToEdit(account: any) {
return true;
}
}
class PrivateNote extends Note {
allowedToEdit(account: any) {
return account.owns(this);
}
set(attributes: any, options?: any): Backbone.Model {
return Backbone.Model.prototype.set.call(this, attributes, options);
}
}
function test_models() {
var sidebar = new Sidebar();
sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color }));
sidebar.set({ color: 'white' });
sidebar.promptColor();
//////////
var note = new PrivateNote();
note.get("title");
note.set({ title: "March 20", content: "In his eyes she eclipses..." });
note.set("title", "A Scandal in Bohemia");
}
class Employee extends Backbone.Model {
reports: EmployeeCollection;
constructor(attributes?: any, options?: any) {
super(options);
this.reports = new EmployeeCollection();
this.reports.url = '../api/employees/' + this.id + '/reports';
}
more() {
this.reports.reset();
}
}
class EmployeeCollection extends Backbone.Collection<Employee> {
findByName(key: any) { }
}
class Book extends Backbone.Model {
title: string;
author: string;
published: boolean;
}
class Library extends Backbone.Collection<Book> {
// This model definition is here only to test type compatibility of the model, but it
// is not necessary in working code as it is automatically inferred through generics.
model: typeof Book;
}
class Books extends Backbone.Collection<Book> { }
function test_collection() {
var books = new Books();
var book1: Book = new Book({ title: "Title 1", author: "Mike" });
books.add(book1);
// Objects can be added to collection by casting to model type.
// Compiler will check if object properties are valid for the cast.
// This gives better type checking than declaring an `any` overload.
books.add(<Book>{ title: "Title 2", author: "Mikey" });
var model: Book = book1.collection.first();
if (model !== book1) {
throw new Error("Error");
}
books.each(book =>
book.get("title"));
var titles = books.map(book =>
book.get("title"));
var publishedBooks = books.filter(book =>
book.get("published") === true);
var alphabetical = books.sortBy((book: Book): number => null);
}
//////////
Backbone.history.start();
module v1Changes {
module events {
function test_once() {
var model = new Employee;
model.once('invalid', () => { }, this);
model.once('invalid', () => { });
}
function test_listenTo() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.listenTo(model, 'invalid', () => { });
}
function test_listenToOnce() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.listenToOnce(model, 'invalid', () => { });
}
function test_stopListening() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.stopListening(model, 'invalid', () => { });
view.stopListening(model, 'invalid');
view.stopListening(model);
}
}
module ModelAndCollection {
function test_url() {
Employee.prototype.url = () => '/employees';
EmployeeCollection.prototype.url = () => '/employees';
}
function test_parse() {
var model = new Employee();
model.parse('{}', {});
var collection = new EmployeeCollection;
collection.parse('{}', {});
}
function test_toJSON() {
var model = new Employee();
model.toJSON({});
var collection = new EmployeeCollection;
collection.toJSON({});
}
function test_sync() {
var model = new Employee();
model.sync();
var collection = new EmployeeCollection;
collection.sync();
}
}
module Model {
function test_validationError() {
var model = new Employee;
if (model.validationError) {
console.log('has validation errors');
}
}
function test_fetch() {
var model = new Employee({ id: 1 });
model.fetch({
success: () => { },
error: () => { }
});
}
function test_set() {
var model = new Employee;
model.set({ name: 'JoeDoe', age: 21 }, { validate: false });
model.set('name', 'JoeDoes', { validate: false });
}
function test_destroy() {
var model = new Employee;
model.destroy({
wait: true,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?, options?) => { }
});
model.destroy({
success: (m?, response?, options?) => { },
error: (m?, jqxhr?) => { }
});
model.destroy({
success: () => { },
error: (m?, jqxhr?) => { }
});
}
function test_save() {
var model = new Employee;
model.save({
name: 'Joe Doe',
age: 21
},
{
wait: true,
validate: false,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?, options?) => { }
});
model.save({
name: 'Joe Doe',
age: 21
},
{
success: () => { },
error: (m?, jqxhr?) => { }
});
}
function test_validate() {
var model = new Employee;
model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false })
}
}
module Collection {
function test_fetch() {
var collection = new EmployeeCollection;
collection.fetch({ reset: true });
}
function test_create() {
var collection = new EmployeeCollection;
var model = new Employee;
collection.create(model, {
validate: false
});
}
}
module Router {
function test_navigate() {
var router = new Backbone.Router;
router.navigate('/employees', { trigger: true });
router.navigate('/employees', true);
}
}
}
/// <reference path="./backbone-global.d.ts" />
function test_events() {
var object = new Backbone.Events();
object.on("alert", (eventName: string) => alert("Triggered " + eventName));
object.trigger("alert", "an event");
var onChange = () => alert('whatever');
var context: any;
object.off("change", onChange);
object.off("change");
object.off(null, onChange);
object.off(null, null, context);
object.off();
}
class SettingDefaults extends Backbone.Model {
// 'defaults' could be set in one of the following ways:
defaults() {
return {
name: "Joe"
}
}
constructor(attributes?: any, options?: any) {
this.defaults = <any>{
name: "Joe"
}
// super has to come last
super(attributes, options);
}
// or set it like this
initialize() {
this.defaults = <any>{
name: "Joe"
}
}
// same patterns could be used for setting 'Router.routes' and 'View.events'
}
class Sidebar extends Backbone.Model {
promptColor() {
var cssColor = prompt("Please enter a CSS color:");
this.set({ color: cssColor });
}
}
class Note extends Backbone.Model {
initialize() { }
author() { }
coordinates() { }
allowedToEdit(account: any) {
return true;
}
}
class PrivateNote extends Note {
allowedToEdit(account: any) {
return account.owns(this);
}
set(attributes: any, options?: any): Backbone.Model {
return Backbone.Model.prototype.set.call(this, attributes, options);
}
}
function test_models() {
var sidebar = new Sidebar();
sidebar.on('change:color', (model: {}, color: string) => $('#sidebar').css({ background: color }));
sidebar.set({ color: 'white' });
sidebar.promptColor();
//////////
var note = new PrivateNote();
note.get("title");
note.set({ title: "March 20", content: "In his eyes she eclipses..." });
note.set("title", "A Scandal in Bohemia");
}
class Employee extends Backbone.Model {
reports: EmployeeCollection;
constructor(attributes?: any, options?: any) {
super(options);
this.reports = new EmployeeCollection();
this.reports.url = '../api/employees/' + this.id + '/reports';
}
more() {
this.reports.reset();
}
}
class EmployeeCollection extends Backbone.Collection<Employee> {
findByName(key: any) { }
}
class Book extends Backbone.Model {
title: string;
author: string;
published: boolean;
}
class Library extends Backbone.Collection<Book> {
// This model definition is here only to test type compatibility of the model, but it
// is not necessary in working code as it is automatically inferred through generics.
model: typeof Book;
}
class Books extends Backbone.Collection<Book> { }
function test_collection() {
var books = new Books();
var book1: Book = new Book({ title: "Title 1", author: "Mike" });
books.add(book1);
// Objects can be added to collection by casting to model type.
// Compiler will check if object properties are valid for the cast.
// This gives better type checking than declaring an `any` overload.
books.add(<Book>{ title: "Title 2", author: "Mikey" });
var model: Book = book1.collection.first();
if (model !== book1) {
throw new Error("Error");
}
books.each(book =>
book.get("title"));
var titles = books.map(book =>
book.get("title"));
var publishedBooks = books.filter(book =>
book.get("published") === true);
var alphabetical = books.sortBy((book: Book): number => null);
}
//////////
Backbone.history.start();
module v1Changes {
module events {
function test_once() {
var model = new Employee;
model.once('invalid', () => { }, this);
model.once('invalid', () => { });
}
function test_listenTo() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.listenTo(model, 'invalid', () => { });
}
function test_listenToOnce() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.listenToOnce(model, 'invalid', () => { });
}
function test_stopListening() {
var model = new Employee;
var view = new Backbone.View<Employee>();
view.stopListening(model, 'invalid', () => { });
view.stopListening(model, 'invalid');
view.stopListening(model);
}
}
module ModelAndCollection {
function test_url() {
Employee.prototype.url = () => '/employees';
EmployeeCollection.prototype.url = () => '/employees';
}
function test_parse() {
var model = new Employee();
model.parse('{}', {});
var collection = new EmployeeCollection;
collection.parse('{}', {});
}
function test_toJSON() {
var model = new Employee();
model.toJSON({});
var collection = new EmployeeCollection;
collection.toJSON({});
}
function test_sync() {
var model = new Employee();
model.sync();
var collection = new EmployeeCollection;
collection.sync();
}
}
module Model {
function test_validationError() {
var model = new Employee;
if (model.validationError) {
console.log('has validation errors');
}
}
function test_fetch() {
var model = new Employee({ id: 1 });
model.fetch({
success: () => { },
error: () => { }
});
}
function test_set() {
var model = new Employee;
model.set({ name: 'JoeDoe', age: 21 }, { validate: false });
model.set('name', 'JoeDoes', { validate: false });
}
function test_destroy() {
var model = new Employee;
model.destroy({
wait: true,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?, options?) => { }
});
model.destroy({
success: (m?, response?, options?) => { },
error: (m?, jqxhr?) => { }
});
model.destroy({
success: () => { },
error: (m?, jqxhr?) => { }
});
}
function test_save() {
var model = new Employee;
model.save({
name: 'Joe Doe',
age: 21
},
{
wait: true,
validate: false,
success: (m?, response?, options?) => { },
error: (m?, jqxhr?, options?) => { }
});
model.save({
name: 'Joe Doe',
age: 21
},
{
success: () => { },
error: (m?, jqxhr?) => { }
});
}
function test_validate() {
var model = new Employee;
model.validate({ name: 'JoeDoe', age: 21 }, { validateAge: false })
}
}
module Collection {
function test_fetch() {
var collection = new EmployeeCollection;
collection.fetch({ reset: true });
}
function test_create() {
var collection = new EmployeeCollection;
var model = new Employee;
collection.create(model, {
validate: false
});
}
}
module Router {
function test_navigate() {
var router = new Backbone.Router;
router.navigate('/employees', { trigger: true });
router.navigate('/employees', true);
}
}
}

View File

@@ -1 +1 @@
--target ES5
--target ES5

View File

@@ -1 +1 @@
--target es5
--target es5

View File

@@ -1,11 +1,11 @@
/// <reference path="bitwise-xor.d.ts" />
"use strict";
import xor = require("bitwise-xor");
var b: Buffer;
b = xor("a", "b");
b = xor(new Buffer("a"), new Buffer("b"));
/// <reference path="bitwise-xor.d.ts" />
"use strict";
import xor = require("bitwise-xor");
var b: Buffer;
b = xor("a", "b");
b = xor(new Buffer("a"), new Buffer("b"));

View File

@@ -1,17 +1,17 @@
// Type definitions for bitwise-xor 0.0.0
// Project: https://github.com/czzarr/node-bitwise-xor
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "bitwise-xor" {
/**
* Bitwise XOR between two Buffers or Strings, returns a Buffer
*/
function xor(b1: Buffer, b2: Buffer): Buffer;
function xor(s1: string, s2: string): Buffer;
export = xor;
}
declare module "bitwise-xor" {
/**
* Bitwise XOR between two Buffers or Strings, returns a Buffer
*/
function xor(b1: Buffer, b2: Buffer): Buffer;
function xor(s1: string, s2: string): Buffer;
export = xor;
}

View File

@@ -1,106 +1,106 @@
// QUnit Tests for Bootbox 4.4.0
/// <reference path="bootbox.d.ts" />
bootbox.alert("Are we ok?");
bootbox.alert("Are we ok with callback?", function () {
console.log("Callback called!");
});
bootbox.alert({
size: "medium",
message: "Are we ok with callback and custom button?",
callback: function () {
console.log("Callback called!");
}
});
bootbox.confirm("Click cancel to pass test", function (result) {
console.log(!result);
});
bootbox.confirm({
message: "Click confirm to pass test",
callback: function (result) {
console.log(result);
}
});
bootbox.prompt("Enter 'ok' to pass test", function (result) {
console.log(result);
});
bootbox.prompt({
message: "Enter 'ok' to pass test", callback: function (result) {
console.log(result);
}
});
bootbox.prompt({
size: "large",
message: "Enter 'ok' to pass test", callback: function (result) {
console.log(result);
}
});
bootbox.dialog({
title: "Wassup?",
message: "Test Dialog",
callback: function (result) { }
});
// Testing the return object of the call. Using the pointer to disable the animation on success callback.
var bBox : JQuery;
bBox = bootbox.dialog({
message: "Test Dialog",
buttons: {
cancel: {
label: "Cancel"
},
confirm: {
label: "Continue",
callback: function () {
bBox.removeClass("fade");
console.log("Outer callback.");
}
}
},
animate: true,
});
var bdo: BootboxDialogOptions;
var sampleButton: BootboxButton = {
label: 'ButtonLabelToUse',
callback: function () {
return 'callback of button click'
},
className: 'additionalButtonClassName'
};
bdo = {
message: '',
className: 'callName',
buttons: {
'ButtonTextLabel': sampleButton
}
};
bootbox.dialog(bdo);
bootbox.setDefaults({
locale: 'en_US',
animate: false,
backdrop: false,
className: 'newClassName',
closeButton: true,
show: true
})
bootbox.hideAll();
var localeOptions: BootboxLocaleValues = {
OK: 'Hus',
CANCEL: 'Nai',
CONFIRM: 'Pakka'
}
bootbox.addLocale("Nepali", localeOptions);
bootbox.setLocale("Nepali");
// QUnit Tests for Bootbox 4.4.0
/// <reference path="bootbox.d.ts" />
bootbox.alert("Are we ok?");
bootbox.alert("Are we ok with callback?", function () {
console.log("Callback called!");
});
bootbox.alert({
size: "medium",
message: "Are we ok with callback and custom button?",
callback: function () {
console.log("Callback called!");
}
});
bootbox.confirm("Click cancel to pass test", function (result) {
console.log(!result);
});
bootbox.confirm({
message: "Click confirm to pass test",
callback: function (result) {
console.log(result);
}
});
bootbox.prompt("Enter 'ok' to pass test", function (result) {
console.log(result);
});
bootbox.prompt({
message: "Enter 'ok' to pass test", callback: function (result) {
console.log(result);
}
});
bootbox.prompt({
size: "large",
message: "Enter 'ok' to pass test", callback: function (result) {
console.log(result);
}
});
bootbox.dialog({
title: "Wassup?",
message: "Test Dialog",
callback: function (result) { }
});
// Testing the return object of the call. Using the pointer to disable the animation on success callback.
var bBox : JQuery;
bBox = bootbox.dialog({
message: "Test Dialog",
buttons: {
cancel: {
label: "Cancel"
},
confirm: {
label: "Continue",
callback: function () {
bBox.removeClass("fade");
console.log("Outer callback.");
}
}
},
animate: true,
});
var bdo: BootboxDialogOptions;
var sampleButton: BootboxButton = {
label: 'ButtonLabelToUse',
callback: function () {
return 'callback of button click'
},
className: 'additionalButtonClassName'
};
bdo = {
message: '',
className: 'callName',
buttons: {
'ButtonTextLabel': sampleButton
}
};
bootbox.dialog(bdo);
bootbox.setDefaults({
locale: 'en_US',
animate: false,
backdrop: false,
className: 'newClassName',
closeButton: true,
show: true
})
bootbox.hideAll();
var localeOptions: BootboxLocaleValues = {
OK: 'Hus',
CANCEL: 'Nai',
CONFIRM: 'Pakka'
}
bootbox.addLocale("Nepali", localeOptions);
bootbox.setLocale("Nepali");
bootbox.removeLocale("Nepali");

164
bootbox/bootbox.d.ts vendored
View File

@@ -1,82 +1,82 @@
// Type definitions for Bootbox 4.4.0
// Project: https://github.com/makeusabrew/bootbox
// Definitions by: Vincent Bortone <https://github.com/vbortone/>, Kon Pik <https://github.com/konpikwastaken/>, Anup Kattel <https://github.com/kanup/>, Dominik Schroeter <https://github.com/icereed/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface BootboxAlertOptions {
size?: string;
message: string;
callback?: () => any;
}
interface BootboxConfirmOptions {
size?: string;
message: string;
callback: (result: boolean) => any;
}
interface BootboxPromptOptions {
size?: string;
message?: string;
callback: (result: string) => any;
}
interface BootboxButton {
label?: string;
className?: string;
callback?: () => any;
}
interface BootboxButtonMap {
[key: string]: BootboxButton | Function;
}
interface BootboxDialogOptions {
message: string | Element;
title?: string | Element;
locale?: string;
callback?: (result: boolean) => any;
onEscape?: () => any | boolean;
show?: boolean;
backdrop?: boolean;
closeButton?: boolean;
animate?: boolean;
className?: string;
size?: string;
buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton
}
interface BootboxDefaultOptions {
locale?: string;
show?: boolean;
backdrop?: boolean;
closeButton?: boolean;
animate?: boolean;
className?: string;
}
interface BootboxLocaleValues {
OK: string;
CANCEL: string;
CONFIRM: string;
}
interface BootboxStatic {
alert(message: string, callback?: () => void): JQuery;
alert(options: BootboxAlertOptions): JQuery;
confirm(message: string, callback: (result: boolean) => void): JQuery;
confirm(options: BootboxConfirmOptions): JQuery;
prompt(message: string, callback: (result: string) => void): JQuery;
prompt(options: BootboxPromptOptions): JQuery;
dialog(message: string, callback?: (result: string) => void): JQuery;
dialog(options: BootboxDialogOptions): JQuery;
setDefaults(options: BootboxDefaultOptions): void;
hideAll(): void;
addLocale(name: string, values: BootboxLocaleValues): void;
removeLocale(name: string): void;
setLocale(name: string): void;
}
declare var bootbox: BootboxStatic;
// Type definitions for Bootbox 4.4.0
// Project: https://github.com/makeusabrew/bootbox
// Definitions by: Vincent Bortone <https://github.com/vbortone/>, Kon Pik <https://github.com/konpikwastaken/>, Anup Kattel <https://github.com/kanup/>, Dominik Schroeter <https://github.com/icereed/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts" />
interface BootboxAlertOptions {
size?: string;
message: string;
callback?: () => any;
}
interface BootboxConfirmOptions {
size?: string;
message: string;
callback: (result: boolean) => any;
}
interface BootboxPromptOptions {
size?: string;
message?: string;
callback: (result: string) => any;
}
interface BootboxButton {
label?: string;
className?: string;
callback?: () => any;
}
interface BootboxButtonMap {
[key: string]: BootboxButton | Function;
}
interface BootboxDialogOptions {
message: string | Element;
title?: string | Element;
locale?: string;
callback?: (result: boolean) => any;
onEscape?: () => any | boolean;
show?: boolean;
backdrop?: boolean;
closeButton?: boolean;
animate?: boolean;
className?: string;
size?: string;
buttons?: BootboxButtonMap; // complex object where each key is of type BootboxButton
}
interface BootboxDefaultOptions {
locale?: string;
show?: boolean;
backdrop?: boolean;
closeButton?: boolean;
animate?: boolean;
className?: string;
}
interface BootboxLocaleValues {
OK: string;
CANCEL: string;
CONFIRM: string;
}
interface BootboxStatic {
alert(message: string, callback?: () => void): JQuery;
alert(options: BootboxAlertOptions): JQuery;
confirm(message: string, callback: (result: boolean) => void): JQuery;
confirm(options: BootboxConfirmOptions): JQuery;
prompt(message: string, callback: (result: string) => void): JQuery;
prompt(options: BootboxPromptOptions): JQuery;
dialog(message: string, callback?: (result: string) => void): JQuery;
dialog(options: BootboxDialogOptions): JQuery;
setDefaults(options: BootboxDefaultOptions): void;
hideAll(): void;
addLocale(name: string, values: BootboxLocaleValues): void;
removeLocale(name: string): void;
setLocale(name: string): void;
}
declare var bootbox: BootboxStatic;

View File

@@ -1,82 +1,82 @@
/// <reference path="bootstrap.datepicker.d.ts"/>
function tests_simple() {
$('#datepicker').datepicker();
$('#datepicker').datepicker({
format: 'mm-dd-yyyy'
});
$('#datepicker').datepicker('setStartDate');
$('#datepicker').datepicker('setStartDate', null);
$('#datepicker').datepicker('setEndDate', '2012-12-31');
$('#date-end')
.datepicker()
.on('changeDate', function (ev) { ev; });
var startDate = new Date(2012, 1, 20);
var endDate = new Date(2012, 1, 25);
$('#date-start')
.datepicker()
//.on("changeDate", function (ev) { // bug https://typescript.codeplex.com/workitem/1976
.on("changeDate", function (ev: DatepickerEventObject) {
if (ev.date.valueOf() > endDate.valueOf()) {
$('#alert').show().find('strong').text('The start date must be before the end date.');
} else {
$('#alert').hide();
startDate = ev.date;
$('#date-start-display').text($('#date-start').data('date'));
}
$('#date-start').datepicker('hide');
});
$('#date-end')
.datepicker()
//.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976
.on('changeDate', function (ev: DatepickerEventObject) {
if (ev.date.valueOf() < startDate.valueOf()) {
$('#alert').show().find('strong').text('The end date must be after the start date.');
} else {
$('#alert').hide();
endDate = ev.date;
$('#date-end-display').text($('#date-end').data('date'));
}
$('#date-end').datepicker('hide');
});
}
$(function () {
$('#dp1').datepicker({
format: 'mm-dd-yyyy'
});
$('#dp2').datepicker();
$('#dp3').datepicker();
$('#dp3').datepicker();
$('#dpYears').datepicker();
$('#dpMonths').datepicker();
var startDate = new Date(2012, 1, 20);
var endDate = new Date(2012, 1, 25);
$('#dp4').datepicker()
//.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976
.on('changeDate', function (ev: DatepickerEventObject) {
if (ev.date.valueOf() > endDate.valueOf()) {
$('#alert').show().find('strong').text('The start date can not be greater then the end date');
} else {
$('#alert').hide();
startDate = ev.date;
$('#startDate').text($('#dp4').data('date'));
}
$('#dp4').datepicker('hide');
});
$('#dp5').datepicker()
//.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976
.on('changeDate', function (ev: DatepickerEventObject) {
if (ev.date.valueOf() < startDate.valueOf()) {
$('#alert').show().find('strong').text('The end date can not be less then the start date');
} else {
$('#alert').hide();
endDate = ev.date;
$('#endDate').text($('#dp5').data('date'));
}
$('#dp5').datepicker('hide');
});
});
/// <reference path="bootstrap.datepicker.d.ts"/>
function tests_simple() {
$('#datepicker').datepicker();
$('#datepicker').datepicker({
format: 'mm-dd-yyyy'
});
$('#datepicker').datepicker('setStartDate');
$('#datepicker').datepicker('setStartDate', null);
$('#datepicker').datepicker('setEndDate', '2012-12-31');
$('#date-end')
.datepicker()
.on('changeDate', function (ev) { ev; });
var startDate = new Date(2012, 1, 20);
var endDate = new Date(2012, 1, 25);
$('#date-start')
.datepicker()
//.on("changeDate", function (ev) { // bug https://typescript.codeplex.com/workitem/1976
.on("changeDate", function (ev: DatepickerEventObject) {
if (ev.date.valueOf() > endDate.valueOf()) {
$('#alert').show().find('strong').text('The start date must be before the end date.');
} else {
$('#alert').hide();
startDate = ev.date;
$('#date-start-display').text($('#date-start').data('date'));
}
$('#date-start').datepicker('hide');
});
$('#date-end')
.datepicker()
//.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976
.on('changeDate', function (ev: DatepickerEventObject) {
if (ev.date.valueOf() < startDate.valueOf()) {
$('#alert').show().find('strong').text('The end date must be after the start date.');
} else {
$('#alert').hide();
endDate = ev.date;
$('#date-end-display').text($('#date-end').data('date'));
}
$('#date-end').datepicker('hide');
});
}
$(function () {
$('#dp1').datepicker({
format: 'mm-dd-yyyy'
});
$('#dp2').datepicker();
$('#dp3').datepicker();
$('#dp3').datepicker();
$('#dpYears').datepicker();
$('#dpMonths').datepicker();
var startDate = new Date(2012, 1, 20);
var endDate = new Date(2012, 1, 25);
$('#dp4').datepicker()
//.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976
.on('changeDate', function (ev: DatepickerEventObject) {
if (ev.date.valueOf() > endDate.valueOf()) {
$('#alert').show().find('strong').text('The start date can not be greater then the end date');
} else {
$('#alert').hide();
startDate = ev.date;
$('#startDate').text($('#dp4').data('date'));
}
$('#dp4').datepicker('hide');
});
$('#dp5').datepicker()
//.on('changeDate', function (ev) { // bug https://typescript.codeplex.com/workitem/1976
.on('changeDate', function (ev: DatepickerEventObject) {
if (ev.date.valueOf() < startDate.valueOf()) {
$('#alert').show().find('strong').text('The end date can not be less then the start date');
} else {
$('#alert').hide();
endDate = ev.date;
$('#endDate').text($('#dp5').data('date'));
}
$('#dp5').datepicker('hide');
});
});

View File

@@ -1,57 +1,57 @@
// Type definitions for bootstrap.datepicker
// Project: https://github.com/eternicode/bootstrap-datepicker
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
/**
* All options that take a “Date” can handle a Date object; a String
* formatted according to the given format; or a timedelta relative
* to today, eg “-1d”, “+6m +1y”, etc, where valid units are “d” (day),
* “w” (week), “m” (month), and “y” (year).
*
* See online docs for more info:
* http://bootstrap-datepicker.readthedocs.org/en/release/options.html
*/
interface DatepickerOptions {
format?: string;
weekStart?: number;
startDate?: any;
endDate?: any;
autoclose?: boolean;
startView?: number;
todayBtn?: any;
todayHighlight?: boolean;
keyboardNavigation?: boolean;
language?: string;
beforeShowDay?: (date: any) => any;
calendarWeeks?: boolean;
clearBtn?: boolean;
daysOfWeekDisabled?: number[];
forceParse?: boolean;
inputs?: any[];
minViewMode?: any;
multidate?: any;
multidateSeparator?: string;
orientation?: string;
}
interface DatepickerEventObject extends JQueryEventObject {
date: Date;
format(format?: string): string;
}
interface JQuery {
datepicker(): JQuery;
datepicker(methodName: string): any;
datepicker(methodName: string, params: any): any;
datepicker(options: DatepickerOptions): JQuery;
off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery;
off(events: "changeDate", handler: (eventObject: DatepickerEventObject) => any): JQuery;
on(events: "changeDate", selector: string, data: any, handler?: (eventObject: DatepickerEventObject) => any): JQuery;
on(events: "changeDate", selector: string, handler: (eventObject: DatepickerEventObject) => any): JQuery;
on(events: 'changeDate', handler: (eventObject: DatepickerEventObject) => any): JQuery;
}
// Type definitions for bootstrap.datepicker
// Project: https://github.com/eternicode/bootstrap-datepicker
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
/**
* All options that take a “Date” can handle a Date object; a String
* formatted according to the given format; or a timedelta relative
* to today, eg “-1d”, “+6m +1y”, etc, where valid units are “d” (day),
* “w” (week), “m” (month), and “y” (year).
*
* See online docs for more info:
* http://bootstrap-datepicker.readthedocs.org/en/release/options.html
*/
interface DatepickerOptions {
format?: string;
weekStart?: number;
startDate?: any;
endDate?: any;
autoclose?: boolean;
startView?: number;
todayBtn?: any;
todayHighlight?: boolean;
keyboardNavigation?: boolean;
language?: string;
beforeShowDay?: (date: any) => any;
calendarWeeks?: boolean;
clearBtn?: boolean;
daysOfWeekDisabled?: number[];
forceParse?: boolean;
inputs?: any[];
minViewMode?: any;
multidate?: any;
multidateSeparator?: string;
orientation?: string;
}
interface DatepickerEventObject extends JQueryEventObject {
date: Date;
format(format?: string): string;
}
interface JQuery {
datepicker(): JQuery;
datepicker(methodName: string): any;
datepicker(methodName: string, params: any): any;
datepicker(options: DatepickerOptions): JQuery;
off(events: "changeDate", selector?: string, handler?: (eventObject: DatepickerEventObject) => any): JQuery;
off(events: "changeDate", handler: (eventObject: DatepickerEventObject) => any): JQuery;
on(events: "changeDate", selector: string, data: any, handler?: (eventObject: DatepickerEventObject) => any): JQuery;
on(events: "changeDate", selector: string, handler: (eventObject: DatepickerEventObject) => any): JQuery;
on(events: 'changeDate', handler: (eventObject: DatepickerEventObject) => any): JQuery;
}

View File

@@ -1,46 +1,46 @@
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="bootstrap.d.ts" />
$('body').off('.data-api');
$('body').off('.alert.data-api');
$(".btn.danger").button("toggle").addClass("fat");
$("#myModal").modal();
$("#myModal").modal({ keyboard: false });
$("#myModal").modal('show');
$('#myModal').on('show', (e) => e.preventDefault());
$('#myModal').modal({ keyboard: false });
$('#myModal').modal('toggle');
$('.dropdown-toggle').dropdown();
$('#navbar').scrollspy();
$('body').scrollspy({ target: '#navbar-example' });
$('#element').tooltip('show');
$('#element').popover('show');
$(".alert").alert();
$(".alert").alert('close');
$('.nav-tabs').button();
$().button('toggle');
$(".collapse").collapse();
$('#myCollapsible').collapse({ toggle: false });
$('.carousel').carousel();
$('.carousel').carousel({ interval: 2000 });
$('.typeahead').typeahead({
matcher: item => true,
sorter: (items: any[]) => items,
updater: item => item,
highlighter: item => ""
});
$('#navbar').affix();
/// <reference path="../jquery/jquery.d.ts" />
/// <reference path="bootstrap.d.ts" />
$('body').off('.data-api');
$('body').off('.alert.data-api');
$(".btn.danger").button("toggle").addClass("fat");
$("#myModal").modal();
$("#myModal").modal({ keyboard: false });
$("#myModal").modal('show');
$('#myModal').on('show', (e) => e.preventDefault());
$('#myModal').modal({ keyboard: false });
$('#myModal').modal('toggle');
$('.dropdown-toggle').dropdown();
$('#navbar').scrollspy();
$('body').scrollspy({ target: '#navbar-example' });
$('#element').tooltip('show');
$('#element').popover('show');
$(".alert").alert();
$(".alert").alert('close');
$('.nav-tabs').button();
$().button('toggle');
$(".collapse").collapse();
$('#myCollapsible').collapse({ toggle: false });
$('.carousel').carousel();
$('.carousel').carousel({ interval: 2000 });
$('.typeahead').typeahead({
matcher: item => true,
sorter: (items: any[]) => items,
updater: item => item,
highlighter: item => ""
});
$('#navbar').affix();

View File

@@ -1,120 +1,120 @@
// Type definitions for Bootstrap 3.3.5
// Project: http://twitter.github.com/bootstrap/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface ModalOptions {
backdrop?: boolean|string;
keyboard?: boolean;
show?: boolean;
remote?: string;
}
interface ModalOptionsBackdropString {
backdrop?: string; // for "static"
keyboard?: boolean;
show?: boolean;
remote?: string;
}
interface ScrollSpyOptions {
offset?: number;
target?: string;
}
interface TooltipOptions {
animation?: boolean;
html?: boolean;
placement?: string | Function;
selector?: string;
title?: string | Function;
trigger?: string;
template?: string;
delay?: number | Object;
container?: string | boolean;
viewport?: string | Function | Object;
}
interface PopoverOptions {
animation?: boolean;
html?: boolean;
placement?: string | Function;
selector?: string;
trigger?: string;
title?: string | Function;
template?: string;
content?: any;
delay?: number | Object;
container?: string | boolean;
viewport?: string | Function | Object;
}
interface CollapseOptions {
parent?: any;
toggle?: boolean;
}
interface CarouselOptions {
interval?: number;
pause?: string;
wrap?: boolean;
keybord?: boolean;
}
interface TypeaheadOptions {
source?: any;
items?: number;
minLength?: number;
matcher?: (item: any) => boolean;
sorter?: (items: any[]) => any[];
updater?: (item: any) => any;
highlighter?: (item: any) => string;
}
interface AffixOptions {
offset?: number | Function | Object;
target?: any;
}
interface JQuery {
modal(options?: ModalOptions): JQuery;
modal(options?: ModalOptionsBackdropString): JQuery;
modal(command: string): JQuery;
dropdown(): JQuery;
dropdown(command: string): JQuery;
scrollspy(command: string): JQuery;
scrollspy(options?: ScrollSpyOptions): JQuery;
tab(): JQuery;
tab(command: string): JQuery;
tooltip(options?: TooltipOptions): JQuery;
tooltip(command: string): JQuery;
popover(options?: PopoverOptions): JQuery;
popover(command: string): JQuery;
alert(): JQuery;
alert(command: string): JQuery;
button(): JQuery;
button(command: string): JQuery;
collapse(options?: CollapseOptions): JQuery;
collapse(command: string): JQuery;
carousel(options?: CarouselOptions): JQuery;
carousel(command: string): JQuery;
typeahead(options?: TypeaheadOptions): JQuery;
affix(options?: AffixOptions): JQuery;
}
declare module "bootstrap" {
}
// Type definitions for Bootstrap 3.3.5
// Project: http://twitter.github.com/bootstrap/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface ModalOptions {
backdrop?: boolean|string;
keyboard?: boolean;
show?: boolean;
remote?: string;
}
interface ModalOptionsBackdropString {
backdrop?: string; // for "static"
keyboard?: boolean;
show?: boolean;
remote?: string;
}
interface ScrollSpyOptions {
offset?: number;
target?: string;
}
interface TooltipOptions {
animation?: boolean;
html?: boolean;
placement?: string | Function;
selector?: string;
title?: string | Function;
trigger?: string;
template?: string;
delay?: number | Object;
container?: string | boolean;
viewport?: string | Function | Object;
}
interface PopoverOptions {
animation?: boolean;
html?: boolean;
placement?: string | Function;
selector?: string;
trigger?: string;
title?: string | Function;
template?: string;
content?: any;
delay?: number | Object;
container?: string | boolean;
viewport?: string | Function | Object;
}
interface CollapseOptions {
parent?: any;
toggle?: boolean;
}
interface CarouselOptions {
interval?: number;
pause?: string;
wrap?: boolean;
keybord?: boolean;
}
interface TypeaheadOptions {
source?: any;
items?: number;
minLength?: number;
matcher?: (item: any) => boolean;
sorter?: (items: any[]) => any[];
updater?: (item: any) => any;
highlighter?: (item: any) => string;
}
interface AffixOptions {
offset?: number | Function | Object;
target?: any;
}
interface JQuery {
modal(options?: ModalOptions): JQuery;
modal(options?: ModalOptionsBackdropString): JQuery;
modal(command: string): JQuery;
dropdown(): JQuery;
dropdown(command: string): JQuery;
scrollspy(command: string): JQuery;
scrollspy(options?: ScrollSpyOptions): JQuery;
tab(): JQuery;
tab(command: string): JQuery;
tooltip(options?: TooltipOptions): JQuery;
tooltip(command: string): JQuery;
popover(options?: PopoverOptions): JQuery;
popover(command: string): JQuery;
alert(): JQuery;
alert(command: string): JQuery;
button(): JQuery;
button(command: string): JQuery;
collapse(options?: CollapseOptions): JQuery;
collapse(command: string): JQuery;
carousel(options?: CarouselOptions): JQuery;
carousel(command: string): JQuery;
typeahead(options?: TypeaheadOptions): JQuery;
affix(options?: AffixOptions): JQuery;
}
declare module "bootstrap" {
}

View File

@@ -1,9 +1,9 @@
// Type definitions for camel-case
// Project: https://github.com/blakeembrey/camel-case
// Definitions by: Sam Saint-Pettersen <https://github.com/stpettersens>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "camel-case" {
function camelCase(string: string, locale?: string): string;
export = camelCase;
}
// Type definitions for camel-case
// Project: https://github.com/blakeembrey/camel-case
// Definitions by: Sam Saint-Pettersen <https://github.com/stpettersens>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "camel-case" {
function camelCase(string: string, locale?: string): string;
export = camelCase;
}

624
casperjs/casperjs.d.ts vendored
View File

@@ -1,312 +1,312 @@
// Type definitions for CasperJS v1.0.0
// Project: http://casperjs.org/
// Definitions by: Jed Mao <https://github.com/jedmao>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../phantomjs/phantomjs.d.ts" />
interface CasperModule {
create(options: CasperOptions): Casper;
selectXPath(expression: string): Object
}
interface EventEmitter {
removeAllFilters(filter: string): Casper;
setFilter(filter: string, cb: Function): boolean;
}
interface Casper extends EventEmitter {
test: Tester;
constructor (options: CasperOptions): Casper;
options: CasperOptions;
// Properties
__utils__: ClientUtils;
// Methods
back(): Casper;
base64encode(url: string, method?: string, data?: any): string;
bypass(nb: number): any;
click(selector: string): boolean;
clickLabel(label: string, tag?: string): boolean;
capture(targetFilePath: string, clipRect: ClipRect): Casper;
captureBase64(format: string): string;
captureBase64(format: string, area: string): string;
captureBase64(format: string, area: ClipRect): string;
captureBase64(format: string, area: any): string;
captureSelector(targetFile: string, selector: string): Casper;
clear(): Casper;
debugHTML(selector?: string, outer?: boolean): Casper;
debugPage(): Casper;
die(message: string, status?: number): Casper;
download(url: string, target?: string, method?: string, data?: any): Casper;
each<T>(array: T[], fn: (self: Casper, item: T, index: number) => void): Casper;
echo(message: string, style?: string): Casper;
evaluate<T>(fn: () => T, ...args: any[]): T
evaluateOrDie(fn: () => any, message?: string, status?: number): Casper;
exit(status?: number): Casper;
exists(selector: string): boolean;
fetchText(selector: string): string;
forward(): Casper;
log(message: string, level?: string, space?: string): Casper;
fill(selector: string, values: any, submit?: boolean): void;
fillSelectors(selector: string, values: any, submit?: boolean): void;
fillXPath(selector: string, values: any, submit?: boolean): void;
getCurrentUrl(): string;
getElementAttribute(selector: string, attribute: string): string;
getElementsAttribute(selector: string, attribute: string): string;
getElementBounds(selector: string): ElementBounds;
getElementsBounds(selector: string): ElementBounds[];
getElementInfo(selector: string): ElementInfo;
getElementsInfo(selector: string): ElementInfo;
getFormValues(selector: string): any;
getGlobal(name: string): any;
getHTML(selector?: string, outer?: boolean): string;
getPageContent(): string;
getTitle(): string;
mouseEvent(type: string, selector: string): boolean;
open(location: string, settings: OpenSettings): Casper;
reload(then?: (response: HttpResponse) => void): Casper;
repeat(times: number, then: Function): Casper;
resourceExists(test: Function): boolean;
resourceExists(test: string): boolean;
run(onComplete: Function, time?: number): Casper;
scrollTo(x: number, y: number): Casper;
scrollToBottom(): Casper;
sendKeys(selector: string, keys: string, options?: any): Casper;
setHttpAuth(username: string, password: string): Casper;
start(url?: string, then?: (response: HttpResponse) => void): Casper;
status(asString: boolean): any;
then(fn: (self?: Casper) => void): Casper;
thenBypass(nb: number): Casper;
thenBypassIf(condition: any, nb: number): Casper;
thenBypassUnless(condition: any, nb: number): Casper;
thenClick(selector: string): Casper;
thenEvaluate(fn: () => any, ...args: any[]): Casper;
thenOpen(location: string, then?: (response: HttpResponse) => void): Casper;
thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper;
thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]): Casper;
toString(): string;
unwait(): Casper;
userAgent(agent: string): string;
viewport(width: number, height: number): Casper;
visible(selector: string): boolean;
wait(timeout: number, then?: Function): Casper;
waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForAlert(then: Function, onTimeout?: Function, timeout?: number): Casper;
waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForUrl(url: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForUrl(url: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
warn(message: string): Casper;
withFrame(frameInfo: string, then: Function): Casper;
withFrame(frameInfo: number, then: Function): Casper;
withPopup(popupInfo: string, step: Function): Casper;
withPopup(popupInfo: RegExp, step: Function): Casper;
zoom(factor: number): Casper;
}
interface HttpResponse {
contentType: string;
headers: any[];
id: number;
redirectURL: string;
stage: string;
status: number;
statusText: string;
time: string;
url: string;
}
interface OpenSettings {
method: string;
data: any;
headers: any;
}
interface ElementBounds {
top: number;
left: number;
width: number;
height: number;
}
interface ElementInfo {
nodeName: string;
attributes: any;
tag: string;
html: string;
text: string;
x: number;
y: number;
width: number;
height: number;
visible: boolean;
}
interface CasperOptions {
clientScripts?: any[];
exitOnError?: boolean;
httpStatusHandlers?: any;
logLevel?: string;
onAlert?: Function;
onDie?: Function;
onError?: Function;
onLoadError?: Function;
onPageInitialized?: Function;
onResourceReceived?: Function;
onResourceRequested?: Function;
onStepComplete?: Function;
onStepTimeout?: Function;
onTimeout?: Function;
onWaitTimeout?: Function;
page?: WebPage;
pageSettings?: any;
remoteScripts?: any[];
safeLogs?: boolean;
silentErrors?: boolean;
stepTimeout?: number;
timeout?: number;
verbose?: boolean;
viewportSize?: any;
retryTimeout?: number;
waitTimeout?: number;
}
interface ClientUtils {
echo(message: string): void;
encode(contents: string): void;
exists(selector: string): void;
findAll(selector: string): void;
findOne(selector: string): void;
getBase64(url: string, method?: string, data?: any): void;
getBinary(url: string, method?: string, data?: any): void;
getDocumentHeight(): void;
getElementBounds(selector: string): void;
getElementsBounds(selector: string): void;
getElementByXPath(expression: string, scope?: HTMLElement): void;
getElementsByXPath(expression: string, scope?: HTMLElement): void;
getFieldValue(inputName: string): void;
getFormValues(selector: string): void;
mouseEvent(type: string, selector: string): void;
removeElementsByXPath(expression: string): void;
sendAJAX(url: string, method?: string, data?: any, async?: boolean): void;
visible(selector: string): void;
}
interface Colorizer {
colorize(text: string, styleName: string): void;
format(text: string, style: any): void;
}
interface Tester {
assert(condition: boolean, message?: string): any;
assertDoesntExist(selector: string, message?: string): any;
assertElementCount(selctor: string, expected: number, message?: string): any;
assertEquals(testValue: any, expected: any, message?: string): any;
assertEval(fn: Function, message: string, arguments: any): any;
assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any): any;
assertExists(selector: string, message?: string): any;
assertFalsy(subject: any, message?: string): any;
assertField(inputName: string, expected: string, message?: string): any;
assertFieldName(inputName: string, expected: string, message?: string, options?: any): any;
assertFieldCSS(cssSelector: string, expected: string, message?: string): any;
assertFieldXPath(xpathSelector: string, expected: string, message?: string): any;
assertHttpStatus(status: number, message?: string): any;
assertMatch(subject: any, pattern: RegExp, message?: string): any;
assertNot(subject: any, message?: string): any;
assertNotEquals(testValue: any, expected: any, message?: string): any;
assertNotVisible(selector: string, message?: string): any;
assertRaises(fn: Function, args: any[], message?: string): any;
assertSelectorDoesntHaveText(selector: string, text: string, message?: string): any;
assertSelectorExists(selector: string, message?: string): any;
assertSelectorHasText(selector: string, text: string, message?: string): any;
assertResourceExists(testFx: Function, message?: string): any;
assertTextExists(expected: string, message?: string): any;
assertTextDoesntExist(unexpected: string, message: string): any;
assertTitle(expected: string, message?: string): any;
assertTitleMatch(pattern: RegExp, message?: string): any;
assertTruthy(subject: any, message?: string): any;
assertType(input: any, type: string, message?: string): any;
assertInstanceOf(input: any, ctor: Function, message?: string): any;
assertUrlMatch(pattern: string, message?: string): any;
assertUrlMatch(pattern: RegExp, message?: string): any;
assertVisible(selector: string, message?: string): any;
/* since 1.1 */
begin(description: string, planned: number, suite: Function): any;
begin(description: string, suite: Function): any;
begin(description: string, planned: number, config: Object): any;
begin(description: string, config: Object): any;
colorize(message: string, style: string): any;
comment(message: string): any;
done(expected?: number): any;
error(message: string): any;
fail(message: string): any;
formatMessage(message: string, style: string): any;
getFailures(): Cases;
getPasses(): Cases;
info(message: string): any;
pass(message: string): any;
renderResults(exit: boolean, status: number, save: string): any;
setup(fn: Function): any;
skip(nb: number, message: string): any;
tearDown(fn: Function): any;
}
interface Cases {
length: number;
cases: Case[];
}
interface Case {
success: boolean;
type: string;
standard: string;
file: string;
values: CaseValues;
}
interface CaseValues {
subject: boolean;
expected: boolean;
}
interface Utils {
betterTypeOf(input: any): any;
dump(value: any): any;
fileExt(file: string): any;
fillBlanks(text: string, pad: number): any;
format(f: string, ...args: any[]): any;
getPropertyPath(obj: any, path: string): any;
inherits(ctor: any, superCtor: any): any;
isArray(value: any): any;
isCasperObject(value: any): any;
isClipRect(value: any): any;
isFalsy(subject: any): any;
isFunction(value: any): any;
isJsFile(file: string): any;
isNull(value: any): any;
isNumber(value: any): any;
isObject(value: any): any;
isRegExp(value: any): any;
isString(value: any): any;
isTruthy(subject: any): any;
isType(what: any, type: string): any;
isUndefined(value: any): any;
isWebPage(what: any): any;
mergeObjects(origin: any, add: any): any;
node(name: string, attributes: any): any;
serialize(value: any): any;
unique(array: any[]): any;
}
// Type definitions for CasperJS v1.0.0
// Project: http://casperjs.org/
// Definitions by: Jed Mao <https://github.com/jedmao>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../phantomjs/phantomjs.d.ts" />
interface CasperModule {
create(options: CasperOptions): Casper;
selectXPath(expression: string): Object
}
interface EventEmitter {
removeAllFilters(filter: string): Casper;
setFilter(filter: string, cb: Function): boolean;
}
interface Casper extends EventEmitter {
test: Tester;
constructor (options: CasperOptions): Casper;
options: CasperOptions;
// Properties
__utils__: ClientUtils;
// Methods
back(): Casper;
base64encode(url: string, method?: string, data?: any): string;
bypass(nb: number): any;
click(selector: string): boolean;
clickLabel(label: string, tag?: string): boolean;
capture(targetFilePath: string, clipRect: ClipRect): Casper;
captureBase64(format: string): string;
captureBase64(format: string, area: string): string;
captureBase64(format: string, area: ClipRect): string;
captureBase64(format: string, area: any): string;
captureSelector(targetFile: string, selector: string): Casper;
clear(): Casper;
debugHTML(selector?: string, outer?: boolean): Casper;
debugPage(): Casper;
die(message: string, status?: number): Casper;
download(url: string, target?: string, method?: string, data?: any): Casper;
each<T>(array: T[], fn: (self: Casper, item: T, index: number) => void): Casper;
echo(message: string, style?: string): Casper;
evaluate<T>(fn: () => T, ...args: any[]): T
evaluateOrDie(fn: () => any, message?: string, status?: number): Casper;
exit(status?: number): Casper;
exists(selector: string): boolean;
fetchText(selector: string): string;
forward(): Casper;
log(message: string, level?: string, space?: string): Casper;
fill(selector: string, values: any, submit?: boolean): void;
fillSelectors(selector: string, values: any, submit?: boolean): void;
fillXPath(selector: string, values: any, submit?: boolean): void;
getCurrentUrl(): string;
getElementAttribute(selector: string, attribute: string): string;
getElementsAttribute(selector: string, attribute: string): string;
getElementBounds(selector: string): ElementBounds;
getElementsBounds(selector: string): ElementBounds[];
getElementInfo(selector: string): ElementInfo;
getElementsInfo(selector: string): ElementInfo;
getFormValues(selector: string): any;
getGlobal(name: string): any;
getHTML(selector?: string, outer?: boolean): string;
getPageContent(): string;
getTitle(): string;
mouseEvent(type: string, selector: string): boolean;
open(location: string, settings: OpenSettings): Casper;
reload(then?: (response: HttpResponse) => void): Casper;
repeat(times: number, then: Function): Casper;
resourceExists(test: Function): boolean;
resourceExists(test: string): boolean;
run(onComplete: Function, time?: number): Casper;
scrollTo(x: number, y: number): Casper;
scrollToBottom(): Casper;
sendKeys(selector: string, keys: string, options?: any): Casper;
setHttpAuth(username: string, password: string): Casper;
start(url?: string, then?: (response: HttpResponse) => void): Casper;
status(asString: boolean): any;
then(fn: (self?: Casper) => void): Casper;
thenBypass(nb: number): Casper;
thenBypassIf(condition: any, nb: number): Casper;
thenBypassUnless(condition: any, nb: number): Casper;
thenClick(selector: string): Casper;
thenEvaluate(fn: () => any, ...args: any[]): Casper;
thenOpen(location: string, then?: (response: HttpResponse) => void): Casper;
thenOpen(location: string, options?: OpenSettings, then?: (response: HttpResponse) => void): Casper;
thenOpenAndEvaluate(location: string, then?: Function, ...args: any[]): Casper;
toString(): string;
unwait(): Casper;
userAgent(agent: string): string;
viewport(width: number, height: number): Casper;
visible(selector: string): boolean;
wait(timeout: number, then?: Function): Casper;
waitFor(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForAlert(then: Function, onTimeout?: Function, timeout?: number): Casper;
waitForPopup(urlPattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForPopup(urlPattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForUrl(url: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForUrl(url: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitWhileSelector(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForResource(testFx: Function, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForText(pattern: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitForText(pattern: RegExp, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitUntilVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
waitWhileVisible(selector: string, then?: Function, onTimeout?: Function, timeout?: number): Casper;
warn(message: string): Casper;
withFrame(frameInfo: string, then: Function): Casper;
withFrame(frameInfo: number, then: Function): Casper;
withPopup(popupInfo: string, step: Function): Casper;
withPopup(popupInfo: RegExp, step: Function): Casper;
zoom(factor: number): Casper;
}
interface HttpResponse {
contentType: string;
headers: any[];
id: number;
redirectURL: string;
stage: string;
status: number;
statusText: string;
time: string;
url: string;
}
interface OpenSettings {
method: string;
data: any;
headers: any;
}
interface ElementBounds {
top: number;
left: number;
width: number;
height: number;
}
interface ElementInfo {
nodeName: string;
attributes: any;
tag: string;
html: string;
text: string;
x: number;
y: number;
width: number;
height: number;
visible: boolean;
}
interface CasperOptions {
clientScripts?: any[];
exitOnError?: boolean;
httpStatusHandlers?: any;
logLevel?: string;
onAlert?: Function;
onDie?: Function;
onError?: Function;
onLoadError?: Function;
onPageInitialized?: Function;
onResourceReceived?: Function;
onResourceRequested?: Function;
onStepComplete?: Function;
onStepTimeout?: Function;
onTimeout?: Function;
onWaitTimeout?: Function;
page?: WebPage;
pageSettings?: any;
remoteScripts?: any[];
safeLogs?: boolean;
silentErrors?: boolean;
stepTimeout?: number;
timeout?: number;
verbose?: boolean;
viewportSize?: any;
retryTimeout?: number;
waitTimeout?: number;
}
interface ClientUtils {
echo(message: string): void;
encode(contents: string): void;
exists(selector: string): void;
findAll(selector: string): void;
findOne(selector: string): void;
getBase64(url: string, method?: string, data?: any): void;
getBinary(url: string, method?: string, data?: any): void;
getDocumentHeight(): void;
getElementBounds(selector: string): void;
getElementsBounds(selector: string): void;
getElementByXPath(expression: string, scope?: HTMLElement): void;
getElementsByXPath(expression: string, scope?: HTMLElement): void;
getFieldValue(inputName: string): void;
getFormValues(selector: string): void;
mouseEvent(type: string, selector: string): void;
removeElementsByXPath(expression: string): void;
sendAJAX(url: string, method?: string, data?: any, async?: boolean): void;
visible(selector: string): void;
}
interface Colorizer {
colorize(text: string, styleName: string): void;
format(text: string, style: any): void;
}
interface Tester {
assert(condition: boolean, message?: string): any;
assertDoesntExist(selector: string, message?: string): any;
assertElementCount(selctor: string, expected: number, message?: string): any;
assertEquals(testValue: any, expected: any, message?: string): any;
assertEval(fn: Function, message: string, arguments: any): any;
assertEvalEquals(fn: Function, expected: any, message?: string, arguments?: any): any;
assertExists(selector: string, message?: string): any;
assertFalsy(subject: any, message?: string): any;
assertField(inputName: string, expected: string, message?: string): any;
assertFieldName(inputName: string, expected: string, message?: string, options?: any): any;
assertFieldCSS(cssSelector: string, expected: string, message?: string): any;
assertFieldXPath(xpathSelector: string, expected: string, message?: string): any;
assertHttpStatus(status: number, message?: string): any;
assertMatch(subject: any, pattern: RegExp, message?: string): any;
assertNot(subject: any, message?: string): any;
assertNotEquals(testValue: any, expected: any, message?: string): any;
assertNotVisible(selector: string, message?: string): any;
assertRaises(fn: Function, args: any[], message?: string): any;
assertSelectorDoesntHaveText(selector: string, text: string, message?: string): any;
assertSelectorExists(selector: string, message?: string): any;
assertSelectorHasText(selector: string, text: string, message?: string): any;
assertResourceExists(testFx: Function, message?: string): any;
assertTextExists(expected: string, message?: string): any;
assertTextDoesntExist(unexpected: string, message: string): any;
assertTitle(expected: string, message?: string): any;
assertTitleMatch(pattern: RegExp, message?: string): any;
assertTruthy(subject: any, message?: string): any;
assertType(input: any, type: string, message?: string): any;
assertInstanceOf(input: any, ctor: Function, message?: string): any;
assertUrlMatch(pattern: string, message?: string): any;
assertUrlMatch(pattern: RegExp, message?: string): any;
assertVisible(selector: string, message?: string): any;
/* since 1.1 */
begin(description: string, planned: number, suite: Function): any;
begin(description: string, suite: Function): any;
begin(description: string, planned: number, config: Object): any;
begin(description: string, config: Object): any;
colorize(message: string, style: string): any;
comment(message: string): any;
done(expected?: number): any;
error(message: string): any;
fail(message: string): any;
formatMessage(message: string, style: string): any;
getFailures(): Cases;
getPasses(): Cases;
info(message: string): any;
pass(message: string): any;
renderResults(exit: boolean, status: number, save: string): any;
setup(fn: Function): any;
skip(nb: number, message: string): any;
tearDown(fn: Function): any;
}
interface Cases {
length: number;
cases: Case[];
}
interface Case {
success: boolean;
type: string;
standard: string;
file: string;
values: CaseValues;
}
interface CaseValues {
subject: boolean;
expected: boolean;
}
interface Utils {
betterTypeOf(input: any): any;
dump(value: any): any;
fileExt(file: string): any;
fillBlanks(text: string, pad: number): any;
format(f: string, ...args: any[]): any;
getPropertyPath(obj: any, path: string): any;
inherits(ctor: any, superCtor: any): any;
isArray(value: any): any;
isCasperObject(value: any): any;
isClipRect(value: any): any;
isFalsy(subject: any): any;
isFunction(value: any): any;
isJsFile(file: string): any;
isNull(value: any): any;
isNumber(value: any): any;
isObject(value: any): any;
isRegExp(value: any): any;
isString(value: any): any;
isTruthy(subject: any): any;
isType(what: any, type: string): any;
isUndefined(value: any): any;
isWebPage(what: any): any;
mergeObjects(origin: any, add: any): any;
node(name: string, attributes: any): any;
serialize(value: any): any;
unique(array: any[]): any;
}

776
chai/chai-3.2.0.d.ts vendored
View File

@@ -1,388 +1,388 @@
// Type definitions for chai 3.2.0
// Project: http://chaijs.com/
// Definitions by: Jed Mao <https://github.com/jedmao/>,
// Bart van der Schoor <https://github.com/Bartvds>,
// Andrew Brown <https://github.com/AGBrown>,
// Olivier Chevet <https://github.com/olivr70>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// <reference path="../assertion-error/assertion-error.d.ts"/>
declare module Chai {
interface ChaiStatic {
expect: ExpectStatic;
should(): Should;
/**
* Provides a way to extend the internals of Chai
*/
use(fn: (chai: any, utils: any) => void): any;
assert: AssertStatic;
config: Config;
AssertionError: typeof AssertionError;
}
export interface ExpectStatic extends AssertionStatic {
fail(actual?: any, expected?: any, message?: string, operator?: string): void;
}
export interface AssertStatic extends Assert {
}
export interface AssertionStatic {
(target: any, message?: string): Assertion;
}
interface ShouldAssertion {
equal(value1: any, value2: any, message?: string): void;
Throw: ShouldThrow;
throw: ShouldThrow;
exist(value: any, message?: string): void;
}
interface Should extends ShouldAssertion {
not: ShouldAssertion;
fail(actual: any, expected: any, message?: string, operator?: string): void;
}
interface ShouldThrow {
(actual: Function): void;
(actual: Function, expected: string|RegExp, message?: string): void;
(actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void;
}
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
not: Assertion;
deep: Deep;
any: KeyFilter;
all: KeyFilter;
a: TypeComparison;
an: TypeComparison;
include: Include;
includes: Include;
contain: Include;
contains: Include;
ok: Assertion;
true: Assertion;
false: Assertion;
null: Assertion;
undefined: Assertion;
NaN: Assertion;
exist: Assertion;
empty: Assertion;
arguments: Assertion;
Arguments: Assertion;
equal: Equal;
equals: Equal;
eq: Equal;
eql: Equal;
eqls: Equal;
property: Property;
ownProperty: OwnProperty;
haveOwnProperty: OwnProperty;
ownPropertyDescriptor: OwnPropertyDescriptor;
haveOwnPropertyDescriptor: OwnPropertyDescriptor;
length: Length;
lengthOf: Length;
match: Match;
matches: Match;
string(string: string, message?: string): Assertion;
keys: Keys;
key(string: string): Assertion;
throw: Throw;
throws: Throw;
Throw: Throw;
respondTo: RespondTo;
respondsTo: RespondTo;
itself: Assertion;
satisfy: Satisfy;
satisfies: Satisfy;
closeTo(expected: number, delta: number, message?: string): Assertion;
members: Members;
increase: PropertyChange;
increases: PropertyChange;
decrease: PropertyChange;
decreases: PropertyChange;
change: PropertyChange;
changes: PropertyChange;
extensible: Assertion;
sealed: Assertion;
frozen: Assertion;
}
interface LanguageChains {
to: Assertion;
be: Assertion;
been: Assertion;
is: Assertion;
that: Assertion;
which: Assertion;
and: Assertion;
has: Assertion;
have: Assertion;
with: Assertion;
at: Assertion;
of: Assertion;
same: Assertion;
}
interface NumericComparison {
above: NumberComparer;
gt: NumberComparer;
greaterThan: NumberComparer;
least: NumberComparer;
gte: NumberComparer;
below: NumberComparer;
lt: NumberComparer;
lessThan: NumberComparer;
most: NumberComparer;
lte: NumberComparer;
within(start: number, finish: number, message?: string): Assertion;
}
interface NumberComparer {
(value: number, message?: string): Assertion;
}
interface TypeComparison {
(type: string, message?: string): Assertion;
instanceof: InstanceOf;
instanceOf: InstanceOf;
}
interface InstanceOf {
(constructor: Object, message?: string): Assertion;
}
interface Deep {
equal: Equal;
include: Include;
property: Property;
members: Members;
}
interface KeyFilter {
keys: Keys;
}
interface Equal {
(value: any, message?: string): Assertion;
}
interface Property {
(name: string, value?: any, message?: string): Assertion;
}
interface OwnProperty {
(name: string, message?: string): Assertion;
}
interface OwnPropertyDescriptor {
(name: string, descriptor: PropertyDescriptor, message?: string): Assertion;
(name: string, message?: string): Assertion;
}
interface Length extends LanguageChains, NumericComparison {
(length: number, message?: string): Assertion;
}
interface Include {
(value: Object, message?: string): Assertion;
(value: string, message?: string): Assertion;
(value: number, message?: string): Assertion;
keys: Keys;
members: Members;
any: KeyFilter;
all: KeyFilter;
}
interface Match {
(regexp: RegExp|string, message?: string): Assertion;
}
interface Keys {
(...keys: string[]): Assertion;
(keys: any[]): Assertion;
(keys: Object): Assertion;
}
interface Throw {
(): Assertion;
(expected: string, message?: string): Assertion;
(expected: RegExp, message?: string): Assertion;
(constructor: Error, expected?: string, message?: string): Assertion;
(constructor: Error, expected?: RegExp, message?: string): Assertion;
(constructor: Function, expected?: string, message?: string): Assertion;
(constructor: Function, expected?: RegExp, message?: string): Assertion;
}
interface RespondTo {
(method: string, message?: string): Assertion;
}
interface Satisfy {
(matcher: Function, message?: string): Assertion;
}
interface Members {
(set: any[], message?: string): Assertion;
}
interface PropertyChange {
(object: Object, prop: string, msg?: string): Assertion;
}
export interface Assert {
/**
* @param expression Expression to test for truthiness.
* @param message Message to display on error.
*/
(expression: any, message?: string): void;
fail(actual?: any, expected?: any, msg?: string, operator?: string): void;
ok(val: any, msg?: string): void;
isOk(val: any, msg?: string): void;
notOk(val: any, msg?: string): void;
isNotOk(val: any, msg?: string): void;
equal(act: any, exp: any, msg?: string): void;
notEqual(act: any, exp: any, msg?: string): void;
strictEqual(act: any, exp: any, msg?: string): void;
notStrictEqual(act: any, exp: any, msg?: string): void;
deepEqual(act: any, exp: any, msg?: string): void;
notDeepEqual(act: any, exp: any, msg?: string): void;
isTrue(val: any, msg?: string): void;
isFalse(val: any, msg?: string): void;
isNull(val: any, msg?: string): void;
isNotNull(val: any, msg?: string): void;
isUndefined(val: any, msg?: string): void;
isDefined(val: any, msg?: string): void;
isNaN(val: any, msg?: string): void;
isNotNaN(val: any, msg?: string): void;
isAbove(val: number, abv: number, msg?: string): void;
isBelow(val: number, blw: number, msg?: string): void;
isFunction(val: any, msg?: string): void;
isNotFunction(val: any, msg?: string): void;
isObject(val: any, msg?: string): void;
isNotObject(val: any, msg?: string): void;
isArray(val: any, msg?: string): void;
isNotArray(val: any, msg?: string): void;
isString(val: any, msg?: string): void;
isNotString(val: any, msg?: string): void;
isNumber(val: any, msg?: string): void;
isNotNumber(val: any, msg?: string): void;
isBoolean(val: any, msg?: string): void;
isNotBoolean(val: any, msg?: string): void;
typeOf(val: any, type: string, msg?: string): void;
notTypeOf(val: any, type: string, msg?: string): void;
instanceOf(val: any, type: Function, msg?: string): void;
notInstanceOf(val: any, type: Function, msg?: string): void;
include(exp: string, inc: any, msg?: string): void;
include(exp: any[], inc: any, msg?: string): void;
notInclude(exp: string, inc: any, msg?: string): void;
notInclude(exp: any[], inc: any, msg?: string): void;
match(exp: any, re: RegExp, msg?: string): void;
notMatch(exp: any, re: RegExp, msg?: string): void;
property(obj: Object, prop: string, msg?: string): void;
notProperty(obj: Object, prop: string, msg?: string): void;
deepProperty(obj: Object, prop: string, msg?: string): void;
notDeepProperty(obj: Object, prop: string, msg?: string): void;
propertyVal(obj: Object, prop: string, val: any, msg?: string): void;
propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
lengthOf(exp: any, len: number, msg?: string): void;
//alias frenzy
throw(fn: Function, msg?: string): void;
throw(fn: Function, regExp: RegExp): void;
throw(fn: Function, errType: Function, msg?: string): void;
throw(fn: Function, errType: Function, regExp: RegExp): void;
throws(fn: Function, msg?: string): void;
throws(fn: Function, regExp: RegExp): void;
throws(fn: Function, errType: Function, msg?: string): void;
throws(fn: Function, errType: Function, regExp: RegExp): void;
Throw(fn: Function, msg?: string): void;
Throw(fn: Function, regExp: RegExp): void;
Throw(fn: Function, errType: Function, msg?: string): void;
Throw(fn: Function, errType: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, msg?: string): void;
doesNotThrow(fn: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, errType: Function, msg?: string): void;
doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void;
operator(val: any, operator: string, val2: any, msg?: string): void;
closeTo(act: number, exp: number, delta: number, msg?: string): void;
sameMembers(set1: any[], set2: any[], msg?: string): void;
sameDeepMembers(set1: any[], set2: any[], msg?: string): void;
includeMembers(superset: any[], subset: any[], msg?: string): void;
ifError(val: any, msg?: string): void;
isExtensible(obj: {}, msg?: string): void;
extensible(obj: {}, msg?: string): void;
isNotExtensible(obj: {}, msg?: string): void;
notExtensible(obj: {}, msg?: string): void;
isSealed(obj: {}, msg?: string): void;
sealed(obj: {}, msg?: string): void;
isNotSealed(obj: {}, msg?: string): void;
notSealed(obj: {}, msg?: string): void;
isFrozen(obj: Object, msg?: string): void;
frozen(obj: Object, msg?: string): void;
isNotFrozen(obj: Object, msg?: string): void;
notFrozen(obj: Object, msg?: string): void;
}
export interface Config {
includeStack: boolean;
}
export class AssertionError {
constructor(message: string, _props?: any, ssf?: Function);
name: string;
message: string;
showDiff: boolean;
stack: string;
}
}
declare var chai: Chai.ChaiStatic;
declare module "chai" {
export = chai;
}
interface Object {
should: Chai.Assertion;
}
// Type definitions for chai 3.2.0
// Project: http://chaijs.com/
// Definitions by: Jed Mao <https://github.com/jedmao/>,
// Bart van der Schoor <https://github.com/Bartvds>,
// Andrew Brown <https://github.com/AGBrown>,
// Olivier Chevet <https://github.com/olivr70>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// <reference path="../assertion-error/assertion-error.d.ts"/>
declare module Chai {
interface ChaiStatic {
expect: ExpectStatic;
should(): Should;
/**
* Provides a way to extend the internals of Chai
*/
use(fn: (chai: any, utils: any) => void): any;
assert: AssertStatic;
config: Config;
AssertionError: typeof AssertionError;
}
export interface ExpectStatic extends AssertionStatic {
fail(actual?: any, expected?: any, message?: string, operator?: string): void;
}
export interface AssertStatic extends Assert {
}
export interface AssertionStatic {
(target: any, message?: string): Assertion;
}
interface ShouldAssertion {
equal(value1: any, value2: any, message?: string): void;
Throw: ShouldThrow;
throw: ShouldThrow;
exist(value: any, message?: string): void;
}
interface Should extends ShouldAssertion {
not: ShouldAssertion;
fail(actual: any, expected: any, message?: string, operator?: string): void;
}
interface ShouldThrow {
(actual: Function): void;
(actual: Function, expected: string|RegExp, message?: string): void;
(actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void;
}
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
not: Assertion;
deep: Deep;
any: KeyFilter;
all: KeyFilter;
a: TypeComparison;
an: TypeComparison;
include: Include;
includes: Include;
contain: Include;
contains: Include;
ok: Assertion;
true: Assertion;
false: Assertion;
null: Assertion;
undefined: Assertion;
NaN: Assertion;
exist: Assertion;
empty: Assertion;
arguments: Assertion;
Arguments: Assertion;
equal: Equal;
equals: Equal;
eq: Equal;
eql: Equal;
eqls: Equal;
property: Property;
ownProperty: OwnProperty;
haveOwnProperty: OwnProperty;
ownPropertyDescriptor: OwnPropertyDescriptor;
haveOwnPropertyDescriptor: OwnPropertyDescriptor;
length: Length;
lengthOf: Length;
match: Match;
matches: Match;
string(string: string, message?: string): Assertion;
keys: Keys;
key(string: string): Assertion;
throw: Throw;
throws: Throw;
Throw: Throw;
respondTo: RespondTo;
respondsTo: RespondTo;
itself: Assertion;
satisfy: Satisfy;
satisfies: Satisfy;
closeTo(expected: number, delta: number, message?: string): Assertion;
members: Members;
increase: PropertyChange;
increases: PropertyChange;
decrease: PropertyChange;
decreases: PropertyChange;
change: PropertyChange;
changes: PropertyChange;
extensible: Assertion;
sealed: Assertion;
frozen: Assertion;
}
interface LanguageChains {
to: Assertion;
be: Assertion;
been: Assertion;
is: Assertion;
that: Assertion;
which: Assertion;
and: Assertion;
has: Assertion;
have: Assertion;
with: Assertion;
at: Assertion;
of: Assertion;
same: Assertion;
}
interface NumericComparison {
above: NumberComparer;
gt: NumberComparer;
greaterThan: NumberComparer;
least: NumberComparer;
gte: NumberComparer;
below: NumberComparer;
lt: NumberComparer;
lessThan: NumberComparer;
most: NumberComparer;
lte: NumberComparer;
within(start: number, finish: number, message?: string): Assertion;
}
interface NumberComparer {
(value: number, message?: string): Assertion;
}
interface TypeComparison {
(type: string, message?: string): Assertion;
instanceof: InstanceOf;
instanceOf: InstanceOf;
}
interface InstanceOf {
(constructor: Object, message?: string): Assertion;
}
interface Deep {
equal: Equal;
include: Include;
property: Property;
members: Members;
}
interface KeyFilter {
keys: Keys;
}
interface Equal {
(value: any, message?: string): Assertion;
}
interface Property {
(name: string, value?: any, message?: string): Assertion;
}
interface OwnProperty {
(name: string, message?: string): Assertion;
}
interface OwnPropertyDescriptor {
(name: string, descriptor: PropertyDescriptor, message?: string): Assertion;
(name: string, message?: string): Assertion;
}
interface Length extends LanguageChains, NumericComparison {
(length: number, message?: string): Assertion;
}
interface Include {
(value: Object, message?: string): Assertion;
(value: string, message?: string): Assertion;
(value: number, message?: string): Assertion;
keys: Keys;
members: Members;
any: KeyFilter;
all: KeyFilter;
}
interface Match {
(regexp: RegExp|string, message?: string): Assertion;
}
interface Keys {
(...keys: string[]): Assertion;
(keys: any[]): Assertion;
(keys: Object): Assertion;
}
interface Throw {
(): Assertion;
(expected: string, message?: string): Assertion;
(expected: RegExp, message?: string): Assertion;
(constructor: Error, expected?: string, message?: string): Assertion;
(constructor: Error, expected?: RegExp, message?: string): Assertion;
(constructor: Function, expected?: string, message?: string): Assertion;
(constructor: Function, expected?: RegExp, message?: string): Assertion;
}
interface RespondTo {
(method: string, message?: string): Assertion;
}
interface Satisfy {
(matcher: Function, message?: string): Assertion;
}
interface Members {
(set: any[], message?: string): Assertion;
}
interface PropertyChange {
(object: Object, prop: string, msg?: string): Assertion;
}
export interface Assert {
/**
* @param expression Expression to test for truthiness.
* @param message Message to display on error.
*/
(expression: any, message?: string): void;
fail(actual?: any, expected?: any, msg?: string, operator?: string): void;
ok(val: any, msg?: string): void;
isOk(val: any, msg?: string): void;
notOk(val: any, msg?: string): void;
isNotOk(val: any, msg?: string): void;
equal(act: any, exp: any, msg?: string): void;
notEqual(act: any, exp: any, msg?: string): void;
strictEqual(act: any, exp: any, msg?: string): void;
notStrictEqual(act: any, exp: any, msg?: string): void;
deepEqual(act: any, exp: any, msg?: string): void;
notDeepEqual(act: any, exp: any, msg?: string): void;
isTrue(val: any, msg?: string): void;
isFalse(val: any, msg?: string): void;
isNull(val: any, msg?: string): void;
isNotNull(val: any, msg?: string): void;
isUndefined(val: any, msg?: string): void;
isDefined(val: any, msg?: string): void;
isNaN(val: any, msg?: string): void;
isNotNaN(val: any, msg?: string): void;
isAbove(val: number, abv: number, msg?: string): void;
isBelow(val: number, blw: number, msg?: string): void;
isFunction(val: any, msg?: string): void;
isNotFunction(val: any, msg?: string): void;
isObject(val: any, msg?: string): void;
isNotObject(val: any, msg?: string): void;
isArray(val: any, msg?: string): void;
isNotArray(val: any, msg?: string): void;
isString(val: any, msg?: string): void;
isNotString(val: any, msg?: string): void;
isNumber(val: any, msg?: string): void;
isNotNumber(val: any, msg?: string): void;
isBoolean(val: any, msg?: string): void;
isNotBoolean(val: any, msg?: string): void;
typeOf(val: any, type: string, msg?: string): void;
notTypeOf(val: any, type: string, msg?: string): void;
instanceOf(val: any, type: Function, msg?: string): void;
notInstanceOf(val: any, type: Function, msg?: string): void;
include(exp: string, inc: any, msg?: string): void;
include(exp: any[], inc: any, msg?: string): void;
notInclude(exp: string, inc: any, msg?: string): void;
notInclude(exp: any[], inc: any, msg?: string): void;
match(exp: any, re: RegExp, msg?: string): void;
notMatch(exp: any, re: RegExp, msg?: string): void;
property(obj: Object, prop: string, msg?: string): void;
notProperty(obj: Object, prop: string, msg?: string): void;
deepProperty(obj: Object, prop: string, msg?: string): void;
notDeepProperty(obj: Object, prop: string, msg?: string): void;
propertyVal(obj: Object, prop: string, val: any, msg?: string): void;
propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
lengthOf(exp: any, len: number, msg?: string): void;
//alias frenzy
throw(fn: Function, msg?: string): void;
throw(fn: Function, regExp: RegExp): void;
throw(fn: Function, errType: Function, msg?: string): void;
throw(fn: Function, errType: Function, regExp: RegExp): void;
throws(fn: Function, msg?: string): void;
throws(fn: Function, regExp: RegExp): void;
throws(fn: Function, errType: Function, msg?: string): void;
throws(fn: Function, errType: Function, regExp: RegExp): void;
Throw(fn: Function, msg?: string): void;
Throw(fn: Function, regExp: RegExp): void;
Throw(fn: Function, errType: Function, msg?: string): void;
Throw(fn: Function, errType: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, msg?: string): void;
doesNotThrow(fn: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, errType: Function, msg?: string): void;
doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void;
operator(val: any, operator: string, val2: any, msg?: string): void;
closeTo(act: number, exp: number, delta: number, msg?: string): void;
sameMembers(set1: any[], set2: any[], msg?: string): void;
sameDeepMembers(set1: any[], set2: any[], msg?: string): void;
includeMembers(superset: any[], subset: any[], msg?: string): void;
ifError(val: any, msg?: string): void;
isExtensible(obj: {}, msg?: string): void;
extensible(obj: {}, msg?: string): void;
isNotExtensible(obj: {}, msg?: string): void;
notExtensible(obj: {}, msg?: string): void;
isSealed(obj: {}, msg?: string): void;
sealed(obj: {}, msg?: string): void;
isNotSealed(obj: {}, msg?: string): void;
notSealed(obj: {}, msg?: string): void;
isFrozen(obj: Object, msg?: string): void;
frozen(obj: Object, msg?: string): void;
isNotFrozen(obj: Object, msg?: string): void;
notFrozen(obj: Object, msg?: string): void;
}
export interface Config {
includeStack: boolean;
}
export class AssertionError {
constructor(message: string, _props?: any, ssf?: Function);
name: string;
message: string;
showDiff: boolean;
stack: string;
}
}
declare var chai: Chai.ChaiStatic;
declare module "chai" {
export = chai;
}
interface Object {
should: Chai.Assertion;
}

802
chai/chai.d.ts vendored
View File

@@ -1,401 +1,401 @@
// Type definitions for chai 3.4.0
// Project: http://chaijs.com/
// Definitions by: Jed Mao <https://github.com/jedmao/>,
// Bart van der Schoor <https://github.com/Bartvds>,
// Andrew Brown <https://github.com/AGBrown>,
// Olivier Chevet <https://github.com/olivr70>,
// Matt Wistrand <https://github.com/mwistrand>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// <reference path="../assertion-error/assertion-error.d.ts"/>
declare module Chai {
interface ChaiStatic {
expect: ExpectStatic;
should(): Should;
/**
* Provides a way to extend the internals of Chai
*/
use(fn: (chai: any, utils: any) => void): any;
assert: AssertStatic;
config: Config;
AssertionError: typeof AssertionError;
}
export interface ExpectStatic extends AssertionStatic {
fail(actual?: any, expected?: any, message?: string, operator?: string): void;
}
export interface AssertStatic extends Assert {
}
export interface AssertionStatic {
(target: any, message?: string): Assertion;
}
interface ShouldAssertion {
equal(value1: any, value2: any, message?: string): void;
Throw: ShouldThrow;
throw: ShouldThrow;
exist(value: any, message?: string): void;
}
interface Should extends ShouldAssertion {
not: ShouldAssertion;
fail(actual: any, expected: any, message?: string, operator?: string): void;
}
interface ShouldThrow {
(actual: Function): void;
(actual: Function, expected: string|RegExp, message?: string): void;
(actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void;
}
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
not: Assertion;
deep: Deep;
any: KeyFilter;
all: KeyFilter;
a: TypeComparison;
an: TypeComparison;
include: Include;
includes: Include;
contain: Include;
contains: Include;
ok: Assertion;
true: Assertion;
false: Assertion;
null: Assertion;
undefined: Assertion;
NaN: Assertion;
exist: Assertion;
empty: Assertion;
arguments: Assertion;
Arguments: Assertion;
equal: Equal;
equals: Equal;
eq: Equal;
eql: Equal;
eqls: Equal;
property: Property;
ownProperty: OwnProperty;
haveOwnProperty: OwnProperty;
ownPropertyDescriptor: OwnPropertyDescriptor;
haveOwnPropertyDescriptor: OwnPropertyDescriptor;
length: Length;
lengthOf: Length;
match: Match;
matches: Match;
string(string: string, message?: string): Assertion;
keys: Keys;
key(string: string): Assertion;
throw: Throw;
throws: Throw;
Throw: Throw;
respondTo: RespondTo;
respondsTo: RespondTo;
itself: Assertion;
satisfy: Satisfy;
satisfies: Satisfy;
closeTo: CloseTo;
approximately: CloseTo;
members: Members;
increase: PropertyChange;
increases: PropertyChange;
decrease: PropertyChange;
decreases: PropertyChange;
change: PropertyChange;
changes: PropertyChange;
extensible: Assertion;
sealed: Assertion;
frozen: Assertion;
oneOf(list: any[], message?: string): Assertion;
}
interface LanguageChains {
to: Assertion;
be: Assertion;
been: Assertion;
is: Assertion;
that: Assertion;
which: Assertion;
and: Assertion;
has: Assertion;
have: Assertion;
with: Assertion;
at: Assertion;
of: Assertion;
same: Assertion;
}
interface NumericComparison {
above: NumberComparer;
gt: NumberComparer;
greaterThan: NumberComparer;
least: NumberComparer;
gte: NumberComparer;
below: NumberComparer;
lt: NumberComparer;
lessThan: NumberComparer;
most: NumberComparer;
lte: NumberComparer;
within(start: number, finish: number, message?: string): Assertion;
}
interface NumberComparer {
(value: number, message?: string): Assertion;
}
interface TypeComparison {
(type: string, message?: string): Assertion;
instanceof: InstanceOf;
instanceOf: InstanceOf;
}
interface InstanceOf {
(constructor: Object, message?: string): Assertion;
}
interface CloseTo {
(expected: number, delta: number, message?: string): Assertion;
}
interface Deep {
equal: Equal;
include: Include;
property: Property;
members: Members;
}
interface KeyFilter {
keys: Keys;
}
interface Equal {
(value: any, message?: string): Assertion;
}
interface Property {
(name: string, value?: any, message?: string): Assertion;
}
interface OwnProperty {
(name: string, message?: string): Assertion;
}
interface OwnPropertyDescriptor {
(name: string, descriptor: PropertyDescriptor, message?: string): Assertion;
(name: string, message?: string): Assertion;
}
interface Length extends LanguageChains, NumericComparison {
(length: number, message?: string): Assertion;
}
interface Include {
(value: Object, message?: string): Assertion;
(value: string, message?: string): Assertion;
(value: number, message?: string): Assertion;
keys: Keys;
members: Members;
any: KeyFilter;
all: KeyFilter;
}
interface Match {
(regexp: RegExp|string, message?: string): Assertion;
}
interface Keys {
(...keys: string[]): Assertion;
(keys: any[]): Assertion;
(keys: Object): Assertion;
}
interface Throw {
(): Assertion;
(expected: string, message?: string): Assertion;
(expected: RegExp, message?: string): Assertion;
(constructor: Error, expected?: string, message?: string): Assertion;
(constructor: Error, expected?: RegExp, message?: string): Assertion;
(constructor: Function, expected?: string, message?: string): Assertion;
(constructor: Function, expected?: RegExp, message?: string): Assertion;
}
interface RespondTo {
(method: string, message?: string): Assertion;
}
interface Satisfy {
(matcher: Function, message?: string): Assertion;
}
interface Members {
(set: any[], message?: string): Assertion;
}
interface PropertyChange {
(object: Object, prop: string, msg?: string): Assertion;
}
export interface Assert {
/**
* @param expression Expression to test for truthiness.
* @param message Message to display on error.
*/
(expression: any, message?: string): void;
fail(actual?: any, expected?: any, msg?: string, operator?: string): void;
ok(val: any, msg?: string): void;
isOk(val: any, msg?: string): void;
notOk(val: any, msg?: string): void;
isNotOk(val: any, msg?: string): void;
equal(act: any, exp: any, msg?: string): void;
notEqual(act: any, exp: any, msg?: string): void;
strictEqual(act: any, exp: any, msg?: string): void;
notStrictEqual(act: any, exp: any, msg?: string): void;
deepEqual(act: any, exp: any, msg?: string): void;
notDeepEqual(act: any, exp: any, msg?: string): void;
isTrue(val: any, msg?: string): void;
isFalse(val: any, msg?: string): void;
isNotTrue(val: any, msg?: string): void;
isNotFalse(val: any, msg?: string): void;
isNull(val: any, msg?: string): void;
isNotNull(val: any, msg?: string): void;
isUndefined(val: any, msg?: string): void;
isDefined(val: any, msg?: string): void;
isNaN(val: any, msg?: string): void;
isNotNaN(val: any, msg?: string): void;
isAbove(val: number, abv: number, msg?: string): void;
isBelow(val: number, blw: number, msg?: string): void;
isAtLeast(val: number, atlst: number, msg?: string): void;
isAtMost(val: number, atmst: number, msg?: string): void;
isFunction(val: any, msg?: string): void;
isNotFunction(val: any, msg?: string): void;
isObject(val: any, msg?: string): void;
isNotObject(val: any, msg?: string): void;
isArray(val: any, msg?: string): void;
isNotArray(val: any, msg?: string): void;
isString(val: any, msg?: string): void;
isNotString(val: any, msg?: string): void;
isNumber(val: any, msg?: string): void;
isNotNumber(val: any, msg?: string): void;
isBoolean(val: any, msg?: string): void;
isNotBoolean(val: any, msg?: string): void;
typeOf(val: any, type: string, msg?: string): void;
notTypeOf(val: any, type: string, msg?: string): void;
instanceOf(val: any, type: Function, msg?: string): void;
notInstanceOf(val: any, type: Function, msg?: string): void;
include(exp: string, inc: any, msg?: string): void;
include(exp: any[], inc: any, msg?: string): void;
notInclude(exp: string, inc: any, msg?: string): void;
notInclude(exp: any[], inc: any, msg?: string): void;
match(exp: any, re: RegExp, msg?: string): void;
notMatch(exp: any, re: RegExp, msg?: string): void;
property(obj: Object, prop: string, msg?: string): void;
notProperty(obj: Object, prop: string, msg?: string): void;
deepProperty(obj: Object, prop: string, msg?: string): void;
notDeepProperty(obj: Object, prop: string, msg?: string): void;
propertyVal(obj: Object, prop: string, val: any, msg?: string): void;
propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
lengthOf(exp: any, len: number, msg?: string): void;
//alias frenzy
throw(fn: Function, msg?: string): void;
throw(fn: Function, regExp: RegExp): void;
throw(fn: Function, errType: Function, msg?: string): void;
throw(fn: Function, errType: Function, regExp: RegExp): void;
throws(fn: Function, msg?: string): void;
throws(fn: Function, regExp: RegExp): void;
throws(fn: Function, errType: Function, msg?: string): void;
throws(fn: Function, errType: Function, regExp: RegExp): void;
Throw(fn: Function, msg?: string): void;
Throw(fn: Function, regExp: RegExp): void;
Throw(fn: Function, errType: Function, msg?: string): void;
Throw(fn: Function, errType: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, msg?: string): void;
doesNotThrow(fn: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, errType: Function, msg?: string): void;
doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void;
operator(val: any, operator: string, val2: any, msg?: string): void;
closeTo(act: number, exp: number, delta: number, msg?: string): void;
approximately(act: number, exp: number, delta: number, msg?: string): void;
sameMembers(set1: any[], set2: any[], msg?: string): void;
sameDeepMembers(set1: any[], set2: any[], msg?: string): void;
includeMembers(superset: any[], subset: any[], msg?: string): void;
ifError(val: any, msg?: string): void;
isExtensible(obj: {}, msg?: string): void;
extensible(obj: {}, msg?: string): void;
isNotExtensible(obj: {}, msg?: string): void;
notExtensible(obj: {}, msg?: string): void;
isSealed(obj: {}, msg?: string): void;
sealed(obj: {}, msg?: string): void;
isNotSealed(obj: {}, msg?: string): void;
notSealed(obj: {}, msg?: string): void;
isFrozen(obj: Object, msg?: string): void;
frozen(obj: Object, msg?: string): void;
isNotFrozen(obj: Object, msg?: string): void;
notFrozen(obj: Object, msg?: string): void;
oneOf(inList: any, list: any[], msg?: string): void;
}
export interface Config {
includeStack: boolean;
}
export class AssertionError {
constructor(message: string, _props?: any, ssf?: Function);
name: string;
message: string;
showDiff: boolean;
stack: string;
}
}
declare var chai: Chai.ChaiStatic;
declare module "chai" {
export = chai;
}
interface Object {
should: Chai.Assertion;
}
// Type definitions for chai 3.4.0
// Project: http://chaijs.com/
// Definitions by: Jed Mao <https://github.com/jedmao/>,
// Bart van der Schoor <https://github.com/Bartvds>,
// Andrew Brown <https://github.com/AGBrown>,
// Olivier Chevet <https://github.com/olivr70>,
// Matt Wistrand <https://github.com/mwistrand>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
// <reference path="../assertion-error/assertion-error.d.ts"/>
declare module Chai {
interface ChaiStatic {
expect: ExpectStatic;
should(): Should;
/**
* Provides a way to extend the internals of Chai
*/
use(fn: (chai: any, utils: any) => void): any;
assert: AssertStatic;
config: Config;
AssertionError: typeof AssertionError;
}
export interface ExpectStatic extends AssertionStatic {
fail(actual?: any, expected?: any, message?: string, operator?: string): void;
}
export interface AssertStatic extends Assert {
}
export interface AssertionStatic {
(target: any, message?: string): Assertion;
}
interface ShouldAssertion {
equal(value1: any, value2: any, message?: string): void;
Throw: ShouldThrow;
throw: ShouldThrow;
exist(value: any, message?: string): void;
}
interface Should extends ShouldAssertion {
not: ShouldAssertion;
fail(actual: any, expected: any, message?: string, operator?: string): void;
}
interface ShouldThrow {
(actual: Function): void;
(actual: Function, expected: string|RegExp, message?: string): void;
(actual: Function, constructor: Error|Function, expected?: string|RegExp, message?: string): void;
}
interface Assertion extends LanguageChains, NumericComparison, TypeComparison {
not: Assertion;
deep: Deep;
any: KeyFilter;
all: KeyFilter;
a: TypeComparison;
an: TypeComparison;
include: Include;
includes: Include;
contain: Include;
contains: Include;
ok: Assertion;
true: Assertion;
false: Assertion;
null: Assertion;
undefined: Assertion;
NaN: Assertion;
exist: Assertion;
empty: Assertion;
arguments: Assertion;
Arguments: Assertion;
equal: Equal;
equals: Equal;
eq: Equal;
eql: Equal;
eqls: Equal;
property: Property;
ownProperty: OwnProperty;
haveOwnProperty: OwnProperty;
ownPropertyDescriptor: OwnPropertyDescriptor;
haveOwnPropertyDescriptor: OwnPropertyDescriptor;
length: Length;
lengthOf: Length;
match: Match;
matches: Match;
string(string: string, message?: string): Assertion;
keys: Keys;
key(string: string): Assertion;
throw: Throw;
throws: Throw;
Throw: Throw;
respondTo: RespondTo;
respondsTo: RespondTo;
itself: Assertion;
satisfy: Satisfy;
satisfies: Satisfy;
closeTo: CloseTo;
approximately: CloseTo;
members: Members;
increase: PropertyChange;
increases: PropertyChange;
decrease: PropertyChange;
decreases: PropertyChange;
change: PropertyChange;
changes: PropertyChange;
extensible: Assertion;
sealed: Assertion;
frozen: Assertion;
oneOf(list: any[], message?: string): Assertion;
}
interface LanguageChains {
to: Assertion;
be: Assertion;
been: Assertion;
is: Assertion;
that: Assertion;
which: Assertion;
and: Assertion;
has: Assertion;
have: Assertion;
with: Assertion;
at: Assertion;
of: Assertion;
same: Assertion;
}
interface NumericComparison {
above: NumberComparer;
gt: NumberComparer;
greaterThan: NumberComparer;
least: NumberComparer;
gte: NumberComparer;
below: NumberComparer;
lt: NumberComparer;
lessThan: NumberComparer;
most: NumberComparer;
lte: NumberComparer;
within(start: number, finish: number, message?: string): Assertion;
}
interface NumberComparer {
(value: number, message?: string): Assertion;
}
interface TypeComparison {
(type: string, message?: string): Assertion;
instanceof: InstanceOf;
instanceOf: InstanceOf;
}
interface InstanceOf {
(constructor: Object, message?: string): Assertion;
}
interface CloseTo {
(expected: number, delta: number, message?: string): Assertion;
}
interface Deep {
equal: Equal;
include: Include;
property: Property;
members: Members;
}
interface KeyFilter {
keys: Keys;
}
interface Equal {
(value: any, message?: string): Assertion;
}
interface Property {
(name: string, value?: any, message?: string): Assertion;
}
interface OwnProperty {
(name: string, message?: string): Assertion;
}
interface OwnPropertyDescriptor {
(name: string, descriptor: PropertyDescriptor, message?: string): Assertion;
(name: string, message?: string): Assertion;
}
interface Length extends LanguageChains, NumericComparison {
(length: number, message?: string): Assertion;
}
interface Include {
(value: Object, message?: string): Assertion;
(value: string, message?: string): Assertion;
(value: number, message?: string): Assertion;
keys: Keys;
members: Members;
any: KeyFilter;
all: KeyFilter;
}
interface Match {
(regexp: RegExp|string, message?: string): Assertion;
}
interface Keys {
(...keys: string[]): Assertion;
(keys: any[]): Assertion;
(keys: Object): Assertion;
}
interface Throw {
(): Assertion;
(expected: string, message?: string): Assertion;
(expected: RegExp, message?: string): Assertion;
(constructor: Error, expected?: string, message?: string): Assertion;
(constructor: Error, expected?: RegExp, message?: string): Assertion;
(constructor: Function, expected?: string, message?: string): Assertion;
(constructor: Function, expected?: RegExp, message?: string): Assertion;
}
interface RespondTo {
(method: string, message?: string): Assertion;
}
interface Satisfy {
(matcher: Function, message?: string): Assertion;
}
interface Members {
(set: any[], message?: string): Assertion;
}
interface PropertyChange {
(object: Object, prop: string, msg?: string): Assertion;
}
export interface Assert {
/**
* @param expression Expression to test for truthiness.
* @param message Message to display on error.
*/
(expression: any, message?: string): void;
fail(actual?: any, expected?: any, msg?: string, operator?: string): void;
ok(val: any, msg?: string): void;
isOk(val: any, msg?: string): void;
notOk(val: any, msg?: string): void;
isNotOk(val: any, msg?: string): void;
equal(act: any, exp: any, msg?: string): void;
notEqual(act: any, exp: any, msg?: string): void;
strictEqual(act: any, exp: any, msg?: string): void;
notStrictEqual(act: any, exp: any, msg?: string): void;
deepEqual(act: any, exp: any, msg?: string): void;
notDeepEqual(act: any, exp: any, msg?: string): void;
isTrue(val: any, msg?: string): void;
isFalse(val: any, msg?: string): void;
isNotTrue(val: any, msg?: string): void;
isNotFalse(val: any, msg?: string): void;
isNull(val: any, msg?: string): void;
isNotNull(val: any, msg?: string): void;
isUndefined(val: any, msg?: string): void;
isDefined(val: any, msg?: string): void;
isNaN(val: any, msg?: string): void;
isNotNaN(val: any, msg?: string): void;
isAbove(val: number, abv: number, msg?: string): void;
isBelow(val: number, blw: number, msg?: string): void;
isAtLeast(val: number, atlst: number, msg?: string): void;
isAtMost(val: number, atmst: number, msg?: string): void;
isFunction(val: any, msg?: string): void;
isNotFunction(val: any, msg?: string): void;
isObject(val: any, msg?: string): void;
isNotObject(val: any, msg?: string): void;
isArray(val: any, msg?: string): void;
isNotArray(val: any, msg?: string): void;
isString(val: any, msg?: string): void;
isNotString(val: any, msg?: string): void;
isNumber(val: any, msg?: string): void;
isNotNumber(val: any, msg?: string): void;
isBoolean(val: any, msg?: string): void;
isNotBoolean(val: any, msg?: string): void;
typeOf(val: any, type: string, msg?: string): void;
notTypeOf(val: any, type: string, msg?: string): void;
instanceOf(val: any, type: Function, msg?: string): void;
notInstanceOf(val: any, type: Function, msg?: string): void;
include(exp: string, inc: any, msg?: string): void;
include(exp: any[], inc: any, msg?: string): void;
notInclude(exp: string, inc: any, msg?: string): void;
notInclude(exp: any[], inc: any, msg?: string): void;
match(exp: any, re: RegExp, msg?: string): void;
notMatch(exp: any, re: RegExp, msg?: string): void;
property(obj: Object, prop: string, msg?: string): void;
notProperty(obj: Object, prop: string, msg?: string): void;
deepProperty(obj: Object, prop: string, msg?: string): void;
notDeepProperty(obj: Object, prop: string, msg?: string): void;
propertyVal(obj: Object, prop: string, val: any, msg?: string): void;
propertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyVal(obj: Object, prop: string, val: any, msg?: string): void;
deepPropertyNotVal(obj: Object, prop: string, val: any, msg?: string): void;
lengthOf(exp: any, len: number, msg?: string): void;
//alias frenzy
throw(fn: Function, msg?: string): void;
throw(fn: Function, regExp: RegExp): void;
throw(fn: Function, errType: Function, msg?: string): void;
throw(fn: Function, errType: Function, regExp: RegExp): void;
throws(fn: Function, msg?: string): void;
throws(fn: Function, regExp: RegExp): void;
throws(fn: Function, errType: Function, msg?: string): void;
throws(fn: Function, errType: Function, regExp: RegExp): void;
Throw(fn: Function, msg?: string): void;
Throw(fn: Function, regExp: RegExp): void;
Throw(fn: Function, errType: Function, msg?: string): void;
Throw(fn: Function, errType: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, msg?: string): void;
doesNotThrow(fn: Function, regExp: RegExp): void;
doesNotThrow(fn: Function, errType: Function, msg?: string): void;
doesNotThrow(fn: Function, errType: Function, regExp: RegExp): void;
operator(val: any, operator: string, val2: any, msg?: string): void;
closeTo(act: number, exp: number, delta: number, msg?: string): void;
approximately(act: number, exp: number, delta: number, msg?: string): void;
sameMembers(set1: any[], set2: any[], msg?: string): void;
sameDeepMembers(set1: any[], set2: any[], msg?: string): void;
includeMembers(superset: any[], subset: any[], msg?: string): void;
ifError(val: any, msg?: string): void;
isExtensible(obj: {}, msg?: string): void;
extensible(obj: {}, msg?: string): void;
isNotExtensible(obj: {}, msg?: string): void;
notExtensible(obj: {}, msg?: string): void;
isSealed(obj: {}, msg?: string): void;
sealed(obj: {}, msg?: string): void;
isNotSealed(obj: {}, msg?: string): void;
notSealed(obj: {}, msg?: string): void;
isFrozen(obj: Object, msg?: string): void;
frozen(obj: Object, msg?: string): void;
isNotFrozen(obj: Object, msg?: string): void;
notFrozen(obj: Object, msg?: string): void;
oneOf(inList: any, list: any[], msg?: string): void;
}
export interface Config {
includeStack: boolean;
}
export class AssertionError {
constructor(message: string, _props?: any, ssf?: Function);
name: string;
message: string;
showDiff: boolean;
stack: string;
}
}
declare var chai: Chai.ChaiStatic;
declare module "chai" {
export = chai;
}
interface Object {
should: Chai.Assertion;
}

View File

@@ -1,14 +1,14 @@
/// <reference path="checksum.d.ts" />
import checksum = require("checksum");
var s: string = checksum("abcd");
var t: string = checksum("abcd", { algorithm: 'sha1' });
checksum.file("myfile.txt", (error: Error, hash: string): void => {
// do nothing
});
checksum.file("myfile.txt", { algorithm: 'sha1' }, (error: Error, hash: string): void => {
// do nothing
});
/// <reference path="checksum.d.ts" />
import checksum = require("checksum");
var s: string = checksum("abcd");
var t: string = checksum("abcd", { algorithm: 'sha1' });
checksum.file("myfile.txt", (error: Error, hash: string): void => {
// do nothing
});
checksum.file("myfile.txt", { algorithm: 'sha1' }, (error: Error, hash: string): void => {
// do nothing
});

View File

@@ -1,44 +1,44 @@
// Type definitions for checksum 0.1.1
// Project: https://github.com/dshaw/checksum
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "checksum" {
module checksum {
/**
* Options object for all functions
*/
interface ChecksumOptions {
/**
* Algorithm to use, default 'sha1'
* Can be 'sha1' or 'md5' (see module 'crypto').
*/
algorithm?: string;
}
/**
* Generate the checksum for a file on disk
* @param filename The file name
* @param callback Callback which is called with the result or an error
*/
function file(filename: string, callback: (error: Error, hash: string) => void): void;
/**
* Generate the checksum for a file on disk
* @param filename The file name
* @param options Options object to indicate hash algo
* @param callback Callback which is called with the result or an error
*/
function file(filename: string, options: ChecksumOptions, callback: (error: Error, hash: string) => void): void;
}
/**
* Generates a checksum for the given value
* @param value Any value
* @param options Allows to set the algorithm
* @returns Checksum
*/
function checksum(value: any, options?: checksum.ChecksumOptions): string;
export = checksum;
}
// Type definitions for checksum 0.1.1
// Project: https://github.com/dshaw/checksum
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "checksum" {
module checksum {
/**
* Options object for all functions
*/
interface ChecksumOptions {
/**
* Algorithm to use, default 'sha1'
* Can be 'sha1' or 'md5' (see module 'crypto').
*/
algorithm?: string;
}
/**
* Generate the checksum for a file on disk
* @param filename The file name
* @param callback Callback which is called with the result or an error
*/
function file(filename: string, callback: (error: Error, hash: string) => void): void;
/**
* Generate the checksum for a file on disk
* @param filename The file name
* @param options Options object to indicate hash algo
* @param callback Callback which is called with the result or an error
*/
function file(filename: string, options: ChecksumOptions, callback: (error: Error, hash: string) => void): void;
}
/**
* Generates a checksum for the given value
* @param value Any value
* @param options Allows to set the algorithm
* @returns Checksum
*/
function checksum(value: any, options?: checksum.ChecksumOptions): string;
export = checksum;
}

View File

@@ -1,294 +1,294 @@
/// <reference path="cheerio.d.ts" />
import * as cheerio from 'cheerio';
/*
* LOADING
*/
let html =
`<ul id="fruits">
<li class="orange">Apple</li>
<li class="class">Orange</li>
<li class="pear">Pear</li>
<input type="text" />
</ul>`;
// Preferred Method
var $ = cheerio.load(html);
// Directly load element
cheerio(html);
cheerio('ul', html);
cheerio('li', 'ul', html);
$ = cheerio.load(html, {
normalizeWhitespace: true,
xmlMode: true
});
$ = cheerio.load(html, {
normalizeWhitespace: true,
xmlMode: true,
decodeEntities: true,
lowerCaseTags: true,
lowerCaseAttributeNames: true,
recognizeCDATA: true,
recognizeSelfClosing: true
});
/**
* Selectors
*/
var $el = $('.class');
var $multiEl = $('selector', 'selector', 'selector');
/**
* Attributes
*/
// attr
$el.attr('id');
$el.attr('id', 'favorite').html();
// data
$el.data();
$el.data('apple-color');
$el.data('kind', 'mac');
// val
$('input[type="text"]').val();
$('input[type="text"]').val('test').html();
// removeAttr
$el.removeAttr('class').html();
// hasClass, addClass, removeClass, toggleClass
$el.addClass('class').addClass('test');
$el.hasClass('test');
$el.removeClass('class').removeClass('test');
$el.addClass('red').removeClass().html();
$el.toggleClass('fruit green red').html();
// is
$el.is('#id');
$el.is($el);
$el.is(() => {
return true;
});
/**
* Forms
*/
// serializeArray
$('<form><input name="foo" value="bar" /></form>').serializeArray();
/**
* Traversing
*/
// find
$el.find('li').length;
$el.find($('.apple')).length;
// .parent([selector])
$el.parent().attr('id');
$el.parent('.class').attr('id');
// .parents([selector])
$el.parents().length;
$el.parents('.class').length;
// .parentsUntil([selector][,filter])
$el.parentsUntil().length;
$el.parentsUntil('.class').length;
// .closest(selector)
$el.closest();
$el.closest('.class');
// .next([selector])
$el.next().hasClass('class');
$el.next('.class').hasClass('class');
// .nextAll([selector])
$el.nextAll().length;
$el.nextAll('.class').length;
// .nextUntil([selector], [filter])
$el.nextUntil();
$el.nextUntil('.class');
// .prev([selector])
$el.prev().hasClass('class');
$el.prev('.class').hasClass('class');
// .prevAll([selector])
$el.prevAll().length;
$el.prevAll('.class').length;
// .prevUntil([selector], [filter])
$el.prevUntil();
$el.prevUntil('.class');
// .slice( start, [end] )
$el.slice(1).eq(0).text();
$el.slice(1, 2).length;
// .siblings([selector])
$el.siblings().length;
$el.siblings('.class').length;
// .children([selector])
$el.children().length;
$el.children('.class').text();
// .contents()
$el.contents().length;
// .each( function(index, element) )
$el.each((i, el) => {
$(el).html();
});
// .map( function(index, element) )
$el.map((i, el) => {
return $(el).text();
}).get().join(' ');
// .filter
$ = cheerio.load(html);
$el.filter('.class').attr('class');
$el.filter($('.class')).attr('class');
$el.filter($('.class')[0]).attr('class');
$el.filter((i, el) => {
return $(el).attr('class') === 'class';
}).attr('class');
// .not
$el.not('.class').length;
$el.not($('.class')).length;
$el.not($('.class')[0]).length;
$el.not((i, el) => {
return $(el).attr('class') === 'class';
}).length;
// .has
$el.has('.class').attr('id');
$el.has($el[0]).attr('id');
// .first()
$el.children().first().text();
// .last()
$el.children().last().text();
// .eq( i )
$el.eq(0).text();
$el.eq(-1).text();
// .get( [i] )
$el.get(0).tagName;
$el.get().length;
// .index()
// .index( selector )
// .index( nodeOrSelection )
$el.index();
$el.index('li');
$el.index($('#fruit, li'));
// .end()
$el.eq(0).end().length;
// .add
$el.add('.class').length
// .addBack( [filter] )
$el.eq(0).addBack().length
$el.eq(0).addBack('.class').length
/**
* Manipulation
*/
// .append( content, [content, ...] )
$el.append('<li class="plum">Plum</li>').html();
$el.append('<li class="plum">Plum</li>', '<li class="plum">Plum</li>').html();
// .prepend( content, [content, ...] )
$el.prepend('<li class="plum">Plum</li>').html();
$el.prepend('<li class="plum">Plum</li>', '<li class="plum">Plum</li>').html();
// .after( content, [content, ...] )
$el.after('<li class="plum">Plum</li>').html();
$el.after('<li class="plum">Plum</li>', '<li class="plum">Plum</li>').html();
// .insertAfter( content )
$('<li class="plum">Plum</li>').insertAfter('.class').html();
// .before( content, [content, ...] )
$el.before('<li class="plum">Plum</li>').html();
$el.before('<li class="plum">Plum</li>', '<li class="plum">Plum</li>').html();
// .insertBefore( content )
$('<li class="plum">Plum</li>').insertBefore('.class').html();
// .remove( [selector] )
$el.remove().html();
$el.remove('.class').html();
// .replaceWith( content )
$el.replaceWith($('<li class="plum">Plum</li>')).html();
// .empty()
$el.empty().html();
// .html( [htmlString] )
$el.html();
$el.html('<li class="mango">Mango</li>').html();
// .text( [textString] )
$el.text();
$el.text('text');
// .wrap( content )
// See https://github.com/cheeriojs/cheerio/issues/731
// $el.wrap($('<div class="red-fruit"></div>')).html();
// .css
$el.css('width');
$el.css(['width', 'height']);
$el.css('width', '50px');
/**
* Rendering
*/
$.html();
$.html('.class');
$.xml();
/**
* Miscellaneous
*/
// .clone() ####
$el.clone().html();
/**
* Utilities
*/
// $.root
$.root().append('<ul id="vegetables"></ul>').html();
// $.contains( container, contained )
$.contains($el[0], $el[0]);
// $.parseHTML( data [, context ] [, keepScripts ] )
$.parseHTML(html);
$.parseHTML(html, null, true);
/**
* Not in doc
*/
$el.toArray();
/// <reference path="cheerio.d.ts" />
import * as cheerio from 'cheerio';
/*
* LOADING
*/
let html =
`<ul id="fruits">
<li class="orange">Apple</li>
<li class="class">Orange</li>
<li class="pear">Pear</li>
<input type="text" />
</ul>`;
// Preferred Method
var $ = cheerio.load(html);
// Directly load element
cheerio(html);
cheerio('ul', html);
cheerio('li', 'ul', html);
$ = cheerio.load(html, {
normalizeWhitespace: true,
xmlMode: true
});
$ = cheerio.load(html, {
normalizeWhitespace: true,
xmlMode: true,
decodeEntities: true,
lowerCaseTags: true,
lowerCaseAttributeNames: true,
recognizeCDATA: true,
recognizeSelfClosing: true
});
/**
* Selectors
*/
var $el = $('.class');
var $multiEl = $('selector', 'selector', 'selector');
/**
* Attributes
*/
// attr
$el.attr('id');
$el.attr('id', 'favorite').html();
// data
$el.data();
$el.data('apple-color');
$el.data('kind', 'mac');
// val
$('input[type="text"]').val();
$('input[type="text"]').val('test').html();
// removeAttr
$el.removeAttr('class').html();
// hasClass, addClass, removeClass, toggleClass
$el.addClass('class').addClass('test');
$el.hasClass('test');
$el.removeClass('class').removeClass('test');
$el.addClass('red').removeClass().html();
$el.toggleClass('fruit green red').html();
// is
$el.is('#id');
$el.is($el);
$el.is(() => {
return true;
});
/**
* Forms
*/
// serializeArray
$('<form><input name="foo" value="bar" /></form>').serializeArray();
/**
* Traversing
*/
// find
$el.find('li').length;
$el.find($('.apple')).length;
// .parent([selector])
$el.parent().attr('id');
$el.parent('.class').attr('id');
// .parents([selector])
$el.parents().length;
$el.parents('.class').length;
// .parentsUntil([selector][,filter])
$el.parentsUntil().length;
$el.parentsUntil('.class').length;
// .closest(selector)
$el.closest();
$el.closest('.class');
// .next([selector])
$el.next().hasClass('class');
$el.next('.class').hasClass('class');
// .nextAll([selector])
$el.nextAll().length;
$el.nextAll('.class').length;
// .nextUntil([selector], [filter])
$el.nextUntil();
$el.nextUntil('.class');
// .prev([selector])
$el.prev().hasClass('class');
$el.prev('.class').hasClass('class');
// .prevAll([selector])
$el.prevAll().length;
$el.prevAll('.class').length;
// .prevUntil([selector], [filter])
$el.prevUntil();
$el.prevUntil('.class');
// .slice( start, [end] )
$el.slice(1).eq(0).text();
$el.slice(1, 2).length;
// .siblings([selector])
$el.siblings().length;
$el.siblings('.class').length;
// .children([selector])
$el.children().length;
$el.children('.class').text();
// .contents()
$el.contents().length;
// .each( function(index, element) )
$el.each((i, el) => {
$(el).html();
});
// .map( function(index, element) )
$el.map((i, el) => {
return $(el).text();
}).get().join(' ');
// .filter
$ = cheerio.load(html);
$el.filter('.class').attr('class');
$el.filter($('.class')).attr('class');
$el.filter($('.class')[0]).attr('class');
$el.filter((i, el) => {
return $(el).attr('class') === 'class';
}).attr('class');
// .not
$el.not('.class').length;
$el.not($('.class')).length;
$el.not($('.class')[0]).length;
$el.not((i, el) => {
return $(el).attr('class') === 'class';
}).length;
// .has
$el.has('.class').attr('id');
$el.has($el[0]).attr('id');
// .first()
$el.children().first().text();
// .last()
$el.children().last().text();
// .eq( i )
$el.eq(0).text();
$el.eq(-1).text();
// .get( [i] )
$el.get(0).tagName;
$el.get().length;
// .index()
// .index( selector )
// .index( nodeOrSelection )
$el.index();
$el.index('li');
$el.index($('#fruit, li'));
// .end()
$el.eq(0).end().length;
// .add
$el.add('.class').length
// .addBack( [filter] )
$el.eq(0).addBack().length
$el.eq(0).addBack('.class').length
/**
* Manipulation
*/
// .append( content, [content, ...] )
$el.append('<li class="plum">Plum</li>').html();
$el.append('<li class="plum">Plum</li>', '<li class="plum">Plum</li>').html();
// .prepend( content, [content, ...] )
$el.prepend('<li class="plum">Plum</li>').html();
$el.prepend('<li class="plum">Plum</li>', '<li class="plum">Plum</li>').html();
// .after( content, [content, ...] )
$el.after('<li class="plum">Plum</li>').html();
$el.after('<li class="plum">Plum</li>', '<li class="plum">Plum</li>').html();
// .insertAfter( content )
$('<li class="plum">Plum</li>').insertAfter('.class').html();
// .before( content, [content, ...] )
$el.before('<li class="plum">Plum</li>').html();
$el.before('<li class="plum">Plum</li>', '<li class="plum">Plum</li>').html();
// .insertBefore( content )
$('<li class="plum">Plum</li>').insertBefore('.class').html();
// .remove( [selector] )
$el.remove().html();
$el.remove('.class').html();
// .replaceWith( content )
$el.replaceWith($('<li class="plum">Plum</li>')).html();
// .empty()
$el.empty().html();
// .html( [htmlString] )
$el.html();
$el.html('<li class="mango">Mango</li>').html();
// .text( [textString] )
$el.text();
$el.text('text');
// .wrap( content )
// See https://github.com/cheeriojs/cheerio/issues/731
// $el.wrap($('<div class="red-fruit"></div>')).html();
// .css
$el.css('width');
$el.css(['width', 'height']);
$el.css('width', '50px');
/**
* Rendering
*/
$.html();
$.html('.class');
$.xml();
/**
* Miscellaneous
*/
// .clone() ####
$el.clone().html();
/**
* Utilities
*/
// $.root
$.root().append('<ul id="vegetables"></ul>').html();
// $.contains( container, contained )
$.contains($el[0], $el[0]);
// $.parseHTML( data [, context ] [, keepScripts ] )
$.parseHTML(html);
$.parseHTML(html, null, true);
/**
* Not in doc
*/
$el.toArray();

532
cheerio/cheerio.d.ts vendored
View File

@@ -1,266 +1,266 @@
// Type definitions for Cheerio v0.17.0
// Project: https://github.com/cheeriojs/cheerio
// Definitions by: Bret Little <https://github.com/blittle>, VILIC VANE <http://vilic.info>, Wayne Maurer <https://github.com/wmaurer>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Cheerio {
// Document References
// Cheerio https://github.com/cheeriojs/cheerio
// JQuery http://api.jquery.com
[index: number]: CheerioElement;
length: number;
// Attributes
attr(name: string): string;
attr(name: string, value: any): Cheerio;
data(): any;
data(name: string): any;
data(name: string, value: any): any;
val(): string;
val(value: string): Cheerio;
removeAttr(name: string): Cheerio;
has(selector: string): Cheerio;
has(element: CheerioElement): Cheerio;
hasClass(className: string): boolean;
addClass(classNames: string): Cheerio;
removeClass(): Cheerio;
removeClass(className: string): Cheerio;
removeClass(func: (index: number, className: string) => string): Cheerio;
toggleClass(className: string): Cheerio;
toggleClass(className: string, toggleSwitch: boolean): Cheerio;
toggleClass(toggleSwitch?: boolean): Cheerio;
toggleClass(func: (index: number, className: string, toggleSwitch: boolean) => string, toggleSwitch?: boolean): Cheerio;
is(selector: string): boolean;
is(element: CheerioElement): boolean;
is(element: CheerioElement[]): boolean;
is(selection: Cheerio): boolean;
is(func: (index: number, element: CheerioElement) => boolean): boolean;
// Form
serializeArray(): {name: string, value: string}[];
// Traversing
find(selector: string): Cheerio;
find(element: Cheerio): Cheerio;
parent(selector?: string): Cheerio;
parents(selector?: string): Cheerio;
parentsUntil(selector?: string, filter?: string): Cheerio;
parentsUntil(element: CheerioElement, filter?: string): Cheerio;
parentsUntil(element: Cheerio, filter?: string): Cheerio;
closest(): Cheerio;
closest(selector: string): Cheerio;
next(selector?: string): Cheerio;
nextAll(): Cheerio;
nextAll(selector: string): Cheerio;
nextUntil(selector?: string, filter?: string): Cheerio;
nextUntil(element: CheerioElement, filter?: string): Cheerio;
nextUntil(element: Cheerio, filter?: string): Cheerio;
prev(selector?: string): Cheerio;
prevAll(): Cheerio;
prevAll(selector: string): Cheerio;
prevUntil(selector?: string, filter?: string): Cheerio;
prevUntil(element: CheerioElement, filter?: string): Cheerio;
prevUntil(element: Cheerio, filter?: string): Cheerio;
slice(start: number, end?: number): Cheerio;
siblings(selector?: string): Cheerio;
children(selector?: string): Cheerio;
contents(): Cheerio;
each(func: (index: number, element: CheerioElement) => any): Cheerio;
map(func: (index: number, element: CheerioElement) => any): Cheerio;
filter(selector: string): Cheerio;
filter(selection: Cheerio): Cheerio;
filter(element: CheerioElement): Cheerio;
filter(elements: CheerioElement[]): Cheerio;
filter(func: (index: number, element: CheerioElement) => boolean): Cheerio;
not(selector: string): Cheerio;
not(selection: Cheerio): Cheerio;
not(element: CheerioElement): Cheerio;
not(func: (index: number, element: CheerioElement) => boolean): Cheerio;
first(): Cheerio;
last(): Cheerio;
eq(index: number): Cheerio;
get(): CheerioElement[];
get(index: number): CheerioElement;
index(): number;
index(selector: string): number;
index(selection: Cheerio): number;
end(): Cheerio;
add(selectorOrHtml: string): Cheerio;
add(selector: string, context: Document): Cheerio;
add(element: CheerioElement): Cheerio;
add(elements: CheerioElement[]): Cheerio;
add(selection: Cheerio): Cheerio;
addBack():Cheerio;
addBack(filter: string):Cheerio;
// Manipulation
append(content: string, ...contents: any[]): Cheerio;
append(content: Document, ...contents: any[]): Cheerio;
append(content: Document[], ...contents: any[]): Cheerio;
append(content: Cheerio, ...contents: any[]): Cheerio;
prepend(content: string, ...contents: any[]): Cheerio;
prepend(content: Document, ...contents: any[]): Cheerio;
prepend(content: Document[], ...contents: any[]): Cheerio;
prepend(content: Cheerio, ...contents: any[]): Cheerio;
after(content: string, ...contents: any[]): Cheerio;
after(content: Document, ...contents: any[]): Cheerio;
after(content: Document[], ...contents: any[]): Cheerio;
after(content: Cheerio, ...contents: any[]): Cheerio;
insertAfter(content: string): Cheerio;
insertAfter(content: Document): Cheerio;
insertAfter(content: Cheerio): Cheerio;
before(content: string, ...contents: any[]): Cheerio;
before(content: Document, ...contents: any[]): Cheerio;
before(content: Document[], ...contents: any[]): Cheerio;
before(content: Cheerio, ...contents: any[]): Cheerio;
insertBefore(content: string): Cheerio;
insertBefore(content: Document): Cheerio;
insertBefore(content: Cheerio): Cheerio;
remove(selector?: string): Cheerio;
replaceWith(content: string): Cheerio;
replaceWith(content: CheerioElement): Cheerio;
replaceWith(content: CheerioElement[]): Cheerio;
replaceWith(content: Cheerio): Cheerio;
empty(): Cheerio;
html(): string;
html(html: string): Cheerio;
text(): string;
text(text: string): Cheerio;
// See https://github.com/cheeriojs/cheerio/issues/731
/*wrap(content: string): Cheerio;
wrap(content: Document): Cheerio;
wrap(content: Cheerio): Cheerio;*/
css(propertyName: string): string;
css(propertyNames: string[]): string[];
css(propertyName: string, value: string): Cheerio;
css(propertyName: string, value: number): Cheerio;
css(propertyName: string, func: (index: number, value: string) => string): Cheerio;
css(propertyName: string, func: (index: number, value: string) => number): Cheerio;
css(properties: Object): Cheerio;
// Rendering
// Miscellaneous
clone(): Cheerio;
// Not Documented
toArray(): CheerioElement[];
}
interface CheerioOptionsInterface {
// Document References
// Cheerio https://github.com/cheeriojs/cheerio
// HTMLParser2 https://github.com/fb55/htmlparser2/wiki/Parser-options
// DomHandler https://github.com/fb55/DomHandler
xmlMode?: boolean;
decodeEntities?: boolean;
lowerCaseTags?: boolean;
lowerCaseAttributeNames?: boolean;
recognizeCDATA?: boolean;
recognizeSelfClosing?: boolean;
normalizeWhitespace?: boolean;
}
interface CheerioSelector {
(selector: string): Cheerio;
(selector: string, context: string): Cheerio;
(selector: string, context: CheerioElement): Cheerio;
(selector: string, context: CheerioElement[]): Cheerio;
(selector: string, context: Cheerio): Cheerio;
(selector: string, context: string, root: string): Cheerio;
(selector: string, context: CheerioElement, root: string): Cheerio;
(selector: string, context: CheerioElement[], root: string): Cheerio;
(selector: string, context: Cheerio, root: string): Cheerio;
(selector: any): Cheerio;
}
interface CheerioStatic extends CheerioSelector {
// Document References
// Cheerio https://github.com/cheeriojs/cheerio
// JQuery http://api.jquery.com
xml(): string;
root(): Cheerio;
contains(container: CheerioElement, contained: CheerioElement): boolean;
parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[];
html(options?: CheerioOptionsInterface): string;
html(selector: string, options?: CheerioOptionsInterface): string;
html(element: Cheerio, options?: CheerioOptionsInterface): string;
html(element: CheerioElement, options?: CheerioOptionsInterface): string;
}
interface CheerioElement {
// Document References
// Node Console
tagName: string;
type: string;
name: string;
attribs: Object;
children: CheerioElement[];
childNodes: CheerioElement[];
lastChild: CheerioElement;
next: CheerioElement;
nextSibling: CheerioElement;
prev: CheerioElement;
previousSibling: CheerioElement;
parent: CheerioElement;
parentNode: CheerioElement;
nodeValue: string;
}
interface CheerioAPI extends CheerioSelector {
load(html: string, options?: CheerioOptionsInterface): CheerioStatic;
}
declare var cheerio:CheerioAPI;
declare module "cheerio" {
export = cheerio;
}
// Type definitions for Cheerio v0.17.0
// Project: https://github.com/cheeriojs/cheerio
// Definitions by: Bret Little <https://github.com/blittle>, VILIC VANE <http://vilic.info>, Wayne Maurer <https://github.com/wmaurer>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Cheerio {
// Document References
// Cheerio https://github.com/cheeriojs/cheerio
// JQuery http://api.jquery.com
[index: number]: CheerioElement;
length: number;
// Attributes
attr(name: string): string;
attr(name: string, value: any): Cheerio;
data(): any;
data(name: string): any;
data(name: string, value: any): any;
val(): string;
val(value: string): Cheerio;
removeAttr(name: string): Cheerio;
has(selector: string): Cheerio;
has(element: CheerioElement): Cheerio;
hasClass(className: string): boolean;
addClass(classNames: string): Cheerio;
removeClass(): Cheerio;
removeClass(className: string): Cheerio;
removeClass(func: (index: number, className: string) => string): Cheerio;
toggleClass(className: string): Cheerio;
toggleClass(className: string, toggleSwitch: boolean): Cheerio;
toggleClass(toggleSwitch?: boolean): Cheerio;
toggleClass(func: (index: number, className: string, toggleSwitch: boolean) => string, toggleSwitch?: boolean): Cheerio;
is(selector: string): boolean;
is(element: CheerioElement): boolean;
is(element: CheerioElement[]): boolean;
is(selection: Cheerio): boolean;
is(func: (index: number, element: CheerioElement) => boolean): boolean;
// Form
serializeArray(): {name: string, value: string}[];
// Traversing
find(selector: string): Cheerio;
find(element: Cheerio): Cheerio;
parent(selector?: string): Cheerio;
parents(selector?: string): Cheerio;
parentsUntil(selector?: string, filter?: string): Cheerio;
parentsUntil(element: CheerioElement, filter?: string): Cheerio;
parentsUntil(element: Cheerio, filter?: string): Cheerio;
closest(): Cheerio;
closest(selector: string): Cheerio;
next(selector?: string): Cheerio;
nextAll(): Cheerio;
nextAll(selector: string): Cheerio;
nextUntil(selector?: string, filter?: string): Cheerio;
nextUntil(element: CheerioElement, filter?: string): Cheerio;
nextUntil(element: Cheerio, filter?: string): Cheerio;
prev(selector?: string): Cheerio;
prevAll(): Cheerio;
prevAll(selector: string): Cheerio;
prevUntil(selector?: string, filter?: string): Cheerio;
prevUntil(element: CheerioElement, filter?: string): Cheerio;
prevUntil(element: Cheerio, filter?: string): Cheerio;
slice(start: number, end?: number): Cheerio;
siblings(selector?: string): Cheerio;
children(selector?: string): Cheerio;
contents(): Cheerio;
each(func: (index: number, element: CheerioElement) => any): Cheerio;
map(func: (index: number, element: CheerioElement) => any): Cheerio;
filter(selector: string): Cheerio;
filter(selection: Cheerio): Cheerio;
filter(element: CheerioElement): Cheerio;
filter(elements: CheerioElement[]): Cheerio;
filter(func: (index: number, element: CheerioElement) => boolean): Cheerio;
not(selector: string): Cheerio;
not(selection: Cheerio): Cheerio;
not(element: CheerioElement): Cheerio;
not(func: (index: number, element: CheerioElement) => boolean): Cheerio;
first(): Cheerio;
last(): Cheerio;
eq(index: number): Cheerio;
get(): CheerioElement[];
get(index: number): CheerioElement;
index(): number;
index(selector: string): number;
index(selection: Cheerio): number;
end(): Cheerio;
add(selectorOrHtml: string): Cheerio;
add(selector: string, context: Document): Cheerio;
add(element: CheerioElement): Cheerio;
add(elements: CheerioElement[]): Cheerio;
add(selection: Cheerio): Cheerio;
addBack():Cheerio;
addBack(filter: string):Cheerio;
// Manipulation
append(content: string, ...contents: any[]): Cheerio;
append(content: Document, ...contents: any[]): Cheerio;
append(content: Document[], ...contents: any[]): Cheerio;
append(content: Cheerio, ...contents: any[]): Cheerio;
prepend(content: string, ...contents: any[]): Cheerio;
prepend(content: Document, ...contents: any[]): Cheerio;
prepend(content: Document[], ...contents: any[]): Cheerio;
prepend(content: Cheerio, ...contents: any[]): Cheerio;
after(content: string, ...contents: any[]): Cheerio;
after(content: Document, ...contents: any[]): Cheerio;
after(content: Document[], ...contents: any[]): Cheerio;
after(content: Cheerio, ...contents: any[]): Cheerio;
insertAfter(content: string): Cheerio;
insertAfter(content: Document): Cheerio;
insertAfter(content: Cheerio): Cheerio;
before(content: string, ...contents: any[]): Cheerio;
before(content: Document, ...contents: any[]): Cheerio;
before(content: Document[], ...contents: any[]): Cheerio;
before(content: Cheerio, ...contents: any[]): Cheerio;
insertBefore(content: string): Cheerio;
insertBefore(content: Document): Cheerio;
insertBefore(content: Cheerio): Cheerio;
remove(selector?: string): Cheerio;
replaceWith(content: string): Cheerio;
replaceWith(content: CheerioElement): Cheerio;
replaceWith(content: CheerioElement[]): Cheerio;
replaceWith(content: Cheerio): Cheerio;
empty(): Cheerio;
html(): string;
html(html: string): Cheerio;
text(): string;
text(text: string): Cheerio;
// See https://github.com/cheeriojs/cheerio/issues/731
/*wrap(content: string): Cheerio;
wrap(content: Document): Cheerio;
wrap(content: Cheerio): Cheerio;*/
css(propertyName: string): string;
css(propertyNames: string[]): string[];
css(propertyName: string, value: string): Cheerio;
css(propertyName: string, value: number): Cheerio;
css(propertyName: string, func: (index: number, value: string) => string): Cheerio;
css(propertyName: string, func: (index: number, value: string) => number): Cheerio;
css(properties: Object): Cheerio;
// Rendering
// Miscellaneous
clone(): Cheerio;
// Not Documented
toArray(): CheerioElement[];
}
interface CheerioOptionsInterface {
// Document References
// Cheerio https://github.com/cheeriojs/cheerio
// HTMLParser2 https://github.com/fb55/htmlparser2/wiki/Parser-options
// DomHandler https://github.com/fb55/DomHandler
xmlMode?: boolean;
decodeEntities?: boolean;
lowerCaseTags?: boolean;
lowerCaseAttributeNames?: boolean;
recognizeCDATA?: boolean;
recognizeSelfClosing?: boolean;
normalizeWhitespace?: boolean;
}
interface CheerioSelector {
(selector: string): Cheerio;
(selector: string, context: string): Cheerio;
(selector: string, context: CheerioElement): Cheerio;
(selector: string, context: CheerioElement[]): Cheerio;
(selector: string, context: Cheerio): Cheerio;
(selector: string, context: string, root: string): Cheerio;
(selector: string, context: CheerioElement, root: string): Cheerio;
(selector: string, context: CheerioElement[], root: string): Cheerio;
(selector: string, context: Cheerio, root: string): Cheerio;
(selector: any): Cheerio;
}
interface CheerioStatic extends CheerioSelector {
// Document References
// Cheerio https://github.com/cheeriojs/cheerio
// JQuery http://api.jquery.com
xml(): string;
root(): Cheerio;
contains(container: CheerioElement, contained: CheerioElement): boolean;
parseHTML(data: string, context?: Document, keepScripts?: boolean): Document[];
html(options?: CheerioOptionsInterface): string;
html(selector: string, options?: CheerioOptionsInterface): string;
html(element: Cheerio, options?: CheerioOptionsInterface): string;
html(element: CheerioElement, options?: CheerioOptionsInterface): string;
}
interface CheerioElement {
// Document References
// Node Console
tagName: string;
type: string;
name: string;
attribs: Object;
children: CheerioElement[];
childNodes: CheerioElement[];
lastChild: CheerioElement;
next: CheerioElement;
nextSibling: CheerioElement;
prev: CheerioElement;
previousSibling: CheerioElement;
parent: CheerioElement;
parentNode: CheerioElement;
nodeValue: string;
}
interface CheerioAPI extends CheerioSelector {
load(html: string, options?: CheerioOptionsInterface): CheerioStatic;
}
declare var cheerio:CheerioAPI;
declare module "cheerio" {
export = cheerio;
}

View File

@@ -1,8 +1,8 @@
/// <reference path="chosen.jquery.d.ts" />
$(".chzn-select").chosen({ no_results_text: "No results matched" });
$("#form_field").chosen().change();
$("#form_field").trigger("liszt:updated");
$(".chzn-select").chosen();
/// <reference path="chosen.jquery.d.ts" />
$(".chzn-select").chosen({ no_results_text: "No results matched" });
$("#form_field").chosen().change();
$("#form_field").trigger("liszt:updated");
$(".chzn-select").chosen();
$(".chzn-select-deselect").chosen({ allow_single_deselect: true });

View File

@@ -1,30 +1,30 @@
// Type definitions for Chosen.JQuery 1.4.2
// Project: http://harvesthq.github.com/chosen/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface ChosenOptions {
allow_single_deselect?: boolean;
disable_search?: boolean;
disable_search_threshold?: number;
enable_split_word_search?: boolean;
inherit_select_classes?: boolean;
max_selected_options?: number;
no_results_text?: string;
placeholder_text_multiple?: string;
placeholder_text_single?: string;
search_contains?: boolean;
single_backstroke_delete?: boolean;
width?: number|string;
display_disabled_options?: boolean;
display_selected_options?: boolean;
include_group_label_in_selected?: boolean;
}
interface JQuery {
chosen(): JQuery;
chosen(options: ChosenOptions): JQuery;
}
// Type definitions for Chosen.JQuery 1.4.2
// Project: http://harvesthq.github.com/chosen/
// Definitions by: Boris Yankov <https://github.com/borisyankov/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../jquery/jquery.d.ts"/>
interface ChosenOptions {
allow_single_deselect?: boolean;
disable_search?: boolean;
disable_search_threshold?: number;
enable_split_word_search?: boolean;
inherit_select_classes?: boolean;
max_selected_options?: number;
no_results_text?: string;
placeholder_text_multiple?: string;
placeholder_text_single?: string;
search_contains?: boolean;
single_backstroke_delete?: boolean;
width?: number|string;
display_disabled_options?: boolean;
display_selected_options?: boolean;
include_group_label_in_selected?: boolean;
}
interface JQuery {
chosen(): JQuery;
chosen(options: ChosenOptions): JQuery;
}

View File

@@ -1 +1 @@

View File

@@ -1,48 +1,48 @@
/// <reference path="codemirror.d.ts" />
var myCodeMirror: CodeMirror.Editor = CodeMirror(document.body);
var myCodeMirror2: CodeMirror.Editor = CodeMirror(document.body, {
value: "function myScript(){return 100;}\n",
mode: "javascript"
});
var myTextArea: HTMLTextAreaElement;
var myCodeMirror3: CodeMirror.Editor = CodeMirror(function (elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
}, { value: myTextArea.value });
var myCodeMirror4: CodeMirror.Editor = CodeMirror.fromTextArea(myTextArea);
var doc: CodeMirror.Doc = new CodeMirror.Doc('text');
var doc2: CodeMirror.Doc = CodeMirror(document.body).getDoc();
var lintStateOptions: CodeMirror.LintStateOptions = {
async: true,
hasGutters: true
};
var lintOptions: CodeMirror.LintOptions = {
async: true,
hasGutters: true,
getAnnotations: (content: string,
updateLintingCallback: CodeMirror.UpdateLintingCallback,
options: CodeMirror.LintStateOptions,
codeMirror: CodeMirror.Editor) => {}
};
var updateLintingCallback: CodeMirror.UpdateLintingCallback = (codeMirror: CodeMirror.Editor,
annotations: CodeMirror.Annotation[]) => {};
var annotation: CodeMirror.Annotation = {
from: {
ch: 0,
line: 0
},
to: {
ch: 1,
line: 0
},
message: "test",
severity: "warning"
};
/// <reference path="codemirror.d.ts" />
var myCodeMirror: CodeMirror.Editor = CodeMirror(document.body);
var myCodeMirror2: CodeMirror.Editor = CodeMirror(document.body, {
value: "function myScript(){return 100;}\n",
mode: "javascript"
});
var myTextArea: HTMLTextAreaElement;
var myCodeMirror3: CodeMirror.Editor = CodeMirror(function (elt) {
myTextArea.parentNode.replaceChild(elt, myTextArea);
}, { value: myTextArea.value });
var myCodeMirror4: CodeMirror.Editor = CodeMirror.fromTextArea(myTextArea);
var doc: CodeMirror.Doc = new CodeMirror.Doc('text');
var doc2: CodeMirror.Doc = CodeMirror(document.body).getDoc();
var lintStateOptions: CodeMirror.LintStateOptions = {
async: true,
hasGutters: true
};
var lintOptions: CodeMirror.LintOptions = {
async: true,
hasGutters: true,
getAnnotations: (content: string,
updateLintingCallback: CodeMirror.UpdateLintingCallback,
options: CodeMirror.LintStateOptions,
codeMirror: CodeMirror.Editor) => {}
};
var updateLintingCallback: CodeMirror.UpdateLintingCallback = (codeMirror: CodeMirror.Editor,
annotations: CodeMirror.Annotation[]) => {};
var annotation: CodeMirror.Annotation = {
from: {
ch: 0,
line: 0
},
to: {
ch: 1,
line: 0
},
message: "test",
severity: "warning"
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,47 +1,47 @@
/// <reference path="content-type.d.ts" />
import MediaType = require('content-type');
// https://github.com/deoxxa/content-type/blob/master/README.md
function new_test(): void {
var p = new MediaType('text/html;level=1;q=0.5');
p.q === 0.5;
p.params.level === "1";
var q = new MediaType('application/json', { profile: 'http://example.com/schema.json' });
q.type === "application/json";
q.params.profile === "http://example.com/schema.json";
q.q = 1;
q.toString() === 'application/json;q=1;profile="http://example.com/schema.json"';
}
function mediaCmp_test(): void {
MediaType.mediaCmp(MediaType.parseMedia('text/html'), MediaType.parseMedia('text/html')) === 0;
MediaType.mediaCmp(MediaType.parseMedia('*/*'), MediaType.parseMedia('text/html')) === 1;
MediaType.mediaCmp(MediaType.parseMedia('text/html;level=1'), MediaType.parseMedia('text/html')) === -1;
MediaType.mediaCmp(MediaType.parseMedia('application/json;profile="v1.json"'), MediaType.parseMedia('application/json;profile="v2.json"')) === null;
}
// https://github.com/deoxxa/content-type/blob/master/example.js
function example(): void {
var representations = [
'application/json',
'text/html',
'application/json;profile="schema.json"',
'application/json;profile="different.json"',
];
var accept = [
'text/html;q=0.50',
'*/*;q=0.01',
'application/json;profile=different.json',
'application/json;profile="a,b;c.json?d=1;f=2";q=0.2',
];
console.log('Formats:\n\t' + representations.map(MediaType.parseMedia).join('\n\t'));
console.log('Accept:\n\t' + accept.map(MediaType.parseMedia).join('\n\t'));
console.log('Selected:', (MediaType.select(representations.map(MediaType.parseMedia), accept.map(MediaType.parseMedia)) || 'None').toString());
/// <reference path="content-type.d.ts" />
import MediaType = require('content-type');
// https://github.com/deoxxa/content-type/blob/master/README.md
function new_test(): void {
var p = new MediaType('text/html;level=1;q=0.5');
p.q === 0.5;
p.params.level === "1";
var q = new MediaType('application/json', { profile: 'http://example.com/schema.json' });
q.type === "application/json";
q.params.profile === "http://example.com/schema.json";
q.q = 1;
q.toString() === 'application/json;q=1;profile="http://example.com/schema.json"';
}
function mediaCmp_test(): void {
MediaType.mediaCmp(MediaType.parseMedia('text/html'), MediaType.parseMedia('text/html')) === 0;
MediaType.mediaCmp(MediaType.parseMedia('*/*'), MediaType.parseMedia('text/html')) === 1;
MediaType.mediaCmp(MediaType.parseMedia('text/html;level=1'), MediaType.parseMedia('text/html')) === -1;
MediaType.mediaCmp(MediaType.parseMedia('application/json;profile="v1.json"'), MediaType.parseMedia('application/json;profile="v2.json"')) === null;
}
// https://github.com/deoxxa/content-type/blob/master/example.js
function example(): void {
var representations = [
'application/json',
'text/html',
'application/json;profile="schema.json"',
'application/json;profile="different.json"',
];
var accept = [
'text/html;q=0.50',
'*/*;q=0.01',
'application/json;profile=different.json',
'application/json;profile="a,b;c.json?d=1;f=2";q=0.2',
];
console.log('Formats:\n\t' + representations.map(MediaType.parseMedia).join('\n\t'));
console.log('Accept:\n\t' + accept.map(MediaType.parseMedia).join('\n\t'));
console.log('Selected:', (MediaType.select(representations.map(MediaType.parseMedia), accept.map(MediaType.parseMedia)) || 'None').toString());
}

View File

@@ -1,32 +1,32 @@
// Type definitions for content-type v0.0.1
// Project: https://github.com/deoxxa/content-type
// Definitions by: Pine Mizune <https://github.com/pine613>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module ContentType {
interface MediaType {
type: string;
q?: number;
params: any;
toString(): string;
}
interface SelectOptions {
sortAvailable?: boolean;
sortAccepted?: boolean;
}
interface MediaTypeStatic {
new (s: string, p?: any): MediaType;
parseMedia(type: string): MediaType;
splitQuotedString(str: string, delimiter?: string, quote?: string): string[];
splitContentTypes(str: string): string[];
select(availableTypes: MediaType[], acceptedTypes: MediaType[], options?: SelectOptions): string;
mediaCmp(a: MediaType, b: MediaType): number;
}
}
declare module "content-type" {
var x: ContentType.MediaTypeStatic;
export = x;
// Type definitions for content-type v0.0.1
// Project: https://github.com/deoxxa/content-type
// Definitions by: Pine Mizune <https://github.com/pine613>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module ContentType {
interface MediaType {
type: string;
q?: number;
params: any;
toString(): string;
}
interface SelectOptions {
sortAvailable?: boolean;
sortAccepted?: boolean;
}
interface MediaTypeStatic {
new (s: string, p?: any): MediaType;
parseMedia(type: string): MediaType;
splitQuotedString(str: string, delimiter?: string, quote?: string): string[];
splitContentTypes(str: string): string[];
select(availableTypes: MediaType[], acceptedTypes: MediaType[], options?: SelectOptions): string;
mediaCmp(a: MediaType, b: MediaType): number;
}
}
declare module "content-type" {
var x: ContentType.MediaTypeStatic;
export = x;
}

View File

@@ -1,15 +1,15 @@
/// <reference path="./convert-source-map.d.ts" />
import convert = require("convert-source-map");
var json = convert
.fromComment('//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlcyI6WyJjb25zb2xlLmxvZyhcImhpXCIpOyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.toJSON();
var modified = convert
.fromComment('//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlcyI6WyJjb25zb2xlLmxvZyhcImhpXCIpOyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.setProperty('sources', ['CONSOLE.LOG("HI");'])
.toJSON();
console.log(json);
console.log(modified);
/// <reference path="./convert-source-map.d.ts" />
import convert = require("convert-source-map");
var json = convert
.fromComment('//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlcyI6WyJjb25zb2xlLmxvZyhcImhpXCIpOyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.toJSON();
var modified = convert
.fromComment('//@ sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9vLmpzIiwic291cmNlcyI6WyJjb25zb2xlLmxvZyhcImhpXCIpOyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSIsInNvdXJjZVJvb3QiOiIvIn0=')
.setProperty('sources', ['CONSOLE.LOG("HI");'])
.toJSON();
console.log(json);
console.log(modified);

View File

@@ -1,27 +1,27 @@
// Type definitions for convert-source-map
// Project: https://github.com/thlorenz/convert-source-map
// Definitions by: Andrew Gaspar <https://github.com/AndrewGaspar/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "convert-source-map" {
export interface SourceMapConverter {
toObject(): any;
toJSON(space?: any): string;
toBase64(): string;
toComment(): string;
addProperty(key: string, value: any): SourceMapConverter;
setProperty(key: string, value: any): SourceMapConverter;
getProperty(key: string): any;
}
export function removeComments(src: string): string;
export var commentRegex: RegExp;
export function fromObject(obj: any): SourceMapConverter;
export function fromJSON(json: string): SourceMapConverter;
export function fromBase64(base64: string): SourceMapConverter;
export function fromComment(comment: string): SourceMapConverter;
export function fromSource(source: string): SourceMapConverter;
}
// Type definitions for convert-source-map
// Project: https://github.com/thlorenz/convert-source-map
// Definitions by: Andrew Gaspar <https://github.com/AndrewGaspar/>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare module "convert-source-map" {
export interface SourceMapConverter {
toObject(): any;
toJSON(space?: any): string;
toBase64(): string;
toComment(): string;
addProperty(key: string, value: any): SourceMapConverter;
setProperty(key: string, value: any): SourceMapConverter;
getProperty(key: string): any;
}
export function removeComments(src: string): string;
export var commentRegex: RegExp;
export function fromObject(obj: any): SourceMapConverter;
export function fromJSON(json: string): SourceMapConverter;
export function fromBase64(base64: string): SourceMapConverter;
export function fromComment(comment: string): SourceMapConverter;
export function fromSource(source: string): SourceMapConverter;
}

View File

@@ -1,33 +1,33 @@
/// <reference path="cookie.d.ts" />
import cookie = require('cookie');
function test_serialize(): void {
var retVal: string;
retVal = cookie.serialize('foo', 'bar');
retVal = cookie.serialize('foo', 'bar', { httpOnly: true });
}
function test_parse(): void {
var retVal: { [key: string]: string };
retVal = cookie.parse('foo=bar; bar=baz;');
retVal = cookie.parse('foo=bar; bar=baz', { decode: x => x });
}
function test_options(): void {
var serializeOptions: CookieSerializeOptions = {
encode: (x: string) => x,
path: '/',
expires: new Date(),
maxAge: 200,
domain: 'example.com',
secure: false,
httpOnly: false
};
var parseOptios: CookieParseOptions = {
decode: (x: string) => x
};
}
/// <reference path="cookie.d.ts" />
import cookie = require('cookie');
function test_serialize(): void {
var retVal: string;
retVal = cookie.serialize('foo', 'bar');
retVal = cookie.serialize('foo', 'bar', { httpOnly: true });
}
function test_parse(): void {
var retVal: { [key: string]: string };
retVal = cookie.parse('foo=bar; bar=baz;');
retVal = cookie.parse('foo=bar; bar=baz', { decode: x => x });
}
function test_options(): void {
var serializeOptions: CookieSerializeOptions = {
encode: (x: string) => x,
path: '/',
expires: new Date(),
maxAge: 200,
domain: 'example.com',
secure: false,
httpOnly: false
};
var parseOptios: CookieParseOptions = {
decode: (x: string) => x
};
}

56
cookie/cookie.d.ts vendored
View File

@@ -1,28 +1,28 @@
// Type definitions for cookie v0.1.2
// Project: https://github.com/jshttp/cookie
// Definitions by: Pine Mizune <https://github.com/pine613>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface CookieSerializeOptions {
encode?: (val: string) => string;
path?: string;
expires?: Date;
maxAge?: number;
domain?: string;
secure?: boolean;
httpOnly?: boolean;
}
interface CookieParseOptions {
decode?: (val: string) => string;
}
interface CookieStatic {
serialize(name: string, val: string, options?: CookieSerializeOptions): string;
parse(str: string, options?: CookieParseOptions): { [key: string]: string };
}
declare module "cookie" {
var cookie: CookieStatic;
export = cookie;
}
// Type definitions for cookie v0.1.2
// Project: https://github.com/jshttp/cookie
// Definitions by: Pine Mizune <https://github.com/pine613>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface CookieSerializeOptions {
encode?: (val: string) => string;
path?: string;
expires?: Date;
maxAge?: number;
domain?: string;
secure?: boolean;
httpOnly?: boolean;
}
interface CookieParseOptions {
decode?: (val: string) => string;
}
interface CookieStatic {
serialize(name: string, val: string, options?: CookieSerializeOptions): string;
parse(str: string, options?: CookieParseOptions): { [key: string]: string };
}
declare module "cookie" {
var cookie: CookieStatic;
export = cookie;
}

View File

@@ -1,33 +1,33 @@
// Type definitions for Apache Cordova Email Composer plugin
// Project: https://github.com/katzer/cordova-plugin-email-composer
// Definitions by: Dave Taylor <http://davetayls.me>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* The plugin provides access to the standard interface that manages the
* editing and sending an email message
*/
interface CordovaPluginEmailComposer {
/** Determine if the device is capable to send emails */
isAvailable(callback:(isAvailable:boolean) => void, scope?:any):void;
/** Open a pre-filled email draft */
open(options?:ICordovaPluginEmailComposerOpenOptions, callback?:() => void, scope?:any):void;
openDraft(options?:ICordovaPluginEmailComposerOpenOptions, callback?:() => void, scope?:any):void;
}
interface ICordovaPluginEmailComposerOpenOptions {
/** An configured email account is required to send emails */
to?:string[];
body?:string;
cc?:string[];
bcc?:string[];
/** Attachments can be either base64 encoded datas, files from the the device storage or assets from within the www folder */
attachments?:any[];
subject?:string;
/** The default value for isHTML is true */
isHtml?:boolean;
}
interface CordovaPlugins {
email:CordovaPluginEmailComposer;
}
// Type definitions for Apache Cordova Email Composer plugin
// Project: https://github.com/katzer/cordova-plugin-email-composer
// Definitions by: Dave Taylor <http://davetayls.me>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/**
* The plugin provides access to the standard interface that manages the
* editing and sending an email message
*/
interface CordovaPluginEmailComposer {
/** Determine if the device is capable to send emails */
isAvailable(callback:(isAvailable:boolean) => void, scope?:any):void;
/** Open a pre-filled email draft */
open(options?:ICordovaPluginEmailComposerOpenOptions, callback?:() => void, scope?:any):void;
openDraft(options?:ICordovaPluginEmailComposerOpenOptions, callback?:() => void, scope?:any):void;
}
interface ICordovaPluginEmailComposerOpenOptions {
/** An configured email account is required to send emails */
to?:string[];
body?:string;
cc?:string[];
bcc?:string[];
/** Attachments can be either base64 encoded datas, files from the the device storage or assets from within the www folder */
attachments?:any[];
subject?:string;
/** The default value for isHTML is true */
isHtml?:boolean;
}
interface CordovaPlugins {
email:CordovaPluginEmailComposer;
}

File diff suppressed because it is too large Load Diff

6064
core-js/core-js.d.ts vendored

File diff suppressed because it is too large Load Diff

View File

@@ -1,22 +1,22 @@
/// <reference path="csv-stringify.d.ts" />
import stringify = require("csv-stringify");
stringify([["1", "2", "3"], ["4", "5", "6"]], (error: Error, output: string): void => {
// nothing
});
stringify([["1", "2", "3"], ["4", "5", "6"]], {
delimiter: ","
}, (error: Error, output: string): void => {
// nothing
});
var s = stringify({ delimiter: "," });
s.write(["1", "2", "3"]);
/// <reference path="csv-stringify.d.ts" />
import stringify = require("csv-stringify");
stringify([["1", "2", "3"], ["4", "5", "6"]], (error: Error, output: string): void => {
// nothing
});
stringify([["1", "2", "3"], ["4", "5", "6"]], {
delimiter: ","
}, (error: Error, output: string): void => {
// nothing
});
var s = stringify({ delimiter: "," });
s.write(["1", "2", "3"]);

View File

@@ -1,83 +1,83 @@
// Type definitions for csv-stringify 0.0.6
// Project: https://github.com/wdavidw/node-csv-stringify
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "csv-stringify" {
module stringify {
interface StringifyOpts {
/**
* List of fields, applied when transform returns an object, order matters, read the transformer documentation for additionnal information, columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line.
*/
columns?: string[];
/**
* Set the field delimiter, one character only, defaults to a comma.
*/
delimiter?: string;
/**
* Add the value of "options.rowDelimiter" on the last line, default to true.
*/
eof?: boolean;
/**
* Defaults to the escape read option.
*/
escape?: boolean;
/**
* Display the column names on the first line if the columns option is provided or discovered.
*/
header?: boolean;
/**
* String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified).
*/
lineBreaks?: string;
/**
* Defaults to the quote read option.
*/
quote?: string;
/**
* Boolean, default to false, quote all the non-empty fields even if not required.
*/
quoted?: boolean;
/**
* Boolean, no default, quote empty fields? If specified, overrides quotedString for empty strings.
*/
quotedEmpty?: boolean;
/**
* Boolean, default to false, quote all fields of type string even if not required.
*/
quotedString?: boolean;
/**
* String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified).
*/
rowDelimiter?: string;
}
interface Stringifier extends NodeJS.ReadWriteStream {
// Stringifier stream takes array of strings
write(line: string[]): boolean;
// repeat declarations from NodeJS.WritableStream to avoid compile error
write(buffer: Buffer, cb?: Function): boolean;
write(str: string, cb?: Function): boolean;
write(str: string, encoding?: string, cb?: Function): boolean;
}
}
/**
* Callback version: string in --> callback with string out
*/
function stringify(input: any[][], opts: stringify.StringifyOpts, callback: (error: Error, output: string) => void): void;
function stringify(input: any[][], callback: (error: Error, output: string) => void): void;
/**
* Streaming stringifier
*/
function stringify(opts: stringify.StringifyOpts): stringify.Stringifier;
export = stringify;
}
// Type definitions for csv-stringify 0.0.6
// Project: https://github.com/wdavidw/node-csv-stringify
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
/// <reference path="../node/node.d.ts" />
declare module "csv-stringify" {
module stringify {
interface StringifyOpts {
/**
* List of fields, applied when transform returns an object, order matters, read the transformer documentation for additionnal information, columns are auto discovered when the user write object, see the "header" option on how to print columns names on the first line.
*/
columns?: string[];
/**
* Set the field delimiter, one character only, defaults to a comma.
*/
delimiter?: string;
/**
* Add the value of "options.rowDelimiter" on the last line, default to true.
*/
eof?: boolean;
/**
* Defaults to the escape read option.
*/
escape?: boolean;
/**
* Display the column names on the first line if the columns option is provided or discovered.
*/
header?: boolean;
/**
* String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified).
*/
lineBreaks?: string;
/**
* Defaults to the quote read option.
*/
quote?: string;
/**
* Boolean, default to false, quote all the non-empty fields even if not required.
*/
quoted?: boolean;
/**
* Boolean, no default, quote empty fields? If specified, overrides quotedString for empty strings.
*/
quotedEmpty?: boolean;
/**
* Boolean, default to false, quote all fields of type string even if not required.
*/
quotedString?: boolean;
/**
* String used to delimit record rows or a special value; special values are 'auto', 'unix', 'mac', 'windows', 'unicode'; defaults to 'auto' (discovered in source or 'unix' if no source is specified).
*/
rowDelimiter?: string;
}
interface Stringifier extends NodeJS.ReadWriteStream {
// Stringifier stream takes array of strings
write(line: string[]): boolean;
// repeat declarations from NodeJS.WritableStream to avoid compile error
write(buffer: Buffer, cb?: Function): boolean;
write(str: string, cb?: Function): boolean;
write(str: string, encoding?: string, cb?: Function): boolean;
}
}
/**
* Callback version: string in --> callback with string out
*/
function stringify(input: any[][], opts: stringify.StringifyOpts, callback: (error: Error, output: string) => void): void;
function stringify(input: any[][], callback: (error: Error, output: string) => void): void;
/**
* Streaming stringifier
*/
function stringify(opts: stringify.StringifyOpts): stringify.Stringifier;
export = stringify;
}

View File

@@ -1,40 +1,40 @@
/// <reference path="cucumber.d.ts" />
function StepSample() {
type Callback = cucumber.CallbackStepDefinition;
var step = <cucumber.StepDefinitions>this;
var hook = <cucumber.Hooks>this;
hook.Before(function(scenario, callback){
scenario.isFailed() && callback.pending();
})
hook.Around(function(scenario, runScenario) {
scenario.isFailed() && runScenario(null, function(){
console.log('finish tasks');
});
});
hook.registerHandler('AfterFeatures', function (event, callback) {
callback();
});
step.Given(/^I am on the Cucumber.js GitHub repository$/, function(callback:Callback) {
this.visit('https://github.com/cucumber/cucumber-js', callback);
});
step.When(/^I go to the README file$/, function(title:string, callback:Callback) {
callback.pending();
});
step.Then(/^I should see "(.*)" as the page title$/, { timeout:60*1000}, function(title:string, callback:Callback) {
var pageTitle = this.browser.text('title');
if (title === pageTitle) {
callback();
} else {
callback(new Error("Expected to be on page with title " + title));
}
});
}
/// <reference path="cucumber.d.ts" />
function StepSample() {
type Callback = cucumber.CallbackStepDefinition;
var step = <cucumber.StepDefinitions>this;
var hook = <cucumber.Hooks>this;
hook.Before(function(scenario, callback){
scenario.isFailed() && callback.pending();
})
hook.Around(function(scenario, runScenario) {
scenario.isFailed() && runScenario(null, function(){
console.log('finish tasks');
});
});
hook.registerHandler('AfterFeatures', function (event, callback) {
callback();
});
step.Given(/^I am on the Cucumber.js GitHub repository$/, function(callback:Callback) {
this.visit('https://github.com/cucumber/cucumber-js', callback);
});
step.When(/^I go to the README file$/, function(title:string, callback:Callback) {
callback.pending();
});
step.Then(/^I should see "(.*)" as the page title$/, { timeout:60*1000}, function(title:string, callback:Callback) {
var pageTitle = this.browser.text('title');
if (title === pageTitle) {
callback();
} else {
callback(new Error("Expected to be on page with title " + title));
}
});
}

View File

@@ -1 +1 @@

View File

@@ -1,66 +1,66 @@
/// <reference path="domo.d.ts" />
function opacity(pct) {
return { opacity: String(pct / 100), filter: "alpha(opacity=" + pct + ")" }
}
HTML({ lang: "en" },
HEAD(
TITLE("Welcome to d?mo"),
STYLE({ type: "text/css" },
STYLE.on("body", { textAlign: "center", fontSize: 50 }),
STYLE.on("h1", opacity(50), { background: "#000", color: "#fff" })
)
),
BODY(H1("Welcome to d?mo"))
);
var withDomo = A({ href: "http://domo-js.com" }, "Learn about d?mo");
var withoutDomo = document.createElement("a");
withoutDomo.setAttribute("href", "http://domo-js.com");
withoutDomo.appendChild(document.createTextNode("Learn about d?mo"));
var styleSheet =
STYLE({ type: "text/css" },
STYLE.on("a", { color: "red" }),
STYLE.on("*", { margin: 0, padding: 0 })
);
var blue = "#3B5998";
var gray = "#3B3B3B";
var defaultRadius = 10;
function roundedCorners(radius) {
return {
borderRadius: radius,
WebkitBorderRadius: radius,
MozBorderRadius: radius
}
};
var styleSheet2 =
STYLE({ type: "text/css" },
STYLE.on("h2", { color: gray }, roundedCorners(defaultRadius)),
STYLE.on("h1", { color: blue }, roundedCorners(defaultRadius * 2))
);
var nestedStyles =
STYLE({ type: "text/css" },
STYLE.on("a", { color: "red" },
STYLE.on("img", { borderWidth: 0 })
)
);
var normalStyles =
STYLE({ type: "text/css" },
STYLE.on("a", { color: "red" }),
STYLE.on("a img", { borderWidth: 0 })
);
var domo = domo.global(false);
domo.HTML(
domo.HEAD(domo.TITLE("Hello, world.")),
domo.BODY("Hello, world.")
/// <reference path="domo.d.ts" />
function opacity(pct) {
return { opacity: String(pct / 100), filter: "alpha(opacity=" + pct + ")" }
}
HTML({ lang: "en" },
HEAD(
TITLE("Welcome to d?mo"),
STYLE({ type: "text/css" },
STYLE.on("body", { textAlign: "center", fontSize: 50 }),
STYLE.on("h1", opacity(50), { background: "#000", color: "#fff" })
)
),
BODY(H1("Welcome to d?mo"))
);
var withDomo = A({ href: "http://domo-js.com" }, "Learn about d?mo");
var withoutDomo = document.createElement("a");
withoutDomo.setAttribute("href", "http://domo-js.com");
withoutDomo.appendChild(document.createTextNode("Learn about d?mo"));
var styleSheet =
STYLE({ type: "text/css" },
STYLE.on("a", { color: "red" }),
STYLE.on("*", { margin: 0, padding: 0 })
);
var blue = "#3B5998";
var gray = "#3B3B3B";
var defaultRadius = 10;
function roundedCorners(radius) {
return {
borderRadius: radius,
WebkitBorderRadius: radius,
MozBorderRadius: radius
}
};
var styleSheet2 =
STYLE({ type: "text/css" },
STYLE.on("h2", { color: gray }, roundedCorners(defaultRadius)),
STYLE.on("h1", { color: blue }, roundedCorners(defaultRadius * 2))
);
var nestedStyles =
STYLE({ type: "text/css" },
STYLE.on("a", { color: "red" },
STYLE.on("img", { borderWidth: 0 })
)
);
var normalStyles =
STYLE({ type: "text/css" },
STYLE.on("a", { color: "red" }),
STYLE.on("a img", { borderWidth: 0 })
);
var domo = domo.global(false);
domo.HTML(
domo.HEAD(domo.TITLE("Hello, world.")),
domo.BODY("Hello, world.")
);

View File

@@ -1 +1 @@

242
domo/domo.d.ts vendored
View File

@@ -1,121 +1,121 @@
// Type definitions for Domo 0.5
// Project: http://domo-js.com/
// Definitions by: Steve Fenton <https://github.com/Steve-Fenton>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Domo {
(attributes?: Object): string;
(attributes?: Object, ...content: string[]): string;
on(element: string, ...styles: Object[]): string;
}
declare var A: Domo;
declare var ABBR: Domo;
declare var ACRONYM: Domo;
declare var ADDRESS: Domo;
declare var AREA: Domo;
declare var ARTICLE: Domo;
declare var ASIDE: Domo;
declare var AUDIO: Domo;
declare var B: Domo;
declare var BDI: Domo;
declare var BDO: Domo;
declare var BIG: Domo;
declare var BLOCKQUOTE: Domo;
declare var BODY: Domo;
declare var BR: Domo;
declare var BUTTON: Domo;
declare var CANVAS: Domo;
declare var CAPTION: Domo;
declare var CITE: Domo;
declare var CODE: Domo;
declare var COL: Domo;
declare var COLGROUP: Domo;
declare var COMMAND: Domo;
declare var DATALIST: Domo;
declare var DD: Domo;
declare var DEL: Domo;
declare var DETAILS: Domo;
declare var DFN: Domo;
declare var DIV: Domo;
declare var DL: Domo;
declare var DT: Domo;
declare var EM: Domo;
declare var EMBED: Domo;
declare var FIELDSET: Domo;
declare var FIGCAPTION: Domo;
declare var FIGURE: Domo;
declare var FOOTER: Domo;
declare var FORM: Domo;
declare var FRAME: Domo;
declare var FRAMESET: Domo;
declare var H1: Domo;
declare var H2: Domo;
declare var H3: Domo;
declare var H4: Domo;
declare var H5: Domo;
declare var H6: Domo;
declare var HEAD: Domo;
declare var HEADER: Domo;
declare var HGROUP: Domo;
declare var HR: Domo;
declare var HTML: Domo;
declare var I: Domo;
declare var IFRAME: Domo;
declare var IMG: Domo;
declare var INPUT: Domo;
declare var INS: Domo;
declare var KBD: Domo;
declare var KEYGEN: Domo;
declare var LABEL: Domo;
declare var LEGEND: Domo;
declare var LI: Domo;
declare var LINK: Domo;
declare var MAP: Domo;
declare var MARK: Domo;
declare var META: Domo;
declare var METER: Domo;
declare var NAV: Domo;
declare var NOSCRIPT: Domo;
declare var OBJECT: Domo;
declare var OL: Domo;
declare var OPTGROUP: Domo;
declare var OPTION: Domo;
declare var OUTPUT: Domo;
declare var P: Domo;
declare var PARAM: Domo;
declare var PRE: Domo;
declare var PROGRESS: Domo;
declare var Q: Domo;
declare var RP: Domo;
declare var RT: Domo;
declare var RUBY: Domo;
declare var SAMP: Domo;
declare var SCRIPT: Domo;
declare var SECTION: Domo;
declare var SELECT: Domo;
declare var SMALL: Domo;
declare var SOURCE: Domo;
declare var SPAN: Domo;
declare var SPLIT: Domo;
declare var STRONG: Domo;
declare var STYLE: Domo;
declare var SUB: Domo;
declare var SUMMARY: Domo;
declare var SUP: Domo;
declare var TABLE: Domo;
declare var TBODY: Domo;
declare var TD: Domo;
declare var TEXTAREA: Domo;
declare var TFOOT: Domo;
declare var TH: Domo;
declare var THEAD: Domo;
declare var TIME: Domo;
declare var TITLE: Domo;
declare var TR: Domo;
declare var TRACK: Domo;
declare var TT: Domo;
declare var UL: Domo;
declare var VAR: Domo;
declare var VIDEO: Domo;
declare var WBR: Domo;
// Type definitions for Domo 0.5
// Project: http://domo-js.com/
// Definitions by: Steve Fenton <https://github.com/Steve-Fenton>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
interface Domo {
(attributes?: Object): string;
(attributes?: Object, ...content: string[]): string;
on(element: string, ...styles: Object[]): string;
}
declare var A: Domo;
declare var ABBR: Domo;
declare var ACRONYM: Domo;
declare var ADDRESS: Domo;
declare var AREA: Domo;
declare var ARTICLE: Domo;
declare var ASIDE: Domo;
declare var AUDIO: Domo;
declare var B: Domo;
declare var BDI: Domo;
declare var BDO: Domo;
declare var BIG: Domo;
declare var BLOCKQUOTE: Domo;
declare var BODY: Domo;
declare var BR: Domo;
declare var BUTTON: Domo;
declare var CANVAS: Domo;
declare var CAPTION: Domo;
declare var CITE: Domo;
declare var CODE: Domo;
declare var COL: Domo;
declare var COLGROUP: Domo;
declare var COMMAND: Domo;
declare var DATALIST: Domo;
declare var DD: Domo;
declare var DEL: Domo;
declare var DETAILS: Domo;
declare var DFN: Domo;
declare var DIV: Domo;
declare var DL: Domo;
declare var DT: Domo;
declare var EM: Domo;
declare var EMBED: Domo;
declare var FIELDSET: Domo;
declare var FIGCAPTION: Domo;
declare var FIGURE: Domo;
declare var FOOTER: Domo;
declare var FORM: Domo;
declare var FRAME: Domo;
declare var FRAMESET: Domo;
declare var H1: Domo;
declare var H2: Domo;
declare var H3: Domo;
declare var H4: Domo;
declare var H5: Domo;
declare var H6: Domo;
declare var HEAD: Domo;
declare var HEADER: Domo;
declare var HGROUP: Domo;
declare var HR: Domo;
declare var HTML: Domo;
declare var I: Domo;
declare var IFRAME: Domo;
declare var IMG: Domo;
declare var INPUT: Domo;
declare var INS: Domo;
declare var KBD: Domo;
declare var KEYGEN: Domo;
declare var LABEL: Domo;
declare var LEGEND: Domo;
declare var LI: Domo;
declare var LINK: Domo;
declare var MAP: Domo;
declare var MARK: Domo;
declare var META: Domo;
declare var METER: Domo;
declare var NAV: Domo;
declare var NOSCRIPT: Domo;
declare var OBJECT: Domo;
declare var OL: Domo;
declare var OPTGROUP: Domo;
declare var OPTION: Domo;
declare var OUTPUT: Domo;
declare var P: Domo;
declare var PARAM: Domo;
declare var PRE: Domo;
declare var PROGRESS: Domo;
declare var Q: Domo;
declare var RP: Domo;
declare var RT: Domo;
declare var RUBY: Domo;
declare var SAMP: Domo;
declare var SCRIPT: Domo;
declare var SECTION: Domo;
declare var SELECT: Domo;
declare var SMALL: Domo;
declare var SOURCE: Domo;
declare var SPAN: Domo;
declare var SPLIT: Domo;
declare var STRONG: Domo;
declare var STYLE: Domo;
declare var SUB: Domo;
declare var SUMMARY: Domo;
declare var SUP: Domo;
declare var TABLE: Domo;
declare var TBODY: Domo;
declare var TD: Domo;
declare var TEXTAREA: Domo;
declare var TFOOT: Domo;
declare var TH: Domo;
declare var THEAD: Domo;
declare var TIME: Domo;
declare var TITLE: Domo;
declare var TR: Domo;
declare var TRACK: Domo;
declare var TT: Domo;
declare var UL: Domo;
declare var VAR: Domo;
declare var VIDEO: Domo;
declare var WBR: Domo;

View File

@@ -1,5 +1,5 @@
/// <reference path="domready.d.ts" />
domready(function () {
// dom is loaded!
/// <reference path="domready.d.ts" />
domready(function () {
// dom is loaded!
})

View File

@@ -1,10 +1,10 @@
// Type definitions for domready
// Project: https://github.com/ded/domready
// Definitions by: Christian Holm Nielsen <https://github.com/dotnetnerd>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare function domready(callback: () => any) : void;
declare module "domready" {
export = domready;
}
// Type definitions for domready
// Project: https://github.com/ded/domready
// Definitions by: Christian Holm Nielsen <https://github.com/dotnetnerd>
// Definitions: https://github.com/borisyankov/DefinitelyTyped
declare function domready(callback: () => any) : void;
declare module "domready" {
export = domready;
}

View File

@@ -1 +1 @@

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